]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/apiaction.php
adding a Status_network::updateKeys() method, since DB_DataObject update doesn't...
[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         $twitter_group['id']=$group->id;
351         $twitter_group['url']=$group->permalink();
352         $twitter_group['nickname']=$group->nickname;
353         $twitter_group['fullname']=$group->fullname;
354         $twitter_group['original_logo']=$group->original_logo;
355         $twitter_group['homepage_logo']=$group->homepage_logo;
356         $twitter_group['stream_logo']=$group->stream_logo;
357         $twitter_group['mini_logo']=$group->mini_logo;
358         $twitter_group['homepage']=$group->homepage;
359         $twitter_group['description']=$group->description;
360         $twitter_group['location']=$group->location;
361         $twitter_group['created']=$this->dateTwitter($group->created);
362         $twitter_group['modified']=$this->dateTwitter($group->modified);
363         return $twitter_group;
364     }
365
366     function twitterRssGroupArray($group)
367     {
368         $entry = array();
369         $entry['content']=$group->description;
370         $entry['title']=$group->nickname;
371         $entry['link']=$group->permalink();
372         $entry['published']=common_date_iso8601($group->created);
373         $entry['updated']==common_date_iso8601($group->modified);
374         $taguribase = common_config('integration', 'groupuri');
375         $entry['id'] = "group:$groupuribase:$entry[link]";
376
377         $entry['description'] = $entry['content'];
378         $entry['pubDate'] = common_date_rfc2822($group->created);
379         $entry['guid'] = $entry['link'];
380
381         return $entry;
382     }
383
384     function twitterRssEntryArray($notice)
385     {
386         $profile = $notice->getProfile();
387         $entry = array();
388
389         // We trim() to avoid extraneous whitespace in the output
390
391         $entry['content'] = common_xml_safe_str(trim($notice->rendered));
392         $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
393         $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
394         $entry['published'] = common_date_iso8601($notice->created);
395
396         $taguribase = TagURI::base();
397         $entry['id'] = "tag:$taguribase:$entry[link]";
398
399         $entry['updated'] = $entry['published'];
400         $entry['author'] = $profile->getBestName();
401
402         // Enclosures
403         $attachments = $notice->attachments();
404         $enclosures = array();
405
406         foreach ($attachments as $attachment) {
407             $enclosure_o=$attachment->getEnclosure();
408             if ($enclosure_o) {
409                  $enclosure = array();
410                  $enclosure['url'] = $enclosure_o->url;
411                  $enclosure['mimetype'] = $enclosure_o->mimetype;
412                  $enclosure['size'] = $enclosure_o->size;
413                  $enclosures[] = $enclosure;
414             }
415         }
416
417         if (!empty($enclosures)) {
418             $entry['enclosures'] = $enclosures;
419         }
420
421         // Tags/Categories
422         $tag = new Notice_tag();
423         $tag->notice_id = $notice->id;
424         if ($tag->find()) {
425             $entry['tags']=array();
426             while ($tag->fetch()) {
427                 $entry['tags'][]=$tag->tag;
428             }
429         }
430         $tag->free();
431
432         // RSS Item specific
433         $entry['description'] = $entry['content'];
434         $entry['pubDate'] = common_date_rfc2822($notice->created);
435         $entry['guid'] = $entry['link'];
436
437         if (isset($notice->lat) && isset($notice->lon)) {
438             // This is the format that GeoJSON expects stuff to be in.
439             // showGeoRSS() below uses it for XML output, so we reuse it
440             $entry['geo'] = array('type' => 'Point',
441                                   'coordinates' => array((float) $notice->lat,
442                                                          (float) $notice->lon));
443         } else {
444             $entry['geo'] = null;
445         }
446
447         return $entry;
448     }
449
450     function twitterRelationshipArray($source, $target)
451     {
452         $relationship = array();
453
454         $relationship['source'] =
455             $this->relationshipDetailsArray($source, $target);
456         $relationship['target'] =
457             $this->relationshipDetailsArray($target, $source);
458
459         return array('relationship' => $relationship);
460     }
461
462     function relationshipDetailsArray($source, $target)
463     {
464         $details = array();
465
466         $details['screen_name'] = $source->nickname;
467         $details['followed_by'] = $target->isSubscribed($source);
468         $details['following'] = $source->isSubscribed($target);
469
470         $notifications = false;
471
472         if ($source->isSubscribed($target)) {
473
474             $sub = Subscription::pkeyGet(array('subscriber' =>
475                 $source->id, 'subscribed' => $target->id));
476
477             if (!empty($sub)) {
478                 $notifications = ($sub->jabber || $sub->sms);
479             }
480         }
481
482         $details['notifications_enabled'] = $notifications;
483         $details['blocking'] = $source->hasBlocked($target);
484         $details['id'] = $source->id;
485
486         return $details;
487     }
488
489     function showTwitterXmlRelationship($relationship)
490     {
491         $this->elementStart('relationship');
492
493         foreach($relationship as $element => $value) {
494             if ($element == 'source' || $element == 'target') {
495                 $this->elementStart($element);
496                 $this->showXmlRelationshipDetails($value);
497                 $this->elementEnd($element);
498             }
499         }
500
501         $this->elementEnd('relationship');
502     }
503
504     function showXmlRelationshipDetails($details)
505     {
506         foreach($details as $element => $value) {
507             $this->element($element, null, $value);
508         }
509     }
510
511     function showTwitterXmlStatus($twitter_status, $tag='status', $namespaces=false)
512     {
513         $attrs = array();
514         if ($namespaces) {
515             $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
516         }
517         $this->elementStart($tag, $attrs);
518         foreach($twitter_status as $element => $value) {
519             switch ($element) {
520             case 'user':
521                 $this->showTwitterXmlUser($twitter_status['user']);
522                 break;
523             case 'text':
524                 $this->element($element, null, common_xml_safe_str($value));
525                 break;
526             case 'attachments':
527                 $this->showXmlAttachments($twitter_status['attachments']);
528                 break;
529             case 'geo':
530                 $this->showGeoXML($value);
531                 break;
532             case 'retweeted_status':
533                 $this->showTwitterXmlStatus($value, 'retweeted_status');
534                 break;
535             default:
536                 $this->element($element, null, $value);
537             }
538         }
539         $this->elementEnd($tag);
540     }
541
542     function showTwitterXmlGroup($twitter_group)
543     {
544         $this->elementStart('group');
545         foreach($twitter_group as $element => $value) {
546             $this->element($element, null, $value);
547         }
548         $this->elementEnd('group');
549     }
550
551     function showTwitterXmlUser($twitter_user, $role='user', $namespaces=false)
552     {
553         $attrs = array();
554         if ($namespaces) {
555             $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
556         }
557         $this->elementStart($role, $attrs);
558         foreach($twitter_user as $element => $value) {
559             if ($element == 'status') {
560                 $this->showTwitterXmlStatus($twitter_user['status']);
561             } else {
562                 $this->element($element, null, $value);
563             }
564         }
565         $this->elementEnd($role);
566     }
567
568     function showXmlAttachments($attachments) {
569         if (!empty($attachments)) {
570             $this->elementStart('attachments', array('type' => 'array'));
571             foreach ($attachments as $attachment) {
572                 $attrs = array();
573                 $attrs['url'] = $attachment['url'];
574                 $attrs['mimetype'] = $attachment['mimetype'];
575                 $attrs['size'] = $attachment['size'];
576                 $this->element('enclosure', $attrs, '');
577             }
578             $this->elementEnd('attachments');
579         }
580     }
581
582     function showGeoXML($geo)
583     {
584         if (empty($geo)) {
585             // empty geo element
586             $this->element('geo');
587         } else {
588             $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
589             $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
590             $this->elementEnd('geo');
591         }
592     }
593
594     function showGeoRSS($geo)
595     {
596         if (!empty($geo)) {
597             $this->element(
598                 'georss:point',
599                 null,
600                 $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
601             );
602         }
603     }
604
605     function showTwitterRssItem($entry)
606     {
607         $this->elementStart('item');
608         $this->element('title', null, $entry['title']);
609         $this->element('description', null, $entry['description']);
610         $this->element('pubDate', null, $entry['pubDate']);
611         $this->element('guid', null, $entry['guid']);
612         $this->element('link', null, $entry['link']);
613
614         # RSS only supports 1 enclosure per item
615         if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
616             $enclosure = $entry['enclosures'][0];
617             $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
618         }
619
620         if(array_key_exists('tags', $entry)){
621             foreach($entry['tags'] as $tag){
622                 $this->element('category', null,$tag);
623             }
624         }
625
626         $this->showGeoRSS($entry['geo']);
627         $this->elementEnd('item');
628     }
629
630     function showJsonObjects($objects)
631     {
632         print(json_encode($objects));
633     }
634
635     function showSingleXmlStatus($notice)
636     {
637         $this->initDocument('xml');
638         $twitter_status = $this->twitterStatusArray($notice);
639         $this->showTwitterXmlStatus($twitter_status, 'status', true);
640         $this->endDocument('xml');
641     }
642
643     function show_single_json_status($notice)
644     {
645         $this->initDocument('json');
646         $status = $this->twitterStatusArray($notice);
647         $this->showJsonObjects($status);
648         $this->endDocument('json');
649     }
650
651     function showXmlTimeline($notice)
652     {
653
654         $this->initDocument('xml');
655         $this->elementStart('statuses', array('type' => 'array',
656                                               'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
657
658         if (is_array($notice)) {
659             foreach ($notice as $n) {
660                 $twitter_status = $this->twitterStatusArray($n);
661                 $this->showTwitterXmlStatus($twitter_status);
662             }
663         } else {
664             while ($notice->fetch()) {
665                 $twitter_status = $this->twitterStatusArray($notice);
666                 $this->showTwitterXmlStatus($twitter_status);
667             }
668         }
669
670         $this->elementEnd('statuses');
671         $this->endDocument('xml');
672     }
673
674     function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
675     {
676
677         $this->initDocument('rss');
678
679         $this->element('title', null, $title);
680         $this->element('link', null, $link);
681
682         if (!is_null($self)) {
683             $this->element(
684                 'atom:link',
685                 array(
686                     'type' => 'application/rss+xml',
687                     'href' => $self,
688                     'rel'  => 'self'
689                 )
690            );
691         }
692
693         if (!is_null($suplink)) {
694             // For FriendFeed's SUP protocol
695             $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
696                                          'rel' => 'http://api.friendfeed.com/2008/03#sup',
697                                          'href' => $suplink,
698                                          'type' => 'application/json'));
699         }
700
701         if (!is_null($logo)) {
702             $this->elementStart('image');
703             $this->element('link', null, $link);
704             $this->element('title', null, $title);
705             $this->element('url', null, $logo);
706             $this->elementEnd('image');
707         }
708
709         $this->element('description', null, $subtitle);
710         $this->element('language', null, 'en-us');
711         $this->element('ttl', null, '40');
712
713         if (is_array($notice)) {
714             foreach ($notice as $n) {
715                 $entry = $this->twitterRssEntryArray($n);
716                 $this->showTwitterRssItem($entry);
717             }
718         } else {
719             while ($notice->fetch()) {
720                 $entry = $this->twitterRssEntryArray($notice);
721                 $this->showTwitterRssItem($entry);
722             }
723         }
724
725         $this->endTwitterRss();
726     }
727
728     function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
729     {
730
731         $this->initDocument('atom');
732
733         $this->element('title', null, $title);
734         $this->element('id', null, $id);
735         $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
736
737         if (!is_null($logo)) {
738             $this->element('logo',null,$logo);
739         }
740
741         if (!is_null($suplink)) {
742             # For FriendFeed's SUP protocol
743             $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
744                                          'href' => $suplink,
745                                          'type' => 'application/json'));
746         }
747
748         if (!is_null($selfuri)) {
749             $this->element('link', array('href' => $selfuri,
750                 'rel' => 'self', 'type' => 'application/atom+xml'), null);
751         }
752
753         $this->element('updated', null, common_date_iso8601('now'));
754         $this->element('subtitle', null, $subtitle);
755
756         if (is_array($notice)) {
757             foreach ($notice as $n) {
758                 $this->raw($n->asAtomEntry());
759             }
760         } else {
761             while ($notice->fetch()) {
762                 $this->raw($notice->asAtomEntry());
763             }
764         }
765
766         $this->endDocument('atom');
767
768     }
769
770     function showRssGroups($group, $title, $link, $subtitle)
771     {
772
773         $this->initDocument('rss');
774
775         $this->element('title', null, $title);
776         $this->element('link', null, $link);
777         $this->element('description', null, $subtitle);
778         $this->element('language', null, 'en-us');
779         $this->element('ttl', null, '40');
780
781         if (is_array($group)) {
782             foreach ($group as $g) {
783                 $twitter_group = $this->twitterRssGroupArray($g);
784                 $this->showTwitterRssItem($twitter_group);
785             }
786         } else {
787             while ($group->fetch()) {
788                 $twitter_group = $this->twitterRssGroupArray($group);
789                 $this->showTwitterRssItem($twitter_group);
790             }
791         }
792
793         $this->endTwitterRss();
794     }
795
796     function showTwitterAtomEntry($entry)
797     {
798         $this->elementStart('entry');
799         $this->element('title', null, common_xml_safe_str($entry['title']));
800         $this->element(
801             'content',
802             array('type' => 'html'),
803             common_xml_safe_str($entry['content'])
804         );
805         $this->element('id', null, $entry['id']);
806         $this->element('published', null, $entry['published']);
807         $this->element('updated', null, $entry['updated']);
808         $this->element('link', array('type' => 'text/html',
809                                      'href' => $entry['link'],
810                                      'rel' => 'alternate'));
811         $this->element('link', array('type' => $entry['avatar-type'],
812                                      'href' => $entry['avatar'],
813                                      'rel' => 'image'));
814         $this->elementStart('author');
815
816         $this->element('name', null, $entry['author-name']);
817         $this->element('uri', null, $entry['author-uri']);
818
819         $this->elementEnd('author');
820         $this->elementEnd('entry');
821     }
822
823     function showXmlDirectMessage($dm, $namespaces=false)
824     {
825         $attrs = array();
826         if ($namespaces) {
827             $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
828         }
829         $this->elementStart('direct_message', $attrs);
830         foreach($dm as $element => $value) {
831             switch ($element) {
832             case 'sender':
833             case 'recipient':
834                 $this->showTwitterXmlUser($value, $element);
835                 break;
836             case 'text':
837                 $this->element($element, null, common_xml_safe_str($value));
838                 break;
839             default:
840                 $this->element($element, null, $value);
841                 break;
842             }
843         }
844         $this->elementEnd('direct_message');
845     }
846
847     function directMessageArray($message)
848     {
849         $dmsg = array();
850
851         $from_profile = $message->getFrom();
852         $to_profile = $message->getTo();
853
854         $dmsg['id'] = $message->id;
855         $dmsg['sender_id'] = $message->from_profile;
856         $dmsg['text'] = trim($message->content);
857         $dmsg['recipient_id'] = $message->to_profile;
858         $dmsg['created_at'] = $this->dateTwitter($message->created);
859         $dmsg['sender_screen_name'] = $from_profile->nickname;
860         $dmsg['recipient_screen_name'] = $to_profile->nickname;
861         $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
862         $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
863
864         return $dmsg;
865     }
866
867     function rssDirectMessageArray($message)
868     {
869         $entry = array();
870
871         $from = $message->getFrom();
872
873         $entry['title'] = sprintf('Message from %1$s to %2$s',
874             $from->nickname, $message->getTo()->nickname);
875
876         $entry['content'] = common_xml_safe_str($message->rendered);
877         $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
878         $entry['published'] = common_date_iso8601($message->created);
879
880         $taguribase = TagURI::base();
881
882         $entry['id'] = "tag:$taguribase:$entry[link]";
883         $entry['updated'] = $entry['published'];
884
885         $entry['author-name'] = $from->getBestName();
886         $entry['author-uri'] = $from->homepage;
887
888         $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
889
890         $entry['avatar']      = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
891         $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
892
893         // RSS item specific
894
895         $entry['description'] = $entry['content'];
896         $entry['pubDate'] = common_date_rfc2822($message->created);
897         $entry['guid'] = $entry['link'];
898
899         return $entry;
900     }
901
902     function showSingleXmlDirectMessage($message)
903     {
904         $this->initDocument('xml');
905         $dmsg = $this->directMessageArray($message);
906         $this->showXmlDirectMessage($dmsg, true);
907         $this->endDocument('xml');
908     }
909
910     function showSingleJsonDirectMessage($message)
911     {
912         $this->initDocument('json');
913         $dmsg = $this->directMessageArray($message);
914         $this->showJsonObjects($dmsg);
915         $this->endDocument('json');
916     }
917
918     function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
919     {
920
921         $this->initDocument('atom');
922
923         $this->element('title', null, common_xml_safe_str($title));
924         $this->element('id', null, $id);
925         $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
926
927         if (!is_null($selfuri)) {
928             $this->element('link', array('href' => $selfuri,
929                 'rel' => 'self', 'type' => 'application/atom+xml'), null);
930         }
931
932         $this->element('updated', null, common_date_iso8601('now'));
933         $this->element('subtitle', null, common_xml_safe_str($subtitle));
934
935         if (is_array($group)) {
936             foreach ($group as $g) {
937                 $this->raw($g->asAtomEntry());
938             }
939         } else {
940             while ($group->fetch()) {
941                 $this->raw($group->asAtomEntry());
942             }
943         }
944
945         $this->endDocument('atom');
946
947     }
948
949     function showJsonTimeline($notice)
950     {
951
952         $this->initDocument('json');
953
954         $statuses = array();
955
956         if (is_array($notice)) {
957             foreach ($notice as $n) {
958                 $twitter_status = $this->twitterStatusArray($n);
959                 array_push($statuses, $twitter_status);
960             }
961         } else {
962             while ($notice->fetch()) {
963                 $twitter_status = $this->twitterStatusArray($notice);
964                 array_push($statuses, $twitter_status);
965             }
966         }
967
968         $this->showJsonObjects($statuses);
969
970         $this->endDocument('json');
971     }
972
973     function showJsonGroups($group)
974     {
975
976         $this->initDocument('json');
977
978         $groups = array();
979
980         if (is_array($group)) {
981             foreach ($group as $g) {
982                 $twitter_group = $this->twitterGroupArray($g);
983                 array_push($groups, $twitter_group);
984             }
985         } else {
986             while ($group->fetch()) {
987                 $twitter_group = $this->twitterGroupArray($group);
988                 array_push($groups, $twitter_group);
989             }
990         }
991
992         $this->showJsonObjects($groups);
993
994         $this->endDocument('json');
995     }
996
997     function showXmlGroups($group)
998     {
999
1000         $this->initDocument('xml');
1001         $this->elementStart('groups', array('type' => 'array'));
1002
1003         if (is_array($group)) {
1004             foreach ($group as $g) {
1005                 $twitter_group = $this->twitterGroupArray($g);
1006                 $this->showTwitterXmlGroup($twitter_group);
1007             }
1008         } else {
1009             while ($group->fetch()) {
1010                 $twitter_group = $this->twitterGroupArray($group);
1011                 $this->showTwitterXmlGroup($twitter_group);
1012             }
1013         }
1014
1015         $this->elementEnd('groups');
1016         $this->endDocument('xml');
1017     }
1018
1019     function showTwitterXmlUsers($user)
1020     {
1021
1022         $this->initDocument('xml');
1023         $this->elementStart('users', array('type' => 'array',
1024                                            'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
1025
1026         if (is_array($user)) {
1027             foreach ($user as $u) {
1028                 $twitter_user = $this->twitterUserArray($u);
1029                 $this->showTwitterXmlUser($twitter_user);
1030             }
1031         } else {
1032             while ($user->fetch()) {
1033                 $twitter_user = $this->twitterUserArray($user);
1034                 $this->showTwitterXmlUser($twitter_user);
1035             }
1036         }
1037
1038         $this->elementEnd('users');
1039         $this->endDocument('xml');
1040     }
1041
1042     function showJsonUsers($user)
1043     {
1044
1045         $this->initDocument('json');
1046
1047         $users = array();
1048
1049         if (is_array($user)) {
1050             foreach ($user as $u) {
1051                 $twitter_user = $this->twitterUserArray($u);
1052                 array_push($users, $twitter_user);
1053             }
1054         } else {
1055             while ($user->fetch()) {
1056                 $twitter_user = $this->twitterUserArray($user);
1057                 array_push($users, $twitter_user);
1058             }
1059         }
1060
1061         $this->showJsonObjects($users);
1062
1063         $this->endDocument('json');
1064     }
1065
1066     function showSingleJsonGroup($group)
1067     {
1068         $this->initDocument('json');
1069         $twitter_group = $this->twitterGroupArray($group);
1070         $this->showJsonObjects($twitter_group);
1071         $this->endDocument('json');
1072     }
1073
1074     function showSingleXmlGroup($group)
1075     {
1076         $this->initDocument('xml');
1077         $twitter_group = $this->twitterGroupArray($group);
1078         $this->showTwitterXmlGroup($twitter_group);
1079         $this->endDocument('xml');
1080     }
1081
1082     function dateTwitter($dt)
1083     {
1084         $dateStr = date('d F Y H:i:s', strtotime($dt));
1085         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1086         $d->setTimezone(new DateTimeZone(common_timezone()));
1087         return $d->format('D M d H:i:s O Y');
1088     }
1089
1090     function initDocument($type='xml')
1091     {
1092         switch ($type) {
1093         case 'xml':
1094             header('Content-Type: application/xml; charset=utf-8');
1095             $this->startXML();
1096             break;
1097         case 'json':
1098             header('Content-Type: application/json; charset=utf-8');
1099
1100             // Check for JSONP callback
1101             $callback = $this->arg('callback');
1102             if ($callback) {
1103                 print $callback . '(';
1104             }
1105             break;
1106         case 'rss':
1107             header("Content-Type: application/rss+xml; charset=utf-8");
1108             $this->initTwitterRss();
1109             break;
1110         case 'atom':
1111             header('Content-Type: application/atom+xml; charset=utf-8');
1112             $this->initTwitterAtom();
1113             break;
1114         default:
1115             $this->clientError(_('Not a supported data format.'));
1116             break;
1117         }
1118
1119         return;
1120     }
1121
1122     function endDocument($type='xml')
1123     {
1124         switch ($type) {
1125         case 'xml':
1126             $this->endXML();
1127             break;
1128         case 'json':
1129
1130             // Check for JSONP callback
1131             $callback = $this->arg('callback');
1132             if ($callback) {
1133                 print ')';
1134             }
1135             break;
1136         case 'rss':
1137             $this->endTwitterRss();
1138             break;
1139         case 'atom':
1140             $this->endTwitterRss();
1141             break;
1142         default:
1143             $this->clientError(_('Not a supported data format.'));
1144             break;
1145         }
1146         return;
1147     }
1148
1149     function clientError($msg, $code = 400, $format = 'xml')
1150     {
1151         $action = $this->trimmed('action');
1152
1153         common_debug("User error '$code' on '$action': $msg", __FILE__);
1154
1155         if (!array_key_exists($code, ClientErrorAction::$status)) {
1156             $code = 400;
1157         }
1158
1159         $status_string = ClientErrorAction::$status[$code];
1160
1161         header('HTTP/1.1 '.$code.' '.$status_string);
1162
1163         if ($format == 'xml') {
1164             $this->initDocument('xml');
1165             $this->elementStart('hash');
1166             $this->element('error', null, $msg);
1167             $this->element('request', null, $_SERVER['REQUEST_URI']);
1168             $this->elementEnd('hash');
1169             $this->endDocument('xml');
1170         } elseif ($format == 'json'){
1171             $this->initDocument('json');
1172             $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1173             print(json_encode($error_array));
1174             $this->endDocument('json');
1175         } else {
1176
1177             // If user didn't request a useful format, throw a regular client error
1178             throw new ClientException($msg, $code);
1179         }
1180     }
1181
1182     function serverError($msg, $code = 500, $content_type = 'xml')
1183     {
1184         $action = $this->trimmed('action');
1185
1186         common_debug("Server error '$code' on '$action': $msg", __FILE__);
1187
1188         if (!array_key_exists($code, ServerErrorAction::$status)) {
1189             $code = 400;
1190         }
1191
1192         $status_string = ServerErrorAction::$status[$code];
1193
1194         header('HTTP/1.1 '.$code.' '.$status_string);
1195
1196         if ($content_type == 'xml') {
1197             $this->initDocument('xml');
1198             $this->elementStart('hash');
1199             $this->element('error', null, $msg);
1200             $this->element('request', null, $_SERVER['REQUEST_URI']);
1201             $this->elementEnd('hash');
1202             $this->endDocument('xml');
1203         } else {
1204             $this->initDocument('json');
1205             $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1206             print(json_encode($error_array));
1207             $this->endDocument('json');
1208         }
1209     }
1210
1211     function initTwitterRss()
1212     {
1213         $this->startXML();
1214         $this->elementStart(
1215             'rss',
1216             array(
1217                 'version'      => '2.0',
1218                 'xmlns:atom'   => 'http://www.w3.org/2005/Atom',
1219                 'xmlns:georss' => 'http://www.georss.org/georss'
1220             )
1221         );
1222         $this->elementStart('channel');
1223         Event::handle('StartApiRss', array($this));
1224     }
1225
1226     function endTwitterRss()
1227     {
1228         $this->elementEnd('channel');
1229         $this->elementEnd('rss');
1230         $this->endXML();
1231     }
1232
1233     function initTwitterAtom()
1234     {
1235         $this->startXML();
1236         // FIXME: don't hardcode the language here!
1237         $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1238                                           'xml:lang' => 'en-US',
1239                                           'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1240     }
1241
1242     function endTwitterAtom()
1243     {
1244         $this->elementEnd('feed');
1245         $this->endXML();
1246     }
1247
1248     function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1249     {
1250         $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1251         switch ($content_type) {
1252         case 'xml':
1253             $this->showTwitterXmlUser($profile_array);
1254             break;
1255         case 'json':
1256             $this->showJsonObjects($profile_array);
1257             break;
1258         default:
1259             $this->clientError(_('Not a supported data format.'));
1260             return;
1261         }
1262         return;
1263     }
1264
1265     function getTargetUser($id)
1266     {
1267         if (empty($id)) {
1268
1269             // Twitter supports these other ways of passing the user ID
1270             if (is_numeric($this->arg('id'))) {
1271                 return User::staticGet($this->arg('id'));
1272             } else if ($this->arg('id')) {
1273                 $nickname = common_canonical_nickname($this->arg('id'));
1274                 return User::staticGet('nickname', $nickname);
1275             } else if ($this->arg('user_id')) {
1276                 // This is to ensure that a non-numeric user_id still
1277                 // overrides screen_name even if it doesn't get used
1278                 if (is_numeric($this->arg('user_id'))) {
1279                     return User::staticGet('id', $this->arg('user_id'));
1280                 }
1281             } else if ($this->arg('screen_name')) {
1282                 $nickname = common_canonical_nickname($this->arg('screen_name'));
1283                 return User::staticGet('nickname', $nickname);
1284             } else {
1285                 // Fall back to trying the currently authenticated user
1286                 return $this->auth_user;
1287             }
1288
1289         } else if (is_numeric($id)) {
1290             return User::staticGet($id);
1291         } else {
1292             $nickname = common_canonical_nickname($id);
1293             return User::staticGet('nickname', $nickname);
1294         }
1295     }
1296
1297     function getTargetGroup($id)
1298     {
1299         if (empty($id)) {
1300             if (is_numeric($this->arg('id'))) {
1301                 return User_group::staticGet($this->arg('id'));
1302             } else if ($this->arg('id')) {
1303                 $nickname = common_canonical_nickname($this->arg('id'));
1304                 $local = Local_group::staticGet('nickname', $nickname);
1305                 if (empty($local)) {
1306                     return null;
1307                 } else {
1308                     return User_group::staticGet('id', $local->id);
1309                 }
1310             } else if ($this->arg('group_id')) {
1311                 // This is to ensure that a non-numeric user_id still
1312                 // overrides screen_name even if it doesn't get used
1313                 if (is_numeric($this->arg('group_id'))) {
1314                     return User_group::staticGet('id', $this->arg('group_id'));
1315                 }
1316             } else if ($this->arg('group_name')) {
1317                 $nickname = common_canonical_nickname($this->arg('group_name'));
1318                 $local = Local_group::staticGet('nickname', $nickname);
1319                 if (empty($local)) {
1320                     return null;
1321                 } else {
1322                     return User_group::staticGet('id', $local->group_id);
1323                 }
1324             }
1325
1326         } else if (is_numeric($id)) {
1327             return User_group::staticGet($id);
1328         } else {
1329             $nickname = common_canonical_nickname($id);
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
1339     /**
1340      * Returns query argument or default value if not found. Certain
1341      * parameters used throughout the API are lightly scrubbed and
1342      * bounds checked.  This overrides Action::arg().
1343      *
1344      * @param string $key requested argument
1345      * @param string $def default value to return if $key is not provided
1346      *
1347      * @return var $var
1348      */
1349     function arg($key, $def=null)
1350     {
1351
1352         // XXX: Do even more input validation/scrubbing?
1353
1354         if (array_key_exists($key, $this->args)) {
1355             switch($key) {
1356             case 'page':
1357                 $page = (int)$this->args['page'];
1358                 return ($page < 1) ? 1 : $page;
1359             case 'count':
1360                 $count = (int)$this->args['count'];
1361                 if ($count < 1) {
1362                     return 20;
1363                 } elseif ($count > 200) {
1364                     return 200;
1365                 } else {
1366                     return $count;
1367                 }
1368             case 'since_id':
1369                 $since_id = (int)$this->args['since_id'];
1370                 return ($since_id < 1) ? 0 : $since_id;
1371             case 'max_id':
1372                 $max_id = (int)$this->args['max_id'];
1373                 return ($max_id < 1) ? 0 : $max_id;
1374             default:
1375                 return parent::arg($key, $def);
1376             }
1377         } else {
1378             return $def;
1379         }
1380     }
1381
1382     /**
1383      * Calculate the complete URI that called up this action.  Used for
1384      * Atom rel="self" links.  Warning: this is funky.
1385      *
1386      * @return string URL    a URL suitable for rel="self" Atom links
1387      */
1388     function getSelfUri()
1389     {
1390         $action = mb_substr(get_class($this), 0, -6); // remove 'Action'
1391
1392         $id = $this->arg('id');
1393         $aargs = array('format' => $this->format);
1394         if (!empty($id)) {
1395             $aargs['id'] = $id;
1396         }
1397
1398         $tag = $this->arg('tag');
1399         if (!empty($tag)) {
1400             $aargs['tag'] = $tag;
1401         }
1402
1403         parse_str($_SERVER['QUERY_STRING'], $params);
1404         $pstring = '';
1405         if (!empty($params)) {
1406             unset($params['p']);
1407             $pstring = http_build_query($params);
1408         }
1409
1410         $uri = common_local_url($action, $aargs);
1411
1412         if (!empty($pstring)) {
1413             $uri .= '?' . $pstring;
1414         }
1415
1416         return $uri;
1417     }
1418
1419 }