Manager.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016 Morris Jobke <hey@morrisjobke.de>
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author blizzz <blizzz@arthur-schiwon.de>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Julius Härtl <jus@bitgrid.net>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. *
  14. * @license GNU AGPL version 3 or any later version
  15. *
  16. * This program is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License as
  18. * published by the Free Software Foundation, either version 3 of the
  19. * License, or (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  28. *
  29. */
  30. namespace OCA\WorkflowEngine;
  31. use Doctrine\DBAL\Exception;
  32. use OCP\Cache\CappedMemoryCache;
  33. use OCA\WorkflowEngine\AppInfo\Application;
  34. use OCA\WorkflowEngine\Check\FileMimeType;
  35. use OCA\WorkflowEngine\Check\FileName;
  36. use OCA\WorkflowEngine\Check\FileSize;
  37. use OCA\WorkflowEngine\Check\FileSystemTags;
  38. use OCA\WorkflowEngine\Check\RequestRemoteAddress;
  39. use OCA\WorkflowEngine\Check\RequestTime;
  40. use OCA\WorkflowEngine\Check\RequestURL;
  41. use OCA\WorkflowEngine\Check\RequestUserAgent;
  42. use OCA\WorkflowEngine\Check\UserGroupMembership;
  43. use OCA\WorkflowEngine\Entity\File;
  44. use OCA\WorkflowEngine\Helper\ScopeContext;
  45. use OCA\WorkflowEngine\Service\Logger;
  46. use OCA\WorkflowEngine\Service\RuleMatcher;
  47. use OCP\AppFramework\QueryException;
  48. use OCP\DB\QueryBuilder\IQueryBuilder;
  49. use OCP\EventDispatcher\IEventDispatcher;
  50. use OCP\Files\Storage\IStorage;
  51. use OCP\ICacheFactory;
  52. use OCP\IConfig;
  53. use OCP\IDBConnection;
  54. use OCP\IL10N;
  55. use OCP\ILogger;
  56. use OCP\IServerContainer;
  57. use OCP\IUserSession;
  58. use OCP\WorkflowEngine\Events\RegisterChecksEvent;
  59. use OCP\WorkflowEngine\Events\RegisterEntitiesEvent;
  60. use OCP\WorkflowEngine\Events\RegisterOperationsEvent;
  61. use OCP\WorkflowEngine\ICheck;
  62. use OCP\WorkflowEngine\IComplexOperation;
  63. use OCP\WorkflowEngine\IEntity;
  64. use OCP\WorkflowEngine\IEntityEvent;
  65. use OCP\WorkflowEngine\IManager;
  66. use OCP\WorkflowEngine\IOperation;
  67. use OCP\WorkflowEngine\IRuleMatcher;
  68. use Symfony\Component\EventDispatcher\EventDispatcherInterface as LegacyDispatcher;
  69. use Symfony\Component\EventDispatcher\GenericEvent;
  70. class Manager implements IManager {
  71. /** @var IStorage */
  72. protected $storage;
  73. /** @var string */
  74. protected $path;
  75. /** @var object */
  76. protected $entity;
  77. /** @var array[] */
  78. protected $operations = [];
  79. /** @var array[] */
  80. protected $checks = [];
  81. /** @var IDBConnection */
  82. protected $connection;
  83. /** @var IServerContainer|\OC\Server */
  84. protected $container;
  85. /** @var IL10N */
  86. protected $l;
  87. /** @var LegacyDispatcher */
  88. protected $legacyEventDispatcher;
  89. /** @var IEntity[] */
  90. protected $registeredEntities = [];
  91. /** @var IOperation[] */
  92. protected $registeredOperators = [];
  93. /** @var ICheck[] */
  94. protected $registeredChecks = [];
  95. /** @var ILogger */
  96. protected $logger;
  97. /** @var CappedMemoryCache<int[]> */
  98. protected CappedMemoryCache $operationsByScope;
  99. /** @var IUserSession */
  100. protected $session;
  101. /** @var IEventDispatcher */
  102. private $dispatcher;
  103. /** @var IConfig */
  104. private $config;
  105. private ICacheFactory $cacheFactory;
  106. public function __construct(
  107. IDBConnection $connection,
  108. IServerContainer $container,
  109. IL10N $l,
  110. LegacyDispatcher $eventDispatcher,
  111. ILogger $logger,
  112. IUserSession $session,
  113. IEventDispatcher $dispatcher,
  114. IConfig $config,
  115. ICacheFactory $cacheFactory,
  116. ) {
  117. $this->connection = $connection;
  118. $this->container = $container;
  119. $this->l = $l;
  120. $this->legacyEventDispatcher = $eventDispatcher;
  121. $this->logger = $logger;
  122. $this->operationsByScope = new CappedMemoryCache(64);
  123. $this->session = $session;
  124. $this->dispatcher = $dispatcher;
  125. $this->config = $config;
  126. $this->cacheFactory = $cacheFactory;
  127. }
  128. public function getRuleMatcher(): IRuleMatcher {
  129. return new RuleMatcher(
  130. $this->session,
  131. $this->container,
  132. $this->l,
  133. $this,
  134. $this->container->query(Logger::class)
  135. );
  136. }
  137. public function getAllConfiguredEvents() {
  138. $cache = $this->cacheFactory->createDistributed('flow');
  139. $cached = $cache->get('events');
  140. if ($cached !== null) {
  141. return $cached;
  142. }
  143. $query = $this->connection->getQueryBuilder();
  144. $query->select('class', 'entity')
  145. ->selectAlias($query->expr()->castColumn('events', IQueryBuilder::PARAM_STR), 'events')
  146. ->from('flow_operations')
  147. ->where($query->expr()->neq('events', $query->createNamedParameter('[]'), IQueryBuilder::PARAM_STR))
  148. ->groupBy('class', 'entity', $query->expr()->castColumn('events', IQueryBuilder::PARAM_STR));
  149. $result = $query->execute();
  150. $operations = [];
  151. while ($row = $result->fetch()) {
  152. $eventNames = \json_decode($row['events']);
  153. $operation = $row['class'];
  154. $entity = $row['entity'];
  155. $operations[$operation] = $operations[$row['class']] ?? [];
  156. $operations[$operation][$entity] = $operations[$operation][$entity] ?? [];
  157. $operations[$operation][$entity] = array_unique(array_merge($operations[$operation][$entity], $eventNames ?? []));
  158. }
  159. $result->closeCursor();
  160. $cache->set('events', $operations, 3600);
  161. return $operations;
  162. }
  163. /**
  164. * @param string $operationClass
  165. * @return ScopeContext[]
  166. */
  167. public function getAllConfiguredScopesForOperation(string $operationClass): array {
  168. static $scopesByOperation = [];
  169. if (isset($scopesByOperation[$operationClass])) {
  170. return $scopesByOperation[$operationClass];
  171. }
  172. $query = $this->connection->getQueryBuilder();
  173. $query->selectDistinct('s.type')
  174. ->addSelect('s.value')
  175. ->from('flow_operations', 'o')
  176. ->leftJoin('o', 'flow_operations_scope', 's', $query->expr()->eq('o.id', 's.operation_id'))
  177. ->where($query->expr()->eq('o.class', $query->createParameter('operationClass')));
  178. $query->setParameters(['operationClass' => $operationClass]);
  179. $result = $query->execute();
  180. $scopesByOperation[$operationClass] = [];
  181. while ($row = $result->fetch()) {
  182. $scope = new ScopeContext($row['type'], $row['value']);
  183. $scopesByOperation[$operationClass][$scope->getHash()] = $scope;
  184. }
  185. return $scopesByOperation[$operationClass];
  186. }
  187. public function getAllOperations(ScopeContext $scopeContext): array {
  188. if (isset($this->operations[$scopeContext->getHash()])) {
  189. return $this->operations[$scopeContext->getHash()];
  190. }
  191. $query = $this->connection->getQueryBuilder();
  192. $query->select('o.*')
  193. ->selectAlias('s.type', 'scope_type')
  194. ->selectAlias('s.value', 'scope_actor_id')
  195. ->from('flow_operations', 'o')
  196. ->leftJoin('o', 'flow_operations_scope', 's', $query->expr()->eq('o.id', 's.operation_id'))
  197. ->where($query->expr()->eq('s.type', $query->createParameter('scope')));
  198. if ($scopeContext->getScope() === IManager::SCOPE_USER) {
  199. $query->andWhere($query->expr()->eq('s.value', $query->createParameter('scopeId')));
  200. }
  201. $query->setParameters(['scope' => $scopeContext->getScope(), 'scopeId' => $scopeContext->getScopeId()]);
  202. $result = $query->execute();
  203. $this->operations[$scopeContext->getHash()] = [];
  204. while ($row = $result->fetch()) {
  205. if (!isset($this->operations[$scopeContext->getHash()][$row['class']])) {
  206. $this->operations[$scopeContext->getHash()][$row['class']] = [];
  207. }
  208. $this->operations[$scopeContext->getHash()][$row['class']][] = $row;
  209. }
  210. return $this->operations[$scopeContext->getHash()];
  211. }
  212. public function getOperations(string $class, ScopeContext $scopeContext): array {
  213. if (!isset($this->operations[$scopeContext->getHash()])) {
  214. $this->getAllOperations($scopeContext);
  215. }
  216. return $this->operations[$scopeContext->getHash()][$class] ?? [];
  217. }
  218. /**
  219. * @param int $id
  220. * @return array
  221. * @throws \UnexpectedValueException
  222. */
  223. protected function getOperation($id) {
  224. $query = $this->connection->getQueryBuilder();
  225. $query->select('*')
  226. ->from('flow_operations')
  227. ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
  228. $result = $query->execute();
  229. $row = $result->fetch();
  230. $result->closeCursor();
  231. if ($row) {
  232. return $row;
  233. }
  234. throw new \UnexpectedValueException($this->l->t('Operation #%s does not exist', [$id]));
  235. }
  236. protected function insertOperation(
  237. string $class,
  238. string $name,
  239. array $checkIds,
  240. string $operation,
  241. string $entity,
  242. array $events
  243. ): int {
  244. $query = $this->connection->getQueryBuilder();
  245. $query->insert('flow_operations')
  246. ->values([
  247. 'class' => $query->createNamedParameter($class),
  248. 'name' => $query->createNamedParameter($name),
  249. 'checks' => $query->createNamedParameter(json_encode(array_unique($checkIds))),
  250. 'operation' => $query->createNamedParameter($operation),
  251. 'entity' => $query->createNamedParameter($entity),
  252. 'events' => $query->createNamedParameter(json_encode($events))
  253. ]);
  254. $query->execute();
  255. $this->cacheFactory->createDistributed('flow')->remove('events');
  256. return $query->getLastInsertId();
  257. }
  258. /**
  259. * @param string $class
  260. * @param string $name
  261. * @param array[] $checks
  262. * @param string $operation
  263. * @return array The added operation
  264. * @throws \UnexpectedValueException
  265. * @throw Exception
  266. */
  267. public function addOperation(
  268. string $class,
  269. string $name,
  270. array $checks,
  271. string $operation,
  272. ScopeContext $scope,
  273. string $entity,
  274. array $events
  275. ) {
  276. $this->validateOperation($class, $name, $checks, $operation, $entity, $events);
  277. $this->connection->beginTransaction();
  278. try {
  279. $checkIds = [];
  280. foreach ($checks as $check) {
  281. $checkIds[] = $this->addCheck($check['class'], $check['operator'], $check['value']);
  282. }
  283. $id = $this->insertOperation($class, $name, $checkIds, $operation, $entity, $events);
  284. $this->addScope($id, $scope);
  285. $this->connection->commit();
  286. } catch (Exception $e) {
  287. $this->connection->rollBack();
  288. throw $e;
  289. }
  290. return $this->getOperation($id);
  291. }
  292. protected function canModify(int $id, ScopeContext $scopeContext):bool {
  293. if (isset($this->operationsByScope[$scopeContext->getHash()])) {
  294. return in_array($id, $this->operationsByScope[$scopeContext->getHash()], true);
  295. }
  296. $qb = $this->connection->getQueryBuilder();
  297. $qb = $qb->select('o.id')
  298. ->from('flow_operations', 'o')
  299. ->leftJoin('o', 'flow_operations_scope', 's', $qb->expr()->eq('o.id', 's.operation_id'))
  300. ->where($qb->expr()->eq('s.type', $qb->createParameter('scope')));
  301. if ($scopeContext->getScope() !== IManager::SCOPE_ADMIN) {
  302. $qb->where($qb->expr()->eq('s.value', $qb->createParameter('scopeId')));
  303. }
  304. $qb->setParameters(['scope' => $scopeContext->getScope(), 'scopeId' => $scopeContext->getScopeId()]);
  305. $result = $qb->execute();
  306. $operations = [];
  307. while (($opId = $result->fetchOne()) !== false) {
  308. $operations[] = (int)$opId;
  309. }
  310. $this->operationsByScope[$scopeContext->getHash()] = $operations;
  311. $result->closeCursor();
  312. return in_array($id, $this->operationsByScope[$scopeContext->getHash()], true);
  313. }
  314. /**
  315. * @param int $id
  316. * @param string $name
  317. * @param array[] $checks
  318. * @param string $operation
  319. * @return array The updated operation
  320. * @throws \UnexpectedValueException
  321. * @throws \DomainException
  322. * @throws Exception
  323. */
  324. public function updateOperation(
  325. int $id,
  326. string $name,
  327. array $checks,
  328. string $operation,
  329. ScopeContext $scopeContext,
  330. string $entity,
  331. array $events
  332. ): array {
  333. if (!$this->canModify($id, $scopeContext)) {
  334. throw new \DomainException('Target operation not within scope');
  335. };
  336. $row = $this->getOperation($id);
  337. $this->validateOperation($row['class'], $name, $checks, $operation, $entity, $events);
  338. $checkIds = [];
  339. try {
  340. $this->connection->beginTransaction();
  341. foreach ($checks as $check) {
  342. $checkIds[] = $this->addCheck($check['class'], $check['operator'], $check['value']);
  343. }
  344. $query = $this->connection->getQueryBuilder();
  345. $query->update('flow_operations')
  346. ->set('name', $query->createNamedParameter($name))
  347. ->set('checks', $query->createNamedParameter(json_encode(array_unique($checkIds))))
  348. ->set('operation', $query->createNamedParameter($operation))
  349. ->set('entity', $query->createNamedParameter($entity))
  350. ->set('events', $query->createNamedParameter(json_encode($events)))
  351. ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
  352. $query->execute();
  353. $this->connection->commit();
  354. } catch (Exception $e) {
  355. $this->connection->rollBack();
  356. throw $e;
  357. }
  358. unset($this->operations[$scopeContext->getHash()]);
  359. $this->cacheFactory->createDistributed('flow')->remove('events');
  360. return $this->getOperation($id);
  361. }
  362. /**
  363. * @param int $id
  364. * @return bool
  365. * @throws \UnexpectedValueException
  366. * @throws Exception
  367. * @throws \DomainException
  368. */
  369. public function deleteOperation($id, ScopeContext $scopeContext) {
  370. if (!$this->canModify($id, $scopeContext)) {
  371. throw new \DomainException('Target operation not within scope');
  372. };
  373. $query = $this->connection->getQueryBuilder();
  374. try {
  375. $this->connection->beginTransaction();
  376. $result = (bool)$query->delete('flow_operations')
  377. ->where($query->expr()->eq('id', $query->createNamedParameter($id)))
  378. ->execute();
  379. if ($result) {
  380. $qb = $this->connection->getQueryBuilder();
  381. $result &= (bool)$qb->delete('flow_operations_scope')
  382. ->where($qb->expr()->eq('operation_id', $qb->createNamedParameter($id)))
  383. ->execute();
  384. }
  385. $this->connection->commit();
  386. } catch (Exception $e) {
  387. $this->connection->rollBack();
  388. throw $e;
  389. }
  390. if (isset($this->operations[$scopeContext->getHash()])) {
  391. unset($this->operations[$scopeContext->getHash()]);
  392. }
  393. $this->cacheFactory->createDistributed('flow')->remove('events');
  394. return $result;
  395. }
  396. protected function validateEvents(string $entity, array $events, IOperation $operation) {
  397. try {
  398. /** @var IEntity $instance */
  399. $instance = $this->container->query($entity);
  400. } catch (QueryException $e) {
  401. throw new \UnexpectedValueException($this->l->t('Entity %s does not exist', [$entity]));
  402. }
  403. if (!$instance instanceof IEntity) {
  404. throw new \UnexpectedValueException($this->l->t('Entity %s is invalid', [$entity]));
  405. }
  406. if (empty($events)) {
  407. if (!$operation instanceof IComplexOperation) {
  408. throw new \UnexpectedValueException($this->l->t('No events are chosen.'));
  409. }
  410. return;
  411. }
  412. $availableEvents = [];
  413. foreach ($instance->getEvents() as $event) {
  414. /** @var IEntityEvent $event */
  415. $availableEvents[] = $event->getEventName();
  416. }
  417. $diff = array_diff($events, $availableEvents);
  418. if (!empty($diff)) {
  419. throw new \UnexpectedValueException($this->l->t('Entity %s has no event %s', [$entity, array_shift($diff)]));
  420. }
  421. }
  422. /**
  423. * @param string $class
  424. * @param string $name
  425. * @param array[] $checks
  426. * @param string $operation
  427. * @throws \UnexpectedValueException
  428. */
  429. public function validateOperation($class, $name, array $checks, $operation, string $entity, array $events) {
  430. try {
  431. /** @var IOperation $instance */
  432. $instance = $this->container->query($class);
  433. } catch (QueryException $e) {
  434. throw new \UnexpectedValueException($this->l->t('Operation %s does not exist', [$class]));
  435. }
  436. if (!($instance instanceof IOperation)) {
  437. throw new \UnexpectedValueException($this->l->t('Operation %s is invalid', [$class]));
  438. }
  439. $this->validateEvents($entity, $events, $instance);
  440. if (count($checks) === 0) {
  441. throw new \UnexpectedValueException($this->l->t('At least one check needs to be provided'));
  442. }
  443. if (strlen((string)$operation) > IManager::MAX_OPERATION_VALUE_BYTES) {
  444. throw new \UnexpectedValueException($this->l->t('The provided operation data is too long'));
  445. }
  446. $instance->validateOperation($name, $checks, $operation);
  447. foreach ($checks as $check) {
  448. if (!is_string($check['class'])) {
  449. throw new \UnexpectedValueException($this->l->t('Invalid check provided'));
  450. }
  451. try {
  452. /** @var ICheck $instance */
  453. $instance = $this->container->query($check['class']);
  454. } catch (QueryException $e) {
  455. throw new \UnexpectedValueException($this->l->t('Check %s does not exist', [$class]));
  456. }
  457. if (!($instance instanceof ICheck)) {
  458. throw new \UnexpectedValueException($this->l->t('Check %s is invalid', [$class]));
  459. }
  460. if (!empty($instance->supportedEntities())
  461. && !in_array($entity, $instance->supportedEntities())
  462. ) {
  463. throw new \UnexpectedValueException($this->l->t('Check %s is not allowed with this entity', [$class]));
  464. }
  465. if (strlen((string)$check['value']) > IManager::MAX_CHECK_VALUE_BYTES) {
  466. throw new \UnexpectedValueException($this->l->t('The provided check value is too long'));
  467. }
  468. $instance->validateCheck($check['operator'], $check['value']);
  469. }
  470. }
  471. /**
  472. * @param int[] $checkIds
  473. * @return array[]
  474. */
  475. public function getChecks(array $checkIds) {
  476. $checkIds = array_map('intval', $checkIds);
  477. $checks = [];
  478. foreach ($checkIds as $i => $checkId) {
  479. if (isset($this->checks[$checkId])) {
  480. $checks[$checkId] = $this->checks[$checkId];
  481. unset($checkIds[$i]);
  482. }
  483. }
  484. if (empty($checkIds)) {
  485. return $checks;
  486. }
  487. $query = $this->connection->getQueryBuilder();
  488. $query->select('*')
  489. ->from('flow_checks')
  490. ->where($query->expr()->in('id', $query->createNamedParameter($checkIds, IQueryBuilder::PARAM_INT_ARRAY)));
  491. $result = $query->execute();
  492. while ($row = $result->fetch()) {
  493. $this->checks[(int) $row['id']] = $row;
  494. $checks[(int) $row['id']] = $row;
  495. }
  496. $result->closeCursor();
  497. $checkIds = array_diff($checkIds, array_keys($checks));
  498. if (!empty($checkIds)) {
  499. $missingCheck = array_pop($checkIds);
  500. throw new \UnexpectedValueException($this->l->t('Check #%s does not exist', $missingCheck));
  501. }
  502. return $checks;
  503. }
  504. /**
  505. * @param string $class
  506. * @param string $operator
  507. * @param string $value
  508. * @return int Check unique ID
  509. */
  510. protected function addCheck($class, $operator, $value) {
  511. $hash = md5($class . '::' . $operator . '::' . $value);
  512. $query = $this->connection->getQueryBuilder();
  513. $query->select('id')
  514. ->from('flow_checks')
  515. ->where($query->expr()->eq('hash', $query->createNamedParameter($hash)));
  516. $result = $query->execute();
  517. if ($row = $result->fetch()) {
  518. $result->closeCursor();
  519. return (int) $row['id'];
  520. }
  521. $query = $this->connection->getQueryBuilder();
  522. $query->insert('flow_checks')
  523. ->values([
  524. 'class' => $query->createNamedParameter($class),
  525. 'operator' => $query->createNamedParameter($operator),
  526. 'value' => $query->createNamedParameter($value),
  527. 'hash' => $query->createNamedParameter($hash),
  528. ]);
  529. $query->execute();
  530. return $query->getLastInsertId();
  531. }
  532. protected function addScope(int $operationId, ScopeContext $scope): void {
  533. $query = $this->connection->getQueryBuilder();
  534. $insertQuery = $query->insert('flow_operations_scope');
  535. $insertQuery->values([
  536. 'operation_id' => $query->createNamedParameter($operationId),
  537. 'type' => $query->createNamedParameter($scope->getScope()),
  538. 'value' => $query->createNamedParameter($scope->getScopeId()),
  539. ]);
  540. $insertQuery->execute();
  541. }
  542. public function formatOperation(array $operation): array {
  543. $checkIds = json_decode($operation['checks'], true);
  544. $checks = $this->getChecks($checkIds);
  545. $operation['checks'] = [];
  546. foreach ($checks as $check) {
  547. // Remove internal values
  548. unset($check['id']);
  549. unset($check['hash']);
  550. $operation['checks'][] = $check;
  551. }
  552. $operation['events'] = json_decode($operation['events'], true) ?? [];
  553. return $operation;
  554. }
  555. /**
  556. * @return IEntity[]
  557. */
  558. public function getEntitiesList(): array {
  559. $this->dispatcher->dispatchTyped(new RegisterEntitiesEvent($this));
  560. $this->legacyEventDispatcher->dispatch(IManager::EVENT_NAME_REG_ENTITY, new GenericEvent($this));
  561. return array_values(array_merge($this->getBuildInEntities(), $this->registeredEntities));
  562. }
  563. /**
  564. * @return IOperation[]
  565. */
  566. public function getOperatorList(): array {
  567. $this->dispatcher->dispatchTyped(new RegisterOperationsEvent($this));
  568. $this->legacyEventDispatcher->dispatch(IManager::EVENT_NAME_REG_OPERATION, new GenericEvent($this));
  569. return array_merge($this->getBuildInOperators(), $this->registeredOperators);
  570. }
  571. /**
  572. * @return ICheck[]
  573. */
  574. public function getCheckList(): array {
  575. $this->dispatcher->dispatchTyped(new RegisterChecksEvent($this));
  576. $this->legacyEventDispatcher->dispatch(IManager::EVENT_NAME_REG_CHECK, new GenericEvent($this));
  577. return array_merge($this->getBuildInChecks(), $this->registeredChecks);
  578. }
  579. public function registerEntity(IEntity $entity): void {
  580. $this->registeredEntities[get_class($entity)] = $entity;
  581. }
  582. public function registerOperation(IOperation $operator): void {
  583. $this->registeredOperators[get_class($operator)] = $operator;
  584. }
  585. public function registerCheck(ICheck $check): void {
  586. $this->registeredChecks[get_class($check)] = $check;
  587. }
  588. /**
  589. * @return IEntity[]
  590. */
  591. protected function getBuildInEntities(): array {
  592. try {
  593. return [
  594. File::class => $this->container->query(File::class),
  595. ];
  596. } catch (QueryException $e) {
  597. $this->logger->logException($e);
  598. return [];
  599. }
  600. }
  601. /**
  602. * @return IOperation[]
  603. */
  604. protected function getBuildInOperators(): array {
  605. try {
  606. return [
  607. // None yet
  608. ];
  609. } catch (QueryException $e) {
  610. $this->logger->logException($e);
  611. return [];
  612. }
  613. }
  614. /**
  615. * @return ICheck[]
  616. */
  617. protected function getBuildInChecks(): array {
  618. try {
  619. return [
  620. $this->container->query(FileMimeType::class),
  621. $this->container->query(FileName::class),
  622. $this->container->query(FileSize::class),
  623. $this->container->query(FileSystemTags::class),
  624. $this->container->query(RequestRemoteAddress::class),
  625. $this->container->query(RequestTime::class),
  626. $this->container->query(RequestURL::class),
  627. $this->container->query(RequestUserAgent::class),
  628. $this->container->query(UserGroupMembership::class),
  629. ];
  630. } catch (QueryException $e) {
  631. $this->logger->logException($e);
  632. return [];
  633. }
  634. }
  635. public function isUserScopeEnabled(): bool {
  636. return $this->config->getAppValue(Application::APP_ID, 'user_scope_disabled', 'no') === 'no';
  637. }
  638. }