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