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