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