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 protected function prepare(array $args=array())
71 parent::prepare($args);
73 $this->target = $this->getTargetProfile($this->arg('id'));
75 if (!($this->target instanceof Profile)) {
76 // TRANS: Client error displayed requesting most recent notices for a non-existing user.
77 $this->clientError(_('No such user.'), 404);
80 $this->notices = $this->getNotices();
88 * Just show the notices
92 protected function handle()
96 if ($this->isPost()) {
99 $this->showTimeline();
104 * Show the timeline of notices
108 function showTimeline()
110 // We'll use the shared params from the Atom stub
111 // for other feed types.
112 $atom = new AtomUserNoticeFeed($this->target->getUser(), $this->auth_user);
114 $link = common_local_url(
116 array('nickname' => $this->target->nickname)
119 $self = $this->getSelfUri();
121 // FriendFeed's SUP protocol
122 // Also added RSS and Atom feeds
124 $suplink = common_local_url('sup', null, null, $this->target->id);
125 header('X-SUP-ID: ' . $suplink);
127 switch($this->format) {
129 $this->showXmlTimeline($this->notices);
132 $this->showRssTimeline(
143 header('Content-Type: application/atom+xml; charset=utf-8');
146 $atom->setSelfLink($self);
148 // Add navigation links: next, prev, first
149 // Note: we use IDs rather than pages for navigation; page boundaries
150 // change too quickly!
152 if (!empty($this->next_id)) {
153 $nextUrl = common_local_url('ApiTimelineUser',
154 array('format' => 'atom',
155 'id' => $this->target->id),
156 array('max_id' => $this->next_id));
158 $atom->addLink($nextUrl,
159 array('rel' => 'next',
160 'type' => 'application/atom+xml'));
163 if (($this->page > 1 || !empty($this->max_id)) && !empty($this->notices)) {
165 $lastNotice = $this->notices[0];
166 $lastId = $lastNotice->id;
168 $prevUrl = common_local_url('ApiTimelineUser',
169 array('format' => 'atom',
170 'id' => $this->target->id),
171 array('since_id' => $lastId));
173 $atom->addLink($prevUrl,
174 array('rel' => 'prev',
175 'type' => 'application/atom+xml'));
178 if ($this->page > 1 || !empty($this->since_id) || !empty($this->max_id)) {
180 $firstUrl = common_local_url('ApiTimelineUser',
181 array('format' => 'atom',
182 'id' => $this->target->id));
184 $atom->addLink($firstUrl,
185 array('rel' => 'first',
186 'type' => 'application/atom+xml'));
190 $atom->addEntryFromNotices($this->notices);
191 $this->raw($atom->getString());
195 $this->showJsonTimeline($this->notices);
198 header('Content-Type: ' . ActivityStreamJSONDocument::CONTENT_TYPE);
199 $doc = new ActivityStreamJSONDocument($this->auth_user);
200 $doc->setTitle($atom->title);
201 $doc->addLink($link, 'alternate', 'text/html');
202 $doc->addItemsFromNotices($this->notices);
204 // XXX: Add paging extension?
206 $this->raw($doc->asString());
209 // TRANS: Client error displayed when coming across a non-supported API method.
210 $this->clientError(_('API method not found.'), $code = 404);
217 * @return array notices
219 function getNotices()
223 $notice = $this->target->getNotices(($this->page-1) * $this->count,
229 while ($notice->fetch()) {
230 if (count($notices) < $this->count) {
231 $notices[] = clone($notice);
233 $this->next_id = $notice->id;
242 * We expose AtomPub here, so non-GET/HEAD reqs must be read/write.
244 * @param array $args other arguments
246 * @return boolean true
249 function isReadOnly($args)
251 return ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD');
255 * When was this feed last modified?
257 * @return string datestamp of the latest notice in the stream
259 function lastModified()
261 if (!empty($this->notices) && (count($this->notices) > 0)) {
262 return strtotime($this->notices[0]->created);
269 * An entity tag for this stream
271 * Returns an Etag based on the action name, language, user ID, and
272 * timestamps of the first and last notice in the timeline
274 * @return string etag
278 if (!empty($this->notices) && (count($this->notices) > 0)) {
279 $last = count($this->notices) - 1;
281 return '"' . implode(
283 array($this->arg('action'),
284 common_user_cache_hash($this->auth_user),
287 strtotime($this->notices[0]->created),
288 strtotime($this->notices[$last]->created))
296 function handlePost()
298 if (empty($this->auth_user) ||
299 $this->auth_user->id != $this->target->id) {
300 // TRANS: Client error displayed trying to add a notice to another user's timeline.
301 $this->clientError(_('Only the user can add to their own timeline.'));
304 // Only handle posts for Atom
305 if ($this->format != 'atom') {
306 // TRANS: Client error displayed when using another format than AtomPub.
307 $this->clientError(_('Only accept AtomPub for Atom feeds.'));
310 $xml = trim(file_get_contents('php://input'));
312 // TRANS: Client error displayed attempting to post an empty API notice.
313 $this->clientError(_('Atom post must not be empty.'));
316 $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
317 $dom = new DOMDocument();
318 $ok = $dom->loadXML($xml);
319 error_reporting($old);
321 // TRANS: Client error displayed attempting to post an API that is not well-formed XML.
322 $this->clientError(_('Atom post must be well-formed XML.'));
325 if ($dom->documentElement->namespaceURI != Activity::ATOM ||
326 $dom->documentElement->localName != 'entry') {
327 // TRANS: Client error displayed when not using an Atom entry.
328 $this->clientError(_('Atom post must be an Atom entry.'));
331 $activity = new Activity($dom->documentElement);
335 if (Event::handle('StartAtomPubNewActivity', array(&$activity, $this->target->getUser(), &$saved))) {
336 if ($activity->verb != ActivityVerb::POST) {
337 // TRANS: Client error displayed when not using the POST verb. Do not translate POST.
338 $this->clientError(_('Can only handle POST activities.'));
341 $note = $activity->objects[0];
343 if (!in_array($note->type, array(ActivityObject::NOTE,
344 ActivityObject::BLOGENTRY,
345 ActivityObject::STATUS))) {
346 // TRANS: Client error displayed when using an unsupported activity object type.
347 // TRANS: %s is the unsupported activity object type.
348 $this->clientError(sprintf(_('Cannot handle activity object type "%s".'),
352 $saved = $this->postNote($activity);
354 Event::handle('EndAtomPubNewActivity', array($activity, $this->target->getUser(), $saved));
357 if (!empty($saved)) {
358 header('HTTP/1.1 201 Created');
359 header("Location: " . common_local_url('ApiStatusesShow', array('id' => $saved->id,
360 'format' => 'atom')));
361 $this->showSingleAtomStatus($saved);
365 function postNote($activity)
367 $note = $activity->objects[0];
369 // Use summary as fallback for content
371 if (!empty($note->content)) {
372 $sourceContent = $note->content;
373 } else if (!empty($note->summary)) {
374 $sourceContent = $note->summary;
375 } else if (!empty($note->title)) {
376 $sourceContent = $note->title;
378 // @fixme fetch from $sourceUrl?
379 // TRANS: Client error displayed when posting a notice without content through the API.
380 // TRANS: %d is the notice ID (number).
381 $this->clientError(sprintf(_('No content for notice %d.'), $note->id));
384 // Get (safe!) HTML and text versions of the content
386 $rendered = $this->purify($sourceContent);
387 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
389 $shortened = $this->auth_user->shortenLinks($content);
391 $options = array('is_local' => Notice::LOCAL_PUBLIC,
392 'rendered' => $rendered,
393 'replies' => array(),
398 // accept remote URI (not necessarily a good idea)
400 common_debug("Note ID is {$note->id}");
402 if (!empty($note->id)) {
403 $notice = Notice::getKV('uri', trim($note->id));
405 if (!empty($notice)) {
406 // TRANS: Client error displayed when using another format than AtomPub.
407 // TRANS: %s is the notice URI.
408 $this->clientError(sprintf(_('Notice with URI "%s" already exists.'), $note->id));
410 common_log(LOG_NOTICE, "Saving client-supplied notice URI '$note->id'");
411 $options['uri'] = $note->id;
414 // accept remote create time (also maybe not such a good idea)
416 if (!empty($activity->time)) {
417 common_log(LOG_NOTICE, "Saving client-supplied create time {$activity->time}");
418 $options['created'] = common_sql_date($activity->time);
421 // Check for optional attributes...
423 if ($activity->context instanceof ActivityContext) {
425 foreach ($activity->context->attention as $uri=>$type) {
427 $profile = Profile::fromUri($uri);
428 if ($profile->isGroup()) {
429 $options['groups'][] = $profile->id;
431 $options['replies'][] = $uri;
433 } catch (UnknownUriException $e) {
434 common_log(LOG_WARNING, sprintf('AtomPub post with unknown attention URI %s', $uri));
438 // Maintain direct reply associations
439 // @fixme what about conversation ID?
441 if (!empty($activity->context->replyToID)) {
442 $orig = Notice::getKV('uri',
443 $activity->context->replyToID);
445 $options['reply_to'] = $orig->id;
449 $location = $activity->context->location;
452 $options['lat'] = $location->lat;
453 $options['lon'] = $location->lon;
454 if ($location->location_id) {
455 $options['location_ns'] = $location->location_ns;
456 $options['location_id'] = $location->location_id;
461 // Atom categories <-> hashtags
463 foreach ($activity->categories as $cat) {
465 $term = common_canonical_tag($cat->term);
467 $options['tags'][] = $term;
472 // Atom enclosures -> attachment URLs
473 foreach ($activity->enclosures as $href) {
474 // @fixme save these locally or....?
475 $options['urls'][] = $href;
478 $saved = Notice::saveNew($this->target->id,
480 'atompub', // TODO: deal with this
486 function purify($content)
488 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
490 $config = array('safe' => 1,
491 'deny_attribute' => 'id,style,on*');
492 return htmLawed($content, $config);