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