api.php 42 KB
Newer Older
1
<?php
2 3
/**
 * StatusNet, the distributed open-source microblogging tool
4
 *
5 6 7 8 9
 * Base API action
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
10 11 12 13 14 15 16 17 18 19 20
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 22 23
 *
 * @category  API
 * @package   StatusNet
Zach Copley's avatar
Zach Copley committed
24 25 26 27 28
 * @author    Craig Andrews <candrews@integralblue.com>
 * @author    Dan Moore <dan@moore.cx>
 * @author    Evan Prodromou <evan@status.net>
 * @author    Jeffery To <jeffery.to@gmail.com>
 * @author    Toby Inkster <mail@tobyinkster.co.uk>
29 30 31 32
 * @author    Zach Copley <zach@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
33 34
 */

35
if (!defined('STATUSNET')) {
36 37
    exit(1);
}
38

39 40 41 42 43
/**
 * Contains most of the Twitter-compatible API output functions.
 *
 * @category API
 * @package  StatusNet
Zach Copley's avatar
Zach Copley committed
44 45 46 47 48
 * @author   Craig Andrews <candrews@integralblue.com>
 * @author   Dan Moore <dan@moore.cx>
 * @author   Evan Prodromou <evan@status.net>
 * @author   Jeffery To <jeffery.to@gmail.com>
 * @author   Toby Inkster <mail@tobyinkster.co.uk>
49 50 51 52 53 54
 * @author   Zach Copley <zach@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */

class ApiAction extends Action
55
{
56 57 58 59 60 61 62 63
    var $format    = null;
    var $user      = null;
    var $auth_user = null;
    var $page      = null;
    var $count     = null;
    var $max_id    = null;
    var $since_id  = null;
    var $since     = null;
64

65 66 67 68 69
    /**
     * Initialization.
     *
     * @param array $args Web and URL arguments
     *
70
     * @return boolean false if user doesn't exist
71 72 73 74 75
     */

    function prepare($args)
    {
        parent::prepare($args);
76

77
        $this->format   = $this->arg('format');
78 79 80 81 82
        $this->page     = (int)$this->arg('page', 1);
        $this->count    = (int)$this->arg('count', 20);
        $this->max_id   = (int)$this->arg('max_id', 0);
        $this->since_id = (int)$this->arg('since_id', 0);
        $this->since    = $this->arg('since');
83

84 85 86 87 88 89 90 91 92 93 94
        return true;
    }

    /**
     * Handle a request
     *
     * @param array $args Arguments from $_REQUEST
     *
     * @return void
     */

95 96
    function handle($args)
    {
97 98
        parent::handle($args);
    }
99

100 101 102
    /**
     * Overrides XMLOutputter::element to write booleans as strings (true|false).
     * See that method's documentation for more info.
103
     *
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
     * @param string $tag     Element type or tagname
     * @param array  $attrs   Array of element attributes, as
     *                        key-value pairs
     * @param string $content string content of the element
     *
     * @return void
     */
    function element($tag, $attrs=null, $content=null)
    {
        if (is_bool($content)) {
            $content = ($content ? 'true' : 'false');
        }

        return parent::element($tag, $attrs, $content);
    }
119

120
    function twitterUserArray($profile, $get_notice=false)
121
    {
122
        $twitter_user = array();
123

124
        $twitter_user['id'] = intval($profile->id);
125 126
        $twitter_user['name'] = $profile->getBestName();
        $twitter_user['screen_name'] = $profile->nickname;
Evan Prodromou's avatar
Evan Prodromou committed
127
        $twitter_user['location'] = ($profile->location) ? $profile->location : null;
128
        $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
129

130
        $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
131 132
        $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
            Avatar::defaultImage(AVATAR_STREAM_SIZE);
133

Evan Prodromou's avatar
Evan Prodromou committed
134
        $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
135
        $twitter_user['protected'] = false; # not supported by StatusNet yet
136
        $twitter_user['followers_count'] = $profile->subscriberCount();
137

138
        $design        = null;
139
        $user          = $profile->getUser();
140

141
        // Note: some profiles don't have an associated user
142 143 144 145 146

        if (!empty($user)) {
            $design = $user->getDesign();
        }

147 148 149 150
        if (empty($design)) {
            $design = Design::siteDesign();
        }

151 152 153 154 155 156 157 158
        $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
        $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
        $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
        $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
        $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
        $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
        $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
        $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
159 160
        $twitter_user['profile_sidebar_border_color'] = '';

161
        $twitter_user['friends_count'] = $profile->subscriptionCount();
162

163
        $twitter_user['created_at'] = $this->dateTwitter($profile->created);
164

165
        $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
166 167 168

        $timezone = 'UTC';

169
        if ($user->timezone) {
170 171 172 173 174 175 176 177 178
            $timezone = $user->timezone;
        }

        $t = new DateTime;
        $t->setTimezone(new DateTimeZone($timezone));

        $twitter_user['utc_offset'] = $t->format('Z');
        $twitter_user['time_zone'] = $timezone;

179 180 181 182 183 184 185 186
        $twitter_user['profile_background_image_url']
            = empty($design->backgroundimage)
            ? '' : ($design->disposition & BACKGROUND_ON)
            ? Design::url($design->backgroundimage) : '';

        $twitter_user['profile_background_tile']
            = empty($design->disposition)
            ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
187

188
        $twitter_user['statuses_count'] = $profile->noticeCount();
189 190 191 192 193

        // Is the requesting user following this user?
        $twitter_user['following'] = false;
        $twitter_user['notifications'] = false;

194
        if (isset($this->auth_user)) {
195

196
            $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
197 198 199

            // Notifications on?
            $sub = Subscription::pkeyGet(array('subscriber' =>
200 201
                                               $this->auth_user->id,
                                               'subscribed' => $profile->id));
202 203 204 205 206

            if ($sub) {
                $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
            }
        }
Evan Prodromou's avatar
Evan Prodromou committed
207

208 209 210
        if ($get_notice) {
            $notice = $profile->getCurrentNotice();
            if ($notice) {
211
                # don't get user!
212
                $twitter_user['status'] = $this->twitterStatusArray($notice, false);
213 214
            }
        }
215

216 217
        return $twitter_user;
    }
218

219
    function twitterStatusArray($notice, $include_user=true)
220 221 222
    {
        $base = $this->twitterSimpleStatusArray($notice, $include_user);

223
        if (!empty($notice->repeat_of)) {
224
            $original = Notice::staticGet('id', $notice->repeat_of);
225
            if (!empty($original)) {
226
                $original_array = $this->twitterSimpleStatusArray($original, $include_user);
227
                $base['retweeted_status'] = $original_array;
228
            }
229
        }
230 231

        return $base;
232 233 234
    }

    function twitterSimpleStatusArray($notice, $include_user=true)
235
    {
236
        $profile = $notice->getProfile();
237

238 239
        $twitter_status = array();
        $twitter_status['text'] = $notice->content;
240
        $twitter_status['truncated'] = false; # Not possible on StatusNet
241
        $twitter_status['created_at'] = $this->dateTwitter($notice->created);
242 243
        $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
            intval($notice->reply_to) : null;
244
        $twitter_status['source'] = $this->sourceLink($notice->source);
245
        $twitter_status['id'] = intval($notice->id);
246 247 248 249 250 251 252 253 254 255 256 257 258 259

        $replier_profile = null;

        if ($notice->reply_to) {
            $reply = Notice::staticGet(intval($notice->reply_to));
            if ($reply) {
                $replier_profile = $reply->getProfile();
            }
        }

        $twitter_status['in_reply_to_user_id'] =
            ($replier_profile) ? intval($replier_profile->id) : null;
        $twitter_status['in_reply_to_screen_name'] =
            ($replier_profile) ? $replier_profile->nickname : null;
260

261 262 263 264 265 266 267 268 269
        if (isset($notice->lat) && isset($notice->lon)) {
            // This is the format that GeoJSON expects stuff to be in
            $twitter_status['geo'] = array('type' => 'Point',
                                           'coordinates' => array((float) $notice->lat,
                                                                  (float) $notice->lon));
        } else {
            $twitter_status['geo'] = null;
        }

270
        if (isset($this->auth_user)) {
271
            $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
272
        } else {
273
            $twitter_status['favorited'] = false;
274
        }
Evan Prodromou's avatar
Evan Prodromou committed
275

276
        // Enclosures
277 278
        $attachments = $notice->attachments();

279 280 281 282 283
        if (!empty($attachments)) {

            $twitter_status['attachments'] = array();

            foreach ($attachments as $attachment) {
284
                if ($attachment->isEnclosure()) {
285 286 287 288 289
                    $enclosure = array();
                    $enclosure['url'] = $attachment->url;
                    $enclosure['mimetype'] = $attachment->mimetype;
                    $enclosure['size'] = $attachment->size;
                    $twitter_status['attachments'][] = $enclosure;
290 291
                }
            }
292 293
        }

294
        if ($include_user) {
295
            # Don't get notice (recursive!)
296
            $twitter_user = $this->twitterUserArray($profile, false);
297 298
            $twitter_status['user'] = $twitter_user;
        }
299

300 301
        return $twitter_status;
    }
302

303
    function twitterGroupArray($group)
304 305 306
    {
        $twitter_group=array();
        $twitter_group['id']=$group->id;
307
        $twitter_group['url']=$group->permalink();
308 309
        $twitter_group['nickname']=$group->nickname;
        $twitter_group['fullname']=$group->fullname;
310
        $twitter_group['homepage_url']=$group->homepage_url;
311 312 313 314 315 316 317
        $twitter_group['original_logo']=$group->original_logo;
        $twitter_group['homepage_logo']=$group->homepage_logo;
        $twitter_group['stream_logo']=$group->stream_logo;
        $twitter_group['mini_logo']=$group->mini_logo;
        $twitter_group['homepage']=$group->homepage;
        $twitter_group['description']=$group->description;
        $twitter_group['location']=$group->location;
318 319
        $twitter_group['created']=$this->dateTwitter($group->created);
        $twitter_group['modified']=$this->dateTwitter($group->modified);
320 321 322
        return $twitter_group;
    }

323
    function twitterRssGroupArray($group)
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    {
        $entry = array();
        $entry['content']=$group->description;
        $entry['title']=$group->nickname;
        $entry['link']=$group->permalink();
        $entry['published']=common_date_iso8601($group->created);
        $entry['updated']==common_date_iso8601($group->modified);
        $taguribase = common_config('integration', 'groupuri');
        $entry['id'] = "group:$groupuribase:$entry[link]";

        $entry['description'] = $entry['content'];
        $entry['pubDate'] = common_date_rfc2822($group->created);
        $entry['guid'] = $entry['link'];

        return $entry;
    }

341
    function twitterRssEntryArray($notice)
342
    {
343 344
        $profile = $notice->getProfile();
        $entry = array();
345

346
        // We trim() to avoid extraneous whitespace in the output
347

348 349 350 351
        $entry['content'] = common_xml_safe_str(trim($notice->rendered));
        $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
        $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
        $entry['published'] = common_date_iso8601($notice->created);
352 353 354 355

        $taguribase = common_config('integration', 'taguri');
        $entry['id'] = "tag:$taguribase:$entry[link]";

356
        $entry['updated'] = $entry['published'];
357
        $entry['author'] = $profile->getBestName();
358

359 360 361 362 363
        // Enclosures
        $attachments = $notice->attachments();
        $enclosures = array();

        foreach ($attachments as $attachment) {
364 365
            $enclosure_o=$attachment->getEnclosure();
            if ($enclosure_o) {
366
                 $enclosure = array();
367 368 369
                 $enclosure['url'] = $enclosure_o->url;
                 $enclosure['mimetype'] = $enclosure_o->mimetype;
                 $enclosure['size'] = $enclosure_o->size;
370 371 372 373 374 375 376 377
                 $enclosures[] = $enclosure;
            }
        }

        if (!empty($enclosures)) {
            $entry['enclosures'] = $enclosures;
        }

378 379 380 381 382 383 384 385 386 387 388
        // Tags/Categories
        $tag = new Notice_tag();
        $tag->notice_id = $notice->id;
        if ($tag->find()) {
            $entry['tags']=array();
            while ($tag->fetch()) {
                $entry['tags'][]=$tag->tag;
            }
        }
        $tag->free();

389
        // RSS Item specific
390 391 392 393
        $entry['description'] = $entry['content'];
        $entry['pubDate'] = common_date_rfc2822($notice->created);
        $entry['guid'] = $entry['link'];

394 395 396 397 398 399 400 401 402 403
        if (isset($notice->lat) && isset($notice->lon)) {
            // This is the format that GeoJSON expects stuff to be in.
            // showGeoRSS() below uses it for XML output, so we reuse it
            $entry['geo'] = array('type' => 'Point',
                                  'coordinates' => array((float) $notice->lat,
                                                         (float) $notice->lon));
        } else {
            $entry['geo'] = null;
        }

404 405 406
        return $entry;
    }

407
    function twitterRelationshipArray($source, $target)
408 409 410 411
    {
        $relationship = array();

        $relationship['source'] =
412
            $this->relationshipDetailsArray($source, $target);
413
        $relationship['target'] =
414
            $this->relationshipDetailsArray($target, $source);
415 416 417 418

        return array('relationship' => $relationship);
    }

419
    function relationshipDetailsArray($source, $target)
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    {
        $details = array();

        $details['screen_name'] = $source->nickname;
        $details['followed_by'] = $target->isSubscribed($source);
        $details['following'] = $source->isSubscribed($target);

        $notifications = false;

        if ($source->isSubscribed($target)) {

            $sub = Subscription::pkeyGet(array('subscriber' =>
                $source->id, 'subscribed' => $target->id));

            if (!empty($sub)) {
                $notifications = ($sub->jabber || $sub->sms);
            }
        }

        $details['notifications_enabled'] = $notifications;
        $details['blocking'] = $source->hasBlocked($target);
        $details['id'] = $source->id;

        return $details;
    }

446
    function showTwitterXmlRelationship($relationship)
447 448 449 450 451 452
    {
        $this->elementStart('relationship');

        foreach($relationship as $element => $value) {
            if ($element == 'source' || $element == 'target') {
                $this->elementStart($element);
453
                $this->showXmlRelationshipDetails($value);
454 455 456 457 458 459 460
                $this->elementEnd($element);
            }
        }

        $this->elementEnd('relationship');
    }

461
    function showXmlRelationshipDetails($details)
462 463 464 465 466 467
    {
        foreach($details as $element => $value) {
            $this->element($element, null, $value);
        }
    }

468
    function showTwitterXmlStatus($twitter_status, $tag='status')
469
    {
470
        $this->elementStart($tag);
471 472 473
        foreach($twitter_status as $element => $value) {
            switch ($element) {
            case 'user':
474
                $this->showTwitterXmlUser($twitter_status['user']);
475 476
                break;
            case 'text':
477
                $this->element($element, null, common_xml_safe_str($value));
478
                break;
479
            case 'attachments':
480
                $this->showXmlAttachments($twitter_status['attachments']);
481
                break;
482 483 484
            case 'geo':
                $this->showGeoRSS($value);
                break;
485 486 487
            case 'retweeted_status':
                $this->showTwitterXmlStatus($value, 'retweeted_status');
                break;
488
            default:
489
                $this->element($element, null, $value);
490 491
            }
        }
492
        $this->elementEnd($tag);
493 494
    }

495
    function showTwitterXmlGroup($twitter_group)
496 497 498 499 500 501 502 503
    {
        $this->elementStart('group');
        foreach($twitter_group as $element => $value) {
            $this->element($element, null, $value);
        }
        $this->elementEnd('group');
    }

504
    function showTwitterXmlUser($twitter_user, $role='user')
505
    {
506
        $this->elementStart($role);
507 508
        foreach($twitter_user as $element => $value) {
            if ($element == 'status') {
509
                $this->showTwitterXmlStatus($twitter_user['status']);
510
            } else {
511
                $this->element($element, null, $value);
512 513
            }
        }
514
        $this->elementEnd($role);
515 516
    }

517
    function showXmlAttachments($attachments) {
518 519 520 521 522 523 524 525 526 527 528 529 530
        if (!empty($attachments)) {
            $this->elementStart('attachments', array('type' => 'array'));
            foreach ($attachments as $attachment) {
                $attrs = array();
                $attrs['url'] = $attachment['url'];
                $attrs['mimetype'] = $attachment['mimetype'];
                $attrs['size'] = $attachment['size'];
                $this->element('enclosure', $attrs, '');
            }
            $this->elementEnd('attachments');
        }
    }

531 532 533 534 535 536 537 538 539 540 541 542
    function showGeoRSS($geo)
    {
        if (empty($geo)) {
            // empty geo element
            $this->element('geo');
        } else {
            $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
            $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
            $this->elementEnd('geo');
        }
    }

543
    function showTwitterRssItem($entry)
544
    {
545 546 547 548 549 550
        $this->elementStart('item');
        $this->element('title', null, $entry['title']);
        $this->element('description', null, $entry['description']);
        $this->element('pubDate', null, $entry['pubDate']);
        $this->element('guid', null, $entry['guid']);
        $this->element('link', null, $entry['link']);
551 552

        # RSS only supports 1 enclosure per item
553
        if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
554 555 556
            $enclosure = $entry['enclosures'][0];
            $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
        }
557

558
        if(array_key_exists('tags', $entry)){
559 560 561 562
            foreach($entry['tags'] as $tag){
                $this->element('category', null,$tag);
            }
        }
563

564
        $this->showGeoRSS($entry['geo']);
565
        $this->elementEnd('item');
566 567
    }

568
    function showJsonObjects($objects)
569
    {
570 571 572
        print(json_encode($objects));
    }

573
    function showSingleXmlStatus($notice)
574
    {
575 576 577 578
        $this->initDocument('xml');
        $twitter_status = $this->twitterStatusArray($notice);
        $this->showTwitterXmlStatus($twitter_status);
        $this->endDocument('xml');
579 580
    }

581 582
    function show_single_json_status($notice)
    {
583 584 585 586
        $this->initDocument('json');
        $status = $this->twitterStatusArray($notice);
        $this->showJsonObjects($status);
        $this->endDocument('json');
587 588
    }

589
    function showXmlTimeline($notice)
590
    {
591

592
        $this->initDocument('xml');
593
        $this->elementStart('statuses', array('type' => 'array'));
594 595 596

        if (is_array($notice)) {
            foreach ($notice as $n) {
597 598
                $twitter_status = $this->twitterStatusArray($n);
                $this->showTwitterXmlStatus($twitter_status);
599 600 601
            }
        } else {
            while ($notice->fetch()) {
602 603
                $twitter_status = $this->twitterStatusArray($notice);
                $this->showTwitterXmlStatus($twitter_status);
604 605 606
            }
        }

607
        $this->elementEnd('statuses');
608
        $this->endDocument('xml');
609 610
    }

611
    function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null)
612
    {
613

614
        $this->initDocument('rss');
615

616 617
        $this->element('title', null, $title);
        $this->element('link', null, $link);
618
        if (!is_null($suplink)) {
619
            // For FriendFeed's SUP protocol
620
            $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
621 622 623 624
                                         'rel' => 'http://api.friendfeed.com/2008/03#sup',
                                         'href' => $suplink,
                                         'type' => 'application/json'));
        }
625 626 627 628 629 630 631 632 633

        if (!is_null($logo)) {
            $this->elementStart('image');
            $this->element('link', null, $link);
            $this->element('title', null, $title);
            $this->element('url', null, $logo);
            $this->elementEnd('image');
        }

634 635 636
        $this->element('description', null, $subtitle);
        $this->element('language', null, 'en-us');
        $this->element('ttl', null, '40');
637 638 639

        if (is_array($notice)) {
            foreach ($notice as $n) {
640 641
                $entry = $this->twitterRssEntryArray($n);
                $this->showTwitterRssItem($entry);
642 643 644
            }
        } else {
            while ($notice->fetch()) {
645 646
                $entry = $this->twitterRssEntryArray($notice);
                $this->showTwitterRssItem($entry);
647 648 649
            }
        }

650
        $this->endTwitterRss();
651 652
    }

653
    function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
654
    {
655

656
        $this->initDocument('atom');
657

658 659 660
        $this->element('title', null, $title);
        $this->element('id', null, $id);
        $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
661

662 663 664 665
        if (!is_null($logo)) {
            $this->element('logo',null,$logo);
        }

666 667
        if (!is_null($suplink)) {
            # For FriendFeed's SUP protocol
668
            $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
669 670 671
                                         'href' => $suplink,
                                         'type' => 'application/json'));
        }
672 673

        if (!is_null($selfuri)) {
674
            $this->element('link', array('href' => $selfuri,
675 676 677 678
                'rel' => 'self', 'type' => 'application/atom+xml'), null);
        }

        $this->element('updated', null, common_date_iso8601('now'));
679
        $this->element('subtitle', null, $subtitle);
680 681 682

        if (is_array($notice)) {
            foreach ($notice as $n) {
683
                $this->raw($n->asAtomEntry());
684 685 686
            }
        } else {
            while ($notice->fetch()) {
687
                $this->raw($notice->asAtomEntry());
688 689 690
            }
        }

691
        $this->endDocument('atom');
692 693 694

    }

695
    function showRssGroups($group, $title, $link, $subtitle)
696 697
    {

698
        $this->initDocument('rss');
699 700 701 702 703 704 705 706 707

        $this->element('title', null, $title);
        $this->element('link', null, $link);
        $this->element('description', null, $subtitle);
        $this->element('language', null, 'en-us');
        $this->element('ttl', null, '40');

        if (is_array($group)) {
            foreach ($group as $g) {
708 709
                $twitter_group = $this->twitterRssGroupArray($g);
                $this->showTwitterRssItem($twitter_group);
710 711 712
            }
        } else {
            while ($group->fetch()) {
713 714
                $twitter_group = $this->twitterRssGroupArray($group);
                $this->showTwitterRssItem($twitter_group);
715 716 717
            }
        }

718
        $this->endTwitterRss();
719 720
    }

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
    function showTwitterAtomEntry($entry)
    {
        $this->elementStart('entry');
        $this->element('title', null, $entry['title']);
        $this->element('content', array('type' => 'html'), $entry['content']);
        $this->element('id', null, $entry['id']);
        $this->element('published', null, $entry['published']);
        $this->element('updated', null, $entry['updated']);
        $this->element('link', array('type' => 'text/html',
                                     'href' => $entry['link'],
                                     'rel' => 'alternate'));
        $this->element('link', array('type' => $entry['avatar-type'],
                                     'href' => $entry['avatar'],
                                     'rel' => 'image'));
        $this->elementStart('author');

        $this->element('name', null, $entry['author-name']);
        $this->element('uri', null, $entry['author-uri']);

        $this->elementEnd('author');
        $this->elementEnd('entry');
    }

    function showXmlDirectMessage($dm)
    {
        $this->elementStart('direct_message');
        foreach($dm as $element => $value) {
            switch ($element) {
            case 'sender':
            case 'recipient':
751
                $this->showTwitterXmlUser($value, $element);
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
                break;
            case 'text':
                $this->element($element, null, common_xml_safe_str($value));
                break;
            default:
                $this->element($element, null, $value);
                break;
            }
        }
        $this->elementEnd('direct_message');
    }

    function directMessageArray($message)
    {
        $dmsg = array();

        $from_profile = $message->getFrom();
        $to_profile = $message->getTo();

        $dmsg['id'] = $message->id;
        $dmsg['sender_id'] = $message->from_profile;
        $dmsg['text'] = trim($message->content);
        $dmsg['recipient_id'] = $message->to_profile;
775
        $dmsg['created_at'] = $this->dateTwitter($message->created);
776 777
        $dmsg['sender_screen_name'] = $from_profile->nickname;
        $dmsg['recipient_screen_name'] = $to_profile->nickname;
778 779
        $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
        $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
780 781 782 783 784 785 786 787 788 789

        return $dmsg;
    }

    function rssDirectMessageArray($message)
    {
        $entry = array();

        $from = $message->getFrom();

790
        $entry['title'] = sprintf('Message from %1$s to %2$s',
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
            $from->nickname, $message->getTo()->nickname);

        $entry['content'] = common_xml_safe_str($message->rendered);
        $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
        $entry['published'] = common_date_iso8601($message->created);

        $taguribase = common_config('integration', 'taguri');

        $entry['id'] = "tag:$taguribase:$entry[link]";
        $entry['updated'] = $entry['published'];

        $entry['author-name'] = $from->getBestName();
        $entry['author-uri'] = $from->homepage;

        $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);

        $entry['avatar']      = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
        $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';

        // RSS item specific

        $entry['description'] = $entry['content'];
        $entry['pubDate'] = common_date_rfc2822($message->created);
        $entry['guid'] = $entry['link'];

        return $entry;
    }

    function showSingleXmlDirectMessage($message)
    {
821
        $this->initDocument('xml');
822 823
        $dmsg = $this->directMessageArray($message);
        $this->showXmlDirectMessage($dmsg);
824
        $this->endDocument('xml');
825 826 827 828
    }

    function showSingleJsonDirectMessage($message)
    {
829
        $this->initDocument('json');
830
        $dmsg = $this->directMessageArray($message);
831 832
        $this->showJsonObjects($dmsg);
        $this->endDocument('json');
833 834
    }

835
    function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
836 837
    {

838
        $this->initDocument('atom');
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861

        $this->element('title', null, $title);
        $this->element('id', null, $id);
        $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);

        if (!is_null($selfuri)) {
            $this->element('link', array('href' => $selfuri,
                'rel' => 'self', 'type' => 'application/atom+xml'), null);
        }

        $this->element('updated', null, common_date_iso8601('now'));
        $this->element('subtitle', null, $subtitle);

        if (is_array($group)) {
            foreach ($group as $g) {
                $this->raw($g->asAtomEntry());
            }
        } else {
            while ($group->fetch()) {
                $this->raw($group->asAtomEntry());
            }
        }

862
        $this->endDocument('atom');
863 864 865

    }

866
    function showJsonTimeline($notice)
867
    {
868

869
        $this->initDocument('json');
870 871 872 873 874

        $statuses = array();

        if (is_array($notice)) {
            foreach ($notice as $n) {
875
                $twitter_status = $this->twitterStatusArray($n);
876 877 878 879
                array_push($statuses, $twitter_status);
            }
        } else {
            while ($notice->fetch()) {
880
                $twitter_status = $this->twitterStatusArray($notice);
881 882 883 884
                array_push($statuses, $twitter_status);
            }
        }

885
        $this->showJsonObjects($statuses);
886

887
        $this->endDocument('json');
888 889
    }

890
    function showJsonGroups($group)
891 892
    {

893
        $this->initDocument('json');
894 895 896 897 898

        $groups = array();

        if (is_array($group)) {
            foreach ($group as $g) {
899
                $twitter_group = $this->twitterGroupArray($g);
900 901 902 903
                array_push($groups, $twitter_group);
            }
        } else {
            while ($group->fetch()) {
904
                $twitter_group = $this->twitterGroupArray($group);
905 906 907 908
                array_push($groups, $twitter_group);
            }
        }

909
        $this->showJsonObjects($groups);
910

911
        $this->endDocument('json');
912 913
    }

914
    function showXmlGroups($group)
915 916
    {

917
        $this->initDocument('xml');
918 919 920 921
        $this->elementStart('groups', array('type' => 'array'));

        if (is_array($group)) {
            foreach ($group as $g) {
922 923
                $twitter_group = $this->twitterGroupArray($g);
                $this->showTwitterXmlGroup($twitter_group);
924 925 926
            }
        } else {
            while ($group->fetch()) {
927 928
                $twitter_group = $this->twitterGroupArray($group);
                $this->showTwitterXmlGroup($twitter_group);
929 930 931 932
            }
        }

        $this->elementEnd('groups');
933
        $this->endDocument('xml');
934 935
    }

936
    function showTwitterXmlUsers($user)
937 938
    {

939
        $this->initDocument('xml');
940 941 942
        $this->elementStart('users', array('type' => 'array'));

        if (is_array($user)) {
943
            foreach ($user as $u) {
944 945
                $twitter_user = $this->twitterUserArray($u);
                $this->showTwitterXmlUser($twitter_user);
946 947 948
            }
        } else {
            while ($user->fetch()) {
949 950
                $twitter_user = $this->twitterUserArray($user);
                $this->showTwitterXmlUser($twitter_user);
951 952 953 954
            }
        }

        $this->elementEnd('users');
955
        $this->endDocument('xml');
956 957
    }

958
    function showJsonUsers($user)
959 960
    {

961
        $this->initDocument('json');
962 963 964 965 966

        $users = array();

        if (is_array($user)) {
            foreach ($user as $u) {
967
                $twitter_user = $this->twitterUserArray($u);
968 969 970 971
                array_push($users, $twitter_user);
            }
        } else {
            while ($user->fetch()) {
972
                $twitter_user = $this->twitterUserArray($user);
973 974 975 976
                array_push($users, $twitter_user);
            }
        }

977
        $this->showJsonObjects($users);
978

979
        $this->endDocument('json');
980 981
    }

982
    function showSingleJsonGroup($group)
983
    {
984 985 986 987
        $this->initDocument('json');
        $twitter_group = $this->twitterGroupArray($group);
        $this->showJsonObjects($twitter_group);
        $this->endDocument('json');
988 989
    }

990
    function showSingleXmlGroup($group)
991
    {
992 993 994 995
        $this->initDocument('xml');
        $twitter_group = $this->twitterGroupArray($group);
        $this->showTwitterXmlGroup($twitter_group);
        $this->endDocument('xml');
996 997
    }

998
    function dateTwitter($dt)
999
    {
Zach Copley's avatar
Zach Copley committed
1000 1001 1002 1003
        $dateStr = date('d F Y H:i:s', strtotime($dt));
        $d = new DateTime($dateStr, new DateTimeZone('UTC'));
        $d->setTimezone(new DateTimeZone(common_timezone()));
        return $d->format('D M d H:i:s O Y');
1004
    }
1005

1006
    function initDocument($type='xml')
1007
    {
1008
        switch ($type) {
1009
        case 'xml':
1010
            header('Content-Type: application/xml; charset=utf-8');
1011
            $this->startXML();
1012
            break;
1013
        case 'json':
1014 1015 1016 1017 1018 1019 1020 1021
            header('Content-Type: application/json; charset=utf-8');

            // Check for JSONP callback
            $callback = $this->arg('callback');
            if ($callback) {
                print $callback . '(';
            }
            break;
1022
        case 'rss':
1023
            header("Content-Type: application/rss+xml; charset=utf-8");
1024
            $this->initTwitterRss();
1025
            break;
1026
        case 'atom':
1027
            header('Content-Type: application/atom+xml; charset=utf-8');
1028
            $this->initTwitterAtom();
1029
            break;
1030
        default:
1031
            $this->clientError(_('Not a supported data format.'));
1032 1033 1034 1035 1036 1037
            break;
        }

        return;
    }

1038
    function endDocument($type='xml')
1039
    {
1040
        switch ($type) {
1041
        case 'xml':
1042
            $this->endXML();
1043
            break;
1044
        case 'json':
1045 1046 1047 1048 1049 1050 1051

            // Check for JSONP callback
            $callback = $this->arg('callback');
            if ($callback) {
                print ')';
            }
            break;
1052
        case 'rss':
1053
            $this->endTwitterRss();
1054
            break;
1055
        case 'atom':
1056
            $this->endTwitterRss();
1057
            break;
1058
        default:
1059
            $this->clientError(_('Not a supported data format.'));
1060 1061 1062 1063 1064
            break;
        }
        return;
    }

1065
    function clientError($msg, $code = 400, $format = 'xml')
1066
    {
1067 1068 1069 1070
        $action = $this->trimmed('action');

        common_debug("User error '$code' on '$action': $msg", __FILE__);

1071
        if (!array_key_exists($code, ClientErrorAction::$status)) {
1072 1073 1074
            $code = 400;
        }

1075 1076
        $status_string = ClientErrorAction::$status[$code];

1077 1078
        header('HTTP/1.1 '.$code.' '.$status_string);

1079
        if ($format == 'xml') {
1080
            $this->initDocument('xml');
1081 1082 1083 1084
            $this->elementStart('hash');
            $this->element('error', null, $msg);
            $this->element('request', null, $_SERVER['REQUEST_URI']);
            $this->elementEnd('hash');
1085
            $this->endDocument('xml');
1086
        } elseif ($format == 'json'){
1087
            $this->initDocument('json');
1088 1089
            $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
            print(json_encode($error_array));
1090
            $this->endDocument('json');
1091
        } else {
1092

1093 1094 1095
            // If user didn't request a useful format, throw a regular client error
            throw new ClientException($msg, $code);
        }
1096 1097
    }

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
    function serverError($msg, $code = 500, $content_type = 'json')
    {
        $action = $this->trimmed('action');

        common_debug("Server error '$code' on '$action': $msg", __FILE__);

        if (!array_key_exists($code, ServerErrorAction::$status