]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/twitterapi.php
2f969f2bafee2c9aeb967ac6f2bb7b0c8a5745a5
[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['nickname']=$group->nickname;
221         $twitter_group['fullname']=$group->fullname;
222         $twitter_group['url']=$group->url;
223         $twitter_group['original_logo']=$group->original_logo;
224         $twitter_group['homepage_logo']=$group->homepage_logo;
225         $twitter_group['stream_logo']=$group->stream_logo;
226         $twitter_group['mini_logo']=$group->mini_logo;
227         $twitter_group['homepage']=$group->homepage;
228         $twitter_group['description']=$group->description;
229         $twitter_group['location']=$group->location;
230         $twitter_group['created']=$this->date_twitter($group->created);
231         $twitter_group['modified']=$this->date_twitter($group->modified);
232         return $twitter_group;
233     }
234
235     function twitter_rss_entry_array($notice)
236     {
237         $profile = $notice->getProfile();
238         $entry = array();
239
240         // We trim() to avoid extraneous whitespace in the output
241
242         $entry['content'] = common_xml_safe_str(trim($notice->rendered));
243         $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
244         $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
245         $entry['published'] = common_date_iso8601($notice->created);
246
247         $taguribase = common_config('integration', 'taguri');
248         $entry['id'] = "tag:$taguribase:$entry[link]";
249
250         $entry['updated'] = $entry['published'];
251         $entry['author'] = $profile->getBestName();
252
253         // Enclosures
254         $attachments = $notice->attachments();
255         $enclosures = array();
256
257         foreach ($attachments as $attachment) {
258             if ($attachment->isEnclosure()) {
259                  $enclosure = array();
260                  $enclosure['url'] = $attachment->url;
261                  $enclosure['mimetype'] = $attachment->mimetype;
262                  $enclosure['size'] = $attachment->size;
263                  $enclosures[] = $enclosure;
264             }
265         }
266
267         if (!empty($enclosures)) {
268             $entry['enclosures'] = $enclosures;
269         }
270
271 /*
272         // Enclosure
273         $attachments = $notice->attachments();
274         if($attachments){
275             $entry['enclosures']=array();
276             foreach($attachments as $attachment){
277                 if ($attachment->isEnclosure()) {
278                     $enclosure=array();
279                     $enclosure['url']=$attachment->url;
280                     $enclosure['mimetype']=$attachment->mimetype;
281                     $enclosure['size']=$attachment->size;
282                     $entry['enclosures'][]=$enclosure;
283                 }
284             }
285         }
286 */
287
288         // Tags/Categories
289         $tag = new Notice_tag();
290         $tag->notice_id = $notice->id;
291         if ($tag->find()) {
292             $entry['tags']=array();
293             while ($tag->fetch()) {
294                 $entry['tags'][]=$tag->tag;
295             }
296         }
297         $tag->free();
298
299         // RSS Item specific
300         $entry['description'] = $entry['content'];
301         $entry['pubDate'] = common_date_rfc2822($notice->created);
302         $entry['guid'] = $entry['link'];
303
304         return $entry;
305     }
306
307     function twitter_rss_dmsg_array($message)
308     {
309
310         $entry = array();
311
312         $entry['title'] = sprintf('Message from %s to %s',
313             $message->getFrom()->nickname, $message->getTo()->nickname);
314
315         $entry['content'] = common_xml_safe_str(trim($message->content));
316         $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
317         $entry['published'] = common_date_iso8601($message->created);
318
319         $taguribase = common_config('integration', 'taguri');
320
321         $entry['id'] = "tag:$taguribase,:$entry[link]";
322         $entry['updated'] = $entry['published'];
323         $entry['author'] = $message->getFrom()->getBestName();
324
325         # RSS Item specific
326         $entry['description'] = $entry['content'];
327         $entry['pubDate'] = common_date_rfc2822($message->created);
328         $entry['guid'] = $entry['link'];
329
330         return $entry;
331     }
332
333     function twitter_dmsg_array($message)
334     {
335         $twitter_dm = array();
336
337         $from_profile = $message->getFrom();
338         $to_profile = $message->getTo();
339
340         $twitter_dm['id'] = $message->id;
341         $twitter_dm['sender_id'] = $message->from_profile;
342         $twitter_dm['text'] = trim($message->content);
343         $twitter_dm['recipient_id'] = $message->to_profile;
344         $twitter_dm['created_at'] = $this->date_twitter($message->created);
345         $twitter_dm['sender_screen_name'] = $from_profile->nickname;
346         $twitter_dm['recipient_screen_name'] = $to_profile->nickname;
347         $twitter_dm['sender'] = $this->twitter_user_array($from_profile, false);
348         $twitter_dm['recipient'] = $this->twitter_user_array($to_profile, false);
349
350         return $twitter_dm;
351     }
352
353     function twitter_relationship_array($source, $target)
354     {
355         $relationship = array();
356
357         $relationship['source'] =
358             $this->relationship_details_array($source, $target);
359         $relationship['target'] =
360             $this->relationship_details_array($target, $source);
361
362         return array('relationship' => $relationship);
363     }
364
365     function relationship_details_array($source, $target)
366     {
367         $details = array();
368
369         $details['screen_name'] = $source->nickname;
370         $details['followed_by'] = $target->isSubscribed($source);
371         $details['following'] = $source->isSubscribed($target);
372
373         $notifications = false;
374
375         if ($source->isSubscribed($target)) {
376
377             $sub = Subscription::pkeyGet(array('subscriber' =>
378                 $source->id, 'subscribed' => $target->id));
379
380             if (!empty($sub)) {
381                 $notifications = ($sub->jabber || $sub->sms);
382             }
383         }
384
385         $details['notifications_enabled'] = $notifications;
386         $details['blocking'] = $source->hasBlocked($target);
387         $details['id'] = $source->id;
388
389         return $details;
390     }
391
392     function show_twitter_xml_relationship($relationship)
393     {
394         $this->elementStart('relationship');
395
396         foreach($relationship as $element => $value) {
397             if ($element == 'source' || $element == 'target') {
398                 $this->elementStart($element);
399                 $this->show_xml_relationship_details($value);
400                 $this->elementEnd($element);
401             }
402         }
403
404         $this->elementEnd('relationship');
405     }
406
407     function show_xml_relationship_details($details)
408     {
409         foreach($details as $element => $value) {
410             $this->element($element, null, $value);
411         }
412     }
413
414     function show_twitter_xml_status($twitter_status)
415     {
416         $this->elementStart('status');
417         foreach($twitter_status as $element => $value) {
418             switch ($element) {
419             case 'user':
420                 $this->show_twitter_xml_user($twitter_status['user']);
421                 break;
422             case 'text':
423                 $this->element($element, null, common_xml_safe_str($value));
424                 break;
425             case 'attachments':
426                 $this->show_xml_attachments($twitter_status['attachments']);
427                 break;
428             default:
429                 $this->element($element, null, $value);
430             }
431         }
432         $this->elementEnd('status');
433     }
434
435     function show_twitter_xml_group($twitter_group)
436     {
437         $this->elementStart('group');
438         foreach($twitter_group as $element => $value) {
439             $this->element($element, null, $value);
440         }
441         $this->elementEnd('group');
442     }
443
444     function show_twitter_xml_user($twitter_user, $role='user')
445     {
446         $this->elementStart($role);
447         foreach($twitter_user as $element => $value) {
448             if ($element == 'status') {
449                 $this->show_twitter_xml_status($twitter_user['status']);
450             } else {
451                 $this->element($element, null, $value);
452             }
453         }
454         $this->elementEnd($role);
455     }
456
457     function show_xml_attachments($attachments) {
458         if (!empty($attachments)) {
459             $this->elementStart('attachments', array('type' => 'array'));
460             foreach ($attachments as $attachment) {
461                 $attrs = array();
462                 $attrs['url'] = $attachment['url'];
463                 $attrs['mimetype'] = $attachment['mimetype'];
464                 $attrs['size'] = $attachment['size'];
465                 $this->element('enclosure', $attrs, '');
466             }
467             $this->elementEnd('attachments');
468         }
469     }
470
471     function show_twitter_rss_item($entry)
472     {
473         $this->elementStart('item');
474         $this->element('title', null, $entry['title']);
475         $this->element('description', null, $entry['description']);
476         $this->element('pubDate', null, $entry['pubDate']);
477         $this->element('guid', null, $entry['guid']);
478         $this->element('link', null, $entry['link']);
479
480         # RSS only supports 1 enclosure per item
481         if($entry['enclosures']){
482             $enclosure = $entry['enclosures'][0];
483             $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
484         }
485         
486         if($entry['tags']){
487             foreach($entry['tags'] as $tag){
488                 $this->element('category', null,$tag);
489             }
490         }
491
492         $this->elementEnd('item');
493     }
494
495     function show_json_objects($objects)
496     {
497         print(json_encode($objects));
498     }
499
500     function show_single_xml_status($notice)
501     {
502         $this->init_document('xml');
503         $twitter_status = $this->twitter_status_array($notice);
504         $this->show_twitter_xml_status($twitter_status);
505         $this->end_document('xml');
506     }
507
508     function show_single_json_status($notice)
509     {
510         $this->init_document('json');
511         $status = $this->twitter_status_array($notice);
512         $this->show_json_objects($status);
513         $this->end_document('json');
514     }
515
516     function show_single_xml_dmsg($message)
517     {
518         $this->init_document('xml');
519         $dmsg = $this->twitter_dmsg_array($message);
520         $this->show_twitter_xml_dmsg($dmsg);
521         $this->end_document('xml');
522     }
523
524     function show_single_json_dmsg($message)
525     {
526         $this->init_document('json');
527         $dmsg = $this->twitter_dmsg_array($message);
528         $this->show_json_objects($dmsg);
529         $this->end_document('json');
530     }
531
532     function show_twitter_xml_dmsg($twitter_dm)
533     {
534         $this->elementStart('direct_message');
535         foreach($twitter_dm as $element => $value) {
536             switch ($element) {
537             case 'sender':
538             case 'recipient':
539                 $this->show_twitter_xml_user($value, $element);
540                 break;
541             case 'text':
542                 $this->element($element, null, common_xml_safe_str($value));
543                 break;
544             default:
545                 $this->element($element, null, $value);
546             }
547         }
548         $this->elementEnd('direct_message');
549     }
550
551     function show_xml_timeline($notice)
552     {
553
554         $this->init_document('xml');
555         $this->elementStart('statuses', array('type' => 'array'));
556
557         if (is_array($notice)) {
558             foreach ($notice as $n) {
559                 $twitter_status = $this->twitter_status_array($n);
560                 $this->show_twitter_xml_status($twitter_status);
561             }
562         } else {
563             while ($notice->fetch()) {
564                 $twitter_status = $this->twitter_status_array($notice);
565                 $this->show_twitter_xml_status($twitter_status);
566             }
567         }
568
569         $this->elementEnd('statuses');
570         $this->end_document('xml');
571     }
572
573     function show_rss_timeline($notice, $title, $link, $subtitle, $suplink=null)
574     {
575
576         $this->init_document('rss');
577
578         $this->elementStart('channel');
579         $this->element('title', null, $title);
580         $this->element('link', null, $link);
581         if (!is_null($suplink)) {
582             # For FriendFeed's SUP protocol
583             $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
584                                          'rel' => 'http://api.friendfeed.com/2008/03#sup',
585                                          'href' => $suplink,
586                                          'type' => 'application/json'));
587         }
588         $this->element('description', null, $subtitle);
589         $this->element('language', null, 'en-us');
590         $this->element('ttl', null, '40');
591
592         if (is_array($notice)) {
593             foreach ($notice as $n) {
594                 $entry = $this->twitter_rss_entry_array($n);
595                 $this->show_twitter_rss_item($entry);
596             }
597         } else {
598             while ($notice->fetch()) {
599                 $entry = $this->twitter_rss_entry_array($notice);
600                 $this->show_twitter_rss_item($entry);
601             }
602         }
603
604         $this->elementEnd('channel');
605         $this->end_twitter_rss();
606     }
607
608     function show_atom_timeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
609     {
610
611         $this->init_document('atom');
612
613         $this->element('title', null, $title);
614         $this->element('id', null, $id);
615         $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
616
617         if (!is_null($suplink)) {
618             # For FriendFeed's SUP protocol
619             $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
620                                          'href' => $suplink,
621                                          'type' => 'application/json'));
622         }
623
624         if (!is_null($selfuri)) {
625             $this->element('link', array('href' => $selfuri,
626                 'rel' => 'self', 'type' => 'application/atom+xml'), null);
627         }
628
629         $this->element('updated', null, common_date_iso8601('now'));
630         $this->element('subtitle', null, $subtitle);
631
632         if (is_array($notice)) {
633             foreach ($notice as $n) {
634                 $this->raw($n->asAtomEntry());
635             }
636         } else {
637             while ($notice->fetch()) {
638                 $this->raw($notice->asAtomEntry());
639             }
640         }
641
642         $this->end_document('atom');
643
644     }
645
646     function show_json_timeline($notice)
647     {
648
649         $this->init_document('json');
650
651         $statuses = array();
652
653         if (is_array($notice)) {
654             foreach ($notice as $n) {
655                 $twitter_status = $this->twitter_status_array($n);
656                 array_push($statuses, $twitter_status);
657             }
658         } else {
659             while ($notice->fetch()) {
660                 $twitter_status = $this->twitter_status_array($notice);
661                 array_push($statuses, $twitter_status);
662             }
663         }
664
665         $this->show_json_objects($statuses);
666
667         $this->end_document('json');
668     }
669
670     function show_single_json_group($group)
671     {
672         $this->init_document('json');
673         $twitter_group = $this->twitter_group_array($group);
674         $this->show_json_objects($twitter_group);
675         $this->end_document('json');
676     }
677
678     function show_single_xml_group($group)
679     {
680         $this->init_document('xml');
681         $twitter_group = $this->twitter_group_array($group);
682         $this->show_twitter_xml_group($twitter_group);
683         $this->end_document('xml');
684     }
685
686     // Anyone know what date format this is?
687     // Twitter's dates look like this: "Mon Jul 14 23:52:38 +0000 2008" -- Zach
688     function date_twitter($dt)
689     {
690         $t = strtotime($dt);
691         return date("D M d H:i:s O Y", $t);
692     }
693
694     // XXX: Candidate for a general utility method somewhere?
695     function count_subscriptions($profile)
696     {
697
698         $count = 0;
699         $sub = new Subscription();
700         $sub->subscribed = $profile->id;
701
702         $count = $sub->find();
703
704         if ($count > 0) {
705             return $count - 1;
706         } else {
707             return 0;
708         }
709     }
710
711     function init_document($type='xml')
712     {
713         switch ($type) {
714         case 'xml':
715             header('Content-Type: application/xml; charset=utf-8');
716             $this->startXML();
717             break;
718         case 'json':
719             header('Content-Type: application/json; charset=utf-8');
720
721             // Check for JSONP callback
722             $callback = $this->arg('callback');
723             if ($callback) {
724                 print $callback . '(';
725             }
726             break;
727         case 'rss':
728             header("Content-Type: application/rss+xml; charset=utf-8");
729             $this->init_twitter_rss();
730             break;
731         case 'atom':
732             header('Content-Type: application/atom+xml; charset=utf-8');
733             $this->init_twitter_atom();
734             break;
735         default:
736             $this->clientError(_('Not a supported data format.'));
737             break;
738         }
739
740         return;
741     }
742
743     function end_document($type='xml')
744     {
745         switch ($type) {
746         case 'xml':
747             $this->endXML();
748             break;
749         case 'json':
750
751             // Check for JSONP callback
752             $callback = $this->arg('callback');
753             if ($callback) {
754                 print ')';
755             }
756             break;
757         case 'rss':
758             $this->end_twitter_rss();
759             break;
760         case 'atom':
761             $this->end_twitter_rss();
762             break;
763         default:
764             $this->clientError(_('Not a supported data format.'));
765             break;
766         }
767         return;
768     }
769
770     function clientError($msg, $code = 400, $content_type = 'json')
771     {
772
773         static $status = array(400 => 'Bad Request',
774                                401 => 'Unauthorized',
775                                402 => 'Payment Required',
776                                403 => 'Forbidden',
777                                404 => 'Not Found',
778                                405 => 'Method Not Allowed',
779                                406 => 'Not Acceptable',
780                                407 => 'Proxy Authentication Required',
781                                408 => 'Request Timeout',
782                                409 => 'Conflict',
783                                410 => 'Gone',
784                                411 => 'Length Required',
785                                412 => 'Precondition Failed',
786                                413 => 'Request Entity Too Large',
787                                414 => 'Request-URI Too Long',
788                                415 => 'Unsupported Media Type',
789                                416 => 'Requested Range Not Satisfiable',
790                                417 => 'Expectation Failed');
791
792         $action = $this->trimmed('action');
793
794         common_debug("User error '$code' on '$action': $msg", __FILE__);
795
796         if (!array_key_exists($code, $status)) {
797             $code = 400;
798         }
799
800         $status_string = $status[$code];
801         header('HTTP/1.1 '.$code.' '.$status_string);
802
803         if ($content_type == 'xml') {
804             $this->init_document('xml');
805             $this->elementStart('hash');
806             $this->element('error', null, $msg);
807             $this->element('request', null, $_SERVER['REQUEST_URI']);
808             $this->elementEnd('hash');
809             $this->end_document('xml');
810         } else {
811             $this->init_document('json');
812             $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
813             print(json_encode($error_array));
814             $this->end_document('json');
815         }
816
817     }
818
819     function init_twitter_rss()
820     {
821         $this->startXML();
822         $this->elementStart('rss', array('version' => '2.0'));
823     }
824
825     function end_twitter_rss()
826     {
827         $this->elementEnd('rss');
828         $this->endXML();
829     }
830
831     function init_twitter_atom()
832     {
833         $this->startXML();
834         // FIXME: don't hardcode the language here!
835         $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
836                                           'xml:lang' => 'en-US',
837                                           'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
838     }
839
840     function end_twitter_atom()
841     {
842         $this->elementEnd('feed');
843         $this->endXML();
844     }
845
846     function show_profile($profile, $content_type='xml', $notice=null)
847     {
848         $profile_array = $this->twitter_user_array($profile, true);
849         switch ($content_type) {
850         case 'xml':
851             $this->show_twitter_xml_user($profile_array);
852             break;
853         case 'json':
854             $this->show_json_objects($profile_array);
855             break;
856         default:
857             $this->clientError(_('Not a supported data format.'));
858             return;
859         }
860         return;
861     }
862
863     function get_user($id, $apidata=null)
864     {
865         if (empty($id)) {
866
867             // Twitter supports these other ways of passing the user ID
868             if (is_numeric($this->arg('id'))) {
869                 return User::staticGet($this->arg('id'));
870             } else if ($this->arg('id')) {
871                 $nickname = common_canonical_nickname($this->arg('id'));
872                 return User::staticGet('nickname', $nickname);
873             } else if ($this->arg('user_id')) {
874                 // This is to ensure that a non-numeric user_id still
875                 // overrides screen_name even if it doesn't get used
876                 if (is_numeric($this->arg('user_id'))) {
877                     return User::staticGet('id', $this->arg('user_id'));
878                 }
879             } else if ($this->arg('screen_name')) {
880                 $nickname = common_canonical_nickname($this->arg('screen_name'));
881                 return User::staticGet('nickname', $nickname);
882             } else {
883                 // Fall back to trying the currently authenticated user
884                 return $apidata['user'];
885             }
886
887         } else if (is_numeric($id)) {
888             return User::staticGet($id);
889         } else {
890             $nickname = common_canonical_nickname($id);
891             return User::staticGet('nickname', $nickname);
892         }
893     }
894
895     function get_group($id, $apidata=null)
896     {
897         if (empty($id)) {
898
899             if (is_numeric($this->arg('id'))) {
900                 return User_group::staticGet($this->arg('id'));
901             } else if ($this->arg('id')) {
902                 $nickname = common_canonical_nickname($this->arg('id'));
903                 return User_group::staticGet('nickname', $nickname);
904             } else if ($this->arg('group_id')) {
905                 // This is to ensure that a non-numeric user_id still
906                 // overrides screen_name even if it doesn't get used
907                 if (is_numeric($this->arg('group_id'))) {
908                     return User_group::staticGet('id', $this->arg('group_id'));
909                 }
910             } else if ($this->arg('group_name')) {
911                 $nickname = common_canonical_nickname($this->arg('group_name'));
912                 return User_group::staticGet('nickname', $nickname);
913             }
914
915         } else if (is_numeric($id)) {
916             return User_group::staticGet($id);
917         } else {
918             $nickname = common_canonical_nickname($id);
919             return User_group::staticGet('nickname', $nickname);
920         }
921     }
922
923     function get_profile($id)
924     {
925         if (is_numeric($id)) {
926             return Profile::staticGet($id);
927         } else {
928             $user = User::staticGet('nickname', $id);
929             if ($user) {
930                 return $user->getProfile();
931             } else {
932                 return null;
933             }
934         }
935     }
936
937     function source_link($source)
938     {
939         $source_name = _($source);
940         switch ($source) {
941         case 'web':
942         case 'xmpp':
943         case 'mail':
944         case 'omb':
945         case 'api':
946             break;
947         default:
948             $ns = Notice_source::staticGet($source);
949             if ($ns) {
950                 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
951             }
952             break;
953         }
954         return $source_name;
955     }
956
957     /**
958      * Returns query argument or default value if not found. Certain
959      * parameters used throughout the API are lightly scrubbed and
960      * bounds checked.  This overrides Action::arg().
961      *
962      * @param string $key requested argument
963      * @param string $def default value to return if $key is not provided
964      *
965      * @return var $var
966      */
967     function arg($key, $def=null)
968     {
969
970         // XXX: Do even more input validation/scrubbing?
971
972         if (array_key_exists($key, $this->args)) {
973             switch($key) {
974             case 'page':
975                 $page = (int)$this->args['page'];
976                 return ($page < 1) ? 1 : $page;
977             case 'count':
978                 $count = (int)$this->args['count'];
979                 if ($count < 1) {
980                     return 20;
981                 } elseif ($count > 200) {
982                     return 200;
983                 } else {
984                     return $count;
985                 }
986             case 'since_id':
987                 $since_id = (int)$this->args['since_id'];
988                 return ($since_id < 1) ? 0 : $since_id;
989             case 'max_id':
990                 $max_id = (int)$this->args['max_id'];
991                 return ($max_id < 1) ? 0 : $max_id;
992             case 'since':
993                 return strtotime($this->args['since']);
994             default:
995                 return parent::arg($key, $def);
996             }
997         } else {
998             return $def;
999         }
1000     }
1001
1002 }