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