1
0

CommentsPlugin.php 6.5 KB

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