CommentsPlugin.php 6.7 KB

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