]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/api.php
Merge commit 'refs/merge-requests/1815' of git://gitorious.org/statusnet/mainline...
[quix0rs-gnu-social.git] / lib / api.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Base API action
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  API
23  * @package   StatusNet
24  * @author    Craig Andrews <candrews@integralblue.com>
25  * @author    Dan Moore <dan@moore.cx>
26  * @author    Evan Prodromou <evan@status.net>
27  * @author    Jeffery To <jeffery.to@gmail.com>
28  * @author    Toby Inkster <mail@tobyinkster.co.uk>
29  * @author    Zach Copley <zach@status.net>
30  * @copyright 2009 StatusNet, Inc.
31  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
32  * @link      http://status.net/
33  */
34
35 if (!defined('STATUSNET')) {
36     exit(1);
37 }
38
39 /**
40  * Contains most of the Twitter-compatible API output functions.
41  *
42  * @category API
43  * @package  StatusNet
44  * @author   Craig Andrews <candrews@integralblue.com>
45  * @author   Dan Moore <dan@moore.cx>
46  * @author   Evan Prodromou <evan@status.net>
47  * @author   Jeffery To <jeffery.to@gmail.com>
48  * @author   Toby Inkster <mail@tobyinkster.co.uk>
49  * @author   Zach Copley <zach@status.net>
50  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
51  * @link     http://status.net/
52  */
53
54 class ApiAction extends Action
55 {
56      var $format   = null;
57      var $user     = null;
58      var $page     = null;
59      var $count    = null;
60      var $max_id   = null;
61      var $since_id = null;
62      var $since    = null;
63      
64     /**
65      * Initialization.
66      *
67      * @param array $args Web and URL arguments
68      *
69      * @return boolean false if user doesn't exist
70      */
71
72     function prepare($args)
73     {
74         parent::prepare($args);
75         
76         $this->format   = $this->arg('format');
77         $this->page     = (int)$this->arg('page', 1);
78         $this->count    = (int)$this->arg('count', 20);
79         $this->max_id   = (int)$this->arg('max_id', 0);
80         $this->since_id = (int)$this->arg('since_id', 0);
81         $this->since    = $this->arg('since');
82         
83         return true;
84     }
85
86     /**
87      * Handle a request
88      *
89      * @param array $args Arguments from $_REQUEST
90      *
91      * @return void
92      */
93
94     function handle($args)
95     {
96         parent::handle($args);
97     }
98
99     /**
100      * Overrides XMLOutputter::element to write booleans as strings (true|false).
101      * See that method's documentation for more info.
102      *
103      * @param string $tag     Element type or tagname
104      * @param array  $attrs   Array of element attributes, as
105      *                        key-value pairs
106      * @param string $content string content of the element
107      *
108      * @return void
109      */
110     function element($tag, $attrs=null, $content=null)
111     {
112         if (is_bool($content)) {
113             $content = ($content ? 'true' : 'false');
114         }
115
116         return parent::element($tag, $attrs, $content);
117     }
118
119     function twitterUserArray($profile, $get_notice=false)
120     {
121         $twitter_user = array();
122
123         $twitter_user['id'] = intval($profile->id);
124         $twitter_user['name'] = $profile->getBestName();
125         $twitter_user['screen_name'] = $profile->nickname;
126         $twitter_user['location'] = ($profile->location) ? $profile->location : null;
127         $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
128
129         $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
130         $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
131             Avatar::defaultImage(AVATAR_STREAM_SIZE);
132
133         $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
134         $twitter_user['protected'] = false; # not supported by StatusNet yet
135         $twitter_user['followers_count'] = $profile->subscriberCount();
136
137         // Need to pull up the user for some of this
138         $user = $profile->getUser();
139         $design = $user->getDesign();
140         $defaultDesign = Design::siteDesign();
141         if (!$design) $design = $defaultDesign;
142         $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
143         $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
144         $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
145         $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
146         $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
147         $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
148         $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
149         $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
150         $twitter_user['profile_sidebar_border_color'] = '';
151
152         $twitter_user['friends_count'] = $profile->subscriptionCount();
153
154         $twitter_user['created_at'] = $this->dateTwitter($profile->created);
155
156         $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
157
158
159         $timezone = 'UTC';
160
161         if ($user->timezone) {
162             $timezone = $user->timezone;
163         }
164
165         $t = new DateTime;
166         $t->setTimezone(new DateTimeZone($timezone));
167
168         $twitter_user['utc_offset'] = $t->format('Z');
169         $twitter_user['time_zone'] = $timezone;
170
171         // To be supported some day, perhaps
172         $twitter_user['profile_background_image_url'] = '';
173         $twitter_user['profile_background_tile'] = false;
174
175         $twitter_user['statuses_count'] = $profile->noticeCount();
176
177         // Is the requesting user following this user?
178         $twitter_user['following'] = false;
179         $twitter_user['notifications'] = false;
180
181         if (isset($apidata['user'])) {
182
183             $twitter_user['following'] = $apidata['user']->isSubscribed($profile);
184
185             // Notifications on?
186             $sub = Subscription::pkeyGet(array('subscriber' =>
187                 $apidata['user']->id, 'subscribed' => $profile->id));
188
189             if ($sub) {
190                 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
191             }
192         }
193
194         if ($get_notice) {
195             $notice = $profile->getCurrentNotice();
196             if ($notice) {
197                 # don't get user!
198                 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
199             }
200         }
201
202         return $twitter_user;
203     }
204
205     function twitterStatusArray($notice, $include_user=true)
206     {
207         $profile = $notice->getProfile();
208
209         $twitter_status = array();
210         $twitter_status['text'] = $notice->content;
211         $twitter_status['truncated'] = false; # Not possible on StatusNet
212         $twitter_status['created_at'] = $this->dateTwitter($notice->created);
213         $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
214             intval($notice->reply_to) : null;
215         $twitter_status['source'] = $this->sourceLink($notice->source);
216         $twitter_status['id'] = intval($notice->id);
217
218         $replier_profile = null;
219
220         if ($notice->reply_to) {
221             $reply = Notice::staticGet(intval($notice->reply_to));
222             if ($reply) {
223                 $replier_profile = $reply->getProfile();
224             }
225         }
226
227         $twitter_status['in_reply_to_user_id'] =
228             ($replier_profile) ? intval($replier_profile->id) : null;
229         $twitter_status['in_reply_to_screen_name'] =
230             ($replier_profile) ? $replier_profile->nickname : null;
231
232         if (isset($this->auth_user)) {
233             $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
234         } else {
235             $twitter_status['favorited'] = false;
236         }
237
238         // Enclosures
239         $attachments = $notice->attachments();
240
241         if (!empty($attachments)) {
242
243             $twitter_status['attachments'] = array();
244
245             foreach ($attachments as $attachment) {
246                 if ($attachment->isEnclosure()) {
247                     $enclosure = array();
248                     $enclosure['url'] = $attachment->url;
249                     $enclosure['mimetype'] = $attachment->mimetype;
250                     $enclosure['size'] = $attachment->size;
251                     $twitter_status['attachments'][] = $enclosure;
252                 }
253             }
254         }
255
256         if ($include_user) {
257             # Don't get notice (recursive!)
258             $twitter_user = $this->twitterUserArray($profile, false);
259             $twitter_status['user'] = $twitter_user;
260         }
261
262         return $twitter_status;
263     }
264
265     function twitterGroupArray($group)
266     {
267         $twitter_group=array();
268         $twitter_group['id']=$group->id;
269         $twitter_group['url']=$group->permalink();
270         $twitter_group['nickname']=$group->nickname;
271         $twitter_group['fullname']=$group->fullname;
272         $twitter_group['homepage_url']=$group->homepage_url;
273         $twitter_group['original_logo']=$group->original_logo;
274         $twitter_group['homepage_logo']=$group->homepage_logo;
275         $twitter_group['stream_logo']=$group->stream_logo;
276         $twitter_group['mini_logo']=$group->mini_logo;
277         $twitter_group['homepage']=$group->homepage;
278         $twitter_group['description']=$group->description;
279         $twitter_group['location']=$group->location;
280         $twitter_group['created']=$this->dateTwitter($group->created);
281         $twitter_group['modified']=$this->dateTwitter($group->modified);
282         return $twitter_group;
283     }
284
285     function twitterRssGroupArray($group)
286     {
287         $entry = array();
288         $entry['content']=$group->description;
289         $entry['title']=$group->nickname;
290         $entry['link']=$group->permalink();
291         $entry['published']=common_date_iso8601($group->created);
292         $entry['updated']==common_date_iso8601($group->modified);
293         $taguribase = common_config('integration', 'groupuri');
294         $entry['id'] = "group:$groupuribase:$entry[link]";
295
296         $entry['description'] = $entry['content'];
297         $entry['pubDate'] = common_date_rfc2822($group->created);
298         $entry['guid'] = $entry['link'];
299
300         return $entry;
301     }
302
303     function twitterRssEntryArray($notice)
304     {
305         $profile = $notice->getProfile();
306         $entry = array();
307
308         // We trim() to avoid extraneous whitespace in the output
309
310         $entry['content'] = common_xml_safe_str(trim($notice->rendered));
311         $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
312         $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
313         $entry['published'] = common_date_iso8601($notice->created);
314
315         $taguribase = common_config('integration', 'taguri');
316         $entry['id'] = "tag:$taguribase:$entry[link]";
317
318         $entry['updated'] = $entry['published'];
319         $entry['author'] = $profile->getBestName();
320
321         // Enclosures
322         $attachments = $notice->attachments();
323         $enclosures = array();
324
325         foreach ($attachments as $attachment) {
326             $enclosure_o=$attachment->getEnclosure();
327             if ($enclosure_o) {
328                  $enclosure = array();
329                  $enclosure['url'] = $enclosure_o->url;
330                  $enclosure['mimetype'] = $enclosure_o->mimetype;
331                  $enclosure['size'] = $enclosure_o->size;
332                  $enclosures[] = $enclosure;
333             }
334         }
335
336         if (!empty($enclosures)) {
337             $entry['enclosures'] = $enclosures;
338         }
339
340         // Tags/Categories
341         $tag = new Notice_tag();
342         $tag->notice_id = $notice->id;
343         if ($tag->find()) {
344             $entry['tags']=array();
345             while ($tag->fetch()) {
346                 $entry['tags'][]=$tag->tag;
347             }
348         }
349         $tag->free();
350
351         // RSS Item specific
352         $entry['description'] = $entry['content'];
353         $entry['pubDate'] = common_date_rfc2822($notice->created);
354         $entry['guid'] = $entry['link'];
355
356         return $entry;
357     }
358
359
360     function twitterRelationshipArray($source, $target)
361     {
362         $relationship = array();
363
364         $relationship['source'] =
365             $this->relationshipDetailsArray($source, $target);
366         $relationship['target'] =
367             $this->relationshipDetailsArray($target, $source);
368
369         return array('relationship' => $relationship);
370     }
371
372     function relationshipDetailsArray($source, $target)
373     {
374         $details = array();
375
376         $details['screen_name'] = $source->nickname;
377         $details['followed_by'] = $target->isSubscribed($source);
378         $details['following'] = $source->isSubscribed($target);
379
380         $notifications = false;
381
382         if ($source->isSubscribed($target)) {
383
384             $sub = Subscription::pkeyGet(array('subscriber' =>
385                 $source->id, 'subscribed' => $target->id));
386
387             if (!empty($sub)) {
388                 $notifications = ($sub->jabber || $sub->sms);
389             }
390         }
391
392         $details['notifications_enabled'] = $notifications;
393         $details['blocking'] = $source->hasBlocked($target);
394         $details['id'] = $source->id;
395
396         return $details;
397     }
398
399     function showTwitterXmlRelationship($relationship)
400     {
401         $this->elementStart('relationship');
402
403         foreach($relationship as $element => $value) {
404             if ($element == 'source' || $element == 'target') {
405                 $this->elementStart($element);
406                 $this->showXmlRelationshipDetails($value);
407                 $this->elementEnd($element);
408             }
409         }
410
411         $this->elementEnd('relationship');
412     }
413
414     function showXmlRelationshipDetails($details)
415     {
416         foreach($details as $element => $value) {
417             $this->element($element, null, $value);
418         }
419     }
420
421     function showTwitterXmlStatus($twitter_status)
422     {
423         $this->elementStart('status');
424         foreach($twitter_status as $element => $value) {
425             switch ($element) {
426             case 'user':
427                 $this->showTwitterXmlUser($twitter_status['user']);
428                 break;
429             case 'text':
430                 $this->element($element, null, common_xml_safe_str($value));
431                 break;
432             case 'attachments':
433                 $this->showXmlAttachments($twitter_status['attachments']);
434                 break;
435             default:
436                 $this->element($element, null, $value);
437             }
438         }
439         $this->elementEnd('status');
440     }
441
442     function showTwitterXmlGroup($twitter_group)
443     {
444         $this->elementStart('group');
445         foreach($twitter_group as $element => $value) {
446             $this->element($element, null, $value);
447         }
448         $this->elementEnd('group');
449     }
450
451     function showTwitterXmlUser($twitter_user, $role='user')
452     {
453         $this->elementStart($role);
454         foreach($twitter_user as $element => $value) {
455             if ($element == 'status') {
456                 $this->showTwitterXmlStatus($twitter_user['status']);
457             } else {
458                 $this->element($element, null, $value);
459             }
460         }
461         $this->elementEnd($role);
462     }
463
464     function showXmlAttachments($attachments) {
465         if (!empty($attachments)) {
466             $this->elementStart('attachments', array('type' => 'array'));
467             foreach ($attachments as $attachment) {
468                 $attrs = array();
469                 $attrs['url'] = $attachment['url'];
470                 $attrs['mimetype'] = $attachment['mimetype'];
471                 $attrs['size'] = $attachment['size'];
472                 $this->element('enclosure', $attrs, '');
473             }
474             $this->elementEnd('attachments');
475         }
476     }
477
478     function showTwitterRssItem($entry)
479     {
480         $this->elementStart('item');
481         $this->element('title', null, $entry['title']);
482         $this->element('description', null, $entry['description']);
483         $this->element('pubDate', null, $entry['pubDate']);
484         $this->element('guid', null, $entry['guid']);
485         $this->element('link', null, $entry['link']);
486
487         # RSS only supports 1 enclosure per item
488         if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
489             $enclosure = $entry['enclosures'][0];
490             $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
491         }
492
493         if(array_key_exists('tags', $entry)){
494             foreach($entry['tags'] as $tag){
495                 $this->element('category', null,$tag);
496             }
497         }
498
499         $this->elementEnd('item');
500     }
501
502     function showJsonObjects($objects)
503     {
504         print(json_encode($objects));
505     }
506
507     function showSingleXmlStatus($notice)
508     {
509         $this->initDocument('xml');
510         $twitter_status = $this->twitterStatusArray($notice);
511         $this->showTwitterXmlStatus($twitter_status);
512         $this->endDocument('xml');
513     }
514
515     function show_single_json_status($notice)
516     {
517         $this->initDocument('json');
518         $status = $this->twitterStatusArray($notice);
519         $this->showJsonObjects($status);
520         $this->endDocument('json');
521     }
522
523
524     function showXmlTimeline($notice)
525     {
526
527         $this->initDocument('xml');
528         $this->elementStart('statuses', array('type' => 'array'));
529
530         if (is_array($notice)) {
531             foreach ($notice as $n) {
532                 $twitter_status = $this->twitterStatusArray($n);
533                 $this->showTwitterXmlStatus($twitter_status);
534             }
535         } else {
536             while ($notice->fetch()) {
537                 $twitter_status = $this->twitterStatusArray($notice);
538                 $this->showTwitterXmlStatus($twitter_status);
539             }
540         }
541
542         $this->elementEnd('statuses');
543         $this->endDocument('xml');
544     }
545
546     function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null)
547     {
548
549         $this->initDocument('rss');
550
551         $this->element('title', null, $title);
552         $this->element('link', null, $link);
553         if (!is_null($suplink)) {
554             // For FriendFeed's SUP protocol
555             $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
556                                          'rel' => 'http://api.friendfeed.com/2008/03#sup',
557                                          'href' => $suplink,
558                                          'type' => 'application/json'));
559         }
560         $this->element('description', null, $subtitle);
561         $this->element('language', null, 'en-us');
562         $this->element('ttl', null, '40');
563
564         if (is_array($notice)) {
565             foreach ($notice as $n) {
566                 $entry = $this->twitterRssEntryArray($n);
567                 $this->showTwitterRssItem($entry);
568             }
569         } else {
570             while ($notice->fetch()) {
571                 $entry = $this->twitterRssEntryArray($notice);
572                 $this->showTwitterRssItem($entry);
573             }
574         }
575
576         $this->endTwitterRss();
577     }
578
579     function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
580     {
581
582         $this->initDocument('atom');
583
584         $this->element('title', null, $title);
585         $this->element('id', null, $id);
586         $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
587
588         if (!is_null($suplink)) {
589             # For FriendFeed's SUP protocol
590             $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
591                                          'href' => $suplink,
592                                          'type' => 'application/json'));
593         }
594
595         if (!is_null($selfuri)) {
596             $this->element('link', array('href' => $selfuri,
597                 'rel' => 'self', 'type' => 'application/atom+xml'), null);
598         }
599
600         $this->element('updated', null, common_date_iso8601('now'));
601         $this->element('subtitle', null, $subtitle);
602
603         if (is_array($notice)) {
604             foreach ($notice as $n) {
605                 $this->raw($n->asAtomEntry());
606             }
607         } else {
608             while ($notice->fetch()) {
609                 $this->raw($notice->asAtomEntry());
610             }
611         }
612
613         $this->endDocument('atom');
614
615     }
616
617     function showRssGroups($group, $title, $link, $subtitle)
618     {
619
620         $this->initDocument('rss');
621
622         $this->element('title', null, $title);
623         $this->element('link', null, $link);
624         $this->element('description', null, $subtitle);
625         $this->element('language', null, 'en-us');
626         $this->element('ttl', null, '40');
627
628         if (is_array($group)) {
629             foreach ($group as $g) {
630                 $twitter_group = $this->twitterRssGroupArray($g);
631                 $this->showTwitterRssItem($twitter_group);
632             }
633         } else {
634             while ($group->fetch()) {
635                 $twitter_group = $this->twitterRssGroupArray($group);
636                 $this->showTwitterRssItem($twitter_group);
637             }
638         }
639
640         $this->endTwitterRss();
641     }
642
643
644     function showTwitterAtomEntry($entry)
645     {
646         $this->elementStart('entry');
647         $this->element('title', null, $entry['title']);
648         $this->element('content', array('type' => 'html'), $entry['content']);
649         $this->element('id', null, $entry['id']);
650         $this->element('published', null, $entry['published']);
651         $this->element('updated', null, $entry['updated']);
652         $this->element('link', array('type' => 'text/html',
653                                      'href' => $entry['link'],
654                                      'rel' => 'alternate'));
655         $this->element('link', array('type' => $entry['avatar-type'],
656                                      'href' => $entry['avatar'],
657                                      'rel' => 'image'));
658         $this->elementStart('author');
659
660         $this->element('name', null, $entry['author-name']);
661         $this->element('uri', null, $entry['author-uri']);
662
663         $this->elementEnd('author');
664         $this->elementEnd('entry');
665     }
666
667     function showXmlDirectMessage($dm)
668     {
669         $this->elementStart('direct_message');
670         foreach($dm as $element => $value) {
671             switch ($element) {
672             case 'sender':
673             case 'recipient':
674                 $this->showTwitterXmlUser($value, $element);
675                 break;
676             case 'text':
677                 $this->element($element, null, common_xml_safe_str($value));
678                 break;
679             default:
680                 $this->element($element, null, $value);
681                 break;
682             }
683         }
684         $this->elementEnd('direct_message');
685     }
686
687     function directMessageArray($message)
688     {
689         $dmsg = array();
690
691         $from_profile = $message->getFrom();
692         $to_profile = $message->getTo();
693
694         $dmsg['id'] = $message->id;
695         $dmsg['sender_id'] = $message->from_profile;
696         $dmsg['text'] = trim($message->content);
697         $dmsg['recipient_id'] = $message->to_profile;
698         $dmsg['created_at'] = $this->dateTwitter($message->created);
699         $dmsg['sender_screen_name'] = $from_profile->nickname;
700         $dmsg['recipient_screen_name'] = $to_profile->nickname;
701         $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
702         $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
703
704         return $dmsg;
705     }
706
707     function rssDirectMessageArray($message)
708     {
709         $entry = array();
710
711         $from = $message->getFrom();
712
713         $entry['title'] = sprintf('Message from %s to %s',
714             $from->nickname, $message->getTo()->nickname);
715
716         $entry['content'] = common_xml_safe_str($message->rendered);
717         $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
718         $entry['published'] = common_date_iso8601($message->created);
719
720         $taguribase = common_config('integration', 'taguri');
721
722         $entry['id'] = "tag:$taguribase:$entry[link]";
723         $entry['updated'] = $entry['published'];
724
725         $entry['author-name'] = $from->getBestName();
726         $entry['author-uri'] = $from->homepage;
727
728         $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
729
730         $entry['avatar']      = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
731         $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
732
733         // RSS item specific
734
735         $entry['description'] = $entry['content'];
736         $entry['pubDate'] = common_date_rfc2822($message->created);
737         $entry['guid'] = $entry['link'];
738
739         return $entry;
740     }
741
742     function showSingleXmlDirectMessage($message)
743     {
744         $this->initDocument('xml');
745         $dmsg = $this->directMessageArray($message);
746         $this->showXmlDirectMessage($dmsg);
747         $this->endDocument('xml');
748     }
749
750     function showSingleJsonDirectMessage($message)
751     {
752         $this->initDocument('json');
753         $dmsg = $this->directMessageArray($message);
754         $this->showJsonObjects($dmsg);
755         $this->endDocument('json');
756     }
757
758     function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
759     {
760
761         $this->initDocument('atom');
762
763         $this->element('title', null, $title);
764         $this->element('id', null, $id);
765         $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
766
767         if (!is_null($selfuri)) {
768             $this->element('link', array('href' => $selfuri,
769                 'rel' => 'self', 'type' => 'application/atom+xml'), null);
770         }
771
772         $this->element('updated', null, common_date_iso8601('now'));
773         $this->element('subtitle', null, $subtitle);
774
775         if (is_array($group)) {
776             foreach ($group as $g) {
777                 $this->raw($g->asAtomEntry());
778             }
779         } else {
780             while ($group->fetch()) {
781                 $this->raw($group->asAtomEntry());
782             }
783         }
784
785         $this->endDocument('atom');
786
787     }
788
789     function showJsonTimeline($notice)
790     {
791
792         $this->initDocument('json');
793
794         $statuses = array();
795
796         if (is_array($notice)) {
797             foreach ($notice as $n) {
798                 $twitter_status = $this->twitterStatusArray($n);
799                 array_push($statuses, $twitter_status);
800             }
801         } else {
802             while ($notice->fetch()) {
803                 $twitter_status = $this->twitterStatusArray($notice);
804                 array_push($statuses, $twitter_status);
805             }
806         }
807
808         $this->showJsonObjects($statuses);
809
810         $this->endDocument('json');
811     }
812
813     function showJsonGroups($group)
814     {
815
816         $this->initDocument('json');
817
818         $groups = array();
819
820         if (is_array($group)) {
821             foreach ($group as $g) {
822                 $twitter_group = $this->twitterGroupArray($g);
823                 array_push($groups, $twitter_group);
824             }
825         } else {
826             while ($group->fetch()) {
827                 $twitter_group = $this->twitterGroupArray($group);
828                 array_push($groups, $twitter_group);
829             }
830         }
831
832         $this->showJsonObjects($groups);
833
834         $this->endDocument('json');
835     }
836
837     function showXmlGroups($group)
838     {
839
840         $this->initDocument('xml');
841         $this->elementStart('groups', array('type' => 'array'));
842
843         if (is_array($group)) {
844             foreach ($group as $g) {
845                 $twitter_group = $this->twitterGroupArray($g);
846                 $this->showTwitterXmlGroup($twitter_group);
847             }
848         } else {
849             while ($group->fetch()) {
850                 $twitter_group = $this->twitterGroupArray($group);
851                 $this->showTwitterXmlGroup($twitter_group);
852             }
853         }
854
855         $this->elementEnd('groups');
856         $this->endDocument('xml');
857     }
858
859     function showTwitterXmlUsers($user)
860     {
861
862         $this->initDocument('xml');
863         $this->elementStart('users', array('type' => 'array'));
864
865         if (is_array($user)) {
866             foreach ($user as $u) {
867                 $twitter_user = $this->twitterUserArray($u);
868                 $this->showTwitterXmlUser($twitter_user);
869             }
870         } else {
871             while ($user->fetch()) {
872                 $twitter_user = $this->twitterUserArray($user);
873                 $this->showTwitterXmlUser($twitter_user);
874             }
875         }
876
877         $this->elementEnd('users');
878         $this->endDocument('xml');
879     }
880
881     function showJsonUsers($user)
882     {
883
884         $this->initDocument('json');
885
886         $users = array();
887
888         if (is_array($user)) {
889             foreach ($user as $u) {
890                 $twitter_user = $this->twitterUserArray($u);
891                 array_push($users, $twitter_user);
892             }
893         } else {
894             while ($user->fetch()) {
895                 $twitter_user = $this->twitterUserArray($user);
896                 array_push($users, $twitter_user);
897             }
898         }
899
900         $this->showJsonObjects($users);
901
902         $this->endDocument('json');
903     }
904
905     function showSingleJsonGroup($group)
906     {
907         $this->initDocument('json');
908         $twitter_group = $this->twitterGroupArray($group);
909         $this->showJsonObjects($twitter_group);
910         $this->endDocument('json');
911     }
912
913     function showSingleXmlGroup($group)
914     {
915         $this->initDocument('xml');
916         $twitter_group = $this->twitterGroupArray($group);
917         $this->showTwitterXmlGroup($twitter_group);
918         $this->endDocument('xml');
919     }
920
921     function dateTwitter($dt)
922     {
923         $dateStr = date('d F Y H:i:s', strtotime($dt));
924         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
925         $d->setTimezone(new DateTimeZone(common_timezone()));
926         return $d->format('D M d H:i:s O Y');
927     }
928
929     function initDocument($type='xml')
930     {
931         switch ($type) {
932         case 'xml':
933             header('Content-Type: application/xml; charset=utf-8');
934             $this->startXML();
935             break;
936         case 'json':
937             header('Content-Type: application/json; charset=utf-8');
938
939             // Check for JSONP callback
940             $callback = $this->arg('callback');
941             if ($callback) {
942                 print $callback . '(';
943             }
944             break;
945         case 'rss':
946             header("Content-Type: application/rss+xml; charset=utf-8");
947             $this->initTwitterRss();
948             break;
949         case 'atom':
950             header('Content-Type: application/atom+xml; charset=utf-8');
951             $this->initTwitterAtom();
952             break;
953         default:
954             $this->clientError(_('Not a supported data format.'));
955             break;
956         }
957
958         return;
959     }
960
961     function endDocument($type='xml')
962     {
963         switch ($type) {
964         case 'xml':
965             $this->endXML();
966             break;
967         case 'json':
968
969             // Check for JSONP callback
970             $callback = $this->arg('callback');
971             if ($callback) {
972                 print ')';
973             }
974             break;
975         case 'rss':
976             $this->endTwitterRss();
977             break;
978         case 'atom':
979             $this->endTwitterRss();
980             break;
981         default:
982             $this->clientError(_('Not a supported data format.'));
983             break;
984         }
985         return;
986     }
987
988     function clientError($msg, $code = 400, $format = 'xml')
989     {
990         $action = $this->trimmed('action');
991
992         common_debug("User error '$code' on '$action': $msg", __FILE__);
993
994         if (!array_key_exists($code, ClientErrorAction::$status)) {
995             $code = 400;
996         }
997
998         $status_string = ClientErrorAction::$status[$code];
999
1000         header('HTTP/1.1 '.$code.' '.$status_string);
1001
1002         if ($format == 'xml') {
1003             $this->initDocument('xml');
1004             $this->elementStart('hash');
1005             $this->element('error', null, $msg);
1006             $this->element('request', null, $_SERVER['REQUEST_URI']);
1007             $this->elementEnd('hash');
1008             $this->endDocument('xml');
1009         } elseif ($format == 'json'){
1010             $this->initDocument('json');
1011             $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1012             print(json_encode($error_array));
1013             $this->endDocument('json');
1014         } else {
1015
1016             // If user didn't request a useful format, throw a regular client error
1017             throw new ClientException($msg, $code);
1018         }
1019     }
1020
1021     function serverError($msg, $code = 500, $content_type = 'json')
1022     {
1023         $action = $this->trimmed('action');
1024
1025         common_debug("Server error '$code' on '$action': $msg", __FILE__);
1026
1027         if (!array_key_exists($code, ServerErrorAction::$status)) {
1028             $code = 400;
1029         }
1030
1031         $status_string = ServerErrorAction::$status[$code];
1032
1033         header('HTTP/1.1 '.$code.' '.$status_string);
1034
1035         if ($content_type == 'xml') {
1036             $this->initDocument('xml');
1037             $this->elementStart('hash');
1038             $this->element('error', null, $msg);
1039             $this->element('request', null, $_SERVER['REQUEST_URI']);
1040             $this->elementEnd('hash');
1041             $this->endDocument('xml');
1042         } else {
1043             $this->initDocument('json');
1044             $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1045             print(json_encode($error_array));
1046             $this->endDocument('json');
1047         }
1048     }
1049
1050     function initTwitterRss()
1051     {
1052         $this->startXML();
1053         $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1054         $this->elementStart('channel');
1055         Event::handle('StartApiRss', array($this));
1056     }
1057
1058     function endTwitterRss()
1059     {
1060         $this->elementEnd('channel');
1061         $this->elementEnd('rss');
1062         $this->endXML();
1063     }
1064
1065     function initTwitterAtom()
1066     {
1067         $this->startXML();
1068         // FIXME: don't hardcode the language here!
1069         $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1070                                           'xml:lang' => 'en-US',
1071                                           'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1072         Event::handle('StartApiAtom', array($this));
1073     }
1074
1075     function endTwitterAtom()
1076     {
1077         $this->elementEnd('feed');
1078         $this->endXML();
1079     }
1080
1081     function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1082     {
1083         $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1084         switch ($content_type) {
1085         case 'xml':
1086             $this->showTwitterXmlUser($profile_array);
1087             break;
1088         case 'json':
1089             $this->showJsonObjects($profile_array);
1090             break;
1091         default:
1092             $this->clientError(_('Not a supported data format.'));
1093             return;
1094         }
1095         return;
1096     }
1097
1098     function getTargetUser($id)
1099     {
1100         if (empty($id)) {
1101
1102             // Twitter supports these other ways of passing the user ID
1103             if (is_numeric($this->arg('id'))) {
1104                 return User::staticGet($this->arg('id'));
1105             } else if ($this->arg('id')) {
1106                 $nickname = common_canonical_nickname($this->arg('id'));
1107                 return User::staticGet('nickname', $nickname);
1108             } else if ($this->arg('user_id')) {
1109                 // This is to ensure that a non-numeric user_id still
1110                 // overrides screen_name even if it doesn't get used
1111                 if (is_numeric($this->arg('user_id'))) {
1112                     return User::staticGet('id', $this->arg('user_id'));
1113                 }
1114             } else if ($this->arg('screen_name')) {
1115                 $nickname = common_canonical_nickname($this->arg('screen_name'));
1116                 return User::staticGet('nickname', $nickname);
1117             } else {
1118                 // Fall back to trying the currently authenticated user
1119                 return $this->auth_user;
1120             }
1121
1122         } else if (is_numeric($id)) {
1123             return User::staticGet($id);
1124         } else {
1125             $nickname = common_canonical_nickname($id);
1126             return User::staticGet('nickname', $nickname);
1127         }
1128     }
1129
1130     function getTargetGroup($id)
1131     {
1132         if (empty($id)) {
1133             if (is_numeric($this->arg('id'))) {
1134                 return User_group::staticGet($this->arg('id'));
1135             } else if ($this->arg('id')) {
1136                 $nickname = common_canonical_nickname($this->arg('id'));
1137                 return User_group::staticGet('nickname', $nickname);
1138             } else if ($this->arg('group_id')) {
1139                 // This is to ensure that a non-numeric user_id still
1140                 // overrides screen_name even if it doesn't get used
1141                 if (is_numeric($this->arg('group_id'))) {
1142                     return User_group::staticGet('id', $this->arg('group_id'));
1143                 }
1144             } else if ($this->arg('group_name')) {
1145                 $nickname = common_canonical_nickname($this->arg('group_name'));
1146                 return User_group::staticGet('nickname', $nickname);
1147             }
1148
1149         } else if (is_numeric($id)) {
1150             return User_group::staticGet($id);
1151         } else {
1152             $nickname = common_canonical_nickname($id);
1153             return User_group::staticGet('nickname', $nickname);
1154         }
1155     }
1156
1157     function sourceLink($source)
1158     {
1159         $source_name = _($source);
1160         switch ($source) {
1161         case 'web':
1162         case 'xmpp':
1163         case 'mail':
1164         case 'omb':
1165         case 'api':
1166             break;
1167         default:
1168             $ns = Notice_source::staticGet($source);
1169             if ($ns) {
1170                 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
1171             }
1172             break;
1173         }
1174         return $source_name;
1175     }
1176
1177     /**
1178      * Returns query argument or default value if not found. Certain
1179      * parameters used throughout the API are lightly scrubbed and
1180      * bounds checked.  This overrides Action::arg().
1181      *
1182      * @param string $key requested argument
1183      * @param string $def default value to return if $key is not provided
1184      *
1185      * @return var $var
1186      */
1187     function arg($key, $def=null)
1188     {
1189
1190         // XXX: Do even more input validation/scrubbing?
1191
1192         if (array_key_exists($key, $this->args)) {
1193             switch($key) {
1194             case 'page':
1195                 $page = (int)$this->args['page'];
1196                 return ($page < 1) ? 1 : $page;
1197             case 'count':
1198                 $count = (int)$this->args['count'];
1199                 if ($count < 1) {
1200                     return 20;
1201                 } elseif ($count > 200) {
1202                     return 200;
1203                 } else {
1204                     return $count;
1205                 }
1206             case 'since_id':
1207                 $since_id = (int)$this->args['since_id'];
1208                 return ($since_id < 1) ? 0 : $since_id;
1209             case 'max_id':
1210                 $max_id = (int)$this->args['max_id'];
1211                 return ($max_id < 1) ? 0 : $max_id;
1212             case 'since':
1213                 return strtotime($this->args['since']);
1214             default:
1215                 return parent::arg($key, $def);
1216             }
1217         } else {
1218             return $def;
1219         }
1220     }
1221
1222 }