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