]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - _darcs/pristine/lib/twitterapi.php
3cddfa9c95b2932b46804e093282021e9f028058
[quix0rs-gnu-social.git] / _darcs / pristine / lib / twitterapi.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('LACONICA')) { exit(1); }
21
22 class TwitterapiAction extends Action {
23
24     var $auth_user;
25
26     function handle($args)
27     {
28         parent::handle($args);
29     }
30
31     function twitter_user_array($profile, $get_notice=false)
32     {
33
34         $twitter_user = array();
35
36         $twitter_user['name'] = $profile->getBestName();
37         $twitter_user['followers_count'] = $this->count_subscriptions($profile);
38         $twitter_user['screen_name'] = $profile->nickname;
39         $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
40         $twitter_user['location'] = ($profile->location) ? $profile->location : null;
41         $twitter_user['id'] = intval($profile->id);
42
43         $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
44
45         $twitter_user['profile_image_url'] = ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE);
46         $twitter_user['protected'] = 'false'; # not supported by Laconica yet
47         $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
48
49         if ($get_notice) {
50             $notice = $profile->getCurrentNotice();
51             if ($notice) {
52                 # don't get user!
53                 $twitter_user['status'] = $this->twitter_status_array($notice, false);
54             }
55         }
56
57         return $twitter_user;
58     }
59
60     function twitter_status_array($notice, $include_user=true)
61     {
62
63         $profile = $notice->getProfile();
64
65         $twitter_status = array();
66         $twitter_status['text'] = $notice->content;
67         $twitter_status['truncated'] = 'false'; # Not possible on Laconica
68         $twitter_status['created_at'] = $this->date_twitter($notice->created);
69         $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ? intval($notice->reply_to) : null;
70         $twitter_status['source'] = $this->source_link($notice->source);
71         $twitter_status['id'] = intval($notice->id);
72         $twitter_status['in_reply_to_user_id'] = ($notice->reply_to) ? $this->replier_by_reply(intval($notice->reply_to)) : null;
73
74         if (isset($this->auth_user)) {
75             $twitter_status['favorited'] = ($this->auth_user->hasFave($notice)) ? 'true' : 'false';
76         } else {
77             $twitter_status['favorited'] = 'false';
78         }
79
80         if ($include_user) {
81             # Don't get notice (recursive!)
82             $twitter_user = $this->twitter_user_array($profile, false);
83             $twitter_status['user'] = $twitter_user;
84         }
85
86         return $twitter_status;
87     }
88
89     function twitter_rss_entry_array($notice)
90     {
91
92         $profile = $notice->getProfile();
93
94         $server = common_config('site', 'server');
95         $entry = array();
96
97         # We trim() to avoid extraneous whitespace in the output
98
99         $entry['content'] = common_xml_safe_str(trim($notice->rendered));
100         $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
101         $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
102         $entry['published'] = common_date_iso8601($notice->created);
103         $entry['id'] = "tag:$server,2008:$entry[link]";
104         $entry['updated'] = $entry['published'];
105
106         # RSS Item specific
107         $entry['description'] = $entry['content'];
108         $entry['pubDate'] = common_date_rfc2822($notice->created);
109         $entry['guid'] = $entry['link'];
110
111         return $entry;
112     }
113
114     function twitter_rss_dmsg_array($message)
115     {
116
117         $server = common_config('site', 'server');
118         $entry = array();
119
120         $entry['title'] = sprintf('Message from %s to %s',
121             $message->getFrom()->nickname, $message->getTo()->nickname);
122
123         $entry['content'] = common_xml_safe_str(trim($message->content));
124         $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
125         $entry['published'] = common_date_iso8601($message->created);
126         $entry['id'] = "tag:$server,2008:$entry[link]";
127         $entry['updated'] = $entry['published'];
128
129         # RSS Item specific
130         $entry['description'] = $entry['content'];
131         $entry['pubDate'] = common_date_rfc2822($message->created);
132         $entry['guid'] = $entry['link'];
133
134         return $entry;
135     }
136
137     function twitter_dmsg_array($message)
138     {
139
140         $twitter_dm = array();
141
142         $from_profile = $message->getFrom();
143         $to_profile = $message->getTo();
144
145         $twitter_dm['id'] = $message->id;
146         $twitter_dm['sender_id'] = $message->from_profile;
147         $twitter_dm['text'] = trim($message->content);
148         $twitter_dm['recipient_id'] = $message->to_profile;
149         $twitter_dm['created_at'] = $this->date_twitter($message->created);
150         $twitter_dm['sender_screen_name'] = $from_profile->nickname;
151         $twitter_dm['recipient_screen_name'] = $to_profile->nickname;
152         $twitter_dm['sender'] = $this->twitter_user_array($from_profile, false);
153         $twitter_dm['recipient'] = $this->twitter_user_array($to_profile, false);
154
155         return $twitter_dm;
156     }
157
158     function show_twitter_xml_status($twitter_status)
159     {
160         common_element_start('status');
161         foreach($twitter_status as $element => $value) {
162             switch ($element) {
163             case 'user':
164                 $this->show_twitter_xml_user($twitter_status['user']);
165                 break;
166             case 'text':
167                 common_element($element, null, common_xml_safe_str($value));
168                 break;
169             default:
170                 common_element($element, null, $value);
171             }
172         }
173         common_element_end('status');
174     }
175
176     function show_twitter_xml_user($twitter_user, $role='user')
177     {
178         common_element_start($role);
179         foreach($twitter_user as $element => $value) {
180             if ($element == 'status') {
181                 $this->show_twitter_xml_status($twitter_user['status']);
182             } else {
183                 common_element($element, null, $value);
184             }
185         }
186         common_element_end($role);
187     }
188
189     function show_twitter_rss_item($entry)
190     {
191         common_element_start('item');
192         common_element('title', null, $entry['title']);
193         common_element('description', null, $entry['description']);
194         common_element('pubDate', null, $entry['pubDate']);
195         common_element('guid', null, $entry['guid']);
196         common_element('link', null, $entry['link']);
197         common_element_end('item');
198     }
199
200     function show_twitter_atom_entry($entry)
201     {
202         common_element_start('entry');
203         common_element('title', null, $entry['title']);
204         common_element('content', array('type' => 'html'), $entry['content']);
205         common_element('id', null, $entry['id']);
206         common_element('published', null, $entry['published']);
207         common_element('updated', null, $entry['updated']);
208         common_element('link', array('href' => $entry['link'], 'rel' => 'alternate', 'type' => 'text/html'), null);
209         common_element_end('entry');
210     }
211
212     function show_json_objects($objects)
213     {
214         print(json_encode($objects));
215     }
216
217     function show_single_xml_status($notice)
218     {
219         $this->init_document('xml');
220         $twitter_status = $this->twitter_status_array($notice);
221         $this->show_twitter_xml_status($twitter_status);
222         $this->end_document('xml');
223     }
224
225     function show_single_json_status($notice)
226     {
227         $this->init_document('json');
228         $status = $this->twitter_status_array($notice);
229         $this->show_json_objects($status);
230         $this->end_document('json');
231     }
232
233     function show_single_xml_dmsg($message)
234     {
235         $this->init_document('xml');
236         $dmsg = $this->twitter_dmsg_array($message);
237         $this->show_twitter_xml_dmsg($dmsg);
238         $this->end_document('xml');
239     }
240
241     function show_single_json_dmsg($message)
242     {
243         $this->init_document('json');
244         $dmsg = $this->twitter_dmsg_array($message);
245         $this->show_json_objects($dmsg);
246         $this->end_document('json');
247     }
248
249     function show_twitter_xml_dmsg($twitter_dm)
250     {
251         common_element_start('direct_message');
252         foreach($twitter_dm as $element => $value) {
253             switch ($element) {
254             case 'sender':
255             case 'recipient':
256                 $this->show_twitter_xml_user($value, $element);
257                 break;
258             case 'text':
259                 common_element($element, null, common_xml_safe_str($value));
260                 break;
261             default:
262                 common_element($element, null, $value);
263             }
264         }
265         common_element_end('direct_message');
266     }
267
268     function show_xml_timeline($notice)
269     {
270
271         $this->init_document('xml');
272         common_element_start('statuses', array('type' => 'array'));
273
274         if (is_array($notice)) {
275             foreach ($notice as $n) {
276                 $twitter_status = $this->twitter_status_array($n);
277                 $this->show_twitter_xml_status($twitter_status);
278             }
279         } else {
280             while ($notice->fetch()) {
281                 $twitter_status = $this->twitter_status_array($notice);
282                 $this->show_twitter_xml_status($twitter_status);
283             }
284         }
285
286         common_element_end('statuses');
287         $this->end_document('xml');
288     }
289
290     function show_rss_timeline($notice, $title, $link, $subtitle, $suplink=null)
291     {
292
293         $this->init_document('rss');
294
295         common_element_start('channel');
296         common_element('title', null, $title);
297         common_element('link', null, $link);
298         if (!is_null($suplink)) {
299             # For FriendFeed's SUP protocol
300             common_element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
301                                          'rel' => 'http://api.friendfeed.com/2008/03#sup',
302                                          'href' => $suplink,
303                                          'type' => 'application/json'));
304         }
305         common_element('description', null, $subtitle);
306         common_element('language', null, 'en-us');
307         common_element('ttl', null, '40');
308
309         if (is_array($notice)) {
310             foreach ($notice as $n) {
311                 $entry = $this->twitter_rss_entry_array($n);
312                 $this->show_twitter_rss_item($entry);
313             }
314         } else {
315             while ($notice->fetch()) {
316                 $entry = $this->twitter_rss_entry_array($notice);
317                 $this->show_twitter_rss_item($entry);
318             }
319         }
320
321         common_element_end('channel');
322         $this->end_twitter_rss();
323     }
324
325     function show_atom_timeline($notice, $title, $id, $link, $subtitle=null, $suplink=null)
326     {
327
328         $this->init_document('atom');
329
330         common_element('title', null, $title);
331         common_element('id', null, $id);
332         common_element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
333         if (!is_null($suplink)) {
334             # For FriendFeed's SUP protocol
335             common_element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
336                                          'href' => $suplink,
337                                          'type' => 'application/json'));
338         }
339         common_element('subtitle', null, $subtitle);
340
341         if (is_array($notice)) {
342             foreach ($notice as $n) {
343                 $entry = $this->twitter_rss_entry_array($n);
344                 $this->show_twitter_atom_entry($entry);
345             }
346         } else {
347             while ($notice->fetch()) {
348                 $entry = $this->twitter_rss_entry_array($notice);
349                 $this->show_twitter_atom_entry($entry);
350             }
351         }
352
353         $this->end_document('atom');
354
355     }
356
357     function show_json_timeline($notice)
358     {
359
360         $this->init_document('json');
361
362         $statuses = array();
363
364         if (is_array($notice)) {
365             foreach ($notice as $n) {
366                 $twitter_status = $this->twitter_status_array($n);
367                 array_push($statuses, $twitter_status);
368             }
369         } else {
370             while ($notice->fetch()) {
371                 $twitter_status = $this->twitter_status_array($notice);
372                 array_push($statuses, $twitter_status);
373             }
374         }
375
376         $this->show_json_objects($statuses);
377
378         $this->end_document('json');
379     }
380
381     // Anyone know what date format this is?
382     // Twitter's dates look like this: "Mon Jul 14 23:52:38 +0000 2008" -- Zach
383     function date_twitter($dt)
384     {
385         $t = strtotime($dt);
386         return date("D M d G:i:s O Y", $t);
387     }
388
389     function replier_by_reply($reply_id)
390     {
391         $notice = Notice::staticGet($reply_id);
392         if ($notice) {
393             $profile = $notice->getProfile();
394             if ($profile) {
395                 return intval($profile->id);
396             } else {
397                 common_debug('Can\'t find a profile for notice: ' . $notice->id, __FILE__);
398             }
399         } else {
400             common_debug("Can't get notice: $reply_id", __FILE__);
401         }
402         return null;
403     }
404
405     // XXX: Candidate for a general utility method somewhere?
406     function count_subscriptions($profile)
407     {
408
409         $count = 0;
410         $sub = new Subscription();
411         $sub->subscribed = $profile->id;
412
413         $count = $sub->find();
414
415         if ($count > 0) {
416             return $count - 1;
417         } else {
418             return 0;
419         }
420     }
421
422     function init_document($type='xml')
423     {
424         switch ($type) {
425          case 'xml':
426             header('Content-Type: application/xml; charset=utf-8');
427             common_start_xml();
428             break;
429          case 'json':
430             header('Content-Type: application/json; charset=utf-8');
431
432             // Check for JSONP callback
433             $callback = $this->arg('callback');
434             if ($callback) {
435                 print $callback . '(';
436             }
437             break;
438          case 'rss':
439             header("Content-Type: application/rss+xml; charset=utf-8");
440             $this->init_twitter_rss();
441             break;
442          case 'atom':
443             header('Content-Type: application/atom+xml; charset=utf-8');
444             $this->init_twitter_atom();
445             break;
446          default:
447             $this->client_error(_('Not a supported data format.'));
448             break;
449         }
450
451         return;
452     }
453
454     function end_document($type='xml')
455     {
456         switch ($type) {
457          case 'xml':
458             common_end_xml();
459             break;
460          case 'json':
461
462             // Check for JSONP callback
463             $callback = $this->arg('callback');
464             if ($callback) {
465                 print ')';
466             }
467             break;
468          case 'rss':
469             $this->end_twitter_rss();
470             break;
471          case 'atom':
472             $this->end_twitter_rss();
473             break;
474          default:
475             $this->client_error(_('Not a supported data format.'));
476             break;
477         }
478         return;
479     }
480
481     function client_error($msg, $code = 400, $content_type = 'json')
482     {
483
484         static $status = array(400 => 'Bad Request',
485                                401 => 'Unauthorized',
486                                402 => 'Payment Required',
487                                403 => 'Forbidden',
488                                404 => 'Not Found',
489                                405 => 'Method Not Allowed',
490                                406 => 'Not Acceptable',
491                                407 => 'Proxy Authentication Required',
492                                408 => 'Request Timeout',
493                                409 => 'Conflict',
494                                410 => 'Gone',
495                                411 => 'Length Required',
496                                412 => 'Precondition Failed',
497                                413 => 'Request Entity Too Large',
498                                414 => 'Request-URI Too Long',
499                                415 => 'Unsupported Media Type',
500                                416 => 'Requested Range Not Satisfiable',
501                                417 => 'Expectation Failed');
502
503         $action = $this->trimmed('action');
504
505         common_debug("User error '$code' on '$action': $msg", __FILE__);
506
507         if (!array_key_exists($code, $status)) {
508             $code = 400;
509         }
510
511         $status_string = $status[$code];
512         header('HTTP/1.1 '.$code.' '.$status_string);
513
514         if ($content_type == 'xml') {
515             $this->init_document('xml');
516             common_element_start('hash');
517             common_element('error', null, $msg);
518             common_element('request', null, $_SERVER['REQUEST_URI']);
519             common_element_end('hash');
520             $this->end_document('xml');
521         } else {
522             $this->init_document('json');
523             $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
524             print(json_encode($error_array));
525             $this->end_document('json');
526         }
527
528     }
529
530     function init_twitter_rss()
531     {
532         common_start_xml();
533         common_element_start('rss', array('version' => '2.0'));
534     }
535
536     function end_twitter_rss()
537     {
538         common_element_end('rss');
539         common_end_xml();
540     }
541
542     function init_twitter_atom()
543     {
544         common_start_xml();
545         common_element_start('feed', array('xmlns' => 'http://www.w3.org/2005/Atom', 'xml:lang' => 'en-US'));
546     }
547
548     function end_twitter_atom()
549     {
550         common_end_xml();
551         common_element_end('feed');
552     }
553
554     function show_profile($profile, $content_type='xml', $notice=null)
555     {
556         $profile_array = $this->twitter_user_array($profile, true);
557         switch ($content_type) {
558          case 'xml':
559             $this->show_twitter_xml_user($profile_array);
560             break;
561          case 'json':
562             $this->show_json_objects($profile_array);
563             break;
564          default:
565             $this->client_error(_('Not a supported data format.'));
566             return;
567         }
568         return;
569     }
570
571     function get_user($id, $apidata=null)
572     {
573         if (!$id) {
574             return $apidata['user'];
575         } else if (is_numeric($id)) {
576             return User::staticGet($id);
577         } else {
578             $nickname = common_canonical_nickname($id);
579             return User::staticGet('nickname', $nickname);
580         }
581     }
582
583     function get_profile($id)
584     {
585         if (is_numeric($id)) {
586             return Profile::staticGet($id);
587         } else {
588             $user = User::staticGet('nickname', $id);
589             if ($user) {
590                 return $user->getProfile();
591             } else {
592                 return null;
593             }
594         }
595     }
596
597     function source_link($source)
598     {
599         $source_name = _($source);
600         switch ($source) {
601          case 'web':
602          case 'xmpp':
603          case 'mail':
604          case 'omb':
605          case 'api':
606             break;
607          default:
608             $ns = Notice_source::staticGet($source);
609             if ($ns) {
610                 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
611             }
612             break;
613         }
614         return $source_name;
615     }
616
617     function show_extended_profile($user, $apidata)
618     {
619
620         $this->auth_user = $apidata['user'];
621
622         $profile = $user->getProfile();
623
624         if (!$profile) {
625             common_server_error(_('User has no profile.'));
626             return;
627         }
628
629         $twitter_user = $this->twitter_user_array($profile, true);
630
631         // Add in extended user fields offered up by this method
632         $twitter_user['created_at'] = $this->date_twitter($profile->created);
633
634         $subbed = DB_DataObject::factory('subscription');
635         $subbed->subscriber = $profile->id;
636         $subbed_count = (int) $subbed->count() - 1;
637
638         $notices = DB_DataObject::factory('notice');
639         $notices->profile_id = $profile->id;
640         $notice_count = (int) $notices->count();
641
642         $twitter_user['friends_count'] = (is_int($subbed_count)) ? $subbed_count : 0;
643         $twitter_user['statuses_count'] = (is_int($notice_count)) ? $notice_count : 0;
644
645         // Other fields Twitter sends...
646         $twitter_user['profile_background_color'] = '';
647         $twitter_user['profile_text_color'] = '';
648         $twitter_user['profile_link_color'] = '';
649         $twitter_user['profile_sidebar_fill_color'] = '';
650
651         $faves = DB_DataObject::factory('fave');
652         $faves->user_id = $user->id;
653         $faves_count = (int) $faves->count();
654         $twitter_user['favourites_count'] = $faves_count;
655
656         $timezone = 'UTC';
657
658         if ($user->timezone) {
659             $timezone = $user->timezone;
660         }
661
662         $t = new DateTime;
663         $t->setTimezone(new DateTimeZone($timezone));
664         $twitter_user['utc_offset'] = $t->format('Z');
665         $twitter_user['time_zone'] = $timezone;
666
667         $following = 'false';
668
669         if (isset($this->auth_user)) {
670             if ($this->auth_user->isSubscribed($profile)) {
671                 $following = 'true';
672             }
673
674             // Not implemented yet
675             $twitter_user['notifications'] = 'false';
676         }
677
678         $twitter_user['following'] = $following;
679
680         if ($apidata['content-type'] == 'xml') {
681             $this->init_document('xml');
682             $this->show_twitter_xml_user($twitter_user);
683             $this->end_document('xml');
684         } elseif ($apidata['content-type'] == 'json') {
685             $this->init_document('json');
686             $this->show_json_objects($twitter_user);
687             $this->end_document('json');
688         }
689
690     }
691
692 }