]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/daemons/twitterstatusfetcher.php
cf75e48f68b0a873fa33a90feb5f58ec4d5261ad
[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             $client = new TwitterBasicAuthClient($flink);
183             common_debug($this->name() . ' - Grabbing friends timeline with basic auth.');
184         }
185
186         $timeline = null;
187
188         try {
189             $timeline = $client->statusesFriendsTimeline();
190         } catch (Exception $e) {
191             common_log(LOG_WARNING, $this->name() .
192                        ' - Twitter client unable to get friends timeline for user ' .
193                        $flink->user_id . ' - code: ' .
194                        $e->getCode() . 'msg: ' . $e->getMessage());
195         }
196
197         if (empty($timeline)) {
198             common_log(LOG_WARNING, $this->name() .  " - Empty timeline.");
199             return;
200         }
201
202         common_debug(LOG_INFO, $this->name() . ' - Retrieved ' . sizeof($timeline) . ' statuses from Twitter.');
203
204         // Reverse to preserve order
205
206         foreach (array_reverse($timeline) as $status) {
207
208             // Hacktastic: filter out stuff coming from this StatusNet
209
210             $source = mb_strtolower(common_config('integration', 'source'));
211
212             if (preg_match("/$source/", mb_strtolower($status->source))) {
213                 common_debug($this->name() . ' - Skipping import of status ' .
214                              $status->id . ' with source ' . $source);
215                 continue;
216             }
217
218             // Don't save it if the user is protected
219             // FIXME: save it but treat it as private
220
221             if ($status->user->protected) {
222                 continue;
223             }
224
225             $this->saveStatus($status, $flink);
226         }
227
228         // Okay, record the time we synced with Twitter for posterity
229
230         $flink->last_noticesync = common_sql_now();
231         $flink->update();
232     }
233
234     function saveStatus($status, $flink)
235     {
236         $profile = $this->ensureProfile($status->user);
237
238         if (empty($profile)) {
239             common_log(LOG_ERR, $this->name() .
240                 ' - Problem saving notice. No associated Profile.');
241             return;
242         }
243
244         $statusUri = $this->makeStatusURI($status->user->screen_name, $status->id);
245
246         // check to see if we've already imported the status
247
248         $dupe = $this->checkDupe($profile, $statusUri);
249
250         if (!empty($dupe)) {
251             common_log(
252                 LOG_INFO,
253                 $this->name() .
254                 " - Ignoring duplicate import: $statusUri"
255             );
256             return;
257         }
258
259         $notice = new Notice();
260
261         $notice->profile_id = $profile->id;
262         $notice->uri        = $statusUri;
263         $notice->url        = $statusUri;
264         $notice->created    = strftime(
265             '%Y-%m-%d %H:%M:%S',
266             strtotime($status->created_at)
267         );
268
269         $notice->source     = 'twitter';
270
271         $notice->reply_to   = null;
272
273         if (!empty($status->in_reply_to_status_id)) {
274             $replyUri = $this->makeStatusURI($status->in_reply_to_screen_name, $status->in_reply_to_status_id);
275             $reply = Notice::staticGet('uri', $replyUri);
276             if (!empty($reply)) {
277                 $notice->reply_to     = $reply->id;
278                 $notice->conversation = $reply->conversation;
279             }
280         }
281
282         if (empty($notice->conversation)) {
283             $conv = Conversation::create();
284             $notice->conversation = $conv->id;
285         }
286
287         $notice->is_local   = Notice::GATEWAY;
288
289         $notice->content    = common_shorten_links($status->text);
290         $notice->rendered   = common_render_content(
291             $notice->content,
292             $notice
293         );
294
295         if (Event::handle('StartNoticeSave', array(&$notice))) {
296
297             $id = $notice->insert();
298
299             if (!$id) {
300                 common_log_db_error($notice, 'INSERT', __FILE__);
301                 common_log(LOG_ERR, $this->name() .
302                     ' - Problem saving notice.');
303             }
304
305             Event::handle('EndNoticeSave', array($notice));
306         }
307
308         Inbox::insertNotice($flink->user_id, $notice->id);
309         $notice->blowOnInsert();
310
311         return $notice;
312     }
313
314     /**
315      * Make an URI for a status.
316      *
317      * @param object $status status object
318      *
319      * @return string URI
320      */
321
322     function makeStatusURI($username, $id)
323     {
324         return 'http://twitter.com/'
325           . $username
326           . '/status/'
327           . $id;
328     }
329
330     /**
331      * Look up a Profile by profileurl field.  Profile::staticGet() was
332      * not working consistently.
333      *
334      * @param string $nickname   local nickname of the Twitter user
335      * @param string $profileurl the profile url
336      *
337      * @return mixed value the first Profile with that url, or null
338      */
339
340     function getProfileByUrl($nickname, $profileurl)
341     {
342         $profile = new Profile();
343         $profile->nickname = $nickname;
344         $profile->profileurl = $profileurl;
345         $profile->limit(1);
346
347         if ($profile->find()) {
348             $profile->fetch();
349             return $profile;
350         }
351
352         return null;
353     }
354
355     /**
356      * Check to see if this Twitter status has already been imported
357      *
358      * @param Profile $profile   Twitter user's local profile
359      * @param string  $statusUri URI of the status on Twitter
360      *
361      * @return mixed value a matching Notice or null
362      */
363
364     function checkDupe($profile, $statusUri)
365     {
366         $notice = new Notice();
367         $notice->uri = $statusUri;
368         $notice->profile_id = $profile->id;
369         $notice->limit(1);
370
371         if ($notice->find()) {
372             $notice->fetch();
373             return $notice;
374         }
375
376         return null;
377     }
378
379     function ensureProfile($user)
380     {
381         // check to see if there's already a profile for this user
382
383         $profileurl = 'http://twitter.com/' . $user->screen_name;
384         $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
385
386         if (!empty($profile)) {
387             common_debug($this->name() .
388                          " - Profile for $profile->nickname found.");
389
390             // Check to see if the user's Avatar has changed
391
392             $this->checkAvatar($user, $profile);
393             return $profile;
394
395         } else {
396
397             common_debug($this->name() . ' - Adding profile and remote profile ' .
398                          "for Twitter user: $profileurl.");
399
400             $profile = new Profile();
401             $profile->query("BEGIN");
402
403             $profile->nickname = $user->screen_name;
404             $profile->fullname = $user->name;
405             $profile->homepage = $user->url;
406             $profile->bio = $user->description;
407             $profile->location = $user->location;
408             $profile->profileurl = $profileurl;
409             $profile->created = common_sql_now();
410
411             try {
412                 $id = $profile->insert();
413             } catch(Exception $e) {
414                 common_log(LOG_WARNING, $this->name . ' Couldn\'t insert profile - ' . $e->getMessage());
415             }
416
417             if (empty($id)) {
418                 common_log_db_error($profile, 'INSERT', __FILE__);
419                 $profile->query("ROLLBACK");
420                 return false;
421             }
422
423             // check for remote profile
424
425             $remote_pro = Remote_profile::staticGet('uri', $profileurl);
426
427             if (empty($remote_pro)) {
428
429                 $remote_pro = new Remote_profile();
430
431                 $remote_pro->id = $id;
432                 $remote_pro->uri = $profileurl;
433                 $remote_pro->created = common_sql_now();
434
435                 try {
436                     $rid = $remote_pro->insert();
437                 } catch (Exception $e) {
438                     common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
439                 }
440
441                 if (empty($rid)) {
442                     common_log_db_error($profile, 'INSERT', __FILE__);
443                     $profile->query("ROLLBACK");
444                     return false;
445                 }
446             }
447
448             $profile->query("COMMIT");
449
450             $this->saveAvatars($user, $id);
451
452             return $profile;
453         }
454     }
455
456     function checkAvatar($twitter_user, $profile)
457     {
458         global $config;
459
460         $path_parts = pathinfo($twitter_user->profile_image_url);
461
462         $newname = 'Twitter_' . $twitter_user->id . '_' .
463             $path_parts['basename'];
464
465         $oldname = $profile->getAvatar(48)->filename;
466
467         if ($newname != $oldname) {
468             common_debug($this->name() . ' - Avatar for Twitter user ' .
469                          "$profile->nickname has changed.");
470             common_debug($this->name() . " - old: $oldname new: $newname");
471
472             $this->updateAvatars($twitter_user, $profile);
473         }
474
475         if ($this->missingAvatarFile($profile)) {
476             common_debug($this->name() . ' - Twitter user ' .
477                          $profile->nickname .
478                          ' is missing one or more local avatars.');
479             common_debug($this->name() ." - old: $oldname new: $newname");
480
481             $this->updateAvatars($twitter_user, $profile);
482         }
483     }
484
485     function updateAvatars($twitter_user, $profile) {
486
487         global $config;
488
489         $path_parts = pathinfo($twitter_user->profile_image_url);
490
491         $img_root = substr($path_parts['basename'], 0, -11);
492         $ext = $path_parts['extension'];
493         $mediatype = $this->getMediatype($ext);
494
495         foreach (array('mini', 'normal', 'bigger') as $size) {
496             $url = $path_parts['dirname'] . '/' .
497                 $img_root . '_' . $size . ".$ext";
498             $filename = 'Twitter_' . $twitter_user->id . '_' .
499                 $img_root . "_$size.$ext";
500
501             $this->updateAvatar($profile->id, $size, $mediatype, $filename);
502             $this->fetchAvatar($url, $filename);
503         }
504     }
505
506     function missingAvatarFile($profile) {
507         foreach (array(24, 48, 73) as $size) {
508             $filename = $profile->getAvatar($size)->filename;
509             $avatarpath = Avatar::path($filename);
510             if (file_exists($avatarpath) == FALSE) {
511                 return true;
512             }
513         }
514         return false;
515     }
516
517     function getMediatype($ext)
518     {
519         $mediatype = null;
520
521         switch (strtolower($ext)) {
522         case 'jpg':
523             $mediatype = 'image/jpg';
524             break;
525         case 'gif':
526             $mediatype = 'image/gif';
527             break;
528         default:
529             $mediatype = 'image/png';
530         }
531
532         return $mediatype;
533     }
534
535     function saveAvatars($user, $id)
536     {
537         global $config;
538
539         $path_parts = pathinfo($user->profile_image_url);
540         $ext = $path_parts['extension'];
541         $end = strlen('_normal' . $ext);
542         $img_root = substr($path_parts['basename'], 0, -($end+1));
543         $mediatype = $this->getMediatype($ext);
544
545         foreach (array('mini', 'normal', 'bigger') as $size) {
546             $url = $path_parts['dirname'] . '/' .
547                 $img_root . '_' . $size . ".$ext";
548             $filename = 'Twitter_' . $user->id . '_' .
549                 $img_root . "_$size.$ext";
550
551             if ($this->fetchAvatar($url, $filename)) {
552                 $this->newAvatar($id, $size, $mediatype, $filename);
553             } else {
554                 common_log(LOG_WARNING, $id() .
555                            " - Problem fetching Avatar: $url");
556             }
557         }
558     }
559
560     function updateAvatar($profile_id, $size, $mediatype, $filename) {
561
562         common_debug($this->name() . " - Updating avatar: $size");
563
564         $profile = Profile::staticGet($profile_id);
565
566         if (empty($profile)) {
567             common_debug($this->name() . " - Couldn't get profile: $profile_id!");
568             return;
569         }
570
571         $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
572         $avatar = $profile->getAvatar($sizes[$size]);
573
574         // Delete the avatar, if present
575
576         if ($avatar) {
577             $avatar->delete();
578         }
579
580         $this->newAvatar($profile->id, $size, $mediatype, $filename);
581     }
582
583     function newAvatar($profile_id, $size, $mediatype, $filename)
584     {
585         global $config;
586
587         $avatar = new Avatar();
588         $avatar->profile_id = $profile_id;
589
590         switch($size) {
591         case 'mini':
592             $avatar->width  = 24;
593             $avatar->height = 24;
594             break;
595         case 'normal':
596             $avatar->width  = 48;
597             $avatar->height = 48;
598             break;
599         default:
600
601             // Note: Twitter's big avatars are a different size than
602             // StatusNet's (StatusNet's = 96)
603
604             $avatar->width  = 73;
605             $avatar->height = 73;
606         }
607
608         $avatar->original = 0; // we don't have the original
609         $avatar->mediatype = $mediatype;
610         $avatar->filename = $filename;
611         $avatar->url = Avatar::url($filename);
612
613         $avatar->created = common_sql_now();
614
615         try {
616             $id = $avatar->insert();
617         } catch (Exception $e) {
618             common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
619         }
620
621         if (empty($id)) {
622             common_log_db_error($avatar, 'INSERT', __FILE__);
623             return null;
624         }
625
626         common_debug($this->name() .
627                      " - Saved new $size avatar for $profile_id.");
628
629         return $id;
630     }
631
632     /**
633      * Fetch a remote avatar image and save to local storage.
634      *
635      * @param string $url avatar source URL
636      * @param string $filename bare local filename for download
637      * @return bool true on success, false on failure
638      */
639     function fetchAvatar($url, $filename)
640     {
641         common_debug($this->name() . " - Fetching Twitter avatar: $url");
642
643         $request = HTTPClient::start();
644         $response = $request->get($url);
645         if ($response->isOk()) {
646             $avatarfile = Avatar::path($filename);
647             $ok = file_put_contents($avatarfile, $response->getBody());
648             if (!$ok) {
649                 common_log(LOG_WARNING, $this->name() .
650                            " - Couldn't open file $filename");
651                 return false;
652             }
653         } else {
654             return false;
655         }
656
657         return true;
658     }
659 }
660
661 $id    = null;
662 $debug = null;
663
664 if (have_option('i')) {
665     $id = get_option_value('i');
666 } else if (have_option('--id')) {
667     $id = get_option_value('--id');
668 } else if (count($args) > 0) {
669     $id = $args[0];
670 } else {
671     $id = null;
672 }
673
674 if (have_option('d') || have_option('debug')) {
675     $debug = true;
676 }
677
678 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);
679 $fetcher->runOnce();
680