]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - scripts/twitterstatusfetcher.php
Better (hopefully) database connection management for child processes
[quix0rs-gnu-social.git] / scripts / 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
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  Laconica
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 Daemon
60 {
61     private $_children = array();
62
63     function __construct($id=null, $daemonize=true)
64     {
65         parent::__construct($daemonize);
66
67         if ($id) {
68             $this->set_id($id);
69         }
70     }
71
72     /**
73      * Name of this daemon
74      *
75      * @return string Name of the daemon.
76      */
77
78     function name()
79     {
80         return ('twitterstatusfetcher.'.$this->_id);
81     }
82
83     /**
84      * Run the daemon
85      *
86      * @return void
87      */
88
89     function run()
90     {
91         if (defined('SCRIPT_DEBUG')) {
92             common_debug($this->name() .
93                 ': debugging log output enabled.');
94         }
95
96         do {
97
98             $flinks = $this->refreshFlinks();
99
100             foreach ($flinks as $f) {
101
102                 $pid = pcntl_fork();
103
104                 if ($pid == -1) {
105                     die ("Couldn't fork!");
106                 }
107
108                 if ($pid) {
109
110                     // Parent
111                     if (defined('SCRIPT_DEBUG')) {
112                         common_debug("Parent: forked new status ".
113                                      " fetcher process " . $pid);
114                     }
115
116                     $this->_children[] = $pid;
117
118                 } else {
119
120                     // Child
121
122                     // Each child ps needs its own DB connection
123
124                     // Note: DataObject::getDatabaseConnection() creates
125                     // a new connection if there isn't one already
126
127                     global $_DB_DATAOBJECT;
128                     $conn = &$f->getDatabaseConnection();
129
130                     $this->getTimeline($f);
131
132                     $conn->disconnect();
133
134                     // XXX: Couldn't find a less brutal way to blow
135                     // away a cached connection
136
137                     unset($_DB_DATAOBJECT['CONNECTIONS']);
138
139                     exit();
140                 }
141
142                 // Remove child from ps list as it finishes
143                 while (($c = pcntl_wait($status, WNOHANG OR WUNTRACED)) > 0) {
144
145                     if (defined('SCRIPT_DEBUG')) {
146                         common_debug("Child $c finished.");
147                     }
148
149                     $this->removePs($this->_children, $c);
150                 }
151
152                 // Wait! We have too many damn kids.
153                 if (sizeof($this->_children) > MAXCHILDREN) {
154
155                     if (defined('SCRIPT_DEBUG')) {
156                         common_debug('Too many children. Waiting...');
157                     }
158
159                     if (($c = pcntl_wait($status, WUNTRACED)) > 0) {
160
161                         if (defined('SCRIPT_DEBUG')) {
162                             common_debug("Finished waiting for $c");
163                         }
164
165                         $this->removePs($this->_children, $c);
166                     }
167                 }
168             }
169
170             // Remove all children from the process list before restarting
171             while (($c = pcntl_wait($status, WUNTRACED)) > 0) {
172
173                 if (defined('SCRIPT_DEBUG')) {
174                     common_debug("Child $c finished.");
175                 }
176
177                 $this->removePs($this->_children, $c);
178             }
179
180             // Rest for a bit before we fetch more statuses
181
182             if (defined('SCRIPT_DEBUG')) {
183                 common_debug('Waiting ' . POLL_INTERVAL .
184                     ' secs before hitting Twitter again.');
185             }
186
187             if (POLL_INTERVAL > 0) {
188                 sleep(POLL_INTERVAL);
189             }
190
191         } while (true);
192     }
193
194     /**
195      * Refresh the foreign links for this user
196      *
197      * @return void
198      */
199
200     function refreshFlinks()
201     {
202         global $_DB_DATAOBJECT;
203
204         $flink = new Foreign_link();
205         $conn = &$flink->getDatabaseConnection();
206
207         $flink->service = TWITTER_SERVICE;
208
209         $flink->orderBy('last_noticesync');
210
211         $cnt = $flink->find();
212
213         if (defined('SCRIPT_DEBUG')) {
214             common_debug('Updating Twitter friends subscriptions' .
215                 " for $cnt users.");
216         }
217
218         $flinks = array();
219
220         while ($flink->fetch()) {
221
222             if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
223                 FOREIGN_NOTICE_RECV) {
224                 $flinks[] = clone($flink);
225             }
226         }
227
228         $flink->free();
229         unset($flink);
230
231         $conn->disconnect();
232         unset($_DB_DATAOBJECT['CONNECTIONS']);
233
234         return $flinks;
235     }
236
237     /**
238      * Unknown
239      *
240      * @param array  &$plist unknown.
241      * @param string $ps     unknown.
242      *
243      * @return unknown
244      * @todo document
245      */
246
247     function removePs(&$plist, $ps)
248     {
249         for ($i = 0; $i < sizeof($plist); $i++) {
250             if ($plist[$i] == $ps) {
251                 unset($plist[$i]);
252                 $plist = array_values($plist);
253                 break;
254             }
255         }
256     }
257
258     function getTimeline($flink)
259     {
260          if (empty($flink)) {
261             common_log(LOG_WARNING,
262                 "Can't retrieve Foreign_link for foreign ID $fid");
263             return;
264         }
265
266         if (defined('SCRIPT_DEBUG')) {
267             common_debug('Trying to get timeline for Twitter user ' .
268                 $flink->foreign_id);
269         }
270
271         // XXX: Biggest remaining issue - How do we know at which status
272         // to start importing?  How many statuses?  Right now I'm going
273         // with the default last 20.
274
275         $client = new TwitterOAuthClient($flink->token, $flink->credentials);
276
277         $timeline = null;
278
279         try {
280             $timeline = $client->statuses_friends_timeline();
281         } catch (OAuthClientCurlException $e) {
282             common_log(LOG_WARNING,
283                        'OAuth client unable to get friends timeline for user ' .
284                        $flink->user_id . ' - code: ' .
285                        $e->getCode() . 'msg: ' . $e->getMessage());
286         }
287
288         if (empty($timeline)) {
289             common_log(LOG_WARNING, "Empty timeline.");
290             return;
291         }
292
293         // Reverse to preserve order
294         foreach (array_reverse($timeline) as $status) {
295
296             // Hacktastic: filter out stuff coming from this Laconica
297             $source = mb_strtolower(common_config('integration', 'source'));
298
299             if (preg_match("/$source/", mb_strtolower($status->source))) {
300                 if (defined('SCRIPT_DEBUG')) {
301                     common_debug('Skipping import of status ' . $status->id .
302                         ' with source ' . $source);
303                 }
304                 continue;
305             }
306
307             $this->saveStatus($status, $flink);
308         }
309
310         // Okay, record the time we synced with Twitter for posterity
311         $flink->last_noticesync = common_sql_now();
312         $flink->update();
313     }
314
315     function saveStatus($status, $flink)
316     {
317         $id = $this->ensureProfile($status->user);
318
319         $profile = Profile::staticGet($id);
320
321         if (empty($profile)) {
322             common_log(LOG_ERR,
323                 'Problem saving notice. No associated Profile.');
324             return null;
325         }
326
327         // XXX: change of screen name?
328
329         $uri = 'http://twitter.com/' . $status->user->screen_name .
330             '/status/' . $status->id;
331
332         $notice = Notice::staticGet('uri', $uri);
333
334         // check to see if we've already imported the status
335
336         if (empty($notice)) {
337
338             $notice = new Notice();
339
340             $notice->profile_id = $id;
341             $notice->uri        = $uri;
342             $notice->created    = strftime('%Y-%m-%d %H:%M:%S',
343                                            strtotime($status->created_at));
344             $notice->content    = common_shorten_links($status->text); // XXX
345             $notice->rendered   = common_render_content($notice->content, $notice);
346             $notice->source     = 'twitter';
347             $notice->reply_to   = null; // XXX lookup reply
348             $notice->is_local   = Notice::GATEWAY;
349
350             if (Event::handle('StartNoticeSave', array(&$notice))) {
351                 $id = $notice->insert();
352                 Event::handle('EndNoticeSave', array($notice));
353             }
354         }
355
356         if (!Notice_inbox::pkeyGet(array('notice_id' => $notice->id,
357                                          'user_id' => $flink->user_id))) {
358             // Add to inbox
359             $inbox = new Notice_inbox();
360
361             $inbox->user_id   = $flink->user_id;
362             $inbox->notice_id = $notice->id;
363             $inbox->created   = $notice->created;
364             $inbox->source    = NOTICE_INBOX_SOURCE_GATEWAY; // From a private source
365
366             $inbox->insert();
367         }
368     }
369
370     function ensureProfile($user)
371     {
372         // check to see if there's already a profile for this user
373         $profileurl = 'http://twitter.com/' . $user->screen_name;
374         $profile = Profile::staticGet('profileurl', $profileurl);
375
376         if (!empty($profile)) {
377             if (defined('SCRIPT_DEBUG')) {
378                 common_debug("Profile for $profile->nickname found.");
379             }
380
381             // Check to see if the user's Avatar has changed
382             $this->checkAvatar($user, $profile);
383
384             return $profile->id;
385
386         } else {
387             if (defined('SCRIPT_DEBUG')) {
388                 common_debug('Adding profile and remote profile ' .
389                     "for Twitter user: $profileurl");
390             }
391
392             $profile = new Profile();
393             $profile->query("BEGIN");
394
395             $profile->nickname = $user->screen_name;
396             $profile->fullname = $user->name;
397             $profile->homepage = $user->url;
398             $profile->bio = $user->description;
399             $profile->location = $user->location;
400             $profile->profileurl = $profileurl;
401             $profile->created = common_sql_now();
402
403             $id = $profile->insert();
404
405             if (empty($id)) {
406                 common_log_db_error($profile, 'INSERT', __FILE__);
407                 $profile->query("ROLLBACK");
408                 return false;
409             }
410
411             // check for remote profile
412             $remote_pro = Remote_profile::staticGet('uri', $profileurl);
413
414             if (!$remote_pro) {
415
416                 $remote_pro = new Remote_profile();
417
418                 $remote_pro->id = $id;
419                 $remote_pro->uri = $profileurl;
420                 $remote_pro->created = common_sql_now();
421
422                 $rid = $remote_pro->insert();
423
424                 if (empty($rid)) {
425                     common_log_db_error($profile, 'INSERT', __FILE__);
426                     $profile->query("ROLLBACK");
427                     return false;
428                 }
429             }
430
431             $profile->query("COMMIT");
432
433             $this->saveAvatars($user, $id);
434
435             return $id;
436         }
437     }
438
439     function checkAvatar($twitter_user, $profile)
440     {
441         global $config;
442
443         $path_parts = pathinfo($twitter_user->profile_image_url);
444
445         $newname = 'Twitter_' . $twitter_user->id . '_' .
446             $path_parts['basename'];
447
448         $oldname = $profile->getAvatar(48)->filename;
449
450         if ($newname != $oldname) {
451
452             if (defined('SCRIPT_DEBUG')) {
453                 common_debug('Avatar for Twitter user ' .
454                     "$profile->nickname has changed.");
455                 common_debug("old: $oldname new: $newname");
456             }
457
458             $this->updateAvatars($twitter_user, $profile);
459         }
460
461         if ($this->missingAvatarFile($profile)) {
462
463             if (defined('SCRIPT_DEBUG')) {
464                 common_debug('Twitter user ' . $profile->nickname .
465                     ' is missing one or more local avatars.');
466                 common_debug("old: $oldname new: $newname");
467             }
468
469             $this->updateAvatars($twitter_user, $profile);
470         }
471
472     }
473
474     function updateAvatars($twitter_user, $profile) {
475
476         global $config;
477
478         $path_parts = pathinfo($twitter_user->profile_image_url);
479
480         $img_root = substr($path_parts['basename'], 0, -11);
481         $ext = $path_parts['extension'];
482         $mediatype = $this->getMediatype($ext);
483
484         foreach (array('mini', 'normal', 'bigger') as $size) {
485             $url = $path_parts['dirname'] . '/' .
486                 $img_root . '_' . $size . ".$ext";
487             $filename = 'Twitter_' . $twitter_user->id . '_' .
488                 $img_root . "_$size.$ext";
489
490             $this->updateAvatar($profile->id, $size, $mediatype, $filename);
491             $this->fetchAvatar($url, $filename);
492         }
493     }
494
495     function missingAvatarFile($profile) {
496
497         foreach (array(24, 48, 73) as $size) {
498
499             $filename = $profile->getAvatar($size)->filename;
500             $avatarpath = Avatar::path($filename);
501
502             if (file_exists($avatarpath) == FALSE) {
503                 return true;
504             }
505         }
506
507         return false;
508     }
509
510     function getMediatype($ext)
511     {
512         $mediatype = null;
513
514         switch (strtolower($ext)) {
515         case 'jpg':
516             $mediatype = 'image/jpg';
517             break;
518         case 'gif':
519             $mediatype = 'image/gif';
520             break;
521         default:
522             $mediatype = 'image/png';
523         }
524
525         return $mediatype;
526     }
527
528     function saveAvatars($user, $id)
529     {
530         global $config;
531
532         $path_parts = pathinfo($user->profile_image_url);
533         $ext = $path_parts['extension'];
534         $end = strlen('_normal' . $ext);
535         $img_root = substr($path_parts['basename'], 0, -($end+1));
536         $mediatype = $this->getMediatype($ext);
537
538         foreach (array('mini', 'normal', 'bigger') as $size) {
539             $url = $path_parts['dirname'] . '/' .
540                 $img_root . '_' . $size . ".$ext";
541             $filename = 'Twitter_' . $user->id . '_' .
542                 $img_root . "_$size.$ext";
543
544             if ($this->fetchAvatar($url, $filename)) {
545                 $this->newAvatar($id, $size, $mediatype, $filename);
546             } else {
547                 common_log(LOG_WARNING, "Problem fetching Avatar: $url", __FILE__);
548             }
549         }
550     }
551
552     function updateAvatar($profile_id, $size, $mediatype, $filename) {
553
554         if (defined('SCRIPT_DEBUG')) {
555             common_debug("Updating avatar: $size");
556         }
557
558         $profile = Profile::staticGet($profile_id);
559
560         if (empty($profile)) {
561             if (defined('SCRIPT_DEBUG')) {
562                 common_debug("Couldn't get profile: $profile_id!");
563             }
564             return;
565         }
566
567         $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
568         $avatar = $profile->getAvatar($sizes[$size]);
569
570         // Delete the avatar, if present
571         if ($avatar) {
572             $avatar->delete();
573         }
574
575         $this->newAvatar($profile->id, $size, $mediatype, $filename);
576     }
577
578     function newAvatar($profile_id, $size, $mediatype, $filename)
579     {
580         global $config;
581
582         $avatar = new Avatar();
583         $avatar->profile_id = $profile_id;
584
585         switch($size) {
586         case 'mini':
587             $avatar->width  = 24;
588             $avatar->height = 24;
589             break;
590         case 'normal':
591             $avatar->width  = 48;
592             $avatar->height = 48;
593             break;
594         default:
595
596             // Note: Twitter's big avatars are a different size than
597             // Laconica's (Laconica's = 96)
598
599             $avatar->width  = 73;
600             $avatar->height = 73;
601         }
602
603         $avatar->original = 0; // we don't have the original
604         $avatar->mediatype = $mediatype;
605         $avatar->filename = $filename;
606         $avatar->url = Avatar::url($filename);
607
608         if (defined('SCRIPT_DEBUG')) {
609             common_debug("new filename: $avatar->url");
610         }
611
612         $avatar->created = common_sql_now();
613
614         $id = $avatar->insert();
615
616         if (empty($id)) {
617             common_log_db_error($avatar, 'INSERT', __FILE__);
618             return null;
619         }
620
621         if (defined('SCRIPT_DEBUG')) {
622             common_debug("Saved new $size avatar for $profile_id.");
623         }
624
625         return $id;
626     }
627
628     function fetchAvatar($url, $filename)
629     {
630         $avatar_dir = INSTALLDIR . '/avatar/';
631
632         $avatarfile = $avatar_dir . $filename;
633
634         $out = fopen($avatarfile, 'wb');
635         if (!$out) {
636             common_log(LOG_WARNING, "Couldn't open file $filename", __FILE__);
637             return false;
638         }
639
640         if (defined('SCRIPT_DEBUG')) {
641             common_debug("Fetching avatar: $url");
642         }
643
644         $ch = curl_init();
645         curl_setopt($ch, CURLOPT_URL, $url);
646         curl_setopt($ch, CURLOPT_FILE, $out);
647         curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
648         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
649         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
650         $result = curl_exec($ch);
651         curl_close($ch);
652
653         fclose($out);
654
655         return $result;
656     }
657 }
658
659 declare(ticks = 1);
660
661 if (have_option('i')) {
662     $id = get_option_value('i');
663 } else if (have_option('--id')) {
664     $id = get_option_value('--id');
665 } else if (count($args) > 0) {
666     $id = $args[0];
667 } else {
668     $id = null;
669 }
670
671 if (have_option('d') || have_option('debug')) {
672     define('SCRIPT_DEBUG', true);
673 }
674
675 $fetcher = new TwitterStatusFetcher($id);
676 $fetcher->runOnce();
677