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