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