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