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