]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitterimport.php
Merge branch 'master' into 0.9.x
[quix0rs-gnu-social.git] / plugins / TwitterBridge / 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::staticGet('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::staticGet('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::staticGet('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::staticGet('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($status->text, ENT_QUOTES, 'UTF-8');
176         $notice->rendered = $this->linkify($status);
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::staticGet() 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::staticGet('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         $path_parts = pathinfo($twitter_user->profile_image_url);
343
344         $newname = 'Twitter_' . $twitter_user->id . '_' .
345             $path_parts['basename'];
346
347         $oldname = $profile->getAvatar(48)->filename;
348
349         if ($newname != $oldname) {
350             common_debug($this->name() . ' - Avatar for Twitter user ' .
351                          "$profile->nickname has changed.");
352             common_debug($this->name() . " - old: $oldname new: $newname");
353
354             $this->updateAvatars($twitter_user, $profile);
355         }
356
357         if ($this->missingAvatarFile($profile)) {
358             common_debug($this->name() . ' - Twitter user ' .
359                          $profile->nickname .
360                          ' is missing one or more local avatars.');
361             common_debug($this->name() ." - old: $oldname new: $newname");
362
363             $this->updateAvatars($twitter_user, $profile);
364         }
365     }
366
367     function updateAvatars($twitter_user, $profile) {
368
369         global $config;
370
371         $path_parts = pathinfo($twitter_user->profile_image_url);
372
373         $img_root = substr($path_parts['basename'], 0, -11);
374         $ext = $path_parts['extension'];
375         $mediatype = $this->getMediatype($ext);
376
377         foreach (array('mini', 'normal', 'bigger') as $size) {
378             $url = $path_parts['dirname'] . '/' .
379                 $img_root . '_' . $size . ".$ext";
380             $filename = 'Twitter_' . $twitter_user->id . '_' .
381                 $img_root . "_$size.$ext";
382
383             $this->updateAvatar($profile->id, $size, $mediatype, $filename);
384             $this->fetchAvatar($url, $filename);
385         }
386     }
387
388     function missingAvatarFile($profile) {
389         foreach (array(24, 48, 73) as $size) {
390             $filename = $profile->getAvatar($size)->filename;
391             $avatarpath = Avatar::path($filename);
392             if (file_exists($avatarpath) == FALSE) {
393                 return true;
394             }
395         }
396         return false;
397     }
398
399     function getMediatype($ext)
400     {
401         $mediatype = null;
402
403         switch (strtolower($ext)) {
404         case 'jpg':
405             $mediatype = 'image/jpg';
406             break;
407         case 'gif':
408             $mediatype = 'image/gif';
409             break;
410         default:
411             $mediatype = 'image/png';
412         }
413
414         return $mediatype;
415     }
416
417     function saveAvatars($user, $id)
418     {
419         global $config;
420
421         $path_parts = pathinfo($user->profile_image_url);
422         $ext = $path_parts['extension'];
423         $end = strlen('_normal' . $ext);
424         $img_root = substr($path_parts['basename'], 0, -($end+1));
425         $mediatype = $this->getMediatype($ext);
426
427         foreach (array('mini', 'normal', 'bigger') as $size) {
428             $url = $path_parts['dirname'] . '/' .
429                 $img_root . '_' . $size . ".$ext";
430             $filename = 'Twitter_' . $user->id . '_' .
431                 $img_root . "_$size.$ext";
432
433             if ($this->fetchAvatar($url, $filename)) {
434                 $this->newAvatar($id, $size, $mediatype, $filename);
435             } else {
436                 common_log(LOG_WARNING, $id() .
437                            " - Problem fetching Avatar: $url");
438             }
439         }
440     }
441
442     function updateAvatar($profile_id, $size, $mediatype, $filename) {
443
444         common_debug($this->name() . " - Updating avatar: $size");
445
446         $profile = Profile::staticGet($profile_id);
447
448         if (empty($profile)) {
449             common_debug($this->name() . " - Couldn't get profile: $profile_id!");
450             return;
451         }
452
453         $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
454         $avatar = $profile->getAvatar($sizes[$size]);
455
456         // Delete the avatar, if present
457         if ($avatar) {
458             $avatar->delete();
459         }
460
461         $this->newAvatar($profile->id, $size, $mediatype, $filename);
462     }
463
464     function newAvatar($profile_id, $size, $mediatype, $filename)
465     {
466         global $config;
467
468         $avatar = new Avatar();
469         $avatar->profile_id = $profile_id;
470
471         switch($size) {
472         case 'mini':
473             $avatar->width  = 24;
474             $avatar->height = 24;
475             break;
476         case 'normal':
477             $avatar->width  = 48;
478             $avatar->height = 48;
479             break;
480         default:
481             // Note: Twitter's big avatars are a different size than
482             // StatusNet's (StatusNet's = 96)
483             $avatar->width  = 73;
484             $avatar->height = 73;
485         }
486
487         $avatar->original = 0; // we don't have the original
488         $avatar->mediatype = $mediatype;
489         $avatar->filename = $filename;
490         $avatar->url = Avatar::url($filename);
491
492         $avatar->created = common_sql_now();
493
494         try {
495             $id = $avatar->insert();
496         } catch (Exception $e) {
497             common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
498         }
499
500         if (empty($id)) {
501             common_log_db_error($avatar, 'INSERT', __FILE__);
502             return null;
503         }
504
505         common_debug($this->name() .
506                      " - Saved new $size avatar for $profile_id.");
507
508         return $id;
509     }
510
511     /**
512      * Fetch a remote avatar image and save to local storage.
513      *
514      * @param string $url avatar source URL
515      * @param string $filename bare local filename for download
516      * @return bool true on success, false on failure
517      */
518     function fetchAvatar($url, $filename)
519     {
520         common_debug($this->name() . " - Fetching Twitter avatar: $url");
521
522         $request = HTTPClient::start();
523         $response = $request->get($url);
524         if ($response->isOk()) {
525             $avatarfile = Avatar::path($filename);
526             $ok = file_put_contents($avatarfile, $response->getBody());
527             if (!$ok) {
528                 common_log(LOG_WARNING, $this->name() .
529                            " - Couldn't open file $filename");
530                 return false;
531             }
532         } else {
533             return false;
534         }
535
536         return true;
537     }
538
539     const URL = 1;
540     const HASHTAG = 2;
541     const MENTION = 3;
542
543     function linkify($status)
544     {
545         $text = $status->text;
546
547         if (empty($status->entities)) {
548             $statusId = twitter_id($status);
549             common_log(LOG_WARNING, "No entities data for {$statusId}; trying to fake up links ourselves.");
550             $text = common_replace_urls_callback($text, 'common_linkify');
551             $text = preg_replace('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.TwitterStatusFetcher::tagLink('\\2')", $text);
552             $text = preg_replace('/(^|\s+)@([a-z0-9A-Z_]{1,64})/e', "'\\1@'.TwitterStatusFetcher::atLink('\\2')", $text);
553             return $text;
554         }
555
556         // Move all the entities into order so we can
557         // replace them and escape surrounding plaintext
558         // in order
559
560         $toReplace = array();
561
562         if (!empty($status->entities->urls)) {
563             foreach ($status->entities->urls as $url) {
564                 $toReplace[$url->indices[0]] = array(self::URL, $url);
565             }
566         }
567
568         if (!empty($status->entities->hashtags)) {
569             foreach ($status->entities->hashtags as $hashtag) {
570                 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
571             }
572         }
573
574         if (!empty($status->entities->user_mentions)) {
575             foreach ($status->entities->user_mentions as $mention) {
576                 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
577             }
578         }
579
580         // sort in forward order by key
581
582         ksort($toReplace);
583
584         $result = '';
585         $cursor = 0;
586
587         foreach ($toReplace as $part) {
588             list($type, $object) = $part;
589             $start = $object->indices[0];
590             $end = $object->indices[1];
591             if ($cursor < $start) {
592                 // Copy in the preceding plaintext
593                 $result .= $this->twitEscape(mb_substr($text, $cursor, $start - $cursor));
594                 $cursor = $start;
595             }
596             $orig = $this->twitEscape(mb_substr($text, $start, $end - $start));
597             switch($type) {
598             case self::URL:
599                 $linkText = $this->makeUrlLink($object, $orig);
600                 break;
601             case self::HASHTAG:
602                 $linkText = $this->makeHashtagLink($object, $orig);
603                 break;
604             case self::MENTION:
605                 $linkText = $this->makeMentionLink($object, $orig);
606                 break;
607             default:
608                 $linkText = $orig;
609                 continue;
610             }
611             $result .= $linkText;
612             $cursor = $end;
613         }
614         $last = $this->twitEscape(mb_substr($text, $cursor));
615         $result .= $last;
616
617         return $result;
618     }
619
620     function twitEscape($str)
621     {
622         // Twitter seems to preemptive turn < and > into &lt; and &gt;
623         // but doesn't for &, so while you may have some magic protection
624         // against XSS by not bothing to escape manually, you still get
625         // invalid XHTML. Thanks!
626         //
627         // Looks like their web interface pretty much sends anything
628         // through intact, so.... to do equivalent, decode all entities
629         // and then re-encode the special ones.
630         return htmlspecialchars(html_entity_decode($str, ENT_COMPAT, 'UTF-8'));
631     }
632
633     function makeUrlLink($object, $orig)
634     {
635         return "<a href='{$object->url}' class='extlink'>{$orig}</a>";
636     }
637
638     function makeHashtagLink($object, $orig)
639     {
640         return "#" . self::tagLink($object->text, substr($orig, 1));
641     }
642
643     function makeMentionLink($object, $orig)
644     {
645         return "@".self::atLink($object->screen_name, $object->name, substr($orig, 1));
646     }
647
648     static function tagLink($tag, $orig)
649     {
650         return "<a href='https://search.twitter.com/search?q=%23{$tag}' class='hashtag'>{$orig}</a>";
651     }
652
653     static function atLink($screenName, $fullName, $orig)
654     {
655         if (!empty($fullName)) {
656             return "<a href='http://twitter.com/#!/{$screenName}' title='{$fullName}'>{$orig}</a>";
657         } else {
658             return "<a href='http://twitter.com/#!/{$screenName}'>{$orig}</a>";
659         }
660     }
661
662     function saveStatusMentions($notice, $status)
663     {
664         $mentions = array();
665
666         if (empty($status->entities) || empty($status->entities->user_mentions)) {
667             return;
668         }
669
670         foreach ($status->entities->user_mentions as $mention) {
671             $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
672             if (!empty($flink)) {
673                 $user = User::staticGet('id', $flink->user_id);
674                 if (!empty($user)) {
675                     $reply = new Reply();
676                     $reply->notice_id  = $notice->id;
677                     $reply->profile_id = $user->id;
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 }