3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, Control Yourself, Inc.
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.
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.
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/>.
20 if (!defined('LACONICA')) {
24 class TwitterapiAction extends Action
32 * @param array $args Web and URL arguments
34 * @return boolean false if user doesn't exist
37 function prepare($args)
39 parent::prepare($args);
46 * @param array $args Arguments from $_REQUEST
51 function handle($args)
53 parent::handle($args);
57 * Overrides XMLOutputter::element to write booleans as strings (true|false).
58 * See that method's documentation for more info.
60 * @param string $tag Element type or tagname
61 * @param array $attrs Array of element attributes, as
63 * @param string $content string content of the element
67 function element($tag, $attrs=null, $content=null)
69 if (is_bool($content)) {
70 $content = ($content ? 'true' : 'false');
73 return parent::element($tag, $attrs, $content);
76 function twitter_user_array($profile, $get_notice=false)
78 $twitter_user = array();
80 $twitter_user['id'] = intval($profile->id);
81 $twitter_user['name'] = $profile->getBestName();
82 $twitter_user['screen_name'] = $profile->nickname;
83 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
84 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
86 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
87 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
88 Avatar::defaultImage(AVATAR_STREAM_SIZE);
90 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
91 $twitter_user['protected'] = false; # not supported by Laconica yet
92 $twitter_user['followers_count'] = $profile->subscriberCount();
94 // To be supported soon...
95 $twitter_user['profile_background_color'] = '';
96 $twitter_user['profile_text_color'] = '';
97 $twitter_user['profile_link_color'] = '';
98 $twitter_user['profile_sidebar_fill_color'] = '';
99 $twitter_user['profile_sidebar_border_color'] = '';
101 $twitter_user['friends_count'] = $profile->subscriptionCount();
103 $twitter_user['created_at'] = $this->date_twitter($profile->created);
105 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
107 // Need to pull up the user for some of this
108 $user = User::staticGet($profile->id);
112 if ($user->timezone) {
113 $timezone = $user->timezone;
117 $t->setTimezone(new DateTimeZone($timezone));
119 $twitter_user['utc_offset'] = $t->format('Z');
120 $twitter_user['time_zone'] = $timezone;
122 // To be supported some day, perhaps
123 $twitter_user['profile_background_image_url'] = '';
124 $twitter_user['profile_background_tile'] = false;
126 $twitter_user['statuses_count'] = $profile->noticeCount();
128 // Is the requesting user following this user?
129 $twitter_user['following'] = false;
130 $twitter_user['notifications'] = false;
132 if (isset($apidata['user'])) {
134 $twitter_user['following'] = $apidata['user']->isSubscribed($profile);
137 $sub = Subscription::pkeyGet(array('subscriber' =>
138 $apidata['user']->id, 'subscribed' => $profile->id));
141 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
146 $notice = $profile->getCurrentNotice();
149 $twitter_user['status'] = $this->twitter_status_array($notice, false);
153 return $twitter_user;
156 function twitter_status_array($notice, $include_user=true)
158 $profile = $notice->getProfile();
160 $twitter_status = array();
161 $twitter_status['text'] = $notice->content;
162 $twitter_status['truncated'] = false; # Not possible on Laconica
163 $twitter_status['created_at'] = $this->date_twitter($notice->created);
164 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
165 intval($notice->reply_to) : null;
166 $twitter_status['source'] = $this->source_link($notice->source);
167 $twitter_status['id'] = intval($notice->id);
169 $replier_profile = null;
171 if ($notice->reply_to) {
172 $reply = Notice::staticGet(intval($notice->reply_to));
174 $replier_profile = $reply->getProfile();
178 $twitter_status['in_reply_to_user_id'] =
179 ($replier_profile) ? intval($replier_profile->id) : null;
180 $twitter_status['in_reply_to_screen_name'] =
181 ($replier_profile) ? $replier_profile->nickname : null;
183 if (isset($this->auth_user)) {
184 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
186 $twitter_status['favorited'] = false;
190 $attachments = $notice->attachments();
191 $twitter_status['attachments']=array();
193 foreach($attachments as $attachment){
194 if ($attachment->isEnclosure()) {
196 $enclosure['url']=$attachment->url;
197 $enclosure['mimetype']=$attachment->mimetype;
198 $enclosure['size']=$attachment->size;
199 $twitter_status['attachments'][]=$enclosure;
205 # Don't get notice (recursive!)
206 $twitter_user = $this->twitter_user_array($profile, false);
207 $twitter_status['user'] = $twitter_user;
210 return $twitter_status;
213 function twitter_rss_entry_array($notice)
215 $profile = $notice->getProfile();
218 # We trim() to avoid extraneous whitespace in the output
220 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
221 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
222 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
223 $entry['published'] = common_date_iso8601($notice->created);
225 $taguribase = common_config('integration', 'taguri');
226 $entry['id'] = "tag:$taguribase:$entry[link]";
228 $entry['updated'] = $entry['published'];
229 $entry['author'] = $profile->getBestName();
232 $attachments = $notice->attachments();
234 $entry['enclosures']=array();
235 foreach($attachments as $attachment){
236 if ($attachment->isEnclosure()) {
238 $enclosure['url']=$attachment->url;
239 $enclosure['mimetype']=$attachment->mimetype;
240 $enclosure['size']=$attachment->size;
241 $entry['enclosures'][]=$enclosure;
247 $entry['description'] = $entry['content'];
248 $entry['pubDate'] = common_date_rfc2822($notice->created);
249 $entry['guid'] = $entry['link'];
254 function twitter_rss_dmsg_array($message)
259 $entry['title'] = sprintf('Message from %s to %s',
260 $message->getFrom()->nickname, $message->getTo()->nickname);
262 $entry['content'] = common_xml_safe_str(trim($message->content));
263 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
264 $entry['published'] = common_date_iso8601($message->created);
266 $taguribase = common_config('integration', 'taguri');
268 $entry['id'] = "tag:$taguribase,:$entry[link]";
269 $entry['updated'] = $entry['published'];
270 $entry['author'] = $message->getFrom()->getBestName();
273 $entry['description'] = $entry['content'];
274 $entry['pubDate'] = common_date_rfc2822($message->created);
275 $entry['guid'] = $entry['link'];
280 function twitter_dmsg_array($message)
282 $twitter_dm = array();
284 $from_profile = $message->getFrom();
285 $to_profile = $message->getTo();
287 $twitter_dm['id'] = $message->id;
288 $twitter_dm['sender_id'] = $message->from_profile;
289 $twitter_dm['text'] = trim($message->content);
290 $twitter_dm['recipient_id'] = $message->to_profile;
291 $twitter_dm['created_at'] = $this->date_twitter($message->created);
292 $twitter_dm['sender_screen_name'] = $from_profile->nickname;
293 $twitter_dm['recipient_screen_name'] = $to_profile->nickname;
294 $twitter_dm['sender'] = $this->twitter_user_array($from_profile, false);
295 $twitter_dm['recipient'] = $this->twitter_user_array($to_profile, false);
300 function twitter_relationship_array($source, $target)
302 $relationship = array();
304 $relationship['source'] =
305 $this->relationship_details_array($source, $target);
306 $relationship['target'] =
307 $this->relationship_details_array($target, $source);
309 return array('relationship' => $relationship);
312 function relationship_details_array($source, $target)
316 $details['screen_name'] = $source->nickname;
317 $details['followed_by'] = $target->isSubscribed($source);
318 $details['following'] = $source->isSubscribed($target);
320 $notifications = false;
322 if ($source->isSubscribed($target)) {
324 $sub = Subscription::pkeyGet(array('subscriber' =>
325 $source->id, 'subscribed' => $target->id));
328 $notifications = ($sub->jabber || $sub->sms);
332 $details['notifications_enabled'] = $notifications;
333 $details['blocking'] = $source->hasBlocked($target);
334 $details['id'] = $source->id;
339 function show_twitter_xml_relationship($relationship)
341 $this->elementStart('relationship');
343 foreach($relationship as $element => $value) {
344 if ($element == 'source' || $element == 'target') {
345 $this->elementStart($element);
346 $this->show_xml_relationship_details($value);
347 $this->elementEnd($element);
351 $this->elementEnd('relationship');
354 function show_xml_relationship_details($details)
356 foreach($details as $element => $value) {
357 $this->element($element, null, $value);
361 function show_twitter_xml_status($twitter_status)
363 $this->elementStart('status');
364 foreach($twitter_status as $element => $value) {
367 $this->show_twitter_xml_user($twitter_status['user']);
370 $this->element($element, null, common_xml_safe_str($value));
373 $this->element($element, null, $value);
376 $this->elementEnd('status');
379 function show_twitter_xml_user($twitter_user, $role='user')
381 $this->elementStart($role);
382 foreach($twitter_user as $element => $value) {
383 if ($element == 'status') {
384 $this->show_twitter_xml_status($twitter_user['status']);
386 $this->element($element, null, $value);
389 $this->elementEnd($role);
392 function show_twitter_rss_item($entry)
394 $this->elementStart('item');
395 $this->element('title', null, $entry['title']);
396 $this->element('description', null, $entry['description']);
397 $this->element('pubDate', null, $entry['pubDate']);
398 $this->element('guid', null, $entry['guid']);
399 $this->element('link', null, $entry['link']);
401 # RSS only supports 1 enclosure per item
402 if($entry['enclosures']){
403 $enclosure = $entry['enclosures'][0];
404 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
407 $this->elementEnd('item');
410 function show_json_objects($objects)
412 print(json_encode($objects));
415 function show_single_xml_status($notice)
417 $this->init_document('xml');
418 $twitter_status = $this->twitter_status_array($notice);
419 $this->show_twitter_xml_status($twitter_status);
420 $this->end_document('xml');
423 function show_single_json_status($notice)
425 $this->init_document('json');
426 $status = $this->twitter_status_array($notice);
427 $this->show_json_objects($status);
428 $this->end_document('json');
431 function show_single_xml_dmsg($message)
433 $this->init_document('xml');
434 $dmsg = $this->twitter_dmsg_array($message);
435 $this->show_twitter_xml_dmsg($dmsg);
436 $this->end_document('xml');
439 function show_single_json_dmsg($message)
441 $this->init_document('json');
442 $dmsg = $this->twitter_dmsg_array($message);
443 $this->show_json_objects($dmsg);
444 $this->end_document('json');
447 function show_twitter_xml_dmsg($twitter_dm)
449 $this->elementStart('direct_message');
450 foreach($twitter_dm as $element => $value) {
454 $this->show_twitter_xml_user($value, $element);
457 $this->element($element, null, common_xml_safe_str($value));
460 $this->element($element, null, $value);
463 $this->elementEnd('direct_message');
466 function show_xml_timeline($notice)
469 $this->init_document('xml');
470 $this->elementStart('statuses', array('type' => 'array'));
472 if (is_array($notice)) {
473 foreach ($notice as $n) {
474 $twitter_status = $this->twitter_status_array($n);
475 $this->show_twitter_xml_status($twitter_status);
478 while ($notice->fetch()) {
479 $twitter_status = $this->twitter_status_array($notice);
480 $this->show_twitter_xml_status($twitter_status);
484 $this->elementEnd('statuses');
485 $this->end_document('xml');
488 function show_rss_timeline($notice, $title, $link, $subtitle, $suplink=null)
491 $this->init_document('rss');
493 $this->elementStart('channel');
494 $this->element('title', null, $title);
495 $this->element('link', null, $link);
496 if (!is_null($suplink)) {
497 # For FriendFeed's SUP protocol
498 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
499 'rel' => 'http://api.friendfeed.com/2008/03#sup',
501 'type' => 'application/json'));
503 $this->element('description', null, $subtitle);
504 $this->element('language', null, 'en-us');
505 $this->element('ttl', null, '40');
507 if (is_array($notice)) {
508 foreach ($notice as $n) {
509 $entry = $this->twitter_rss_entry_array($n);
510 $this->show_twitter_rss_item($entry);
513 while ($notice->fetch()) {
514 $entry = $this->twitter_rss_entry_array($notice);
515 $this->show_twitter_rss_item($entry);
519 $this->elementEnd('channel');
520 $this->end_twitter_rss();
523 function show_atom_timeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
526 $this->init_document('atom');
528 $this->element('title', null, $title);
529 $this->element('id', null, $id);
530 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
532 if (!is_null($suplink)) {
533 # For FriendFeed's SUP protocol
534 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
536 'type' => 'application/json'));
539 if (!is_null($selfuri)) {
540 $this->element('link', array('href' => $selfuri,
541 'rel' => 'self', 'type' => 'application/atom+xml'), null);
544 $this->element('updated', null, common_date_iso8601('now'));
545 $this->element('subtitle', null, $subtitle);
547 if (is_array($notice)) {
548 foreach ($notice as $n) {
549 $this->raw($n->asAtomEntry());
552 while ($notice->fetch()) {
553 $this->raw($notice->asAtomEntry());
557 $this->end_document('atom');
561 function show_json_timeline($notice)
564 $this->init_document('json');
568 if (is_array($notice)) {
569 foreach ($notice as $n) {
570 $twitter_status = $this->twitter_status_array($n);
571 array_push($statuses, $twitter_status);
574 while ($notice->fetch()) {
575 $twitter_status = $this->twitter_status_array($notice);
576 array_push($statuses, $twitter_status);
580 $this->show_json_objects($statuses);
582 $this->end_document('json');
585 // Anyone know what date format this is?
586 // Twitter's dates look like this: "Mon Jul 14 23:52:38 +0000 2008" -- Zach
587 function date_twitter($dt)
590 return date("D M d H:i:s O Y", $t);
593 // XXX: Candidate for a general utility method somewhere?
594 function count_subscriptions($profile)
598 $sub = new Subscription();
599 $sub->subscribed = $profile->id;
601 $count = $sub->find();
610 function init_document($type='xml')
614 header('Content-Type: application/xml; charset=utf-8');
618 header('Content-Type: application/json; charset=utf-8');
620 // Check for JSONP callback
621 $callback = $this->arg('callback');
623 print $callback . '(';
627 header("Content-Type: application/rss+xml; charset=utf-8");
628 $this->init_twitter_rss();
631 header('Content-Type: application/atom+xml; charset=utf-8');
632 $this->init_twitter_atom();
635 $this->clientError(_('Not a supported data format.'));
642 function end_document($type='xml')
650 // Check for JSONP callback
651 $callback = $this->arg('callback');
657 $this->end_twitter_rss();
660 $this->end_twitter_rss();
663 $this->clientError(_('Not a supported data format.'));
669 function clientError($msg, $code = 400, $content_type = 'json')
672 static $status = array(400 => 'Bad Request',
673 401 => 'Unauthorized',
674 402 => 'Payment Required',
677 405 => 'Method Not Allowed',
678 406 => 'Not Acceptable',
679 407 => 'Proxy Authentication Required',
680 408 => 'Request Timeout',
683 411 => 'Length Required',
684 412 => 'Precondition Failed',
685 413 => 'Request Entity Too Large',
686 414 => 'Request-URI Too Long',
687 415 => 'Unsupported Media Type',
688 416 => 'Requested Range Not Satisfiable',
689 417 => 'Expectation Failed');
691 $action = $this->trimmed('action');
693 common_debug("User error '$code' on '$action': $msg", __FILE__);
695 if (!array_key_exists($code, $status)) {
699 $status_string = $status[$code];
700 header('HTTP/1.1 '.$code.' '.$status_string);
702 if ($content_type == 'xml') {
703 $this->init_document('xml');
704 $this->elementStart('hash');
705 $this->element('error', null, $msg);
706 $this->element('request', null, $_SERVER['REQUEST_URI']);
707 $this->elementEnd('hash');
708 $this->end_document('xml');
710 $this->init_document('json');
711 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
712 print(json_encode($error_array));
713 $this->end_document('json');
718 function init_twitter_rss()
721 $this->elementStart('rss', array('version' => '2.0'));
724 function end_twitter_rss()
726 $this->elementEnd('rss');
730 function init_twitter_atom()
733 // FIXME: don't hardcode the language here!
734 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
735 'xml:lang' => 'en-US',
736 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
739 function end_twitter_atom()
741 $this->elementEnd('feed');
745 function show_profile($profile, $content_type='xml', $notice=null)
747 $profile_array = $this->twitter_user_array($profile, true);
748 switch ($content_type) {
750 $this->show_twitter_xml_user($profile_array);
753 $this->show_json_objects($profile_array);
756 $this->clientError(_('Not a supported data format.'));
762 function get_user($id, $apidata=null)
766 // Twitter supports these other ways of passing the user ID
767 if (is_numeric($this->arg('id'))) {
768 return User::staticGet($this->arg('id'));
769 } else if ($this->arg('id')) {
770 $nickname = common_canonical_nickname($this->arg('id'));
771 return User::staticGet('nickname', $nickname);
772 } else if ($this->arg('user_id')) {
773 // This is to ensure that a non-numeric user_id still
774 // overrides screen_name even if it doesn't get used
775 if (is_numeric($this->arg('user_id'))) {
776 return User::staticGet('id', $this->arg('user_id'));
778 } else if ($this->arg('screen_name')) {
779 $nickname = common_canonical_nickname($this->arg('screen_name'));
780 return User::staticGet('nickname', $nickname);
782 // Fall back to trying the currently authenticated user
783 return $apidata['user'];
786 } else if (is_numeric($id)) {
787 return User::staticGet($id);
789 $nickname = common_canonical_nickname($id);
790 return User::staticGet('nickname', $nickname);
794 function get_group($id, $apidata=null)
798 if (is_numeric($this->arg('id'))) {
799 return User_group::staticGet($this->arg('id'));
800 } else if ($this->arg('id')) {
801 $nickname = common_canonical_nickname($this->arg('id'));
802 return User_group::staticGet('nickname', $nickname);
803 } else if ($this->arg('group_id')) {
804 // This is to ensure that a non-numeric user_id still
805 // overrides screen_name even if it doesn't get used
806 if (is_numeric($this->arg('group_id'))) {
807 return User_group::staticGet('id', $this->arg('group_id'));
809 } else if ($this->arg('group_name')) {
810 $nickname = common_canonical_nickname($this->arg('group_name'));
811 return User_group::staticGet('nickname', $nickname);
814 } else if (is_numeric($id)) {
815 return User_group::staticGet($id);
817 $nickname = common_canonical_nickname($id);
818 return User_group::staticGet('nickname', $nickname);
822 function get_profile($id)
824 if (is_numeric($id)) {
825 return Profile::staticGet($id);
827 $user = User::staticGet('nickname', $id);
829 return $user->getProfile();
836 function source_link($source)
838 $source_name = _($source);
847 $ns = Notice_source::staticGet($source);
849 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
857 * Returns query argument or default value if not found. Certain
858 * parameters used throughout the API are lightly scrubbed and
859 * bounds checked. This overrides Action::arg().
861 * @param string $key requested argument
862 * @param string $def default value to return if $key is not provided
866 function arg($key, $def=null)
869 // XXX: Do even more input validation/scrubbing?
871 if (array_key_exists($key, $this->args)) {
874 $page = (int)$this->args['page'];
875 return ($page < 1) ? 1 : $page;
877 $count = (int)$this->args['count'];
880 } elseif ($count > 200) {
886 $since_id = (int)$this->args['since_id'];
887 return ($since_id < 1) ? 0 : $since_id;
889 $max_id = (int)$this->args['max_id'];
890 return ($max_id < 1) ? 0 : $max_id;
892 return strtotime($this->args['since']);
894 return parent::arg($key, $def);