]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/daemons/twitterstatusfetcher.php
06c59959a796eb7f6b22757b543d166789d5de54
[quix0rs-gnu-social.git] / plugins / TwitterBridge / daemons / twitterstatusfetcher.php
1 #!/usr/bin/env php
2 <?php
3 /**
4  * StatusNet - the distributed open-source microblogging tool
5  * Copyright (C) 2008-2010, StatusNet, Inc.
6  *
7  * 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
21 define('INSTALLDIR', realpath(dirname(__FILE__) . '/../../..'));
22
23 // Tune number of processes and how often to poll Twitter
24 // XXX: Should these things be in config.php?
25 define('MAXCHILDREN', 2);
26 define('POLL_INTERVAL', 60); // in seconds
27
28 $shortoptions = 'di::';
29 $longoptions = array('id::', 'debug');
30
31 $helptext = <<<END_OF_TRIM_HELP
32 Batch script for retrieving Twitter messages from foreign service.
33
34   -i --id              Identity (default 'generic')
35   -d --debug           Debug (lots of log output)
36
37 END_OF_TRIM_HELP;
38
39 require_once INSTALLDIR . '/scripts/commandline.inc';
40 require_once INSTALLDIR . '/lib/common.php';
41 require_once INSTALLDIR . '/lib/daemon.php';
42 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
43 require_once INSTALLDIR . '/plugins/TwitterBridge/twitteroauthclient.php';
44
45 /**
46  * Fetch statuses from Twitter
47  *
48  * Fetches statuses from Twitter and inserts them as notices
49  *
50  * NOTE: an Avatar path MUST be set in config.php for this
51  * script to work, e.g.:
52  *     $config['avatar']['path'] = $config['site']['path'] . '/avatar/';
53  *
54  * @todo @fixme @gar Fix the above. For some reason $_path is always empty when
55  * this script is run, so the default avatar path is always set wrong in
56  * default.php. Therefore it must be set explicitly in config.php. --Z
57  *
58  * @category Twitter
59  * @package  StatusNet
60  * @author   Zach Copley <zach@status.net>
61  * @author   Evan Prodromou <evan@status.net>
62  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
63  * @link     http://status.net/
64  */
65
66 class TwitterStatusFetcher extends ParallelizingDaemon
67 {
68     /**
69      *  Constructor
70      *
71      * @param string  $id           the name/id of this daemon
72      * @param int     $interval     sleep this long before doing everything again
73      * @param int     $max_children maximum number of child processes at a time
74      * @param boolean $debug        debug output flag
75      *
76      * @return void
77      *
78      **/
79     function __construct($id = null, $interval = 60,
80                          $max_children = 2, $debug = null)
81     {
82         parent::__construct($id, $interval, $max_children, $debug);
83     }
84
85     /**
86      * Name of this daemon
87      *
88      * @return string Name of the daemon.
89      */
90
91     function name()
92     {
93         return ('twitterstatusfetcher.'.$this->_id);
94     }
95
96     /**
97      * Find all the Twitter foreign links for users who have requested
98      * importing of their friends' timelines
99      *
100      * @return array flinks an array of Foreign_link objects
101      */
102
103     function getObjects()
104     {
105         global $_DB_DATAOBJECT;
106
107         $flink = new Foreign_link();
108         $conn = &$flink->getDatabaseConnection();
109
110         $flink->service = TWITTER_SERVICE;
111         $flink->orderBy('last_noticesync');
112         $flink->find();
113
114         $flinks = array();
115
116         while ($flink->fetch()) {
117
118             if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
119                 FOREIGN_NOTICE_RECV) {
120                 $flinks[] = clone($flink);
121                 common_log(LOG_INFO, "sync: foreign id $flink->foreign_id");
122             } else {
123                 common_log(LOG_INFO, "nothing to sync");
124             }
125         }
126
127         $flink->free();
128         unset($flink);
129
130         $conn->disconnect();
131         unset($_DB_DATAOBJECT['CONNECTIONS']);
132
133         return $flinks;
134     }
135
136     function childTask($flink) {
137
138         // Each child ps needs its own DB connection
139
140         // Note: DataObject::getDatabaseConnection() creates
141         // a new connection if there isn't one already
142
143         $conn = &$flink->getDatabaseConnection();
144
145         $this->getTimeline($flink);
146
147         $flink->last_friendsync = common_sql_now();
148         $flink->update();
149
150         $conn->disconnect();
151
152         // XXX: Couldn't find a less brutal way to blow
153         // away a cached connection
154
155         global $_DB_DATAOBJECT;
156         unset($_DB_DATAOBJECT['CONNECTIONS']);
157     }
158
159     function getTimeline($flink)
160     {
161         if (empty($flink)) {
162             common_log(LOG_WARNING, $this->name() .
163                        " - Can't retrieve Foreign_link for foreign ID $fid");
164             return;
165         }
166
167         common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
168                      $flink->foreign_id);
169
170         // XXX: Biggest remaining issue - How do we know at which status
171         // to start importing?  How many statuses?  Right now I'm going
172         // with the default last 20.
173
174         $client = null;
175
176         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
177             $token = TwitterOAuthClient::unpackToken($flink->credentials);
178             $client = new TwitterOAuthClient($token->key, $token->secret);
179             common_debug($this->name() . ' - Grabbing friends timeline with OAuth.');
180         } else {
181             common_debug("Skipping friends timeline for $flink->foreign_id since not OAuth.");
182         }
183
184         $timeline = null;
185
186         try {
187             $timeline = $client->statusesHomeTimeline();
188         } catch (Exception $e) {
189             common_log(LOG_WARNING, $this->name() .
190                        ' - Twitter client unable to get friends timeline for user ' .
191                        $flink->user_id . ' - code: ' .
192                        $e->getCode() . 'msg: ' . $e->getMessage());
193         }
194
195         if (empty($timeline)) {
196             common_log(LOG_WARNING, $this->name() .  " - Empty timeline.");
197             return;
198         }
199
200         common_debug(LOG_INFO, $this->name() . ' - Retrieved ' . sizeof($timeline) . ' statuses from Twitter.');
201
202         // Reverse to preserve order
203
204         foreach (array_reverse($timeline) as $status) {
205
206             // Hacktastic: filter out stuff coming from this StatusNet
207
208             $source = mb_strtolower(common_config('integration', 'source'));
209
210             if (preg_match("/$source/", mb_strtolower($status->source))) {
211                 common_debug($this->name() . ' - Skipping import of status ' .
212                              $status->id . ' with source ' . $source);
213                 continue;
214             }
215
216             // Don't save it if the user is protected
217             // FIXME: save it but treat it as private
218
219             if ($status->user->protected) {
220                 continue;
221             }
222
223             $notice = $this->saveStatus($status);
224
225             if (!empty($notice)) {
226                 Inbox::insertNotice($flink->user_id, $notice->id);
227             }
228         }
229
230         // Okay, record the time we synced with Twitter for posterity
231
232         $flink->last_noticesync = common_sql_now();
233         $flink->update();
234     }
235
236     function saveStatus($status)
237     {
238         $profile = $this->ensureProfile($status->user);
239
240         if (empty($profile)) {
241             common_log(LOG_ERR, $this->name() .
242                 ' - Problem saving notice. No associated Profile.');
243             return null;
244         }
245
246         $statusUri = $this->makeStatusURI($status->user->screen_name, $status->id);
247
248         // check to see if we've already imported the status
249
250         $n2s = Notice_to_status::staticGet('status_id', $status->id);
251
252         if (!empty($n2s)) {
253             common_log(
254                 LOG_INFO,
255                 $this->name() .
256                 " - Ignoring duplicate import: {$status->id}"
257             );
258             return Notice::staticGet('id', $n2s->notice_id);
259         }
260
261         common_debug("Saving status {$status->id} with data " . print_r($status, true));
262
263         // If it's a retweet, save it as a repeat!
264
265         if (!empty($status->retweeted_status)) {
266             common_log(LOG_INFO, "Status {$status->id} is a retweet of {$status->retweeted_status->id}.");
267             $original = $this->saveStatus($status->retweeted_status);
268             if (empty($original)) {
269                 return null;
270             } else {
271                 $author = $original->getProfile();
272                 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
273                 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
274                 $content = sprintf(_('RT @%1$s %2$s'),
275                                    $author->nickname,
276                                    $original->content);
277                 $repeat = Notice::saveNew($profile->id,
278                                           $content,
279                                           'twitter',
280                                           array('repeat_of' => $original->id,
281                                                 'uri' => $statusUri));
282                 common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
283                 Notice_to_status::saveNew($repeat->id, $status->id);
284                 return $repeat;
285             }
286         }
287
288         $notice = new Notice();
289
290         $notice->profile_id = $profile->id;
291         $notice->uri        = $statusUri;
292         $notice->url        = $statusUri;
293         $notice->created    = strftime(
294             '%Y-%m-%d %H:%M:%S',
295             strtotime($status->created_at)
296         );
297
298         $notice->source     = 'twitter';
299
300         $notice->reply_to   = null;
301
302         if (!empty($status->in_reply_to_status_id)) {
303             common_log(LOG_INFO, "Status {$status->id} is a reply to status {$status->in_reply_to_status_id}");
304             $n2s = Notice_to_status::staticGet('status_id', $status->in_reply_to_status_id);
305             if (empty($n2s)) {
306                 common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
307             } else {
308                 $reply = Notice::staticGet('id', $n2s->notice_id);
309                 if (empty($reply)) {
310                     common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
311                 } else {
312                     common_log(LOG_INFO, "Found local notice {$reply->id} for status {$status->in_reply_to_status_id}");
313                     $notice->reply_to     = $reply->id;
314                     $notice->conversation = $reply->conversation;
315                 }
316             }
317         }
318
319         if (empty($notice->conversation)) {
320             $conv = Conversation::create();
321             $notice->conversation = $conv->id;
322             common_log(LOG_INFO, "No known conversation for status {$status->id} so making a new one {$conv->id}.");
323         }
324
325         $notice->is_local   = Notice::GATEWAY;
326
327         $notice->content    = common_shorten_links($status->text);
328         $notice->rendered   = common_render_content(
329             $notice->content,
330             $notice
331         );
332
333         if (Event::handle('StartNoticeSave', array(&$notice))) {
334
335             $id = $notice->insert();
336
337             if (!$id) {
338                 common_log_db_error($notice, 'INSERT', __FILE__);
339                 common_log(LOG_ERR, $this->name() .
340                     ' - Problem saving notice.');
341             }
342
343             Event::handle('EndNoticeSave', array($notice));
344         }
345
346         Notice_to_status::saveNew($notice->id, $status->id);
347         $notice->blowOnInsert();
348
349         return $notice;
350     }
351
352     /**
353      * Make an URI for a status.
354      *
355      * @param object $status status object
356      *
357      * @return string URI
358      */
359
360     function makeStatusURI($username, $id)
361     {
362         return 'http://twitter.com/'
363           . $username
364           . '/status/'
365           . $id;
366     }
367
368     /**
369      * Look up a Profile by profileurl field.  Profile::staticGet() was
370      * not working consistently.
371      *
372      * @param string $nickname   local nickname of the Twitter user
373      * @param string $profileurl the profile url
374      *
375      * @return mixed value the first Profile with that url, or null
376      */
377
378     function getProfileByUrl($nickname, $profileurl)
379     {
380         $profile = new Profile();
381         $profile->nickname = $nickname;
382         $profile->profileurl = $profileurl;
383         $profile->limit(1);
384
385         if ($profile->find()) {
386             $profile->fetch();
387             return $profile;
388         }
389
390         return null;
391     }
392
393     /**
394      * Check to see if this Twitter status has already been imported
395      *
396      * @param Profile $profile   Twitter user's local profile
397      * @param string  $statusUri URI of the status on Twitter
398      *
399      * @return mixed value a matching Notice or null
400      */
401
402     function checkDupe($profile, $statusUri)
403     {
404         $notice = new Notice();
405         $notice->uri = $statusUri;
406         $notice->profile_id = $profile->id;
407         $notice->limit(1);
408
409         if ($notice->find()) {
410             $notice->fetch();
411             return $notice;
412         }
413
414         return null;
415     }
416
417     function ensureProfile($user)
418     {
419         // check to see if there's already a profile for this user
420
421         $profileurl = 'http://twitter.com/' . $user->screen_name;
422         $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
423
424         if (!empty($profile)) {
425             common_debug($this->name() .
426                          " - Profile for $profile->nickname found.");
427
428             // Check to see if the user's Avatar has changed
429
430             $this->checkAvatar($user, $profile);
431             return $profile;
432
433         } else {
434
435             common_debug($this->name() . ' - Adding profile and remote profile ' .
436                          "for Twitter user: $profileurl.");
437
438             $profile = new Profile();
439             $profile->query("BEGIN");
440
441             $profile->nickname = $user->screen_name;
442             $profile->fullname = $user->name;
443             $profile->homepage = $user->url;
444             $profile->bio = $user->description;
445             $profile->location = $user->location;
446             $profile->profileurl = $profileurl;
447             $profile->created = common_sql_now();
448
449             try {
450                 $id = $profile->insert();
451             } catch(Exception $e) {
452                 common_log(LOG_WARNING, $this->name . ' Couldn\'t insert profile - ' . $e->getMessage());
453             }
454
455             if (empty($id)) {
456                 common_log_db_error($profile, 'INSERT', __FILE__);
457                 $profile->query("ROLLBACK");
458                 return false;
459             }
460
461             // check for remote profile
462
463             $remote_pro = Remote_profile::staticGet('uri', $profileurl);
464
465             if (empty($remote_pro)) {
466
467                 $remote_pro = new Remote_profile();
468
469                 $remote_pro->id = $id;
470                 $remote_pro->uri = $profileurl;
471                 $remote_pro->created = common_sql_now();
472
473                 try {
474                     $rid = $remote_pro->insert();
475                 } catch (Exception $e) {
476                     common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
477                 }
478
479                 if (empty($rid)) {
480                     common_log_db_error($profile, 'INSERT', __FILE__);
481                     $profile->query("ROLLBACK");
482                     return false;
483                 }
484             }
485
486             $profile->query("COMMIT");
487
488             $this->saveAvatars($user, $id);
489
490             return $profile;
491         }
492     }
493
494     function checkAvatar($twitter_user, $profile)
495     {
496         global $config;
497
498         $path_parts = pathinfo($twitter_user->profile_image_url);
499
500         $newname = 'Twitter_' . $twitter_user->id . '_' .
501             $path_parts['basename'];
502
503         $oldname = $profile->getAvatar(48)->filename;
504
505         if ($newname != $oldname) {
506             common_debug($this->name() . ' - Avatar for Twitter user ' .
507                          "$profile->nickname has changed.");
508             common_debug($this->name() . " - old: $oldname new: $newname");
509
510             $this->updateAvatars($twitter_user, $profile);
511         }
512
513         if ($this->missingAvatarFile($profile)) {
514             common_debug($this->name() . ' - Twitter user ' .
515                          $profile->nickname .
516                          ' is missing one or more local avatars.');
517             common_debug($this->name() ." - old: $oldname new: $newname");
518
519             $this->updateAvatars($twitter_user, $profile);
520         }
521     }
522
523     function updateAvatars($twitter_user, $profile) {
524
525         global $config;
526
527         $path_parts = pathinfo($twitter_user->profile_image_url);
528
529         $img_root = substr($path_parts['basename'], 0, -11);
530         $ext = $path_parts['extension'];
531         $mediatype = $this->getMediatype($ext);
532
533         foreach (array('mini', 'normal', 'bigger') as $size) {
534             $url = $path_parts['dirname'] . '/' .
535                 $img_root . '_' . $size . ".$ext";
536             $filename = 'Twitter_' . $twitter_user->id . '_' .
537                 $img_root . "_$size.$ext";
538
539             $this->updateAvatar($profile->id, $size, $mediatype, $filename);
540             $this->fetchAvatar($url, $filename);
541         }
542     }
543
544     function missingAvatarFile($profile) {
545         foreach (array(24, 48, 73) as $size) {
546             $filename = $profile->getAvatar($size)->filename;
547             $avatarpath = Avatar::path($filename);
548             if (file_exists($avatarpath) == FALSE) {
549                 return true;
550             }
551         }
552         return false;
553     }
554
555     function getMediatype($ext)
556     {
557         $mediatype = null;
558
559         switch (strtolower($ext)) {
560         case 'jpg':
561             $mediatype = 'image/jpg';
562             break;
563         case 'gif':
564             $mediatype = 'image/gif';
565             break;
566         default:
567             $mediatype = 'image/png';
568         }
569
570         return $mediatype;
571     }
572
573     function saveAvatars($user, $id)
574     {
575         global $config;
576
577         $path_parts = pathinfo($user->profile_image_url);
578         $ext = $path_parts['extension'];
579         $end = strlen('_normal' . $ext);
580         $img_root = substr($path_parts['basename'], 0, -($end+1));
581         $mediatype = $this->getMediatype($ext);
582
583         foreach (array('mini', 'normal', 'bigger') as $size) {
584             $url = $path_parts['dirname'] . '/' .
585                 $img_root . '_' . $size . ".$ext";
586             $filename = 'Twitter_' . $user->id . '_' .
587                 $img_root . "_$size.$ext";
588
589             if ($this->fetchAvatar($url, $filename)) {
590                 $this->newAvatar($id, $size, $mediatype, $filename);
591             } else {
592                 common_log(LOG_WARNING, $id() .
593                            " - Problem fetching Avatar: $url");
594             }
595         }
596     }
597
598     function updateAvatar($profile_id, $size, $mediatype, $filename) {
599
600         common_debug($this->name() . " - Updating avatar: $size");
601
602         $profile = Profile::staticGet($profile_id);
603
604         if (empty($profile)) {
605             common_debug($this->name() . " - Couldn't get profile: $profile_id!");
606             return;
607         }
608
609         $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
610         $avatar = $profile->getAvatar($sizes[$size]);
611
612         // Delete the avatar, if present
613
614         if ($avatar) {
615             $avatar->delete();
616         }
617
618         $this->newAvatar($profile->id, $size, $mediatype, $filename);
619     }
620
621     function newAvatar($profile_id, $size, $mediatype, $filename)
622     {
623         global $config;
624
625         $avatar = new Avatar();
626         $avatar->profile_id = $profile_id;
627
628         switch($size) {
629         case 'mini':
630             $avatar->width  = 24;
631             $avatar->height = 24;
632             break;
633         case 'normal':
634             $avatar->width  = 48;
635             $avatar->height = 48;
636             break;
637         default:
638
639             // Note: Twitter's big avatars are a different size than
640             // StatusNet's (StatusNet's = 96)
641
642             $avatar->width  = 73;
643             $avatar->height = 73;
644         }
645
646         $avatar->original = 0; // we don't have the original
647         $avatar->mediatype = $mediatype;
648         $avatar->filename = $filename;
649         $avatar->url = Avatar::url($filename);
650
651         $avatar->created = common_sql_now();
652
653         try {
654             $id = $avatar->insert();
655         } catch (Exception $e) {
656             common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
657         }
658
659         if (empty($id)) {
660             common_log_db_error($avatar, 'INSERT', __FILE__);
661             return null;
662         }
663
664         common_debug($this->name() .
665                      " - Saved new $size avatar for $profile_id.");
666
667         return $id;
668     }
669
670     /**
671      * Fetch a remote avatar image and save to local storage.
672      *
673      * @param string $url avatar source URL
674      * @param string $filename bare local filename for download
675      * @return bool true on success, false on failure
676      */
677     function fetchAvatar($url, $filename)
678     {
679         common_debug($this->name() . " - Fetching Twitter avatar: $url");
680
681         $request = HTTPClient::start();
682         $response = $request->get($url);
683         if ($response->isOk()) {
684             $avatarfile = Avatar::path($filename);
685             $ok = file_put_contents($avatarfile, $response->getBody());
686             if (!$ok) {
687                 common_log(LOG_WARNING, $this->name() .
688                            " - Couldn't open file $filename");
689                 return false;
690             }
691         } else {
692             return false;
693         }
694
695         return true;
696     }
697 }
698
699 $id    = null;
700 $debug = null;
701
702 if (have_option('i')) {
703     $id = get_option_value('i');
704 } else if (have_option('--id')) {
705     $id = get_option_value('--id');
706 } else if (count($args) > 0) {
707     $id = $args[0];
708 } else {
709     $id = null;
710 }
711
712 if (have_option('d') || have_option('debug')) {
713     $debug = true;
714 }
715
716 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);
717 $fetcher->runOnce();
718