]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/lib/twitterimport.php
780fa8f92625c8ad66c40a888422e9c58944fb8e
[quix0rs-gnu-social.git] / plugins / TwitterBridge / lib / twitterimport.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * PHP version 5
6  *
7  * LICENCE: This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  * @category  Plugin
21  * @package   StatusNet
22  * @author    Zach Copley <zach@status.net>
23  * @author    Julien C <chaumond@gmail.com>
24  * @author    Brion Vibber <brion@status.net>
25  * @copyright 2009-2010 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 if (!defined('STATUSNET')) {
31     exit(1);
32 }
33
34 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
35
36 /**
37  * Encapsulation of the Twitter status -> notice incoming bridge import.
38  * Is used by both the polling twitterstatusfetcher.php daemon, and the
39  * in-progress streaming import.
40  *
41  * @category Plugin
42  * @package  StatusNet
43  * @author   Zach Copley <zach@status.net>
44  * @author   Julien C <chaumond@gmail.com>
45  * @author   Brion Vibber <brion@status.net>
46  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
47  * @link     http://status.net/
48  * @link     http://twitter.com/
49  */
50 class TwitterImport
51 {
52     public function importStatus($status)
53     {
54         // Hacktastic: filter out stuff coming from this StatusNet
55         $source = mb_strtolower(common_config('integration', 'source'));
56
57         if (preg_match("/$source/", mb_strtolower($status->source))) {
58             common_debug($this->name() . ' - Skipping import of status ' .
59                          twitter_id($status) . ' with source ' . $source);
60             return null;
61         }
62
63         // Don't save it if the user is protected
64         // FIXME: save it but treat it as private
65         if ($status->user->protected) {
66             return null;
67         }
68
69         $notice = $this->saveStatus($status);
70
71         return $notice;
72     }
73
74     function name()
75     {
76         return get_class($this);
77     }
78
79     function saveStatus($status)
80     {
81         $profile = $this->ensureProfile($status->user);
82
83         if (empty($profile)) {
84             common_log(LOG_ERR, $this->name() .
85                 ' - Problem saving notice. No associated Profile.');
86             return null;
87         }
88
89         $statusId = twitter_id($status);
90         $statusUri = $this->makeStatusURI($status->user->screen_name, $statusId);
91
92         // check to see if we've already imported the status
93         $n2s = Notice_to_status::getKV('status_id', $statusId);
94
95         if (!empty($n2s)) {
96             common_log(
97                 LOG_INFO,
98                 $this->name() .
99                 " - Ignoring duplicate import: {$statusId}"
100             );
101             return Notice::getKV('id', $n2s->notice_id);
102         }
103
104         // If it's a retweet, save it as a repeat!
105         if (!empty($status->retweeted_status)) {
106             common_log(LOG_INFO, "Status {$statusId} is a retweet of " . twitter_id($status->retweeted_status) . ".");
107             $original = $this->saveStatus($status->retweeted_status);
108             if (empty($original)) {
109                 return null;
110             } else {
111                 $author = $original->getProfile();
112                 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
113                 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
114                 $content = sprintf(_m('RT @%1$s %2$s'),
115                                    $author->nickname,
116                                    $original->content);
117
118                 if (Notice::contentTooLong($content)) {
119                     $contentlimit = Notice::maxContent();
120                     $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
121                 }
122
123                 $repeat = Notice::saveNew($profile->id,
124                                           $content,
125                                           'twitter',
126                                           array('repeat_of' => $original->id,
127                                                 'uri' => $statusUri,
128                                                 'is_local' => Notice::GATEWAY));
129                 common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
130                 Notice_to_status::saveNew($repeat->id, $statusId);
131                 return $repeat;
132             }
133         }
134
135         $notice = new Notice();
136
137         $notice->profile_id = $profile->id;
138         $notice->uri        = $statusUri;
139         $notice->url        = $statusUri;
140         $notice->created    = strftime(
141             '%Y-%m-%d %H:%M:%S',
142             strtotime($status->created_at)
143         );
144
145         $notice->source     = 'twitter';
146
147         $notice->reply_to   = null;
148
149         $replyTo = twitter_id($status, 'in_reply_to_status_id');
150         if (!empty($replyTo)) {
151             common_log(LOG_INFO, "Status {$statusId} is a reply to status {$replyTo}");
152             $n2s = Notice_to_status::getKV('status_id', $replyTo);
153             if (empty($n2s)) {
154                 common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
155             } else {
156                 $reply = Notice::getKV('id', $n2s->notice_id);
157                 if (empty($reply)) {
158                     common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
159                 } else {
160                     common_log(LOG_INFO, "Found local notice {$reply->id} for status {$replyTo}");
161                     $notice->reply_to     = $reply->id;
162                     $notice->conversation = $reply->conversation;
163                 }
164             }
165         }
166
167         if (empty($notice->conversation)) {
168             $conv = Conversation::create();
169             $notice->conversation = $conv->id;
170             common_log(LOG_INFO, "No known conversation for status {$statusId} so making a new one {$conv->id}.");
171         }
172
173         $notice->is_local   = Notice::GATEWAY;
174
175         $notice->content  = html_entity_decode($this->linkify($status, FALSE), ENT_QUOTES, 'UTF-8');
176         $notice->rendered = $this->linkify($status, TRUE);
177
178         if (Event::handle('StartNoticeSave', array(&$notice))) {
179
180             $id = $notice->insert();
181
182             if (!$id) {
183                 common_log_db_error($notice, 'INSERT', __FILE__);
184                 common_log(LOG_ERR, $this->name() .
185                     ' - Problem saving notice.');
186             }
187
188             Event::handle('EndNoticeSave', array($notice));
189         }
190
191         Notice_to_status::saveNew($notice->id, $statusId);
192
193         $this->saveStatusMentions($notice, $status);
194         $this->saveStatusAttachments($notice, $status);
195
196         $notice->blowOnInsert();
197
198         return $notice;
199     }
200
201     /**
202      * Make an URI for a status.
203      *
204      * @param object $status status object
205      *
206      * @return string URI
207      */
208     function makeStatusURI($username, $id)
209     {
210         return 'http://twitter.com/#!/'
211           . $username
212           . '/status/'
213           . $id;
214     }
215
216
217     /**
218      * Look up a Profile by profileurl field.  Profile::getKV() was
219      * not working consistently.
220      *
221      * @param string $nickname   local nickname of the Twitter user
222      * @param string $profileurl the profile url
223      *
224      * @return mixed value the first Profile with that url, or null
225      */
226     function getProfileByUrl($nickname, $profileurl)
227     {
228         $profile = new Profile();
229         $profile->nickname = $nickname;
230         $profile->profileurl = $profileurl;
231         $profile->limit(1);
232
233         if ($profile->find()) {
234             $profile->fetch();
235             return $profile;
236         }
237
238         return null;
239     }
240
241     /**
242      * Check to see if this Twitter status has already been imported
243      *
244      * @param Profile $profile   Twitter user's local profile
245      * @param string  $statusUri URI of the status on Twitter
246      *
247      * @return mixed value a matching Notice or null
248      */
249     function checkDupe($profile, $statusUri)
250     {
251         $notice = new Notice();
252         $notice->uri = $statusUri;
253         $notice->profile_id = $profile->id;
254         $notice->limit(1);
255
256         if ($notice->find()) {
257             $notice->fetch();
258             return $notice;
259         }
260
261         return null;
262     }
263
264     function ensureProfile($user)
265     {
266         // check to see if there's already a profile for this user
267         $profileurl = 'http://twitter.com/' . $user->screen_name;
268         $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
269
270         if (!empty($profile)) {
271             common_debug($this->name() .
272                          " - Profile for $profile->nickname found.");
273
274             // Check to see if the user's Avatar has changed
275
276             $this->checkAvatar($user, $profile);
277             return $profile;
278
279         } else {
280             common_debug($this->name() . ' - Adding profile and remote profile ' .
281                          "for Twitter user: $profileurl.");
282
283             $profile = new Profile();
284             $profile->query("BEGIN");
285
286             $profile->nickname = $user->screen_name;
287             $profile->fullname = $user->name;
288             $profile->homepage = $user->url;
289             $profile->bio = $user->description;
290             $profile->location = $user->location;
291             $profile->profileurl = $profileurl;
292             $profile->created = common_sql_now();
293
294             try {
295                 $id = $profile->insert();
296             } catch(Exception $e) {
297                 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert profile - ' . $e->getMessage());
298             }
299
300             if (empty($id)) {
301                 common_log_db_error($profile, 'INSERT', __FILE__);
302                 $profile->query("ROLLBACK");
303                 return false;
304             }
305
306             // check for remote profile
307
308             $remote_pro = Remote_profile::getKV('uri', $profileurl);
309
310             if (empty($remote_pro)) {
311                 $remote_pro = new Remote_profile();
312
313                 $remote_pro->id = $id;
314                 $remote_pro->uri = $profileurl;
315                 $remote_pro->created = common_sql_now();
316
317                 try {
318                     $rid = $remote_pro->insert();
319                 } catch (Exception $e) {
320                     common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
321                 }
322
323                 if (empty($rid)) {
324                     common_log_db_error($profile, 'INSERT', __FILE__);
325                     $profile->query("ROLLBACK");
326                     return false;
327                 }
328             }
329
330             $profile->query("COMMIT");
331
332             $this->saveAvatars($user, $id);
333
334             return $profile;
335         }
336     }
337
338     function checkAvatar($twitter_user, $profile)
339     {
340         global $config;
341
342         $newname = 'Twitter_' . $twitter_user->id . '_' . basename($twitter_user->profile_image_url);
343
344         try {
345             $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
346             $oldname = $avatar->filename;
347             unset($avatar);
348         } catch (Exception $e) {
349             $oldname = null;
350         }
351         
352
353         if ($newname != $oldname) {
354             common_debug($this->name() . ' - Avatar for Twitter user ' .
355                          "$profile->nickname has changed.");
356             common_debug($this->name() . " - old: $oldname new: $newname");
357
358             $this->updateAvatars($twitter_user, $profile);
359         }
360
361         if (Avatar::hasOriginal($profile)) {
362             common_debug($this->name() . ' - Twitter user ' .
363                          $profile->nickname .
364                          ' is missing one or more local avatars.');
365             common_debug($this->name() ." - old: $oldname new: $newname");
366
367             $this->updateAvatars($twitter_user, $profile);
368         }
369     }
370
371     function updateAvatars($twitter_user, $profile) {
372
373         global $config;
374
375         $path_parts = pathinfo($twitter_user->profile_image_url);
376
377         $ext = (isset($path_parts['extension']) ? '.'.$path_parts['extension'] : '');   // some lack extension
378         $img_root = basename($path_parts['basename'], '_normal'.$ext);  // cut off extension
379         $mediatype = $this->getMediatype(substr($ext, 1));
380
381         foreach (array('mini', 'normal', 'bigger') as $size) {
382             $url = $path_parts['dirname'] . '/' .
383                 $img_root . '_' . $size . $ext;
384             $filename = 'Twitter_' . $twitter_user->id . '_' .
385                 $img_root . '_' . $size . $ext;
386
387             $this->updateAvatar($profile->id, $size, $mediatype, $filename);
388             $this->fetchAvatar($url, $filename);
389         }
390     }
391
392     function getMediatype($ext)
393     {
394         $mediatype = null;
395
396         switch (strtolower($ext)) {
397         case 'jpeg':
398         case 'jpg':
399             $mediatype = 'image/jpeg';
400             break;
401         case 'gif':
402             $mediatype = 'image/gif';
403             break;
404         default:
405             $mediatype = 'image/png';
406         }
407
408         return $mediatype;
409     }
410
411     function saveAvatars($user, $id)
412     {
413         global $config;
414
415         $path_parts = pathinfo($user->profile_image_url);
416         $ext = (isset($path_parts['extension']) ? '.'.$path_parts['extension'] : '');
417         $img_root = basename($path_parts['basename'], '_normal'.$ext);
418         $mediatype = $this->getMediatype(substr($ext, 1));
419
420         foreach (array('mini', 'normal', 'bigger') as $size) {
421             $url = $path_parts['dirname'] . '/' .
422                 $img_root . '_' . $size . $ext;
423             $filename = 'Twitter_' . $user->id . '_' .
424                 $img_root . '_' . $size . $ext;
425
426             if ($this->fetchAvatar($url, $filename)) {
427                 $this->newAvatar($id, $size, $mediatype, $filename);
428             } else {
429                 common_log(LOG_WARNING, $id() .
430                            " - Problem fetching Avatar: $url");
431             }
432         }
433     }
434
435     function updateAvatar($profile_id, $size, $mediatype, $filename) {
436
437         common_debug($this->name() . " - Updating avatar: $size");
438
439         $profile = Profile::getKV($profile_id);
440
441         if (empty($profile)) {
442             common_debug($this->name() . " - Couldn't get profile: $profile_id!");
443             return;
444         }
445
446         Avatar::deleteFromProfile($profile);
447
448         $this->newAvatar($profile->id, $size, $mediatype, $filename);
449     }
450
451     function newAvatar($profile_id, $size, $mediatype, $filename)
452     {
453         global $config;
454
455         $avatar = new Avatar();
456         $avatar->profile_id = $profile_id;
457
458         switch($size) {
459         case 'mini':
460             $avatar->width  = 24;
461             $avatar->height = 24;
462             break;
463         case 'normal':
464             $avatar->width  = 48;
465             $avatar->height = 48;
466             break;
467         default:
468             // Note: Twitter's big avatars are a different size than
469             // StatusNet's (StatusNet's = 96)
470             $avatar->width  = 73;
471             $avatar->height = 73;
472         }
473
474         $avatar->original = 0; // we don't have the original
475         $avatar->mediatype = $mediatype;
476         $avatar->filename = $filename;
477         $avatar->url = Avatar::url($filename);
478
479         $avatar->created = common_sql_now();
480
481         try {
482             $id = $avatar->insert();
483         } catch (Exception $e) {
484             common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
485         }
486
487         if (empty($id)) {
488             common_log_db_error($avatar, 'INSERT', __FILE__);
489             return null;
490         }
491
492         common_debug($this->name() .
493                      " - Saved new $size avatar for $profile_id.");
494
495         return $id;
496     }
497
498     /**
499      * Fetch a remote avatar image and save to local storage.
500      *
501      * @param string $url avatar source URL
502      * @param string $filename bare local filename for download
503      * @return bool true on success, false on failure
504      */
505     function fetchAvatar($url, $filename)
506     {
507         common_debug($this->name() . " - Fetching Twitter avatar: $url");
508
509         $request = HTTPClient::start();
510         $response = $request->get($url);
511         if ($response->isOk()) {
512             $avatarfile = Avatar::path($filename);
513             $ok = file_put_contents($avatarfile, $response->getBody());
514             if (!$ok) {
515                 common_log(LOG_WARNING, $this->name() .
516                            " - Couldn't open file $filename");
517                 return false;
518             }
519         } else {
520             return false;
521         }
522
523         return true;
524     }
525
526     const URL = 1;
527     const HASHTAG = 2;
528     const MENTION = 3;
529
530     function linkify($status, $html = FALSE)
531     {
532         $text = $status->text;
533
534         if (empty($status->entities)) {
535             $statusId = twitter_id($status);
536             common_log(LOG_WARNING, "No entities data for {$statusId}; trying to fake up links ourselves.");
537             $text = common_replace_urls_callback($text, 'common_linkify');
538             $text = preg_replace('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.TwitterStatusFetcher::tagLink('\\2')", $text);
539             $text = preg_replace('/(^|\s+)@([a-z0-9A-Z_]{1,64})/e', "'\\1@'.TwitterStatusFetcher::atLink('\\2')", $text);
540             return $text;
541         }
542
543         // Move all the entities into order so we can
544         // replace them and escape surrounding plaintext
545         // in order
546
547         $toReplace = array();
548
549         if (!empty($status->entities->urls)) {
550             foreach ($status->entities->urls as $url) {
551                 $toReplace[$url->indices[0]] = array(self::URL, $url);
552             }
553         }
554
555         if (!empty($status->entities->hashtags)) {
556             foreach ($status->entities->hashtags as $hashtag) {
557                 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
558             }
559         }
560
561         if (!empty($status->entities->user_mentions)) {
562             foreach ($status->entities->user_mentions as $mention) {
563                 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
564             }
565         }
566
567         // sort in forward order by key
568
569         ksort($toReplace);
570
571         $result = '';
572         $cursor = 0;
573
574         foreach ($toReplace as $part) {
575             list($type, $object) = $part;
576             $start = $object->indices[0];
577             $end = $object->indices[1];
578             if ($cursor < $start) {
579                 // Copy in the preceding plaintext
580                 $result .= $this->twitEscape(mb_substr($text, $cursor, $start - $cursor));
581                 $cursor = $start;
582             }
583             $orig = $this->twitEscape(mb_substr($text, $start, $end - $start));
584             switch($type) {
585             case self::URL:
586                 $linkText = $this->makeUrlLink($object, $orig, $html);
587                 break;
588             case self::HASHTAG:
589                 if ($html) {
590                     $linkText = $this->makeHashtagLink($object, $orig);
591                 }else{
592                     $linkText = $orig;
593                 }
594                 break;
595             case self::MENTION:
596                 if ($html) {
597                     $linkText = $this->makeMentionLink($object, $orig);
598                 }else{
599                     $linkText = $orig;
600                 }
601                 break;
602             default:
603                 $linkText = $orig;
604                 continue;
605             }
606             $result .= $linkText;
607             $cursor = $end;
608         }
609         $last = $this->twitEscape(mb_substr($text, $cursor));
610         $result .= $last;
611
612         return $result;
613     }
614
615     function twitEscape($str)
616     {
617         // Twitter seems to preemptive turn < and > into &lt; and &gt;
618         // but doesn't for &, so while you may have some magic protection
619         // against XSS by not bothing to escape manually, you still get
620         // invalid XHTML. Thanks!
621         //
622         // Looks like their web interface pretty much sends anything
623         // through intact, so.... to do equivalent, decode all entities
624         // and then re-encode the special ones.
625         return htmlspecialchars(html_entity_decode($str, ENT_COMPAT, 'UTF-8'));
626     }
627
628     function makeUrlLink($object, $orig, $html)
629     {
630         if ($html) {
631             return '<a href="'.htmlspecialchars($object->expanded_url).'" class="extlink">'.htmlspecialchars($object->display_url).'</a>';
632         }else{
633             return htmlspecialchars($object->expanded_url);
634         }
635     }
636
637     function makeHashtagLink($object, $orig)
638     {
639         return "#" . self::tagLink($object->text, substr($orig, 1));
640     }
641
642     function makeMentionLink($object, $orig)
643     {
644         return "@".self::atLink($object->screen_name, $object->name, substr($orig, 1));
645     }
646
647     static function tagLink($tag, $orig)
648     {
649         return "<a href='https://search.twitter.com/search?q=%23{$tag}' class='hashtag'>{$orig}</a>";
650     }
651
652     static function atLink($screenName, $fullName, $orig)
653     {
654         if (!empty($fullName)) {
655             return "<a href='http://twitter.com/#!/{$screenName}' title='{$fullName}'>{$orig}</a>";
656         } else {
657             return "<a href='http://twitter.com/#!/{$screenName}'>{$orig}</a>";
658         }
659     }
660
661     function saveStatusMentions($notice, $status)
662     {
663         $mentions = array();
664
665         if (empty($status->entities) || empty($status->entities->user_mentions)) {
666             return;
667         }
668
669         foreach ($status->entities->user_mentions as $mention) {
670             $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
671             if (!empty($flink)) {
672                 $user = User::getKV('id', $flink->user_id);
673                 if (!empty($user)) {
674                     $reply = new Reply();
675                     $reply->notice_id  = $notice->id;
676                     $reply->profile_id = $user->id;
677                     $reply->modified   = $notice->created;
678                     common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
679                     $id = $reply->insert();
680                 }
681             }
682         }
683     }
684
685     /**
686      * Record URL links from the notice. Needed to get thumbnail records
687      * for referenced photo and video posts, etc.
688      *
689      * @param Notice $notice
690      * @param object $status
691      */
692     function saveStatusAttachments($notice, $status)
693     {
694         if (common_config('attachments', 'process_links')) {
695             if (!empty($status->entities) && !empty($status->entities->urls)) {
696                 foreach ($status->entities->urls as $url) {
697                     File::processNew($url->url, $notice->id);
698                 }
699             }
700         }
701     }
702 }