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 $enclosures = array();
193 foreach ($attachments as $attachment) {
194 if ($attachment->isEnclosure()) {
195 $enclosure = array();
196 $enclosure['url'] = $attachment->url;
197 $enclosure['mimetype'] = $attachment->mimetype;
198 $enclosure['size'] = $attachment->size;
199 $enclosures[] = $enclosure;
203 if (!empty($enclosures)) {
204 $twitter_status['attachments'] = $enclosures;
208 # Don't get notice (recursive!)
209 $twitter_user = $this->twitter_user_array($profile, false);
210 $twitter_status['user'] = $twitter_user;
213 return $twitter_status;
216 function twitter_group_array($group)
218 $twitter_group=array();
219 $twitter_group['id']=$group->id;
220 $twitter_group['nickname']=$group->nickname;
221 $twitter_group['fullname']=$group->fullname;
222 $twitter_group['url']=$group->url;
223 $twitter_group['original_logo']=$group->original_logo;
224 $twitter_group['homepage_logo']=$group->homepage_logo;
225 $twitter_group['stream_logo']=$group->stream_logo;
226 $twitter_group['mini_logo']=$group->mini_logo;
227 $twitter_group['homepage']=$group->homepage;
228 $twitter_group['description']=$group->description;
229 $twitter_group['location']=$group->location;
230 $twitter_group['created']=$this->date_twitter($group->created);
231 $twitter_group['modified']=$this->date_twitter($group->modified);
232 return $twitter_group;
235 function twitter_rss_entry_array($notice)
237 $profile = $notice->getProfile();
240 // We trim() to avoid extraneous whitespace in the output
242 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
243 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
244 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
245 $entry['published'] = common_date_iso8601($notice->created);
247 $taguribase = common_config('integration', 'taguri');
248 $entry['id'] = "tag:$taguribase:$entry[link]";
250 $entry['updated'] = $entry['published'];
251 $entry['author'] = $profile->getBestName();
254 $attachments = $notice->attachments();
255 $enclosures = array();
257 foreach ($attachments as $attachment) {
258 if ($attachment->isEnclosure()) {
259 $enclosure = array();
260 $enclosure['url'] = $attachment->url;
261 $enclosure['mimetype'] = $attachment->mimetype;
262 $enclosure['size'] = $attachment->size;
263 $enclosures[] = $enclosure;
267 if (!empty($enclosures)) {
268 $entry['enclosures'] = $enclosures;
273 $attachments = $notice->attachments();
275 $entry['enclosures']=array();
276 foreach($attachments as $attachment){
277 if ($attachment->isEnclosure()) {
279 $enclosure['url']=$attachment->url;
280 $enclosure['mimetype']=$attachment->mimetype;
281 $enclosure['size']=$attachment->size;
282 $entry['enclosures'][]=$enclosure;
289 $tag = new Notice_tag();
290 $tag->notice_id = $notice->id;
292 $entry['tags']=array();
293 while ($tag->fetch()) {
294 $entry['tags'][]=$tag->tag;
300 $entry['description'] = $entry['content'];
301 $entry['pubDate'] = common_date_rfc2822($notice->created);
302 $entry['guid'] = $entry['link'];
307 function twitter_rss_dmsg_array($message)
312 $entry['title'] = sprintf('Message from %s to %s',
313 $message->getFrom()->nickname, $message->getTo()->nickname);
315 $entry['content'] = common_xml_safe_str(trim($message->content));
316 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
317 $entry['published'] = common_date_iso8601($message->created);
319 $taguribase = common_config('integration', 'taguri');
321 $entry['id'] = "tag:$taguribase,:$entry[link]";
322 $entry['updated'] = $entry['published'];
323 $entry['author'] = $message->getFrom()->getBestName();
326 $entry['description'] = $entry['content'];
327 $entry['pubDate'] = common_date_rfc2822($message->created);
328 $entry['guid'] = $entry['link'];
333 function twitter_dmsg_array($message)
335 $twitter_dm = array();
337 $from_profile = $message->getFrom();
338 $to_profile = $message->getTo();
340 $twitter_dm['id'] = $message->id;
341 $twitter_dm['sender_id'] = $message->from_profile;
342 $twitter_dm['text'] = trim($message->content);
343 $twitter_dm['recipient_id'] = $message->to_profile;
344 $twitter_dm['created_at'] = $this->date_twitter($message->created);
345 $twitter_dm['sender_screen_name'] = $from_profile->nickname;
346 $twitter_dm['recipient_screen_name'] = $to_profile->nickname;
347 $twitter_dm['sender'] = $this->twitter_user_array($from_profile, false);
348 $twitter_dm['recipient'] = $this->twitter_user_array($to_profile, false);
353 function twitter_relationship_array($source, $target)
355 $relationship = array();
357 $relationship['source'] =
358 $this->relationship_details_array($source, $target);
359 $relationship['target'] =
360 $this->relationship_details_array($target, $source);
362 return array('relationship' => $relationship);
365 function relationship_details_array($source, $target)
369 $details['screen_name'] = $source->nickname;
370 $details['followed_by'] = $target->isSubscribed($source);
371 $details['following'] = $source->isSubscribed($target);
373 $notifications = false;
375 if ($source->isSubscribed($target)) {
377 $sub = Subscription::pkeyGet(array('subscriber' =>
378 $source->id, 'subscribed' => $target->id));
381 $notifications = ($sub->jabber || $sub->sms);
385 $details['notifications_enabled'] = $notifications;
386 $details['blocking'] = $source->hasBlocked($target);
387 $details['id'] = $source->id;
392 function show_twitter_xml_relationship($relationship)
394 $this->elementStart('relationship');
396 foreach($relationship as $element => $value) {
397 if ($element == 'source' || $element == 'target') {
398 $this->elementStart($element);
399 $this->show_xml_relationship_details($value);
400 $this->elementEnd($element);
404 $this->elementEnd('relationship');
407 function show_xml_relationship_details($details)
409 foreach($details as $element => $value) {
410 $this->element($element, null, $value);
414 function show_twitter_xml_status($twitter_status)
416 $this->elementStart('status');
417 foreach($twitter_status as $element => $value) {
420 $this->show_twitter_xml_user($twitter_status['user']);
423 $this->element($element, null, common_xml_safe_str($value));
426 $this->show_xml_attachments($twitter_status['attachments']);
429 $this->element($element, null, $value);
432 $this->elementEnd('status');
435 function show_twitter_xml_group($twitter_group)
437 $this->elementStart('group');
438 foreach($twitter_group as $element => $value) {
439 $this->element($element, null, $value);
441 $this->elementEnd('group');
444 function show_twitter_xml_user($twitter_user, $role='user')
446 $this->elementStart($role);
447 foreach($twitter_user as $element => $value) {
448 if ($element == 'status') {
449 $this->show_twitter_xml_status($twitter_user['status']);
451 $this->element($element, null, $value);
454 $this->elementEnd($role);
457 function show_xml_attachments($attachments) {
458 if (!empty($attachments)) {
459 $this->elementStart('attachments', array('type' => 'array'));
460 foreach ($attachments as $attachment) {
462 $attrs['url'] = $attachment['url'];
463 $attrs['mimetype'] = $attachment['mimetype'];
464 $attrs['size'] = $attachment['size'];
465 $this->element('enclosure', $attrs, '');
467 $this->elementEnd('attachments');
471 function show_twitter_rss_item($entry)
473 $this->elementStart('item');
474 $this->element('title', null, $entry['title']);
475 $this->element('description', null, $entry['description']);
476 $this->element('pubDate', null, $entry['pubDate']);
477 $this->element('guid', null, $entry['guid']);
478 $this->element('link', null, $entry['link']);
480 # RSS only supports 1 enclosure per item
481 if($entry['enclosures']){
482 $enclosure = $entry['enclosures'][0];
483 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
487 foreach($entry['tags'] as $tag){
488 $this->element('category', null,$tag);
492 $this->elementEnd('item');
495 function show_json_objects($objects)
497 print(json_encode($objects));
500 function show_single_xml_status($notice)
502 $this->init_document('xml');
503 $twitter_status = $this->twitter_status_array($notice);
504 $this->show_twitter_xml_status($twitter_status);
505 $this->end_document('xml');
508 function show_single_json_status($notice)
510 $this->init_document('json');
511 $status = $this->twitter_status_array($notice);
512 $this->show_json_objects($status);
513 $this->end_document('json');
516 function show_single_xml_dmsg($message)
518 $this->init_document('xml');
519 $dmsg = $this->twitter_dmsg_array($message);
520 $this->show_twitter_xml_dmsg($dmsg);
521 $this->end_document('xml');
524 function show_single_json_dmsg($message)
526 $this->init_document('json');
527 $dmsg = $this->twitter_dmsg_array($message);
528 $this->show_json_objects($dmsg);
529 $this->end_document('json');
532 function show_twitter_xml_dmsg($twitter_dm)
534 $this->elementStart('direct_message');
535 foreach($twitter_dm as $element => $value) {
539 $this->show_twitter_xml_user($value, $element);
542 $this->element($element, null, common_xml_safe_str($value));
545 $this->element($element, null, $value);
548 $this->elementEnd('direct_message');
551 function show_xml_timeline($notice)
554 $this->init_document('xml');
555 $this->elementStart('statuses', array('type' => 'array'));
557 if (is_array($notice)) {
558 foreach ($notice as $n) {
559 $twitter_status = $this->twitter_status_array($n);
560 $this->show_twitter_xml_status($twitter_status);
563 while ($notice->fetch()) {
564 $twitter_status = $this->twitter_status_array($notice);
565 $this->show_twitter_xml_status($twitter_status);
569 $this->elementEnd('statuses');
570 $this->end_document('xml');
573 function show_rss_timeline($notice, $title, $link, $subtitle, $suplink=null)
576 $this->init_document('rss');
578 $this->elementStart('channel');
579 $this->element('title', null, $title);
580 $this->element('link', null, $link);
581 if (!is_null($suplink)) {
582 # For FriendFeed's SUP protocol
583 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
584 'rel' => 'http://api.friendfeed.com/2008/03#sup',
586 'type' => 'application/json'));
588 $this->element('description', null, $subtitle);
589 $this->element('language', null, 'en-us');
590 $this->element('ttl', null, '40');
592 if (is_array($notice)) {
593 foreach ($notice as $n) {
594 $entry = $this->twitter_rss_entry_array($n);
595 $this->show_twitter_rss_item($entry);
598 while ($notice->fetch()) {
599 $entry = $this->twitter_rss_entry_array($notice);
600 $this->show_twitter_rss_item($entry);
604 $this->elementEnd('channel');
605 $this->end_twitter_rss();
608 function show_atom_timeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
611 $this->init_document('atom');
613 $this->element('title', null, $title);
614 $this->element('id', null, $id);
615 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
617 if (!is_null($suplink)) {
618 # For FriendFeed's SUP protocol
619 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
621 'type' => 'application/json'));
624 if (!is_null($selfuri)) {
625 $this->element('link', array('href' => $selfuri,
626 'rel' => 'self', 'type' => 'application/atom+xml'), null);
629 $this->element('updated', null, common_date_iso8601('now'));
630 $this->element('subtitle', null, $subtitle);
632 if (is_array($notice)) {
633 foreach ($notice as $n) {
634 $this->raw($n->asAtomEntry());
637 while ($notice->fetch()) {
638 $this->raw($notice->asAtomEntry());
642 $this->end_document('atom');
646 function show_json_timeline($notice)
649 $this->init_document('json');
653 if (is_array($notice)) {
654 foreach ($notice as $n) {
655 $twitter_status = $this->twitter_status_array($n);
656 array_push($statuses, $twitter_status);
659 while ($notice->fetch()) {
660 $twitter_status = $this->twitter_status_array($notice);
661 array_push($statuses, $twitter_status);
665 $this->show_json_objects($statuses);
667 $this->end_document('json');
670 function show_single_json_group($group)
672 $this->init_document('json');
673 $twitter_group = $this->twitter_group_array($group);
674 $this->show_json_objects($twitter_group);
675 $this->end_document('json');
678 function show_single_xml_group($group)
680 $this->init_document('xml');
681 $twitter_group = $this->twitter_group_array($group);
682 $this->show_twitter_xml_group($twitter_group);
683 $this->end_document('xml');
686 // Anyone know what date format this is?
687 // Twitter's dates look like this: "Mon Jul 14 23:52:38 +0000 2008" -- Zach
688 function date_twitter($dt)
691 return date("D M d H:i:s O Y", $t);
694 // XXX: Candidate for a general utility method somewhere?
695 function count_subscriptions($profile)
699 $sub = new Subscription();
700 $sub->subscribed = $profile->id;
702 $count = $sub->find();
711 function init_document($type='xml')
715 header('Content-Type: application/xml; charset=utf-8');
719 header('Content-Type: application/json; charset=utf-8');
721 // Check for JSONP callback
722 $callback = $this->arg('callback');
724 print $callback . '(';
728 header("Content-Type: application/rss+xml; charset=utf-8");
729 $this->init_twitter_rss();
732 header('Content-Type: application/atom+xml; charset=utf-8');
733 $this->init_twitter_atom();
736 $this->clientError(_('Not a supported data format.'));
743 function end_document($type='xml')
751 // Check for JSONP callback
752 $callback = $this->arg('callback');
758 $this->end_twitter_rss();
761 $this->end_twitter_rss();
764 $this->clientError(_('Not a supported data format.'));
770 function clientError($msg, $code = 400, $content_type = 'json')
773 static $status = array(400 => 'Bad Request',
774 401 => 'Unauthorized',
775 402 => 'Payment Required',
778 405 => 'Method Not Allowed',
779 406 => 'Not Acceptable',
780 407 => 'Proxy Authentication Required',
781 408 => 'Request Timeout',
784 411 => 'Length Required',
785 412 => 'Precondition Failed',
786 413 => 'Request Entity Too Large',
787 414 => 'Request-URI Too Long',
788 415 => 'Unsupported Media Type',
789 416 => 'Requested Range Not Satisfiable',
790 417 => 'Expectation Failed');
792 $action = $this->trimmed('action');
794 common_debug("User error '$code' on '$action': $msg", __FILE__);
796 if (!array_key_exists($code, $status)) {
800 $status_string = $status[$code];
801 header('HTTP/1.1 '.$code.' '.$status_string);
803 if ($content_type == 'xml') {
804 $this->init_document('xml');
805 $this->elementStart('hash');
806 $this->element('error', null, $msg);
807 $this->element('request', null, $_SERVER['REQUEST_URI']);
808 $this->elementEnd('hash');
809 $this->end_document('xml');
811 $this->init_document('json');
812 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
813 print(json_encode($error_array));
814 $this->end_document('json');
819 function init_twitter_rss()
822 $this->elementStart('rss', array('version' => '2.0'));
825 function end_twitter_rss()
827 $this->elementEnd('rss');
831 function init_twitter_atom()
834 // FIXME: don't hardcode the language here!
835 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
836 'xml:lang' => 'en-US',
837 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
840 function end_twitter_atom()
842 $this->elementEnd('feed');
846 function show_profile($profile, $content_type='xml', $notice=null)
848 $profile_array = $this->twitter_user_array($profile, true);
849 switch ($content_type) {
851 $this->show_twitter_xml_user($profile_array);
854 $this->show_json_objects($profile_array);
857 $this->clientError(_('Not a supported data format.'));
863 function get_user($id, $apidata=null)
867 // Twitter supports these other ways of passing the user ID
868 if (is_numeric($this->arg('id'))) {
869 return User::staticGet($this->arg('id'));
870 } else if ($this->arg('id')) {
871 $nickname = common_canonical_nickname($this->arg('id'));
872 return User::staticGet('nickname', $nickname);
873 } else if ($this->arg('user_id')) {
874 // This is to ensure that a non-numeric user_id still
875 // overrides screen_name even if it doesn't get used
876 if (is_numeric($this->arg('user_id'))) {
877 return User::staticGet('id', $this->arg('user_id'));
879 } else if ($this->arg('screen_name')) {
880 $nickname = common_canonical_nickname($this->arg('screen_name'));
881 return User::staticGet('nickname', $nickname);
883 // Fall back to trying the currently authenticated user
884 return $apidata['user'];
887 } else if (is_numeric($id)) {
888 return User::staticGet($id);
890 $nickname = common_canonical_nickname($id);
891 return User::staticGet('nickname', $nickname);
895 function get_group($id, $apidata=null)
899 if (is_numeric($this->arg('id'))) {
900 return User_group::staticGet($this->arg('id'));
901 } else if ($this->arg('id')) {
902 $nickname = common_canonical_nickname($this->arg('id'));
903 return User_group::staticGet('nickname', $nickname);
904 } else if ($this->arg('group_id')) {
905 // This is to ensure that a non-numeric user_id still
906 // overrides screen_name even if it doesn't get used
907 if (is_numeric($this->arg('group_id'))) {
908 return User_group::staticGet('id', $this->arg('group_id'));
910 } else if ($this->arg('group_name')) {
911 $nickname = common_canonical_nickname($this->arg('group_name'));
912 return User_group::staticGet('nickname', $nickname);
915 } else if (is_numeric($id)) {
916 return User_group::staticGet($id);
918 $nickname = common_canonical_nickname($id);
919 return User_group::staticGet('nickname', $nickname);
923 function get_profile($id)
925 if (is_numeric($id)) {
926 return Profile::staticGet($id);
928 $user = User::staticGet('nickname', $id);
930 return $user->getProfile();
937 function source_link($source)
939 $source_name = _($source);
948 $ns = Notice_source::staticGet($source);
950 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
958 * Returns query argument or default value if not found. Certain
959 * parameters used throughout the API are lightly scrubbed and
960 * bounds checked. This overrides Action::arg().
962 * @param string $key requested argument
963 * @param string $def default value to return if $key is not provided
967 function arg($key, $def=null)
970 // XXX: Do even more input validation/scrubbing?
972 if (array_key_exists($key, $this->args)) {
975 $page = (int)$this->args['page'];
976 return ($page < 1) ? 1 : $page;
978 $count = (int)$this->args['count'];
981 } elseif ($count > 200) {
987 $since_id = (int)$this->args['since_id'];
988 return ($since_id < 1) ? 0 : $since_id;
990 $max_id = (int)$this->args['max_id'];
991 return ($max_id < 1) ? 0 : $max_id;
993 return strtotime($this->args['since']);
995 return parent::arg($key, $def);