]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/twitterapi.php
Merge branch '0.8.x' of git@gitorious.org:laconica/mainline into 0.8.x
[quix0rs-gnu-social.git] / lib / twitterapi.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, Control Yourself, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('LACONICA')) {
21     exit(1);
22 }
23
24 class TwitterapiAction extends Action
25 {
26
27     var $auth_user;
28
29     /**
30      * Initialization.
31      *
32      * @param array $args Web and URL arguments
33      *
34      * @return boolean false if user doesn't exist
35      */
36
37     function prepare($args)
38     {
39         parent::prepare($args);
40         return true;
41     }
42
43     /**
44      * Handle a request
45      *
46      * @param array $args Arguments from $_REQUEST
47      *
48      * @return void
49      */
50
51     function handle($args)
52     {
53         parent::handle($args);
54     }
55
56     /**
57      * Overrides XMLOutputter::element to write booleans as strings (true|false).
58      * See that method's documentation for more info.
59      *
60      * @param string $tag     Element type or tagname
61      * @param array  $attrs   Array of element attributes, as
62      *                        key-value pairs
63      * @param string $content string content of the element
64      *
65      * @return void
66      */
67     function element($tag, $attrs=null, $content=null)
68     {
69         if (is_bool($content)) {
70             $content = ($content ? 'true' : 'false');
71         }
72
73         return parent::element($tag, $attrs, $content);
74     }
75
76     function twitter_user_array($profile, $get_notice=false)
77     {
78         $twitter_user = array();
79
80         $twitter_user['id'] = intval($profile->id);
81         $twitter_user['name'] = $profile->getBestName();
82         $twitter_user['screen_name'] = $profile->nickname;
83         $twitter_user['location'] = ($profile->location) ? $profile->location : null;
84         $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
85
86         $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
87         $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
88             Avatar::defaultImage(AVATAR_STREAM_SIZE);
89
90         $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
91         $twitter_user['protected'] = false; # not supported by Laconica yet
92         $twitter_user['followers_count'] = $profile->subscriberCount();
93
94         // To be supported soon...
95         $twitter_user['profile_background_color'] = '';
96         $twitter_user['profile_text_color'] = '';
97         $twitter_user['profile_link_color'] = '';
98         $twitter_user['profile_sidebar_fill_color'] = '';
99         $twitter_user['profile_sidebar_border_color'] = '';
100
101         $twitter_user['friends_count'] = $profile->subscriptionCount();
102
103         $twitter_user['created_at'] = $this->date_twitter($profile->created);
104
105         $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
106
107         // Need to pull up the user for some of this
108         $user = User::staticGet($profile->id);
109
110         $timezone = 'UTC';
111
112         if ($user->timezone) {
113             $timezone = $user->timezone;
114         }
115
116         $t = new DateTime;
117         $t->setTimezone(new DateTimeZone($timezone));
118
119         $twitter_user['utc_offset'] = $t->format('Z');
120         $twitter_user['time_zone'] = $timezone;
121
122         // To be supported some day, perhaps
123         $twitter_user['profile_background_image_url'] = '';
124         $twitter_user['profile_background_tile'] = false;
125
126         $twitter_user['statuses_count'] = $profile->noticeCount();
127
128         // Is the requesting user following this user?
129         $twitter_user['following'] = false;
130         $twitter_user['notifications'] = false;
131
132         if (isset($apidata['user'])) {
133
134             $twitter_user['following'] = $apidata['user']->isSubscribed($profile);
135
136             // Notifications on?
137             $sub = Subscription::pkeyGet(array('subscriber' =>
138                 $apidata['user']->id, 'subscribed' => $profile->id));
139
140             if ($sub) {
141                 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
142             }
143         }
144
145         if ($get_notice) {
146             $notice = $profile->getCurrentNotice();
147             if ($notice) {
148                 # don't get user!
149                 $twitter_user['status'] = $this->twitter_status_array($notice, false);
150             }
151         }
152
153         return $twitter_user;
154     }
155
156     function twitter_status_array($notice, $include_user=true)
157     {
158         $profile = $notice->getProfile();
159
160         $twitter_status = array();
161         $twitter_status['text'] = $notice->content;
162         $twitter_status['truncated'] = false; # Not possible on Laconica
163         $twitter_status['created_at'] = $this->date_twitter($notice->created);
164         $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
165             intval($notice->reply_to) : null;
166         $twitter_status['source'] = $this->source_link($notice->source);
167         $twitter_status['id'] = intval($notice->id);
168
169         $replier_profile = null;
170
171         if ($notice->reply_to) {
172             $reply = Notice::staticGet(intval($notice->reply_to));
173             if ($reply) {
174                 $replier_profile = $reply->getProfile();
175             }
176         }
177
178         $twitter_status['in_reply_to_user_id'] =
179             ($replier_profile) ? intval($replier_profile->id) : null;
180         $twitter_status['in_reply_to_screen_name'] =
181             ($replier_profile) ? $replier_profile->nickname : null;
182
183         if (isset($this->auth_user)) {
184             $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
185         } else {
186             $twitter_status['favorited'] = false;
187         }
188
189         // Enclosures
190         $attachments = $notice->attachments();
191         $enclosures = array();
192
193         foreach ($attachments as $attachment) {
194             if ($attachment->isEnclosure()) {
195                  $enclosure = array();
196                  $enclosure['url'] = $attachment->url;
197                  $enclosure['mimetype'] = $attachment->mimetype;
198                  $enclosure['size'] = $attachment->size;
199                  $enclosures[] = $enclosure;
200             }
201         }
202
203         if (!empty($enclosures)) {
204             $twitter_status['attachments'] = $enclosures;
205         }
206
207         if ($include_user) {
208             # Don't get notice (recursive!)
209             $twitter_user = $this->twitter_user_array($profile, false);
210             $twitter_status['user'] = $twitter_user;
211         }
212
213         return $twitter_status;
214     }
215
216     function twitter_group_array($group)
217     {
218         $twitter_group=array();
219         $twitter_group['id']=$group->id;
220         $twitter_group['url']=$group->permalink();
221         $twitter_group['nickname']=$group->nickname;
222         $twitter_group['fullname']=$group->fullname;
223         $twitter_group['homepage_url']=$group->homepage_url;
224         $twitter_group['original_logo']=$group->original_logo;
225         $twitter_group['homepage_logo']=$group->homepage_logo;
226         $twitter_group['stream_logo']=$group->stream_logo;
227         $twitter_group['mini_logo']=$group->mini_logo;
228         $twitter_group['homepage']=$group->homepage;
229         $twitter_group['description']=$group->description;
230         $twitter_group['location']=$group->location;
231         $twitter_group['created']=$this->date_twitter($group->created);
232         $twitter_group['modified']=$this->date_twitter($group->modified);
233         return $twitter_group;
234     }
235
236     function twitter_rss_entry_array($notice)
237     {
238         $profile = $notice->getProfile();
239         $entry = array();
240
241         // We trim() to avoid extraneous whitespace in the output
242
243         $entry['content'] = common_xml_safe_str(trim($notice->rendered));
244         $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
245         $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
246         $entry['published'] = common_date_iso8601($notice->created);
247
248         $taguribase = common_config('integration', 'taguri');
249         $entry['id'] = "tag:$taguribase:$entry[link]";
250
251         $entry['updated'] = $entry['published'];
252         $entry['author'] = $profile->getBestName();
253
254         // Enclosures
255         $attachments = $notice->attachments();
256         $enclosures = array();
257
258         foreach ($attachments as $attachment) {
259             if ($attachment->isEnclosure()) {
260                  $enclosure = array();
261                  $enclosure['url'] = $attachment->url;
262                  $enclosure['mimetype'] = $attachment->mimetype;
263                  $enclosure['size'] = $attachment->size;
264                  $enclosures[] = $enclosure;
265             }
266         }
267
268         if (!empty($enclosures)) {
269             $entry['enclosures'] = $enclosures;
270         }
271
272 /*
273         // Enclosure
274         $attachments = $notice->attachments();
275         if($attachments){
276             $entry['enclosures']=array();
277             foreach($attachments as $attachment){
278                 if ($attachment->isEnclosure()) {
279                     $enclosure=array();
280                     $enclosure['url']=$attachment->url;
281                     $enclosure['mimetype']=$attachment->mimetype;
282                     $enclosure['size']=$attachment->size;
283                     $entry['enclosures'][]=$enclosure;
284                 }
285             }
286         }
287 */
288
289         // Tags/Categories
290         $tag = new Notice_tag();
291         $tag->notice_id = $notice->id;
292         if ($tag->find()) {
293             $entry['tags']=array();
294             while ($tag->fetch()) {
295                 $entry['tags'][]=$tag->tag;
296             }
297         }
298         $tag->free();
299
300         // RSS Item specific
301         $entry['description'] = $entry['content'];
302         $entry['pubDate'] = common_date_rfc2822($notice->created);
303         $entry['guid'] = $entry['link'];
304
305         return $entry;
306     }
307
308     function twitter_rss_dmsg_array($message)
309     {
310
311         $entry = array();
312
313         $entry['title'] = sprintf('Message from %s to %s',
314             $message->getFrom()->nickname, $message->getTo()->nickname);
315
316         $entry['content'] = common_xml_safe_str(trim($message->content));
317         $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
318         $entry['published'] = common_date_iso8601($message->created);
319
320         $taguribase = common_config('integration', 'taguri');
321
322         $entry['id'] = "tag:$taguribase,:$entry[link]";
323         $entry['updated'] = $entry['published'];
324         $entry['author'] = $message->getFrom()->getBestName();
325
326         # RSS Item specific
327         $entry['description'] = $entry['content'];
328         $entry['pubDate'] = common_date_rfc2822($message->created);
329         $entry['guid'] = $entry['link'];
330
331         return $entry;
332     }
333
334     function twitter_dmsg_array($message)
335     {
336         $twitter_dm = array();
337
338         $from_profile = $message->getFrom();
339         $to_profile = $message->getTo();
340
341         $twitter_dm['id'] = $message->id;
342         $twitter_dm['sender_id'] = $message->from_profile;
343         $twitter_dm['text'] = trim($message->content);
344         $twitter_dm['recipient_id'] = $message->to_profile;
345         $twitter_dm['created_at'] = $this->date_twitter($message->created);
346         $twitter_dm['sender_screen_name'] = $from_profile->nickname;
347         $twitter_dm['recipient_screen_name'] = $to_profile->nickname;
348         $twitter_dm['sender'] = $this->twitter_user_array($from_profile, false);
349         $twitter_dm['recipient'] = $this->twitter_user_array($to_profile, false);
350
351         return $twitter_dm;
352     }
353
354     function twitter_relationship_array($source, $target)
355     {
356         $relationship = array();
357
358         $relationship['source'] =
359             $this->relationship_details_array($source, $target);
360         $relationship['target'] =
361             $this->relationship_details_array($target, $source);
362
363         return array('relationship' => $relationship);
364     }
365
366     function relationship_details_array($source, $target)
367     {
368         $details = array();
369
370         $details['screen_name'] = $source->nickname;
371         $details['followed_by'] = $target->isSubscribed($source);
372         $details['following'] = $source->isSubscribed($target);
373
374         $notifications = false;
375
376         if ($source->isSubscribed($target)) {
377
378             $sub = Subscription::pkeyGet(array('subscriber' =>
379                 $source->id, 'subscribed' => $target->id));
380
381             if (!empty($sub)) {
382                 $notifications = ($sub->jabber || $sub->sms);
383             }
384         }
385
386         $details['notifications_enabled'] = $notifications;
387         $details['blocking'] = $source->hasBlocked($target);
388         $details['id'] = $source->id;
389
390         return $details;
391     }
392
393     function show_twitter_xml_relationship($relationship)
394     {
395         $this->elementStart('relationship');
396
397         foreach($relationship as $element => $value) {
398             if ($element == 'source' || $element == 'target') {
399                 $this->elementStart($element);
400                 $this->show_xml_relationship_details($value);
401                 $this->elementEnd($element);
402             }
403         }
404
405         $this->elementEnd('relationship');
406     }
407
408     function show_xml_relationship_details($details)
409     {
410         foreach($details as $element => $value) {
411             $this->element($element, null, $value);
412         }
413     }
414
415     function show_twitter_xml_status($twitter_status)
416     {
417         $this->elementStart('status');
418         foreach($twitter_status as $element => $value) {
419             switch ($element) {
420             case 'user':
421                 $this->show_twitter_xml_user($twitter_status['user']);
422                 break;
423             case 'text':
424                 $this->element($element, null, common_xml_safe_str($value));
425                 break;
426             case 'attachments':
427                 $this->show_xml_attachments($twitter_status['attachments']);
428                 break;
429             default:
430                 $this->element($element, null, $value);
431             }
432         }
433         $this->elementEnd('status');
434     }
435
436     function show_twitter_xml_group($twitter_group)
437     {
438         $this->elementStart('group');
439         foreach($twitter_group as $element => $value) {
440             $this->element($element, null, $value);
441         }
442         $this->elementEnd('group');
443     }
444
445     function show_twitter_xml_user($twitter_user, $role='user')
446     {
447         $this->elementStart($role);
448         foreach($twitter_user as $element => $value) {
449             if ($element == 'status') {
450                 $this->show_twitter_xml_status($twitter_user['status']);
451             } else {
452                 $this->element($element, null, $value);
453             }
454         }
455         $this->elementEnd($role);
456     }
457
458     function show_xml_attachments($attachments) {
459         if (!empty($attachments)) {
460             $this->elementStart('attachments', array('type' => 'array'));
461             foreach ($attachments as $attachment) {
462                 $attrs = array();
463                 $attrs['url'] = $attachment['url'];
464                 $attrs['mimetype'] = $attachment['mimetype'];
465                 $attrs['size'] = $attachment['size'];
466                 $this->element('enclosure', $attrs, '');
467             }
468             $this->elementEnd('attachments');
469         }
470     }
471
472     function show_twitter_rss_item($entry)
473     {
474         $this->elementStart('item');
475         $this->element('title', null, $entry['title']);
476         $this->element('description', null, $entry['description']);
477         $this->element('pubDate', null, $entry['pubDate']);
478         $this->element('guid', null, $entry['guid']);
479         $this->element('link', null, $entry['link']);
480
481         # RSS only supports 1 enclosure per item
482         if($entry['enclosures']){
483             $enclosure = $entry['enclosures'][0];
484             $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
485         }
486         
487         if($entry['tags']){
488             foreach($entry['tags'] as $tag){
489                 $this->element('category', null,$tag);
490             }
491         }
492
493         $this->elementEnd('item');
494     }
495
496     function show_json_objects($objects)
497     {
498         print(json_encode($objects));
499     }
500
501     function show_single_xml_status($notice)
502     {
503         $this->init_document('xml');
504         $twitter_status = $this->twitter_status_array($notice);
505         $this->show_twitter_xml_status($twitter_status);
506         $this->end_document('xml');
507     }
508
509     function show_single_json_status($notice)
510     {
511         $this->init_document('json');
512         $status = $this->twitter_status_array($notice);
513         $this->show_json_objects($status);
514         $this->end_document('json');
515     }
516
517     function show_single_xml_dmsg($message)
518     {
519         $this->init_document('xml');
520         $dmsg = $this->twitter_dmsg_array($message);
521         $this->show_twitter_xml_dmsg($dmsg);
522         $this->end_document('xml');
523     }
524
525     function show_single_json_dmsg($message)
526     {
527         $this->init_document('json');
528         $dmsg = $this->twitter_dmsg_array($message);
529         $this->show_json_objects($dmsg);
530         $this->end_document('json');
531     }
532
533     function show_twitter_xml_dmsg($twitter_dm)
534     {
535         $this->elementStart('direct_message');
536         foreach($twitter_dm as $element => $value) {
537             switch ($element) {
538             case 'sender':
539             case 'recipient':
540                 $this->show_twitter_xml_user($value, $element);
541                 break;
542             case 'text':
543                 $this->element($element, null, common_xml_safe_str($value));
544                 break;
545             default:
546                 $this->element($element, null, $value);
547             }
548         }
549         $this->elementEnd('direct_message');
550     }
551
552     function show_xml_timeline($notice)
553     {
554
555         $this->init_document('xml');
556         $this->elementStart('statuses', array('type' => 'array'));
557
558         if (is_array($notice)) {
559             foreach ($notice as $n) {
560                 $twitter_status = $this->twitter_status_array($n);
561                 $this->show_twitter_xml_status($twitter_status);
562             }
563         } else {
564             while ($notice->fetch()) {
565                 $twitter_status = $this->twitter_status_array($notice);
566                 $this->show_twitter_xml_status($twitter_status);
567             }
568         }
569
570         $this->elementEnd('statuses');
571         $this->end_document('xml');
572     }
573
574     function show_rss_timeline($notice, $title, $link, $subtitle, $suplink=null)
575     {
576
577         $this->init_document('rss');
578
579         $this->elementStart('channel');
580         $this->element('title', null, $title);
581         $this->element('link', null, $link);
582         if (!is_null($suplink)) {
583             # For FriendFeed's SUP protocol
584             $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
585                                          'rel' => 'http://api.friendfeed.com/2008/03#sup',
586                                          'href' => $suplink,
587                                          'type' => 'application/json'));
588         }
589         $this->element('description', null, $subtitle);
590         $this->element('language', null, 'en-us');
591         $this->element('ttl', null, '40');
592
593         if (is_array($notice)) {
594             foreach ($notice as $n) {
595                 $entry = $this->twitter_rss_entry_array($n);
596                 $this->show_twitter_rss_item($entry);
597             }
598         } else {
599             while ($notice->fetch()) {
600                 $entry = $this->twitter_rss_entry_array($notice);
601                 $this->show_twitter_rss_item($entry);
602             }
603         }
604
605         $this->elementEnd('channel');
606         $this->end_twitter_rss();
607     }
608
609     function show_atom_timeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
610     {
611
612         $this->init_document('atom');
613
614         $this->element('title', null, $title);
615         $this->element('id', null, $id);
616         $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
617
618         if (!is_null($suplink)) {
619             # For FriendFeed's SUP protocol
620             $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
621                                          'href' => $suplink,
622                                          'type' => 'application/json'));
623         }
624
625         if (!is_null($selfuri)) {
626             $this->element('link', array('href' => $selfuri,
627                 'rel' => 'self', 'type' => 'application/atom+xml'), null);
628         }
629
630         $this->element('updated', null, common_date_iso8601('now'));
631         $this->element('subtitle', null, $subtitle);
632
633         if (is_array($notice)) {
634             foreach ($notice as $n) {
635                 $this->raw($n->asAtomEntry());
636             }
637         } else {
638             while ($notice->fetch()) {
639                 $this->raw($notice->asAtomEntry());
640             }
641         }
642
643         $this->end_document('atom');
644
645     }
646
647     function show_json_timeline($notice)
648     {
649
650         $this->init_document('json');
651
652         $statuses = array();
653
654         if (is_array($notice)) {
655             foreach ($notice as $n) {
656                 $twitter_status = $this->twitter_status_array($n);
657                 array_push($statuses, $twitter_status);
658             }
659         } else {
660             while ($notice->fetch()) {
661                 $twitter_status = $this->twitter_status_array($notice);
662                 array_push($statuses, $twitter_status);
663             }
664         }
665
666         $this->show_json_objects($statuses);
667
668         $this->end_document('json');
669     }
670
671     function show_single_json_group($group)
672     {
673         $this->init_document('json');
674         $twitter_group = $this->twitter_group_array($group);
675         $this->show_json_objects($twitter_group);
676         $this->end_document('json');
677     }
678
679     function show_single_xml_group($group)
680     {
681         $this->init_document('xml');
682         $twitter_group = $this->twitter_group_array($group);
683         $this->show_twitter_xml_group($twitter_group);
684         $this->end_document('xml');
685     }
686
687     // Anyone know what date format this is?
688     // Twitter's dates look like this: "Mon Jul 14 23:52:38 +0000 2008" -- Zach
689     function date_twitter($dt)
690     {
691         $t = strtotime($dt);
692         return date("D M d H:i:s O Y", $t);
693     }
694
695     // XXX: Candidate for a general utility method somewhere?
696     function count_subscriptions($profile)
697     {
698
699         $count = 0;
700         $sub = new Subscription();
701         $sub->subscribed = $profile->id;
702
703         $count = $sub->find();
704
705         if ($count > 0) {
706             return $count - 1;
707         } else {
708             return 0;
709         }
710     }
711
712     function init_document($type='xml')
713     {
714         switch ($type) {
715         case 'xml':
716             header('Content-Type: application/xml; charset=utf-8');
717             $this->startXML();
718             break;
719         case 'json':
720             header('Content-Type: application/json; charset=utf-8');
721
722             // Check for JSONP callback
723             $callback = $this->arg('callback');
724             if ($callback) {
725                 print $callback . '(';
726             }
727             break;
728         case 'rss':
729             header("Content-Type: application/rss+xml; charset=utf-8");
730             $this->init_twitter_rss();
731             break;
732         case 'atom':
733             header('Content-Type: application/atom+xml; charset=utf-8');
734             $this->init_twitter_atom();
735             break;
736         default:
737             $this->clientError(_('Not a supported data format.'));
738             break;
739         }
740
741         return;
742     }
743
744     function end_document($type='xml')
745     {
746         switch ($type) {
747         case 'xml':
748             $this->endXML();
749             break;
750         case 'json':
751
752             // Check for JSONP callback
753             $callback = $this->arg('callback');
754             if ($callback) {
755                 print ')';
756             }
757             break;
758         case 'rss':
759             $this->end_twitter_rss();
760             break;
761         case 'atom':
762             $this->end_twitter_rss();
763             break;
764         default:
765             $this->clientError(_('Not a supported data format.'));
766             break;
767         }
768         return;
769     }
770
771     function clientError($msg, $code = 400, $content_type = 'json')
772     {
773
774         static $status = array(400 => 'Bad Request',
775                                401 => 'Unauthorized',
776                                402 => 'Payment Required',
777                                403 => 'Forbidden',
778                                404 => 'Not Found',
779                                405 => 'Method Not Allowed',
780                                406 => 'Not Acceptable',
781                                407 => 'Proxy Authentication Required',
782                                408 => 'Request Timeout',
783                                409 => 'Conflict',
784                                410 => 'Gone',
785                                411 => 'Length Required',
786                                412 => 'Precondition Failed',
787                                413 => 'Request Entity Too Large',
788                                414 => 'Request-URI Too Long',
789                                415 => 'Unsupported Media Type',
790                                416 => 'Requested Range Not Satisfiable',
791                                417 => 'Expectation Failed');
792
793         $action = $this->trimmed('action');
794
795         common_debug("User error '$code' on '$action': $msg", __FILE__);
796
797         if (!array_key_exists($code, $status)) {
798             $code = 400;
799         }
800
801         $status_string = $status[$code];
802         header('HTTP/1.1 '.$code.' '.$status_string);
803
804         if ($content_type == 'xml') {
805             $this->init_document('xml');
806             $this->elementStart('hash');
807             $this->element('error', null, $msg);
808             $this->element('request', null, $_SERVER['REQUEST_URI']);
809             $this->elementEnd('hash');
810             $this->end_document('xml');
811         } else {
812             $this->init_document('json');
813             $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
814             print(json_encode($error_array));
815             $this->end_document('json');
816         }
817
818     }
819
820     function init_twitter_rss()
821     {
822         $this->startXML();
823         $this->elementStart('rss', array('version' => '2.0'));
824     }
825
826     function end_twitter_rss()
827     {
828         $this->elementEnd('rss');
829         $this->endXML();
830     }
831
832     function init_twitter_atom()
833     {
834         $this->startXML();
835         // FIXME: don't hardcode the language here!
836         $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
837                                           'xml:lang' => 'en-US',
838                                           'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
839     }
840
841     function end_twitter_atom()
842     {
843         $this->elementEnd('feed');
844         $this->endXML();
845     }
846
847     function show_profile($profile, $content_type='xml', $notice=null)
848     {
849         $profile_array = $this->twitter_user_array($profile, true);
850         switch ($content_type) {
851         case 'xml':
852             $this->show_twitter_xml_user($profile_array);
853             break;
854         case 'json':
855             $this->show_json_objects($profile_array);
856             break;
857         default:
858             $this->clientError(_('Not a supported data format.'));
859             return;
860         }
861         return;
862     }
863
864     function get_user($id, $apidata=null)
865     {
866         if (empty($id)) {
867
868             // Twitter supports these other ways of passing the user ID
869             if (is_numeric($this->arg('id'))) {
870                 return User::staticGet($this->arg('id'));
871             } else if ($this->arg('id')) {
872                 $nickname = common_canonical_nickname($this->arg('id'));
873                 return User::staticGet('nickname', $nickname);
874             } else if ($this->arg('user_id')) {
875                 // This is to ensure that a non-numeric user_id still
876                 // overrides screen_name even if it doesn't get used
877                 if (is_numeric($this->arg('user_id'))) {
878                     return User::staticGet('id', $this->arg('user_id'));
879                 }
880             } else if ($this->arg('screen_name')) {
881                 $nickname = common_canonical_nickname($this->arg('screen_name'));
882                 return User::staticGet('nickname', $nickname);
883             } else {
884                 // Fall back to trying the currently authenticated user
885                 return $apidata['user'];
886             }
887
888         } else if (is_numeric($id)) {
889             return User::staticGet($id);
890         } else {
891             $nickname = common_canonical_nickname($id);
892             return User::staticGet('nickname', $nickname);
893         }
894     }
895
896     function get_group($id, $apidata=null)
897     {
898         if (empty($id)) {
899
900             if (is_numeric($this->arg('id'))) {
901                 return User_group::staticGet($this->arg('id'));
902             } else if ($this->arg('id')) {
903                 $nickname = common_canonical_nickname($this->arg('id'));
904                 return User_group::staticGet('nickname', $nickname);
905             } else if ($this->arg('group_id')) {
906                 // This is to ensure that a non-numeric user_id still
907                 // overrides screen_name even if it doesn't get used
908                 if (is_numeric($this->arg('group_id'))) {
909                     return User_group::staticGet('id', $this->arg('group_id'));
910                 }
911             } else if ($this->arg('group_name')) {
912                 $nickname = common_canonical_nickname($this->arg('group_name'));
913                 return User_group::staticGet('nickname', $nickname);
914             }
915
916         } else if (is_numeric($id)) {
917             return User_group::staticGet($id);
918         } else {
919             $nickname = common_canonical_nickname($id);
920             return User_group::staticGet('nickname', $nickname);
921         }
922     }
923
924     function get_profile($id)
925     {
926         if (is_numeric($id)) {
927             return Profile::staticGet($id);
928         } else {
929             $user = User::staticGet('nickname', $id);
930             if ($user) {
931                 return $user->getProfile();
932             } else {
933                 return null;
934             }
935         }
936     }
937
938     function source_link($source)
939     {
940         $source_name = _($source);
941         switch ($source) {
942         case 'web':
943         case 'xmpp':
944         case 'mail':
945         case 'omb':
946         case 'api':
947             break;
948         default:
949             $ns = Notice_source::staticGet($source);
950             if ($ns) {
951                 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
952             }
953             break;
954         }
955         return $source_name;
956     }
957
958     /**
959      * Returns query argument or default value if not found. Certain
960      * parameters used throughout the API are lightly scrubbed and
961      * bounds checked.  This overrides Action::arg().
962      *
963      * @param string $key requested argument
964      * @param string $def default value to return if $key is not provided
965      *
966      * @return var $var
967      */
968     function arg($key, $def=null)
969     {
970
971         // XXX: Do even more input validation/scrubbing?
972
973         if (array_key_exists($key, $this->args)) {
974             switch($key) {
975             case 'page':
976                 $page = (int)$this->args['page'];
977                 return ($page < 1) ? 1 : $page;
978             case 'count':
979                 $count = (int)$this->args['count'];
980                 if ($count < 1) {
981                     return 20;
982                 } elseif ($count > 200) {
983                     return 200;
984                 } else {
985                     return $count;
986                 }
987             case 'since_id':
988                 $since_id = (int)$this->args['since_id'];
989                 return ($since_id < 1) ? 0 : $since_id;
990             case 'max_id':
991                 $max_id = (int)$this->args['max_id'];
992                 return ($max_id < 1) ? 0 : $max_id;
993             case 'since':
994                 return strtotime($this->args['since']);
995             default:
996                 return parent::arg($key, $def);
997             }
998         } else {
999             return $def;
1000         }
1001     }
1002
1003 }