]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/lib/twitterimport.php
Twitter Import + avatar fixes (cleaning up + fixing)
[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 $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         // If it's a retweet, save it as a repeat!
106         if (!empty($status->retweeted_status)) {
107             common_log(LOG_INFO, "Status {$statusId} is a retweet of " . twitter_id($status->retweeted_status) . ".");
108             $original = $this->saveStatus($status->retweeted_status);
109             if (empty($original)) {
110                 return null;
111             } else {
112                 $author = $original->getProfile();
113                 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
114                 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
115                 $content = sprintf(_m('RT @%1$s %2$s'),
116                                    $author->nickname,
117                                    $original->content);
118
119                 if (Notice::contentTooLong($content)) {
120                     $contentlimit = Notice::maxContent();
121                     $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
122                 }
123
124                 $repeat = Notice::saveNew($profile->id,
125                                           $content,
126                                           'twitter',
127                                           array('repeat_of' => $original->id,
128                                                 'uri' => $statusUri,
129                                                 'is_local' => Notice::GATEWAY));
130                 common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
131                 Notice_to_status::saveNew($repeat->id, $statusId);
132                 return $repeat;
133             }
134         }
135
136         $notice = new Notice();
137
138         $notice->profile_id = $profile->id;
139         $notice->uri        = $statusUri;
140         $notice->url        = $statusUri;
141         $notice->created    = strftime(
142             '%Y-%m-%d %H:%M:%S',
143             strtotime($status->created_at)
144         );
145
146         $notice->source     = 'twitter';
147
148         $notice->reply_to   = null;
149
150         $replyTo = twitter_id($status, 'in_reply_to_status_id');
151         if (!empty($replyTo)) {
152             common_log(LOG_INFO, "Status {$statusId} is a reply to status {$replyTo}");
153             $n2s = Notice_to_status::getKV('status_id', $replyTo);
154             if (empty($n2s)) {
155                 common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
156             } else {
157                 $reply = Notice::getKV('id', $n2s->notice_id);
158                 if (empty($reply)) {
159                     common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
160                 } else {
161                     common_log(LOG_INFO, "Found local notice {$reply->id} for status {$replyTo}");
162                     $notice->reply_to     = $reply->id;
163                     $notice->conversation = $reply->conversation;
164                 }
165             }
166         }
167
168         if (empty($notice->conversation)) {
169             $conv = Conversation::create();
170             $notice->conversation = $conv->id;
171             common_log(LOG_INFO, "No known conversation for status {$statusId} so making a new one {$conv->id}.");
172         }
173
174         $notice->is_local   = Notice::GATEWAY;
175
176         $notice->content  = html_entity_decode($this->linkify($status, FALSE), ENT_QUOTES, 'UTF-8');
177         $notice->rendered = $this->linkify($status, TRUE);
178
179         if (Event::handle('StartNoticeSave', array(&$notice))) {
180
181             $id = $notice->insert();
182
183             if (!$id) {
184                 common_log_db_error($notice, 'INSERT', __FILE__);
185                 common_log(LOG_ERR, __METHOD__ . ' - 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     protected 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             throw new NoResultException($profile);
235         }
236
237         $profile->fetch();
238         return $profile;
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     protected function ensureProfile($twuser)
265     {
266         // check to see if there's already a profile for this user
267         $profileurl = 'http://twitter.com/' . $twuser->screen_name;
268         try {
269             $profile = $this->getProfileByUrl($twuser->screen_name, $profileurl);
270             $this->checkAvatar($twuser, $profile);
271             return $profile;
272         } catch (NoResultException $e) {
273             common_debug(__METHOD__ . ' - Adding profile and remote profile ' .
274                          "for Twitter user: $profileurl.");
275         }
276
277         $profile = new Profile();
278         $profile->query("BEGIN");
279         $profile->nickname   = $twuser->screen_name;
280         $profile->fullname   = $twuser->name;
281         $profile->homepage   = $twuser->url;
282         $profile->bio        = $twuser->description;
283         $profile->location   = $twuser->location;
284         $profile->profileurl = $profileurl;
285         $profile->created    = common_sql_now();
286
287         try {
288             $id = $profile->insert();   // insert _should_ throw exception on failure
289             if (empty($id)) {
290                 throw new Exception('Failed insert');
291             }
292         } catch(Exception $e) {
293             common_log(LOG_WARNING, __METHOD__ . " Couldn't insert profile: " . $e->getMessage());
294             common_log_db_error($profile, 'INSERT', __FILE__);
295             $profile->query("ROLLBACK");
296             return false;
297         }
298
299         // check for remote profile
300         $remote_pro = Remote_profile::getKV('uri', $profileurl);
301
302         if (!($remote_pro instanceof Remote_profile)) {
303             $remote_pro = new Remote_profile();
304             $remote_pro->id = $id;
305             $remote_pro->uri = $profileurl;
306             $remote_pro->created = common_sql_now();
307
308             try {
309                 $rid = $remote_pro->insert();
310                 if (empty($rid)) {
311                     throw new Exception('Failed insert');
312                 }
313             } catch (Exception $e) {
314                 common_log(LOG_WARNING, __METHOD__ . " Couldn't save remote profile: " . $e->getMessage());
315                 common_log_db_error($profile, 'INSERT', __FILE__);
316                 $profile->query("ROLLBACK");
317                 return false;
318             }
319         }
320
321         $profile->query("COMMIT");
322         $this->updateAvatar($twuser, $profile);
323         return $profile;
324     }
325
326     protected function checkAvatar($twuser, Profile $profile)
327     {
328         $path_parts = pathinfo($twuser->profile_image_url);
329         $ext        = isset($path_parts['extension'])
330                         ? '.'.$path_parts['extension']
331                         : '';   // some lack extension
332         $img_root   = basename($path_parts['basename'], '_normal'.$ext);        // cut off extension
333         $newname = "Twitter_{$twuser->id}_{$img_root}_{$this->avatarsizename}{$ext}";
334
335         try {
336             $avatar = Avatar::getUploaded($profile);
337             $oldname = $avatar->filename;
338             $avatar->free();
339         } catch (Exception $e) {
340             $oldname = null;
341         }
342         
343         if ($newname != $oldname || !Avatar::hasUploaded($profile)) {
344             common_debug(__METHOD__ . " - Avatar for {$profile->nickname} has changed.");
345             $this->updateAvatar($twuser, $profile);
346         }
347     }
348
349     protected function updateAvatar($twuser, Profile $profile)
350     {
351         $path_parts = pathinfo($twuser->profile_image_url);
352         $ext        = isset($path_parts['extension'])
353                         ? '.'.$path_parts['extension']
354                         : '';   // some lack extension
355         $img_root   = basename($path_parts['basename'], '_normal'.$ext);        // cut off extension
356         $url        = "{$path_parts['dirname']}/{$img_root}_{$this->avatarsizename}{$ext}";
357         $filename   = "Twitter_{$twuser->id}_{$img_root}_{$this->avatarsizename}{$ext}";
358         $mediatype  = $this->getMediatype(substr($ext, 1));
359
360         try {
361             $this->newAvatar($profile, $url, $filename, $mediatype);
362         } catch (Exception $e) {
363             if (file_exists(Avatar::path($filename))) {
364                 unlink(Avatar::path($filename));
365             }
366         }
367     }
368
369     protected function getMediatype($ext)
370     {
371         $mediatype = null;
372
373         switch (strtolower($ext)) {
374         case 'jpeg':
375         case 'jpg':
376             $mediatype = 'image/jpeg';
377             break;
378         case 'gif':
379             $mediatype = 'image/gif';
380             break;
381         default:
382             $mediatype = 'image/png';
383         }
384
385         return $mediatype;
386     }
387
388     protected function newAvatar(Profile $profile, $url, $filename, $mediatype)
389     {
390         // Clear out old avatars, won't do anything if there are none
391         Avatar::deleteFromProfile($profile);
392
393         // throws exception if unable to fetch
394         $this->fetchRemoteUrl($url, Avatar::path($filename));
395
396         $avatar = new Avatar();
397         $avatar->profile_id = $profile->id;
398         $avatar->original   = 1; // this is an original/"uploaded" avatar
399         $avatar->mediatype  = $mediatype;
400         $avatar->filename   = $filename;
401         $avatar->url        = Avatar::url($filename);
402         $avatar->width      = $this->avatarsize;
403         $avatar->height     = $this->avatarsize;
404
405         $avatar->created = common_sql_now();
406
407         $id = $avatar->insert();
408
409         if (empty($id)) {
410             common_log(LOG_WARNING, __METHOD__ . " Couldn't insert avatar - " . $e->getMessage());
411             common_log_db_error($avatar, 'INSERT', __FILE__);
412             throw new ServerException('Could not insert avatar');
413         }
414
415         common_debug(__METHOD__ . " - Saved new avatar for {$profile->id}.");
416
417         return $avatar;
418     }
419
420     /**
421      * Fetch a remote avatar image and save to local storage.
422      *
423      * @param string $url avatar source URL
424      * @param string $filename bare local filename for download
425      * @return bool true on success, false on failure
426      */
427     protected function fetchRemoteUrl($url, $filename)
428     {
429         common_debug(__METHOD__ . " - Fetching Twitter avatar: {$url} to {$filename}");
430         $request = HTTPClient::start();
431         $request->setConfig('connect_timeout', 3);  // I had problems with throttling
432         $request->setConfig('timeout', 6);          // and locking the process sucks.
433         $response = $request->get($url);
434         if ($response->isOk()) {
435             if (!file_put_contents($filename, $response->getBody())) {
436                 throw new ServerException('Failed saving fetched file');
437             }
438         } else {
439             throw new Exception('Unexpected HTTP status code');
440         }
441         return true;
442     }
443
444     const URL = 1;
445     const HASHTAG = 2;
446     const MENTION = 3;
447
448     function linkify($status, $html = FALSE)
449     {
450         $text = $status->text;
451
452         if (empty($status->entities)) {
453             $statusId = twitter_id($status);
454             common_log(LOG_WARNING, "No entities data for {$statusId}; trying to fake up links ourselves.");
455             $text = common_replace_urls_callback($text, 'common_linkify');
456             $text = preg_replace('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.TwitterStatusFetcher::tagLink('\\2')", $text);
457             $text = preg_replace('/(^|\s+)@([a-z0-9A-Z_]{1,64})/e', "'\\1@'.TwitterStatusFetcher::atLink('\\2')", $text);
458             return $text;
459         }
460
461         // Move all the entities into order so we can
462         // replace them and escape surrounding plaintext
463         // in order
464
465         $toReplace = array();
466
467         if (!empty($status->entities->urls)) {
468             foreach ($status->entities->urls as $url) {
469                 $toReplace[$url->indices[0]] = array(self::URL, $url);
470             }
471         }
472
473         if (!empty($status->entities->hashtags)) {
474             foreach ($status->entities->hashtags as $hashtag) {
475                 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
476             }
477         }
478
479         if (!empty($status->entities->user_mentions)) {
480             foreach ($status->entities->user_mentions as $mention) {
481                 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
482             }
483         }
484
485         // sort in forward order by key
486
487         ksort($toReplace);
488
489         $result = '';
490         $cursor = 0;
491
492         foreach ($toReplace as $part) {
493             list($type, $object) = $part;
494             $start = $object->indices[0];
495             $end = $object->indices[1];
496             if ($cursor < $start) {
497                 // Copy in the preceding plaintext
498                 $result .= $this->twitEscape(mb_substr($text, $cursor, $start - $cursor));
499                 $cursor = $start;
500             }
501             $orig = $this->twitEscape(mb_substr($text, $start, $end - $start));
502             switch($type) {
503             case self::URL:
504                 $linkText = $this->makeUrlLink($object, $orig, $html);
505                 break;
506             case self::HASHTAG:
507                 if ($html) {
508                     $linkText = $this->makeHashtagLink($object, $orig);
509                 }else{
510                     $linkText = $orig;
511                 }
512                 break;
513             case self::MENTION:
514                 if ($html) {
515                     $linkText = $this->makeMentionLink($object, $orig);
516                 }else{
517                     $linkText = $orig;
518                 }
519                 break;
520             default:
521                 $linkText = $orig;
522                 continue;
523             }
524             $result .= $linkText;
525             $cursor = $end;
526         }
527         $last = $this->twitEscape(mb_substr($text, $cursor));
528         $result .= $last;
529
530         return $result;
531     }
532
533     function twitEscape($str)
534     {
535         // Twitter seems to preemptive turn < and > into &lt; and &gt;
536         // but doesn't for &, so while you may have some magic protection
537         // against XSS by not bothing to escape manually, you still get
538         // invalid XHTML. Thanks!
539         //
540         // Looks like their web interface pretty much sends anything
541         // through intact, so.... to do equivalent, decode all entities
542         // and then re-encode the special ones.
543         return htmlspecialchars(html_entity_decode($str, ENT_COMPAT, 'UTF-8'));
544     }
545
546     function makeUrlLink($object, $orig, $html)
547     {
548         if ($html) {
549             return '<a href="'.htmlspecialchars($object->expanded_url).'" class="extlink">'.htmlspecialchars($object->display_url).'</a>';
550         }else{
551             return htmlspecialchars($object->expanded_url);
552         }
553     }
554
555     function makeHashtagLink($object, $orig)
556     {
557         return "#" . self::tagLink($object->text, substr($orig, 1));
558     }
559
560     function makeMentionLink($object, $orig)
561     {
562         return "@".self::atLink($object->screen_name, $object->name, substr($orig, 1));
563     }
564
565     static function tagLink($tag, $orig)
566     {
567         return "<a href='https://search.twitter.com/search?q=%23{$tag}' class='hashtag'>{$orig}</a>";
568     }
569
570     static function atLink($screenName, $fullName, $orig)
571     {
572         if (!empty($fullName)) {
573             return "<a href='http://twitter.com/#!/{$screenName}' title='{$fullName}'>{$orig}</a>";
574         } else {
575             return "<a href='http://twitter.com/#!/{$screenName}'>{$orig}</a>";
576         }
577     }
578
579     function saveStatusMentions($notice, $status)
580     {
581         $mentions = array();
582
583         if (empty($status->entities) || empty($status->entities->user_mentions)) {
584             return;
585         }
586
587         foreach ($status->entities->user_mentions as $mention) {
588             $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
589             if (!empty($flink)) {
590                 $user = User::getKV('id', $flink->user_id);
591                 if (!empty($user)) {
592                     $reply = new Reply();
593                     $reply->notice_id  = $notice->id;
594                     $reply->profile_id = $user->id;
595                     $reply->modified   = $notice->created;
596                     common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
597                     $id = $reply->insert();
598                 }
599             }
600         }
601     }
602
603     /**
604      * Record URL links from the notice. Needed to get thumbnail records
605      * for referenced photo and video posts, etc.
606      *
607      * @param Notice $notice
608      * @param object $status
609      */
610     function saveStatusAttachments($notice, $status)
611     {
612         if (common_config('attachments', 'process_links')) {
613             if (!empty($status->entities) && !empty($status->entities->urls)) {
614                 foreach ($status->entities->urls as $url) {
615                     File::processNew($url->url, $notice->id);
616                 }
617             }
618         }
619     }
620 }