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