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