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