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