GitHost.io will be shut down on June 1, 2019. At that point this instance will be unreachable and all data will be irrevocably deleted. More details at https://about.gitlab.com/gitlab-hosted/#githost-is-shutting-down-on-june-1st-2019

apiaction.php 51.7 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
    @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
    {
mmn's avatar
mmn 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'] = $profile->getID();
218
        $twitter_user['name'] = $profile->getBestName();
219 220 221
        $twitter_user['screen_name'] = $profile->getNickname();
        $twitter_user['location'] = $profile->location;
        $twitter_user['description'] = $profile->getDescription();
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
            $in_reply_to = null;
333 334 335
        } catch (NoResultException $e) {
            // the in_reply_to message has probably been deleted
            $in_reply_to = null;
336 337
        }
        $twitter_status['in_reply_to_status_id'] = $in_reply_to;
338 339

        $source = null;
340
        $source_link = null;
341 342

        $ns = $notice->getSource();
343
        if ($ns instanceof Notice_source) {
344 345 346 347 348 349
            $source = $ns->code;
            if (!empty($ns->url)) {
                $source_link = $ns->url;
                if (!empty($ns->name)) {
                    $source = $ns->name;
                }
350 351 352
            }
        }

353
        $twitter_status['uri'] = $notice->getUri();
354
        $twitter_status['source'] = $source;
355
        $twitter_status['source_link'] = $source_link;
356
        $twitter_status['id'] = intval($notice->id);
357 358 359 360

        $replier_profile = null;

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

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

382
        // Enclosures
383 384
        $attachments = $notice->attachments();

385 386 387 388 389
        if (!empty($attachments)) {

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

            foreach ($attachments as $attachment) {
390 391
                try {
                    $enclosure_o = $attachment->getEnclosure();
392
                    $enclosure = array();
393 394 395
                    $enclosure['url'] = $enclosure_o->url;
                    $enclosure['mimetype'] = $enclosure_o->mimetype;
                    $enclosure['size'] = $enclosure_o->size;
396
                    $twitter_status['attachments'][] = $enclosure;
397 398
                } catch (ServerException $e) {
                    // There was not enough metadata available
399 400
                }
            }
401 402
        }

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

409 410
        // StatusNet-specific

411
        $twitter_status['statusnet_html'] = $notice->getRendered();
412
        $twitter_status['statusnet_conversation_id'] = intval($notice->conversation);
413

414 415 416 417
        // 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)));

418 419
        return $twitter_status;
    }
420

421
    function twitterGroupArray($group)
422
    {
423 424
        $twitter_group = array();

425
        $twitter_group['id'] = intval($group->id);
426 427 428 429
        $twitter_group['url'] = $group->permalink();
        $twitter_group['nickname'] = $group->nickname;
        $twitter_group['fullname'] = $group->fullname;

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

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

450 451 452
        return $twitter_group;
    }

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

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

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

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

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

        return $twitter_list;
    }

497
    function twitterRssEntryArray($notice)
498
    {
499
        $entry = array();
500

501 502
        if (Event::handle('StartRssEntryArray', array($notice, &$entry))) {
            $profile = $notice->getProfile();
503

504
            // We trim() to avoid extraneous whitespace in the output
505

506
            $entry['content'] = common_xml_safe_str(trim($notice->getRendered()));
507 508 509
            $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);
510

511 512
            $taguribase = TagURI::base();
            $entry['id'] = "tag:$taguribase:$entry[link]";
513

514 515
            $entry['updated'] = $entry['published'];
            $entry['author'] = $profile->getBestName();
516

517 518 519 520 521
            // Enclosures
            $attachments = $notice->attachments();
            $enclosures = array();

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

534 535 536
            if (!empty($enclosures)) {
                $entry['enclosures'] = $enclosures;
            }
537

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

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

            Event::handle('EndRssEntryArray', array($notice, &$entry));
566 567
        }

568 569 570
        return $entry;
    }

571
    function twitterRelationshipArray($source, $target)
572 573 574 575
    {
        $relationship = array();

        $relationship['source'] =
576
            $this->relationshipDetailsArray($source->getProfile(), $target->getProfile());
577
        $relationship['target'] =
578
            $this->relationshipDetailsArray($target->getProfile(), $source->getProfile());
579 580 581 582

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

583
    function relationshipDetailsArray(Profile $source, Profile $target)
584 585 586
    {
        $details = array();

587 588
        $details['screen_name'] = $source->getNickname();
        $details['followed_by'] = $target->isSubscribed($source);
589

590 591 592 593 594 595 596
        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;
597 598
        }

599
        $details['blocking'] = $source->hasBlocked($target);
600
        $details['id'] = intval($source->id);
601 602 603 604

        return $details;
    }

605
    function showTwitterXmlRelationship($relationship)
606 607 608 609 610 611
    {
        $this->elementStart('relationship');

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

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

620
    function showXmlRelationshipDetails($details)
621 622 623 624 625 626
    {
        foreach($details as $element => $value) {
            $this->element($element, null, $value);
        }
    }

627
    function showTwitterXmlStatus($twitter_status, $tag='status', $namespaces=false)
628
    {
629 630 631 632 633
        $attrs = array();
        if ($namespaces) {
            $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
        }
        $this->elementStart($tag, $attrs);
634 635 636
        foreach($twitter_status as $element => $value) {
            switch ($element) {
            case 'user':
637
                $this->showTwitterXmlUser($twitter_status['user']);
638 639
                break;
            case 'text':
640
                $this->element($element, null, common_xml_safe_str($value));
641
                break;
642
            case 'attachments':
643
                $this->showXmlAttachments($twitter_status['attachments']);
644
                break;
645
            case 'geo':
646
                $this->showGeoXML($value);
647
                break;
648
            case 'retweeted_status':
649
                // FIXME: MOVE TO SHARE PLUGIN
650 651
                $this->showTwitterXmlStatus($value, 'retweeted_status');
                break;
652
            default:
653
                if (strncmp($element, 'statusnet_', 10) == 0) {
654 655 656 657 658
                    if ($element === 'statusnet_in_groups' && is_array($value)) {
                        // QVITTERFIX because it would cause an array to be sent as $value
                        // THIS IS UNDOCUMENTED AND SHOULD NEVER BE RELIED UPON (qvitter uses json output)
                        $value = json_encode($value);
                    }
659 660 661 662
                    $this->element('statusnet:'.substr($element, 10), null, $value);
                } else {
                    $this->element($element, null, $value);
                }
663 664
            }
        }
665
        $this->elementEnd($tag);
666 667
    }

668
    function showTwitterXmlGroup($twitter_group)
669 670 671 672 673 674 675 676
    {
        $this->elementStart('group');
        foreach($twitter_group as $element => $value) {
            $this->element($element, null, $value);
        }
        $this->elementEnd('group');
    }

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

691
    function showTwitterXmlUser($twitter_user, $role='user', $namespaces=false)
692
    {
693 694 695 696 697
        $attrs = array();
        if ($namespaces) {
            $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
        }
        $this->elementStart($role, $attrs);
698 699
        foreach($twitter_user as $element => $value) {
            if ($element == 'status') {
700
                $this->showTwitterXmlStatus($twitter_user['status']);
701 702
            } else if (strncmp($element, 'statusnet_', 10) == 0) {
                $this->element('statusnet:'.substr($element, 10), null, $value);
703
            } else {
704
                $this->element($element, null, $value);
705 706
            }
        }
707
        $this->elementEnd($role);
708 709
    }

710
    function showXmlAttachments($attachments) {
711 712 713 714 715 716 717 718 719 720 721 722 723
        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');
        }
    }

724 725 726 727 728 729 730 731 732 733 734 735
    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');
        }
    }

736 737
    function showGeoRSS($geo)
    {
738 739 740 741 742 743
        if (!empty($geo)) {
            $this->element(
                'georss:point',
                null,
                $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
            );
744 745 746
        }
    }

747
    function showTwitterRssItem($entry)
748
    {
749 750 751 752 753 754
        $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']);
755

756
        // RSS only supports 1 enclosure per item
757
        if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
758 759 760
            $enclosure = $entry['enclosures'][0];
            $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
        }
761

762
        if(array_key_exists('tags', $entry)){
763 764 765 766
            foreach($entry['tags'] as $tag){
                $this->element('category', null,$tag);
            }
        }
767

768
        $this->showGeoRSS($entry['geo']);
769
        $this->elementEnd('item');
770 771
    }

772
    function showJsonObjects($objects)
773
    {
774 775 776 777 778 779
        $json_objects = json_encode($objects);
        if($json_objects === false) {
            $this->clientError(_('JSON encoding failed. Error: ').json_last_error_msg());     		   
        } else {
        	print $json_objects;
        }
780 781
    }

782

783
    function showSingleXmlStatus($notice)
784
    {
785 786
        $this->initDocument('xml');
        $twitter_status = $this->twitterStatusArray($notice);
787
        $this->showTwitterXmlStatus($twitter_status, 'status', true);
788
        $this->endDocument('xml');
789 790
    }

791 792
    function showSingleAtomStatus($notice)
    {
793 794
        header('Content-Type: application/atom+xml;type=entry;charset="utf-8"');
        print '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
795
        print $notice->asAtomEntry(true, true, true, $this->scoped);
796 797
    }

798 799
    function show_single_json_status($notice)
    {
800 801 802 803
        $this->initDocument('json');
        $status = $this->twitterStatusArray($notice);
        $this->showJsonObjects($status);
        $this->endDocument('json');
804 805
    }

806
    function showXmlTimeline($notice)
807
    {
808
        $this->initDocument('xml');
809 810
        $this->elementStart('statuses', array('type' => 'array',
                                              'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
811 812

        if (is_array($notice)) {
813 814 815 816 817 818
            //FIXME: make everything calling showJsonTimeline use only Notice objects
            $ids = array();
            foreach ($notice as $n) {
                $ids[] = $n->getID();
            }
            $notice = Notice::multiGet('id', $ids);
819 820 821 822
        }

        while ($notice->fetch()) {
            try {
823 824
                $twitter_status = $this->twitterStatusArray($notice);
                $this->showTwitterXmlStatus($twitter_status);
825 826 827
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                continue;
828 829 830
            }
        }

831
        $this->elementEnd('statuses');
832
        $this->endDocument('xml');
833 834
    }

835
    function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
836
    {
837
        $this->initDocument('rss');
838

839 840
        $this->element('title', null, $title);
        $this->element('link', null, $link);
841 842 843 844 845 846 847 848 849 850 851 852

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

853
        if (!is_null($suplink)) {
854
            // For FriendFeed's SUP protocol
855
            $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
856 857 858 859
                                         'rel' => 'http://api.friendfeed.com/2008/03#sup',
                                         'href' => $suplink,
                                         'type' => 'application/json'));
        }
860 861 862 863 864 865 866 867 868

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

869 870 871
        $this->element('description', null, $subtitle);
        $this->element('language', null, 'en-us');
        $this->element('ttl', null, '40');
872 873

        if (is_array($notice)) {
874 875 876 877 878 879
            //FIXME: make everything calling showJsonTimeline use only Notice objects
            $ids = array();
            foreach ($notice as $n) {
                $ids[] = $n->getID();
            }
            $notice = Notice::multiGet('id', $ids);
880 881 882 883
        }

        while ($notice->fetch()) {
            try {
884 885
                $entry = $this->twitterRssEntryArray($notice);
                $this->showTwitterRssItem($entry);
886 887 888
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                // continue on exceptions
889 890 891
            }
        }

892
        $this->endTwitterRss();
893 894
    }

895
    function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
896
    {
897
        $this->initDocument('atom');
898

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

903 904 905 906
        if (!is_null($logo)) {
            $this->element('logo',null,$logo);
        }

907
        if (!is_null($suplink)) {
908
            // For FriendFeed's SUP protocol
909
            $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
910 911 912
                                         'href' => $suplink,
                                         'type' => 'application/json'));
        }
913 914

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

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

        if (is_array($notice)) {
923 924 925 926 927 928
            //FIXME: make everything calling showJsonTimeline use only Notice objects
            $ids = array();
            foreach ($notice as $n) {
                $ids[] = $n->getID();
            }
            $notice = Notice::multiGet('id', $ids);
929 930 931 932
        }

        while ($notice->fetch()) {
            try {
933
                $this->raw($notice->asAtomEntry());
934 935 936
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                continue;
937 938 939
            }
        }

940
        $this->endDocument('atom');
941 942
    }

943
    function showRssGroups($group, $title, $link, $subtitle)
944
    {
945
        $this->initDocument('rss');
946 947 948 949 950 951 952 953 954

        $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) {
955 956
                $twitter_group = $this->twitterRssGroupArray($g);
                $this->showTwitterRssItem($twitter_group);
957 958 959
            }
        } else {
            while ($group->fetch()) {
960 961
                $twitter_group = $this->twitterRssGroupArray($group);
                $this->showTwitterRssItem($twitter_group);
962 963 964
            }
        }

965
        $this->endTwitterRss();
966 967
    }

968 969 970
    function showTwitterAtomEntry($entry)
    {
        $this->elementStart('entry');
971 972 973 974 975 976
        $this->element('title', null, common_xml_safe_str($entry['title']));
        $this->element(
            'content',
            array('type' => 'html'),
            common_xml_safe_str($entry['content'])
        );
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
        $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');
    }

995
    function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
996
    {
997
        $this->initDocument('atom');
998

999
        $this->element('title', null, common_xml_safe_str($title));
1000 1001 1002 1003 1004 1005 1006 1007 1008
        $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'));
1009
        $this->element('subtitle', null, common_xml_safe_str($subtitle));
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020

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

1021
        $this->endDocument('atom');
1022 1023 1024

    }

1025
    function showJsonTimeline($notice)
1026
    {
1027
        $this->initDocument('json');
1028 1029 1030 1031

        $statuses = array();

        if (is_array($notice)) {
1032 1033 1034 1035 1036 1037
            //FIXME: make everything calling showJsonTimeline use only Notice objects
            $ids = array();
            foreach ($notice as $n) {
                $ids[] = $n->getID();
            }
            $notice = Notice::multiGet('id', $ids);
1038 1039 1040 1041
        }

        while ($notice->fetch()) {
            try {
1042
                $twitter_status = $this->twitterStatusArray($notice);
1043
                array_push($statuses, $twitter_status);
1044 1045 1046
            } catch (Exception $e) {
                common_log(LOG_ERR, $e->getMessage());
                continue;
1047 1048 1049
            }
        }

1050
        $this->showJsonObjects($statuses);
1051

1052
        $this->endDocument('json');
1053 1054
    }

1055
    function showJsonGroups($group)
1056
    {
1057
        $this->initDocument('json');
1058 1059 1060 1061 1062

        $groups = array();

        if (is_array($group)) {
            foreach ($group as $g) {
1063
                $twitter_group = $this->twitterGroupArray($g);
1064 1065 1066 1067
                array_push($groups, $twitter_group);
            }
        } else {
            while ($group->fetch()) {
1068
                $twitter_group = $this->twitterGroupArray($group);
1069 1070 1071 1072
                array_push($groups, $twitter_group);
            }
        }

1073
        $this->showJsonObjects($groups);
1074

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

1078
    function showXmlGroups($group)
1079 1080
    {

1081
        $this->initDocument('xml');
1082 1083 1084 1085
        $this->elementStart('groups', array('type' => 'array'));

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

        $this->elementEnd('groups');
1097
        $this->endDocument('xml');
1098 1099
    }

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 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
    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');
    }

1159
    function showTwitterXmlUsers($user)
1160
    {
1161
        $this->initDocument('xml');
1162 1163
        $this->elementStart('users', array('type' => 'array',
                                           'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
1164 1165

        if (is_array($user)) {
1166
            foreach ($user as $u) {
1167 1168
                $twitter_user = $this->twitterUserArray($u);
                $this->showTwitterXmlUser($twitter_user);
1169 1170 1171
            }
        } else {
            while ($user->fetch()) {
1172 1173
                $twitter_user = $this->twitterUserArray($user);
                $this->showTwitterXmlUser($twitter_user);
1174 1175 1176 1177
            }
        }

        $this->elementEnd('users');
1178
        $this->endDocument('xml');
1179 1180
    }

1181
    function showJsonUsers($user)
1182
    {
1183
        $this->initDocument('json');
1184 1185 1186 1187 1188

        $users = array();

        if (is_array($user)) {
            foreach ($user as $u) {
1189
                $twitter_user = $this->twitterUserArray($u);
1190 1191 1192 1193
                array_push($users, $twitter_user);
            }
        } else {
            while ($user->fetch()) {
1194
                $twitter_user = $this->twitterUserArray($user);
1195 1196 1197 1198
                array_push($users, $twitter_user);
            }
        }

1199
        $this->showJsonObjects($users);
1200

1201
        $this->endDocument('json');
1202 1203
    }

1204
    function showSingleJsonGroup($group)
1205
    {
1206 1207 1208 1209
        $this->initDocument('json');
        $twitter_group = $this->twitterGroupArray($group);
        $this->showJsonObjects($twitter_group);
        $this->endDocument('json');
1210 1211
    }

1212
    function showSingleXmlGroup($group)
1213
    {
1214 1215 1216 1217
        $this->initDocument('xml');
        $twitter_group = $this->twitterGroupArray($group);
        $this->showTwitterXmlGroup($twitter_group);
        $this->endDocument('xml');
1218 1219
    }

1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
    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');
    }

1236
    static function dateTwitter($dt)
1237
    {
Zach Copley's avatar
Zach Copley committed
1238 1239 1240 1241
        $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');
1242
    }
1243

1244
    function initDocument($type='xml')
1245
    {
1246
        switch ($type) {
1247
        case 'xml':
1248
            header('Content-Type: application/xml; charset=utf-8');
1249
            $this->startXML();
1250
            break;
1251
        case 'json':
1252 1253 1254
            header('Content-Type: application/json; charset=utf-8');

            // Check for JSONP callback
1255 1256
            if (isset($this->callback)) {
                print $this->callback . '(';
1257 1258
            }
            break;
1259
        case 'rss':
1260
            header("Content-Type: application/rss+xml; charset=utf-8");
1261
            $this->initTwitterRss();
1262
            break;
1263
        case 'atom':
1264
            header('Content-Type: application/atom+xml; charset=utf-8');
1265
            $this->initTwitterAtom();
1266
            break;
1267
        default:
1268
            // TRANS: Client error on an API request with an unsupported data format.
1269
            $this->clientError(_('Not a supported data format.'));
1270 1271 1272 1273 1274
        }

        return;
    }

1275
    function endDocument($type='xml')
1276
    {
1277
        switch ($type) {
1278
        case 'xml':
1279
            $this->endXML();
1280
            break;
1281
        case 'json':
1282
            // Check for JSONP callback
1283
            if (isset($this->callback)) {
1284