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