1
0

CommentsPlugin.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. * @author Vincent Petry <vincent@nextcloud.com>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OCA\DAV\Comments;
  27. use OCP\Comments\IComment;
  28. use OCP\Comments\ICommentsManager;
  29. use OCP\IUserSession;
  30. use Sabre\DAV\Exception\BadRequest;
  31. use Sabre\DAV\Exception\NotFound;
  32. use Sabre\DAV\Exception\ReportNotSupported;
  33. use Sabre\DAV\Exception\UnsupportedMediaType;
  34. use Sabre\DAV\Server;
  35. use Sabre\DAV\ServerPlugin;
  36. use Sabre\DAV\Xml\Element\Response;
  37. use Sabre\DAV\Xml\Response\MultiStatus;
  38. use Sabre\HTTP\RequestInterface;
  39. use Sabre\HTTP\ResponseInterface;
  40. use Sabre\Xml\Writer;
  41. /**
  42. * Sabre plugin to handle comments:
  43. */
  44. class CommentsPlugin extends ServerPlugin {
  45. // namespace
  46. public const NS_OWNCLOUD = 'http://owncloud.org/ns';
  47. public const REPORT_NAME = '{http://owncloud.org/ns}filter-comments';
  48. public const REPORT_PARAM_LIMIT = '{http://owncloud.org/ns}limit';
  49. public const REPORT_PARAM_OFFSET = '{http://owncloud.org/ns}offset';
  50. public const REPORT_PARAM_TIMESTAMP = '{http://owncloud.org/ns}datetime';
  51. /** @var ICommentsManager */
  52. protected $commentsManager;
  53. /** @var \Sabre\DAV\Server $server */
  54. private $server;
  55. /** @var \OCP\IUserSession */
  56. protected $userSession;
  57. /**
  58. * Comments plugin
  59. *
  60. * @param ICommentsManager $commentsManager
  61. * @param IUserSession $userSession
  62. */
  63. public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) {
  64. $this->commentsManager = $commentsManager;
  65. $this->userSession = $userSession;
  66. }
  67. /**
  68. * This initializes the plugin.
  69. *
  70. * This function is called by Sabre\DAV\Server, after
  71. * addPlugin is called.
  72. *
  73. * This method should set up the required event subscriptions.
  74. *
  75. * @param Server $server
  76. * @return void
  77. */
  78. public function initialize(Server $server) {
  79. $this->server = $server;
  80. if (!str_starts_with($this->server->getRequestUri(), 'comments/')) {
  81. return;
  82. }
  83. $this->server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
  84. $this->server->xml->classMap['DateTime'] = function (Writer $writer, \DateTime $value) {
  85. $writer->write(\Sabre\HTTP\toDate($value));
  86. };
  87. $this->server->on('report', [$this, 'onReport']);
  88. $this->server->on('method:POST', [$this, 'httpPost']);
  89. }
  90. /**
  91. * POST operation on Comments collections
  92. *
  93. * @param RequestInterface $request request object
  94. * @param ResponseInterface $response response object
  95. * @return null|false
  96. */
  97. public function httpPost(RequestInterface $request, ResponseInterface $response) {
  98. $path = $request->getPath();
  99. $node = $this->server->tree->getNodeForPath($path);
  100. if (!$node instanceof EntityCollection) {
  101. return null;
  102. }
  103. $data = $request->getBodyAsString();
  104. $comment = $this->createComment(
  105. $node->getName(),
  106. $node->getId(),
  107. $data,
  108. $request->getHeader('Content-Type')
  109. );
  110. // update read marker for the current user/poster to avoid
  111. // having their own comments marked as unread
  112. $node->setReadMarker(null);
  113. $url = rtrim($request->getUrl(), '/') . '/' . urlencode($comment->getId());
  114. $response->setHeader('Content-Location', $url);
  115. // created
  116. $response->setStatus(201);
  117. return false;
  118. }
  119. /**
  120. * Returns a list of reports this plugin supports.
  121. *
  122. * This will be used in the {DAV:}supported-report-set property.
  123. *
  124. * @param string $uri
  125. * @return array
  126. */
  127. public function getSupportedReportSet($uri) {
  128. return [self::REPORT_NAME];
  129. }
  130. /**
  131. * REPORT operations to look for comments
  132. *
  133. * @param string $reportName
  134. * @param array $report
  135. * @param string $uri
  136. * @return bool
  137. * @throws NotFound
  138. * @throws ReportNotSupported
  139. */
  140. public function onReport($reportName, $report, $uri) {
  141. $node = $this->server->tree->getNodeForPath($uri);
  142. if (!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) {
  143. throw new ReportNotSupported();
  144. }
  145. $args = ['limit' => 0, 'offset' => 0, 'datetime' => null];
  146. $acceptableParameters = [
  147. $this::REPORT_PARAM_LIMIT,
  148. $this::REPORT_PARAM_OFFSET,
  149. $this::REPORT_PARAM_TIMESTAMP
  150. ];
  151. $ns = '{' . $this::NS_OWNCLOUD . '}';
  152. foreach ($report as $parameter) {
  153. if (!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) {
  154. continue;
  155. }
  156. $args[str_replace($ns, '', $parameter['name'])] = $parameter['value'];
  157. }
  158. if (!is_null($args['datetime'])) {
  159. $args['datetime'] = new \DateTime((string)$args['datetime']);
  160. }
  161. $results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']);
  162. $responses = [];
  163. foreach ($results as $node) {
  164. $nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId();
  165. $resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames());
  166. if (isset($resultSet[0]) && isset($resultSet[0][200])) {
  167. $responses[] = new Response(
  168. $this->server->getBaseUri() . $nodePath,
  169. [200 => $resultSet[0][200]],
  170. '200'
  171. );
  172. }
  173. }
  174. $xml = $this->server->xml->write(
  175. '{DAV:}multistatus',
  176. new MultiStatus($responses)
  177. );
  178. $this->server->httpResponse->setStatus(207);
  179. $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8');
  180. $this->server->httpResponse->setBody($xml);
  181. return false;
  182. }
  183. /**
  184. * Creates a new comment
  185. *
  186. * @param string $objectType e.g. "files"
  187. * @param string $objectId e.g. the file id
  188. * @param string $data JSON encoded string containing the properties of the tag to create
  189. * @param string $contentType content type of the data
  190. * @return IComment newly created comment
  191. *
  192. * @throws BadRequest if a field was missing
  193. * @throws UnsupportedMediaType if the content type is not supported
  194. */
  195. private function createComment($objectType, $objectId, $data, $contentType = 'application/json') {
  196. if (explode(';', $contentType)[0] === 'application/json') {
  197. $data = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
  198. } else {
  199. throw new UnsupportedMediaType();
  200. }
  201. $actorType = $data['actorType'];
  202. $actorId = null;
  203. if ($actorType === 'users') {
  204. $user = $this->userSession->getUser();
  205. if (!is_null($user)) {
  206. $actorId = $user->getUID();
  207. }
  208. }
  209. if (is_null($actorId)) {
  210. throw new BadRequest('Invalid actor "' . $actorType .'"');
  211. }
  212. try {
  213. $comment = $this->commentsManager->create($actorType, $actorId, $objectType, $objectId);
  214. $comment->setMessage($data['message']);
  215. $comment->setVerb($data['verb']);
  216. $this->commentsManager->save($comment);
  217. return $comment;
  218. } catch (\InvalidArgumentException $e) {
  219. throw new BadRequest('Invalid input values', 0, $e);
  220. } catch (\OCP\Comments\MessageTooLongException $e) {
  221. $msg = 'Message exceeds allowed character limit of ';
  222. throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0, $e);
  223. }
  224. }
  225. }