apiaction.php 53.3 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
class ApiValidationException extends Exception { }

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

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

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

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

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

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

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

159 160 161 162 163 164
        $this->source = $this->trimmed('source');

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

165 166 167 168 169 170 171 172 173 174
        return true;
    }

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

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

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

205 206
        $user = $profile->getUser();

207
        $twitter_user['id'] = intval($profile->id);
208 209
        $twitter_user['name'] = $profile->getBestName();
        $twitter_user['screen_name'] = $profile->nickname;
Evan Prodromou's avatar
Evan Prodromou committed
210
        $twitter_user['location'] = ($profile->location) ? $profile->location : null;
211
        $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
212

213
        $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
214 215
        $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
            Avatar::defaultImage(AVATAR_STREAM_SIZE);
216

Evan Prodromou's avatar
Evan Prodromou committed
217
        $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
218
        $twitter_user['protected'] = (!empty($user) && $user->private_stream) ? true : false;
219
        $twitter_user['followers_count'] = $profile->subscriberCount();
220

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

223
        $twitter_user['friends_count'] = $profile->subscriptionCount();
224

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

227
        $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
228 229 230

        $timezone = 'UTC';

231
        if (!empty($user) && $user->timezone) {
232 233 234 235 236 237 238 239
            $timezone = $user->timezone;
        }

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

        $twitter_user['utc_offset'] = $t->format('Z');
        $twitter_user['time_zone'] = $timezone;
240
        $twitter_user['statuses_count'] = $profile->noticeCount();
241 242 243

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

247
        if (isset($this->auth_user)) {
248

249
            $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
250
            $twitter_user['statusnet_blocking']  = $this->auth_user->hasBlocked($profile);
251 252 253

            // Notifications on?
            $sub = Subscription::pkeyGet(array('subscriber' =>
254 255
                                               $this->auth_user->id,
                                               'subscribed' => $profile->id));
256 257 258 259 260

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

262 263 264
        if ($get_notice) {
            $notice = $profile->getCurrentNotice();
            if ($notice) {
265
                // don't get user!
266
                $twitter_user['status'] = $this->twitterStatusArray($notice, false);
267 268
            }
        }
269

270 271
        // StatusNet-specific

272
        $twitter_user['statusnet_profile_url'] = $profile->profileurl;
273

274 275
        return $twitter_user;
    }
276

277
    function twitterStatusArray($notice, $include_user=true)
278 279 280
    {
        $base = $this->twitterSimpleStatusArray($notice, $include_user);

281
        if (!empty($notice->repeat_of)) {
282
            $original = Notice::staticGet('id', $notice->repeat_of);
283
            if (!empty($original)) {
284
                $original_array = $this->twitterSimpleStatusArray($original, $include_user);
285
                $base['retweeted_status'] = $original_array;
286
            }
287
        }
288 289

        return $base;
290 291 292
    }

    function twitterSimpleStatusArray($notice, $include_user=true)
293
    {
294
        $profile = $notice->getProfile();
295

296 297
        $twitter_status = array();
        $twitter_status['text'] = $notice->content;
298
        $twitter_status['truncated'] = false; # Not possible on StatusNet
299
        $twitter_status['created_at'] = $this->dateTwitter($notice->created);
300 301
        $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
            intval($notice->reply_to) : null;
302 303 304 305 306 307

        $source = null;

        $ns = $notice->getSource();
        if ($ns) {
            if (!empty($ns->name) && !empty($ns->url)) {
308 309 310 311 312
                $source = '<a href="'
		    . htmlspecialchars($ns->url)
		    . '" rel="nofollow">'
		    . htmlspecialchars($ns->name)
		    . '</a>';
313 314 315 316 317
            } else {
                $source = $ns->code;
            }
        }

318
        $twitter_status['source'] = $source;
319
        $twitter_status['id'] = intval($notice->id);
320 321 322 323 324 325 326 327 328 329 330 331 332 333

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

335 336 337 338 339 340 341 342 343
        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;
        }

344
        if (isset($this->auth_user)) {
345
            $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
346
        } else {
347
            $twitter_status['favorited'] = false;
348
        }
Evan Prodromou's avatar
Evan Prodromou committed
349

350
        // Enclosures
351 352
        $attachments = $notice->attachments();

353 354 355 356 357
        if (!empty($attachments)) {

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

            foreach ($attachments as $attachment) {
358
                $enclosure_o=$attachment->getEnclosure();
359
                if ($enclosure_o) {
360
                    $enclosure = array();
361 362 363
                    $enclosure['url'] = $enclosure_o->url;
                    $enclosure['mimetype'] = $enclosure_o->mimetype;
                    $enclosure['size'] = $enclosure_o->size;
364
                    $twitter_status['attachments'][] = $enclosure;
365 366
                }
            }
367 368
        }

369
        if ($include_user && $profile) {
370
            // Don't get notice (recursive!)
371
            $twitter_user = $this->twitterUserArray($profile, false);
372 373
            $twitter_status['user'] = $twitter_user;
        }
374

375 376
        // StatusNet-specific

377
        $twitter_status['statusnet_html'] = $notice->rendered;
378
        $twitter_status['statusnet_conversation_id'] = intval($notice->conversation);
379

380 381
        return $twitter_status;
    }
382

383
    function twitterGroupArray($group)
384
    {
385 386
        $twitter_group = array();

387
        $twitter_group['id'] = intval($group->id);
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
        $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);

411 412 413
        return $twitter_group;
    }

414
    function twitterRssGroupArray($group)
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
    {
        $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;
    }

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    function twitterListArray($list)
    {
        $profile = Profile::staticGet('id', $list->tagger);

        $twitter_list = array();
        $twitter_list['id'] = $list->id;
        $twitter_list['name'] = $list->tag;
        $twitter_list['full_name'] = '@'.$profile->nickname.'/'.$list->tag;;
        $twitter_list['slug'] = $list->tag;
        $twitter_list['description'] = $list->description;
        $twitter_list['subscriber_count'] = $list->subscriberCount();
        $twitter_list['member_count'] = $list->taggedCount();
        $twitter_list['uri'] = $list->getUri();

        if (isset($this->auth_user)) {
            $twitter_list['following'] = $list->hasSubscriber($this->auth_user);
        } else {
            $twitter_list['following'] = false;
        }

        $twitter_list['mode'] = ($list->private) ? 'private' : 'public';
        $twitter_list['user'] = $this->twitterUserArray($profile, false);

        return $twitter_list;
    }

458
    function twitterRssEntryArray($notice)
459
    {
460
        $entry = array();
461

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

465
            // We trim() to avoid extraneous whitespace in the output
466

467 468 469 470
            $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);
471

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

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

478 479 480 481 482 483 484 485 486 487 488 489 490
            // 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;
                }
491 492
            }

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

497 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
            // 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));
524 525
        }

526 527 528
        return $entry;
    }

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

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

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

541
    function relationshipDetailsArray($source, $target)
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
    {
        $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);
562
        $details['id'] = intval($source->id);
563 564 565 566

        return $details;
    }

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

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

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

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

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

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

633 634 635 636 637 638 639 640 641 642 643 644 645 646
    function showTwitterXmlList($twitter_list)
    {
        $this->elementStart('list');
        foreach($twitter_list as $element => $value) {
            if($element == 'user') {
                $this->showTwitterXmlUser($value, 'user');
            }
            else {
                $this->element($element, null, $value);
            }
        }
        $this->elementEnd('list');
    }

647
    function showTwitterXmlUser($twitter_user, $role='user', $namespaces=false)
648
    {
649 650 651 652 653
        $attrs = array();
        if ($namespaces) {
            $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
        }
        $this->elementStart($role, $attrs);
654 655
        foreach($twitter_user as $element => $value) {
            if ($element == 'status') {
656
                $this->showTwitterXmlStatus($twitter_user['status']);
657 658
            } else if (strncmp($element, 'statusnet_', 10) == 0) {
                $this->element('statusnet:'.substr($element, 10), null, $value);
659
            } else {
660
                $this->element($element, null, $value);
661 662
            }
        }
663
        $this->elementEnd($role);
664 665
    }

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

680 681 682 683 684 685 686 687 688 689 690 691
    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');
        }
    }

692 693
    function showGeoRSS($geo)
    {
694 695 696 697 698 699
        if (!empty($geo)) {
            $this->element(
                'georss:point',
                null,
                $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
            );
700 701 702
        }
    }

703
    function showTwitterRssItem($entry)
704
    {
705 706 707 708 709 710
        $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']);
711

712
        // RSS only supports 1 enclosure per item
713
        if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
714 715 716
            $enclosure = $entry['enclosures'][0];
            $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
        }
717

718
        if(array_key_exists('tags', $entry)){
719 720 721 722
            foreach($entry['tags'] as $tag){
                $this->element('category', null,$tag);
            }
        }
723

724
        $this->showGeoRSS($entry['geo']);
725
        $this->elementEnd('item');
726 727
    }

728
    function showJsonObjects($objects)
729
    {
730 731 732
        print(json_encode($objects));
    }

733
    function showSingleXmlStatus($notice)
734
    {
735 736
        $this->initDocument('xml');
        $twitter_status = $this->twitterStatusArray($notice);
737
        $this->showTwitterXmlStatus($twitter_status, 'status', true);
738
        $this->endDocument('xml');
739 740
    }

741 742 743 744 745 746
    function showSingleAtomStatus($notice)
    {
        header('Content-Type: application/atom+xml; charset=utf-8');
        print $notice->asAtomEntry(true, true, true, $this->auth_user);
    }

747 748
    function show_single_json_status($notice)
    {
749 750 751 752
        $this->initDocument('json');
        $status = $this->twitterStatusArray($notice);
        $this->showJsonObjects($status);
        $this->endDocument('json');
753 754
    }

755
    function showXmlTimeline($notice)
756
    {
757
        $this->initDocument('xml');
758 759
        $this->elementStart('statuses', array('type' => 'array',
                                              'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
760 761

        if (is_array($notice)) {
762 763 764 765 766
            $notice = new ArrayWrapper($notice);
        }

        while ($notice->fetch()) {
            try {
767 768
                $twitter_status = $this->twitterStatusArray($notice);
                $this->showTwitterXmlStatus($twitter_status);
769 770 771
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                continue;
772 773 774
            }
        }

775
        $this->elementEnd('statuses');
776
        $this->endDocument('xml');
777 778
    }

779
    function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
780
    {
781
        $this->initDocument('rss');
782

783 784
        $this->element('title', null, $title);
        $this->element('link', null, $link);
785 786 787 788 789 790 791 792 793 794 795 796

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

797
        if (!is_null($suplink)) {
798
            // For FriendFeed's SUP protocol
799
            $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
800 801 802 803
                                         'rel' => 'http://api.friendfeed.com/2008/03#sup',
                                         'href' => $suplink,
                                         'type' => 'application/json'));
        }
804 805 806 807 808 809 810 811 812

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

813 814 815
        $this->element('description', null, $subtitle);
        $this->element('language', null, 'en-us');
        $this->element('ttl', null, '40');
816 817

        if (is_array($notice)) {
818 819 820 821 822
            $notice = new ArrayWrapper($notice);
        }

        while ($notice->fetch()) {
            try {
823 824
                $entry = $this->twitterRssEntryArray($notice);
                $this->showTwitterRssItem($entry);
825 826 827
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                // continue on exceptions
828 829 830
            }
        }

831
        $this->endTwitterRss();
832 833
    }

834
    function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
835
    {
836
        $this->initDocument('atom');
837

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

842 843 844 845
        if (!is_null($logo)) {
            $this->element('logo',null,$logo);
        }

846
        if (!is_null($suplink)) {
847
            // For FriendFeed's SUP protocol
848
            $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
849 850 851
                                         'href' => $suplink,
                                         'type' => 'application/json'));
        }
852 853

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

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

        if (is_array($notice)) {
862 863 864 865 866
            $notice = new ArrayWrapper($notice);
        }

        while ($notice->fetch()) {
            try {
867
                $this->raw($notice->asAtomEntry());
868 869 870
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                continue;
871 872 873
            }
        }

874
        $this->endDocument('atom');
875 876
    }

877
    function showRssGroups($group, $title, $link, $subtitle)
878
    {
879
        $this->initDocument('rss');
880 881 882 883 884 885 886 887 888

        $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) {
889 890
                $twitter_group = $this->twitterRssGroupArray($g);
                $this->showTwitterRssItem($twitter_group);
891 892 893
            }
        } else {
            while ($group->fetch()) {
894 895
                $twitter_group = $this->twitterRssGroupArray($group);
                $this->showTwitterRssItem($twitter_group);
896 897 898
            }
        }

899
        $this->endTwitterRss();
900 901
    }

902 903 904
    function showTwitterAtomEntry($entry)
    {
        $this->elementStart('entry');
905 906 907 908 909 910
        $this->element('title', null, common_xml_safe_str($entry['title']));
        $this->element(
            'content',
            array('type' => 'html'),
            common_xml_safe_str($entry['content'])
        );
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
        $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');
    }

929
    function showXmlDirectMessage($dm, $namespaces=false)
930
    {
931 932 933 934 935
        $attrs = array();
        if ($namespaces) {
            $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
        }
        $this->elementStart('direct_message', $attrs);
936 937 938 939
        foreach($dm as $element => $value) {
            switch ($element) {
            case 'sender':
            case 'recipient':
940
                $this->showTwitterXmlUser($value, $element);
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
                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();

960 961
        $dmsg['id'] = intval($message->id);
        $dmsg['sender_id'] = intval($from_profile);
962
        $dmsg['text'] = trim($message->content);
963
        $dmsg['recipient_id'] = intval($to_profile);
964
        $dmsg['created_at'] = $this->dateTwitter($message->created);
965 966
        $dmsg['sender_screen_name'] = $from_profile->nickname;
        $dmsg['recipient_screen_name'] = $to_profile->nickname;
967 968
        $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
        $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
969 970 971 972 973 974 975 976 977 978

        return $dmsg;
    }

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

        $from = $message->getFrom();

979
        $entry['title'] = sprintf('Message from %1$s to %2$s',
980 981 982 983 984 985
            $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);

986
        $taguribase = TagURI::base();
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009

        $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)
    {
1010
        $this->initDocument('xml');
1011
        $dmsg = $this->directMessageArray($message);
1012
        $this->showXmlDirectMessage($dmsg, true);
1013
        $this->endDocument('xml');
1014 1015 1016 1017
    }

    function showSingleJsonDirectMessage($message)
    {
1018
        $this->initDocument('json');
1019
        $dmsg = $this->directMessageArray($message);
1020 1021
        $this->showJsonObjects($dmsg);
        $this->endDocument('json');
1022 1023
    }

1024
    function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
1025
    {
1026
        $this->initDocument('atom');
1027

1028
        $this->element('title', null, common_xml_safe_str($title));
1029 1030 1031 1032 1033 1034 1035 1036 1037
        $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'));
1038
        $this->element('subtitle', null, common_xml_safe_str($subtitle));
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049

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

1050
        $this->endDocument('atom');
1051 1052 1053

    }

1054
    function showJsonTimeline($notice)
1055
    {
1056
        $this->initDocument('json');
1057 1058 1059 1060

        $statuses = array();

        if (is_array($notice)) {
1061 1062 1063 1064 1065
            $notice = new ArrayWrapper($notice);
        }

        while ($notice->fetch()) {
            try {
1066
                $twitter_status = $this->twitterStatusArray($notice);
1067
                array_push($statuses, $twitter_status);
1068 1069 1070
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                continue;
1071 1072 1073
            }
        }

1074
        $this->showJsonObjects($statuses);
1075

1076
        $this->endDocument('json');
1077 1078
    }

1079
    function showJsonGroups($group)
1080
    {
1081
        $this->initDocument('json');
1082 1083 1084 1085 1086

        $groups = array();

        if (is_array($group)) {
            foreach ($group as $g) {
1087
                $twitter_group = $this->twitterGroupArray($g);
1088 1089 1090 1091
                array_push($groups, $twitter_group);
            }
        } else {
            while ($group->fetch()) {
1092
                $twitter_group = $this->twitterGroupArray($group);
1093 1094 1095 1096
                array_push($groups, $twitter_group);
            }
        }

1097
        $this->showJsonObjects($groups);
1098

1099
        $this->endDocument('json');
1100 1101
    }

1102
    function showXmlGroups($group)
1103 1104
    {

1105
        $this->initDocument('xml');
1106 1107 1108 1109
        $this->elementStart('groups', array('type' => 'array'));

        if (is_array($group)) {
            foreach ($group as $g) {
1110 1111
                $twitter_group = $this->twitterGroupArray($g);
                $this->showTwitterXmlGroup($twitter_group);
1112 1113 1114
            }
        } else {
            while ($group->fetch()) {
1115 1116
                $twitter_group = $this->twitterGroupArray($group);
                $this->showTwitterXmlGroup($twitter_group);
1117 1118 1119 1120
            }
        }

        $this->elementEnd('groups');
1121
        $this->endDocument('xml');
1122 1123
    }

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    function showXmlLists($list, $next_cursor=0, $prev_cursor=0)
    {

        $this->initDocument('xml');
        $this->elementStart('lists_list');
        $this->elementStart('lists', array('type' => 'array'));

        if (is_array($list)) {
            foreach ($list as $l) {
                $twitter_list = $this->twitterListArray($l);
                $this->showTwitterXmlList($twitter_list);
            }
        } else {
            while ($list->fetch()) {
                $twitter_list = $this->twitterListArray($list);
                $this->showTwitterXmlList($twitter_list);
            }
        }

        $this->elementEnd('lists');

        $this->element('next_cursor', null, $next_cursor);
        $this->element('previous_cursor', null, $prev_cursor);

        $this->elementEnd('lists_list');
        $this->endDocument('xml');
    }

    function showJsonLists($list, $next_cursor=0, $prev_cursor=0)
    {
        $this->initDocument('json');

        $lists = array();

        if (is_array($list)) {
            foreach ($list as $l) {
                $twitter_list = $this->twitterListArray($l);
                array_push($lists, $twitter_list);
            }
        } else {
            while ($list->fetch()) {
                $twitter_list = $this->twitterListArray($list);
                array_push($lists, $twitter_list);
            }
        }

        $lists_list = array(
            'lists' => $lists,
            'next_cursor' => $next_cursor,
            'next_cursor_str' => strval($next_cursor),
            'previous_cursor' => $prev_cursor,
            'previous_cursor_str' => strval($prev_cursor)
        );

        $this->showJsonObjects($lists_list);

        $this->endDocument('json');
    }

1183
    function showTwitterXmlUsers($user)
1184
    {
1185
        $this->initDocument('xml');
1186 1187
        $this->elementStart('users', array('type' => 'array',
                                           'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
1188 1189

        if (is_array($user)) {
1190
            foreach ($user as $u) {
1191 1192
                $twitter_user = $this->twitterUserArray($u);
                $this->showTwitterXmlUser($twitter_user);
1193 1194 1195
            }
        } else {
            while ($user->fetch()) {
1196 1197
                $twitter_user = $this->twitterUserArray($user);
                $this->showTwitterXmlUser($twitter_user);
1198 1199 1200 1201
            }
        }

        $this->elementEnd('users');
1202
        $this->endDocument('xml');
1203 1204
    }

1205
    function showJsonUsers($user)
1206
    {
1207
        $this->initDocument('json');
1208 1209 1210 1211 1212

        $users = array();

        if (is_array($user)) {
            foreach ($user as $u) {
1213
                $twitter_user = $this->twitterUserArray($u);
1214 1215 1216 1217
                array_push($users, $twitter_user);
            }
        } else {
            while ($user->fetch()) {
1218
                $twitter_user = $this->twitterUserArray($user);
1219 1220 1221 1222
                array_push($users, $twitter_user);
            }
        }

1223
        $this->showJsonObjects($users);
1224

1225
        $this->endDocument('json');
1226 1227
    }

1228
    function showSingleJsonGroup($group)
1229
    {
1230 1231 1232 1233
        $this->initDocument('json');
        $twitter_group = $this->twitterGroupArray($group);
        $this->showJsonObjects($twitter_group);
        $this->endDocument('json');
1234 1235
    }

1236
    function showSingleXmlGroup($group)
1237
    {
1238 1239 1240 1241
        $this->initDocument('xml');
        $twitter_group = $this->twitterGroupArray($group);
        $this->showTwitterXmlGroup($twitter_group);
        $this->endDocument('xml');
1242 1243
    }

1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
    function showSingleJsonList($list)
    {
        $this->initDocument('json');
        $twitter_list = $this->twitterListArray($list);
        $this->showJsonObjects($twitter_list);
        $this->endDocument('json');
    }

    function showSingleXmlList($list)
    {
        $this->initDocument('xml');
        $twitter_list = $this->twitterListArray($list);
        $this->showTwitterXmlList($twitter_list);
        $this->endDocument('xml');
    }

1260
    function dateTwitter($dt)
1261
    {
Zach Copley's avatar
Zach Copley committed
1262 1263 1264 1265
        $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');
1266
    }
1267

1268
    function initDocument($type='xml')
1269
    {
1270
        switch ($type) {
1271
        case 'xml':
1272
            header('Content-Type: application/xml; charset=utf-8');
1273
            $this->startXML();
1274
            break;
1275
        case 'json':
1276 1277 1278
            header('Content-Type: application/json; charset=utf-8');

            // Check for JSONP callback
1279 1280
            if (isset($this->callback)) {
                print $this->callback . '(';
1281 1282
            }
            break;
1283
        case 'rss':
1284
            header("Content-Type: application/rss+xml; charset=utf-8");
1285
            $this->initTwitterRss();
1286
            break;
1287
        case 'atom':
1288
            header('Content-Type: application/atom+xml; charset=utf-8');
1289
            $this->initTwitterAtom();
1290
            break;
1291
        default:
1292
            // TRANS: Client error on an API request with an unsupported data format.
1293
            $this->clientError(_('Not a supported data format.'));
1294 1295 1296 1297 1298 1299
            break;
        }

        return;
    }

1300
    function endDocument($type='xml')
1301
    {
1302
        switch ($type) {
1303
        case 'xml':
1304
            $this->endXML();
1305
            break;
1306
        case 'json':
1307
            // Check for JSONP callback
1308
            if (isset($this->callback)) {
1309 1310 1311
                print ')';
            }
            break;
1312
        case 'rss':
1313
            $this->endTwitterRss();
1314
            break;
1315
        case 'atom':
1316
            $this->endTwitterRss();
1317
            break;
1318
        default:
1319
            // TRANS: Client error on an API request with an unsupported data format.
1320
            $this->clientError(_('Not a supported data format.'));
1321 1322 1323 1324 1325
            break;
        }
        return;
    }

1326
    function clientError($msg, $code = 400, $format = null)
1327
    {
1328
        $action = $this->trimmed('action');
1329 1330 1331
        if ($format === null) {
            $format = $this->format;
        }
1332 1333 1334

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

1335
        if (!array_key_exists($code, ClientErrorAction::$status)) {
1336 1337 1338
            $code = 400;
        }

1339 1340
        $status_string = ClientErrorAction::