Comment.php 12 KB

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