]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - scripts/twitterstatusfetcher.php
Better avatar handling - pull in any missing Twitter 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($user, $profile)
355     {
356         global $config;
357
358         $path_parts = pathinfo($user->profile_image_url);
359         $newname = 'Twitter_' . $user->id . '_' .
360             $path_parts['basename'];
361
362         $oldname = $profile->getAvatar(48)->filename;
363
364         if ($newname != $oldname || $this->missingAvatarFile($profile)) {
365
366             if (defined('SCRIPT_DEBUG')) {
367                 common_debug('Avatar for Twitter user ' .
368                     "$profile->nickname has changed, or was missing locally.");
369                 common_debug("old: $oldname new: $newname");
370             }
371
372             $img_root = substr($path_parts['basename'], 0, -11);
373             $ext = $path_parts['extension'];
374             $mediatype = $this->getMediatype($ext);
375
376             foreach (array('mini', 'normal', 'bigger') as $size) {
377                 $url = $path_parts['dirname'] . '/' .
378                     $img_root . '_' . $size . ".$ext";
379                 $filename = 'Twitter_' . $user->id . '_' .
380                     $img_root . "_$size.$ext";
381
382                 if ($this->fetchAvatar($url, $filename)) {
383                     $this->updateAvatar($profile->id, $size, $mediatype, $filename);
384                 }
385             }
386         }
387     }
388
389     function missingAvatarFile($profile) {
390
391         foreach (array(24, 48, 73) as $size) {
392
393             $filename = $profile->getAvatar($size)->filename;
394             $avatarpath = Avatar::path($filename);
395
396             if (file_exists($avatarpath) == FALSE) {
397                 return true;
398             }
399         }
400
401         return false;
402     }
403
404     function getMediatype($ext)
405     {
406         $mediatype = null;
407
408         switch (strtolower($ext)) {
409         case 'jpg':
410             $mediatype = 'image/jpg';
411             break;
412         case 'gif':
413             $mediatype = 'image/gif';
414             break;
415         default:
416             $mediatype = 'image/png';
417         }
418
419         return $mediatype;
420     }
421
422     function saveAvatars($user, $id)
423     {
424         global $config;
425
426         $path_parts = pathinfo($user->profile_image_url);
427         $ext = $path_parts['extension'];
428         $end = strlen('_normal' . $ext);
429         $img_root = substr($path_parts['basename'], 0, -($end+1));
430         $mediatype = $this->getMediatype($ext);
431
432         foreach (array('mini', 'normal', 'bigger') as $size) {
433             $url = $path_parts['dirname'] . '/' .
434                 $img_root . '_' . $size . ".$ext";
435             $filename = 'Twitter_' . $user->id . '_' .
436                 $img_root . "_$size.$ext";
437
438             if ($this->fetchAvatar($url, $filename)) {
439                 $this->newAvatar($id, $size, $mediatype, $filename);
440             } else {
441                 common_log(LOG_WARNING, "Problem fetching Avatar: $url", __FILE__);
442             }
443         }
444     }
445
446     function updateAvatar($profile_id, $size, $mediatype, $filename) {
447
448         if (defined('SCRIPT_DEBUG')) {
449             common_debug("Updating avatar: $size");
450         }
451
452         $profile = Profile::staticGet($profile_id);
453
454         if (!$profile) {
455             if (defined('SCRIPT_DEBUG')) {
456                 common_debug("Couldn't get profile: $profile_id!");
457             }
458             return;
459         }
460
461         $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
462         $avatar = $profile->getAvatar($sizes[$size]);
463
464         if ($avatar) {
465             if (defined('SCRIPT_DEBUG')) {
466                 common_debug("Deleting $size avatar for $profile->nickname.");
467             }
468             $avatar->delete();
469         }
470
471         $this->newAvatar($profile->id, $size, $mediatype, $filename);
472     }
473
474     function newAvatar($profile_id, $size, $mediatype, $filename)
475     {
476         global $config;
477
478         $avatar = new Avatar();
479         $avatar->profile_id = $profile_id;
480
481         switch($size) {
482         case 'mini':
483             $avatar->width  = 24;
484             $avatar->height = 24;
485             break;
486         case 'normal':
487             $avatar->width  = 48;
488             $avatar->height = 48;
489             break;
490         default:
491
492             // Note: Twitter's big avatars are a different size than
493             // Laconica's (Laconica's = 96)
494
495             $avatar->width  = 73;
496             $avatar->height = 73;
497         }
498
499         $avatar->original = 0; // we don't have the original
500         $avatar->mediatype = $mediatype;
501         $avatar->filename = $filename;
502         $avatar->url = Avatar::url($filename);
503
504         if (defined('SCRIPT_DEBUG')) {
505             common_debug("new filename: $avatar->url");
506         }
507
508         $avatar->created = common_sql_now();
509
510         $id = $avatar->insert();
511
512         if (!$id) {
513             common_log_db_error($avatar, 'INSERT', __FILE__);
514             return null;
515         }
516
517         if (defined('SCRIPT_DEBUG')) {
518             common_debug("Saved new $size avatar for $profile_id.");
519         }
520
521         return $id;
522     }
523
524     function fetchAvatar($url, $filename)
525     {
526         $avatar_dir = INSTALLDIR . '/avatar/';
527
528         $avatarfile = $avatar_dir . $filename;
529
530         $out = fopen($avatarfile, 'wb');
531         if (!$out) {
532             common_log(LOG_WARNING, "Couldn't open file $filename", __FILE__);
533             return false;
534         }
535
536         if (defined('SCRIPT_DEBUG')) {
537             common_debug("Fetching avatar: $url");
538         }
539
540         $ch = curl_init();
541         curl_setopt($ch, CURLOPT_URL, $url);
542         curl_setopt($ch, CURLOPT_FILE, $out);
543         curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
544         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
545         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
546         $result = curl_exec($ch);
547         curl_close($ch);
548
549         fclose($out);
550
551         return $result;
552     }
553 }
554
555 ini_set("max_execution_time", "0");
556 ini_set("max_input_time", "0");
557 set_time_limit(0);
558 mb_internal_encoding('UTF-8');
559 declare(ticks = 1);
560
561 $fetcher = new TwitterStatusFetcher();
562 $fetcher->runOnce();
563