3 * StatusNet, the distributed open-source microblogging tool
5 * Show a user's timeline
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@status.net>
26 * @author Jeffery To <jeffery.to@gmail.com>
27 * @author mac65 <mac65@mac65.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <robin@millette.info>
30 * @author Zach Copley <zach@status.net>
31 * @copyright 2009 StatusNet, Inc.
32 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
34 * @link http://status.net/
37 if (!defined('STATUSNET')) {
41 require_once INSTALLDIR . '/lib/apibareauth.php';
44 * Returns the most recent notices (default 20) posted by the authenticating
45 * user. Another user's timeline can be requested via the id parameter. This
46 * is the API equivalent of the user profile web page.
50 * @author Craig Andrews <candrews@integralblue.com>
51 * @author Evan Prodromou <evan@status.net>
52 * @author Jeffery To <jeffery.to@gmail.com>
53 * @author mac65 <mac65@mac65.com>
54 * @author Mike Cochrane <mikec@mikenz.geek.nz>
55 * @author Robin Millette <robin@millette.info>
56 * @author Zach Copley <zach@status.net>
57 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
58 * @link http://status.net/
60 class ApiTimelineUserAction extends ApiBareAuthAction
65 * Take arguments for running
67 * @param array $args $_REQUEST args
69 * @return boolean success flag
71 function prepare($args)
73 parent::prepare($args);
75 $this->user = $this->getTargetUser($this->arg('id'));
77 if (empty($this->user)) {
78 // TRANS: Client error displayed requesting most recent notices for a non-existing user.
79 $this->clientError(_('No such user.'), 404, $this->format);
83 $this->notices = $this->getNotices();
91 * Just show the notices
93 * @param array $args $_REQUEST data (unused)
97 function handle($args)
99 parent::handle($args);
101 if ($this->isPost()) {
104 $this->showTimeline();
109 * Show the timeline of notices
113 function showTimeline()
115 $profile = $this->user->getProfile();
117 // We'll use the shared params from the Atom stub
118 // for other feed types.
119 $atom = new AtomUserNoticeFeed($this->user, $this->auth_user);
121 $link = common_local_url(
123 array('nickname' => $this->user->nickname)
126 $self = $this->getSelfUri();
128 // FriendFeed's SUP protocol
129 // Also added RSS and Atom feeds
131 $suplink = common_local_url('sup', null, null, $this->user->id);
132 header('X-SUP-ID: ' . $suplink);
134 switch($this->format) {
136 $this->showXmlTimeline($this->notices);
139 $this->showRssTimeline(
150 header('Content-Type: application/atom+xml; charset=utf-8');
153 $atom->setSelfLink($self);
155 // Add navigation links: next, prev, first
156 // Note: we use IDs rather than pages for navigation; page boundaries
157 // change too quickly!
159 if (!empty($this->next_id)) {
160 $nextUrl = common_local_url('ApiTimelineUser',
161 array('format' => 'atom',
162 'id' => $this->user->id),
163 array('max_id' => $this->next_id));
165 $atom->addLink($nextUrl,
166 array('rel' => 'next',
167 'type' => 'application/atom+xml'));
170 if (($this->page > 1 || !empty($this->max_id)) && !empty($this->notices)) {
172 $lastNotice = $this->notices[0];
173 $lastId = $lastNotice->id;
175 $prevUrl = common_local_url('ApiTimelineUser',
176 array('format' => 'atom',
177 'id' => $this->user->id),
178 array('since_id' => $lastId));
180 $atom->addLink($prevUrl,
181 array('rel' => 'prev',
182 'type' => 'application/atom+xml'));
185 if ($this->page > 1 || !empty($this->since_id) || !empty($this->max_id)) {
187 $firstUrl = common_local_url('ApiTimelineUser',
188 array('format' => 'atom',
189 'id' => $this->user->id));
191 $atom->addLink($firstUrl,
192 array('rel' => 'first',
193 'type' => 'application/atom+xml'));
197 $atom->addEntryFromNotices($this->notices);
198 $this->raw($atom->getString());
202 $this->showJsonTimeline($this->notices);
205 header('Content-Type: application/json; charset=utf-8');
206 $doc = new ActivityStreamJSONDocument($this->auth_user);
207 $doc->setTitle($atom->title);
208 $doc->addLink($link, 'alternate', 'text/html');
209 $doc->addItemsFromNotices($this->notices);
211 // XXX: Add paging extension?
213 $this->raw($doc->asString());
216 // TRANS: Client error displayed when trying to handle an unknown API method.
217 $this->clientError(_('API method not found.'), $code = 404);
225 * @return array notices
227 function getNotices()
231 $notice = $this->user->getNotices(($this->page-1) * $this->count,
236 while ($notice->fetch()) {
237 if (count($notices) < $this->count) {
238 $notices[] = clone($notice);
240 $this->next_id = $notice->id;
249 * We expose AtomPub here, so non-GET/HEAD reqs must be read/write.
251 * @param array $args other arguments
253 * @return boolean true
256 function isReadOnly($args)
258 return ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD');
262 * When was this feed last modified?
264 * @return string datestamp of the latest notice in the stream
266 function lastModified()
268 if (!empty($this->notices) && (count($this->notices) > 0)) {
269 return strtotime($this->notices[0]->created);
276 * An entity tag for this stream
278 * Returns an Etag based on the action name, language, user ID, and
279 * timestamps of the first and last notice in the timeline
281 * @return string etag
285 if (!empty($this->notices) && (count($this->notices) > 0)) {
286 $last = count($this->notices) - 1;
288 return '"' . implode(
290 array($this->arg('action'),
291 common_user_cache_hash($this->auth_user),
294 strtotime($this->notices[0]->created),
295 strtotime($this->notices[$last]->created))
303 function handlePost()
305 if (empty($this->auth_user) ||
306 $this->auth_user->id != $this->user->id) {
307 // TRANS: Client error displayed trying to add a notice to another user's timeline.
308 $this->clientError(_('Only the user can add to their own timeline.'));
312 // Only handle posts for Atom
313 if ($this->format != 'atom') {
314 // TRANS: Client error displayed when using another format than AtomPub.
315 $this->clientError(_('Only accept AtomPub for Atom feeds.'));
319 $xml = trim(file_get_contents('php://input'));
321 // TRANS: Client error displayed attempting to post an empty API notice.
322 $this->clientError(_('Atom post must not be empty.'));
325 $dom = DOMDocument::loadXML($xml);
327 // TRANS: Client error displayed attempting to post an API that is not well-formed XML.
328 $this->clientError(_('Atom post must be well-formed XML.'));
331 if ($dom->documentElement->namespaceURI != Activity::ATOM ||
332 $dom->documentElement->localName != 'entry') {
333 // TRANS: Client error displayed when not using an Atom entry.
334 $this->clientError(_('Atom post must be an Atom entry.'));
338 $activity = new Activity($dom->documentElement);
342 if (Event::handle('StartAtomPubNewActivity', array(&$activity, $this->user, &$saved))) {
343 if ($activity->verb != ActivityVerb::POST) {
344 // TRANS: Client error displayed when not using the POST verb. Do not translate POST.
345 $this->clientError(_('Can only handle POST activities.'));
349 $note = $activity->objects[0];
351 if (!in_array($note->type, array(ActivityObject::NOTE,
352 ActivityObject::BLOGENTRY,
353 ActivityObject::STATUS))) {
354 // TRANS: Client error displayed when using an unsupported activity object type.
355 // TRANS: %s is the unsupported activity object type.
356 $this->clientError(sprintf(_('Cannot handle activity object type "%s".'),
361 $saved = $this->postNote($activity);
363 Event::handle('EndAtomPubNewActivity', array($activity, $this->user, $saved));
366 if (!empty($saved)) {
367 header('HTTP/1.1 201 Created');
368 header("Location: " . common_local_url('ApiStatusesShow', array('id' => $saved->id,
369 'format' => 'atom')));
370 $this->showSingleAtomStatus($saved);
374 function postNote($activity)
376 $note = $activity->objects[0];
378 // Use summary as fallback for content
380 if (!empty($note->content)) {
381 $sourceContent = $note->content;
382 } else if (!empty($note->summary)) {
383 $sourceContent = $note->summary;
384 } else if (!empty($note->title)) {
385 $sourceContent = $note->title;
387 // @fixme fetch from $sourceUrl?
388 // TRANS: Client error displayed when posting a notice without content through the API.
389 // TRANS: %d is the notice ID (number).
390 $this->clientError(sprintf(_('No content for notice %d.'),
395 // Get (safe!) HTML and text versions of the content
397 $rendered = $this->purify($sourceContent);
398 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
400 $shortened = $this->auth_user->shortenLinks($content);
402 $options = array('is_local' => Notice::LOCAL_PUBLIC,
403 'rendered' => $rendered,
404 'replies' => array(),
409 // accept remote URI (not necessarily a good idea)
411 common_debug("Note ID is {$note->id}");
413 if (!empty($note->id)) {
414 $notice = Notice::staticGet('uri', trim($note->id));
416 if (!empty($notice)) {
417 // TRANS: Client error displayed when using another format than AtomPub.
418 // TRANS: %s is the notice URI.
419 $this->clientError(sprintf(_('Notice with URI "%s" already exists.'),
423 common_log(LOG_NOTICE, "Saving client-supplied notice URI '$note->id'");
424 $options['uri'] = $note->id;
427 // accept remote create time (also maybe not such a good idea)
429 if (!empty($activity->time)) {
430 common_log(LOG_NOTICE, "Saving client-supplied create time {$activity->time}");
431 $options['created'] = common_sql_date($activity->time);
434 // Check for optional attributes...
436 if (!empty($activity->context)) {
438 foreach ($activity->context->attention as $uri) {
440 $profile = Profile::fromURI($uri);
442 if (!empty($profile)) {
443 $options['replies'][] = $uri;
445 $group = User_group::staticGet('uri', $uri);
446 if (!empty($group)) {
447 $options['groups'][] = $uri;
449 // @fixme: hook for discovery here
450 common_log(LOG_WARNING, sprintf('AtomPub post with unknown attention URI %s', $uri));
455 // Maintain direct reply associations
456 // @fixme what about conversation ID?
458 if (!empty($activity->context->replyToID)) {
459 $orig = Notice::staticGet('uri',
460 $activity->context->replyToID);
462 $options['reply_to'] = $orig->id;
466 $location = $activity->context->location;
469 $options['lat'] = $location->lat;
470 $options['lon'] = $location->lon;
471 if ($location->location_id) {
472 $options['location_ns'] = $location->location_ns;
473 $options['location_id'] = $location->location_id;
478 // Atom categories <-> hashtags
480 foreach ($activity->categories as $cat) {
482 $term = common_canonical_tag($cat->term);
484 $options['tags'][] = $term;
489 // Atom enclosures -> attachment URLs
490 foreach ($activity->enclosures as $href) {
491 // @fixme save these locally or....?
492 $options['urls'][] = $href;
495 $saved = Notice::saveNew($this->user->id,
497 'atompub', // TODO: deal with this
503 function purify($content)
505 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
507 $config = array('safe' => 1,
508 'deny_attribute' => 'id,style,on*');
509 return htmLawed($content, $config);