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