Manager.php 22 KB

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