You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

383 lines
11 KiB

  1. <?php
  2. namespace p3k\XRay\Formats;
  3. const BASE_URL = 'https://www.instagram.com/';
  4. const QUERY_MEDIA = BASE_URL.'graphql/query/?query_hash=42323d64886122307be10013ad2dcc44&variables=%s';
  5. const QUERY_MEDIA_VARS = '{"id":"%s","first":%d,"after":"%s"}';
  6. use DOMDocument, DOMXPath;
  7. use DateTime, DateTimeZone;
  8. class Instagram extends Format {
  9. private static $gis;
  10. private static $extra_photos = 20;
  11. public static function matches_host($url) {
  12. $host = parse_url($url, PHP_URL_HOST);
  13. return in_array($host, ['www.instagram.com','instagram.com']);
  14. }
  15. public static function matches($url) {
  16. return self::matches_host($url);
  17. }
  18. public static function parse($http, $html, $url, $opts=[]) {
  19. if(isset($opts['length'])) {
  20. self::$extra_photos = intval($opts['length'])-12;
  21. }
  22. if(preg_match('#instagram.com/([^/]+)/$#', $url)) {
  23. if(isset($opts['expect']) && $opts['expect'] == 'feed')
  24. return self::parseFeed($http, $html, $url);
  25. else
  26. return self::parseProfile($http, $html, $url);
  27. } else {
  28. return self::parsePhoto($http, $html, $url);
  29. }
  30. }
  31. private static function parseProfile($http, $html, $url) {
  32. $profileData = self::_parseProfileFromHTML($html);
  33. if(!$profileData)
  34. return self::_unknown();
  35. $card = self::_buildHCardFromInstagramProfile($profileData);
  36. return [
  37. 'data' => $card
  38. ];
  39. }
  40. private static function _getIntstagramGIS($params) {
  41. $data = self::$gis.":".$params;
  42. return md5($data);
  43. }
  44. private static function _getMorePhotos($http,$html,$url,$profileData) {
  45. $params = sprintf(
  46. QUERY_MEDIA_VARS,
  47. $profileData['id'],
  48. self::$extra_photos,
  49. $profileData['edge_owner_to_timeline_media']['page_info']['end_cursor']
  50. );
  51. $url = sprintf(QUERY_MEDIA,$params);
  52. $headers = [];
  53. $headers[] = 'x-instagram-gis: ' . self::_getIntstagramGIS($params);
  54. $headers[] = 'x-requested-with: XMLHttpRequest';
  55. $resp = $http->get($url,$headers);
  56. if(!$resp['error']) {
  57. $data = json_decode($resp['body'],true);
  58. $photos = $data['data']['user']['edge_owner_to_timeline_media']['edges'];
  59. return $photos;
  60. }
  61. return null;
  62. }
  63. private static function parseFeed($http, $html, $url) {
  64. $profileData = self::_parseProfileFromHTML($html);
  65. if(!$profileData)
  66. return self::_unknown();
  67. $photos = $profileData['edge_owner_to_timeline_media']['edges'];
  68. $items = [];
  69. $morePhotos = self::_getMorePhotos($http,$html,$url,$profileData);
  70. $photos = array_merge($photos,$morePhotos);
  71. foreach($photos as $photoData) {
  72. $item = self::parsePhotoFromData($http, $photoData['node'],
  73. BASE_URL.'p/'.$photoData['node']['shortcode'].'/', $profileData);
  74. // Note: Not all the photo info is available in the initial JSON.
  75. // Things like video mp4 URLs and person tags and locations are missing.
  76. // Consumers of the feed will need to fetch the photo permalink in order to get all missing information.
  77. // if($photoData['is_video'])
  78. // $item['data']['video'] = true;
  79. $items[] = $item['data'];
  80. }
  81. return [
  82. 'data' => [
  83. 'type' => 'feed',
  84. 'items' => $items,
  85. ]
  86. ];
  87. }
  88. private static function parsePhoto($http, $html, $url, $profile=false) {
  89. $photoData = self::_extractPhotoDataFromPhotoPage($html);
  90. return self::parsePhotoFromData($http, $photoData, $url, $profile);
  91. }
  92. private static function parsePhotoFromData($http, $photoData, $url, $profile=false) {
  93. if(!$photoData)
  94. return self::_unknown();
  95. // Start building the h-entry
  96. $entry = array(
  97. 'type' => 'entry',
  98. 'url' => $url,
  99. 'author' => [
  100. 'type' => 'card',
  101. 'name' => null,
  102. 'photo' => null,
  103. 'url' => null
  104. ]
  105. );
  106. $profiles = [];
  107. if(!$profile) {
  108. // Fetch profile info for this user
  109. $username = $photoData['owner']['username'];
  110. $profile = self::_getInstagramProfile($username, $http);
  111. if($profile) {
  112. $entry['author'] = self::_buildHCardFromInstagramProfile($profile);
  113. $profiles[] = $profile;
  114. }
  115. } else {
  116. $entry['author'] = self::_buildHCardFromInstagramProfile($profile);
  117. $profiles[] = $profile;
  118. }
  119. // Content and hashtags
  120. $caption = false;
  121. if(isset($photoData['caption'])) {
  122. $caption = $photoData['caption'];
  123. } elseif(isset($photoData['edge_media_to_caption']['edges'][0]['node']['text'])) {
  124. $caption = $photoData['edge_media_to_caption']['edges'][0]['node']['text'];
  125. }
  126. if($caption) {
  127. if(preg_match_all('/#([a-z0-9_-]+)/i', $caption, $matches)) {
  128. $entry['category'] = [];
  129. foreach($matches[1] as $match) {
  130. $entry['category'][] = $match;
  131. }
  132. }
  133. $entry['content'] = [
  134. 'text' => $caption
  135. ];
  136. }
  137. $refs = [];
  138. // Include the photo/video media URLs
  139. // (Always return arrays, even for single images)
  140. if(array_key_exists('edge_sidecar_to_children', $photoData)) {
  141. // Multi-post
  142. // For now, we will only pull photos from multi-posts, and skip videos.
  143. $entry['photo'] = [];
  144. foreach($photoData['edge_sidecar_to_children']['edges'] as $edge) {
  145. $entry['photo'][] = $edge['node']['display_url'];
  146. // Don't need to pull person-tags from here because the main parent object already has them.
  147. }
  148. } else {
  149. // Single photo or video
  150. if(array_key_exists('display_src', $photoData))
  151. $entry['photo'] = [$photoData['display_src']];
  152. elseif(array_key_exists('display_url', $photoData))
  153. $entry['photo'] = [$photoData['display_url']];
  154. if(isset($photoData['is_video']) && $photoData['is_video'] && isset($photoData['video_url'])) {
  155. $entry['video'] = [$photoData['video_url']];
  156. }
  157. }
  158. // Find person tags and fetch user profiles
  159. if(isset($photoData['edge_media_to_tagged_user']['edges'])) {
  160. if(!isset($entry['category'])) $entry['category'] = [];
  161. foreach($photoData['edge_media_to_tagged_user']['edges'] as $edge) {
  162. $profile = self::_getInstagramProfile($edge['node']['user']['username'], $http);
  163. if($profile) {
  164. $card = self::_buildHCardFromInstagramProfile($profile);
  165. $entry['category'][] = $card['url'];
  166. $refs[$card['url']] = $card;
  167. $profiles[] = $profile;
  168. }
  169. }
  170. }
  171. // Published date
  172. if(isset($photoData['taken_at_timestamp']))
  173. $published = DateTime::createFromFormat('U', $photoData['taken_at_timestamp']);
  174. elseif(isset($photoData['date']))
  175. $published = DateTime::createFromFormat('U', $photoData['date']);
  176. // Include venue data
  177. $locations = [];
  178. if(isset($photoData['location'])) {
  179. $location = self::_getInstagramLocation($photoData['location']['id'], $http);
  180. if($location) {
  181. $entry['location'] = [$location['url']];
  182. $refs[$location['url']] = $location;
  183. $locations[] = $location;
  184. // Look up timezone
  185. if($location['latitude']) {
  186. $tz = \p3k\Timezone::timezone_for_location($location['latitude'], $location['longitude']);
  187. if($tz) {
  188. $published->setTimeZone(new DateTimeZone($tz));
  189. }
  190. }
  191. }
  192. }
  193. $entry['published'] = $published->format('c');
  194. if(count($refs)) {
  195. $entry['refs'] = $refs;
  196. }
  197. return [
  198. 'data' => $entry,
  199. 'original' => json_encode([
  200. 'photo' => $photoData,
  201. 'profiles' => $profiles,
  202. 'locations' => $locations
  203. ])
  204. ];
  205. }
  206. private static function _buildHCardFromInstagramProfile($profile) {
  207. if(!$profile) return false;
  208. $author = [
  209. 'type' => 'card'
  210. ];
  211. if($profile['full_name'])
  212. $author['name'] = $profile['full_name'];
  213. else
  214. $author['name'] = $profile['username'];
  215. if(isset($profile['external_url']) && $profile['external_url'])
  216. $author['url'] = $profile['external_url'];
  217. else
  218. $author['url'] = BASE_URL . $profile['username'];
  219. if(isset($profile['profile_pic_url_hd']))
  220. $author['photo'] = $profile['profile_pic_url_hd'];
  221. else
  222. $author['photo'] = $profile['profile_pic_url'];
  223. if(isset($profile['biography']))
  224. $author['note'] = $profile['biography'];
  225. return $author;
  226. }
  227. private static function _getInstagramProfile($username, $http) {
  228. $response = $http->get(BASE_URL.$username.'/');
  229. if(!$response['error'])
  230. return self::_parseProfileFromHTML($response['body']);
  231. return null;
  232. }
  233. private static function _parseProfileFromHTML($html) {
  234. $data = self::_extractIGData($html);
  235. if(isset($data['rhx_gis'])) {
  236. self::$gis = $data['rhx_gis'];
  237. }
  238. if(isset($data['entry_data']['ProfilePage'][0])) {
  239. $profile = $data['entry_data']['ProfilePage'][0];
  240. if($profile && isset($profile['graphql']['user'])) {
  241. $user = $profile['graphql']['user'];
  242. return $user;
  243. }
  244. }
  245. return null;
  246. }
  247. private static function _getInstagramLocation($id, $http) {
  248. $igURL = BASE_URL.'explore/locations/'.$id.'/';
  249. $response = $http->get($igURL);
  250. if($response['body']) {
  251. $data = self::_extractVenueDataFromVenuePage($response['body']);
  252. if($data) {
  253. return [
  254. 'type' => 'card',
  255. 'name' => $data['name'],
  256. 'url' => $igURL,
  257. 'latitude' => $data['lat'],
  258. 'longitude' => $data['lng'],
  259. ];
  260. }
  261. }
  262. return null;
  263. }
  264. private static function _extractPhotoDataFromPhotoPage($html) {
  265. $data = self::_extractIGData($html);
  266. if($data && is_array($data) && array_key_exists('entry_data', $data)) {
  267. if(is_array($data['entry_data']) && array_key_exists('PostPage', $data['entry_data'])) {
  268. $post = $data['entry_data']['PostPage'];
  269. if(isset($post[0]['graphql']['shortcode_media'])) {
  270. return $post[0]['graphql']['shortcode_media'];
  271. } elseif(isset($post[0]['graphql']['media'])) {
  272. return $post[0]['graphql']['media'];
  273. } elseif(isset($post[0]['media'])) {
  274. return $post[0]['media'];
  275. }
  276. }
  277. }
  278. return null;
  279. }
  280. private static function _extractVenueDataFromVenuePage($html) {
  281. $data = self::_extractIGData($html);
  282. if($data && isset($data['entry_data']['LocationsPage'])) {
  283. $data = $data['entry_data']['LocationsPage'];
  284. if(isset($data[0]['graphql']['location'])) {
  285. $location = $data[0]['graphql']['location'];
  286. # we don't need these and they're huge, so drop them now
  287. unset($location['media']);
  288. unset($location['top_posts']);
  289. return $location;
  290. }
  291. }
  292. return null;
  293. }
  294. private static function _extractIGData($html) {
  295. $doc = new DOMDocument();
  296. @$doc->loadHTML($html);
  297. if(!$doc) {
  298. return null;
  299. }
  300. $xpath = new DOMXPath($doc);
  301. $data = null;
  302. foreach($xpath->query('//script') as $script) {
  303. if(preg_match('/window\._sharedData = ({.+});/', $script->textContent, $match)) {
  304. $data = json_decode($match[1], true);
  305. }
  306. }
  307. return $data;
  308. }
  309. }