]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/twitterapi.php
Merge commit 'br3nda/0.8.x-pginstaller' into 0.8.x
[quix0rs-gnu-social.git] / lib / twitterapi.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, Control Yourself, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('LACONICA')) {
21     exit(1);
22 }
23
24 class TwitterapiAction extends Action
25 {
26
27     var $auth_user;
28
29     /**
30      * Initialization.
31      *
32      * @param array $args Web and URL arguments
33      *
34      * @return boolean false if user doesn't exist
35      */
36
37     function prepare($args)
38     {
39         parent::prepare($args);
40         return true;
41     }
42
43     /**
44      * Handle a request
45      *
46      * @param array $args Arguments from $_REQUEST
47      *
48      * @return void
49      */
50
51     function handle($args)
52     {
53         parent::handle($args);
54     }
55
56     /**
57      * Overrides XMLOutputter::element to write booleans as strings (true|false).
58      * See that method's documentation for more info.
59      *
60      * @param string $tag     Element type or tagname
61      * @param array  $attrs   Array of element attributes, as
62      *                        key-value pairs
63      * @param string $content string content of the element
64      *
65      * @return void
66      */
67     function element($tag, $attrs=null, $content=null)
68     {
69         if (is_bool($content)) {
70             $content = ($content ? 'true' : 'false');
71         }
72
73         return parent::element($tag, $attrs, $content);
74     }
75
76     function twitter_user_array($profile, $get_notice=false)
77     {
78         $twitter_user = array();
79
80         $twitter_user['id'] = intval($profile->id);
81         $twitter_user['name'] = $profile->getBestName();
82         $twitter_user['screen_name'] = $profile->nickname;
83         $twitter_user['location'] = ($profile->location) ? $profile->location : null;
84         $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
85
86         $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
87         $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
88             Avatar::defaultImage(AVATAR_STREAM_SIZE);
89
90         $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
91         $twitter_user['protected'] = false; # not supported by Laconica yet
92         $twitter_user['followers_count'] = $profile->subscriberCount();
93
94         // To be supported soon...
95         $twitter_user['profile_background_color'] = '';
96         $twitter_user['profile_text_color'] = '';
97         $twitter_user['profile_link_color'] = '';
98         $twitter_user['profile_sidebar_fill_color'] = '';
99         $twitter_user['profile_sidebar_border_color'] = '';
100
101         $twitter_user['friends_count'] = $profile->subscriptionCount();
102
103         $twitter_user['created_at'] = $this->date_twitter($profile->created);
104
105         $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
106
107         // Need to pull up the user for some of this
108         $user = User::staticGet($profile->id);
109
110         $timezone = 'UTC';
111
112         if ($user->timezone) {
113             $timezone = $user->timezone;
114         }
115
116         $t = new DateTime;
117         $t->setTimezone(new DateTimeZone($timezone));
118
119         $twitter_user['utc_offset'] = $t->format('Z');
120         $twitter_user['time_zone'] = $timezone;
121
122         // To be supported some day, perhaps
123         $twitter_user['profile_background_image_url'] = '';
124         $twitter_user['profile_background_tile'] = false;
125
126         $twitter_user['statuses_count'] = $profile->noticeCount();
127
128         // Is the requesting user following this user?
129         $twitter_user['following'] = false;
130         $twitter_user['notifications'] = false;
131
132         if (isset($apidata['user'])) {
133
134             $twitter_user['following'] = $apidata['user']->isSubscribed($profile);
135
136             // Notifications on?
137             $sub = Subscription::pkeyGet(array('subscriber' =>
138                 $apidata['user']->id, 'subscribed' => $profile->id));
139
140             if ($sub) {
141                 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
142             }
143         }
144
145         if ($get_notice) {
146             $notice = $profile->getCurrentNotice();
147             if ($notice) {
148                 # don't get user!
149                 $twitter_user['status'] = $this->twitter_status_array($notice, false);
150             }
151         }
152
153         return $twitter_user;
154     }
155
156     function twitter_status_array($notice, $include_user=true)
157     {
158         $profile = $notice->getProfile();
159
160         $twitter_status = array();
161         $twitter_status['text'] = $notice->content;
162         $twitter_status['truncated'] = false; # Not possible on Laconica
163         $twitter_status['created_at'] = $this->date_twitter($notice->created);
164         $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
165             intval($notice->reply_to) : null;
166         $twitter_status['source'] = $this->source_link($notice->source);
167         $twitter_status['id'] = intval($notice->id);
168
169         $replier_profile = null;
170
171         if ($notice->reply_to) {
172             $reply = Notice::staticGet(intval($notice->reply_to));
173             if ($reply) {
174                 $replier_profile = $reply->getProfile();
175             }
176         }
177
178         $twitter_status['in_reply_to_user_id'] =
179             ($replier_profile) ? intval($replier_profile->id) : null;
180         $twitter_status['in_reply_to_screen_name'] =
181             ($replier_profile) ? $replier_profile->nickname : null;
182
183         if (isset($this->auth_user)) {
184             $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
185         } else {
186             $twitter_status['favorited'] = false;
187         }
188
189         // Enclosures
190         $attachments = $notice->attachments();
191         $enclosures = array();
192
193         foreach ($attachments as $attachment) {
194             if ($attachment->isEnclosure()) {
195                  $enclosure = array();
196                  $enclosure['url'] = $attachment->url;
197                  $enclosure['mimetype'] = $attachment->mimetype;
198                  $enclosure['size'] = $attachment->size;
199                  $enclosures[] = $enclosure;
200             }
201         }
202
203         if (!empty($enclosures)) {
204             $twitter_status['attachments'] = $enclosures;
205         }
206
207         if ($include_user) {
208             # Don't get notice (recursive!)
209             $twitter_user = $this->twitter_user_array($profile, false);
210             $twitter_status['user'] = $twitter_user;
211         }
212
213         return $twitter_status;
214     }
215
216     function twitter_rss_entry_array($notice)
217     {
218         $profile = $notice->getProfile();
219         $entry = array();
220
221         // We trim() to avoid extraneous whitespace in the output
222
223         $entry['content'] = common_xml_safe_str(trim($notice->rendered));
224         $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
225         $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
226         $entry['published'] = common_date_iso8601($notice->created);
227
228         $taguribase = common_config('integration', 'taguri');
229         $entry['id'] = "tag:$taguribase:$entry[link]";
230
231         $entry['updated'] = $entry['published'];
232         $entry['author'] = $profile->getBestName();
233
234         // Enclosures
235         $attachments = $notice->attachments();
236         $enclosures = array();
237
238         foreach ($attachments as $attachment) {
239             if ($attachment->isEnclosure()) {
240                  $enclosure = array();
241                  $enclosure['url'] = $attachment->url;
242                  $enclosure['mimetype'] = $attachment->mimetype;
243                  $enclosure['size'] = $attachment->size;
244                  $enclosures[] = $enclosure;
245             }
246         }
247
248         if (!empty($enclosures)) {
249             $entry['enclosures'] = $enclosures;
250         }
251
252 /*
253         // Enclosure
254         $attachments = $notice->attachments();
255         if($attachments){
256             $entry['enclosures']=array();
257             foreach($attachments as $attachment){
258                 if ($attachment->isEnclosure()) {
259                     $enclosure=array();
260                     $enclosure['url']=$attachment->url;
261                     $enclosure['mimetype']=$attachment->mimetype;
262                     $enclosure['size']=$attachment->size;
263                     $entry['enclosures'][]=$enclosure;
264                 }
265             }
266         }
267 */
268         // RSS Item specific
269         $entry['description'] = $entry['content'];
270         $entry['pubDate'] = common_date_rfc2822($notice->created);
271         $entry['guid'] = $entry['link'];
272
273         return $entry;
274     }
275
276     function twitter_rss_dmsg_array($message)
277     {
278
279         $entry = array();
280
281         $entry['title'] = sprintf('Message from %s to %s',
282             $message->getFrom()->nickname, $message->getTo()->nickname);
283
284         $entry['content'] = common_xml_safe_str(trim($message->content));
285         $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
286         $entry['published'] = common_date_iso8601($message->created);
287
288         $taguribase = common_config('integration', 'taguri');
289
290         $entry['id'] = "tag:$taguribase,:$entry[link]";
291         $entry['updated'] = $entry['published'];
292         $entry['author'] = $message->getFrom()->getBestName();
293
294         # RSS Item specific
295         $entry['description'] = $entry['content'];
296         $entry['pubDate'] = common_date_rfc2822($message->created);
297         $entry['guid'] = $entry['link'];
298
299         return $entry;
300     }
301
302     function twitter_dmsg_array($message)
303     {
304         $twitter_dm = array();
305
306         $from_profile = $message->getFrom();
307         $to_profile = $message->getTo();
308
309         $twitter_dm['id'] = $message->id;
310         $twitter_dm['sender_id'] = $message->from_profile;
311         $twitter_dm['text'] = trim($message->content);
312         $twitter_dm['recipient_id'] = $message->to_profile;
313         $twitter_dm['created_at'] = $this->date_twitter($message->created);
314         $twitter_dm['sender_screen_name'] = $from_profile->nickname;
315         $twitter_dm['recipient_screen_name'] = $to_profile->nickname;
316         $twitter_dm['sender'] = $this->twitter_user_array($from_profile, false);
317         $twitter_dm['recipient'] = $this->twitter_user_array($to_profile, false);
318
319         return $twitter_dm;
320     }
321
322     function twitter_relationship_array($source, $target)
323     {
324         $relationship = array();
325
326         $relationship['source'] =
327             $this->relationship_details_array($source, $target);
328         $relationship['target'] =
329             $this->relationship_details_array($target, $source);
330
331         return array('relationship' => $relationship);
332     }
333
334     function relationship_details_array($source, $target)
335     {
336         $details = array();
337
338         $details['screen_name'] = $source->nickname;
339         $details['followed_by'] = $target->isSubscribed($source);
340         $details['following'] = $source->isSubscribed($target);
341
342         $notifications = false;
343
344         if ($source->isSubscribed($target)) {
345
346             $sub = Subscription::pkeyGet(array('subscriber' =>
347                 $source->id, 'subscribed' => $target->id));
348
349             if (!empty($sub)) {
350                 $notifications = ($sub->jabber || $sub->sms);
351             }
352         }
353
354         $details['notifications_enabled'] = $notifications;
355         $details['blocking'] = $source->hasBlocked($target);
356         $details['id'] = $source->id;
357
358         return $details;
359     }
360
361     function show_twitter_xml_relationship($relationship)
362     {
363         $this->elementStart('relationship');
364
365         foreach($relationship as $element => $value) {
366             if ($element == 'source' || $element == 'target') {
367                 $this->elementStart($element);
368                 $this->show_xml_relationship_details($value);
369                 $this->elementEnd($element);
370             }
371         }
372
373         $this->elementEnd('relationship');
374     }
375
376     function show_xml_relationship_details($details)
377     {
378         foreach($details as $element => $value) {
379             $this->element($element, null, $value);
380         }
381     }
382
383     function show_twitter_xml_status($twitter_status)
384     {
385         $this->elementStart('status');
386         foreach($twitter_status as $element => $value) {
387             switch ($element) {
388             case 'user':
389                 $this->show_twitter_xml_user($twitter_status['user']);
390                 break;
391             case 'text':
392                 $this->element($element, null, common_xml_safe_str($value));
393                 break;
394             case 'attachments':
395                 $this->show_xml_attachments($twitter_status['attachments']);
396                 break;
397             default:
398                 $this->element($element, null, $value);
399             }
400         }
401         $this->elementEnd('status');
402     }
403
404     function show_twitter_xml_user($twitter_user, $role='user')
405     {
406         $this->elementStart($role);
407         foreach($twitter_user as $element => $value) {
408             if ($element == 'status') {
409                 $this->show_twitter_xml_status($twitter_user['status']);
410             } else {
411                 $this->element($element, null, $value);
412             }
413         }
414         $this->elementEnd($role);
415     }
416
417     function show_xml_attachments($attachments) {
418         if (!empty($attachments)) {
419             $this->elementStart('attachments', array('type' => 'array'));
420             foreach ($attachments as $attachment) {
421                 $attrs = array();
422                 $attrs['url'] = $attachment['url'];
423                 $attrs['mimetype'] = $attachment['mimetype'];
424                 $attrs['size'] = $attachment['size'];
425                 $this->element('enclosure', $attrs, '');
426             }
427             $this->elementEnd('attachments');
428         }
429     }
430
431     function show_twitter_rss_item($entry)
432     {
433         $this->elementStart('item');
434         $this->element('title', null, $entry['title']);
435         $this->element('description', null, $entry['description']);
436         $this->element('pubDate', null, $entry['pubDate']);
437         $this->element('guid', null, $entry['guid']);
438         $this->element('link', null, $entry['link']);
439
440         # RSS only supports 1 enclosure per item
441         if($entry['enclosures']){
442             $enclosure = $entry['enclosures'][0];
443             $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
444         }
445
446         $this->elementEnd('item');
447     }
448
449     function show_json_objects($objects)
450     {
451         print(json_encode($objects));
452     }
453
454     function show_single_xml_status($notice)
455     {
456         $this->init_document('xml');
457         $twitter_status = $this->twitter_status_array($notice);
458         $this->show_twitter_xml_status($twitter_status);
459         $this->end_document('xml');
460     }
461
462     function show_single_json_status($notice)
463     {
464         $this->init_document('json');
465         $status = $this->twitter_status_array($notice);
466         $this->show_json_objects($status);
467         $this->end_document('json');
468     }
469
470     function show_single_xml_dmsg($message)
471     {
472         $this->init_document('xml');
473         $dmsg = $this->twitter_dmsg_array($message);
474         $this->show_twitter_xml_dmsg($dmsg);
475         $this->end_document('xml');
476     }
477
478     function show_single_json_dmsg($message)
479     {
480         $this->init_document('json');
481         $dmsg = $this->twitter_dmsg_array($message);
482         $this->show_json_objects($dmsg);
483         $this->end_document('json');
484     }
485
486     function show_twitter_xml_dmsg($twitter_dm)
487     {
488         $this->elementStart('direct_message');
489         foreach($twitter_dm as $element => $value) {
490             switch ($element) {
491             case 'sender':
492             case 'recipient':
493                 $this->show_twitter_xml_user($value, $element);
494                 break;
495             case 'text':
496                 $this->element($element, null, common_xml_safe_str($value));
497                 break;
498             default:
499                 $this->element($element, null, $value);
500             }
501         }
502         $this->elementEnd('direct_message');
503     }
504
505     function show_xml_timeline($notice)
506     {
507
508         $this->init_document('xml');
509         $this->elementStart('statuses', array('type' => 'array'));
510
511         if (is_array($notice)) {
512             foreach ($notice as $n) {
513                 $twitter_status = $this->twitter_status_array($n);
514                 $this->show_twitter_xml_status($twitter_status);
515             }
516         } else {
517             while ($notice->fetch()) {
518                 $twitter_status = $this->twitter_status_array($notice);
519                 $this->show_twitter_xml_status($twitter_status);
520             }
521         }
522
523         $this->elementEnd('statuses');
524         $this->end_document('xml');
525     }
526
527     function show_rss_timeline($notice, $title, $link, $subtitle, $suplink=null)
528     {
529
530         $this->init_document('rss');
531
532         $this->elementStart('channel');
533         $this->element('title', null, $title);
534         $this->element('link', null, $link);
535         if (!is_null($suplink)) {
536             # For FriendFeed's SUP protocol
537             $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
538                                          'rel' => 'http://api.friendfeed.com/2008/03#sup',
539                                          'href' => $suplink,
540                                          'type' => 'application/json'));
541         }
542         $this->element('description', null, $subtitle);
543         $this->element('language', null, 'en-us');
544         $this->element('ttl', null, '40');
545
546         if (is_array($notice)) {
547             foreach ($notice as $n) {
548                 $entry = $this->twitter_rss_entry_array($n);
549                 $this->show_twitter_rss_item($entry);
550             }
551         } else {
552             while ($notice->fetch()) {
553                 $entry = $this->twitter_rss_entry_array($notice);
554                 $this->show_twitter_rss_item($entry);
555             }
556         }
557
558         $this->elementEnd('channel');
559         $this->end_twitter_rss();
560     }
561
562     function show_atom_timeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
563     {
564
565         $this->init_document('atom');
566
567         $this->element('title', null, $title);
568         $this->element('id', null, $id);
569         $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
570
571         if (!is_null($suplink)) {
572             # For FriendFeed's SUP protocol
573             $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
574                                          'href' => $suplink,
575                                          'type' => 'application/json'));
576         }
577
578         if (!is_null($selfuri)) {
579             $this->element('link', array('href' => $selfuri,
580                 'rel' => 'self', 'type' => 'application/atom+xml'), null);
581         }
582
583         $this->element('updated', null, common_date_iso8601('now'));
584         $this->element('subtitle', null, $subtitle);
585
586         if (is_array($notice)) {
587             foreach ($notice as $n) {
588                 $this->raw($n->asAtomEntry());
589             }
590         } else {
591             while ($notice->fetch()) {
592                 $this->raw($notice->asAtomEntry());
593             }
594         }
595
596         $this->end_document('atom');
597
598     }
599
600     function show_json_timeline($notice)
601     {
602
603         $this->init_document('json');
604
605         $statuses = array();
606
607         if (is_array($notice)) {
608             foreach ($notice as $n) {
609                 $twitter_status = $this->twitter_status_array($n);
610                 array_push($statuses, $twitter_status);
611             }
612         } else {
613             while ($notice->fetch()) {
614                 $twitter_status = $this->twitter_status_array($notice);
615                 array_push($statuses, $twitter_status);
616             }
617         }
618
619         $this->show_json_objects($statuses);
620
621         $this->end_document('json');
622     }
623
624     // Anyone know what date format this is?
625     // Twitter's dates look like this: "Mon Jul 14 23:52:38 +0000 2008" -- Zach
626     function date_twitter($dt)
627     {
628         $t = strtotime($dt);
629         return date("D M d H:i:s O Y", $t);
630     }
631
632     // XXX: Candidate for a general utility method somewhere?
633     function count_subscriptions($profile)
634     {
635
636         $count = 0;
637         $sub = new Subscription();
638         $sub->subscribed = $profile->id;
639
640         $count = $sub->find();
641
642         if ($count > 0) {
643             return $count - 1;
644         } else {
645             return 0;
646         }
647     }
648
649     function init_document($type='xml')
650     {
651         switch ($type) {
652         case 'xml':
653             header('Content-Type: application/xml; charset=utf-8');
654             $this->startXML();
655             break;
656         case 'json':
657             header('Content-Type: application/json; charset=utf-8');
658
659             // Check for JSONP callback
660             $callback = $this->arg('callback');
661             if ($callback) {
662                 print $callback . '(';
663             }
664             break;
665         case 'rss':
666             header("Content-Type: application/rss+xml; charset=utf-8");
667             $this->init_twitter_rss();
668             break;
669         case 'atom':
670             header('Content-Type: application/atom+xml; charset=utf-8');
671             $this->init_twitter_atom();
672             break;
673         default:
674             $this->clientError(_('Not a supported data format.'));
675             break;
676         }
677
678         return;
679     }
680
681     function end_document($type='xml')
682     {
683         switch ($type) {
684         case 'xml':
685             $this->endXML();
686             break;
687         case 'json':
688
689             // Check for JSONP callback
690             $callback = $this->arg('callback');
691             if ($callback) {
692                 print ')';
693             }
694             break;
695         case 'rss':
696             $this->end_twitter_rss();
697             break;
698         case 'atom':
699             $this->end_twitter_rss();
700             break;
701         default:
702             $this->clientError(_('Not a supported data format.'));
703             break;
704         }
705         return;
706     }
707
708     function clientError($msg, $code = 400, $content_type = 'json')
709     {
710
711         static $status = array(400 => 'Bad Request',
712                                401 => 'Unauthorized',
713                                402 => 'Payment Required',
714                                403 => 'Forbidden',
715                                404 => 'Not Found',
716                                405 => 'Method Not Allowed',
717                                406 => 'Not Acceptable',
718                                407 => 'Proxy Authentication Required',
719                                408 => 'Request Timeout',
720                                409 => 'Conflict',
721                                410 => 'Gone',
722                                411 => 'Length Required',
723                                412 => 'Precondition Failed',
724                                413 => 'Request Entity Too Large',
725                                414 => 'Request-URI Too Long',
726                                415 => 'Unsupported Media Type',
727                                416 => 'Requested Range Not Satisfiable',
728                                417 => 'Expectation Failed');
729
730         $action = $this->trimmed('action');
731
732         common_debug("User error '$code' on '$action': $msg", __FILE__);
733
734         if (!array_key_exists($code, $status)) {
735             $code = 400;
736         }
737
738         $status_string = $status[$code];
739         header('HTTP/1.1 '.$code.' '.$status_string);
740
741         if ($content_type == 'xml') {
742             $this->init_document('xml');
743             $this->elementStart('hash');
744             $this->element('error', null, $msg);
745             $this->element('request', null, $_SERVER['REQUEST_URI']);
746             $this->elementEnd('hash');
747             $this->end_document('xml');
748         } else {
749             $this->init_document('json');
750             $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
751             print(json_encode($error_array));
752             $this->end_document('json');
753         }
754
755     }
756
757     function init_twitter_rss()
758     {
759         $this->startXML();
760         $this->elementStart('rss', array('version' => '2.0'));
761     }
762
763     function end_twitter_rss()
764     {
765         $this->elementEnd('rss');
766         $this->endXML();
767     }
768
769     function init_twitter_atom()
770     {
771         $this->startXML();
772         // FIXME: don't hardcode the language here!
773         $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
774                                           'xml:lang' => 'en-US',
775                                           'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
776     }
777
778     function end_twitter_atom()
779     {
780         $this->elementEnd('feed');
781         $this->endXML();
782     }
783
784     function show_profile($profile, $content_type='xml', $notice=null)
785     {
786         $profile_array = $this->twitter_user_array($profile, true);
787         switch ($content_type) {
788         case 'xml':
789             $this->show_twitter_xml_user($profile_array);
790             break;
791         case 'json':
792             $this->show_json_objects($profile_array);
793             break;
794         default:
795             $this->clientError(_('Not a supported data format.'));
796             return;
797         }
798         return;
799     }
800
801     function get_user($id, $apidata=null)
802     {
803         if (empty($id)) {
804
805             // Twitter supports these other ways of passing the user ID
806             if (is_numeric($this->arg('id'))) {
807                 return User::staticGet($this->arg('id'));
808             } else if ($this->arg('id')) {
809                 $nickname = common_canonical_nickname($this->arg('id'));
810                 return User::staticGet('nickname', $nickname);
811             } else if ($this->arg('user_id')) {
812                 // This is to ensure that a non-numeric user_id still
813                 // overrides screen_name even if it doesn't get used
814                 if (is_numeric($this->arg('user_id'))) {
815                     return User::staticGet('id', $this->arg('user_id'));
816                 }
817             } else if ($this->arg('screen_name')) {
818                 $nickname = common_canonical_nickname($this->arg('screen_name'));
819                 return User::staticGet('nickname', $nickname);
820             } else {
821                 // Fall back to trying the currently authenticated user
822                 return $apidata['user'];
823             }
824
825         } else if (is_numeric($id)) {
826             return User::staticGet($id);
827         } else {
828             $nickname = common_canonical_nickname($id);
829             return User::staticGet('nickname', $nickname);
830         }
831     }
832
833     function get_group($id, $apidata=null)
834     {
835         if (empty($id)) {
836
837             if (is_numeric($this->arg('id'))) {
838                 return User_group::staticGet($this->arg('id'));
839             } else if ($this->arg('id')) {
840                 $nickname = common_canonical_nickname($this->arg('id'));
841                 return User_group::staticGet('nickname', $nickname);
842             } else if ($this->arg('group_id')) {
843                 // This is to ensure that a non-numeric user_id still
844                 // overrides screen_name even if it doesn't get used
845                 if (is_numeric($this->arg('group_id'))) {
846                     return User_group::staticGet('id', $this->arg('group_id'));
847                 }
848             } else if ($this->arg('group_name')) {
849                 $nickname = common_canonical_nickname($this->arg('group_name'));
850                 return User_group::staticGet('nickname', $nickname);
851             }
852
853         } else if (is_numeric($id)) {
854             return User_group::staticGet($id);
855         } else {
856             $nickname = common_canonical_nickname($id);
857             return User_group::staticGet('nickname', $nickname);
858         }
859     }
860
861     function get_profile($id)
862     {
863         if (is_numeric($id)) {
864             return Profile::staticGet($id);
865         } else {
866             $user = User::staticGet('nickname', $id);
867             if ($user) {
868                 return $user->getProfile();
869             } else {
870                 return null;
871             }
872         }
873     }
874
875     function source_link($source)
876     {
877         $source_name = _($source);
878         switch ($source) {
879         case 'web':
880         case 'xmpp':
881         case 'mail':
882         case 'omb':
883         case 'api':
884             break;
885         default:
886             $ns = Notice_source::staticGet($source);
887             if ($ns) {
888                 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
889             }
890             break;
891         }
892         return $source_name;
893     }
894
895     /**
896      * Returns query argument or default value if not found. Certain
897      * parameters used throughout the API are lightly scrubbed and
898      * bounds checked.  This overrides Action::arg().
899      *
900      * @param string $key requested argument
901      * @param string $def default value to return if $key is not provided
902      *
903      * @return var $var
904      */
905     function arg($key, $def=null)
906     {
907
908         // XXX: Do even more input validation/scrubbing?
909
910         if (array_key_exists($key, $this->args)) {
911             switch($key) {
912             case 'page':
913                 $page = (int)$this->args['page'];
914                 return ($page < 1) ? 1 : $page;
915             case 'count':
916                 $count = (int)$this->args['count'];
917                 if ($count < 1) {
918                     return 20;
919                 } elseif ($count > 200) {
920                     return 200;
921                 } else {
922                     return $count;
923                 }
924             case 'since_id':
925                 $since_id = (int)$this->args['since_id'];
926                 return ($since_id < 1) ? 0 : $since_id;
927             case 'max_id':
928                 $max_id = (int)$this->args['max_id'];
929                 return ($max_id < 1) ? 0 : $max_id;
930             case 'since':
931                 return strtotime($this->args['since']);
932             default:
933                 return parent::arg($key, $def);
934             }
935         } else {
936             return $def;
937         }
938     }
939
940 }