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