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