]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/lib/twitterimport.php
Merge branch 'master' into nightly
[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 dirname(__DIR__) . '/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 $avatarsizename = 'reasonably_small'; // a Twitter size name for 128x128 px
53     public $avatarsize = 128;   // they're square...
54
55     public function importStatus($status)
56     {
57         // Hacktastic: filter out stuff coming from this StatusNet
58         $source = mb_strtolower(common_config('integration', 'source'));
59
60         if (preg_match("/$source/", mb_strtolower($status->source))) {
61             common_debug(__METHOD__ . ' - Skipping import of status ' .
62                          twitter_id($status) . " with source {$source}");
63             return null;
64         }
65
66         // Don't save it if the user is protected
67         // FIXME: save it but treat it as private
68         if ($status->user->protected) {
69             return null;
70         }
71
72         $notice = $this->saveStatus($status);
73
74         return $notice;
75     }
76
77     function name()
78     {
79         return get_class($this);
80     }
81
82     function saveStatus($status)
83     {
84         $profile = $this->ensureProfile($status->user);
85
86         if (empty($profile)) {
87             common_log(LOG_ERR, __METHOD__ . ' - Problem saving notice. No associated Profile.');
88             return null;
89         }
90
91         $statusId = twitter_id($status);
92         $statusUri = $this->makeStatusURI($status->user->screen_name, $statusId);
93
94         // check to see if we've already imported the status
95         $n2s = Notice_to_status::getKV('status_id', $statusId);
96
97         if (!empty($n2s)) {
98             common_log(
99                 LOG_INFO,
100                 __METHOD__ . " - Ignoring duplicate import: {$statusId}"
101             );
102             return Notice::getKV('id', $n2s->notice_id);
103         }
104
105         $dupe = Notice::getKV('uri', $statusUri);
106         if($dupe instanceof Notice) {
107             // Add it to our record
108             Notice_to_status::saveNew($dupe->id, $statusId);
109             common_log(
110                 LOG_INFO,
111                 __METHOD__ . " - Ignoring duplicate import: {$statusId}"
112             );
113             return $dupe;
114         }
115
116         // If it's a retweet, save it as a repeat!
117         if (!empty($status->retweeted_status)) {
118             common_log(LOG_INFO, "Status {$statusId} is a retweet of " . twitter_id($status->retweeted_status) . ".");
119             $original = $this->saveStatus($status->retweeted_status);
120             if (empty($original)) {
121                 return null;
122             } else {
123                 $author = $original->getProfile();
124                 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
125                 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
126                 $content = sprintf(_m('RT @%1$s %2$s'),
127                                    $author->nickname,
128                                    $original->content);
129
130                 if (Notice::contentTooLong($content)) {
131                     $contentlimit = Notice::maxContent();
132                     $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
133                 }
134
135                 $repeat = Notice::saveNew($profile->id,
136                                           $content,
137                                           'twitter',
138                                           array('repeat_of' => $original->id,
139                                                 'uri' => $statusUri,
140                                                 'is_local' => Notice::GATEWAY,
141                                                         'object_type' => ActivityObject::NOTE,
142                                                         'verb' => ActivityVerb::POST
143                                           ));
144                 common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
145                 Notice_to_status::saveNew($repeat->id, $statusId);
146                 return $repeat;
147             }
148         }
149
150         $notice = new Notice();
151
152         $notice->profile_id     = $profile->id;
153         $notice->uri            = $statusUri;
154         $notice->url            = $statusUri;
155         $notice->verb           = ActivityVerb::POST;
156         $notice->object_type    = ActivityObject::NOTE;
157         $notice->created        = strftime(
158             '%Y-%m-%d %H:%M:%S',
159             strtotime($status->created_at)
160         );
161
162         $notice->source         = 'twitter';
163
164         $notice->reply_to       = null;
165
166         $replyTo = twitter_id($status, 'in_reply_to_status_id');
167         if (!empty($replyTo)) {
168             common_log(LOG_INFO, "Status {$statusId} is a reply to status {$replyTo}");
169             $n2s = Notice_to_status::getKV('status_id', $replyTo);
170             if (empty($n2s)) {
171                 common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
172             } else {
173                 $reply = Notice::getKV('id', $n2s->notice_id);
174                 if (empty($reply)) {
175                     common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
176                 } else {
177                     common_log(LOG_INFO, "Found local notice {$reply->id} for status {$replyTo}");
178                     $notice->reply_to     = $reply->id;
179                     $notice->conversation = $reply->conversation;
180                 }
181             }
182         }
183
184         $notice->is_local   = Notice::GATEWAY;
185
186         $notice->content  = html_entity_decode($this->linkify($status, FALSE), ENT_QUOTES, 'UTF-8');
187         $notice->rendered = $this->linkify($status, TRUE);
188
189         if (Event::handle('StartNoticeSave', array(&$notice))) {
190
191             if (empty($notice->conversation)) {
192                 $conv = Conversation::create();
193                 common_log(LOG_INFO, "No known conversation for status {$statusId} so a new one ({$conv->getID()}) was created.");
194                 $notice->conversation = $conv->getID();
195             }
196
197             $id = $notice->insert();
198
199             if ($id === false) {
200                 common_log_db_error($notice, 'INSERT', __FILE__);
201                 common_log(LOG_ERR, __METHOD__ . ' - Problem saving notice.');
202             }
203
204             Event::handle('EndNoticeSave', array($notice));
205         }
206
207         Notice_to_status::saveNew($notice->id, $statusId);
208
209         $this->saveStatusMentions($notice, $status);
210         $this->saveStatusAttachments($notice, $status);
211
212         $notice->blowOnInsert();
213
214         return $notice;
215     }
216
217     /**
218      * Make an URI for a status.
219      *
220      * @param object $status status object
221      *
222      * @return string URI
223      */
224     function makeStatusURI($username, $id)
225     {
226         return 'https://twitter.com/'
227           . $username
228           . '/status/'
229           . $id;
230     }
231
232
233     /**
234      * Look up a Profile by profileurl field.  Profile::getKV() was
235      * not working consistently.
236      *
237      * @param string $nickname   local nickname of the Twitter user
238      * @param string $profileurl the profile url
239      *
240      * @return mixed value the first Profile with that url, or null
241      */
242     protected function getProfileByUrl($nickname, $profileurl)
243     {
244         $profile = new Profile();
245         $profile->nickname = $nickname;
246         $profile->profileurl = $profileurl;
247         $profile->limit(1);
248
249         if (!$profile->find(true)) {
250             $profile->profileurl = str_replace('https://', 'http://', $profileurl);
251             if (!$profile->find(true)) {
252                 throw new NoResultException($profile);
253             }
254         }
255         return $profile;
256     }
257
258     protected function ensureProfile($twuser)
259     {
260         // check to see if there's already a profile for this user
261         $profileurl = 'https://twitter.com/' . $twuser->screen_name;
262         try {
263             $profile = $this->getProfileByUrl($twuser->screen_name, $profileurl);
264             $this->updateAvatar($twuser, $profile);
265             return $profile;
266         } catch (NoResultException $e) {
267             common_debug(__METHOD__ . ' - Adding profile and remote profile ' .
268                          "for Twitter user: $profileurl.");
269         }
270
271         $profile = new Profile();
272         $profile->query("BEGIN");
273         $profile->nickname   = $twuser->screen_name;
274         $profile->fullname   = $twuser->name;
275         $profile->homepage   = $twuser->url;
276         $profile->bio        = $twuser->description;
277         $profile->location   = $twuser->location;
278         $profile->profileurl = $profileurl;
279         $profile->created    = common_sql_now();
280
281         try {
282             $id = $profile->insert();   // insert _should_ throw exception on failure
283             if (empty($id)) {
284                 throw new Exception('Failed insert');
285             }
286         } catch(Exception $e) {
287             common_log(LOG_WARNING, __METHOD__ . " Couldn't insert profile: " . $e->getMessage());
288             common_log_db_error($profile, 'INSERT', __FILE__);
289             $profile->query("ROLLBACK");
290             return false;
291         }
292
293         $profile->query("COMMIT");
294         $this->updateAvatar($twuser, $profile);
295         return $profile;
296     }
297
298     /*
299      * Checks whether we have to update the profile's avatar
300      *
301      * @return true when updated, false on failure, null when no action taken
302      */
303     protected function updateAvatar($twuser, Profile $profile)
304     {
305         $path_parts = pathinfo($twuser->profile_image_url);
306         $ext        = isset($path_parts['extension'])
307                         ? '.'.$path_parts['extension']
308                         : '';   // some lack extension
309         $img_root   = basename($path_parts['basename'], '_normal'.$ext);        // cut off extension
310         $filename   = "Twitter_{$twuser->id}_{$img_root}_{$this->avatarsizename}{$ext}";
311
312         try {
313             $avatar = Avatar::getUploaded($profile);
314             if ($avatar->filename === $filename) {
315                 return null;
316             }
317             common_debug(__METHOD__ . " - Updating profile avatar (profile_id={$profile->id}) " .
318                         "from {$avatar->filename} to {$filename}");
319             // else we continue with creating a new avatar
320         } catch (NoAvatarException $e) {
321             // Avatar was not found. We can catch NoAvatarException or FileNotFoundException
322             // but generally we just want to continue creating a new avatar.
323             common_debug(__METHOD__ . " - No avatar found for (profile_id={$profile->id})");
324         }
325         
326         $url        = "{$path_parts['dirname']}/{$img_root}_{$this->avatarsizename}{$ext}";
327         $mediatype  = $this->getMediatype(mb_substr($ext, 1));
328
329         try {
330             $this->newAvatar($profile, $url, $filename, $mediatype);
331         } catch (Exception $e) {
332             if (file_exists(Avatar::path($filename))) {
333                 unlink(Avatar::path($filename));
334             }
335             return false;
336         }
337
338         return true;
339     }
340
341     protected function getMediatype($ext)
342     {
343         $mediatype = null;
344
345         switch (strtolower($ext)) {
346         case 'jpeg':
347         case 'jpg':
348             $mediatype = 'image/jpeg';
349             break;
350         case 'gif':
351             $mediatype = 'image/gif';
352             break;
353         default:
354             $mediatype = 'image/png';
355         }
356
357         return $mediatype;
358     }
359
360     protected function newAvatar(Profile $profile, $url, $filename, $mediatype)
361     {
362         // Clear out old avatars, won't do anything if there are none
363         Avatar::deleteFromProfile($profile);
364
365         // throws exception if unable to fetch
366         $this->fetchRemoteUrl($url, Avatar::path($filename));
367
368         $avatar = new Avatar();
369         $avatar->profile_id = $profile->id;
370         $avatar->original   = 1; // this is an original/"uploaded" avatar
371         $avatar->mediatype  = $mediatype;
372         $avatar->filename   = $filename;
373         $avatar->width      = $this->avatarsize;
374         $avatar->height     = $this->avatarsize;
375
376         $avatar->created = common_sql_now();
377
378         $id = $avatar->insert();
379
380         if (empty($id)) {
381             common_log(LOG_WARNING, __METHOD__ . " Couldn't insert avatar - " . $e->getMessage());
382             common_log_db_error($avatar, 'INSERT', __FILE__);
383             throw new ServerException('Could not insert avatar');
384         }
385
386         common_debug(__METHOD__ . " - Saved new avatar for {$profile->id}.");
387
388         return $avatar;
389     }
390
391     /**
392      * Fetch a remote avatar image and save to local storage.
393      *
394      * @param string $url avatar source URL
395      * @param string $filename bare local filename for download
396      * @return bool true on success, false on failure
397      */
398     protected function fetchRemoteUrl($url, $filename)
399     {
400         common_debug(__METHOD__ . " - Fetching Twitter avatar: {$url} to {$filename}");
401         $request = HTTPClient::start();
402         $request->setConfig('connect_timeout', 3);  // I had problems with throttling
403         $request->setConfig('timeout', 6);          // and locking the process sucks.
404         $response = $request->get($url);
405         if ($response->isOk()) {
406             if (!file_put_contents($filename, $response->getBody())) {
407                 throw new ServerException('Failed saving fetched file');
408             }
409         } else {
410             throw new Exception('Unexpected HTTP status code');
411         }
412         return true;
413     }
414
415     const URL = 1;
416     const HASHTAG = 2;
417     const MENTION = 3;
418
419     function linkify($status, $html = FALSE)
420     {
421         $text = $status->text;
422
423         if (empty($status->entities)) {
424             $statusId = twitter_id($status);
425             common_log(LOG_WARNING, "No entities data for {$statusId}; trying to fake up links ourselves.");
426             $text = common_replace_urls_callback($text, 'common_linkify');
427             $text = preg_replace_callback('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/',
428                         function ($m) { return $m[1].'#'.TwitterStatusFetcher::tagLink($m[2]); }, $text);
429             $text = preg_replace_callback('/(^|\s+)@([a-z0-9A-Z_]{1,64})/',
430                         function ($m) { return $m[1].'@'.TwitterStatusFetcher::atLink($m[2]); }, $text);
431             return $text;
432         }
433
434         // Move all the entities into order so we can
435         // replace them and escape surrounding plaintext
436         // in order
437
438         $toReplace = array();
439
440         if (!empty($status->entities->urls)) {
441             foreach ($status->entities->urls as $url) {
442                 $toReplace[$url->indices[0]] = array(self::URL, $url);
443             }
444         }
445
446         if (!empty($status->entities->hashtags)) {
447             foreach ($status->entities->hashtags as $hashtag) {
448                 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
449             }
450         }
451
452         if (!empty($status->entities->user_mentions)) {
453             foreach ($status->entities->user_mentions as $mention) {
454                 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
455             }
456         }
457
458         // sort in forward order by key
459
460         ksort($toReplace);
461
462         $result = '';
463         $cursor = 0;
464
465         foreach ($toReplace as $part) {
466             list($type, $object) = $part;
467             $start = $object->indices[0];
468             $end = $object->indices[1];
469             if ($cursor < $start) {
470                 // Copy in the preceding plaintext
471                 $result .= $this->twitEscape(mb_substr($text, $cursor, $start - $cursor));
472                 $cursor = $start;
473             }
474             $orig = $this->twitEscape(mb_substr($text, $start, $end - $start));
475             switch($type) {
476             case self::URL:
477                 $linkText = $this->makeUrlLink($object, $orig, $html);
478                 break;
479             case self::HASHTAG:
480                 if ($html) {
481                     $linkText = $this->makeHashtagLink($object, $orig);
482                 }else{
483                     $linkText = $orig;
484                 }
485                 break;
486             case self::MENTION:
487                 if ($html) {
488                     $linkText = $this->makeMentionLink($object, $orig);
489                 }else{
490                     $linkText = $orig;
491                 }
492                 break;
493             default:
494                 $linkText = $orig;
495                 continue;
496             }
497             $result .= $linkText;
498             $cursor = $end;
499         }
500         $last = $this->twitEscape(mb_substr($text, $cursor));
501         $result .= $last;
502
503         return $result;
504     }
505
506     function twitEscape($str)
507     {
508         // Twitter seems to preemptive turn < and > into &lt; and &gt;
509         // but doesn't for &, so while you may have some magic protection
510         // against XSS by not bothing to escape manually, you still get
511         // invalid XHTML. Thanks!
512         //
513         // Looks like their web interface pretty much sends anything
514         // through intact, so.... to do equivalent, decode all entities
515         // and then re-encode the special ones.
516         return htmlspecialchars(html_entity_decode($str, ENT_COMPAT, 'UTF-8'));
517     }
518
519     function makeUrlLink($object, $orig, $html)
520     {
521         if ($html) {
522             return '<a href="'.htmlspecialchars($object->expanded_url).'" class="extlink">'.htmlspecialchars($object->display_url).'</a>';
523         }else{
524             return htmlspecialchars($object->expanded_url);
525         }
526     }
527
528     function makeHashtagLink($object, $orig)
529     {
530         return "#" . self::tagLink($object->text, substr($orig, 1));
531     }
532
533     function makeMentionLink($object, $orig)
534     {
535         return "@".self::atLink($object->screen_name, $object->name, substr($orig, 1));
536     }
537
538     static function tagLink($tag, $orig)
539     {
540         return "<a href='https://twitter.com/search?q=%23{$tag}' class='hashtag'>{$orig}</a>";
541     }
542
543     static function atLink($screenName, $fullName, $orig)
544     {
545         if (!empty($fullName)) {
546             return "<a href='https://twitter.com/{$screenName}' title='{$fullName}'>{$orig}</a>";
547         } else {
548             return "<a href='https://twitter.com/{$screenName}'>{$orig}</a>";
549         }
550     }
551
552     function saveStatusMentions($notice, $status)
553     {
554         $mentions = array();
555
556         if (empty($status->entities) || empty($status->entities->user_mentions)) {
557             return;
558         }
559
560         foreach ($status->entities->user_mentions as $mention) {
561             try {
562                 $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
563                 $user = $flink->getUser();
564                 $reply = new Reply();
565                 $reply->notice_id  = $notice->id;
566                 $reply->profile_id = $user->id;
567                 $reply->modified   = $notice->created;
568                 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
569                 $id = $reply->insert();
570             } catch (NoSuchUserException $e) {
571                 common_log(LOG_WARNING, 'No local user found for Foreign_link with id: '.$mention->id);
572             } catch (NoResultException $e) {
573                 common_log(LOG_WARNING, 'No foreign link or profile found for Foreign_link with id: '.$mention->id);
574             }
575         }
576     }
577
578     /**
579      * Record URL links from the notice. Needed to get thumbnail records
580      * for referenced photo and video posts, etc.
581      *
582      * @param Notice $notice
583      * @param object $status
584      */
585     function saveStatusAttachments(Notice $notice, $status)
586     {
587         if (common_config('attachments', 'process_links')) {
588             if (!empty($status->entities) && !empty($status->entities->urls)) {
589                 foreach ($status->entities->urls as $url) {
590                     try {
591                         File::processNew($url->url, $notice);
592                     } catch (ServerException $e) {
593                         // Could not process attached URL
594                     }
595                 }
596             }
597         }
598     }
599 }