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