3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, Controlez-Vous, 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')) { exit(1); }
22 class TwitterapiAction extends Action
30 * @param array $args Web and URL arguments
32 * @return boolean false if user doesn't exist
35 function prepare($args)
37 parent::prepare($args);
44 * @param array $args Arguments from $_REQUEST
49 function handle($args)
51 parent::handle($args);
55 * Overrides XMLOutputter::element to write booleans as strings (true|false).
56 * See that method's documentation for more info.
58 * @param string $tag Element type or tagname
59 * @param array $attrs Array of element attributes, as
61 * @param string $content string content of the element
65 function element($tag, $attrs=null, $content=null)
67 if (is_bool($content)) {
68 $content = ($content ? 'true' : 'false');
71 return parent::element($tag, $attrs, $content);
74 function twitter_user_array($profile, $get_notice=false)
76 $twitter_user = array();
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;
84 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
85 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
86 Avatar::defaultImage(AVATAR_STREAM_SIZE);
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);
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'] = '';
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;
104 $twitter_user['created_at'] = $this->date_twitter($profile->created);
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!
111 // Need to pull up the user for some of this
112 $user = User::staticGet($profile->id);
116 if ($user->timezone) {
117 $timezone = $user->timezone;
121 $t->setTimezone(new DateTimeZone($timezone));
123 $twitter_user['utc_offset'] = $t->format('Z');
124 $twitter_user['time_zone'] = $timezone;
126 // To be supported some day, perhaps
127 $twitter_user['profile_background_image_url'] = '';
128 $twitter_user['profile_background_tile'] = false;
130 $notices = DB_DataObject::factory('notice');
131 $notices->profile_id = $profile->id;
132 $notice_count = (int) $notices->count();
134 $twitter_user['statuses_count'] = (is_int($notice_count)) ? $notice_count : 0;
136 // Is the requesting user following this user?
137 $twitter_user['following'] = false;
138 $twitter_user['notifications'] = false;
140 if (isset($apidata['user'])) {
142 $twitter_user['following'] = $apidata['user']->isSubscribed($profile);
145 $sub = Subscription::pkeyGet(array('subscriber' =>
146 $apidata['user']->id, 'subscribed' => $profile->id));
149 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
154 $notice = $profile->getCurrentNotice();
157 $twitter_user['status'] = $this->twitter_status_array($notice, false);
161 return $twitter_user;
164 function twitter_status_array($notice, $include_user=true)
166 $profile = $notice->getProfile();
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);
177 $replier_profile = null;
179 if ($notice->reply_to) {
180 $reply = Notice::staticGet(intval($notice->reply_to));
182 $replier_profile = $reply->getProfile();
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;
191 if (isset($this->auth_user)) {
192 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
194 $twitter_status['favorited'] = false;
198 # Don't get notice (recursive!)
199 $twitter_user = $this->twitter_user_array($profile, false);
200 $twitter_status['user'] = $twitter_user;
203 return $twitter_status;
206 function twitter_rss_entry_array($notice)
209 $profile = $notice->getProfile();
212 # We trim() to avoid extraneous whitespace in the output
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);
219 $taguribase = common_config('integration', 'taguri');
220 $entry['id'] = "tag:$taguribase:$entry[link]";
222 $entry['updated'] = $entry['published'];
223 $entry['author'] = $profile->getBestName();
226 $entry['description'] = $entry['content'];
227 $entry['pubDate'] = common_date_rfc2822($notice->created);
228 $entry['guid'] = $entry['link'];
233 function twitter_rss_dmsg_array($message)
238 $entry['title'] = sprintf('Message from %s to %s',
239 $message->getFrom()->nickname, $message->getTo()->nickname);
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);
245 $taguribase = common_config('integration', 'taguri');
247 $entry['id'] = "tag:$taguribase,:$entry[link]";
248 $entry['updated'] = $entry['published'];
249 $entry['author'] = $message->getFrom()->getBestName();
252 $entry['description'] = $entry['content'];
253 $entry['pubDate'] = common_date_rfc2822($message->created);
254 $entry['guid'] = $entry['link'];
259 function twitter_dmsg_array($message)
261 $twitter_dm = array();
263 $from_profile = $message->getFrom();
264 $to_profile = $message->getTo();
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);
279 function show_twitter_xml_status($twitter_status)
281 $this->elementStart('status');
282 foreach($twitter_status as $element => $value) {
285 $this->show_twitter_xml_user($twitter_status['user']);
288 $this->element($element, null, common_xml_safe_str($value));
291 $this->element($element, null, $value);
294 $this->elementEnd('status');
297 function show_twitter_xml_user($twitter_user, $role='user')
299 $this->elementStart($role);
300 foreach($twitter_user as $element => $value) {
301 if ($element == 'status') {
302 $this->show_twitter_xml_status($twitter_user['status']);
304 $this->element($element, null, $value);
307 $this->elementEnd($role);
310 function show_twitter_rss_item($entry)
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');
321 function show_json_objects($objects)
323 print(json_encode($objects));
326 function show_single_xml_status($notice)
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');
334 function show_single_json_status($notice)
336 $this->init_document('json');
337 $status = $this->twitter_status_array($notice);
338 $this->show_json_objects($status);
339 $this->end_document('json');
342 function show_single_xml_dmsg($message)
344 $this->init_document('xml');
345 $dmsg = $this->twitter_dmsg_array($message);
346 $this->show_twitter_xml_dmsg($dmsg);
347 $this->end_document('xml');
350 function show_single_json_dmsg($message)
352 $this->init_document('json');
353 $dmsg = $this->twitter_dmsg_array($message);
354 $this->show_json_objects($dmsg);
355 $this->end_document('json');
358 function show_twitter_xml_dmsg($twitter_dm)
360 $this->elementStart('direct_message');
361 foreach($twitter_dm as $element => $value) {
365 $this->show_twitter_xml_user($value, $element);
368 $this->element($element, null, common_xml_safe_str($value));
371 $this->element($element, null, $value);
374 $this->elementEnd('direct_message');
377 function show_xml_timeline($notice)
380 $this->init_document('xml');
381 $this->elementStart('statuses', array('type' => 'array'));
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);
389 while ($notice->fetch()) {
390 $twitter_status = $this->twitter_status_array($notice);
391 $this->show_twitter_xml_status($twitter_status);
395 $this->elementEnd('statuses');
396 $this->end_document('xml');
399 function show_rss_timeline($notice, $title, $link, $subtitle, $suplink=null)
402 $this->init_document('rss');
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',
412 'type' => 'application/json'));
414 $this->element('description', null, $subtitle);
415 $this->element('language', null, 'en-us');
416 $this->element('ttl', null, '40');
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);
424 while ($notice->fetch()) {
425 $entry = $this->twitter_rss_entry_array($notice);
426 $this->show_twitter_rss_item($entry);
430 $this->elementEnd('channel');
431 $this->end_twitter_rss();
434 function show_atom_timeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
437 $this->init_document('atom');
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);
443 if (!is_null($suplink)) {
444 # For FriendFeed's SUP protocol
445 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
447 'type' => 'application/json'));
450 if (!is_null($selfuri)) {
451 $this->element('link', array('href' => $selfuri,
452 'rel' => 'self', 'type' => 'application/atom+xml'), null);
455 $this->element('updated', null, common_date_iso8601('now'));
456 $this->element('subtitle', null, $subtitle);
458 if (is_array($notice)) {
459 foreach ($notice as $n) {
460 $this->raw($n->asAtomEntry());
463 while ($notice->fetch()) {
464 $this->raw($notice->asAtomEntry());
468 $this->end_document('atom');
472 function show_json_timeline($notice)
475 $this->init_document('json');
479 if (is_array($notice)) {
480 foreach ($notice as $n) {
481 $twitter_status = $this->twitter_status_array($n);
482 array_push($statuses, $twitter_status);
485 while ($notice->fetch()) {
486 $twitter_status = $this->twitter_status_array($notice);
487 array_push($statuses, $twitter_status);
491 $this->show_json_objects($statuses);
493 $this->end_document('json');
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)
501 return date("D M d H:i:s O Y", $t);
504 // XXX: Candidate for a general utility method somewhere?
505 function count_subscriptions($profile)
509 $sub = new Subscription();
510 $sub->subscribed = $profile->id;
512 $count = $sub->find();
521 function init_document($type='xml')
525 header('Content-Type: application/xml; charset=utf-8');
529 header('Content-Type: application/json; charset=utf-8');
531 // Check for JSONP callback
532 $callback = $this->arg('callback');
534 print $callback . '(';
538 header("Content-Type: application/rss+xml; charset=utf-8");
539 $this->init_twitter_rss();
542 header('Content-Type: application/atom+xml; charset=utf-8');
543 $this->init_twitter_atom();
546 $this->client_error(_('Not a supported data format.'));
553 function end_document($type='xml')
561 // Check for JSONP callback
562 $callback = $this->arg('callback');
568 $this->end_twitter_rss();
571 $this->end_twitter_rss();
574 $this->client_error(_('Not a supported data format.'));
580 function client_error($msg, $code = 400, $content_type = 'json')
583 static $status = array(400 => 'Bad Request',
584 401 => 'Unauthorized',
585 402 => 'Payment Required',
588 405 => 'Method Not Allowed',
589 406 => 'Not Acceptable',
590 407 => 'Proxy Authentication Required',
591 408 => 'Request Timeout',
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');
602 $action = $this->trimmed('action');
604 common_debug("User error '$code' on '$action': $msg", __FILE__);
606 if (!array_key_exists($code, $status)) {
610 $status_string = $status[$code];
611 header('HTTP/1.1 '.$code.' '.$status_string);
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');
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');
629 function init_twitter_rss()
632 $this->elementStart('rss', array('version' => '2.0'));
635 function end_twitter_rss()
637 $this->elementEnd('rss');
641 function init_twitter_atom()
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'));
650 function end_twitter_atom()
652 $this->elementEnd('feed');
656 function show_profile($profile, $content_type='xml', $notice=null)
658 $profile_array = $this->twitter_user_array($profile, true);
659 switch ($content_type) {
661 $this->show_twitter_xml_user($profile_array);
664 $this->show_json_objects($profile_array);
667 $this->client_error(_('Not a supported data format.'));
673 function get_user($id, $apidata=null)
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'));
689 } else if ($this->arg('screen_name')) {
690 $nickname = common_canonical_nickname($this->arg('screen_name'));
691 return User::staticGet('nickname', $nickname);
693 // Fall back to trying the currently authenticated user
694 return $apidata['user'];
697 } else if (is_numeric($id)) {
698 return User::staticGet($id);
700 $nickname = common_canonical_nickname($id);
701 return User::staticGet('nickname', $nickname);
705 function get_profile($id)
707 if (is_numeric($id)) {
708 return Profile::staticGet($id);
710 $user = User::staticGet('nickname', $id);
712 return $user->getProfile();
719 function source_link($source)
721 $source_name = _($source);
730 $ns = Notice_source::staticGet($source);
732 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';