]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/twitterapi.php
Merge branch 'mgrdcm-review' into 0.7.x
[quix0rs-gnu-social.git] / 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
25     var $auth_user;
26
27     /**
28      * Initialization.
29      *
30      * @param array $args Web and URL arguments
31      *
32      * @return boolean false if user doesn't exist
33      */
34
35     function prepare($args)
36     {
37         parent::prepare($args);
38         return true;
39     }
40
41     /**
42      * Handle a request
43      *
44      * @param array $args Arguments from $_REQUEST
45      *
46      * @return void
47      */
48
49     function handle($args)
50     {
51         parent::handle($args);
52     }
53
54     /**
55      * Overrides XMLOutputter::element to write booleans as strings (true|false).
56      * See that method's documentation for more info.
57      *
58      * @param string $tag     Element type or tagname
59      * @param array  $attrs   Array of element attributes, as
60      *                        key-value pairs
61      * @param string $content string content of the element
62      *
63      * @return void
64      */
65     function element($tag, $attrs=null, $content=null)
66     {
67         if (is_bool($content)) {
68             $content = ($content ? 'true' : 'false');
69         }
70
71         return parent::element($tag, $attrs, $content);
72     }
73
74     function twitter_user_array($profile, $get_notice=false)
75     {
76         $twitter_user = array();
77
78         $twitter_user['id'] = intval($profile->id);
79         $twitter_user['name'] = $profile->getBestName();
80         $twitter_user['screen_name'] = $profile->nickname;
81         $twitter_user['location'] = ($profile->location) ? $profile->location : null;
82         $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
83
84         $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
85         $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
86             Avatar::defaultImage(AVATAR_STREAM_SIZE);
87
88         $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
89         $twitter_user['protected'] = false; # not supported by Laconica yet
90         $twitter_user['followers_count'] = $this->count_subscriptions($profile);
91
92         // To be supported soon...
93         $twitter_user['profile_background_color'] = '';
94         $twitter_user['profile_text_color'] = '';
95         $twitter_user['profile_link_color'] = '';
96         $twitter_user['profile_sidebar_fill_color'] = '';
97         $twitter_user['profile_sidebar_border_color'] = '';
98
99         $subbed = DB_DataObject::factory('subscription');
100         $subbed->subscriber = $profile->id;
101         $subbed_count = (int) $subbed->count() - 1;
102         $twitter_user['friends_count'] = (is_int($subbed_count)) ? $subbed_count : 0;
103
104         $twitter_user['created_at'] = $this->date_twitter($profile->created);
105
106         $faves = DB_DataObject::factory('fave');
107         $faves->user_id = $user->id;
108         $faves_count = (int) $faves->count();
109         $twitter_user['favourites_count'] = $faves_count; // British spelling!
110
111         // Need to pull up the user for some of this
112         $user = User::staticGet($profile->id);
113
114         $timezone = 'UTC';
115
116         if ($user->timezone) {
117             $timezone = $user->timezone;
118         }
119
120         $t = new DateTime;
121         $t->setTimezone(new DateTimeZone($timezone));
122
123         $twitter_user['utc_offset'] = $t->format('Z');
124         $twitter_user['time_zone'] = $timezone;
125
126         // To be supported some day, perhaps
127         $twitter_user['profile_background_image_url'] = '';
128         $twitter_user['profile_background_tile'] = false;
129
130         $notices = DB_DataObject::factory('notice');
131         $notices->profile_id = $profile->id;
132         $notice_count = (int) $notices->count();
133
134         $twitter_user['statuses_count'] = (is_int($notice_count)) ? $notice_count : 0;
135
136         // Is the requesting user following this user?
137         $twitter_user['following'] = false;
138         $twitter_user['notifications'] = false;
139
140         if (isset($apidata['user'])) {
141
142             $twitter_user['following'] = $apidata['user']->isSubscribed($profile);
143
144             // Notifications on?
145             $sub = Subscription::pkeyGet(array('subscriber' =>
146                 $apidata['user']->id, 'subscribed' => $profile->id));
147
148             if ($sub) {
149                 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
150             }
151         }
152
153         if ($get_notice) {
154             $notice = $profile->getCurrentNotice();
155             if ($notice) {
156                 # don't get user!
157                 $twitter_user['status'] = $this->twitter_status_array($notice, false);
158             }
159         }
160
161         return $twitter_user;
162     }
163
164     function twitter_status_array($notice, $include_user=true)
165     {
166         $profile = $notice->getProfile();
167
168         $twitter_status = array();
169         $twitter_status['text'] = $notice->content;
170         $twitter_status['truncated'] = false; # Not possible on Laconica
171         $twitter_status['created_at'] = $this->date_twitter($notice->created);
172         $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
173             intval($notice->reply_to) : null;
174         $twitter_status['source'] = $this->source_link($notice->source);
175         $twitter_status['id'] = intval($notice->id);
176
177         $replier_profile = null;
178
179         if ($notice->reply_to) {
180             $reply = Notice::staticGet(intval($notice->reply_to));
181             if ($reply) {
182                 $replier_profile = $reply->getProfile();
183             }
184         }
185
186         $twitter_status['in_reply_to_user_id'] =
187             ($replier_profile) ? intval($replier_profile->id) : null;
188         $twitter_status['in_reply_to_screen_name'] =
189             ($replier_profile) ? $replier_profile->nickname : null;
190
191         if (isset($this->auth_user)) {
192             $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
193         } else {
194             $twitter_status['favorited'] = false;
195         }
196
197         if ($include_user) {
198             # Don't get notice (recursive!)
199             $twitter_user = $this->twitter_user_array($profile, false);
200             $twitter_status['user'] = $twitter_user;
201         }
202
203         return $twitter_status;
204     }
205
206     function twitter_rss_entry_array($notice)
207     {
208
209         $profile = $notice->getProfile();
210         $entry = array();
211
212         # We trim() to avoid extraneous whitespace in the output
213
214         $entry['content'] = common_xml_safe_str(trim($notice->rendered));
215         $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
216         $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
217         $entry['published'] = common_date_iso8601($notice->created);
218
219         $taguribase = common_config('integration', 'taguri');
220         $entry['id'] = "tag:$taguribase:$entry[link]";
221
222         $entry['updated'] = $entry['published'];
223         $entry['author'] = $profile->getBestName();
224
225         # RSS Item specific
226         $entry['description'] = $entry['content'];
227         $entry['pubDate'] = common_date_rfc2822($notice->created);
228         $entry['guid'] = $entry['link'];
229
230         return $entry;
231     }
232
233     function twitter_rss_dmsg_array($message)
234     {
235
236         $entry = array();
237
238         $entry['title'] = sprintf('Message from %s to %s',
239             $message->getFrom()->nickname, $message->getTo()->nickname);
240
241         $entry['content'] = common_xml_safe_str(trim($message->content));
242         $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
243         $entry['published'] = common_date_iso8601($message->created);
244
245         $taguribase = common_config('integration', 'taguri');
246
247         $entry['id'] = "tag:$taguribase,:$entry[link]";
248         $entry['updated'] = $entry['published'];
249         $entry['author'] = $message->getFrom()->getBestName();
250
251         # RSS Item specific
252         $entry['description'] = $entry['content'];
253         $entry['pubDate'] = common_date_rfc2822($message->created);
254         $entry['guid'] = $entry['link'];
255
256         return $entry;
257     }
258
259     function twitter_dmsg_array($message)
260     {
261         $twitter_dm = array();
262
263         $from_profile = $message->getFrom();
264         $to_profile = $message->getTo();
265
266         $twitter_dm['id'] = $message->id;
267         $twitter_dm['sender_id'] = $message->from_profile;
268         $twitter_dm['text'] = trim($message->content);
269         $twitter_dm['recipient_id'] = $message->to_profile;
270         $twitter_dm['created_at'] = $this->date_twitter($message->created);
271         $twitter_dm['sender_screen_name'] = $from_profile->nickname;
272         $twitter_dm['recipient_screen_name'] = $to_profile->nickname;
273         $twitter_dm['sender'] = $this->twitter_user_array($from_profile, false);
274         $twitter_dm['recipient'] = $this->twitter_user_array($to_profile, false);
275
276         return $twitter_dm;
277     }
278
279     function show_twitter_xml_status($twitter_status)
280     {
281         $this->elementStart('status');
282         foreach($twitter_status as $element => $value) {
283             switch ($element) {
284             case 'user':
285                 $this->show_twitter_xml_user($twitter_status['user']);
286                 break;
287             case 'text':
288                 $this->element($element, null, common_xml_safe_str($value));
289                 break;
290             default:
291                 $this->element($element, null, $value);
292             }
293         }
294         $this->elementEnd('status');
295     }
296
297     function show_twitter_xml_user($twitter_user, $role='user')
298     {
299         $this->elementStart($role);
300         foreach($twitter_user as $element => $value) {
301             if ($element == 'status') {
302                 $this->show_twitter_xml_status($twitter_user['status']);
303             } else {
304                 $this->element($element, null, $value);
305             }
306         }
307         $this->elementEnd($role);
308     }
309
310     function show_twitter_rss_item($entry)
311     {
312         $this->elementStart('item');
313         $this->element('title', null, $entry['title']);
314         $this->element('description', null, $entry['description']);
315         $this->element('pubDate', null, $entry['pubDate']);
316         $this->element('guid', null, $entry['guid']);
317         $this->element('link', null, $entry['link']);
318         $this->elementEnd('item');
319     }
320
321     function show_json_objects($objects)
322     {
323         print(json_encode($objects));
324     }
325
326     function show_single_xml_status($notice)
327     {
328         $this->init_document('xml');
329         $twitter_status = $this->twitter_status_array($notice);
330         $this->show_twitter_xml_status($twitter_status);
331         $this->end_document('xml');
332     }
333
334     function show_single_json_status($notice)
335     {
336         $this->init_document('json');
337         $status = $this->twitter_status_array($notice);
338         $this->show_json_objects($status);
339         $this->end_document('json');
340     }
341
342     function show_single_xml_dmsg($message)
343     {
344         $this->init_document('xml');
345         $dmsg = $this->twitter_dmsg_array($message);
346         $this->show_twitter_xml_dmsg($dmsg);
347         $this->end_document('xml');
348     }
349
350     function show_single_json_dmsg($message)
351     {
352         $this->init_document('json');
353         $dmsg = $this->twitter_dmsg_array($message);
354         $this->show_json_objects($dmsg);
355         $this->end_document('json');
356     }
357
358     function show_twitter_xml_dmsg($twitter_dm)
359     {
360         $this->elementStart('direct_message');
361         foreach($twitter_dm as $element => $value) {
362             switch ($element) {
363             case 'sender':
364             case 'recipient':
365                 $this->show_twitter_xml_user($value, $element);
366                 break;
367             case 'text':
368                 $this->element($element, null, common_xml_safe_str($value));
369                 break;
370             default:
371                 $this->element($element, null, $value);
372             }
373         }
374         $this->elementEnd('direct_message');
375     }
376
377     function show_xml_timeline($notice)
378     {
379
380         $this->init_document('xml');
381         $this->elementStart('statuses', array('type' => 'array'));
382
383         if (is_array($notice)) {
384             foreach ($notice as $n) {
385                 $twitter_status = $this->twitter_status_array($n);
386                 $this->show_twitter_xml_status($twitter_status);
387             }
388         } else {
389             while ($notice->fetch()) {
390                 $twitter_status = $this->twitter_status_array($notice);
391                 $this->show_twitter_xml_status($twitter_status);
392             }
393         }
394
395         $this->elementEnd('statuses');
396         $this->end_document('xml');
397     }
398
399     function show_rss_timeline($notice, $title, $link, $subtitle, $suplink=null)
400     {
401
402         $this->init_document('rss');
403
404         $this->elementStart('channel');
405         $this->element('title', null, $title);
406         $this->element('link', null, $link);
407         if (!is_null($suplink)) {
408             # For FriendFeed's SUP protocol
409             $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
410                                          'rel' => 'http://api.friendfeed.com/2008/03#sup',
411                                          'href' => $suplink,
412                                          'type' => 'application/json'));
413         }
414         $this->element('description', null, $subtitle);
415         $this->element('language', null, 'en-us');
416         $this->element('ttl', null, '40');
417
418         if (is_array($notice)) {
419             foreach ($notice as $n) {
420                 $entry = $this->twitter_rss_entry_array($n);
421                 $this->show_twitter_rss_item($entry);
422             }
423         } else {
424             while ($notice->fetch()) {
425                 $entry = $this->twitter_rss_entry_array($notice);
426                 $this->show_twitter_rss_item($entry);
427             }
428         }
429
430         $this->elementEnd('channel');
431         $this->end_twitter_rss();
432     }
433
434     function show_atom_timeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
435     {
436
437         $this->init_document('atom');
438
439         $this->element('title', null, $title);
440         $this->element('id', null, $id);
441         $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
442
443         if (!is_null($suplink)) {
444             # For FriendFeed's SUP protocol
445             $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
446                                          'href' => $suplink,
447                                          'type' => 'application/json'));
448         }
449
450         if (!is_null($selfuri)) {
451             $this->element('link', array('href' => $selfuri,
452                 'rel' => 'self', 'type' => 'application/atom+xml'), null);
453         }
454
455         $this->element('updated', null, common_date_iso8601('now'));
456         $this->element('subtitle', null, $subtitle);
457
458         if (is_array($notice)) {
459             foreach ($notice as $n) {
460                 $this->raw($n->asAtomEntry());
461             }
462         } else {
463             while ($notice->fetch()) {
464                 $this->raw($notice->asAtomEntry());
465             }
466         }
467
468         $this->end_document('atom');
469
470     }
471
472     function show_json_timeline($notice)
473     {
474
475         $this->init_document('json');
476
477         $statuses = array();
478
479         if (is_array($notice)) {
480             foreach ($notice as $n) {
481                 $twitter_status = $this->twitter_status_array($n);
482                 array_push($statuses, $twitter_status);
483             }
484         } else {
485             while ($notice->fetch()) {
486                 $twitter_status = $this->twitter_status_array($notice);
487                 array_push($statuses, $twitter_status);
488             }
489         }
490
491         $this->show_json_objects($statuses);
492
493         $this->end_document('json');
494     }
495
496     // Anyone know what date format this is?
497     // Twitter's dates look like this: "Mon Jul 14 23:52:38 +0000 2008" -- Zach
498     function date_twitter($dt)
499     {
500         $t = strtotime($dt);
501         return date("D M d H:i:s O Y", $t);
502     }
503
504     // XXX: Candidate for a general utility method somewhere?
505     function count_subscriptions($profile)
506     {
507
508         $count = 0;
509         $sub = new Subscription();
510         $sub->subscribed = $profile->id;
511
512         $count = $sub->find();
513
514         if ($count > 0) {
515             return $count - 1;
516         } else {
517             return 0;
518         }
519     }
520
521     function init_document($type='xml')
522     {
523         switch ($type) {
524          case 'xml':
525             header('Content-Type: application/xml; charset=utf-8');
526             $this->startXML();
527             break;
528          case 'json':
529             header('Content-Type: application/json; charset=utf-8');
530
531             // Check for JSONP callback
532             $callback = $this->arg('callback');
533             if ($callback) {
534                 print $callback . '(';
535             }
536             break;
537          case 'rss':
538             header("Content-Type: application/rss+xml; charset=utf-8");
539             $this->init_twitter_rss();
540             break;
541          case 'atom':
542             header('Content-Type: application/atom+xml; charset=utf-8');
543             $this->init_twitter_atom();
544             break;
545          default:
546             $this->client_error(_('Not a supported data format.'));
547             break;
548         }
549
550         return;
551     }
552
553     function end_document($type='xml')
554     {
555         switch ($type) {
556          case 'xml':
557             $this->endXML();
558             break;
559          case 'json':
560
561             // Check for JSONP callback
562             $callback = $this->arg('callback');
563             if ($callback) {
564                 print ')';
565             }
566             break;
567          case 'rss':
568             $this->end_twitter_rss();
569             break;
570          case 'atom':
571             $this->end_twitter_rss();
572             break;
573          default:
574             $this->client_error(_('Not a supported data format.'));
575             break;
576         }
577         return;
578     }
579
580     function client_error($msg, $code = 400, $content_type = 'json')
581     {
582
583         static $status = array(400 => 'Bad Request',
584                                401 => 'Unauthorized',
585                                402 => 'Payment Required',
586                                403 => 'Forbidden',
587                                404 => 'Not Found',
588                                405 => 'Method Not Allowed',
589                                406 => 'Not Acceptable',
590                                407 => 'Proxy Authentication Required',
591                                408 => 'Request Timeout',
592                                409 => 'Conflict',
593                                410 => 'Gone',
594                                411 => 'Length Required',
595                                412 => 'Precondition Failed',
596                                413 => 'Request Entity Too Large',
597                                414 => 'Request-URI Too Long',
598                                415 => 'Unsupported Media Type',
599                                416 => 'Requested Range Not Satisfiable',
600                                417 => 'Expectation Failed');
601
602         $action = $this->trimmed('action');
603
604         common_debug("User error '$code' on '$action': $msg", __FILE__);
605
606         if (!array_key_exists($code, $status)) {
607             $code = 400;
608         }
609
610         $status_string = $status[$code];
611         header('HTTP/1.1 '.$code.' '.$status_string);
612
613         if ($content_type == 'xml') {
614             $this->init_document('xml');
615             $this->elementStart('hash');
616             $this->element('error', null, $msg);
617             $this->element('request', null, $_SERVER['REQUEST_URI']);
618             $this->elementEnd('hash');
619             $this->end_document('xml');
620         } else {
621             $this->init_document('json');
622             $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
623             print(json_encode($error_array));
624             $this->end_document('json');
625         }
626
627     }
628
629     function init_twitter_rss()
630     {
631         $this->startXML();
632         $this->elementStart('rss', array('version' => '2.0'));
633     }
634
635     function end_twitter_rss()
636     {
637         $this->elementEnd('rss');
638         $this->endXML();
639     }
640
641     function init_twitter_atom()
642     {
643         $this->startXML();
644         // FIXME: don't hardcode the language here!
645         $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
646                                           'xml:lang' => 'en-US',
647                                           'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
648     }
649
650     function end_twitter_atom()
651     {
652         $this->elementEnd('feed');
653         $this->endXML();
654     }
655
656     function show_profile($profile, $content_type='xml', $notice=null)
657     {
658         $profile_array = $this->twitter_user_array($profile, true);
659         switch ($content_type) {
660          case 'xml':
661             $this->show_twitter_xml_user($profile_array);
662             break;
663          case 'json':
664             $this->show_json_objects($profile_array);
665             break;
666          default:
667             $this->client_error(_('Not a supported data format.'));
668             return;
669         }
670         return;
671     }
672
673     function get_user($id, $apidata=null)
674     {
675         if (!$id) {
676             
677             // Twitter supports these other ways of passing the user ID
678             if (is_numeric($this->arg('id'))) {
679                 return User::staticGet($this->arg('id'));
680             } else if ($this->arg('id')) {
681                 $nickname = common_canonical_nickname($this->arg('id'));
682                 return User::staticGet('nickname', $nickname);
683             } else if ($this->arg('user_id')) {
684                 // This is to ensure that a non-numeric user_id still 
685                 // overrides screen_name even if it doesn't get used
686                 if (is_numeric($this->arg('user_id'))) {
687                     return User::staticGet('id', $this->arg('user_id'));
688                 }
689             } else if ($this->arg('screen_name')) {
690                 $nickname = common_canonical_nickname($this->arg('screen_name'));
691                 return User::staticGet('nickname', $nickname);
692             } else {
693                 // Fall back to trying the currently authenticated user
694                 return $apidata['user'];
695             }
696             
697         } else if (is_numeric($id)) {
698             return User::staticGet($id);
699         } else {
700             $nickname = common_canonical_nickname($id);
701             return User::staticGet('nickname', $nickname);
702         }
703     }
704
705     function get_profile($id)
706     {
707         if (is_numeric($id)) {
708             return Profile::staticGet($id);
709         } else {
710             $user = User::staticGet('nickname', $id);
711             if ($user) {
712                 return $user->getProfile();
713             } else {
714                 return null;
715             }
716         }
717     }
718
719     function source_link($source)
720     {
721         $source_name = _($source);
722         switch ($source) {
723          case 'web':
724          case 'xmpp':
725          case 'mail':
726          case 'omb':
727          case 'api':
728             break;
729          default:
730             $ns = Notice_source::staticGet($source);
731             if ($ns) {
732                 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
733             }
734             break;
735         }
736         return $source_name;
737     }
738
739 }