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.

363 lines
11 KiB

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