apitimelineuser.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * Show a user's timeline
  6. *
  7. * PHP version 5
  8. *
  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.
  13. *
  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.
  18. *
  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/>.
  21. *
  22. * @category API
  23. * @package StatusNet
  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/
  35. */
  36. if (!defined('STATUSNET')) {
  37. exit(1);
  38. }
  39. /**
  40. * Returns the most recent notices (default 20) posted by the authenticating
  41. * user. Another user's timeline can be requested via the id parameter. This
  42. * is the API equivalent of the user profile web page.
  43. *
  44. * @category API
  45. * @package StatusNet
  46. * @author Craig Andrews <candrews@integralblue.com>
  47. * @author Evan Prodromou <evan@status.net>
  48. * @author Jeffery To <jeffery.to@gmail.com>
  49. * @author mac65 <mac65@mac65.com>
  50. * @author Mike Cochrane <mikec@mikenz.geek.nz>
  51. * @author Robin Millette <robin@millette.info>
  52. * @author Zach Copley <zach@status.net>
  53. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  54. * @link http://status.net/
  55. */
  56. class ApiTimelineUserAction extends ApiBareAuthAction
  57. {
  58. var $notices = null;
  59. var $next_id = null;
  60. /**
  61. * Take arguments for running
  62. *
  63. * @param array $args $_REQUEST args
  64. *
  65. * @return boolean success flag
  66. */
  67. protected function prepare(array $args=array())
  68. {
  69. parent::prepare($args);
  70. $this->target = $this->getTargetProfile($this->arg('id'));
  71. if (!($this->target instanceof Profile)) {
  72. // TRANS: Client error displayed requesting most recent notices for a non-existing user.
  73. $this->clientError(_('No such user.'), 404);
  74. }
  75. if (!$this->target->isLocal()) {
  76. $this->serverError(_('Remote user timelines are not available here yet.'), 501);
  77. }
  78. $this->notices = $this->getNotices();
  79. return true;
  80. }
  81. /**
  82. * Handle the request
  83. *
  84. * Just show the notices
  85. *
  86. * @return void
  87. */
  88. protected function handle()
  89. {
  90. parent::handle();
  91. if ($this->isPost()) {
  92. $this->handlePost();
  93. } else {
  94. $this->showTimeline();
  95. }
  96. }
  97. /**
  98. * Show the timeline of notices
  99. *
  100. * @return void
  101. */
  102. function showTimeline()
  103. {
  104. // We'll use the shared params from the Atom stub
  105. // for other feed types.
  106. $atom = new AtomUserNoticeFeed($this->target->getUser(), $this->auth_user);
  107. $link = common_local_url(
  108. 'showstream',
  109. array('nickname' => $this->target->nickname)
  110. );
  111. $self = $this->getSelfUri();
  112. // FriendFeed's SUP protocol
  113. // Also added RSS and Atom feeds
  114. $suplink = common_local_url('sup', null, null, $this->target->id);
  115. header('X-SUP-ID: ' . $suplink);
  116. // paging links
  117. $nextUrl = !empty($this->next_id)
  118. ? common_local_url('ApiTimelineUser',
  119. array('format' => $this->format,
  120. 'id' => $this->target->id),
  121. array('max_id' => $this->next_id))
  122. : null;
  123. $prevExtra = array();
  124. if (!empty($this->notices)) {
  125. assert($this->notices[0] instanceof Notice);
  126. $prevExtra['since_id'] = $this->notices[0]->id;
  127. }
  128. $prevUrl = common_local_url('ApiTimelineUser',
  129. array('format' => $this->format,
  130. 'id' => $this->target->id),
  131. $prevExtra);
  132. $firstUrl = common_local_url('ApiTimelineUser',
  133. array('format' => $this->format,
  134. 'id' => $this->target->id));
  135. switch($this->format) {
  136. case 'xml':
  137. $this->showXmlTimeline($this->notices);
  138. break;
  139. case 'rss':
  140. $this->showRssTimeline(
  141. $this->notices,
  142. $atom->title,
  143. $link,
  144. $atom->subtitle,
  145. $suplink,
  146. $atom->logo,
  147. $self
  148. );
  149. break;
  150. case 'atom':
  151. header('Content-Type: application/atom+xml; charset=utf-8');
  152. $atom->setId($self);
  153. $atom->setSelfLink($self);
  154. // Add navigation links: next, prev, first
  155. // Note: we use IDs rather than pages for navigation; page boundaries
  156. // change too quickly!
  157. if (!empty($this->next_id)) {
  158. $atom->addLink($nextUrl,
  159. array('rel' => 'next',
  160. 'type' => 'application/atom+xml'));
  161. }
  162. if (($this->page > 1 || !empty($this->max_id)) && !empty($this->notices)) {
  163. $atom->addLink($prevUrl,
  164. array('rel' => 'prev',
  165. 'type' => 'application/atom+xml'));
  166. }
  167. if ($this->page > 1 || !empty($this->since_id) || !empty($this->max_id)) {
  168. $atom->addLink($firstUrl,
  169. array('rel' => 'first',
  170. 'type' => 'application/atom+xml'));
  171. }
  172. $atom->addEntryFromNotices($this->notices);
  173. $this->raw($atom->getString());
  174. break;
  175. case 'json':
  176. $this->showJsonTimeline($this->notices);
  177. break;
  178. case 'as':
  179. header('Content-Type: ' . ActivityStreamJSONDocument::CONTENT_TYPE);
  180. $doc = new ActivityStreamJSONDocument($this->auth_user);
  181. $doc->setTitle($atom->title);
  182. $doc->addLink($link, 'alternate', 'text/html');
  183. $doc->addItemsFromNotices($this->notices);
  184. if (!empty($this->next_id)) {
  185. $doc->addLink($nextUrl,
  186. array('rel' => 'next',
  187. 'type' => ActivityStreamJSONDocument::CONTENT_TYPE));
  188. }
  189. if (($this->page > 1 || !empty($this->max_id)) && !empty($this->notices)) {
  190. $doc->addLink($prevUrl,
  191. array('rel' => 'prev',
  192. 'type' => ActivityStreamJSONDocument::CONTENT_TYPE));
  193. }
  194. if ($this->page > 1 || !empty($this->since_id) || !empty($this->max_id)) {
  195. $doc->addLink($firstUrl,
  196. array('rel' => 'first',
  197. 'type' => ActivityStreamJSONDocument::CONTENT_TYPE));
  198. }
  199. $this->raw($doc->asString());
  200. break;
  201. default:
  202. // TRANS: Client error displayed when coming across a non-supported API method.
  203. $this->clientError(_('API method not found.'), 404);
  204. }
  205. }
  206. /**
  207. * Get notices
  208. *
  209. * @return array notices
  210. */
  211. function getNotices()
  212. {
  213. $notices = array();
  214. $notice = $this->target->getNotices(($this->page-1) * $this->count,
  215. $this->count + 1,
  216. $this->since_id,
  217. $this->max_id,
  218. $this->scoped);
  219. while ($notice->fetch()) {
  220. if (count($notices) < $this->count) {
  221. $notices[] = clone($notice);
  222. } else {
  223. $this->next_id = $notice->id;
  224. break;
  225. }
  226. }
  227. return $notices;
  228. }
  229. /**
  230. * We expose AtomPub here, so non-GET/HEAD reqs must be read/write.
  231. *
  232. * @param array $args other arguments
  233. *
  234. * @return boolean true
  235. */
  236. function isReadOnly($args)
  237. {
  238. return ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD');
  239. }
  240. /**
  241. * When was this feed last modified?
  242. *
  243. * @return string datestamp of the latest notice in the stream
  244. */
  245. function lastModified()
  246. {
  247. if (!empty($this->notices) && (count($this->notices) > 0)) {
  248. return strtotime($this->notices[0]->created);
  249. }
  250. return null;
  251. }
  252. /**
  253. * An entity tag for this stream
  254. *
  255. * Returns an Etag based on the action name, language, user ID, and
  256. * timestamps of the first and last notice in the timeline
  257. *
  258. * @return string etag
  259. */
  260. function etag()
  261. {
  262. if (!empty($this->notices) && (count($this->notices) > 0)) {
  263. $last = count($this->notices) - 1;
  264. return '"' . implode(
  265. ':',
  266. array($this->arg('action'),
  267. common_user_cache_hash($this->auth_user),
  268. common_language(),
  269. $this->target->id,
  270. strtotime($this->notices[0]->created),
  271. strtotime($this->notices[$last]->created))
  272. )
  273. . '"';
  274. }
  275. return null;
  276. }
  277. function handlePost()
  278. {
  279. if (empty($this->auth_user) ||
  280. $this->auth_user->id != $this->target->id) {
  281. // TRANS: Client error displayed trying to add a notice to another user's timeline.
  282. $this->clientError(_('Only the user can add to their own timeline.'));
  283. }
  284. // Only handle posts for Atom
  285. if ($this->format != 'atom') {
  286. // TRANS: Client error displayed when using another format than AtomPub.
  287. $this->clientError(_('Only accept AtomPub for Atom feeds.'));
  288. }
  289. $xml = trim(file_get_contents('php://input'));
  290. if (empty($xml)) {
  291. // TRANS: Client error displayed attempting to post an empty API notice.
  292. $this->clientError(_('Atom post must not be empty.'));
  293. }
  294. $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
  295. $dom = new DOMDocument();
  296. $ok = $dom->loadXML($xml);
  297. error_reporting($old);
  298. if (!$ok) {
  299. // TRANS: Client error displayed attempting to post an API that is not well-formed XML.
  300. $this->clientError(_('Atom post must be well-formed XML.'));
  301. }
  302. if ($dom->documentElement->namespaceURI != Activity::ATOM ||
  303. $dom->documentElement->localName != 'entry') {
  304. // TRANS: Client error displayed when not using an Atom entry.
  305. $this->clientError(_('Atom post must be an Atom entry.'));
  306. }
  307. $activity = new Activity($dom->documentElement);
  308. $saved = null;
  309. if (Event::handle('StartAtomPubNewActivity', array(&$activity, $this->target->getUser(), &$saved))) {
  310. if ($activity->verb != ActivityVerb::POST) {
  311. // TRANS: Client error displayed when not using the POST verb. Do not translate POST.
  312. $this->clientError(_('Can only handle POST activities.'));
  313. }
  314. $note = $activity->objects[0];
  315. if (!in_array($note->type, array(ActivityObject::NOTE,
  316. ActivityObject::BLOGENTRY,
  317. ActivityObject::STATUS))) {
  318. // TRANS: Client error displayed when using an unsupported activity object type.
  319. // TRANS: %s is the unsupported activity object type.
  320. $this->clientError(sprintf(_('Cannot handle activity object type "%s".'),
  321. $note->type));
  322. }
  323. $saved = $this->postNote($activity);
  324. Event::handle('EndAtomPubNewActivity', array($activity, $this->target->getUser(), $saved));
  325. }
  326. if (!empty($saved)) {
  327. header('HTTP/1.1 201 Created');
  328. header("Location: " . common_local_url('ApiStatusesShow', array('id' => $saved->id,
  329. 'format' => 'atom')));
  330. $this->showSingleAtomStatus($saved);
  331. }
  332. }
  333. function postNote($activity)
  334. {
  335. $note = $activity->objects[0];
  336. // Use summary as fallback for content
  337. if (!empty($note->content)) {
  338. $sourceContent = $note->content;
  339. } else if (!empty($note->summary)) {
  340. $sourceContent = $note->summary;
  341. } else if (!empty($note->title)) {
  342. $sourceContent = $note->title;
  343. } else {
  344. // @fixme fetch from $sourceUrl?
  345. // TRANS: Client error displayed when posting a notice without content through the API.
  346. // TRANS: %d is the notice ID (number).
  347. $this->clientError(sprintf(_('No content for notice %d.'), $note->id));
  348. }
  349. // Get (safe!) HTML and text versions of the content
  350. $rendered = common_purify($sourceContent);
  351. $content = common_strip_html($rendered);
  352. $shortened = $this->auth_user->shortenLinks($content);
  353. $options = array('is_local' => Notice::LOCAL_PUBLIC,
  354. 'rendered' => $rendered,
  355. 'replies' => array(),
  356. 'groups' => array(),
  357. 'tags' => array(),
  358. 'urls' => array());
  359. // accept remote URI (not necessarily a good idea)
  360. common_debug("Note ID is {$note->id}");
  361. if (!empty($note->id)) {
  362. $notice = Notice::getKV('uri', trim($note->id));
  363. if (!empty($notice)) {
  364. // TRANS: Client error displayed when using another format than AtomPub.
  365. // TRANS: %s is the notice URI.
  366. $this->clientError(sprintf(_('Notice with URI "%s" already exists.'), $note->id));
  367. }
  368. common_log(LOG_NOTICE, "Saving client-supplied notice URI '$note->id'");
  369. $options['uri'] = $note->id;
  370. }
  371. // accept remote create time (also maybe not such a good idea)
  372. if (!empty($activity->time)) {
  373. common_log(LOG_NOTICE, "Saving client-supplied create time {$activity->time}");
  374. $options['created'] = common_sql_date($activity->time);
  375. }
  376. // Check for optional attributes...
  377. if ($activity->context instanceof ActivityContext) {
  378. foreach ($activity->context->attention as $uri=>$type) {
  379. try {
  380. $profile = Profile::fromUri($uri);
  381. if ($profile->isGroup()) {
  382. $options['groups'][] = $profile->id;
  383. } else {
  384. $options['replies'][] = $uri;
  385. }
  386. } catch (UnknownUriException $e) {
  387. common_log(LOG_WARNING, sprintf('AtomPub post with unknown attention URI %s', $uri));
  388. }
  389. }
  390. // Maintain direct reply associations
  391. // @fixme what about conversation ID?
  392. if (!empty($activity->context->replyToID)) {
  393. $orig = Notice::getKV('uri',
  394. $activity->context->replyToID);
  395. if (!empty($orig)) {
  396. $options['reply_to'] = $orig->id;
  397. }
  398. }
  399. $location = $activity->context->location;
  400. if ($location) {
  401. $options['lat'] = $location->lat;
  402. $options['lon'] = $location->lon;
  403. if ($location->location_id) {
  404. $options['location_ns'] = $location->location_ns;
  405. $options['location_id'] = $location->location_id;
  406. }
  407. }
  408. }
  409. // Atom categories <-> hashtags
  410. foreach ($activity->categories as $cat) {
  411. if ($cat->term) {
  412. $term = common_canonical_tag($cat->term);
  413. if ($term) {
  414. $options['tags'][] = $term;
  415. }
  416. }
  417. }
  418. // Atom enclosures -> attachment URLs
  419. foreach ($activity->enclosures as $href) {
  420. // @fixme save these locally or....?
  421. $options['urls'][] = $href;
  422. }
  423. $saved = Notice::saveNew($this->target->id,
  424. $content,
  425. 'atompub', // TODO: deal with this
  426. $options);
  427. return $saved;
  428. }
  429. }