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