CommentsPlugin.php 7.3 KB

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