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