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