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