apitimelineuser.php 18 KB

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