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')) {
42 * Returns the most recent notices (default 20) posted by the authenticating
43 * user. Another user's timeline can be requested via the id parameter. This
44 * is the API equivalent of the user profile web page.
48 * @author Craig Andrews <candrews@integralblue.com>
49 * @author Evan Prodromou <evan@status.net>
50 * @author Jeffery To <jeffery.to@gmail.com>
51 * @author mac65 <mac65@mac65.com>
52 * @author Mike Cochrane <mikec@mikenz.geek.nz>
53 * @author Robin Millette <robin@millette.info>
54 * @author Zach Copley <zach@status.net>
55 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
56 * @link http://status.net/
58 class ApiTimelineUserAction extends ApiBareAuthAction
63 * Take arguments for running
65 * @param array $args $_REQUEST args
67 * @return boolean success flag
69 function prepare($args)
71 parent::prepare($args);
73 $this->user = $this->getTargetUser($this->arg('id'));
75 if (empty($this->user)) {
76 // TRANS: Client error displayed requesting most recent notices for a non-existing user.
77 $this->clientError(_('No such user.'), 404, $this->format);
81 $this->notices = $this->getNotices();
89 * Just show the notices
91 * @param array $args $_REQUEST data (unused)
95 function handle($args)
97 parent::handle($args);
99 if ($this->isPost()) {
102 $this->showTimeline();
107 * Show the timeline of notices
111 function showTimeline()
113 $profile = $this->user->getProfile();
115 // We'll use the shared params from the Atom stub
116 // for other feed types.
117 $atom = new AtomUserNoticeFeed($this->user, $this->auth_user);
119 $link = common_local_url(
121 array('nickname' => $this->user->nickname)
124 $self = $this->getSelfUri();
126 // FriendFeed's SUP protocol
127 // Also added RSS and Atom feeds
129 $suplink = common_local_url('sup', null, null, $this->user->id);
130 header('X-SUP-ID: ' . $suplink);
132 switch($this->format) {
134 $this->showXmlTimeline($this->notices);
137 $this->showRssTimeline(
148 header('Content-Type: application/atom+xml; charset=utf-8');
151 $atom->setSelfLink($self);
153 // Add navigation links: next, prev, first
154 // Note: we use IDs rather than pages for navigation; page boundaries
155 // change too quickly!
157 if (!empty($this->next_id)) {
158 $nextUrl = common_local_url('ApiTimelineUser',
159 array('format' => 'atom',
160 'id' => $this->user->id),
161 array('max_id' => $this->next_id));
163 $atom->addLink($nextUrl,
164 array('rel' => 'next',
165 'type' => 'application/atom+xml'));
168 if (($this->page > 1 || !empty($this->max_id)) && !empty($this->notices)) {
170 $lastNotice = $this->notices[0];
171 $lastId = $lastNotice->id;
173 $prevUrl = common_local_url('ApiTimelineUser',
174 array('format' => 'atom',
175 'id' => $this->user->id),
176 array('since_id' => $lastId));
178 $atom->addLink($prevUrl,
179 array('rel' => 'prev',
180 'type' => 'application/atom+xml'));
183 if ($this->page > 1 || !empty($this->since_id) || !empty($this->max_id)) {
185 $firstUrl = common_local_url('ApiTimelineUser',
186 array('format' => 'atom',
187 'id' => $this->user->id));
189 $atom->addLink($firstUrl,
190 array('rel' => 'first',
191 'type' => 'application/atom+xml'));
195 $atom->addEntryFromNotices($this->notices);
196 $this->raw($atom->getString());
200 $this->showJsonTimeline($this->notices);
203 header('Content-Type: ' . ActivityStreamJSONDocument::CONTENT_TYPE);
204 $doc = new ActivityStreamJSONDocument($this->auth_user);
205 $doc->setTitle($atom->title);
206 $doc->addLink($link, 'alternate', 'text/html');
207 $doc->addItemsFromNotices($this->notices);
209 // XXX: Add paging extension?
211 $this->raw($doc->asString());
214 // TRANS: Client error displayed when coming across a non-supported API method.
215 $this->clientError(_('API method not found.'), $code = 404);
223 * @return array notices
225 function getNotices()
229 $notice = $this->user->getNotices(($this->page-1) * $this->count,
234 while ($notice->fetch()) {
235 if (count($notices) < $this->count) {
236 $notices[] = clone($notice);
238 $this->next_id = $notice->id;
247 * We expose AtomPub here, so non-GET/HEAD reqs must be read/write.
249 * @param array $args other arguments
251 * @return boolean true
254 function isReadOnly($args)
256 return ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD');
260 * When was this feed last modified?
262 * @return string datestamp of the latest notice in the stream
264 function lastModified()
266 if (!empty($this->notices) && (count($this->notices) > 0)) {
267 return strtotime($this->notices[0]->created);
274 * An entity tag for this stream
276 * Returns an Etag based on the action name, language, user ID, and
277 * timestamps of the first and last notice in the timeline
279 * @return string etag
283 if (!empty($this->notices) && (count($this->notices) > 0)) {
284 $last = count($this->notices) - 1;
286 return '"' . implode(
288 array($this->arg('action'),
289 common_user_cache_hash($this->auth_user),
292 strtotime($this->notices[0]->created),
293 strtotime($this->notices[$last]->created))
301 function handlePost()
303 if (empty($this->auth_user) ||
304 $this->auth_user->id != $this->user->id) {
305 // TRANS: Client error displayed trying to add a notice to another user's timeline.
306 $this->clientError(_('Only the user can add to their own timeline.'));
310 // Only handle posts for Atom
311 if ($this->format != 'atom') {
312 // TRANS: Client error displayed when using another format than AtomPub.
313 $this->clientError(_('Only accept AtomPub for Atom feeds.'));
317 $xml = trim(file_get_contents('php://input'));
319 // TRANS: Client error displayed attempting to post an empty API notice.
320 $this->clientError(_('Atom post must not be empty.'));
323 $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
324 $dom = new DOMDocument();
325 $ok = $dom->loadXML($xml);
326 error_reporting($old);
328 // TRANS: Client error displayed attempting to post an API that is not well-formed XML.
329 $this->clientError(_('Atom post must be well-formed XML.'));
332 if ($dom->documentElement->namespaceURI != Activity::ATOM ||
333 $dom->documentElement->localName != 'entry') {
334 // TRANS: Client error displayed when not using an Atom entry.
335 $this->clientError(_('Atom post must be an Atom entry.'));
339 $activity = new Activity($dom->documentElement);
343 if (Event::handle('StartAtomPubNewActivity', array(&$activity, $this->user, &$saved))) {
344 if ($activity->verb != ActivityVerb::POST) {
345 // TRANS: Client error displayed when not using the POST verb. Do not translate POST.
346 $this->clientError(_('Can only handle POST activities.'));
350 $note = $activity->objects[0];
352 if (!in_array($note->type, array(ActivityObject::NOTE,
353 ActivityObject::BLOGENTRY,
354 ActivityObject::STATUS))) {
355 // TRANS: Client error displayed when using an unsupported activity object type.
356 // TRANS: %s is the unsupported activity object type.
357 $this->clientError(sprintf(_('Cannot handle activity object type "%s".'),
362 $saved = $this->postNote($activity);
364 Event::handle('EndAtomPubNewActivity', array($activity, $this->user, $saved));
367 if (!empty($saved)) {
368 header('HTTP/1.1 201 Created');
369 header("Location: " . common_local_url('ApiStatusesShow', array('id' => $saved->id,
370 'format' => 'atom')));
371 $this->showSingleAtomStatus($saved);
375 function postNote($activity)
377 $note = $activity->objects[0];
379 // Use summary as fallback for content
381 if (!empty($note->content)) {
382 $sourceContent = $note->content;
383 } else if (!empty($note->summary)) {
384 $sourceContent = $note->summary;
385 } else if (!empty($note->title)) {
386 $sourceContent = $note->title;
388 // @fixme fetch from $sourceUrl?
389 // TRANS: Client error displayed when posting a notice without content through the API.
390 // TRANS: %d is the notice ID (number).
391 $this->clientError(sprintf(_('No content for notice %d.'),
396 // Get (safe!) HTML and text versions of the content
398 $rendered = $this->purify($sourceContent);
399 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
401 $shortened = $this->auth_user->shortenLinks($content);
403 $options = array('is_local' => Notice::LOCAL_PUBLIC,
404 'rendered' => $rendered,
405 'replies' => array(),
410 // accept remote URI (not necessarily a good idea)
412 common_debug("Note ID is {$note->id}");
414 if (!empty($note->id)) {
415 $notice = Notice::getKV('uri', trim($note->id));
417 if (!empty($notice)) {
418 // TRANS: Client error displayed when using another format than AtomPub.
419 // TRANS: %s is the notice URI.
420 $this->clientError(sprintf(_('Notice with URI "%s" already exists.'),
424 common_log(LOG_NOTICE, "Saving client-supplied notice URI '$note->id'");
425 $options['uri'] = $note->id;
428 // accept remote create time (also maybe not such a good idea)
430 if (!empty($activity->time)) {
431 common_log(LOG_NOTICE, "Saving client-supplied create time {$activity->time}");
432 $options['created'] = common_sql_date($activity->time);
435 // Check for optional attributes...
437 if (!empty($activity->context)) {
439 foreach ($activity->context->attention as $uri) {
441 $profile = Profile::fromURI($uri);
443 if (!empty($profile)) {
444 $options['replies'][] = $uri;
446 $group = User_group::getKV('uri', $uri);
447 if (!empty($group)) {
448 $options['groups'][] = $group->id;
450 // @fixme: hook for discovery here
451 common_log(LOG_WARNING, sprintf('AtomPub post with unknown attention URI %s', $uri));
456 // Maintain direct reply associations
457 // @fixme what about conversation ID?
459 if (!empty($activity->context->replyToID)) {
460 $orig = Notice::getKV('uri',
461 $activity->context->replyToID);
463 $options['reply_to'] = $orig->id;
467 $location = $activity->context->location;
470 $options['lat'] = $location->lat;
471 $options['lon'] = $location->lon;
472 if ($location->location_id) {
473 $options['location_ns'] = $location->location_ns;
474 $options['location_id'] = $location->location_id;
479 // Atom categories <-> hashtags
481 foreach ($activity->categories as $cat) {
483 $term = common_canonical_tag($cat->term);
485 $options['tags'][] = $term;
490 // Atom enclosures -> attachment URLs
491 foreach ($activity->enclosures as $href) {
492 // @fixme save these locally or....?
493 $options['urls'][] = $href;
496 $saved = Notice::saveNew($this->user->id,
498 'atompub', // TODO: deal with this
504 function purify($content)
506 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
508 $config = array('safe' => 1,
509 'deny_attribute' => 'id,style,on*');
510 return htmLawed($content, $config);