Comment.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 OC\Comments;
  8. use OCP\Comments\IComment;
  9. use OCP\Comments\IllegalIDChangeException;
  10. use OCP\Comments\MessageTooLongException;
  11. class Comment implements IComment {
  12. protected array $data = [
  13. 'id' => '',
  14. 'parentId' => '0',
  15. 'topmostParentId' => '0',
  16. 'childrenCount' => '0',
  17. 'message' => '',
  18. 'verb' => '',
  19. 'actorType' => '',
  20. 'actorId' => '',
  21. 'objectType' => '',
  22. 'objectId' => '',
  23. 'referenceId' => null,
  24. 'metaData' => null,
  25. 'creationDT' => null,
  26. 'latestChildDT' => null,
  27. 'reactions' => null,
  28. 'expire_date' => null,
  29. ];
  30. /**
  31. * Comment constructor.
  32. *
  33. * @param array $data optional, array with keys according to column names from
  34. * the comments database scheme
  35. */
  36. public function __construct(?array $data = null) {
  37. if (is_array($data)) {
  38. $this->fromArray($data);
  39. }
  40. }
  41. /**
  42. * Returns the ID of the comment
  43. *
  44. * It may return an empty string, if the comment was not stored.
  45. * It is expected that the concrete Comment implementation gives an ID
  46. * by itself (e.g. after saving).
  47. *
  48. * @since 9.0.0
  49. */
  50. public function getId(): string {
  51. return $this->data['id'];
  52. }
  53. /**
  54. * Sets the ID of the comment and returns itself
  55. *
  56. * It is only allowed to set the ID only, if the current id is an empty
  57. * string (which means it is not stored in a database, storage or whatever
  58. * the concrete implementation does), or vice versa. Changing a given ID is
  59. * not permitted and must result in an IllegalIDChangeException.
  60. *
  61. * @param string $id
  62. * @return IComment
  63. * @throws IllegalIDChangeException
  64. * @since 9.0.0
  65. */
  66. public function setId($id): IComment {
  67. if (!is_string($id)) {
  68. throw new \InvalidArgumentException('String expected.');
  69. }
  70. $id = trim($id);
  71. if ($this->data['id'] === '' || ($this->data['id'] !== '' && $id === '')) {
  72. $this->data['id'] = $id;
  73. return $this;
  74. }
  75. throw new IllegalIDChangeException('Not allowed to assign a new ID to an already saved comment.');
  76. }
  77. /**
  78. * Returns the parent ID of the comment
  79. *
  80. * @since 9.0.0
  81. */
  82. public function getParentId(): string {
  83. return $this->data['parentId'];
  84. }
  85. /**
  86. * Sets the parent ID and returns itself
  87. *
  88. * @param string $parentId
  89. * @since 9.0.0
  90. */
  91. public function setParentId($parentId): IComment {
  92. if (!is_string($parentId)) {
  93. throw new \InvalidArgumentException('String expected.');
  94. }
  95. $this->data['parentId'] = trim($parentId);
  96. return $this;
  97. }
  98. /**
  99. * Returns the topmost parent ID of the comment
  100. *
  101. * @since 9.0.0
  102. */
  103. public function getTopmostParentId(): string {
  104. return $this->data['topmostParentId'];
  105. }
  106. /**
  107. * Sets the topmost parent ID and returns itself
  108. *
  109. * @param string $id
  110. * @since 9.0.0
  111. */
  112. public function setTopmostParentId($id): IComment {
  113. if (!is_string($id)) {
  114. throw new \InvalidArgumentException('String expected.');
  115. }
  116. $this->data['topmostParentId'] = trim($id);
  117. return $this;
  118. }
  119. /**
  120. * Returns the number of children
  121. *
  122. * @since 9.0.0
  123. */
  124. public function getChildrenCount(): int {
  125. return $this->data['childrenCount'];
  126. }
  127. /**
  128. * Sets the number of children
  129. *
  130. * @param int $count
  131. * @since 9.0.0
  132. */
  133. public function setChildrenCount($count): IComment {
  134. if (!is_int($count)) {
  135. throw new \InvalidArgumentException('Integer expected.');
  136. }
  137. $this->data['childrenCount'] = $count;
  138. return $this;
  139. }
  140. /**
  141. * Returns the message of the comment
  142. * @since 9.0.0
  143. */
  144. public function getMessage(): string {
  145. return $this->data['message'];
  146. }
  147. /**
  148. * sets the message of the comment and returns itself
  149. *
  150. * @param string $message
  151. * @param int $maxLength
  152. * @throws MessageTooLongException
  153. * @since 9.0.0
  154. */
  155. public function setMessage($message, $maxLength = self::MAX_MESSAGE_LENGTH): IComment {
  156. if (!is_string($message)) {
  157. throw new \InvalidArgumentException('String expected.');
  158. }
  159. $message = trim($message);
  160. if ($maxLength && mb_strlen($message, 'UTF-8') > $maxLength) {
  161. throw new MessageTooLongException('Comment message must not exceed ' . $maxLength. ' characters');
  162. }
  163. $this->data['message'] = $message;
  164. return $this;
  165. }
  166. /**
  167. * returns an array containing mentions that are included in the comment
  168. *
  169. * @return array each mention provides a 'type' and an 'id', see example below
  170. * @since 11.0.0
  171. *
  172. * The return array looks like:
  173. * [
  174. * [
  175. * 'type' => 'user',
  176. * 'id' => 'citizen4'
  177. * ],
  178. * [
  179. * 'type' => 'group',
  180. * 'id' => 'media'
  181. * ],
  182. * …
  183. * ]
  184. *
  185. */
  186. public function getMentions(): array {
  187. $ok = preg_match_all("/\B(?<![^a-z0-9_\-@\.\'\s])@(\"guest\/[a-f0-9]+\"|\"(?:federated_)?(?:group|team|user){1}\/[a-z0-9_\-@\.\' \/:]+\"|\"[a-z0-9_\-@\.\' ]+\"|[a-z0-9_\-@\.\']+)/i", $this->getMessage(), $mentions);
  188. if (!$ok || !isset($mentions[0])) {
  189. return [];
  190. }
  191. $mentionIds = array_unique($mentions[0]);
  192. usort($mentionIds, static function ($mentionId1, $mentionId2) {
  193. return mb_strlen($mentionId2) <=> mb_strlen($mentionId1);
  194. });
  195. $result = [];
  196. foreach ($mentionIds as $mentionId) {
  197. // Cut-off the @ and remove wrapping double-quotes
  198. $cleanId = trim(substr($mentionId, 1), '"');
  199. if (str_starts_with($cleanId, 'guest/')) {
  200. $result[] = ['type' => 'guest', 'id' => $cleanId];
  201. } elseif (str_starts_with($cleanId, 'federated_group/')) {
  202. $result[] = ['type' => 'federated_group', 'id' => substr($cleanId, 16)];
  203. } elseif (str_starts_with($cleanId, 'group/')) {
  204. $result[] = ['type' => 'group', 'id' => substr($cleanId, 6)];
  205. } elseif (str_starts_with($cleanId, 'federated_team/')) {
  206. $result[] = ['type' => 'federated_team', 'id' => substr($cleanId, 15)];
  207. } elseif (str_starts_with($cleanId, 'team/')) {
  208. $result[] = ['type' => 'team', 'id' => substr($cleanId, 5)];
  209. } elseif (str_starts_with($cleanId, 'federated_user/')) {
  210. $result[] = ['type' => 'federated_user', 'id' => substr($cleanId, 15)];
  211. } else {
  212. $result[] = ['type' => 'user', 'id' => $cleanId];
  213. }
  214. }
  215. return $result;
  216. }
  217. /**
  218. * Returns the verb of the comment
  219. *
  220. * @since 9.0.0
  221. */
  222. public function getVerb(): string {
  223. return $this->data['verb'];
  224. }
  225. /**
  226. * Sets the verb of the comment, e.g. 'comment' or 'like'
  227. *
  228. * @param string $verb
  229. * @since 9.0.0
  230. */
  231. public function setVerb($verb): IComment {
  232. if (!is_string($verb) || !trim($verb)) {
  233. throw new \InvalidArgumentException('Non-empty String expected.');
  234. }
  235. $this->data['verb'] = trim($verb);
  236. return $this;
  237. }
  238. /**
  239. * Returns the actor type
  240. * @since 9.0.0
  241. */
  242. public function getActorType(): string {
  243. return $this->data['actorType'];
  244. }
  245. /**
  246. * Returns the actor ID
  247. * @since 9.0.0
  248. */
  249. public function getActorId(): string {
  250. return $this->data['actorId'];
  251. }
  252. /**
  253. * Sets (overwrites) the actor type and id
  254. *
  255. * @param string $actorType e.g. 'users'
  256. * @param string $actorId e.g. 'zombie234'
  257. * @since 9.0.0
  258. */
  259. public function setActor($actorType, $actorId): IComment {
  260. if (
  261. !is_string($actorType) || !trim($actorType)
  262. || !is_string($actorId) || $actorId === ''
  263. ) {
  264. throw new \InvalidArgumentException('String expected.');
  265. }
  266. $this->data['actorType'] = trim($actorType);
  267. $this->data['actorId'] = $actorId;
  268. return $this;
  269. }
  270. /**
  271. * Returns the creation date of the comment.
  272. *
  273. * If not explicitly set, it shall default to the time of initialization.
  274. * @since 9.0.0
  275. * @throw \LogicException if creation date time is not set yet
  276. */
  277. public function getCreationDateTime(): \DateTime {
  278. if (!isset($this->data['creationDT'])) {
  279. throw new \LogicException('Cannot get creation date before setting one or writting to database');
  280. }
  281. return $this->data['creationDT'];
  282. }
  283. /**
  284. * Sets the creation date of the comment and returns itself
  285. * @since 9.0.0
  286. */
  287. public function setCreationDateTime(\DateTime $dateTime): IComment {
  288. $this->data['creationDT'] = $dateTime;
  289. return $this;
  290. }
  291. /**
  292. * Returns the DateTime of the most recent child, if set, otherwise null
  293. * @since 9.0.0
  294. */
  295. public function getLatestChildDateTime(): ?\DateTime {
  296. return $this->data['latestChildDT'];
  297. }
  298. /**
  299. * @inheritDoc
  300. */
  301. public function setLatestChildDateTime(?\DateTime $dateTime = null): IComment {
  302. $this->data['latestChildDT'] = $dateTime;
  303. return $this;
  304. }
  305. /**
  306. * Returns the object type the comment is attached to
  307. * @since 9.0.0
  308. */
  309. public function getObjectType(): string {
  310. return $this->data['objectType'];
  311. }
  312. /**
  313. * Returns the object id the comment is attached to
  314. * @since 9.0.0
  315. */
  316. public function getObjectId(): string {
  317. return $this->data['objectId'];
  318. }
  319. /**
  320. * Sets (overwrites) the object of the comment
  321. *
  322. * @param string $objectType e.g. 'files'
  323. * @param string $objectId e.g. '16435'
  324. * @since 9.0.0
  325. */
  326. public function setObject($objectType, $objectId): IComment {
  327. if (
  328. !is_string($objectType) || !trim($objectType)
  329. || !is_string($objectId) || trim($objectId) === ''
  330. ) {
  331. throw new \InvalidArgumentException('String expected.');
  332. }
  333. $this->data['objectType'] = trim($objectType);
  334. $this->data['objectId'] = trim($objectId);
  335. return $this;
  336. }
  337. /**
  338. * Returns the reference id of the comment
  339. * @since 19.0.0
  340. */
  341. public function getReferenceId(): ?string {
  342. return $this->data['referenceId'];
  343. }
  344. /**
  345. * Sets (overwrites) the reference id of the comment
  346. *
  347. * @param string $referenceId e.g. sha256 hash sum
  348. * @since 19.0.0
  349. */
  350. public function setReferenceId(?string $referenceId): IComment {
  351. if ($referenceId === null) {
  352. $this->data['referenceId'] = $referenceId;
  353. } else {
  354. $referenceId = trim($referenceId);
  355. if ($referenceId === '') {
  356. throw new \InvalidArgumentException('Non empty string expected.');
  357. }
  358. $this->data['referenceId'] = $referenceId;
  359. }
  360. return $this;
  361. }
  362. /**
  363. * @inheritDoc
  364. */
  365. public function getMetaData(): ?array {
  366. if ($this->data['metaData'] === null) {
  367. return null;
  368. }
  369. try {
  370. $metaData = json_decode($this->data['metaData'], true, flags: JSON_THROW_ON_ERROR);
  371. } catch (\JsonException $e) {
  372. return null;
  373. }
  374. return is_array($metaData) ? $metaData : null;
  375. }
  376. /**
  377. * @inheritDoc
  378. */
  379. public function setMetaData(?array $metaData): IComment {
  380. if ($metaData === null) {
  381. $this->data['metaData'] = null;
  382. } else {
  383. $this->data['metaData'] = json_encode($metaData, JSON_THROW_ON_ERROR);
  384. }
  385. return $this;
  386. }
  387. /**
  388. * @inheritDoc
  389. */
  390. public function getReactions(): array {
  391. return $this->data['reactions'] ?? [];
  392. }
  393. /**
  394. * @inheritDoc
  395. */
  396. public function setReactions(?array $reactions): IComment {
  397. $this->data['reactions'] = $reactions;
  398. return $this;
  399. }
  400. /**
  401. * @inheritDoc
  402. */
  403. public function setExpireDate(?\DateTime $dateTime): IComment {
  404. $this->data['expire_date'] = $dateTime;
  405. return $this;
  406. }
  407. /**
  408. * @inheritDoc
  409. */
  410. public function getExpireDate(): ?\DateTime {
  411. return $this->data['expire_date'];
  412. }
  413. /**
  414. * sets the comment data based on an array with keys as taken from the
  415. * database.
  416. *
  417. * @param array $data
  418. */
  419. protected function fromArray($data): IComment {
  420. foreach (array_keys($data) as $key) {
  421. // translate DB keys to internal setter names
  422. $setter = 'set' . implode('', array_map('ucfirst', explode('_', $key)));
  423. $setter = str_replace('Timestamp', 'DateTime', $setter);
  424. if (method_exists($this, $setter)) {
  425. $this->$setter($data[$key]);
  426. }
  427. }
  428. foreach (['actor', 'object'] as $role) {
  429. if (isset($data[$role . '_type']) && isset($data[$role . '_id'])) {
  430. $setter = 'set' . ucfirst($role);
  431. $this->$setter($data[$role . '_type'], $data[$role . '_id']);
  432. }
  433. }
  434. return $this;
  435. }
  436. }