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