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