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