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