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