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