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