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