apitimelineuser.php 13.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Show a user's timeline
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * 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/>.
 *
 * @category  API
 * @package   StatusNet
Zach Copley's avatar
Zach Copley committed
24 25 26 27 28 29
 * @author    Craig Andrews <candrews@integralblue.com>
 * @author    Evan Prodromou <evan@status.net>
 * @author    Jeffery To <jeffery.to@gmail.com>
 * @author    mac65 <mac65@mac65.com>
 * @author    Mike Cochrane <mikec@mikenz.geek.nz>
 * @author    Robin Millette <robin@millette.info>
30 31
 * @author    Zach Copley <zach@status.net>
 * @copyright 2009 StatusNet, Inc.
32
 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33 34 35 36
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

37
if (!defined('GNUSOCIAL')) { exit(1); }
38 39 40 41 42 43 44 45

/**
 * Returns the most recent notices (default 20) posted by the authenticating
 * user. Another user's timeline can be requested via the id parameter. This
 * is the API equivalent of the user profile web page.
 *
 * @category API
 * @package  StatusNet
Zach Copley's avatar
Zach Copley committed
46 47 48 49 50 51
 * @author   Craig Andrews <candrews@integralblue.com>
 * @author   Evan Prodromou <evan@status.net>
 * @author   Jeffery To <jeffery.to@gmail.com>
 * @author   mac65 <mac65@mac65.com>
 * @author   Mike Cochrane <mikec@mikenz.geek.nz>
 * @author   Robin Millette <robin@millette.info>
52 53 54 55
 * @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/
 */
56
class ApiTimelineUserAction extends ApiBareAuthAction
57 58 59
{
    var $notices = null;

60 61
    var $next_id = null;

62 63 64 65 66 67 68
    /**
     * Take arguments for running
     *
     * @param array $args $_REQUEST args
     *
     * @return boolean success flag
     */
69
    protected function prepare(array $args=array())
70 71 72
    {
        parent::prepare($args);

73
        $this->target = $this->getTargetProfile($this->arg('id'));
74

75
        if (!($this->target instanceof Profile)) {
Siebrand Mazeland's avatar
Siebrand Mazeland committed
76
            // TRANS: Client error displayed requesting most recent notices for a non-existing user.
77
            $this->clientError(_('No such user.'), 404);
78 79
        }

80 81 82 83
        if (!$this->target->isLocal()) {
            $this->serverError(_('Remote user timelines are not available here yet.'), 501);
        }

84 85 86 87 88 89 90 91 92 93 94 95
        $this->notices = $this->getNotices();

        return true;
    }

    /**
     * Handle the request
     *
     * Just show the notices
     *
     * @return void
     */
96
    protected function handle()
97
    {
98
        parent::handle();
99 100 101 102 103 104

        if ($this->isPost()) {
            $this->handlePost();
        } else {
            $this->showTimeline();
        }
105 106 107 108 109 110 111 112 113
    }

    /**
     * Show the timeline of notices
     *
     * @return void
     */
    function showTimeline()
    {
114 115
        // We'll use the shared params from the Atom stub
        // for other feed types.
116
        $atom = new AtomUserNoticeFeed($this->target->getUser(), $this->scoped);
117 118

        $link = common_local_url(
119
                                 'showstream',
120
                                 array('nickname' => $this->target->getNickname())
121
                                 );
122

123
        $self = $this->getSelfUri();
124 125 126 127

        // FriendFeed's SUP protocol
        // Also added RSS and Atom feeds

128
        $suplink = common_local_url('sup', null, null, $this->target->getID());
129 130
        header('X-SUP-ID: ' . $suplink);

131 132

        // paging links
133 134
        $nextUrl = !empty($this->next_id)
                    ? common_local_url('ApiTimelineUser',
135
                                    array('format' => $this->format,
136
                                          'id' => $this->target->getID()),
137 138
                                    array('max_id' => $this->next_id))
                    : null;
mmn's avatar
mmn committed
139 140 141 142 143 144 145

        $prevExtra = array();
        if (!empty($this->notices)) {
            assert($this->notices[0] instanceof Notice);
            $prevExtra['since_id'] = $this->notices[0]->id;
        }

146 147
        $prevUrl = common_local_url('ApiTimelineUser',
                                    array('format' => $this->format,
148
                                          'id' => $this->target->getID()),
mmn's avatar
mmn committed
149
                                    $prevExtra);
150 151
        $firstUrl = common_local_url('ApiTimelineUser',
                                    array('format' => $this->format,
152
                                          'id' => $this->target->getID()));
153

154
        switch($this->format) {
155
        case 'xml':
156
            $this->showXmlTimeline($this->notices);
157 158
            break;
        case 'rss':
159
            $this->showRssTimeline(
160 161 162 163 164 165 166 167
                                   $this->notices,
                                   $atom->title,
                                   $link,
                                   $atom->subtitle,
                                   $suplink,
                                   $atom->logo,
                                   $self
                                   );
168 169
            break;
        case 'atom':
170 171
            header('Content-Type: application/atom+xml; charset=utf-8');

172 173
            $atom->setId($self);
            $atom->setSelfLink($self);
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

            // Add navigation links: next, prev, first
            // Note: we use IDs rather than pages for navigation; page boundaries
            // change too quickly!

            if (!empty($this->next_id)) {
                $atom->addLink($nextUrl,
                               array('rel' => 'next',
                                     'type' => 'application/atom+xml'));
            }

            if (($this->page > 1 || !empty($this->max_id)) && !empty($this->notices)) {
                $atom->addLink($prevUrl,
                               array('rel' => 'prev',
                                     'type' => 'application/atom+xml'));
            }

            if ($this->page > 1 || !empty($this->since_id) || !empty($this->max_id)) {
                $atom->addLink($firstUrl,
                               array('rel' => 'first',
                                     'type' => 'application/atom+xml'));

            }

198
            $atom->addEntryFromNotices($this->notices);
199
            $this->raw($atom->getString());
200

201 202
            break;
        case 'json':
203
            $this->showJsonTimeline($this->notices);
204
            break;
205
        case 'as':
206
            header('Content-Type: ' . ActivityStreamJSONDocument::CONTENT_TYPE);
207
            $doc = new ActivityStreamJSONDocument($this->scoped);
208 209 210 211
            $doc->setTitle($atom->title);
            $doc->addLink($link, 'alternate', 'text/html');
            $doc->addItemsFromNotices($this->notices);

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
            if (!empty($this->next_id)) {
                $doc->addLink($nextUrl,
                               array('rel' => 'next',
                                     'type' => ActivityStreamJSONDocument::CONTENT_TYPE));
            }

            if (($this->page > 1 || !empty($this->max_id)) && !empty($this->notices)) {
                $doc->addLink($prevUrl,
                               array('rel' => 'prev',
                                     'type' => ActivityStreamJSONDocument::CONTENT_TYPE));
            }

            if ($this->page > 1 || !empty($this->since_id) || !empty($this->max_id)) {
                $doc->addLink($firstUrl,
                               array('rel' => 'first',
                                     'type' => ActivityStreamJSONDocument::CONTENT_TYPE));
            }
229 230 231

            $this->raw($doc->asString());
            break;
232
        default:
233
            // TRANS: Client error displayed when coming across a non-supported API method.
234
            $this->clientError(_('API method not found.'), 404);
235 236 237 238 239 240 241 242 243 244 245 246
        }
    }

    /**
     * Get notices
     *
     * @return array notices
     */
    function getNotices()
    {
        $notices = array();

247
        $notice = $this->target->getNotices(($this->page-1) * $this->count,
248 249
                                          $this->count + 1,
                                          $this->since_id,
250 251
                                          $this->max_id,
                                          $this->scoped);
252 253

        while ($notice->fetch()) {
254 255 256 257 258 259
            if (count($notices) < $this->count) {
                $notices[] = clone($notice);
            } else {
                $this->next_id = $notice->id;
                break;
            }
260 261 262 263 264 265
        }

        return $notices;
    }

    /**
266
     * We expose AtomPub here, so non-GET/HEAD reqs must be read/write.
267 268 269 270 271
     *
     * @param array $args other arguments
     *
     * @return boolean true
     */
272

273 274
    function isReadOnly($args)
    {
275
        return ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD');
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    }

    /**
     * When was this feed last modified?
     *
     * @return string datestamp of the latest notice in the stream
     */
    function lastModified()
    {
        if (!empty($this->notices) && (count($this->notices) > 0)) {
            return strtotime($this->notices[0]->created);
        }

        return null;
    }

    /**
     * An entity tag for this stream
     *
     * Returns an Etag based on the action name, language, user ID, and
     * timestamps of the first and last notice in the timeline
     *
     * @return string etag
     */
    function etag()
    {
        if (!empty($this->notices) && (count($this->notices) > 0)) {
            $last = count($this->notices) - 1;

305
            return '"' . implode(
306 307
                                 ':',
                                 array($this->arg('action'),
308
                                       common_user_cache_hash($this->scoped),
309
                                       common_language(),
310
                                       $this->target->getID(),
311 312 313 314
                                       strtotime($this->notices[0]->created),
                                       strtotime($this->notices[$last]->created))
                                 )
              . '"';
315 316 317 318 319
        }

        return null;
    }

320 321
    function handlePost()
    {
322 323
        if (!$this->scoped instanceof Profile ||
                !$this->target->sameAs($this->scoped)) {
324
            // TRANS: Client error displayed trying to add a notice to another user's timeline.
325
            $this->clientError(_('Only the user can add to their own timeline.'), 403);
326 327
        }

328
        // Only handle posts for Atom
329
        if ($this->format != 'atom') {
330 331
            // TRANS: Client error displayed when using another format than AtomPub.
            $this->clientError(_('Only accept AtomPub for Atom feeds.'));
332 333
        }

334 335
        $xml = trim(file_get_contents('php://input'));
        if (empty($xml)) {
336
            // TRANS: Client error displayed attempting to post an empty API notice.
337 338
            $this->clientError(_('Atom post must not be empty.'));
        }
339

340 341 342 343 344
        $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
        $dom = new DOMDocument();
        $ok = $dom->loadXML($xml);
        error_reporting($old);
        if (!$ok) {
345
            // TRANS: Client error displayed attempting to post an API that is not well-formed XML.
346 347
            $this->clientError(_('Atom post must be well-formed XML.'));
        }
348 349 350

        if ($dom->documentElement->namespaceURI != Activity::ATOM ||
            $dom->documentElement->localName != 'entry') {
351
            // TRANS: Client error displayed when not using an Atom entry.
352 353 354 355 356
            $this->clientError(_('Atom post must be an Atom entry.'));
        }

        $activity = new Activity($dom->documentElement);

357
        common_debug('AtomPub: Ignoring right now, but this POST was made to collection: '.$activity->id);
358

359 360 361 362 363 364
        // Reset activity data so we can handle it in the same functions as with OStatus
        // because we don't let clients set their own UUIDs... Not sure what AtomPub thinks
        // about that though.
        $activity->id = null;
        $activity->actor = null;    // not used anyway, we use $this->target
        $activity->objects[0]->id = null;
365

366 367 368 369
        $stored = null;
        if (Event::handle('StartAtomPubNewActivity', array($activity, $this->target, &$stored))) {
            // TRANS: Client error displayed when not using the POST verb. Do not translate POST.
            throw new ClientException(_('Could not handle this Atom Activity.'));
370
        }
371 372
        if (!$stored instanceof Notice) {
            throw new ServerException('Server did not create a Notice object from handled AtomPub activity.');
373
        }
374
        Event::handle('EndAtomPubNewActivity', array($activity, $this->target, $stored));
375

376 377 378 379
        header('HTTP/1.1 201 Created');
        header("Location: " . common_local_url('ApiStatusesShow', array('id' => $stored->getID(),
                                                                        'format' => 'atom')));
        $this->showSingleAtomStatus($stored);
380
    }
381
}