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