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