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