]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitterimport.php
07a9cf95f66c9f63f49dccf380ce1a9590bf0fab
[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                          $status->id . ' 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         $statusUri = $this->makeStatusURI($status->user->screen_name, $status->id);
90
91         // check to see if we've already imported the status
92         $n2s = Notice_to_status::staticGet('status_id', $status->id);
93
94         if (!empty($n2s)) {
95             common_log(
96                 LOG_INFO,
97                 $this->name() .
98                 " - Ignoring duplicate import: {$status->id}"
99             );
100             return Notice::staticGet('id', $n2s->notice_id);
101         }
102
103         // If it's a retweet, save it as a repeat!
104         if (!empty($status->retweeted_status)) {
105             common_log(LOG_INFO, "Status {$status->id} is a retweet of {$status->retweeted_status->id}.");
106             $original = $this->saveStatus($status->retweeted_status);
107             if (empty($original)) {
108                 return null;
109             } else {
110                 $author = $original->getProfile();
111                 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
112                 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
113                 $content = sprintf(_m('RT @%1$s %2$s'),
114                                    $author->nickname,
115                                    $original->content);
116
117                 if (Notice::contentTooLong($content)) {
118                     $contentlimit = Notice::maxContent();
119                     $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
120                 }
121
122                 $repeat = Notice::saveNew($profile->id,
123                                           $content,
124                                           'twitter',
125                                           array('repeat_of' => $original->id,
126                                                 'uri' => $statusUri,
127                                                 'is_local' => Notice::GATEWAY));
128                 common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
129                 Notice_to_status::saveNew($repeat->id, $status->id);
130                 return $repeat;
131             }
132         }
133
134         $notice = new Notice();
135
136         $notice->profile_id = $profile->id;
137         $notice->uri        = $statusUri;
138         $notice->url        = $statusUri;
139         $notice->created    = strftime(
140             '%Y-%m-%d %H:%M:%S',
141             strtotime($status->created_at)
142         );
143
144         $notice->source     = 'twitter';
145
146         $notice->reply_to   = null;
147
148         if (!empty($status->in_reply_to_status_id)) {
149             common_log(LOG_INFO, "Status {$status->id} is a reply to status {$status->in_reply_to_status_id}");
150             $n2s = Notice_to_status::staticGet('status_id', $status->in_reply_to_status_id);
151             if (empty($n2s)) {
152                 common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
153             } else {
154                 $reply = Notice::staticGet('id', $n2s->notice_id);
155                 if (empty($reply)) {
156                     common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
157                 } else {
158                     common_log(LOG_INFO, "Found local notice {$reply->id} for status {$status->in_reply_to_status_id}");
159                     $notice->reply_to     = $reply->id;
160                     $notice->conversation = $reply->conversation;
161                 }
162             }
163         }
164
165         if (empty($notice->conversation)) {
166             $conv = Conversation::create();
167             $notice->conversation = $conv->id;
168             common_log(LOG_INFO, "No known conversation for status {$status->id} so making a new one {$conv->id}.");
169         }
170
171         $notice->is_local   = Notice::GATEWAY;
172
173         $notice->content  = html_entity_decode($status->text, ENT_QUOTES, 'UTF-8');
174         $notice->rendered = $this->linkify($status);
175
176         if (Event::handle('StartNoticeSave', array(&$notice))) {
177
178             $id = $notice->insert();
179
180             if (!$id) {
181                 common_log_db_error($notice, 'INSERT', __FILE__);
182                 common_log(LOG_ERR, $this->name() .
183                     ' - Problem saving notice.');
184             }
185
186             Event::handle('EndNoticeSave', array($notice));
187         }
188
189         Notice_to_status::saveNew($notice->id, $status->id);
190
191         $this->saveStatusMentions($notice, $status);
192
193         $notice->blowOnInsert();
194
195         return $notice;
196     }
197
198     /**
199      * Make an URI for a status.
200      *
201      * @param object $status status object
202      *
203      * @return string URI
204      */
205     function makeStatusURI($username, $id)
206     {
207         return 'http://twitter.com/'
208           . $username
209           . '/status/'
210           . $id;
211     }
212
213
214     /**
215      * Look up a Profile by profileurl field.  Profile::staticGet() was
216      * not working consistently.
217      *
218      * @param string $nickname   local nickname of the Twitter user
219      * @param string $profileurl the profile url
220      *
221      * @return mixed value the first Profile with that url, or null
222      */
223     function getProfileByUrl($nickname, $profileurl)
224     {
225         $profile = new Profile();
226         $profile->nickname = $nickname;
227         $profile->profileurl = $profileurl;
228         $profile->limit(1);
229
230         if ($profile->find()) {
231             $profile->fetch();
232             return $profile;
233         }
234
235         return null;
236     }
237
238     /**
239      * Check to see if this Twitter status has already been imported
240      *
241      * @param Profile $profile   Twitter user's local profile
242      * @param string  $statusUri URI of the status on Twitter
243      *
244      * @return mixed value a matching Notice or null
245      */
246     function checkDupe($profile, $statusUri)
247     {
248         $notice = new Notice();
249         $notice->uri = $statusUri;
250         $notice->profile_id = $profile->id;
251         $notice->limit(1);
252
253         if ($notice->find()) {
254             $notice->fetch();
255             return $notice;
256         }
257
258         return null;
259     }
260
261     function ensureProfile($user)
262     {
263         // check to see if there's already a profile for this user
264         $profileurl = 'http://twitter.com/' . $user->screen_name;
265         $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
266
267         if (!empty($profile)) {
268             common_debug($this->name() .
269                          " - Profile for $profile->nickname found.");
270
271             // Check to see if the user's Avatar has changed
272
273             $this->checkAvatar($user, $profile);
274             return $profile;
275
276         } else {
277             common_debug($this->name() . ' - Adding profile and remote profile ' .
278                          "for Twitter user: $profileurl.");
279
280             $profile = new Profile();
281             $profile->query("BEGIN");
282
283             $profile->nickname = $user->screen_name;
284             $profile->fullname = $user->name;
285             $profile->homepage = $user->url;
286             $profile->bio = $user->description;
287             $profile->location = $user->location;
288             $profile->profileurl = $profileurl;
289             $profile->created = common_sql_now();
290
291             try {
292                 $id = $profile->insert();
293             } catch(Exception $e) {
294                 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert profile - ' . $e->getMessage());
295             }
296
297             if (empty($id)) {
298                 common_log_db_error($profile, 'INSERT', __FILE__);
299                 $profile->query("ROLLBACK");
300                 return false;
301             }
302
303             // check for remote profile
304
305             $remote_pro = Remote_profile::staticGet('uri', $profileurl);
306
307             if (empty($remote_pro)) {
308                 $remote_pro = new Remote_profile();
309
310                 $remote_pro->id = $id;
311                 $remote_pro->uri = $profileurl;
312                 $remote_pro->created = common_sql_now();
313
314                 try {
315                     $rid = $remote_pro->insert();
316                 } catch (Exception $e) {
317                     common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
318                 }
319
320                 if (empty($rid)) {
321                     common_log_db_error($profile, 'INSERT', __FILE__);
322                     $profile->query("ROLLBACK");
323                     return false;
324                 }
325             }
326
327             $profile->query("COMMIT");
328
329             $this->saveAvatars($user, $id);
330
331             return $profile;
332         }
333     }
334
335     function checkAvatar($twitter_user, $profile)
336     {
337         global $config;
338
339         $path_parts = pathinfo($twitter_user->profile_image_url);
340
341         $newname = 'Twitter_' . $twitter_user->id . '_' .
342             $path_parts['basename'];
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         $img_root = substr($path_parts['basename'], 0, -11);
371         $ext = $path_parts['extension'];
372         $mediatype = $this->getMediatype($ext);
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 'jpg':
402             $mediatype = 'image/jpg';
403             break;
404         case 'gif':
405             $mediatype = 'image/gif';
406             break;
407         default:
408             $mediatype = 'image/png';
409         }
410
411         return $mediatype;
412     }
413
414     function saveAvatars($user, $id)
415     {
416         global $config;
417
418         $path_parts = pathinfo($user->profile_image_url);
419         $ext = $path_parts['extension'];
420         $end = strlen('_normal' . $ext);
421         $img_root = substr($path_parts['basename'], 0, -($end+1));
422         $mediatype = $this->getMediatype($ext);
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::staticGet($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)
541     {
542         $text = $status->text;
543
544         if (empty($status->entities)) {
545             common_log(LOG_WARNING, "No entities data for {$status->id}; trying to fake up links ourselves.");
546             $text = common_replace_urls_callback($text, 'common_linkify');
547             $text = preg_replace('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.TwitterStatusFetcher::tagLink('\\2')", $text);
548             $text = preg_replace('/(^|\s+)@([a-z0-9A-Z_]{1,64})/e', "'\\1@'.TwitterStatusFetcher::atLink('\\2')", $text);
549             return $text;
550         }
551
552         // Move all the entities into order so we can
553         // replace them in reverse order and thus
554         // not mess up their indices
555
556         $toReplace = array();
557
558         if (!empty($status->entities->urls)) {
559             foreach ($status->entities->urls as $url) {
560                 $toReplace[$url->indices[0]] = array(self::URL, $url);
561             }
562         }
563
564         if (!empty($status->entities->hashtags)) {
565             foreach ($status->entities->hashtags as $hashtag) {
566                 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
567             }
568         }
569
570         if (!empty($status->entities->user_mentions)) {
571             foreach ($status->entities->user_mentions as $mention) {
572                 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
573             }
574         }
575
576         // sort in reverse order by key
577
578         krsort($toReplace);
579
580         foreach ($toReplace as $part) {
581             list($type, $object) = $part;
582             switch($type) {
583             case self::URL:
584                 $linkText = $this->makeUrlLink($object);
585                 break;
586             case self::HASHTAG:
587                 $linkText = $this->makeHashtagLink($object);
588                 break;
589             case self::MENTION:
590                 $linkText = $this->makeMentionLink($object);
591                 break;
592             default:
593                 continue;
594             }
595             $text = mb_substr($text, 0, $object->indices[0]) . $linkText . mb_substr($text, $object->indices[1]);
596         }
597         return $text;
598     }
599
600     function makeUrlLink($object)
601     {
602         return "<a href='{$object->url}' class='extlink'>{$object->url}</a>";
603     }
604
605     function makeHashtagLink($object)
606     {
607         return "#" . self::tagLink($object->text);
608     }
609
610     function makeMentionLink($object)
611     {
612         return "@".self::atLink($object->screen_name, $object->name);
613     }
614
615     static function tagLink($tag)
616     {
617         return "<a href='https://twitter.com/search?q=%23{$tag}' class='hashtag'>{$tag}</a>";
618     }
619
620     static function atLink($screenName, $fullName=null)
621     {
622         if (!empty($fullName)) {
623             return "<a href='http://twitter.com/{$screenName}' title='{$fullName}'>{$screenName}</a>";
624         } else {
625             return "<a href='http://twitter.com/{$screenName}'>{$screenName}</a>";
626         }
627     }
628
629     function saveStatusMentions($notice, $status)
630     {
631         $mentions = array();
632
633         if (empty($status->entities) || empty($status->entities->user_mentions)) {
634             return;
635         }
636
637         foreach ($status->entities->user_mentions as $mention) {
638             $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
639             if (!empty($flink)) {
640                 $user = User::staticGet('id', $flink->user_id);
641                 if (!empty($user)) {
642                     $reply = new Reply();
643                     $reply->notice_id  = $notice->id;
644                     $reply->profile_id = $user->id;
645                     common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
646                     $id = $reply->insert();
647                 }
648             }
649         }
650     }
651 }