1
0

LegacyProvider.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Comments\Search;
  8. use OCP\Comments\IComment;
  9. use OCP\Comments\ICommentsManager;
  10. use OCP\Files\Folder;
  11. use OCP\Files\Node;
  12. use OCP\Files\NotFoundException;
  13. use OCP\IUser;
  14. use OCP\Search\Provider;
  15. use function count;
  16. class LegacyProvider extends Provider {
  17. /**
  18. * Search for $query
  19. *
  20. * @param string $query
  21. * @return array An array of OCP\Search\Result's
  22. * @since 7.0.0
  23. */
  24. public function search($query): array {
  25. $cm = \OC::$server->get(ICommentsManager::class);
  26. $us = \OC::$server->getUserSession();
  27. $user = $us->getUser();
  28. if (!$user instanceof IUser) {
  29. return [];
  30. }
  31. $uf = \OC::$server->getUserFolder($user->getUID());
  32. if ($uf === null) {
  33. return [];
  34. }
  35. $result = [];
  36. $numComments = 50;
  37. $offset = 0;
  38. while (count($result) < $numComments) {
  39. /** @var IComment[] $comments */
  40. $comments = $cm->search($query, 'files', '', 'comment', $offset, $numComments);
  41. foreach ($comments as $comment) {
  42. if ($comment->getActorType() !== 'users') {
  43. continue;
  44. }
  45. $displayName = $cm->resolveDisplayName('user', $comment->getActorId());
  46. try {
  47. $file = $this->getFileForComment($uf, $comment);
  48. $result[] = new Result($query,
  49. $comment,
  50. $displayName,
  51. $file->getPath()
  52. );
  53. } catch (NotFoundException $e) {
  54. continue;
  55. }
  56. }
  57. if (count($comments) < $numComments) {
  58. // Didn't find more comments when we tried to get, so there are no more comments.
  59. return $result;
  60. }
  61. $offset += $numComments;
  62. $numComments = 50 - count($result);
  63. }
  64. return $result;
  65. }
  66. /**
  67. * @param Folder $userFolder
  68. * @param IComment $comment
  69. * @return Node
  70. * @throws NotFoundException
  71. */
  72. protected function getFileForComment(Folder $userFolder, IComment $comment): Node {
  73. $nodes = $userFolder->getById((int)$comment->getObjectId());
  74. if (empty($nodes)) {
  75. throw new NotFoundException('File not found');
  76. }
  77. return array_shift($nodes);
  78. }
  79. }