apiaction.php 50 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
 * @author    Zach Copley <zach@status.net>
30
 * @copyright 2009-2010 StatusNet, Inc.
31
 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
32 33
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
34 35
 */

36 37 38 39 40 41 42 43 44 45 46 47
/* External API usage documentation. Please update when you change how the API works. */

/*! @mainpage StatusNet REST API

    @section Introduction

    Some explanatory text about the API would be nice.

    @section API Methods

    @subsection timelinesmethods_sec Timeline Methods

48
    @li @ref publictimeline
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    @li @ref friendstimeline

    @subsection statusmethods_sec Status Methods

    @li @ref statusesupdate

    @subsection usermethods_sec User Methods

    @subsection directmessagemethods_sec Direct Message Methods

    @subsection friendshipmethods_sec Friendship Methods

    @subsection socialgraphmethods_sec Social Graph Methods

    @subsection accountmethods_sec Account Methods

    @subsection favoritesmethods_sec Favorites Methods

    @subsection blockmethods_sec Block Methods

    @subsection oauthmethods_sec OAuth Methods

    @subsection helpmethods_sec Help Methods

    @subsection groupmethods_sec Group Methods

    @page apiroot API Root

    The URLs for methods referred to in this API documentation are
    relative to the StatusNet API root. The API root is determined by the
    site's @b server and @b path variables, which are generally specified
    in config.php. For example:

    @code
    $config['site']['server'] = 'example.org';
    $config['site']['path'] = 'statusnet'
    @endcode

    The pattern for a site's API root is: @c protocol://server/path/api E.g:

    @c http://example.org/statusnet/api

    The @b path can be empty.  In that case the API root would simply be:

    @c http://example.org/api

*/

97
if (!defined('STATUSNET')) {
98 99
    exit(1);
}
100

101 102 103 104 105
/**
 * Contains most of the Twitter-compatible API output functions.
 *
 * @category API
 * @package  StatusNet
Zach Copley's avatar
Zach Copley committed
106 107 108 109 110
 * @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>
111 112 113 114 115
 * @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
116
{
117 118 119
    const READ_ONLY  = 1;
    const READ_WRITE = 2;

120 121 122 123 124 125 126
    var $format    = null;
    var $user      = null;
    var $auth_user = null;
    var $page      = null;
    var $count     = null;
    var $max_id    = null;
    var $since_id  = null;
127
    var $source    = null;
128
    var $callback  = null;
129

130 131
    var $access    = self::READ_ONLY;  // read (default) or read-write

132 133
    static $reserved_sources = array('web', 'omb', 'ostatus', 'mail', 'xmpp', 'api');

134 135 136 137 138
    /**
     * Initialization.
     *
     * @param array $args Web and URL arguments
     *
139
     * @return boolean false if user doesn't exist
140 141 142
     */
    function prepare($args)
    {
143
        StatusNet::setApi(true); // reduce exception reports to aid in debugging
144
        parent::prepare($args);
145

146
        $this->format   = $this->arg('format');
147
        $this->callback = $this->arg('callback');
148 149 150 151
        $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);
152 153

        if ($this->arg('since')) {
154
            header('X-StatusNet-Warning: since parameter is disabled; use since_id');
155
        }
156

157 158 159 160 161 162
        $this->source = $this->trimmed('source');

        if (empty($this->source) || in_array($this->source, self::$reserved_sources)) {
            $this->source = 'api';
        }

163 164 165 166 167 168 169 170 171 172
        return true;
    }

    /**
     * Handle a request
     *
     * @param array $args Arguments from $_REQUEST
     *
     * @return void
     */
173 174
    function handle($args)
    {
175
        header('Access-Control-Allow-Origin: *');
176 177
        parent::handle($args);
    }
178

179 180 181
    /**
     * Overrides XMLOutputter::element to write booleans as strings (true|false).
     * See that method's documentation for more info.
182
     *
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
     * @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);
    }
198

199
    function twitterUserArray($profile, $get_notice=false)
200
    {
201
        $twitter_user = array();
202

203
        $twitter_user['id'] = intval($profile->id);
204 205
        $twitter_user['name'] = $profile->getBestName();
        $twitter_user['screen_name'] = $profile->nickname;
Evan Prodromou's avatar
Evan Prodromou committed
206
        $twitter_user['location'] = ($profile->location) ? $profile->location : null;
207
        $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
208

209
        $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
210 211
        $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
            Avatar::defaultImage(AVATAR_STREAM_SIZE);
212

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

217
        $design        = null;
218
        $user          = $profile->getUser();
219

220
        // Note: some profiles don't have an associated user
221

222 223
        $defaultDesign = Design::siteDesign();

224 225 226 227
        if (!empty($user)) {
            $design = $user->getDesign();
        }

228
        if (empty($design)) {
229
            $design = $defaultDesign;
230 231
        }

232 233 234 235 236 237 238 239
        $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();
240 241
        $twitter_user['profile_sidebar_border_color'] = '';

242
        $twitter_user['friends_count'] = $profile->subscriptionCount();
243

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

246
        $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
247 248 249

        $timezone = 'UTC';

250
        if (!empty($user) && $user->timezone) {
251 252 253 254 255 256 257 258 259
            $timezone = $user->timezone;
        }

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

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

260 261 262 263 264 265 266 267
        $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';
268

269
        $twitter_user['statuses_count'] = $profile->noticeCount();
270 271 272

        // Is the requesting user following this user?
        $twitter_user['following'] = false;
273
        $twitter_user['statusnet:blocking'] = false;
274 275
        $twitter_user['notifications'] = false;

276
        if (isset($this->auth_user)) {
277

278
            $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
279
            $twitter_user['statusnet:blocking']  = $this->auth_user->hasBlocked($profile);
280 281 282

            // Notifications on?
            $sub = Subscription::pkeyGet(array('subscriber' =>
283 284
                                               $this->auth_user->id,
                                               'subscribed' => $profile->id));
285 286 287 288 289

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

291 292 293
        if ($get_notice) {
            $notice = $profile->getCurrentNotice();
            if ($notice) {
294
                # don't get user!
295
                $twitter_user['status'] = $this->twitterStatusArray($notice, false);
296 297
            }
        }
298

299 300
        // StatusNet-specific

301
        $twitter_user['statusnet_profile_url'] = $profile->profileurl;
302

303 304
        return $twitter_user;
    }
305

306
    function twitterStatusArray($notice, $include_user=true)
307 308 309
    {
        $base = $this->twitterSimpleStatusArray($notice, $include_user);

310
        if (!empty($notice->repeat_of)) {
311
            $original = Notice::staticGet('id', $notice->repeat_of);
312
            if (!empty($original)) {
313
                $original_array = $this->twitterSimpleStatusArray($original, $include_user);
314
                $base['retweeted_status'] = $original_array;
315
            }
316
        }
317 318

        return $base;
319 320 321
    }

    function twitterSimpleStatusArray($notice, $include_user=true)
322
    {
323
        $profile = $notice->getProfile();
324

325 326
        $twitter_status = array();
        $twitter_status['text'] = $notice->content;
327
        $twitter_status['truncated'] = false; # Not possible on StatusNet
328
        $twitter_status['created_at'] = $this->dateTwitter($notice->created);
329 330
        $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
            intval($notice->reply_to) : null;
331 332 333 334 335 336

        $source = null;

        $ns = $notice->getSource();
        if ($ns) {
            if (!empty($ns->name) && !empty($ns->url)) {
337 338 339 340 341
                $source = '<a href="'
		    . htmlspecialchars($ns->url)
		    . '" rel="nofollow">'
		    . htmlspecialchars($ns->name)
		    . '</a>';
342 343 344 345 346
            } else {
                $source = $ns->code;
            }
        }

347
        $twitter_status['source'] = $source;
348
        $twitter_status['id'] = intval($notice->id);
349 350 351 352 353 354 355 356 357 358 359 360 361 362

        $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;
363

364 365 366 367 368 369 370 371 372
        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;
        }

373
        if (isset($this->auth_user)) {
374
            $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
375
        } else {
376
            $twitter_status['favorited'] = false;
377
        }
Evan Prodromou's avatar
Evan Prodromou committed
378

379
        // Enclosures
380 381
        $attachments = $notice->attachments();

382 383 384 385 386
        if (!empty($attachments)) {

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

            foreach ($attachments as $attachment) {
387
                $enclosure_o=$attachment->getEnclosure();
388
                if ($enclosure_o) {
389
                    $enclosure = array();
390 391 392
                    $enclosure['url'] = $enclosure_o->url;
                    $enclosure['mimetype'] = $enclosure_o->mimetype;
                    $enclosure['size'] = $enclosure_o->size;
393
                    $twitter_status['attachments'][] = $enclosure;
394 395
                }
            }
396 397
        }

398
        if ($include_user && $profile) {
399
            # Don't get notice (recursive!)
400
            $twitter_user = $this->twitterUserArray($profile, false);
401 402
            $twitter_status['user'] = $twitter_user;
        }
403

404 405
        // StatusNet-specific

406
        $twitter_status['statusnet_html'] = $notice->rendered;
407

408 409
        return $twitter_status;
    }
410

411
    function twitterGroupArray($group)
412
    {
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
        $twitter_group = array();

        $twitter_group['id'] = $group->id;
        $twitter_group['url'] = $group->permalink();
        $twitter_group['nickname'] = $group->nickname;
        $twitter_group['fullname'] = $group->fullname;

        if (isset($this->auth_user)) {
            $twitter_group['member'] = $this->auth_user->isMember($group);
            $twitter_group['blocked'] = Group_block::isBlocked(
                $group,
                $this->auth_user->getProfile()
            );
        }

        $twitter_group['member_count'] = $group->getMemberCount();
        $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;
        $twitter_group['created'] = $this->dateTwitter($group->created);
        $twitter_group['modified'] = $this->dateTwitter($group->modified);

439 440 441
        return $twitter_group;
    }

442
    function twitterRssGroupArray($group)
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
    {
        $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;
    }

460
    function twitterRssEntryArray($notice)
461
    {
462
        $entry = array();
463

464 465
        if (Event::handle('StartRssEntryArray', array($notice, &$entry))) {
            $profile = $notice->getProfile();
466

467
            // We trim() to avoid extraneous whitespace in the output
468

469 470 471 472
            $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);
473

474 475
            $taguribase = TagURI::base();
            $entry['id'] = "tag:$taguribase:$entry[link]";
476

477 478
            $entry['updated'] = $entry['published'];
            $entry['author'] = $profile->getBestName();
479

480 481 482 483 484 485 486 487 488 489 490 491 492
            // Enclosures
            $attachments = $notice->attachments();
            $enclosures = array();

            foreach ($attachments as $attachment) {
                $enclosure_o=$attachment->getEnclosure();
                if ($enclosure_o) {
                    $enclosure = array();
                    $enclosure['url'] = $enclosure_o->url;
                    $enclosure['mimetype'] = $enclosure_o->mimetype;
                    $enclosure['size'] = $enclosure_o->size;
                    $enclosures[] = $enclosure;
                }
493 494
            }

495 496 497
            if (!empty($enclosures)) {
                $entry['enclosures'] = $enclosures;
            }
498

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
            // 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();

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

            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;
            }

            Event::handle('EndRssEntryArray', array($notice, &$entry));
526 527
        }

528 529 530
        return $entry;
    }

531
    function twitterRelationshipArray($source, $target)
532 533 534 535
    {
        $relationship = array();

        $relationship['source'] =
536
            $this->relationshipDetailsArray($source, $target);
537
        $relationship['target'] =
538
            $this->relationshipDetailsArray($target, $source);
539 540 541 542

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

543
    function relationshipDetailsArray($source, $target)
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
    {
        $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;
    }

569
    function showTwitterXmlRelationship($relationship)
570 571 572 573 574 575
    {
        $this->elementStart('relationship');

        foreach($relationship as $element => $value) {
            if ($element == 'source' || $element == 'target') {
                $this->elementStart($element);
576
                $this->showXmlRelationshipDetails($value);
577 578 579 580 581 582 583
                $this->elementEnd($element);
            }
        }

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

584
    function showXmlRelationshipDetails($details)
585 586 587 588 589 590
    {
        foreach($details as $element => $value) {
            $this->element($element, null, $value);
        }
    }

591
    function showTwitterXmlStatus($twitter_status, $tag='status', $namespaces=false)
592
    {
593 594 595 596 597
        $attrs = array();
        if ($namespaces) {
            $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
        }
        $this->elementStart($tag, $attrs);
598 599 600
        foreach($twitter_status as $element => $value) {
            switch ($element) {
            case 'user':
601
                $this->showTwitterXmlUser($twitter_status['user']);
602 603
                break;
            case 'text':
604
                $this->element($element, null, common_xml_safe_str($value));
605
                break;
606
            case 'attachments':
607
                $this->showXmlAttachments($twitter_status['attachments']);
608
                break;
609
            case 'geo':
610
                $this->showGeoXML($value);
611
                break;
612 613 614
            case 'retweeted_status':
                $this->showTwitterXmlStatus($value, 'retweeted_status');
                break;
615
            default:
616 617 618 619 620
                if (strncmp($element, 'statusnet_', 10) == 0) {
                    $this->element('statusnet:'.substr($element, 10), null, $value);
                } else {
                    $this->element($element, null, $value);
                }
621 622
            }
        }
623
        $this->elementEnd($tag);
624 625
    }

626
    function showTwitterXmlGroup($twitter_group)
627 628 629 630 631 632 633 634
    {
        $this->elementStart('group');
        foreach($twitter_group as $element => $value) {
            $this->element($element, null, $value);
        }
        $this->elementEnd('group');
    }

635
    function showTwitterXmlUser($twitter_user, $role='user', $namespaces=false)
636
    {
637 638 639 640 641
        $attrs = array();
        if ($namespaces) {
            $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
        }
        $this->elementStart($role, $attrs);
642 643
        foreach($twitter_user as $element => $value) {
            if ($element == 'status') {
644
                $this->showTwitterXmlStatus($twitter_user['status']);
645 646
            } else if (strncmp($element, 'statusnet_', 10) == 0) {
                $this->element('statusnet:'.substr($element, 10), null, $value);
647
            } else {
648
                $this->element($element, null, $value);
649 650
            }
        }
651
        $this->elementEnd($role);
652 653
    }

654
    function showXmlAttachments($attachments) {
655 656 657 658 659 660 661 662 663 664 665 666 667
        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');
        }
    }

668 669 670 671 672 673 674 675 676 677 678 679
    function showGeoXML($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');
        }
    }

680 681
    function showGeoRSS($geo)
    {
682 683 684 685 686 687
        if (!empty($geo)) {
            $this->element(
                'georss:point',
                null,
                $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
            );
688 689 690
        }
    }

691
    function showTwitterRssItem($entry)
692
    {
693 694 695 696 697 698
        $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']);
699 700

        # RSS only supports 1 enclosure per item
701
        if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
702 703 704
            $enclosure = $entry['enclosures'][0];
            $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
        }
705

706
        if(array_key_exists('tags', $entry)){
707 708 709 710
            foreach($entry['tags'] as $tag){
                $this->element('category', null,$tag);
            }
        }
711

712
        $this->showGeoRSS($entry['geo']);
713
        $this->elementEnd('item');
714 715
    }

716
    function showJsonObjects($objects)
717
    {
718 719 720
        print(json_encode($objects));
    }

721
    function showSingleXmlStatus($notice)
722
    {
723 724
        $this->initDocument('xml');
        $twitter_status = $this->twitterStatusArray($notice);
725
        $this->showTwitterXmlStatus($twitter_status, 'status', true);
726
        $this->endDocument('xml');
727 728
    }

729 730
    function show_single_json_status($notice)
    {
731 732 733 734
        $this->initDocument('json');
        $status = $this->twitterStatusArray($notice);
        $this->showJsonObjects($status);
        $this->endDocument('json');
735 736
    }

737
    function showXmlTimeline($notice)
738
    {
739
        $this->initDocument('xml');
740 741
        $this->elementStart('statuses', array('type' => 'array',
                                              'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
742 743

        if (is_array($notice)) {
744 745 746 747 748
            $notice = new ArrayWrapper($notice);
        }

        while ($notice->fetch()) {
            try {
749 750
                $twitter_status = $this->twitterStatusArray($notice);
                $this->showTwitterXmlStatus($twitter_status);
751 752 753
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                continue;
754 755 756
            }
        }

757
        $this->elementEnd('statuses');
758
        $this->endDocument('xml');
759 760
    }

761
    function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
762
    {
763
        $this->initDocument('rss');
764

765 766
        $this->element('title', null, $title);
        $this->element('link', null, $link);
767 768 769 770 771 772 773 774 775 776 777 778

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

779
        if (!is_null($suplink)) {
780
            // For FriendFeed's SUP protocol
781
            $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
782 783 784 785
                                         'rel' => 'http://api.friendfeed.com/2008/03#sup',
                                         'href' => $suplink,
                                         'type' => 'application/json'));
        }
786 787 788 789 790 791 792 793 794

        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');
        }

795 796 797
        $this->element('description', null, $subtitle);
        $this->element('language', null, 'en-us');
        $this->element('ttl', null, '40');
798 799

        if (is_array($notice)) {
800 801 802 803 804 805 806 807 808 809
            $notice = new ArrayWrapper($notice);
        }

        while ($notice->fetch()) {
            try {
                $entry = $this->twitterRssEntryArray($notice);
                $this->showTwitterRssItem($entry);
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                // continue on exceptions
810 811 812
            }
        }

813
        $this->endTwitterRss();
814 815
    }

816
    function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
817
    {
818
        $this->initDocument('atom');
819

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

824 825 826 827
        if (!is_null($logo)) {
            $this->element('logo',null,$logo);
        }

828 829
        if (!is_null($suplink)) {
            # For FriendFeed's SUP protocol
830
            $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
831 832 833
                                         'href' => $suplink,
                                         'type' => 'application/json'));
        }
834 835

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

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

        if (is_array($notice)) {
844 845 846 847 848
            $notice = new ArrayWrapper($notice);
        }

        while ($notice->fetch()) {
            try {
849
                $this->raw($notice->asAtomEntry());
850 851 852
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                continue;
853 854 855
            }
        }

856
        $this->endDocument('atom');
857 858
    }

859
    function showRssGroups($group, $title, $link, $subtitle)
860
    {
861
        $this->initDocument('rss');
862 863 864 865 866 867 868 869 870

        $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) {
871 872
                $twitter_group = $this->twitterRssGroupArray($g);
                $this->showTwitterRssItem($twitter_group);
873 874 875
            }
        } else {
            while ($group->fetch()) {
876 877
                $twitter_group = $this->twitterRssGroupArray($group);
                $this->showTwitterRssItem($twitter_group);
878 879 880
            }
        }

881
        $this->endTwitterRss();
882 883
    }

884 885 886
    function showTwitterAtomEntry($entry)
    {
        $this->elementStart('entry');
887 888 889 890 891 892
        $this->element('title', null, common_xml_safe_str($entry['title']));
        $this->element(
            'content',
            array('type' => 'html'),
            common_xml_safe_str($entry['content'])
        );
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
        $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');
    }

911
    function showXmlDirectMessage($dm, $namespaces=false)
912
    {
913 914 915 916 917
        $attrs = array();
        if ($namespaces) {
            $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
        }
        $this->elementStart('direct_message', $attrs);
918 919 920 921
        foreach($dm as $element => $value) {
            switch ($element) {
            case 'sender':
            case 'recipient':
922
                $this->showTwitterXmlUser($value, $element);
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
                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;
946
        $dmsg['created_at'] = $this->dateTwitter($message->created);
947 948
        $dmsg['sender_screen_name'] = $from_profile->nickname;
        $dmsg['recipient_screen_name'] = $to_profile->nickname;
949 950
        $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
        $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
951 952 953 954 955 956 957 958 959 960

        return $dmsg;
    }

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

        $from = $message->getFrom();

961
        $entry['title'] = sprintf('Message from %1$s to %2$s',
962 963 964 965 966 967
            $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);

968
        $taguribase = TagURI::base();
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991

        $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)
    {
992
        $this->initDocument('xml');
993
        $dmsg = $this->directMessageArray($message);
994
        $this->showXmlDirectMessage($dmsg, true);
995
        $this->endDocument('xml');
996 997 998 999
    }

    function showSingleJsonDirectMessage($message)
    {
1000
        $this->initDocument('json');
1001
        $dmsg = $this->directMessageArray($message);
1002 1003
        $this->showJsonObjects($dmsg);
        $this->endDocument('json');
1004 1005
    }

1006
    function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
1007
    {
1008
        $this->initDocument('atom');
1009

1010
        $this->element('title', null, common_xml_safe_str($title));
1011 1012 1013 1014 1015 1016 1017 1018 1019
        $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'));
1020
        $this->element('subtitle', null, common_xml_safe_str($subtitle));
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031

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

1032
        $this->endDocument('atom');
1033 1034 1035

    }

1036
    function showJsonTimeline($notice)
1037
    {
1038
        $this->initDocument('json');
1039 1040 1041 1042

        $statuses = array();

        if (is_array($notice)) {
1043 1044 1045 1046 1047
            $notice = new ArrayWrapper($notice);
        }

        while ($notice->fetch()) {
            try {
1048
                $twitter_status = $this->twitterStatusArray($notice);
1049
                array_push($statuses, $twitter_status);
1050 1051 1052
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                continue;
1053 1054 1055
            }
        }

1056
        $this->showJsonObjects($statuses);
1057

1058
        $this->endDocument('json');
1059 1060
    }

1061
    function showJsonGroups($group)
1062
    {
1063
        $this->initDocument('json');
1064 1065 1066 1067 1068

        $groups = array();

        if (is_array($group)) {
            foreach ($group as $g) {
1069
                $twitter_group = $this->twitterGroupArray($g);
1070 1071 1072 1073
                array_push($groups, $twitter_group);
            }
        } else {
            while ($group->fetch()) {
1074
                $twitter_group = $this->twitterGroupArray($group);
1075 1076 1077 1078
                array_push($groups, $twitter_group);
            }
        }

1079
        $this->showJsonObjects($groups);
1080

1081
        $this->endDocument('json');
1082 1083
    }

1084
    function showXmlGroups($group)
1085 1086
    {

1087
        $this->initDocument('xml');
1088 1089 1090 1091
        $this->elementStart('groups', array('type' => 'array'));

        if (is_array($group)) {
            foreach ($group as $g) {
1092 1093
                $twitter_group = $this->twitterGroupArray($g);
                $this->showTwitterXmlGroup($twitter_group);
1094 1095 1096
            }
        } else {
            while ($group->fetch()) {
1097 1098
                $twitter_group = $this->twitterGroupArray($group);
                $this->showTwitterXmlGroup($twitter_group);
1099 1100 1101 1102
            }
        }

        $this->elementEnd('groups');
1103
        $this->endDocument('xml');
1104 1105
    }

1106
    function showTwitterXmlUsers($user)
1107
    {
1108
        $this->initDocument('xml');
1109 1110
        $this->elementStart('users', array('type' => 'array',
                                           'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
1111 1112

        if (is_array($user)) {
1113
            foreach ($user as $u) {
1114 1115
                $twitter_user = $this->twitterUserArray($u);
                $this->showTwitterXmlUser($twitter_user);
1116 1117 1118
            }
        } else {
            while ($user->fetch()) {
1119 1120
                $twitter_user = $this->twitterUserArray($user);
                $this->showTwitterXmlUser($twitter_user);
1121 1122 1123 1124
            }
        }

        $this->elementEnd('users');
1125
        $this->endDocument('xml');
1126 1127
    }

1128
    function showJsonUsers($user)
1129
    {
1130
        $this->initDocument('json');
1131 1132 1133 1134 1135

        $users = array();

        if (is_array($user)) {
            foreach ($user as $u) {
1136
                $twitter_user = $this->twitterUserArray($u);
1137 1138 1139 1140
                array_push($users, $twitter_user);
            }
        } else {
            while ($user->fetch()) {
1141
                $twitter_user = $this->twitterUserArray($user);
1142 1143 1144 1145
                array_push($users, $twitter_user);
            }
        }

1146
        $this->showJsonObjects($users);
1147

1148
        $this->endDocument('json');
1149 1150
    }

1151
    function showSingleJsonGroup($group)
1152
    {
1153 1154 1155 1156
        $this->initDocument('json');
        $twitter_group = $this->twitterGroupArray($group);
        $this->showJsonObjects($twitter_group);
        $this->endDocument('json');
1157 1158
    }

1159
    function showSingleXmlGroup($group)
1160
    {
1161 1162 1163 1164
        $this->initDocument('xml');
        $twitter_group = $this->twitterGroupArray($group);
        $this->showTwitterXmlGroup($twitter_group);
        $this->endDocument('xml');
1165 1166
    }

1167
    function dateTwitter($dt)
1168
    {
Zach Copley's avatar
Zach Copley committed
1169 1170 1171 1172
        $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');
1173
    }
1174

1175
    function initDocument($type='xml')
1176
    {
1177
        switch ($type) {
1178
        case 'xml':
1179
            header('Content-Type: application/xml; charset=utf-8');
1180
            $this->startXML();
1181
            break;
1182
        case 'json':
1183 1184 1185
            header('Content-Type: application/json; charset=utf-8');

            // Check for JSONP callback
1186 1187
            if (isset($this->callback)) {
                print $this->callback . '(';
1188 1189
            }
            break;
1190
        case 'rss':
1191
            header("Content-Type: application/rss+xml; charset=utf-8");
1192
            $this->initTwitterRss();
1193
            break;
1194
        case 'atom':
1195
            header('Content-Type: application/atom+xml; charset=utf-8');
1196
            $this->initTwitterAtom();
1197
            break;
1198
        default:
1199
            // TRANS: Client error on an API request with an unsupported data format.
1200
            $this->clientError(_('Not a supported data format.'));
1201 1202 1203 1204 1205 1206
            break;
        }

        return;
    }

1207
    function endDocument($type='xml')
1208
    {
1209
        switch ($type) {
1210
        case 'xml':
1211
            $this->endXML();
1212
            break;
1213
        case 'json':
1214
            // Check for JSONP callback
1215
            if (isset($this->callback)) {
1216 1217 1218
                print ')';
            }
            break;
1219
        case 'rss':
1220
            $this->endTwitterRss();
1221
            break;
1222
        case 'atom':
1223
            $this->endTwitterRss();
1224
            break;
1225
        default:
1226
            // TRANS: Client error on an API request with an unsupported data format.
1227
            $this->clientError(_('Not a supported data format.'));
1228 1229 1230 1231 1232
            break;
        }
        return;
    }

1233
    function clientError($msg, $code = 400, $format = 'xml')
1234
    {
1235 1236 1237 1238
        $action = $this->trimmed('action');

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

1239
        if (!array_key_exists($code, ClientErrorAction::$status)) {
1240 1241 1242
            $code = 400;
        }

1243 1244
        $status_string = ClientErrorAction::$status[$code];

1245 1246 1247 1248
        // Do not emit error header for JSONP
        if (!isset($this->callback)) {
            header('HTTP/1.1 '.$code.' '.$status_string);
        }
1249

1250
        if ($format == 'xml') {
1251
            $this->initDocument('xml');
1252 1253 1254 1255
            $this->elementStart('hash');
            $this->element('error', null, $msg);
            $this->element('request', null, $_SERVER['REQUEST_URI']);
            $this->elementEnd('hash');
1256
            $this->endDocument('xml');
1257
        } elseif ($format == 'json'){
1258
            $this->initDocument('json');
1259 1260
            $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
            print(json_encode($error_array));
1261
            $this->endDocument('json');
1262
        } else {
1263

1264 1265 1266
            // If user didn't request a useful format, throw a regular client error
            throw new ClientException($msg, $code);
        }
1267 1268
    }

1269
    function serverError($msg, $code = 500, $content_type = 'xml')
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
    {
        $action = $this->trimmed('action');

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

        if (!array_key_exists($code, ServerErrorAction::$status)) {
            $code = 400;
        }

        $status_string = ServerErrorAction::$status[$code];

1281 1282 1283 1284
        // Do not emit error header for JSONP
        if (!isset($this->callback)) {
            header('HTTP/1.1 '.$code.' '.$status_string);
        }
1285 1286

        if ($content_type == 'xml') {
1287
            $this->initDocument('xml');
1288 1289 1290 1291
            $this->elementStart('hash');
            $this->element('error', null, $msg);
            $this->element('request', null, $_SERVER['REQUEST_URI']);
            $this->elementEnd('hash');