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