Helper.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Joas Schilling <coding@schilljs.com>
  6. *
  7. * @license AGPL-3.0
  8. *
  9. * This code is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License, version 3,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License, version 3,
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>
  20. *
  21. */
  22. namespace OCA\Files\Activity;
  23. use OCP\Files\Folder;
  24. use OCP\ITagManager;
  25. class Helper {
  26. /** If a user has a lot of favorites the query might get too slow and long */
  27. const FAVORITE_LIMIT = 50;
  28. /** @var ITagManager */
  29. protected $tagManager;
  30. /**
  31. * @param ITagManager $tagManager
  32. */
  33. public function __construct(ITagManager $tagManager) {
  34. $this->tagManager = $tagManager;
  35. }
  36. /**
  37. * Returns an array with the favorites
  38. *
  39. * @param string $user
  40. * @return array
  41. * @throws \RuntimeException when too many or no favorites where found
  42. */
  43. public function getFavoriteFilePaths($user) {
  44. $tags = $this->tagManager->load('files', [], false, $user);
  45. $favorites = $tags->getFavorites();
  46. if (empty($favorites)) {
  47. throw new \RuntimeException('No favorites', 1);
  48. } else if (isset($favorites[self::FAVORITE_LIMIT])) {
  49. throw new \RuntimeException('Too many favorites', 2);
  50. }
  51. // Can not DI because the user is not known on instantiation
  52. $rootFolder = \OC::$server->getUserFolder($user);
  53. $folders = $items = [];
  54. foreach ($favorites as $favorite) {
  55. $nodes = $rootFolder->getById($favorite);
  56. if (!empty($nodes)) {
  57. /** @var \OCP\Files\Node $node */
  58. $node = array_shift($nodes);
  59. $path = substr($node->getPath(), strlen($user . '/files/'));
  60. $items[] = $path;
  61. if ($node instanceof Folder) {
  62. $folders[] = $path;
  63. }
  64. }
  65. }
  66. if (empty($items)) {
  67. throw new \RuntimeException('No favorites', 1);
  68. }
  69. return [
  70. 'items' => $items,
  71. 'folders' => $folders,
  72. ];
  73. }
  74. }