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