Manager.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2018 Joas Schilling <coding@schilljs.com>
  5. *
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Julius Härtl <jus@bitgrid.net>
  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\Collaboration\Resources;
  27. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  28. use OCP\Collaboration\Resources\CollectionException;
  29. use OCP\Collaboration\Resources\ICollection;
  30. use OCP\Collaboration\Resources\IManager;
  31. use OCP\Collaboration\Resources\IProvider;
  32. use OCP\Collaboration\Resources\IProviderManager;
  33. use OCP\Collaboration\Resources\IResource;
  34. use OCP\Collaboration\Resources\ResourceException;
  35. use OCP\DB\QueryBuilder\IQueryBuilder;
  36. use OCP\IDBConnection;
  37. use OCP\IUser;
  38. use Psr\Log\LoggerInterface;
  39. class Manager implements IManager {
  40. public const TABLE_COLLECTIONS = 'collres_collections';
  41. public const TABLE_RESOURCES = 'collres_resources';
  42. public const TABLE_ACCESS_CACHE = 'collres_accesscache';
  43. /** @var string[] */
  44. protected array $providers = [];
  45. public function __construct(
  46. protected IDBConnection $connection,
  47. protected IProviderManager $providerManager,
  48. protected LoggerInterface $logger,
  49. ) {
  50. }
  51. /**
  52. * @throws CollectionException when the collection could not be found
  53. * @since 16.0.0
  54. */
  55. public function getCollection(int $id): ICollection {
  56. $query = $this->connection->getQueryBuilder();
  57. $query->select('*')
  58. ->from(self::TABLE_COLLECTIONS)
  59. ->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  60. $result = $query->execute();
  61. $row = $result->fetch();
  62. $result->closeCursor();
  63. if (!$row) {
  64. throw new CollectionException('Collection not found');
  65. }
  66. return new Collection($this, $this->connection, (int) $row['id'], (string) $row['name']);
  67. }
  68. /**
  69. * @throws CollectionException when the collection could not be found
  70. * @since 16.0.0
  71. */
  72. public function getCollectionForUser(int $id, ?IUser $user): ICollection {
  73. $query = $this->connection->getQueryBuilder();
  74. $userId = $user instanceof IUser ? $user->getUID() : '';
  75. $query->select('*')
  76. ->from(self::TABLE_COLLECTIONS, 'c')
  77. ->leftJoin(
  78. 'c', self::TABLE_ACCESS_CACHE, 'a',
  79. $query->expr()->andX(
  80. $query->expr()->eq('c.id', 'a.collection_id'),
  81. $query->expr()->eq('a.user_id', $query->createNamedParameter($userId, IQueryBuilder::PARAM_STR))
  82. )
  83. )
  84. ->where($query->expr()->eq('c.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  85. $result = $query->execute();
  86. $row = $result->fetch();
  87. $result->closeCursor();
  88. if (!$row) {
  89. throw new CollectionException('Collection not found');
  90. }
  91. $access = $row['access'] === null ? null : (bool) $row['access'];
  92. if ($user instanceof IUser) {
  93. return new Collection($this, $this->connection, (int) $row['id'], (string) $row['name'], $user, $access);
  94. }
  95. return new Collection($this, $this->connection, (int) $row['id'], (string) $row['name'], $user, $access);
  96. }
  97. /**
  98. * @return ICollection[]
  99. * @since 16.0.0
  100. */
  101. public function searchCollections(IUser $user, string $filter, int $limit = 50, int $start = 0): array {
  102. $query = $this->connection->getQueryBuilder();
  103. $userId = $user->getUID();
  104. $query->select('c.*', 'a.access')
  105. ->from(self::TABLE_COLLECTIONS, 'c')
  106. ->leftJoin(
  107. 'c', self::TABLE_ACCESS_CACHE, 'a',
  108. $query->expr()->andX(
  109. $query->expr()->eq('c.id', 'a.collection_id'),
  110. $query->expr()->eq('a.user_id', $query->createNamedParameter($userId, IQueryBuilder::PARAM_STR))
  111. )
  112. )
  113. ->where($query->expr()->eq('a.access', $query->createNamedParameter(1, IQueryBuilder::PARAM_INT)))
  114. ->orderBy('c.id')
  115. ->setMaxResults($limit)
  116. ->setFirstResult($start);
  117. if ($filter !== '') {
  118. $query->andWhere($query->expr()->iLike('c.name', $query->createNamedParameter('%' . $this->connection->escapeLikeParameter($filter) . '%')));
  119. }
  120. $result = $query->execute();
  121. $collections = [];
  122. $foundResults = 0;
  123. while ($row = $result->fetch()) {
  124. $foundResults++;
  125. $access = $row['access'] === null ? null : (bool) $row['access'];
  126. $collection = new Collection($this, $this->connection, (int)$row['id'], (string)$row['name'], $user, $access);
  127. if ($collection->canAccess($user)) {
  128. $collections[] = $collection;
  129. }
  130. }
  131. $result->closeCursor();
  132. if (empty($collections) && $foundResults === $limit) {
  133. return $this->searchCollections($user, $filter, $limit, $start + $limit);
  134. }
  135. return $collections;
  136. }
  137. /**
  138. * @since 16.0.0
  139. */
  140. public function newCollection(string $name): ICollection {
  141. $query = $this->connection->getQueryBuilder();
  142. $query->insert(self::TABLE_COLLECTIONS)
  143. ->values([
  144. 'name' => $query->createNamedParameter($name),
  145. ]);
  146. $query->execute();
  147. return new Collection($this, $this->connection, $query->getLastInsertId(), $name);
  148. }
  149. /**
  150. * @since 16.0.0
  151. */
  152. public function createResource(string $type, string $id): IResource {
  153. return new Resource($this, $this->connection, $type, $id);
  154. }
  155. /**
  156. * @throws ResourceException
  157. * @since 16.0.0
  158. */
  159. public function getResourceForUser(string $type, string $id, ?IUser $user): IResource {
  160. $query = $this->connection->getQueryBuilder();
  161. $userId = $user instanceof IUser ? $user->getUID() : '';
  162. $query->select('r.*', 'a.access')
  163. ->from(self::TABLE_RESOURCES, 'r')
  164. ->leftJoin(
  165. 'r', self::TABLE_ACCESS_CACHE, 'a',
  166. $query->expr()->andX(
  167. $query->expr()->eq('r.resource_id', 'a.resource_id'),
  168. $query->expr()->eq('r.resource_type', 'a.resource_type'),
  169. $query->expr()->eq('a.user_id', $query->createNamedParameter($userId, IQueryBuilder::PARAM_STR))
  170. )
  171. )
  172. ->where($query->expr()->eq('r.resource_type', $query->createNamedParameter($type, IQueryBuilder::PARAM_STR)))
  173. ->andWhere($query->expr()->eq('r.resource_id', $query->createNamedParameter($id, IQueryBuilder::PARAM_STR)));
  174. $result = $query->execute();
  175. $row = $result->fetch();
  176. $result->closeCursor();
  177. if (!$row) {
  178. throw new ResourceException('Resource not found');
  179. }
  180. $access = $row['access'] === null ? null : (bool) $row['access'];
  181. if ($user instanceof IUser) {
  182. return new Resource($this, $this->connection, $type, $id, $user, $access);
  183. }
  184. return new Resource($this, $this->connection, $type, $id, null, $access);
  185. }
  186. /**
  187. * @return IResource[]
  188. * @since 16.0.0
  189. */
  190. public function getResourcesByCollectionForUser(ICollection $collection, ?IUser $user): array {
  191. $query = $this->connection->getQueryBuilder();
  192. $userId = $user instanceof IUser ? $user->getUID() : '';
  193. $query->select('r.*', 'a.access')
  194. ->from(self::TABLE_RESOURCES, 'r')
  195. ->leftJoin(
  196. 'r', self::TABLE_ACCESS_CACHE, 'a',
  197. $query->expr()->andX(
  198. $query->expr()->eq('r.resource_id', 'a.resource_id'),
  199. $query->expr()->eq('r.resource_type', 'a.resource_type'),
  200. $query->expr()->eq('a.user_id', $query->createNamedParameter($userId, IQueryBuilder::PARAM_STR))
  201. )
  202. )
  203. ->where($query->expr()->eq('r.collection_id', $query->createNamedParameter($collection->getId(), IQueryBuilder::PARAM_INT)));
  204. $resources = [];
  205. $result = $query->execute();
  206. while ($row = $result->fetch()) {
  207. $access = $row['access'] === null ? null : (bool) $row['access'];
  208. $resources[] = new Resource($this, $this->connection, $row['resource_type'], $row['resource_id'], $user, $access);
  209. }
  210. $result->closeCursor();
  211. return $resources;
  212. }
  213. /**
  214. * Get the rich object data of a resource
  215. *
  216. * @since 16.0.0
  217. */
  218. public function getResourceRichObject(IResource $resource): array {
  219. foreach ($this->providerManager->getResourceProviders() as $provider) {
  220. if ($provider->getType() === $resource->getType()) {
  221. try {
  222. return $provider->getResourceRichObject($resource);
  223. } catch (ResourceException $e) {
  224. }
  225. }
  226. }
  227. return [];
  228. }
  229. /**
  230. * Can a user/guest access the collection
  231. *
  232. * @since 16.0.0
  233. */
  234. public function canAccessResource(IResource $resource, ?IUser $user): bool {
  235. $access = $this->checkAccessCacheForUserByResource($resource, $user);
  236. if (\is_bool($access)) {
  237. return $access;
  238. }
  239. $access = false;
  240. foreach ($this->providerManager->getResourceProviders() as $provider) {
  241. if ($provider->getType() === $resource->getType()) {
  242. try {
  243. if ($provider->canAccessResource($resource, $user)) {
  244. $access = true;
  245. break;
  246. }
  247. } catch (ResourceException $e) {
  248. }
  249. }
  250. }
  251. $this->cacheAccessForResource($resource, $user, $access);
  252. return $access;
  253. }
  254. /**
  255. * Can a user/guest access the collection
  256. *
  257. * @since 16.0.0
  258. */
  259. public function canAccessCollection(ICollection $collection, ?IUser $user): bool {
  260. $access = $this->checkAccessCacheForUserByCollection($collection, $user);
  261. if (\is_bool($access)) {
  262. return $access;
  263. }
  264. $access = null;
  265. // Access is granted when a user can access all resources
  266. foreach ($collection->getResources() as $resource) {
  267. if (!$resource->canAccess($user)) {
  268. $access = false;
  269. break;
  270. }
  271. $access = true;
  272. }
  273. $this->cacheAccessForCollection($collection, $user, $access);
  274. return $access;
  275. }
  276. protected function checkAccessCacheForUserByResource(IResource $resource, ?IUser $user): ?bool {
  277. $query = $this->connection->getQueryBuilder();
  278. $userId = $user instanceof IUser ? $user->getUID() : '';
  279. $query->select('access')
  280. ->from(self::TABLE_ACCESS_CACHE)
  281. ->where($query->expr()->eq('resource_id', $query->createNamedParameter($resource->getId(), IQueryBuilder::PARAM_STR)))
  282. ->andWhere($query->expr()->eq('resource_type', $query->createNamedParameter($resource->getType(), IQueryBuilder::PARAM_STR)))
  283. ->andWhere($query->expr()->eq('user_id', $query->createNamedParameter($userId, IQueryBuilder::PARAM_STR)))
  284. ->setMaxResults(1);
  285. $hasAccess = null;
  286. $result = $query->execute();
  287. if ($row = $result->fetch()) {
  288. $hasAccess = (bool) $row['access'];
  289. }
  290. $result->closeCursor();
  291. return $hasAccess;
  292. }
  293. protected function checkAccessCacheForUserByCollection(ICollection $collection, ?IUser $user): ?bool {
  294. $query = $this->connection->getQueryBuilder();
  295. $userId = $user instanceof IUser ? $user->getUID() : '';
  296. $query->select('access')
  297. ->from(self::TABLE_ACCESS_CACHE)
  298. ->where($query->expr()->eq('collection_id', $query->createNamedParameter($collection->getId(), IQueryBuilder::PARAM_INT)))
  299. ->andWhere($query->expr()->eq('user_id', $query->createNamedParameter($userId, IQueryBuilder::PARAM_STR)))
  300. ->setMaxResults(1);
  301. $hasAccess = null;
  302. $result = $query->execute();
  303. if ($row = $result->fetch()) {
  304. $hasAccess = (bool) $row['access'];
  305. }
  306. $result->closeCursor();
  307. return $hasAccess;
  308. }
  309. public function cacheAccessForResource(IResource $resource, ?IUser $user, bool $access): void {
  310. $query = $this->connection->getQueryBuilder();
  311. $userId = $user instanceof IUser ? $user->getUID() : '';
  312. $query->insert(self::TABLE_ACCESS_CACHE)
  313. ->values([
  314. 'user_id' => $query->createNamedParameter($userId),
  315. 'resource_id' => $query->createNamedParameter($resource->getId()),
  316. 'resource_type' => $query->createNamedParameter($resource->getType()),
  317. 'access' => $query->createNamedParameter($access, IQueryBuilder::PARAM_BOOL),
  318. ]);
  319. try {
  320. $query->execute();
  321. } catch (UniqueConstraintViolationException $e) {
  322. }
  323. }
  324. public function cacheAccessForCollection(ICollection $collection, ?IUser $user, bool $access): void {
  325. $query = $this->connection->getQueryBuilder();
  326. $userId = $user instanceof IUser ? $user->getUID() : '';
  327. $query->insert(self::TABLE_ACCESS_CACHE)
  328. ->values([
  329. 'user_id' => $query->createNamedParameter($userId),
  330. 'collection_id' => $query->createNamedParameter($collection->getId()),
  331. 'access' => $query->createNamedParameter($access, IQueryBuilder::PARAM_BOOL),
  332. ]);
  333. try {
  334. $query->execute();
  335. } catch (UniqueConstraintViolationException $e) {
  336. }
  337. }
  338. public function invalidateAccessCacheForUser(?IUser $user): void {
  339. $query = $this->connection->getQueryBuilder();
  340. $userId = $user instanceof IUser ? $user->getUID() : '';
  341. $query->delete(self::TABLE_ACCESS_CACHE)
  342. ->where($query->expr()->eq('user_id', $query->createNamedParameter($userId)));
  343. $query->execute();
  344. }
  345. public function invalidateAccessCacheForResource(IResource $resource): void {
  346. $query = $this->connection->getQueryBuilder();
  347. $query->delete(self::TABLE_ACCESS_CACHE)
  348. ->where($query->expr()->eq('resource_id', $query->createNamedParameter($resource->getId())))
  349. ->andWhere($query->expr()->eq('resource_type', $query->createNamedParameter($resource->getType(), IQueryBuilder::PARAM_STR)));
  350. $query->execute();
  351. foreach ($resource->getCollections() as $collection) {
  352. $this->invalidateAccessCacheForCollection($collection);
  353. }
  354. }
  355. public function invalidateAccessCacheForAllCollections(): void {
  356. $query = $this->connection->getQueryBuilder();
  357. $query->delete(self::TABLE_ACCESS_CACHE)
  358. ->where($query->expr()->neq('collection_id', $query->createNamedParameter(0)));
  359. $query->execute();
  360. }
  361. public function invalidateAccessCacheForCollection(ICollection $collection): void {
  362. $query = $this->connection->getQueryBuilder();
  363. $query->delete(self::TABLE_ACCESS_CACHE)
  364. ->where($query->expr()->eq('collection_id', $query->createNamedParameter($collection->getId())));
  365. $query->execute();
  366. }
  367. public function invalidateAccessCacheForProvider(IProvider $provider): void {
  368. $query = $this->connection->getQueryBuilder();
  369. $query->delete(self::TABLE_ACCESS_CACHE)
  370. ->where($query->expr()->eq('resource_type', $query->createNamedParameter($provider->getType(), IQueryBuilder::PARAM_STR)));
  371. $query->execute();
  372. }
  373. public function invalidateAccessCacheForResourceByUser(IResource $resource, ?IUser $user): void {
  374. $query = $this->connection->getQueryBuilder();
  375. $userId = $user instanceof IUser ? $user->getUID() : '';
  376. $query->delete(self::TABLE_ACCESS_CACHE)
  377. ->where($query->expr()->eq('resource_id', $query->createNamedParameter($resource->getId())))
  378. ->andWhere($query->expr()->eq('user_id', $query->createNamedParameter($userId)));
  379. $query->execute();
  380. foreach ($resource->getCollections() as $collection) {
  381. $this->invalidateAccessCacheForCollectionByUser($collection, $user);
  382. }
  383. }
  384. protected function invalidateAccessCacheForCollectionByUser(ICollection $collection, ?IUser $user): void {
  385. $query = $this->connection->getQueryBuilder();
  386. $userId = $user instanceof IUser ? $user->getUID() : '';
  387. $query->delete(self::TABLE_ACCESS_CACHE)
  388. ->where($query->expr()->eq('collection_id', $query->createNamedParameter($collection->getId())))
  389. ->andWhere($query->expr()->eq('user_id', $query->createNamedParameter($userId)));
  390. $query->execute();
  391. }
  392. public function invalidateAccessCacheForProviderByUser(IProvider $provider, ?IUser $user): void {
  393. $query = $this->connection->getQueryBuilder();
  394. $userId = $user instanceof IUser ? $user->getUID() : '';
  395. $query->delete(self::TABLE_ACCESS_CACHE)
  396. ->where($query->expr()->eq('resource_type', $query->createNamedParameter($provider->getType(), IQueryBuilder::PARAM_STR)))
  397. ->andWhere($query->expr()->eq('user_id', $query->createNamedParameter($userId)));
  398. $query->execute();
  399. }
  400. public function registerResourceProvider(string $provider): void {
  401. $this->logger->debug('\OC\Collaboration\Resources\Manager::registerResourceProvider is deprecated', ['provider' => $provider]);
  402. $this->providerManager->registerResourceProvider($provider);
  403. }
  404. /**
  405. * Get the resource type of the provider
  406. *
  407. * @since 16.0.0
  408. */
  409. public function getType(): string {
  410. return '';
  411. }
  412. }