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.

343 lines
10 KiB

6 years ago
6 years ago
6 years ago
6 years ago
  1. <?php
  2. namespace p3k\XRay\Formats;
  3. use DateTime, DateTimeZone;
  4. class Twitter extends Format {
  5. public static function matches_host($url) {
  6. $host = parse_url($url, PHP_URL_HOST);
  7. return in_array($host, ['mobile.twitter.com','twitter.com','www.twitter.com','twtr.io']);
  8. }
  9. public static function matches($url) {
  10. if(preg_match('/https?:\/\/(?:mobile\.twitter\.com|twitter\.com|twtr\.io)\/(?:[a-z0-9_\/!#]+statuse?s?\/([0-9]+)|([a-zA-Z0-9_]+))/i', $url, $match))
  11. return $match;
  12. else
  13. return false;
  14. }
  15. public static function fetch($url, $creds) {
  16. if(!($match = self::matches($url))) {
  17. return false;
  18. }
  19. $tweet_id = $match[1];
  20. $host = parse_url($url, PHP_URL_HOST);
  21. if($host == 'twtr.io') {
  22. $tweet_id = self::b60to10($tweet_id);
  23. }
  24. $twitter = new \Twitter($creds['twitter_api_key'], $creds['twitter_api_secret'], $creds['twitter_access_token'], $creds['twitter_access_token_secret']);
  25. try {
  26. $tweet = $twitter->request('statuses/show/'.$tweet_id, 'GET', ['tweet_mode'=>'extended']);
  27. } catch(\TwitterException $e) {
  28. return [
  29. 'error' => 'twitter_error',
  30. 'error_description' => $e->getMessage()
  31. ];
  32. }
  33. return [
  34. 'url' => $url,
  35. 'body' => $tweet,
  36. 'code' => 200,
  37. ];
  38. }
  39. public static function parse($http_response) {
  40. $json = is_array($http_response) ? $http_response['body'] : $http_response->body;
  41. $url = is_array($http_response) ? $http_response['url'] : $http_response->url;
  42. if(is_string($json))
  43. $tweet = json_decode($json);
  44. else
  45. $tweet = $json;
  46. if(!$tweet) {
  47. return self::_unknown();
  48. }
  49. $entry = array(
  50. 'type' => 'entry',
  51. 'url' => $url,
  52. 'author' => [
  53. 'type' => 'card',
  54. 'name' => null,
  55. 'nickname' => null,
  56. 'photo' => null,
  57. 'url' => null,
  58. ]
  59. );
  60. $refs = [];
  61. if(property_exists($tweet, 'retweeted_status')) {
  62. // No content for retweets
  63. $reposted = $tweet->retweeted_status;
  64. $repostOf = 'https://twitter.com/' . $reposted->user->screen_name . '/status/' . $reposted->id_str;
  65. $entry['repost-of'] = $repostOf;
  66. $repostedEntry = self::parse(['body' => $reposted, 'url' => $repostOf]);
  67. if(isset($repostedEntry['data']['refs'])) {
  68. foreach($repostedEntry['data']['refs'] as $k=>$v) {
  69. $refs[$k] = $v;
  70. }
  71. }
  72. $refs[$repostOf] = $repostedEntry['data'];
  73. } else {
  74. $entry['content'] = self::expandTweetContent($tweet);
  75. }
  76. // Published date
  77. $published = new DateTime($tweet->created_at);
  78. if(property_exists($tweet->user, 'utc_offset')) {
  79. $tz = new DateTimeZone(sprintf('%+d', $tweet->user->utc_offset / 3600));
  80. $published->setTimeZone($tz);
  81. }
  82. $entry['published'] = $published->format('c');
  83. // Hashtags
  84. if(property_exists($tweet, 'entities') && property_exists($tweet->entities, 'hashtags')) {
  85. if(count($tweet->entities->hashtags)) {
  86. $entry['category'] = [];
  87. foreach($tweet->entities->hashtags as $hashtag) {
  88. $entry['category'][] = $hashtag->text;
  89. }
  90. }
  91. }
  92. // In-Reply-To
  93. if(property_exists($tweet, 'in_reply_to_status_id_str') && $tweet->in_reply_to_status_id_str) {
  94. $entry['in-reply-to'] = [
  95. 'https://twitter.com/'.$tweet->in_reply_to_screen_name.'/status/'.$tweet->in_reply_to_status_id_str
  96. ];
  97. }
  98. // Don't include the RT'd photo or video in the main object.
  99. // They get included in the reposted object instead.
  100. if(!property_exists($tweet, 'retweeted_status')) {
  101. // Photos and Videos
  102. if(property_exists($tweet, 'extended_entities') && property_exists($tweet->extended_entities, 'media')) {
  103. foreach($tweet->extended_entities->media as $media) {
  104. self::extractMedia($media, $entry);
  105. }
  106. }
  107. // Photos from Streaming API Tweets
  108. if(property_exists($tweet, 'extended_tweet')) {
  109. if(property_exists($tweet->extended_tweet, 'entities') && property_exists($tweet->extended_tweet->entities, 'media')) {
  110. foreach($tweet->extended_tweet->entities->media as $media) {
  111. self::extractMedia($media, $entry);
  112. }
  113. }
  114. }
  115. // Place
  116. if(property_exists($tweet, 'place') && $tweet->place) {
  117. $place = $tweet->place;
  118. if($place->place_type == 'city') {
  119. $entry['location'] = $place->url;
  120. $refs[$place->url] = [
  121. 'type' => 'adr',
  122. 'name' => $place->full_name,
  123. 'locality' => $place->name,
  124. 'country-name' => $place->country,
  125. ];
  126. }
  127. }
  128. }
  129. // Quoted Status
  130. if(property_exists($tweet, 'quoted_status')) {
  131. $quoteOf = 'https://twitter.com/' . $tweet->quoted_status->user->screen_name . '/status/' . $tweet->quoted_status_id_str;
  132. $quotedEntry = self::parse(['body' => $tweet->quoted_status, 'url' => $quoteOf]);
  133. if(isset($quotedEntry['data']['refs'])) {
  134. foreach($quotedEntry['data']['refs'] as $k=>$v) {
  135. $refs[$k] = $v;
  136. }
  137. }
  138. $refs[$quoteOf] = $quotedEntry['data'];
  139. $entry['quotation-of'] = $quoteOf;
  140. }
  141. if($author = self::_buildHCardFromTwitterProfile($tweet->user)) {
  142. $entry['author'] = $author;
  143. }
  144. if(count($refs)) {
  145. $entry['refs'] = $refs;
  146. }
  147. $entry['post-type'] = \p3k\XRay\PostType::discover($entry);
  148. return [
  149. 'data' => $entry,
  150. 'original' => $tweet,
  151. 'source-format' => 'twitter',
  152. ];
  153. }
  154. private static function extractMedia($media, &$entry) {
  155. if($media->type == 'photo') {
  156. if(!array_key_exists('photo', $entry))
  157. $entry['photo'] = [];
  158. $entry['photo'][] = $media->media_url_https;
  159. } elseif($media->type == 'video' || $media->type == 'animated_gif') {
  160. if(!array_key_exists('photo', $entry))
  161. $entry['photo'] = [];
  162. if(!array_key_exists('video', $entry))
  163. $entry['video'] = [];
  164. // Include the thumbnail
  165. $entry['photo'][] = $media->media_url_https;
  166. // Find the highest bitrate video that is mp4
  167. $videos = $media->video_info->variants;
  168. $videos = array_filter($videos, function($v) {
  169. return property_exists($v, 'bitrate') && $v->content_type == 'video/mp4';
  170. });
  171. if(count($videos)) {
  172. usort($videos, function($a,$b) {
  173. return $a->bitrate < $b->bitrate;
  174. });
  175. $entry['video'][] = $videos[0]->url;
  176. }
  177. }
  178. }
  179. private static function _buildHCardFromTwitterProfile($profile) {
  180. if(!$profile) return false;
  181. $author = [
  182. 'type' => 'card'
  183. ];
  184. $author['nickname'] = $profile->screen_name;
  185. $author['location'] = $profile->location;
  186. $author['bio'] = self::expandTwitterObjectURLs($profile->description, $profile, 'description');
  187. if($profile->name)
  188. $author['name'] = $profile->name;
  189. else
  190. $author['name'] = $profile->screen_name;
  191. $author['url'] = 'https://twitter.com/' . $profile->screen_name;
  192. $author['photo'] = $profile->profile_image_url_https;
  193. return $author;
  194. }
  195. private static function expandTweetContent($tweet) {
  196. $entities = new \StdClass;
  197. if(property_exists($tweet, 'truncated') && $tweet->truncated) {
  198. if(property_exists($tweet, 'extended_tweet')) {
  199. $text = $tweet->extended_tweet->full_text;
  200. $text = mb_substr($text,
  201. $tweet->extended_tweet->display_text_range[0],
  202. $tweet->extended_tweet->display_text_range[1]-$tweet->extended_tweet->display_text_range[0],
  203. 'UTF-8');
  204. if(property_exists($tweet->extended_tweet, 'entities')) {
  205. $entities = $tweet->extended_tweet->entities;
  206. }
  207. } else {
  208. $text = $tweet->text;
  209. if(property_exists($tweet, 'entities')) {
  210. $entities = $tweet->entities;
  211. }
  212. }
  213. } else {
  214. // Only use the "display" segment of the text
  215. if(property_exists($tweet, 'full_text')) {
  216. // Only use the "display" segment of the text
  217. $text = mb_substr($tweet->full_text,
  218. $tweet->display_text_range[0],
  219. $tweet->display_text_range[1]-$tweet->display_text_range[0],
  220. 'UTF-8');
  221. } else {
  222. $text = $tweet->text;
  223. }
  224. if(property_exists($tweet, 'entities')) {
  225. $entities = $tweet->entities;
  226. }
  227. }
  228. // Twitter escapes & as &amp; in the text
  229. $text = html_entity_decode($text);
  230. $html = str_replace("\n", "<br>\n", $text);
  231. if(property_exists($entities, 'user_mentions')) {
  232. foreach($entities->user_mentions as $user) {
  233. $html = str_replace('@'.$user->screen_name, '<a href="https://twitter.com/'.$user->screen_name.'">@'.$user->screen_name.'</a>', $html);
  234. }
  235. }
  236. if(property_exists($entities, 'urls')) {
  237. foreach($entities->urls as $url) {
  238. $text = str_replace($url->url, $url->expanded_url, $text);
  239. $html = str_replace($url->url, '<a href="'.$url->expanded_url.'">'.$url->expanded_url.'</a>', $html);
  240. }
  241. }
  242. $content = [
  243. 'text' => $text,
  244. ];
  245. if($html != $text)
  246. $content['html'] = $html;
  247. return $content;
  248. }
  249. private static function expandTwitterObjectURLs($text, $object, $key) {
  250. if(property_exists($object, 'entities')
  251. && property_exists($object->entities, $key)
  252. && property_exists($object->entities->{$key}, 'urls')) {
  253. foreach($object->entities->{$key}->urls as $url) {
  254. $text = str_replace($url->url, $url->expanded_url, $text);
  255. }
  256. }
  257. return $text;
  258. }
  259. /**
  260. * Converts base 60 to base 10, with error checking
  261. * http://tantek.pbworks.com/NewBase60
  262. * @param string $s
  263. * @return int
  264. */
  265. function b60to10($s)
  266. {
  267. $n = 0;
  268. for($i = 0; $i < strlen($s); $i++) // iterate from first to last char of $s
  269. {
  270. $c = ord($s[$i]); // put current ASCII of char into $c
  271. if ($c>=48 && $c<=57) { $c=bcsub($c,48); }
  272. else if ($c>=65 && $c<=72) { $c=bcsub($c,55); }
  273. else if ($c==73 || $c==108) { $c=1; } // typo capital I, lowercase l to 1
  274. else if ($c>=74 && $c<=78) { $c=bcsub($c,56); }
  275. else if ($c==79) { $c=0; } // error correct typo capital O to 0
  276. else if ($c>=80 && $c<=90) { $c=bcsub($c,57); }
  277. else if ($c==95) { $c=34; } // underscore
  278. else if ($c>=97 && $c<=107) { $c=bcsub($c,62); }
  279. else if ($c>=109 && $c<=122) { $c=bcsub($c,63); }
  280. else { $c = 0; } // treat all other noise as 0
  281. $n = bcadd(bcmul(60, $n), $c);
  282. }
  283. return $n;
  284. }
  285. }