]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/api.php
95a0779add67c0cd18f64c904d31101e6029e7dd
[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 twitter_user_array($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->date_twitter($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->twitter_status_array($notice, false);
183             }
184         }
185
186         return $twitter_user;
187     }
188
189     function twitter_status_array($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->date_twitter($notice->created);
197         $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
198             intval($notice->reply_to) : null;
199         $twitter_status['source'] = $this->source_link($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->twitter_user_array($profile, false);
243             $twitter_status['user'] = $twitter_user;
244         }
245
246         return $twitter_status;
247     }
248
249     function twitter_group_array($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->date_twitter($group->created);
265         $twitter_group['modified']=$this->date_twitter($group->modified);
266         return $twitter_group;
267     }
268
269     function twitter_rss_group_array($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 twitter_rss_entry_array($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 twitter_relationship_array($source, $target)
345     {
346         $relationship = array();
347
348         $relationship['source'] =
349             $this->relationship_details_array($source, $target);
350         $relationship['target'] =
351             $this->relationship_details_array($target, $source);
352
353         return array('relationship' => $relationship);
354     }
355
356     function relationship_details_array($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 show_twitter_xml_relationship($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->show_xml_relationship_details($value);
391                 $this->elementEnd($element);
392             }
393         }
394
395         $this->elementEnd('relationship');
396     }
397
398     function show_xml_relationship_details($details)
399     {
400         foreach($details as $element => $value) {
401             $this->element($element, null, $value);
402         }
403     }
404
405     function show_twitter_xml_status($twitter_status)
406     {
407         $this->elementStart('status');
408         foreach($twitter_status as $element => $value) {
409             switch ($element) {
410             case 'user':
411                 $this->show_twitter_xml_user($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->show_xml_attachments($twitter_status['attachments']);
418                 break;
419             default:
420                 $this->element($element, null, $value);
421             }
422         }
423         $this->elementEnd('status');
424     }
425
426     function show_twitter_xml_group($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 show_twitter_xml_user($twitter_user, $role='user')
436     {
437         $this->elementStart($role);
438         foreach($twitter_user as $element => $value) {
439             if ($element == 'status') {
440                 $this->show_twitter_xml_status($twitter_user['status']);
441             } else {
442                 $this->element($element, null, $value);
443             }
444         }
445         $this->elementEnd($role);
446     }
447
448     function show_xml_attachments($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 show_twitter_rss_item($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 show_json_objects($objects)
487     {
488         print(json_encode($objects));
489     }
490
491     function show_single_xml_status($notice)
492     {
493         $this->init_document('xml');
494         $twitter_status = $this->twitter_status_array($notice);
495         $this->show_twitter_xml_status($twitter_status);
496         $this->end_document('xml');
497     }
498
499     function show_single_json_status($notice)
500     {
501         $this->init_document('json');
502         $status = $this->twitter_status_array($notice);
503         $this->show_json_objects($status);
504         $this->end_document('json');
505     }
506
507
508     function show_xml_timeline($notice)
509     {
510
511         $this->init_document('xml');
512         $this->elementStart('statuses', array('type' => 'array'));
513
514         if (is_array($notice)) {
515             foreach ($notice as $n) {
516                 $twitter_status = $this->twitter_status_array($n);
517                 $this->show_twitter_xml_status($twitter_status);
518             }
519         } else {
520             while ($notice->fetch()) {
521                 $twitter_status = $this->twitter_status_array($notice);
522                 $this->show_twitter_xml_status($twitter_status);
523             }
524         }
525
526         $this->elementEnd('statuses');
527         $this->end_document('xml');
528     }
529
530     function show_rss_timeline($notice, $title, $link, $subtitle, $suplink=null)
531     {
532
533         $this->init_document('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->twitter_rss_entry_array($n);
551                 $this->show_twitter_rss_item($entry);
552             }
553         } else {
554             while ($notice->fetch()) {
555                 $entry = $this->twitter_rss_entry_array($notice);
556                 $this->show_twitter_rss_item($entry);
557             }
558         }
559
560         $this->end_twitter_rss();
561     }
562
563     function show_atom_timeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
564     {
565
566         $this->init_document('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->end_document('atom');
598
599     }
600
601     function show_rss_groups($group, $title, $link, $subtitle)
602     {
603
604         $this->init_document('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->twitter_rss_group_array($g);
615                 $this->show_twitter_rss_item($twitter_group);
616             }
617         } else {
618             while ($group->fetch()) {
619                 $twitter_group = $this->twitter_rss_group_array($group);
620                 $this->show_twitter_rss_item($twitter_group);
621             }
622         }
623
624         $this->end_twitter_rss();
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->show_twitter_xml_user($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->date_twitter($message->created);
683         $dmsg['sender_screen_name'] = $from_profile->nickname;
684         $dmsg['recipient_screen_name'] = $to_profile->nickname;
685         $dmsg['sender'] = $this->twitter_user_array($from_profile, false);
686         $dmsg['recipient'] = $this->twitter_user_array($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->init_document('xml');
729         $dmsg = $this->directMessageArray($message);
730         $this->showXmlDirectMessage($dmsg);
731         $this->end_document('xml');
732     }
733
734     function showSingleJsonDirectMessage($message)
735     {
736         $this->init_document('json');
737         $dmsg = $this->directMessageArray($message);
738         $this->show_json_objects($dmsg);
739         $this->end_document('json');
740     }
741
742     function show_atom_groups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
743     {
744
745         $this->init_document('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->end_document('atom');
770
771     }
772
773     function show_json_timeline($notice)
774     {
775
776         $this->init_document('json');
777
778         $statuses = array();
779
780         if (is_array($notice)) {
781             foreach ($notice as $n) {
782                 $twitter_status = $this->twitter_status_array($n);
783                 array_push($statuses, $twitter_status);
784             }
785         } else {
786             while ($notice->fetch()) {
787                 $twitter_status = $this->twitter_status_array($notice);
788                 array_push($statuses, $twitter_status);
789             }
790         }
791
792         $this->show_json_objects($statuses);
793
794         $this->end_document('json');
795     }
796
797     function show_json_groups($group)
798     {
799
800         $this->init_document('json');
801
802         $groups = array();
803
804         if (is_array($group)) {
805             foreach ($group as $g) {
806                 $twitter_group = $this->twitter_group_array($g);
807                 array_push($groups, $twitter_group);
808             }
809         } else {
810             while ($group->fetch()) {
811                 $twitter_group = $this->twitter_group_array($group);
812                 array_push($groups, $twitter_group);
813             }
814         }
815
816         $this->show_json_objects($groups);
817
818         $this->end_document('json');
819     }
820
821     function show_xml_groups($group)
822     {
823
824         $this->init_document('xml');
825         $this->elementStart('groups', array('type' => 'array'));
826
827         if (is_array($group)) {
828             foreach ($group as $g) {
829                 $twitter_group = $this->twitter_group_array($g);
830                 $this->show_twitter_xml_group($twitter_group);
831             }
832         } else {
833             while ($group->fetch()) {
834                 $twitter_group = $this->twitter_group_array($group);
835                 $this->show_twitter_xml_group($twitter_group);
836             }
837         }
838
839         $this->elementEnd('groups');
840         $this->end_document('xml');
841     }
842
843     function show_twitter_xml_users($user)
844     {
845
846         $this->init_document('xml');
847         $this->elementStart('users', array('type' => 'array'));
848
849         if (is_array($user)) {
850             foreach ($user as $u) {
851                 $twitter_user = $this->twitter_user_array($u);
852                 $this->show_twitter_xml_user($twitter_user);
853             }
854         } else {
855             while ($user->fetch()) {
856                 $twitter_user = $this->twitter_user_array($user);
857                 $this->show_twitter_xml_user($twitter_user);
858             }
859         }
860
861         $this->elementEnd('users');
862         $this->end_document('xml');
863     }
864
865     function show_json_users($user)
866     {
867
868         $this->init_document('json');
869
870         $users = array();
871
872         if (is_array($user)) {
873             foreach ($user as $u) {
874                 $twitter_user = $this->twitter_user_array($u);
875                 array_push($users, $twitter_user);
876             }
877         } else {
878             while ($user->fetch()) {
879                 $twitter_user = $this->twitter_user_array($user);
880                 array_push($users, $twitter_user);
881             }
882         }
883
884         $this->show_json_objects($users);
885
886         $this->end_document('json');
887     }
888
889     function show_single_json_group($group)
890     {
891         $this->init_document('json');
892         $twitter_group = $this->twitter_group_array($group);
893         $this->show_json_objects($twitter_group);
894         $this->end_document('json');
895     }
896
897     function show_single_xml_group($group)
898     {
899         $this->init_document('xml');
900         $twitter_group = $this->twitter_group_array($group);
901         $this->show_twitter_xml_group($twitter_group);
902         $this->end_document('xml');
903     }
904
905     function date_twitter($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     // XXX: Candidate for a general utility method somewhere?
914     function count_subscriptions($profile)
915     {
916
917         $count = 0;
918         $sub = new Subscription();
919         $sub->subscribed = $profile->id;
920
921         $count = $sub->find();
922
923         if ($count > 0) {
924             return $count - 1;
925         } else {
926             return 0;
927         }
928     }
929
930     function init_document($type='xml')
931     {
932         switch ($type) {
933         case 'xml':
934             header('Content-Type: application/xml; charset=utf-8');
935             $this->startXML();
936             break;
937         case 'json':
938             header('Content-Type: application/json; charset=utf-8');
939
940             // Check for JSONP callback
941             $callback = $this->arg('callback');
942             if ($callback) {
943                 print $callback . '(';
944             }
945             break;
946         case 'rss':
947             header("Content-Type: application/rss+xml; charset=utf-8");
948             $this->init_twitter_rss();
949             break;
950         case 'atom':
951             header('Content-Type: application/atom+xml; charset=utf-8');
952             $this->init_twitter_atom();
953             break;
954         default:
955             $this->clientError(_('Not a supported data format.'));
956             break;
957         }
958
959         return;
960     }
961
962     function end_document($type='xml')
963     {
964         switch ($type) {
965         case 'xml':
966             $this->endXML();
967             break;
968         case 'json':
969
970             // Check for JSONP callback
971             $callback = $this->arg('callback');
972             if ($callback) {
973                 print ')';
974             }
975             break;
976         case 'rss':
977             $this->end_twitter_rss();
978             break;
979         case 'atom':
980             $this->end_twitter_rss();
981             break;
982         default:
983             $this->clientError(_('Not a supported data format.'));
984             break;
985         }
986         return;
987     }
988
989     function clientError($msg, $code = 400, $format = 'xml')
990     {
991         $action = $this->trimmed('action');
992
993         common_debug("User error '$code' on '$action': $msg", __FILE__);
994
995         if (!array_key_exists($code, ClientErrorAction::$status)) {
996             $code = 400;
997         }
998
999         $status_string = ClientErrorAction::$status[$code];
1000
1001         header('HTTP/1.1 '.$code.' '.$status_string);
1002
1003         if ($format == 'xml') {
1004             $this->init_document('xml');
1005             $this->elementStart('hash');
1006             $this->element('error', null, $msg);
1007             $this->element('request', null, $_SERVER['REQUEST_URI']);
1008             $this->elementEnd('hash');
1009             $this->end_document('xml');
1010         } elseif ($format == 'json'){
1011             $this->init_document('json');
1012             $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1013             print(json_encode($error_array));
1014             $this->end_document('json');
1015         } else {
1016
1017             // If user didn't request a useful format, throw a regular client error
1018             throw new ClientException($msg, $code);
1019         }
1020     }
1021
1022     function serverError($msg, $code = 500, $content_type = 'json')
1023     {
1024         $action = $this->trimmed('action');
1025
1026         common_debug("Server error '$code' on '$action': $msg", __FILE__);
1027
1028         if (!array_key_exists($code, ServerErrorAction::$status)) {
1029             $code = 400;
1030         }
1031
1032         $status_string = ServerErrorAction::$status[$code];
1033
1034         header('HTTP/1.1 '.$code.' '.$status_string);
1035
1036         if ($content_type == 'xml') {
1037             $this->init_document('xml');
1038             $this->elementStart('hash');
1039             $this->element('error', null, $msg);
1040             $this->element('request', null, $_SERVER['REQUEST_URI']);
1041             $this->elementEnd('hash');
1042             $this->end_document('xml');
1043         } else {
1044             $this->init_document('json');
1045             $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1046             print(json_encode($error_array));
1047             $this->end_document('json');
1048         }
1049     }
1050
1051     function init_twitter_rss()
1052     {
1053         $this->startXML();
1054         $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1055         $this->elementStart('channel');
1056         Event::handle('StartApiRss', array($this));
1057     }
1058
1059     function end_twitter_rss()
1060     {
1061         $this->elementEnd('channel');
1062         $this->elementEnd('rss');
1063         $this->endXML();
1064     }
1065
1066     function init_twitter_atom()
1067     {
1068         $this->startXML();
1069         // FIXME: don't hardcode the language here!
1070         $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1071                                           'xml:lang' => 'en-US',
1072                                           'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1073         Event::handle('StartApiAtom', array($this));
1074     }
1075
1076     function end_twitter_atom()
1077     {
1078         $this->elementEnd('feed');
1079         $this->endXML();
1080     }
1081
1082     function show_profile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1083     {
1084         $profile_array = $this->twitter_user_array($profile, $includeStatuses);
1085         switch ($content_type) {
1086         case 'xml':
1087             $this->show_twitter_xml_user($profile_array);
1088             break;
1089         case 'json':
1090             $this->show_json_objects($profile_array);
1091             break;
1092         default:
1093             $this->clientError(_('Not a supported data format.'));
1094             return;
1095         }
1096         return;
1097     }
1098
1099     function getTargetUser($id)
1100     {
1101         if (empty($id)) {
1102
1103             // Twitter supports these other ways of passing the user ID
1104             if (is_numeric($this->arg('id'))) {
1105                 return User::staticGet($this->arg('id'));
1106             } else if ($this->arg('id')) {
1107                 $nickname = common_canonical_nickname($this->arg('id'));
1108                 return User::staticGet('nickname', $nickname);
1109             } else if ($this->arg('user_id')) {
1110                 // This is to ensure that a non-numeric user_id still
1111                 // overrides screen_name even if it doesn't get used
1112                 if (is_numeric($this->arg('user_id'))) {
1113                     return User::staticGet('id', $this->arg('user_id'));
1114                 }
1115             } else if ($this->arg('screen_name')) {
1116                 $nickname = common_canonical_nickname($this->arg('screen_name'));
1117                 return User::staticGet('nickname', $nickname);
1118             } else {
1119                 // Fall back to trying the currently authenticated user
1120                 return $this->auth_user;
1121             }
1122
1123         } else if (is_numeric($id)) {
1124             return User::staticGet($id);
1125         } else {
1126             $nickname = common_canonical_nickname($id);
1127             return User::staticGet('nickname', $nickname);
1128         }
1129     }
1130
1131     function getTargetGroup($id)
1132     {
1133         if (empty($id)) {
1134             if (is_numeric($this->arg('id'))) {
1135                 return User_group::staticGet($this->arg('id'));
1136             } else if ($this->arg('id')) {
1137                 $nickname = common_canonical_nickname($this->arg('id'));
1138                 return User_group::staticGet('nickname', $nickname);
1139             } else if ($this->arg('group_id')) {
1140                 // This is to ensure that a non-numeric user_id still
1141                 // overrides screen_name even if it doesn't get used
1142                 if (is_numeric($this->arg('group_id'))) {
1143                     return User_group::staticGet('id', $this->arg('group_id'));
1144                 }
1145             } else if ($this->arg('group_name')) {
1146                 $nickname = common_canonical_nickname($this->arg('group_name'));
1147                 return User_group::staticGet('nickname', $nickname);
1148             }
1149
1150         } else if (is_numeric($id)) {
1151             return User_group::staticGet($id);
1152         } else {
1153             $nickname = common_canonical_nickname($id);
1154             return User_group::staticGet('nickname', $nickname);
1155         }
1156     }
1157
1158     function source_link($source)
1159     {
1160         $source_name = _($source);
1161         switch ($source) {
1162         case 'web':
1163         case 'xmpp':
1164         case 'mail':
1165         case 'omb':
1166         case 'api':
1167             break;
1168         default:
1169             $ns = Notice_source::staticGet($source);
1170             if ($ns) {
1171                 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
1172             }
1173             break;
1174         }
1175         return $source_name;
1176     }
1177
1178     /**
1179      * Returns query argument or default value if not found. Certain
1180      * parameters used throughout the API are lightly scrubbed and
1181      * bounds checked.  This overrides Action::arg().
1182      *
1183      * @param string $key requested argument
1184      * @param string $def default value to return if $key is not provided
1185      *
1186      * @return var $var
1187      */
1188     function arg($key, $def=null)
1189     {
1190
1191         // XXX: Do even more input validation/scrubbing?
1192
1193         if (array_key_exists($key, $this->args)) {
1194             switch($key) {
1195             case 'page':
1196                 $page = (int)$this->args['page'];
1197                 return ($page < 1) ? 1 : $page;
1198             case 'count':
1199                 $count = (int)$this->args['count'];
1200                 if ($count < 1) {
1201                     return 20;
1202                 } elseif ($count > 200) {
1203                     return 200;
1204                 } else {
1205                     return $count;
1206                 }
1207             case 'since_id':
1208                 $since_id = (int)$this->args['since_id'];
1209                 return ($since_id < 1) ? 0 : $since_id;
1210             case 'max_id':
1211                 $max_id = (int)$this->args['max_id'];
1212                 return ($max_id < 1) ? 0 : $max_id;
1213             case 'since':
1214                 return strtotime($this->args['since']);
1215             default:
1216                 return parent::arg($key, $def);
1217             }
1218         } else {
1219             return $def;
1220         }
1221     }
1222
1223 }