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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        $timezone = 'UTC';

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

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

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

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

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

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

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

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

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

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

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

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

216 217
        return $twitter_user;
    }
218

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

        if (empty($notice->repeat_of)) {
            return $base;
        } else {
            $original = Notice::staticGet('id', $notice->repeat_of);
227 228 229 230 231 232 233
            if (empty($original)) {
                return $base;
            } else {
                $original_array = $this->twitterSimpleStatusArray($original, $include_user);
                $original_array['retweeted_status'] = $base;
                return $original_array;
            }
234 235 236 237
        }
    }

    function twitterSimpleStatusArray($notice, $include_user=true)
238
    {
239
        $profile = $notice->getProfile();
240

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

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

264 265 266 267 268 269 270 271 272
        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;
        }

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

279
        // Enclosures
280 281
        $attachments = $notice->attachments();

282 283 284 285 286
        if (!empty($attachments)) {

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

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

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

303 304
        return $twitter_status;
    }
305

306
    function twitterGroupArray($group)
307 308 309
    {
        $twitter_group=array();
        $twitter_group['id']=$group->id;
310
        $twitter_group['url']=$group->permalink();
311 312
        $twitter_group['nickname']=$group->nickname;
        $twitter_group['fullname']=$group->fullname;
313
        $twitter_group['homepage_url']=$group->homepage_url;
314 315 316 317 318 319 320
        $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;
321 322
        $twitter_group['created']=$this->dateTwitter($group->created);
        $twitter_group['modified']=$this->dateTwitter($group->modified);
323 324 325
        return $twitter_group;
    }

326
    function twitterRssGroupArray($group)
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    {
        $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;
    }

344
    function twitterRssEntryArray($notice)
345
    {
346 347
        $profile = $notice->getProfile();
        $entry = array();
348

349
        // We trim() to avoid extraneous whitespace in the output
350

351 352 353 354
        $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);
355 356 357 358

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

359
        $entry['updated'] = $entry['published'];
360
        $entry['author'] = $profile->getBestName();
361

362 363 364 365 366
        // Enclosures
        $attachments = $notice->attachments();
        $enclosures = array();

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

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

381 382 383 384 385 386 387 388 389 390 391
        // 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();

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

397 398 399 400 401 402 403 404 405 406
        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;
        }

407 408 409
        return $entry;
    }

410
    function twitterRelationshipArray($source, $target)
411 412 413 414
    {
        $relationship = array();

        $relationship['source'] =
415
            $this->relationshipDetailsArray($source, $target);
416
        $relationship['target'] =
417
            $this->relationshipDetailsArray($target, $source);
418 419 420 421

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

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

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

        $notifications = false;

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

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

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

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

        return $details;
    }

449
    function showTwitterXmlRelationship($relationship)
450 451 452 453 454 455
    {
        $this->elementStart('relationship');

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

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

464
    function showXmlRelationshipDetails($details)
465 466 467 468 469 470
    {
        foreach($details as $element => $value) {
            $this->element($element, null, $value);
        }
    }

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

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

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

520
    function showXmlAttachments($attachments) {
521 522 523 524 525 526 527 528 529 530 531 532 533
        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');
        }
    }

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

546
    function showTwitterRssItem($entry)
547
    {
548 549 550 551 552 553
        $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']);
554 555

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

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

567
        $this->showGeoRSS($entry['geo']);
568
        $this->elementEnd('item');
569 570
    }

571
    function showJsonObjects($objects)
572
    {
573 574 575
        print(json_encode($objects));
    }

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

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

592
    function showXmlTimeline($notice)
593
    {
594

595
        $this->initDocument('xml');
596
        $this->elementStart('statuses', array('type' => 'array'));
597 598 599

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

610
        $this->elementEnd('statuses');
611
        $this->endDocument('xml');
612 613
    }

614
    function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null)
615
    {
616

617
        $this->initDocument('rss');
618

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

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

637 638 639
        $this->element('description', null, $subtitle);
        $this->element('language', null, 'en-us');
        $this->element('ttl', null, '40');
640 641 642

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

653
        $this->endTwitterRss();
654 655
    }

656
    function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
657
    {
658

659
        $this->initDocument('atom');
660

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

665 666 667 668
        if (!is_null($logo)) {
            $this->element('logo',null,$logo);
        }

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

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

        $this->element('updated', null, common_date_iso8601('now'));
682
        $this->element('subtitle', null, $subtitle);
683 684 685

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

694
        $this->endDocument('atom');
695 696 697

    }

698
    function showRssGroups($group, $title, $link, $subtitle)
699 700
    {

701
        $this->initDocument('rss');
702 703 704 705 706 707 708 709 710

        $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) {
711 712
                $twitter_group = $this->twitterRssGroupArray($g);
                $this->showTwitterRssItem($twitter_group);
713 714 715
            }
        } else {
            while ($group->fetch()) {
716 717
                $twitter_group = $this->twitterRssGroupArray($group);
                $this->showTwitterRssItem($twitter_group);
718 719 720
            }
        }

721
        $this->endTwitterRss();
722 723
    }

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

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

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

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

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

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

        $dmsg['id'] = $message->id;
        $dmsg['sender_id'] = $message->from_profile;
        $dmsg['text'] = trim($message->content);
        $dmsg['recipient_id'] = $message->to_profile;
778
        $dmsg['created_at'] = $this->dateTwitter($message->created);
779 780
        $dmsg['sender_screen_name'] = $from_profile->nickname;
        $dmsg['recipient_screen_name'] = $to_profile->nickname;
781 782
        $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
        $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823

        return $dmsg;
    }

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

        $from = $message->getFrom();

        $entry['title'] = sprintf('Message from %s to %s',
            $from->nickname, $message->getTo()->nickname);

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

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

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

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

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

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

        // RSS item specific

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

        return $entry;
    }

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

    function showSingleJsonDirectMessage($message)
    {
832
        $this->initDocument('json');
833
        $dmsg = $this->directMessageArray($message);
834 835
        $this->showJsonObjects($dmsg);
        $this->endDocument('json');
836 837
    }

838
    function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
839 840
    {

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

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

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

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

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

865
        $this->endDocument('atom');
866 867 868

    }

869
    function showJsonTimeline($notice)
870
    {
871

872
        $this->initDocument('json');
873 874 875 876 877

        $statuses = array();

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

888
        $this->showJsonObjects($statuses);
889

890
        $this->endDocument('json');
891 892
    }

893
    function showJsonGroups($group)
894 895
    {

896
        $this->initDocument('json');
897 898 899 900 901

        $groups = array();

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

912
        $this->showJsonObjects($groups);
913

914
        $this->endDocument('json');
915 916
    }

917
    function showXmlGroups($group)
918 919
    {

920
        $this->initDocument('xml');
921 922 923 924
        $this->elementStart('groups', array('type' => 'array'));

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

        $this->elementEnd('groups');
936
        $this->endDocument('xml');
937 938
    }

939
    function showTwitterXmlUsers($user)
940 941
    {

942
        $this->initDocument('xml');
943 944 945
        $this->elementStart('users', array('type' => 'array'));

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

        $this->elementEnd('users');
958
        $this->endDocument('xml');
959 960
    }

961
    function showJsonUsers($user)
962 963
    {

964
        $this->initDocument('json');
965 966 967 968 969

        $users = array();

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

980
        $this->showJsonObjects($users);
981

982
        $this->endDocument('json');
983 984
    }

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

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

1001
    function dateTwitter($dt)
1002
    {
Zach Copley's avatar
Zach Copley committed
1003 1004 1005 1006
        $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');
1007
    }
1008

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