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