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