We are no longer offering accounts on this server. Consider https://gitlab.freedesktop.org/ as a place to host projects.

apiaction.php 50.9 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

Zach Copley's avatar
Zach Copley committed
48
    @li @ref publictimeline
49 50 51 52 53 54 55 56
    @li @ref friendstimeline

    @subsection statusmethods_sec Status Methods

    @li @ref statusesupdate

    @subsection usermethods_sec User Methods

57
    @subsection directmessagemethods_sec Direct Message Methods (now a plugin)
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

    @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
    var $user      = null;
    var $auth_user = null;
    var $page      = null;
    var $count     = null;
126 127
    var $offset    = null;
    var $limit     = null;
128 129
    var $max_id    = null;
    var $since_id  = null;
130
    var $source    = null;
131
    var $callback  = null;
132
    var $format    = null;
133

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

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

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

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

157 158 159 160
        // These two are not used everywhere, mainly just AtompubAction extensions
        $this->offset   = ($this->page-1) * $this->count;
        $this->limit    = $this->count + 1;

161
        if ($this->arg('since')) {
162
            header('X-GNUsocial-Warning: since parameter is disabled; use since_id');
163
        }
164

165 166 167 168 169 170
        $this->source = $this->trimmed('source');

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

171 172 173 174 175 176 177 178 179 180
        return true;
    }

    /**
     * Handle a request
     *
     * @param array $args Arguments from $_REQUEST
     *
     * @return void
     */
181
    protected function handle()
182
    {
183
        header('Access-Control-Allow-Origin: *');
184
        parent::handle();
185
    }
186

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

207
    function twitterUserArray($profile, $get_notice=false)
208
    {
209
        $twitter_user = array();
210

211 212 213 214 215
        try {
            $user = $profile->getUser();
        } catch (NoSuchUserException $e) {
            $user = null;
        }
216

217
        $twitter_user['id'] = intval($profile->id);
218 219
        $twitter_user['name'] = $profile->getBestName();
        $twitter_user['screen_name'] = $profile->nickname;
Evan Prodromou's avatar
Evan Prodromou committed
220
        $twitter_user['location'] = ($profile->location) ? $profile->location : null;
221
        $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
222

223 224
        // TODO: avatar url template (example.com/user/avatar?size={x}x{y})
        $twitter_user['profile_image_url'] = Avatar::urlByProfile($profile, AVATAR_STREAM_SIZE);
225 226
        $twitter_user['profile_image_url_https'] = $twitter_user['profile_image_url'];

227 228 229 230 231 232 233 234 235 236
        // START introduced by qvitter API, not necessary for StatusNet API
        $twitter_user['profile_image_url_profile_size'] = Avatar::urlByProfile($profile, AVATAR_PROFILE_SIZE);
        try {
            $avatar  = Avatar::getUploaded($profile);
            $origurl = $avatar->displayUrl();
        } catch (Exception $e) {
            $origurl = $twitter_user['profile_image_url_profile_size'];
        }
        $twitter_user['profile_image_url_original'] = $origurl;

237
        $twitter_user['groups_count'] = $profile->getGroupCount();
238 239 240 241
        foreach (array('linkcolor', 'backgroundcolor') as $key) {
            $twitter_user[$key] = Profile_prefs::getConfigData($profile, 'theme', $key);
        }
        // END introduced by qvitter API, not necessary for StatusNet API
242

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

247
        // Note: some profiles don't have an associated user
248

249
        $twitter_user['friends_count'] = $profile->subscriptionCount();
250

251
        $twitter_user['created_at'] = self::dateTwitter($profile->created);
252 253 254

        $timezone = 'UTC';

255
        if (!empty($user) && $user->timezone) {
256 257 258 259 260 261 262 263
            $timezone = $user->timezone;
        }

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

        $twitter_user['utc_offset'] = $t->format('Z');
        $twitter_user['time_zone'] = $timezone;
264
        $twitter_user['statuses_count'] = $profile->noticeCount();
265 266

        // Is the requesting user following this user?
267
        // These values might actually also mean "unknown". Ambiguity issues?
268
        $twitter_user['following'] = false;
269
        $twitter_user['statusnet_blocking'] = false;
270 271
        $twitter_user['notifications'] = false;

272 273 274 275 276
        if ($this->scoped instanceof Profile) {
            try {
                $sub = Subscription::getSubscription($this->scoped, $profile);
                // Notifications on?
                $twitter_user['following'] = true;
277
                $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
278 279
            } catch (NoResultException $e) {
                // well, the values are already false...
280
            }
281
            $twitter_user['statusnet_blocking']  = $this->scoped->hasBlocked($profile);            
282
        }
Evan Prodromou's avatar
Evan Prodromou committed
283

284 285
        if ($get_notice) {
            $notice = $profile->getCurrentNotice();
286
            if ($notice instanceof Notice) {
287
                // don't get user!
288
                $twitter_user['status'] = $this->twitterStatusArray($notice, false);
289 290
            }
        }
291

292 293
        // StatusNet-specific

294
        $twitter_user['statusnet_profile_url'] = $profile->profileurl;
295

296 297 298
        // The event call to handle NoticeSimpleStatusArray lets plugins add data to the output array
        Event::handle('TwitterUserArray', array($profile, &$twitter_user, $this->scoped, array()));

299 300
        return $twitter_user;
    }
301

302
    function twitterStatusArray($notice, $include_user=true)
303 304 305
    {
        $base = $this->twitterSimpleStatusArray($notice, $include_user);

306
        // FIXME: MOVE TO SHARE PLUGIN
307
        if (!empty($notice->repeat_of)) {
308
            $original = Notice::getKV('id', $notice->repeat_of);
309 310 311
            if ($original instanceof Notice) {
                $orig_array = $this->twitterSimpleStatusArray($original, $include_user);
                $base['retweeted_status'] = $orig_array;
312
            }
313
        }
314 315

        return $base;
316 317 318
    }

    function twitterSimpleStatusArray($notice, $include_user=true)
319
    {
320
        $profile = $notice->getProfile();
321

322 323
        $twitter_status = array();
        $twitter_status['text'] = $notice->content;
324
        $twitter_status['truncated'] = false; # Not possible on StatusNet
325
        $twitter_status['created_at'] = self::dateTwitter($notice->created);
326
        try {
327 328 329 330
            // We could just do $notice->reply_to but maybe the future holds a
            // different story for parenting.
            $parent = $notice->getParent();
            $in_reply_to = $parent->id;
331
        } catch (NoParentNoticeException $e) {
332 333 334
            $in_reply_to = null;
        }
        $twitter_status['in_reply_to_status_id'] = $in_reply_to;
335 336 337 338

        $source = null;

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

351
        $twitter_status['uri'] = $notice->getUri();
352
        $twitter_status['source'] = $source;
353
        $twitter_status['id'] = intval($notice->id);
354 355 356 357

        $replier_profile = null;

        if ($notice->reply_to) {
358
            $reply = Notice::getKV(intval($notice->reply_to));
359 360 361 362 363 364 365 366 367
            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;
368

369 370
        try {
            $notloc = Notice_location::locFromStored($notice);
371 372
            // This is the format that GeoJSON expects stuff to be in
            $twitter_status['geo'] = array('type' => 'Point',
373 374 375
                                           'coordinates' => array((float) $notloc->lat,
                                                                  (float) $notloc->lon));
        } catch (ServerException $e) {
376 377 378
            $twitter_status['geo'] = null;
        }

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

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

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

            foreach ($attachments as $attachment) {
387 388
                try {
                    $enclosure_o = $attachment->getEnclosure();
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
                } catch (ServerException $e) {
                    // There was not enough metadata available
396 397
                }
            }
398 399
        }

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

406 407
        // StatusNet-specific

408
        $twitter_status['statusnet_html'] = $notice->rendered;
409
        $twitter_status['statusnet_conversation_id'] = intval($notice->conversation);
410

411 412 413 414
        // The event call to handle NoticeSimpleStatusArray lets plugins add data to the output array
        Event::handle('NoticeSimpleStatusArray', array($notice, &$twitter_status, $this->scoped,
                                                       array('include_user'=>$include_user)));

415 416
        return $twitter_status;
    }
417

418
    function twitterGroupArray($group)
419
    {
420 421
        $twitter_group = array();

422
        $twitter_group['id'] = intval($group->id);
423 424 425 426
        $twitter_group['url'] = $group->permalink();
        $twitter_group['nickname'] = $group->nickname;
        $twitter_group['fullname'] = $group->fullname;

427 428
        if ($this->scoped instanceof Profile) {
            $twitter_group['member'] = $this->scoped->isMember($group);
429 430
            $twitter_group['blocked'] = Group_block::isBlocked(
                $group,
431
                $this->scoped
432 433 434
            );
        }

435
        $twitter_group['admin_count'] = $group->getAdminCount();
436 437 438 439 440 441 442 443
        $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;
444 445
        $twitter_group['created'] = self::dateTwitter($group->created);
        $twitter_group['modified'] = self::dateTwitter($group->modified);
446

447 448 449
        return $twitter_group;
    }

450
    function twitterRssGroupArray($group)
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
    {
        $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;
    }

468 469
    function twitterListArray($list)
    {
470
        $profile = Profile::getKV('id', $list->tagger);
471 472 473 474 475 476 477 478 479 480 481

        $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();

482 483
        if ($this->scoped instanceof Profile) {
            $twitter_list['following'] = $list->hasSubscriber($this->scoped);
484 485 486 487 488 489 490 491 492 493
        } else {
            $twitter_list['following'] = false;
        }

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

        return $twitter_list;
    }

494
    function twitterRssEntryArray($notice)
495
    {
496
        $entry = array();
497

498 499
        if (Event::handle('StartRssEntryArray', array($notice, &$entry))) {
            $profile = $notice->getProfile();
500

501
            // We trim() to avoid extraneous whitespace in the output
502

503 504 505 506
            $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);
507

508 509
            $taguribase = TagURI::base();
            $entry['id'] = "tag:$taguribase:$entry[link]";
510

511 512
            $entry['updated'] = $entry['published'];
            $entry['author'] = $profile->getBestName();
513

514 515 516 517 518
            // Enclosures
            $attachments = $notice->attachments();
            $enclosures = array();

            foreach ($attachments as $attachment) {
519 520
                try {
                    $enclosure_o = $attachment->getEnclosure();
521 522 523 524 525
                    $enclosure = array();
                    $enclosure['url'] = $enclosure_o->url;
                    $enclosure['mimetype'] = $enclosure_o->mimetype;
                    $enclosure['size'] = $enclosure_o->size;
                    $enclosures[] = $enclosure;
526 527
                } catch (ServerException $e) {
                    // There was not enough metadata available
528
                }
529 530
            }

531 532 533
            if (!empty($enclosures)) {
                $entry['enclosures'] = $enclosures;
            }
534

535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
            // 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'];

551 552
            try {
                $notloc = Notice_location::locFromStored($notice);
553 554 555
                // 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',
556 557 558
                                      'coordinates' => array((float) $notloc->lat,
                                                             (float) $notloc->lon));
            } catch (ServerException $e) {
559 560 561 562
                $entry['geo'] = null;
            }

            Event::handle('EndRssEntryArray', array($notice, &$entry));
563 564
        }

565 566 567
        return $entry;
    }

568
    function twitterRelationshipArray($source, $target)
569 570 571 572
    {
        $relationship = array();

        $relationship['source'] =
573
            $this->relationshipDetailsArray($source->getProfile(), $target->getProfile());
574
        $relationship['target'] =
575
            $this->relationshipDetailsArray($target->getProfile(), $source->getProfile());
576 577 578 579

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

580
    function relationshipDetailsArray(Profile $source, Profile $target)
581 582 583
    {
        $details = array();

584 585
        $details['screen_name'] = $source->getNickname();
        $details['followed_by'] = $target->isSubscribed($source);
586

587 588 589 590 591 592 593
        try {
            $sub = Subscription::getSubscription($source, $target);
            $details['following'] = true;
            $details['notifications_enabled'] = ($sub->jabber || $sub->sms);
        } catch (NoResultException $e) {
            $details['following'] = false;
            $details['notifications_enabled'] = false;
594 595
        }

596
        $details['blocking'] = $source->hasBlocked($target);
597
        $details['id'] = intval($source->id);
598 599 600 601

        return $details;
    }

602
    function showTwitterXmlRelationship($relationship)
603 604 605 606 607 608
    {
        $this->elementStart('relationship');

        foreach($relationship as $element => $value) {
            if ($element == 'source' || $element == 'target') {
                $this->elementStart($element);
609
                $this->showXmlRelationshipDetails($value);
610 611 612 613 614 615 616
                $this->elementEnd($element);
            }
        }

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

617
    function showXmlRelationshipDetails($details)
618 619 620 621 622 623
    {
        foreach($details as $element => $value) {
            $this->element($element, null, $value);
        }
    }

624
    function showTwitterXmlStatus($twitter_status, $tag='status', $namespaces=false)
625
    {
626 627 628 629 630
        $attrs = array();
        if ($namespaces) {
            $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
        }
        $this->elementStart($tag, $attrs);
631 632 633
        foreach($twitter_status as $element => $value) {
            switch ($element) {
            case 'user':
634
                $this->showTwitterXmlUser($twitter_status['user']);
635 636
                break;
            case 'text':
637
                $this->element($element, null, common_xml_safe_str($value));
638
                break;
639
            case 'attachments':
640
                $this->showXmlAttachments($twitter_status['attachments']);
641
                break;
642
            case 'geo':
643
                $this->showGeoXML($value);
644
                break;
645
            case 'retweeted_status':
646
                // FIXME: MOVE TO SHARE PLUGIN
647 648
                $this->showTwitterXmlStatus($value, 'retweeted_status');
                break;
649
            default:
650 651 652 653 654
                if (strncmp($element, 'statusnet_', 10) == 0) {
                    $this->element('statusnet:'.substr($element, 10), null, $value);
                } else {
                    $this->element($element, null, $value);
                }
655 656
            }
        }
657
        $this->elementEnd($tag);
658 659
    }

660
    function showTwitterXmlGroup($twitter_group)
661 662 663 664 665 666 667 668
    {
        $this->elementStart('group');
        foreach($twitter_group as $element => $value) {
            $this->element($element, null, $value);
        }
        $this->elementEnd('group');
    }

669 670 671 672 673 674 675 676 677 678 679 680 681 682
    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');
    }

683
    function showTwitterXmlUser($twitter_user, $role='user', $namespaces=false)
684
    {
685 686 687 688 689
        $attrs = array();
        if ($namespaces) {
            $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
        }
        $this->elementStart($role, $attrs);
690 691
        foreach($twitter_user as $element => $value) {
            if ($element == 'status') {
692
                $this->showTwitterXmlStatus($twitter_user['status']);
693 694
            } else if (strncmp($element, 'statusnet_', 10) == 0) {
                $this->element('statusnet:'.substr($element, 10), null, $value);
695
            } else {
696
                $this->element($element, null, $value);
697 698
            }
        }
699
        $this->elementEnd($role);
700 701
    }

702
    function showXmlAttachments($attachments) {
703 704 705 706 707 708 709 710 711 712 713 714 715
        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');
        }
    }

716 717 718 719 720 721 722 723 724 725 726 727
    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');
        }
    }

728 729
    function showGeoRSS($geo)
    {
730 731 732 733 734 735
        if (!empty($geo)) {
            $this->element(
                'georss:point',
                null,
                $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
            );
736 737 738
        }
    }

739
    function showTwitterRssItem($entry)
740
    {
741 742 743 744 745 746
        $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']);
747

748
        // RSS only supports 1 enclosure per item
749
        if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
750 751 752
            $enclosure = $entry['enclosures'][0];
            $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
        }
753

754
        if(array_key_exists('tags', $entry)){
755 756 757 758
            foreach($entry['tags'] as $tag){
                $this->element('category', null,$tag);
            }
        }
759

760
        $this->showGeoRSS($entry['geo']);
761
        $this->elementEnd('item');
762 763
    }

764
    function showJsonObjects($objects)
765
    {
766 767 768
        print(json_encode($objects));
    }

769
    function showSingleXmlStatus($notice)
770
    {
771 772
        $this->initDocument('xml');
        $twitter_status = $this->twitterStatusArray($notice);
773
        $this->showTwitterXmlStatus($twitter_status, 'status', true);
774
        $this->endDocument('xml');
775 776
    }

777 778 779
    function showSingleAtomStatus($notice)
    {
        header('Content-Type: application/atom+xml; charset=utf-8');
780
        print $notice->asAtomEntry(true, true, true, $this->scoped);
781 782
    }

783 784
    function show_single_json_status($notice)
    {
785 786 787 788
        $this->initDocument('json');
        $status = $this->twitterStatusArray($notice);
        $this->showJsonObjects($status);
        $this->endDocument('json');
789 790
    }

791
    function showXmlTimeline($notice)
792
    {
793
        $this->initDocument('xml');
794 795
        $this->elementStart('statuses', array('type' => 'array',
                                              'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
796 797

        if (is_array($notice)) {
798 799 800 801 802 803
            //FIXME: make everything calling showJsonTimeline use only Notice objects
            $ids = array();
            foreach ($notice as $n) {
                $ids[] = $n->getID();
            }
            $notice = Notice::multiGet('id', $ids);
804 805 806 807
        }

        while ($notice->fetch()) {
            try {
808 809
                $twitter_status = $this->twitterStatusArray($notice);
                $this->showTwitterXmlStatus($twitter_status);
810 811 812
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                continue;
813 814 815
            }
        }

816
        $this->elementEnd('statuses');
817
        $this->endDocument('xml');
818 819
    }

820
    function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
821
    {
822
        $this->initDocument('rss');
823

824 825
        $this->element('title', null, $title);
        $this->element('link', null, $link);
826 827 828 829 830 831 832 833 834 835 836 837

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

838
        if (!is_null($suplink)) {
839
            // For FriendFeed's SUP protocol
840
            $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
841 842 843 844
                                         'rel' => 'http://api.friendfeed.com/2008/03#sup',
                                         'href' => $suplink,
                                         'type' => 'application/json'));
        }
845 846 847 848 849 850 851 852 853

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

854 855 856
        $this->element('description', null, $subtitle);
        $this->element('language', null, 'en-us');
        $this->element('ttl', null, '40');
857 858

        if (is_array($notice)) {
859 860 861 862 863 864
            //FIXME: make everything calling showJsonTimeline use only Notice objects
            $ids = array();
            foreach ($notice as $n) {
                $ids[] = $n->getID();
            }
            $notice = Notice::multiGet('id', $ids);
865 866 867 868
        }

        while ($notice->fetch()) {
            try {
869 870
                $entry = $this->twitterRssEntryArray($notice);
                $this->showTwitterRssItem($entry);
871 872 873
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                // continue on exceptions
874 875 876
            }
        }

877
        $this->endTwitterRss();
878 879
    }

880
    function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
881
    {
882
        $this->initDocument('atom');
883

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

888 889 890 891
        if (!is_null($logo)) {
            $this->element('logo',null,$logo);
        }

892
        if (!is_null($suplink)) {
893
            // For FriendFeed's SUP protocol
894
            $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
895 896 897
                                         'href' => $suplink,
                                         'type' => 'application/json'));
        }
898 899

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

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

        if (is_array($notice)) {
908 909 910 911 912 913
            //FIXME: make everything calling showJsonTimeline use only Notice objects
            $ids = array();
            foreach ($notice as $n) {
                $ids[] = $n->getID();
            }
            $notice = Notice::multiGet('id', $ids);
914 915