1
0

Comment.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. * @psalm-return list<array{type: 'guest'|'email'|'federated_group'|'group'|'federated_team'|'team'|'federated_user'|'user', id: non-empty-lowercase-string}>
  171. * @since 30.0.2 Type 'email' is supported
  172. * @since 29.0.0 Types 'federated_group', 'federated_team', 'team' and 'federated_user' are supported
  173. * @since 23.0.0 Type 'group' is supported
  174. * @since 17.0.0 Type 'guest' is supported
  175. * @since 11.0.0
  176. */
  177. public function getMentions(): array {
  178. $ok = preg_match_all("/\B(?<![^a-z0-9_\-@\.\'\s])@(\"(guest|email)\/[a-f0-9]+\"|\"(?:federated_)?(?:group|team|user){1}\/[a-z0-9_\-@\.\' \/:]+\"|\"[a-z0-9_\-@\.\' ]+\"|[a-z0-9_\-@\.\']+)/i", $this->getMessage(), $mentions);
  179. if (!$ok || !isset($mentions[0])) {
  180. return [];
  181. }
  182. $mentionIds = array_unique($mentions[0]);
  183. usort($mentionIds, static function ($mentionId1, $mentionId2) {
  184. return mb_strlen($mentionId2) <=> mb_strlen($mentionId1);
  185. });
  186. $result = [];
  187. foreach ($mentionIds as $mentionId) {
  188. // Cut-off the @ and remove wrapping double-quotes
  189. /** @var non-empty-lowercase-string $cleanId */
  190. $cleanId = trim(substr($mentionId, 1), '"');
  191. if (str_starts_with($cleanId, 'guest/')) {
  192. $result[] = ['type' => 'guest', 'id' => $cleanId];
  193. } elseif (str_starts_with($cleanId, 'email/')) {
  194. /** @var non-empty-lowercase-string $cleanId */
  195. $cleanId = substr($cleanId, 6);
  196. $result[] = ['type' => 'email', 'id' => $cleanId];
  197. } elseif (str_starts_with($cleanId, 'federated_group/')) {
  198. /** @var non-empty-lowercase-string $cleanId */
  199. $cleanId = substr($cleanId, 16);
  200. $result[] = ['type' => 'federated_group', 'id' => $cleanId];
  201. } elseif (str_starts_with($cleanId, 'group/')) {
  202. /** @var non-empty-lowercase-string $cleanId */
  203. $cleanId = substr($cleanId, 6);
  204. $result[] = ['type' => 'group', 'id' => $cleanId];
  205. } elseif (str_starts_with($cleanId, 'federated_team/')) {
  206. /** @var non-empty-lowercase-string $cleanId */
  207. $cleanId = substr($cleanId, 15);
  208. $result[] = ['type' => 'federated_team', 'id' => $cleanId];
  209. } elseif (str_starts_with($cleanId, 'team/')) {
  210. /** @var non-empty-lowercase-string $cleanId */
  211. $cleanId = substr($cleanId, 5);
  212. $result[] = ['type' => 'team', 'id' => $cleanId];
  213. } elseif (str_starts_with($cleanId, 'federated_user/')) {
  214. /** @var non-empty-lowercase-string $cleanId */
  215. $cleanId = substr($cleanId, 15);
  216. $result[] = ['type' => 'federated_user', 'id' => $cleanId];
  217. } else {
  218. $result[] = ['type' => 'user', 'id' => $cleanId];
  219. }
  220. }
  221. return $result;
  222. }
  223. /**
  224. * Returns the verb of the comment
  225. *
  226. * @since 9.0.0
  227. */
  228. public function getVerb(): string {
  229. return $this->data['verb'];
  230. }
  231. /**
  232. * Sets the verb of the comment, e.g. 'comment' or 'like'
  233. *
  234. * @param string $verb
  235. * @since 9.0.0
  236. */
  237. public function setVerb($verb): IComment {
  238. if (!is_string($verb) || !trim($verb)) {
  239. throw new \InvalidArgumentException('Non-empty String expected.');
  240. }
  241. $this->data['verb'] = trim($verb);
  242. return $this;
  243. }
  244. /**
  245. * Returns the actor type
  246. * @since 9.0.0
  247. */
  248. public function getActorType(): string {
  249. return $this->data['actorType'];
  250. }
  251. /**
  252. * Returns the actor ID
  253. * @since 9.0.0
  254. */
  255. public function getActorId(): string {
  256. return $this->data['actorId'];
  257. }
  258. /**
  259. * Sets (overwrites) the actor type and id
  260. *
  261. * @param string $actorType e.g. 'users'
  262. * @param string $actorId e.g. 'zombie234'
  263. * @since 9.0.0
  264. */
  265. public function setActor($actorType, $actorId): IComment {
  266. if (
  267. !is_string($actorType) || !trim($actorType)
  268. || !is_string($actorId) || $actorId === ''
  269. ) {
  270. throw new \InvalidArgumentException('String expected.');
  271. }
  272. $this->data['actorType'] = trim($actorType);
  273. $this->data['actorId'] = $actorId;
  274. return $this;
  275. }
  276. /**
  277. * Returns the creation date of the comment.
  278. *
  279. * If not explicitly set, it shall default to the time of initialization.
  280. * @since 9.0.0
  281. * @throws \LogicException if creation date time is not set yet
  282. */
  283. public function getCreationDateTime(): \DateTime {
  284. if (!isset($this->data['creationDT'])) {
  285. throw new \LogicException('Cannot get creation date before setting one or writting to database');
  286. }
  287. return $this->data['creationDT'];
  288. }
  289. /**
  290. * Sets the creation date of the comment and returns itself
  291. * @since 9.0.0
  292. */
  293. public function setCreationDateTime(\DateTime $dateTime): IComment {
  294. $this->data['creationDT'] = $dateTime;
  295. return $this;
  296. }
  297. /**
  298. * Returns the DateTime of the most recent child, if set, otherwise null
  299. * @since 9.0.0
  300. */
  301. public function getLatestChildDateTime(): ?\DateTime {
  302. return $this->data['latestChildDT'];
  303. }
  304. /**
  305. * @inheritDoc
  306. */
  307. public function setLatestChildDateTime(?\DateTime $dateTime = null): IComment {
  308. $this->data['latestChildDT'] = $dateTime;
  309. return $this;
  310. }
  311. /**
  312. * Returns the object type the comment is attached to
  313. * @since 9.0.0
  314. */
  315. public function getObjectType(): string {
  316. return $this->data['objectType'];
  317. }
  318. /**
  319. * Returns the object id the comment is attached to
  320. * @since 9.0.0
  321. */
  322. public function getObjectId(): string {
  323. return $this->data['objectId'];
  324. }
  325. /**
  326. * Sets (overwrites) the object of the comment
  327. *
  328. * @param string $objectType e.g. 'files'
  329. * @param string $objectId e.g. '16435'
  330. * @since 9.0.0
  331. */
  332. public function setObject($objectType, $objectId): IComment {
  333. if (
  334. !is_string($objectType) || !trim($objectType)
  335. || !is_string($objectId) || trim($objectId) === ''
  336. ) {
  337. throw new \InvalidArgumentException('String expected.');
  338. }
  339. $this->data['objectType'] = trim($objectType);
  340. $this->data['objectId'] = trim($objectId);
  341. return $this;
  342. }
  343. /**
  344. * Returns the reference id of the comment
  345. * @since 19.0.0
  346. */
  347. public function getReferenceId(): ?string {
  348. return $this->data['referenceId'];
  349. }
  350. /**
  351. * Sets (overwrites) the reference id of the comment
  352. *
  353. * @param string $referenceId e.g. sha256 hash sum
  354. * @since 19.0.0
  355. */
  356. public function setReferenceId(?string $referenceId): IComment {
  357. if ($referenceId === null) {
  358. $this->data['referenceId'] = $referenceId;
  359. } else {
  360. $referenceId = trim($referenceId);
  361. if ($referenceId === '') {
  362. throw new \InvalidArgumentException('Non empty string expected.');
  363. }
  364. $this->data['referenceId'] = $referenceId;
  365. }
  366. return $this;
  367. }
  368. /**
  369. * @inheritDoc
  370. */
  371. public function getMetaData(): ?array {
  372. if ($this->data['metaData'] === null) {
  373. return null;
  374. }
  375. try {
  376. $metaData = json_decode($this->data['metaData'], true, flags: JSON_THROW_ON_ERROR);
  377. } catch (\JsonException $e) {
  378. return null;
  379. }
  380. return is_array($metaData) ? $metaData : null;
  381. }
  382. /**
  383. * @inheritDoc
  384. */
  385. public function setMetaData(?array $metaData): IComment {
  386. if ($metaData === null) {
  387. $this->data['metaData'] = null;
  388. } else {
  389. $this->data['metaData'] = json_encode($metaData, JSON_THROW_ON_ERROR);
  390. }
  391. return $this;
  392. }
  393. /**
  394. * @inheritDoc
  395. */
  396. public function getReactions(): array {
  397. return $this->data['reactions'] ?? [];
  398. }
  399. /**
  400. * @inheritDoc
  401. */
  402. public function setReactions(?array $reactions): IComment {
  403. $this->data['reactions'] = $reactions;
  404. return $this;
  405. }
  406. /**
  407. * @inheritDoc
  408. */
  409. public function setExpireDate(?\DateTime $dateTime): IComment {
  410. $this->data['expire_date'] = $dateTime;
  411. return $this;
  412. }
  413. /**
  414. * @inheritDoc
  415. */
  416. public function getExpireDate(): ?\DateTime {
  417. return $this->data['expire_date'];
  418. }
  419. /**
  420. * sets the comment data based on an array with keys as taken from the
  421. * database.
  422. *
  423. * @param array $data
  424. */
  425. protected function fromArray($data): IComment {
  426. foreach (array_keys($data) as $key) {
  427. // translate DB keys to internal setter names
  428. $setter = 'set' . implode('', array_map('ucfirst', explode('_', $key)));
  429. $setter = str_replace('Timestamp', 'DateTime', $setter);
  430. if (method_exists($this, $setter)) {
  431. $this->$setter($data[$key]);
  432. }
  433. }
  434. foreach (['actor', 'object'] as $role) {
  435. if (isset($data[$role . '_type']) && isset($data[$role . '_id'])) {
  436. $setter = 'set' . ucfirst($role);
  437. $this->$setter($data[$role . '_type'], $data[$role . '_id']);
  438. }
  439. }
  440. return $this;
  441. }
  442. }