1
0

Manager.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  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. class Manager implements IManager {
  69. /** @var IStorage */
  70. protected $storage;
  71. /** @var string */
  72. protected $path;
  73. /** @var object */
  74. protected $entity;
  75. /** @var array[] */
  76. protected $operations = [];
  77. /** @var array[] */
  78. protected $checks = [];
  79. /** @var IDBConnection */
  80. protected $connection;
  81. /** @var IServerContainer|\OC\Server */
  82. protected $container;
  83. /** @var IL10N */
  84. protected $l;
  85. /** @var IEntity[] */
  86. protected $registeredEntities = [];
  87. /** @var IOperation[] */
  88. protected $registeredOperators = [];
  89. /** @var ICheck[] */
  90. protected $registeredChecks = [];
  91. /** @var ILogger */
  92. protected $logger;
  93. /** @var CappedMemoryCache<int[]> */
  94. protected CappedMemoryCache $operationsByScope;
  95. /** @var IUserSession */
  96. protected $session;
  97. /** @var IEventDispatcher */
  98. private $dispatcher;
  99. /** @var IConfig */
  100. private $config;
  101. private ICacheFactory $cacheFactory;
  102. public function __construct(
  103. IDBConnection $connection,
  104. IServerContainer $container,
  105. IL10N $l,
  106. ILogger $logger,
  107. IUserSession $session,
  108. IEventDispatcher $dispatcher,
  109. IConfig $config,
  110. ICacheFactory $cacheFactory,
  111. ) {
  112. $this->connection = $connection;
  113. $this->container = $container;
  114. $this->l = $l;
  115. $this->logger = $logger;
  116. $this->operationsByScope = new CappedMemoryCache(64);
  117. $this->session = $session;
  118. $this->dispatcher = $dispatcher;
  119. $this->config = $config;
  120. $this->cacheFactory = $cacheFactory;
  121. }
  122. public function getRuleMatcher(): IRuleMatcher {
  123. return new RuleMatcher(
  124. $this->session,
  125. $this->container,
  126. $this->l,
  127. $this,
  128. $this->container->query(Logger::class)
  129. );
  130. }
  131. public function getAllConfiguredEvents() {
  132. $cache = $this->cacheFactory->createDistributed('flow');
  133. $cached = $cache->get('events');
  134. if ($cached !== null) {
  135. return $cached;
  136. }
  137. $query = $this->connection->getQueryBuilder();
  138. $query->select('class', 'entity')
  139. ->selectAlias($query->expr()->castColumn('events', IQueryBuilder::PARAM_STR), 'events')
  140. ->from('flow_operations')
  141. ->where($query->expr()->neq('events', $query->createNamedParameter('[]'), IQueryBuilder::PARAM_STR))
  142. ->groupBy('class', 'entity', $query->expr()->castColumn('events', IQueryBuilder::PARAM_STR));
  143. $result = $query->execute();
  144. $operations = [];
  145. while ($row = $result->fetch()) {
  146. $eventNames = \json_decode($row['events']);
  147. $operation = $row['class'];
  148. $entity = $row['entity'];
  149. $operations[$operation] = $operations[$row['class']] ?? [];
  150. $operations[$operation][$entity] = $operations[$operation][$entity] ?? [];
  151. $operations[$operation][$entity] = array_unique(array_merge($operations[$operation][$entity], $eventNames ?? []));
  152. }
  153. $result->closeCursor();
  154. $cache->set('events', $operations, 3600);
  155. return $operations;
  156. }
  157. /**
  158. * @param string $operationClass
  159. * @return ScopeContext[]
  160. */
  161. public function getAllConfiguredScopesForOperation(string $operationClass): array {
  162. static $scopesByOperation = [];
  163. if (isset($scopesByOperation[$operationClass])) {
  164. return $scopesByOperation[$operationClass];
  165. }
  166. try {
  167. /** @var IOperation $operation */
  168. $operation = $this->container->query($operationClass);
  169. } catch (QueryException $e) {
  170. return [];
  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. if (!$operation->isAvailableForScope((int) $row['type'])) {
  184. continue;
  185. }
  186. $scopesByOperation[$operationClass][$scope->getHash()] = $scope;
  187. }
  188. return $scopesByOperation[$operationClass];
  189. }
  190. public function getAllOperations(ScopeContext $scopeContext): array {
  191. if (isset($this->operations[$scopeContext->getHash()])) {
  192. return $this->operations[$scopeContext->getHash()];
  193. }
  194. $query = $this->connection->getQueryBuilder();
  195. $query->select('o.*')
  196. ->selectAlias('s.type', 'scope_type')
  197. ->selectAlias('s.value', 'scope_actor_id')
  198. ->from('flow_operations', 'o')
  199. ->leftJoin('o', 'flow_operations_scope', 's', $query->expr()->eq('o.id', 's.operation_id'))
  200. ->where($query->expr()->eq('s.type', $query->createParameter('scope')));
  201. if ($scopeContext->getScope() === IManager::SCOPE_USER) {
  202. $query->andWhere($query->expr()->eq('s.value', $query->createParameter('scopeId')));
  203. }
  204. $query->setParameters(['scope' => $scopeContext->getScope(), 'scopeId' => $scopeContext->getScopeId()]);
  205. $result = $query->execute();
  206. $this->operations[$scopeContext->getHash()] = [];
  207. while ($row = $result->fetch()) {
  208. try {
  209. /** @var IOperation $operation */
  210. $operation = $this->container->query($row['class']);
  211. } catch (QueryException $e) {
  212. continue;
  213. }
  214. if (!$operation->isAvailableForScope((int) $row['scope_type'])) {
  215. continue;
  216. }
  217. if (!isset($this->operations[$scopeContext->getHash()][$row['class']])) {
  218. $this->operations[$scopeContext->getHash()][$row['class']] = [];
  219. }
  220. $this->operations[$scopeContext->getHash()][$row['class']][] = $row;
  221. }
  222. return $this->operations[$scopeContext->getHash()];
  223. }
  224. public function getOperations(string $class, ScopeContext $scopeContext): array {
  225. if (!isset($this->operations[$scopeContext->getHash()])) {
  226. $this->getAllOperations($scopeContext);
  227. }
  228. return $this->operations[$scopeContext->getHash()][$class] ?? [];
  229. }
  230. /**
  231. * @param int $id
  232. * @return array
  233. * @throws \UnexpectedValueException
  234. */
  235. protected function getOperation($id) {
  236. $query = $this->connection->getQueryBuilder();
  237. $query->select('*')
  238. ->from('flow_operations')
  239. ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
  240. $result = $query->execute();
  241. $row = $result->fetch();
  242. $result->closeCursor();
  243. if ($row) {
  244. return $row;
  245. }
  246. throw new \UnexpectedValueException($this->l->t('Operation #%s does not exist', [$id]));
  247. }
  248. protected function insertOperation(
  249. string $class,
  250. string $name,
  251. array $checkIds,
  252. string $operation,
  253. string $entity,
  254. array $events
  255. ): int {
  256. $query = $this->connection->getQueryBuilder();
  257. $query->insert('flow_operations')
  258. ->values([
  259. 'class' => $query->createNamedParameter($class),
  260. 'name' => $query->createNamedParameter($name),
  261. 'checks' => $query->createNamedParameter(json_encode(array_unique($checkIds))),
  262. 'operation' => $query->createNamedParameter($operation),
  263. 'entity' => $query->createNamedParameter($entity),
  264. 'events' => $query->createNamedParameter(json_encode($events))
  265. ]);
  266. $query->execute();
  267. $this->cacheFactory->createDistributed('flow')->remove('events');
  268. return $query->getLastInsertId();
  269. }
  270. /**
  271. * @param string $class
  272. * @param string $name
  273. * @param array[] $checks
  274. * @param string $operation
  275. * @return array The added operation
  276. * @throws \UnexpectedValueException
  277. * @throw Exception
  278. */
  279. public function addOperation(
  280. string $class,
  281. string $name,
  282. array $checks,
  283. string $operation,
  284. ScopeContext $scope,
  285. string $entity,
  286. array $events
  287. ) {
  288. $this->validateOperation($class, $name, $checks, $operation, $scope, $entity, $events);
  289. $this->connection->beginTransaction();
  290. try {
  291. $checkIds = [];
  292. foreach ($checks as $check) {
  293. $checkIds[] = $this->addCheck($check['class'], $check['operator'], $check['value']);
  294. }
  295. $id = $this->insertOperation($class, $name, $checkIds, $operation, $entity, $events);
  296. $this->addScope($id, $scope);
  297. $this->connection->commit();
  298. } catch (Exception $e) {
  299. $this->connection->rollBack();
  300. throw $e;
  301. }
  302. return $this->getOperation($id);
  303. }
  304. protected function canModify(int $id, ScopeContext $scopeContext):bool {
  305. if (isset($this->operationsByScope[$scopeContext->getHash()])) {
  306. return in_array($id, $this->operationsByScope[$scopeContext->getHash()], true);
  307. }
  308. $qb = $this->connection->getQueryBuilder();
  309. $qb = $qb->select('o.id')
  310. ->from('flow_operations', 'o')
  311. ->leftJoin('o', 'flow_operations_scope', 's', $qb->expr()->eq('o.id', 's.operation_id'))
  312. ->where($qb->expr()->eq('s.type', $qb->createParameter('scope')));
  313. if ($scopeContext->getScope() !== IManager::SCOPE_ADMIN) {
  314. $qb->where($qb->expr()->eq('s.value', $qb->createParameter('scopeId')));
  315. }
  316. $qb->setParameters(['scope' => $scopeContext->getScope(), 'scopeId' => $scopeContext->getScopeId()]);
  317. $result = $qb->execute();
  318. $operations = [];
  319. while (($opId = $result->fetchOne()) !== false) {
  320. $operations[] = (int)$opId;
  321. }
  322. $this->operationsByScope[$scopeContext->getHash()] = $operations;
  323. $result->closeCursor();
  324. return in_array($id, $this->operationsByScope[$scopeContext->getHash()], true);
  325. }
  326. /**
  327. * @param int $id
  328. * @param string $name
  329. * @param array[] $checks
  330. * @param string $operation
  331. * @return array The updated operation
  332. * @throws \UnexpectedValueException
  333. * @throws \DomainException
  334. * @throws Exception
  335. */
  336. public function updateOperation(
  337. int $id,
  338. string $name,
  339. array $checks,
  340. string $operation,
  341. ScopeContext $scopeContext,
  342. string $entity,
  343. array $events
  344. ): array {
  345. if (!$this->canModify($id, $scopeContext)) {
  346. throw new \DomainException('Target operation not within scope');
  347. };
  348. $row = $this->getOperation($id);
  349. $this->validateOperation($row['class'], $name, $checks, $operation, $scopeContext, $entity, $events);
  350. $checkIds = [];
  351. try {
  352. $this->connection->beginTransaction();
  353. foreach ($checks as $check) {
  354. $checkIds[] = $this->addCheck($check['class'], $check['operator'], $check['value']);
  355. }
  356. $query = $this->connection->getQueryBuilder();
  357. $query->update('flow_operations')
  358. ->set('name', $query->createNamedParameter($name))
  359. ->set('checks', $query->createNamedParameter(json_encode(array_unique($checkIds))))
  360. ->set('operation', $query->createNamedParameter($operation))
  361. ->set('entity', $query->createNamedParameter($entity))
  362. ->set('events', $query->createNamedParameter(json_encode($events)))
  363. ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
  364. $query->execute();
  365. $this->connection->commit();
  366. } catch (Exception $e) {
  367. $this->connection->rollBack();
  368. throw $e;
  369. }
  370. unset($this->operations[$scopeContext->getHash()]);
  371. $this->cacheFactory->createDistributed('flow')->remove('events');
  372. return $this->getOperation($id);
  373. }
  374. /**
  375. * @param int $id
  376. * @return bool
  377. * @throws \UnexpectedValueException
  378. * @throws Exception
  379. * @throws \DomainException
  380. */
  381. public function deleteOperation($id, ScopeContext $scopeContext) {
  382. if (!$this->canModify($id, $scopeContext)) {
  383. throw new \DomainException('Target operation not within scope');
  384. };
  385. $query = $this->connection->getQueryBuilder();
  386. try {
  387. $this->connection->beginTransaction();
  388. $result = (bool)$query->delete('flow_operations')
  389. ->where($query->expr()->eq('id', $query->createNamedParameter($id)))
  390. ->execute();
  391. if ($result) {
  392. $qb = $this->connection->getQueryBuilder();
  393. $result &= (bool)$qb->delete('flow_operations_scope')
  394. ->where($qb->expr()->eq('operation_id', $qb->createNamedParameter($id)))
  395. ->execute();
  396. }
  397. $this->connection->commit();
  398. } catch (Exception $e) {
  399. $this->connection->rollBack();
  400. throw $e;
  401. }
  402. if (isset($this->operations[$scopeContext->getHash()])) {
  403. unset($this->operations[$scopeContext->getHash()]);
  404. }
  405. $this->cacheFactory->createDistributed('flow')->remove('events');
  406. return $result;
  407. }
  408. protected function validateEvents(string $entity, array $events, IOperation $operation) {
  409. try {
  410. /** @var IEntity $instance */
  411. $instance = $this->container->query($entity);
  412. } catch (QueryException $e) {
  413. throw new \UnexpectedValueException($this->l->t('Entity %s does not exist', [$entity]));
  414. }
  415. if (!$instance instanceof IEntity) {
  416. throw new \UnexpectedValueException($this->l->t('Entity %s is invalid', [$entity]));
  417. }
  418. if (empty($events)) {
  419. if (!$operation instanceof IComplexOperation) {
  420. throw new \UnexpectedValueException($this->l->t('No events are chosen.'));
  421. }
  422. return;
  423. }
  424. $availableEvents = [];
  425. foreach ($instance->getEvents() as $event) {
  426. /** @var IEntityEvent $event */
  427. $availableEvents[] = $event->getEventName();
  428. }
  429. $diff = array_diff($events, $availableEvents);
  430. if (!empty($diff)) {
  431. throw new \UnexpectedValueException($this->l->t('Entity %s has no event %s', [$entity, array_shift($diff)]));
  432. }
  433. }
  434. /**
  435. * @param string $class
  436. * @param string $name
  437. * @param array[] $checks
  438. * @param string $operation
  439. * @param ScopeContext $scope
  440. * @param string $entity
  441. * @param array $events
  442. * @throws \UnexpectedValueException
  443. */
  444. public function validateOperation($class, $name, array $checks, $operation, ScopeContext $scope, string $entity, array $events) {
  445. try {
  446. /** @var IOperation $instance */
  447. $instance = $this->container->query($class);
  448. } catch (QueryException $e) {
  449. throw new \UnexpectedValueException($this->l->t('Operation %s does not exist', [$class]));
  450. }
  451. if (!($instance instanceof IOperation)) {
  452. throw new \UnexpectedValueException($this->l->t('Operation %s is invalid', [$class]));
  453. }
  454. if (!$instance->isAvailableForScope($scope->getScope())) {
  455. throw new \UnexpectedValueException($this->l->t('Operation %s is invalid', [$class]));
  456. }
  457. $this->validateEvents($entity, $events, $instance);
  458. if (count($checks) === 0) {
  459. throw new \UnexpectedValueException($this->l->t('At least one check needs to be provided'));
  460. }
  461. if (strlen((string)$operation) > IManager::MAX_OPERATION_VALUE_BYTES) {
  462. throw new \UnexpectedValueException($this->l->t('The provided operation data is too long'));
  463. }
  464. $instance->validateOperation($name, $checks, $operation);
  465. foreach ($checks as $check) {
  466. if (!is_string($check['class'])) {
  467. throw new \UnexpectedValueException($this->l->t('Invalid check provided'));
  468. }
  469. try {
  470. /** @var ICheck $instance */
  471. $instance = $this->container->query($check['class']);
  472. } catch (QueryException $e) {
  473. throw new \UnexpectedValueException($this->l->t('Check %s does not exist', [$class]));
  474. }
  475. if (!($instance instanceof ICheck)) {
  476. throw new \UnexpectedValueException($this->l->t('Check %s is invalid', [$class]));
  477. }
  478. if (!empty($instance->supportedEntities())
  479. && !in_array($entity, $instance->supportedEntities())
  480. ) {
  481. throw new \UnexpectedValueException($this->l->t('Check %s is not allowed with this entity', [$class]));
  482. }
  483. if (strlen((string)$check['value']) > IManager::MAX_CHECK_VALUE_BYTES) {
  484. throw new \UnexpectedValueException($this->l->t('The provided check value is too long'));
  485. }
  486. $instance->validateCheck($check['operator'], $check['value']);
  487. }
  488. }
  489. /**
  490. * @param int[] $checkIds
  491. * @return array[]
  492. */
  493. public function getChecks(array $checkIds) {
  494. $checkIds = array_map('intval', $checkIds);
  495. $checks = [];
  496. foreach ($checkIds as $i => $checkId) {
  497. if (isset($this->checks[$checkId])) {
  498. $checks[$checkId] = $this->checks[$checkId];
  499. unset($checkIds[$i]);
  500. }
  501. }
  502. if (empty($checkIds)) {
  503. return $checks;
  504. }
  505. $query = $this->connection->getQueryBuilder();
  506. $query->select('*')
  507. ->from('flow_checks')
  508. ->where($query->expr()->in('id', $query->createNamedParameter($checkIds, IQueryBuilder::PARAM_INT_ARRAY)));
  509. $result = $query->execute();
  510. while ($row = $result->fetch()) {
  511. $this->checks[(int) $row['id']] = $row;
  512. $checks[(int) $row['id']] = $row;
  513. }
  514. $result->closeCursor();
  515. $checkIds = array_diff($checkIds, array_keys($checks));
  516. if (!empty($checkIds)) {
  517. $missingCheck = array_pop($checkIds);
  518. throw new \UnexpectedValueException($this->l->t('Check #%s does not exist', $missingCheck));
  519. }
  520. return $checks;
  521. }
  522. /**
  523. * @param string $class
  524. * @param string $operator
  525. * @param string $value
  526. * @return int Check unique ID
  527. */
  528. protected function addCheck($class, $operator, $value) {
  529. $hash = md5($class . '::' . $operator . '::' . $value);
  530. $query = $this->connection->getQueryBuilder();
  531. $query->select('id')
  532. ->from('flow_checks')
  533. ->where($query->expr()->eq('hash', $query->createNamedParameter($hash)));
  534. $result = $query->execute();
  535. if ($row = $result->fetch()) {
  536. $result->closeCursor();
  537. return (int) $row['id'];
  538. }
  539. $query = $this->connection->getQueryBuilder();
  540. $query->insert('flow_checks')
  541. ->values([
  542. 'class' => $query->createNamedParameter($class),
  543. 'operator' => $query->createNamedParameter($operator),
  544. 'value' => $query->createNamedParameter($value),
  545. 'hash' => $query->createNamedParameter($hash),
  546. ]);
  547. $query->execute();
  548. return $query->getLastInsertId();
  549. }
  550. protected function addScope(int $operationId, ScopeContext $scope): void {
  551. $query = $this->connection->getQueryBuilder();
  552. $insertQuery = $query->insert('flow_operations_scope');
  553. $insertQuery->values([
  554. 'operation_id' => $query->createNamedParameter($operationId),
  555. 'type' => $query->createNamedParameter($scope->getScope()),
  556. 'value' => $query->createNamedParameter($scope->getScopeId()),
  557. ]);
  558. $insertQuery->execute();
  559. }
  560. public function formatOperation(array $operation): array {
  561. $checkIds = json_decode($operation['checks'], true);
  562. $checks = $this->getChecks($checkIds);
  563. $operation['checks'] = [];
  564. foreach ($checks as $check) {
  565. // Remove internal values
  566. unset($check['id']);
  567. unset($check['hash']);
  568. $operation['checks'][] = $check;
  569. }
  570. $operation['events'] = json_decode($operation['events'], true) ?? [];
  571. return $operation;
  572. }
  573. /**
  574. * @return IEntity[]
  575. */
  576. public function getEntitiesList(): array {
  577. $this->dispatcher->dispatchTyped(new RegisterEntitiesEvent($this));
  578. return array_values(array_merge($this->getBuildInEntities(), $this->registeredEntities));
  579. }
  580. /**
  581. * @return IOperation[]
  582. */
  583. public function getOperatorList(): array {
  584. $this->dispatcher->dispatchTyped(new RegisterOperationsEvent($this));
  585. return array_merge($this->getBuildInOperators(), $this->registeredOperators);
  586. }
  587. /**
  588. * @return ICheck[]
  589. */
  590. public function getCheckList(): array {
  591. $this->dispatcher->dispatchTyped(new RegisterChecksEvent($this));
  592. return array_merge($this->getBuildInChecks(), $this->registeredChecks);
  593. }
  594. public function registerEntity(IEntity $entity): void {
  595. $this->registeredEntities[get_class($entity)] = $entity;
  596. }
  597. public function registerOperation(IOperation $operator): void {
  598. $this->registeredOperators[get_class($operator)] = $operator;
  599. }
  600. public function registerCheck(ICheck $check): void {
  601. $this->registeredChecks[get_class($check)] = $check;
  602. }
  603. /**
  604. * @return IEntity[]
  605. */
  606. protected function getBuildInEntities(): array {
  607. try {
  608. return [
  609. File::class => $this->container->query(File::class),
  610. ];
  611. } catch (QueryException $e) {
  612. $this->logger->logException($e);
  613. return [];
  614. }
  615. }
  616. /**
  617. * @return IOperation[]
  618. */
  619. protected function getBuildInOperators(): array {
  620. try {
  621. return [
  622. // None yet
  623. ];
  624. } catch (QueryException $e) {
  625. $this->logger->logException($e);
  626. return [];
  627. }
  628. }
  629. /**
  630. * @return ICheck[]
  631. */
  632. protected function getBuildInChecks(): array {
  633. try {
  634. return [
  635. $this->container->query(FileMimeType::class),
  636. $this->container->query(FileName::class),
  637. $this->container->query(FileSize::class),
  638. $this->container->query(FileSystemTags::class),
  639. $this->container->query(RequestRemoteAddress::class),
  640. $this->container->query(RequestTime::class),
  641. $this->container->query(RequestURL::class),
  642. $this->container->query(RequestUserAgent::class),
  643. $this->container->query(UserGroupMembership::class),
  644. ];
  645. } catch (QueryException $e) {
  646. $this->logger->logException($e);
  647. return [];
  648. }
  649. }
  650. public function isUserScopeEnabled(): bool {
  651. return $this->config->getAppValue(Application::APP_ID, 'user_scope_disabled', 'no') === 'no';
  652. }
  653. }