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