QuerySearchHelper.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Robin Appelman <robin@icewind.nl>
  7. * @author Roeland Jago Douma <roeland@famdouma.nl>
  8. * @author Tobias Kaminsky <tobias@kaminsky.me>
  9. *
  10. * @license GNU AGPL version 3 or any later version
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License as
  14. * published by the Free Software Foundation, either version 3 of the
  15. * License, or (at your option) any later version.
  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
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. namespace OC\Files\Cache;
  27. use OC\Files\Cache\Wrapper\CacheJail;
  28. use OC\Files\Search\QueryOptimizer\QueryOptimizer;
  29. use OC\Files\Search\SearchBinaryOperator;
  30. use OC\SystemConfig;
  31. use OCP\DB\QueryBuilder\IQueryBuilder;
  32. use OCP\Files\Cache\ICache;
  33. use OCP\Files\Cache\ICacheEntry;
  34. use OCP\Files\IMimeTypeLoader;
  35. use OCP\Files\IRootFolder;
  36. use OCP\Files\Mount\IMountPoint;
  37. use OCP\Files\Search\ISearchBinaryOperator;
  38. use OCP\Files\Search\ISearchQuery;
  39. use OCP\IDBConnection;
  40. use OCP\IGroupManager;
  41. use OCP\IUser;
  42. use Psr\Log\LoggerInterface;
  43. class QuerySearchHelper {
  44. /** @var IMimeTypeLoader */
  45. private $mimetypeLoader;
  46. /** @var IDBConnection */
  47. private $connection;
  48. /** @var SystemConfig */
  49. private $systemConfig;
  50. private LoggerInterface $logger;
  51. /** @var SearchBuilder */
  52. private $searchBuilder;
  53. /** @var QueryOptimizer */
  54. private $queryOptimizer;
  55. private IGroupManager $groupManager;
  56. public function __construct(
  57. IMimeTypeLoader $mimetypeLoader,
  58. IDBConnection $connection,
  59. SystemConfig $systemConfig,
  60. LoggerInterface $logger,
  61. SearchBuilder $searchBuilder,
  62. QueryOptimizer $queryOptimizer,
  63. IGroupManager $groupManager,
  64. ) {
  65. $this->mimetypeLoader = $mimetypeLoader;
  66. $this->connection = $connection;
  67. $this->systemConfig = $systemConfig;
  68. $this->logger = $logger;
  69. $this->searchBuilder = $searchBuilder;
  70. $this->queryOptimizer = $queryOptimizer;
  71. $this->groupManager = $groupManager;
  72. }
  73. protected function getQueryBuilder() {
  74. return new CacheQueryBuilder(
  75. $this->connection,
  76. $this->systemConfig,
  77. $this->logger
  78. );
  79. }
  80. protected function applySearchConstraints(CacheQueryBuilder $query, ISearchQuery $searchQuery, array $caches): void {
  81. $storageFilters = array_values(array_map(function (ICache $cache) {
  82. return $cache->getQueryFilterForStorage();
  83. }, $caches));
  84. $storageFilter = new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_OR, $storageFilters);
  85. $filter = new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [$searchQuery->getSearchOperation(), $storageFilter]);
  86. $this->queryOptimizer->processOperator($filter);
  87. $searchExpr = $this->searchBuilder->searchOperatorToDBExpr($query, $filter);
  88. if ($searchExpr) {
  89. $query->andWhere($searchExpr);
  90. }
  91. $this->searchBuilder->addSearchOrdersToQuery($query, $searchQuery->getOrder());
  92. if ($searchQuery->getLimit()) {
  93. $query->setMaxResults($searchQuery->getLimit());
  94. }
  95. if ($searchQuery->getOffset()) {
  96. $query->setFirstResult($searchQuery->getOffset());
  97. }
  98. }
  99. /**
  100. * @return array<array-key, array{id: int, name: string, visibility: int, editable: int, ref_file_id: int, number_files: int}>
  101. */
  102. public function findUsedTagsInCaches(ISearchQuery $searchQuery, array $caches): array {
  103. $query = $this->getQueryBuilder();
  104. $query->selectTagUsage();
  105. $this->applySearchConstraints($query, $searchQuery, $caches);
  106. $result = $query->execute();
  107. $tags = $result->fetchAll();
  108. $result->closeCursor();
  109. return $tags;
  110. }
  111. protected function equipQueryForSystemTags(CacheQueryBuilder $query, IUser $user): void {
  112. $query->leftJoin('file', 'systemtag_object_mapping', 'systemtagmap', $query->expr()->andX(
  113. $query->expr()->eq('file.fileid', $query->expr()->castColumn('systemtagmap.objectid', IQueryBuilder::PARAM_INT)),
  114. $query->expr()->eq('systemtagmap.objecttype', $query->createNamedParameter('files'))
  115. ));
  116. $on = $query->expr()->andX($query->expr()->eq('systemtag.id', 'systemtagmap.systemtagid'));
  117. if (!$this->groupManager->isAdmin($user->getUID())) {
  118. $on->add($query->expr()->eq('systemtag.visibility', $query->createNamedParameter(true)));
  119. }
  120. $query->leftJoin('systemtagmap', 'systemtag', 'systemtag', $on);
  121. }
  122. protected function equipQueryForDavTags(CacheQueryBuilder $query, IUser $user): void {
  123. $query
  124. ->leftJoin('file', 'vcategory_to_object', 'tagmap', $query->expr()->eq('file.fileid', 'tagmap.objid'))
  125. ->leftJoin('tagmap', 'vcategory', 'tag', $query->expr()->andX(
  126. $query->expr()->eq('tagmap.type', 'tag.type'),
  127. $query->expr()->eq('tagmap.categoryid', 'tag.id'),
  128. $query->expr()->eq('tag.type', $query->createNamedParameter('files')),
  129. $query->expr()->eq('tag.uid', $query->createNamedParameter($user->getUID()))
  130. ));
  131. }
  132. /**
  133. * Perform a file system search in multiple caches
  134. *
  135. * the results will be grouped by the same array keys as the $caches argument to allow
  136. * post-processing based on which cache the result came from
  137. *
  138. * @template T of array-key
  139. * @param ISearchQuery $searchQuery
  140. * @param array<T, ICache> $caches
  141. * @return array<T, ICacheEntry[]>
  142. */
  143. public function searchInCaches(ISearchQuery $searchQuery, array $caches): array {
  144. // search in multiple caches at once by creating one query in the following format
  145. // SELECT ... FROM oc_filecache WHERE
  146. // <filter expressions from the search query>
  147. // AND (
  148. // <filter expression for storage1> OR
  149. // <filter expression for storage2> OR
  150. // ...
  151. // );
  152. //
  153. // This gives us all the files matching the search query from all caches
  154. //
  155. // while the resulting rows don't have a way to tell what storage they came from (multiple storages/caches can share storage_id)
  156. // we can just ask every cache if the row belongs to them and give them the cache to do any post processing on the result.
  157. $builder = $this->getQueryBuilder();
  158. $query = $builder->selectFileCache('file', false);
  159. $requestedFields = $this->searchBuilder->extractRequestedFields($searchQuery->getSearchOperation());
  160. if (in_array('systemtag', $requestedFields)) {
  161. $this->equipQueryForSystemTags($query, $this->requireUser($searchQuery));
  162. }
  163. if (in_array('tagname', $requestedFields) || in_array('favorite', $requestedFields)) {
  164. $this->equipQueryForDavTags($query, $this->requireUser($searchQuery));
  165. }
  166. $this->applySearchConstraints($query, $searchQuery, $caches);
  167. $result = $query->execute();
  168. $files = $result->fetchAll();
  169. $rawEntries = array_map(function (array $data) {
  170. return Cache::cacheEntryFromData($data, $this->mimetypeLoader);
  171. }, $files);
  172. $result->closeCursor();
  173. // loop through all caches for each result to see if the result matches that storage
  174. // results are grouped by the same array keys as the caches argument to allow the caller to distinguish the source of the results
  175. $results = array_fill_keys(array_keys($caches), []);
  176. foreach ($rawEntries as $rawEntry) {
  177. foreach ($caches as $cacheKey => $cache) {
  178. $entry = $cache->getCacheEntryFromSearchResult($rawEntry);
  179. if ($entry) {
  180. $results[$cacheKey][] = $entry;
  181. }
  182. }
  183. }
  184. return $results;
  185. }
  186. protected function requireUser(ISearchQuery $searchQuery): IUser {
  187. $user = $searchQuery->getUser();
  188. if ($user === null) {
  189. throw new \InvalidArgumentException("This search operation requires the user to be set in the query");
  190. }
  191. return $user;
  192. }
  193. /**
  194. * @return list{0?: array<array-key, ICache>, 1?: array<array-key, IMountPoint>}
  195. */
  196. public function getCachesAndMountPointsForSearch(IRootFolder $root, string $path, bool $limitToHome = false): array {
  197. $rootLength = strlen($path);
  198. $mount = $root->getMount($path);
  199. $storage = $mount->getStorage();
  200. if ($storage === null) {
  201. return [];
  202. }
  203. $internalPath = $mount->getInternalPath($path);
  204. if ($internalPath !== '') {
  205. // a temporary CacheJail is used to handle filtering down the results to within this folder
  206. /** @var ICache[] $caches */
  207. $caches = ['' => new CacheJail($storage->getCache(''), $internalPath)];
  208. } else {
  209. /** @var ICache[] $caches */
  210. $caches = ['' => $storage->getCache('')];
  211. }
  212. /** @var IMountPoint[] $mountByMountPoint */
  213. $mountByMountPoint = ['' => $mount];
  214. if (!$limitToHome) {
  215. $mounts = $root->getMountsIn($path);
  216. foreach ($mounts as $mount) {
  217. $storage = $mount->getStorage();
  218. if ($storage) {
  219. $relativeMountPoint = ltrim(substr($mount->getMountPoint(), $rootLength), '/');
  220. $caches[$relativeMountPoint] = $storage->getCache('');
  221. $mountByMountPoint[$relativeMountPoint] = $mount;
  222. }
  223. }
  224. }
  225. return [$caches, $mountByMountPoint];
  226. }
  227. }