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