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