QuerySearchHelper.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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\Node\Root;
  29. use OC\Files\Search\QueryOptimizer\QueryOptimizer;
  30. use OC\Files\Search\SearchBinaryOperator;
  31. use OC\SystemConfig;
  32. use OCP\DB\QueryBuilder\IQueryBuilder;
  33. use OCP\Files\Cache\ICache;
  34. use OCP\Files\Cache\ICacheEntry;
  35. use OCP\Files\Folder;
  36. use OCP\Files\IMimeTypeLoader;
  37. use OCP\Files\Mount\IMountPoint;
  38. use OCP\Files\Search\ISearchBinaryOperator;
  39. use OCP\Files\Search\ISearchQuery;
  40. use OCP\IDBConnection;
  41. use Psr\Log\LoggerInterface;
  42. class QuerySearchHelper {
  43. /** @var IMimeTypeLoader */
  44. private $mimetypeLoader;
  45. /** @var IDBConnection */
  46. private $connection;
  47. /** @var SystemConfig */
  48. private $systemConfig;
  49. private LoggerInterface $logger;
  50. /** @var SearchBuilder */
  51. private $searchBuilder;
  52. /** @var QueryOptimizer */
  53. private $queryOptimizer;
  54. public function __construct(
  55. IMimeTypeLoader $mimetypeLoader,
  56. IDBConnection $connection,
  57. SystemConfig $systemConfig,
  58. LoggerInterface $logger,
  59. SearchBuilder $searchBuilder,
  60. QueryOptimizer $queryOptimizer
  61. ) {
  62. $this->mimetypeLoader = $mimetypeLoader;
  63. $this->connection = $connection;
  64. $this->systemConfig = $systemConfig;
  65. $this->logger = $logger;
  66. $this->searchBuilder = $searchBuilder;
  67. $this->queryOptimizer = $queryOptimizer;
  68. }
  69. protected function getQueryBuilder() {
  70. return new CacheQueryBuilder(
  71. $this->connection,
  72. $this->systemConfig,
  73. $this->logger
  74. );
  75. }
  76. protected function applySearchConstraints(CacheQueryBuilder $query, ISearchQuery $searchQuery, array $caches): void {
  77. $storageFilters = array_values(array_map(function (ICache $cache) {
  78. return $cache->getQueryFilterForStorage();
  79. }, $caches));
  80. $storageFilter = new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_OR, $storageFilters);
  81. $filter = new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [$searchQuery->getSearchOperation(), $storageFilter]);
  82. $this->queryOptimizer->processOperator($filter);
  83. $searchExpr = $this->searchBuilder->searchOperatorToDBExpr($query, $filter);
  84. if ($searchExpr) {
  85. $query->andWhere($searchExpr);
  86. }
  87. $this->searchBuilder->addSearchOrdersToQuery($query, $searchQuery->getOrder());
  88. if ($searchQuery->getLimit()) {
  89. $query->setMaxResults($searchQuery->getLimit());
  90. }
  91. if ($searchQuery->getOffset()) {
  92. $query->setFirstResult($searchQuery->getOffset());
  93. }
  94. }
  95. /**
  96. * @return array<array-key, array{id: int, name: string, visibility: int, editable: int, ref_file_id: int, number_files: int}>
  97. */
  98. public function findUsedTagsInCaches(ISearchQuery $searchQuery, array $caches): array {
  99. $query = $this->getQueryBuilder();
  100. $query->selectTagUsage();
  101. $this->applySearchConstraints($query, $searchQuery, $caches);
  102. $result = $query->execute();
  103. $tags = $result->fetchAll();
  104. $result->closeCursor();
  105. return $tags;
  106. }
  107. /**
  108. * Perform a file system search in multiple caches
  109. *
  110. * the results will be grouped by the same array keys as the $caches argument to allow
  111. * post-processing based on which cache the result came from
  112. *
  113. * @template T of array-key
  114. * @param ISearchQuery $searchQuery
  115. * @param array<T, ICache> $caches
  116. * @return array<T, ICacheEntry[]>
  117. */
  118. public function searchInCaches(ISearchQuery $searchQuery, array $caches): array {
  119. // search in multiple caches at once by creating one query in the following format
  120. // SELECT ... FROM oc_filecache WHERE
  121. // <filter expressions from the search query>
  122. // AND (
  123. // <filter expression for storage1> OR
  124. // <filter expression for storage2> OR
  125. // ...
  126. // );
  127. //
  128. // This gives us all the files matching the search query from all caches
  129. //
  130. // while the resulting rows don't have a way to tell what storage they came from (multiple storages/caches can share storage_id)
  131. // 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.
  132. $builder = $this->getQueryBuilder();
  133. $query = $builder->selectFileCache('file', false);
  134. if ($this->searchBuilder->shouldJoinTags($searchQuery->getSearchOperation())) {
  135. $user = $searchQuery->getUser();
  136. if ($user === null) {
  137. throw new \InvalidArgumentException("Searching by tag requires the user to be set in the query");
  138. }
  139. $query
  140. ->leftJoin('file', 'vcategory_to_object', 'tagmap', $builder->expr()->eq('file.fileid', 'tagmap.objid'))
  141. ->leftJoin('tagmap', 'vcategory', 'tag', $builder->expr()->andX(
  142. $builder->expr()->eq('tagmap.type', 'tag.type'),
  143. $builder->expr()->eq('tagmap.categoryid', 'tag.id'),
  144. $builder->expr()->eq('tag.type', $builder->createNamedParameter('files')),
  145. $builder->expr()->eq('tag.uid', $builder->createNamedParameter($user->getUID()))
  146. ))
  147. ->leftJoin('file', 'systemtag_object_mapping', 'systemtagmap', $builder->expr()->andX(
  148. $builder->expr()->eq('file.fileid', $builder->expr()->castColumn('systemtagmap.objectid', IQueryBuilder::PARAM_INT)),
  149. $builder->expr()->eq('systemtagmap.objecttype', $builder->createNamedParameter('files'))
  150. ))
  151. ->leftJoin('systemtagmap', 'systemtag', 'systemtag', $builder->expr()->andX(
  152. $builder->expr()->eq('systemtag.id', 'systemtagmap.systemtagid'),
  153. $builder->expr()->eq('systemtag.visibility', $builder->createNamedParameter(true))
  154. ));
  155. }
  156. $this->applySearchConstraints($query, $searchQuery, $caches);
  157. $result = $query->execute();
  158. $files = $result->fetchAll();
  159. $rawEntries = array_map(function (array $data) {
  160. return Cache::cacheEntryFromData($data, $this->mimetypeLoader);
  161. }, $files);
  162. $result->closeCursor();
  163. // loop through all caches for each result to see if the result matches that storage
  164. // results are grouped by the same array keys as the caches argument to allow the caller to distinguish the source of the results
  165. $results = array_fill_keys(array_keys($caches), []);
  166. foreach ($rawEntries as $rawEntry) {
  167. foreach ($caches as $cacheKey => $cache) {
  168. $entry = $cache->getCacheEntryFromSearchResult($rawEntry);
  169. if ($entry) {
  170. $results[$cacheKey][] = $entry;
  171. }
  172. }
  173. }
  174. return $results;
  175. }
  176. /**
  177. * @return array{array<string, ICache>, array<string, IMountPoint>}
  178. */
  179. public function getCachesAndMountPointsForSearch(Root $root, string $path, bool $limitToHome = false): array {
  180. $rootLength = strlen($path);
  181. $mount = $root->getMount($path);
  182. $storage = $mount->getStorage();
  183. $internalPath = $mount->getInternalPath($path);
  184. if ($internalPath !== '') {
  185. // a temporary CacheJail is used to handle filtering down the results to within this folder
  186. $caches = ['' => new CacheJail($storage->getCache(''), $internalPath)];
  187. } else {
  188. $caches = ['' => $storage->getCache('')];
  189. }
  190. $mountByMountPoint = ['' => $mount];
  191. if (!$limitToHome) {
  192. /** @var IMountPoint[] $mounts */
  193. $mounts = $root->getMountsIn($path);
  194. foreach ($mounts as $mount) {
  195. $storage = $mount->getStorage();
  196. if ($storage) {
  197. $relativeMountPoint = ltrim(substr($mount->getMountPoint(), $rootLength), '/');
  198. $caches[$relativeMountPoint] = $storage->getCache('');
  199. $mountByMountPoint[$relativeMountPoint] = $mount;
  200. }
  201. }
  202. }
  203. return [$caches, $mountByMountPoint];
  204. }
  205. }