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