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.

342 lines
9.8 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 parsePhotoFromData($http, $photoData, $url, $profile=false) {
  62. if(!$photoData)
  63. return self::_unknown();
  64. // Start building the h-entry
  65. $entry = array(
  66. 'type' => 'entry',
  67. 'url' => $url,
  68. 'author' => [
  69. 'type' => 'card',
  70. 'name' => null,
  71. 'photo' => null,
  72. 'url' => null
  73. ]
  74. );
  75. $profiles = [];
  76. if(!$profile) {
  77. // Fetch profile info for this user
  78. $username = $photoData['owner']['username'];
  79. $profile = self::_getInstagramProfile($username, $http);
  80. if($profile) {
  81. $entry['author'] = self::_buildHCardFromInstagramProfile($profile);
  82. $profiles[] = $profile;
  83. }
  84. } else {
  85. $entry['author'] = self::_buildHCardFromInstagramProfile($profile);
  86. $profiles[] = $profile;
  87. }
  88. // Content and hashtags
  89. $caption = false;
  90. if(isset($photoData['caption'])) {
  91. $caption = $photoData['caption'];
  92. } elseif(isset($photoData['edge_media_to_caption']['edges'][0]['node']['text'])) {
  93. $caption = $photoData['edge_media_to_caption']['edges'][0]['node']['text'];
  94. }
  95. if($caption) {
  96. if(preg_match_all('/#([a-z0-9_-]+)/i', $caption, $matches)) {
  97. $entry['category'] = [];
  98. foreach($matches[1] as $match) {
  99. $entry['category'][] = $match;
  100. }
  101. }
  102. $entry['content'] = [
  103. 'text' => $caption
  104. ];
  105. }
  106. $refs = [];
  107. // Include the photo/video media URLs
  108. // (Always return arrays, even for single images)
  109. if(array_key_exists('edge_sidecar_to_children', $photoData)) {
  110. // Multi-post
  111. // For now, we will only pull photos from multi-posts, and skip videos.
  112. $entry['photo'] = [];
  113. foreach($photoData['edge_sidecar_to_children']['edges'] as $edge) {
  114. $entry['photo'][] = $edge['node']['display_url'];
  115. // Don't need to pull person-tags from here because the main parent object already has them.
  116. }
  117. } else {
  118. // Single photo or video
  119. if(array_key_exists('display_src', $photoData))
  120. $entry['photo'] = [$photoData['display_src']];
  121. elseif(array_key_exists('display_url', $photoData))
  122. $entry['photo'] = [$photoData['display_url']];
  123. if(isset($photoData['is_video']) && $photoData['is_video'] && isset($photoData['video_url'])) {
  124. $entry['video'] = [$photoData['video_url']];
  125. }
  126. }
  127. // Find person tags and fetch user profiles
  128. if(isset($photoData['edge_media_to_tagged_user']['edges'])) {
  129. if(!isset($entry['category'])) $entry['category'] = [];
  130. foreach($photoData['edge_media_to_tagged_user']['edges'] as $edge) {
  131. $profile = self::_getInstagramProfile($edge['node']['user']['username'], $http);
  132. if($profile) {
  133. $card = self::_buildHCardFromInstagramProfile($profile);
  134. $entry['category'][] = $card['url'];
  135. $refs[$card['url']] = $card;
  136. $profiles[] = $profile;
  137. }
  138. }
  139. }
  140. // Published date
  141. if(isset($photoData['taken_at_timestamp']))
  142. $published = DateTime::createFromFormat('U', $photoData['taken_at_timestamp']);
  143. elseif(isset($photoData['date']))
  144. $published = DateTime::createFromFormat('U', $photoData['date']);
  145. // Include venue data
  146. $locations = [];
  147. if(isset($photoData['location'])) {
  148. $location = self::_getInstagramLocation($photoData['location']['id'], $http);
  149. if($location) {
  150. $entry['location'] = [$location['url']];
  151. $refs[$location['url']] = $location;
  152. $locations[] = $location;
  153. // Look up timezone
  154. if($location['latitude']) {
  155. $tz = \p3k\Timezone::timezone_for_location($location['latitude'], $location['longitude']);
  156. if($tz) {
  157. $published->setTimeZone(new DateTimeZone($tz));
  158. }
  159. }
  160. }
  161. }
  162. $entry['published'] = $published->format('c');
  163. if(count($refs)) {
  164. $entry['refs'] = $refs;
  165. }
  166. $entry['post-type'] = \p3k\XRay\PostType::discover($entry);
  167. return [
  168. 'data' => $entry,
  169. 'original' => json_encode([
  170. 'photo' => $photoData,
  171. 'profiles' => $profiles,
  172. 'locations' => $locations
  173. ]),
  174. 'source-format' => 'instagram',
  175. ];
  176. }
  177. private static function _buildHCardFromInstagramProfile($profile) {
  178. if(!$profile) return false;
  179. $author = [
  180. 'type' => 'card'
  181. ];
  182. if($profile['full_name'])
  183. $author['name'] = $profile['full_name'];
  184. else
  185. $author['name'] = $profile['username'];
  186. if(isset($profile['external_url']) && $profile['external_url'])
  187. $author['url'] = $profile['external_url'];
  188. else
  189. $author['url'] = 'https://www.instagram.com/' . $profile['username'];
  190. if(isset($profile['profile_pic_url_hd']))
  191. $author['photo'] = $profile['profile_pic_url_hd'];
  192. else
  193. $author['photo'] = $profile['profile_pic_url'];
  194. if(isset($profile['biography']))
  195. $author['note'] = $profile['biography'];
  196. return $author;
  197. }
  198. private static function _getInstagramProfile($username, $http) {
  199. $response = $http->get('https://www.instagram.com/'.$username.'/');
  200. if(!$response['error'])
  201. return self::_parseProfileFromHTML($response['body']);
  202. return null;
  203. }
  204. private static function _parseProfileFromHTML($html) {
  205. $data = self::_extractIGData($html);
  206. if(isset($data['entry_data']['ProfilePage'][0])) {
  207. $profile = $data['entry_data']['ProfilePage'][0];
  208. if($profile && isset($profile['graphql']['user'])) {
  209. $user = $profile['graphql']['user'];
  210. return $user;
  211. }
  212. }
  213. return null;
  214. }
  215. private static function _getInstagramLocation($id, $http) {
  216. $igURL = 'https://www.instagram.com/explore/locations/'.$id.'/';
  217. $response = $http->get($igURL);
  218. if($response['body']) {
  219. $data = self::_extractVenueDataFromVenuePage($response['body']);
  220. if($data) {
  221. return [
  222. 'type' => 'card',
  223. 'name' => $data['name'],
  224. 'url' => $igURL,
  225. 'latitude' => $data['lat'],
  226. 'longitude' => $data['lng'],
  227. ];
  228. }
  229. }
  230. return null;
  231. }
  232. private static function _extractPhotoDataFromPhotoPage($html) {
  233. $data = self::_extractIGData($html);
  234. if($data && is_array($data) && array_key_exists('entry_data', $data)) {
  235. if(is_array($data['entry_data']) && array_key_exists('PostPage', $data['entry_data'])) {
  236. $post = $data['entry_data']['PostPage'];
  237. if(isset($post[0]['graphql']['shortcode_media'])) {
  238. return $post[0]['graphql']['shortcode_media'];
  239. } elseif(isset($post[0]['graphql']['media'])) {
  240. return $post[0]['graphql']['media'];
  241. } elseif(isset($post[0]['media'])) {
  242. return $post[0]['media'];
  243. }
  244. }
  245. }
  246. return null;
  247. }
  248. private static function _extractVenueDataFromVenuePage($html) {
  249. $data = self::_extractIGData($html);
  250. if($data && isset($data['entry_data']['LocationsPage'])) {
  251. $data = $data['entry_data']['LocationsPage'];
  252. if(isset($data[0]['graphql']['location'])) {
  253. $location = $data[0]['graphql']['location'];
  254. # we don't need these and they're huge, so drop them now
  255. unset($location['media']);
  256. unset($location['top_posts']);
  257. return $location;
  258. }
  259. }
  260. return null;
  261. }
  262. private static function _extractIGData($html) {
  263. $doc = new DOMDocument();
  264. @$doc->loadHTML($html);
  265. if(!$doc) {
  266. return null;
  267. }
  268. $xpath = new DOMXPath($doc);
  269. $data = null;
  270. foreach($xpath->query('//script') as $script) {
  271. if(preg_match('/window\._sharedData = ({.+});/', $script->textContent, $match)) {
  272. $data = json_decode($match[1], true);
  273. }
  274. }
  275. return $data;
  276. }
  277. }