Manager.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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 OC\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 */
  97. protected $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. $this->operationsByScope[$scopeContext->getHash()] = [];
  314. while (($opId = $result->fetchOne()) !== false) {
  315. $this->operationsByScope[$scopeContext->getHash()][] = (int)$opId;
  316. }
  317. $result->closeCursor();
  318. return in_array($id, $this->operationsByScope[$scopeContext->getHash()], true);
  319. }
  320. /**
  321. * @param int $id
  322. * @param string $name
  323. * @param array[] $checks
  324. * @param string $operation
  325. * @return array The updated operation
  326. * @throws \UnexpectedValueException
  327. * @throws \DomainException
  328. * @throws Exception
  329. */
  330. public function updateOperation(
  331. int $id,
  332. string $name,
  333. array $checks,
  334. string $operation,
  335. ScopeContext $scopeContext,
  336. string $entity,
  337. array $events
  338. ): array {
  339. if (!$this->canModify($id, $scopeContext)) {
  340. throw new \DomainException('Target operation not within scope');
  341. };
  342. $row = $this->getOperation($id);
  343. $this->validateOperation($row['class'], $name, $checks, $operation, $scopeContext, $entity, $events);
  344. $checkIds = [];
  345. try {
  346. $this->connection->beginTransaction();
  347. foreach ($checks as $check) {
  348. $checkIds[] = $this->addCheck($check['class'], $check['operator'], $check['value']);
  349. }
  350. $query = $this->connection->getQueryBuilder();
  351. $query->update('flow_operations')
  352. ->set('name', $query->createNamedParameter($name))
  353. ->set('checks', $query->createNamedParameter(json_encode(array_unique($checkIds))))
  354. ->set('operation', $query->createNamedParameter($operation))
  355. ->set('entity', $query->createNamedParameter($entity))
  356. ->set('events', $query->createNamedParameter(json_encode($events)))
  357. ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
  358. $query->execute();
  359. $this->connection->commit();
  360. } catch (Exception $e) {
  361. $this->connection->rollBack();
  362. throw $e;
  363. }
  364. unset($this->operations[$scopeContext->getHash()]);
  365. return $this->getOperation($id);
  366. }
  367. /**
  368. * @param int $id
  369. * @return bool
  370. * @throws \UnexpectedValueException
  371. * @throws Exception
  372. * @throws \DomainException
  373. */
  374. public function deleteOperation($id, ScopeContext $scopeContext) {
  375. if (!$this->canModify($id, $scopeContext)) {
  376. throw new \DomainException('Target operation not within scope');
  377. };
  378. $query = $this->connection->getQueryBuilder();
  379. try {
  380. $this->connection->beginTransaction();
  381. $result = (bool)$query->delete('flow_operations')
  382. ->where($query->expr()->eq('id', $query->createNamedParameter($id)))
  383. ->execute();
  384. if ($result) {
  385. $qb = $this->connection->getQueryBuilder();
  386. $result &= (bool)$qb->delete('flow_operations_scope')
  387. ->where($qb->expr()->eq('operation_id', $qb->createNamedParameter($id)))
  388. ->execute();
  389. }
  390. $this->connection->commit();
  391. } catch (Exception $e) {
  392. $this->connection->rollBack();
  393. throw $e;
  394. }
  395. if (isset($this->operations[$scopeContext->getHash()])) {
  396. unset($this->operations[$scopeContext->getHash()]);
  397. }
  398. return $result;
  399. }
  400. protected function validateEvents(string $entity, array $events, IOperation $operation) {
  401. try {
  402. /** @var IEntity $instance */
  403. $instance = $this->container->query($entity);
  404. } catch (QueryException $e) {
  405. throw new \UnexpectedValueException($this->l->t('Entity %s does not exist', [$entity]));
  406. }
  407. if (!$instance instanceof IEntity) {
  408. throw new \UnexpectedValueException($this->l->t('Entity %s is invalid', [$entity]));
  409. }
  410. if (empty($events)) {
  411. if (!$operation instanceof IComplexOperation) {
  412. throw new \UnexpectedValueException($this->l->t('No events are chosen.'));
  413. }
  414. return;
  415. }
  416. $availableEvents = [];
  417. foreach ($instance->getEvents() as $event) {
  418. /** @var IEntityEvent $event */
  419. $availableEvents[] = $event->getEventName();
  420. }
  421. $diff = array_diff($events, $availableEvents);
  422. if (!empty($diff)) {
  423. throw new \UnexpectedValueException($this->l->t('Entity %s has no event %s', [$entity, array_shift($diff)]));
  424. }
  425. }
  426. /**
  427. * @param string $class
  428. * @param string $name
  429. * @param array[] $checks
  430. * @param string $operation
  431. * @param ScopeContext $scope
  432. * @param string $entity
  433. * @param array $events
  434. * @throws \UnexpectedValueException
  435. */
  436. public function validateOperation($class, $name, array $checks, $operation, ScopeContext $scope, string $entity, array $events) {
  437. try {
  438. /** @var IOperation $instance */
  439. $instance = $this->container->query($class);
  440. } catch (QueryException $e) {
  441. throw new \UnexpectedValueException($this->l->t('Operation %s does not exist', [$class]));
  442. }
  443. if (!($instance instanceof IOperation)) {
  444. throw new \UnexpectedValueException($this->l->t('Operation %s is invalid', [$class]));
  445. }
  446. if (!$instance->isAvailableForScope($scope->getScope())) {
  447. throw new \UnexpectedValueException($this->l->t('Operation %s is invalid', [$class]));
  448. }
  449. $this->validateEvents($entity, $events, $instance);
  450. if (count($checks) === 0) {
  451. throw new \UnexpectedValueException($this->l->t('At least one check needs to be provided'));
  452. }
  453. if (strlen((string)$operation) > IManager::MAX_OPERATION_VALUE_BYTES) {
  454. throw new \UnexpectedValueException($this->l->t('The provided operation data is too long'));
  455. }
  456. $instance->validateOperation($name, $checks, $operation);
  457. foreach ($checks as $check) {
  458. if (!is_string($check['class'])) {
  459. throw new \UnexpectedValueException($this->l->t('Invalid check provided'));
  460. }
  461. try {
  462. /** @var ICheck $instance */
  463. $instance = $this->container->query($check['class']);
  464. } catch (QueryException $e) {
  465. throw new \UnexpectedValueException($this->l->t('Check %s does not exist', [$class]));
  466. }
  467. if (!($instance instanceof ICheck)) {
  468. throw new \UnexpectedValueException($this->l->t('Check %s is invalid', [$class]));
  469. }
  470. if (!empty($instance->supportedEntities())
  471. && !in_array($entity, $instance->supportedEntities())
  472. ) {
  473. throw new \UnexpectedValueException($this->l->t('Check %s is not allowed with this entity', [$class]));
  474. }
  475. if (strlen((string)$check['value']) > IManager::MAX_CHECK_VALUE_BYTES) {
  476. throw new \UnexpectedValueException($this->l->t('The provided check value is too long'));
  477. }
  478. $instance->validateCheck($check['operator'], $check['value']);
  479. }
  480. }
  481. /**
  482. * @param int[] $checkIds
  483. * @return array[]
  484. */
  485. public function getChecks(array $checkIds) {
  486. $checkIds = array_map('intval', $checkIds);
  487. $checks = [];
  488. foreach ($checkIds as $i => $checkId) {
  489. if (isset($this->checks[$checkId])) {
  490. $checks[$checkId] = $this->checks[$checkId];
  491. unset($checkIds[$i]);
  492. }
  493. }
  494. if (empty($checkIds)) {
  495. return $checks;
  496. }
  497. $query = $this->connection->getQueryBuilder();
  498. $query->select('*')
  499. ->from('flow_checks')
  500. ->where($query->expr()->in('id', $query->createNamedParameter($checkIds, IQueryBuilder::PARAM_INT_ARRAY)));
  501. $result = $query->execute();
  502. while ($row = $result->fetch()) {
  503. $this->checks[(int) $row['id']] = $row;
  504. $checks[(int) $row['id']] = $row;
  505. }
  506. $result->closeCursor();
  507. $checkIds = array_diff($checkIds, array_keys($checks));
  508. if (!empty($checkIds)) {
  509. $missingCheck = array_pop($checkIds);
  510. throw new \UnexpectedValueException($this->l->t('Check #%s does not exist', $missingCheck));
  511. }
  512. return $checks;
  513. }
  514. /**
  515. * @param string $class
  516. * @param string $operator
  517. * @param string $value
  518. * @return int Check unique ID
  519. */
  520. protected function addCheck($class, $operator, $value) {
  521. $hash = md5($class . '::' . $operator . '::' . $value);
  522. $query = $this->connection->getQueryBuilder();
  523. $query->select('id')
  524. ->from('flow_checks')
  525. ->where($query->expr()->eq('hash', $query->createNamedParameter($hash)));
  526. $result = $query->execute();
  527. if ($row = $result->fetch()) {
  528. $result->closeCursor();
  529. return (int) $row['id'];
  530. }
  531. $query = $this->connection->getQueryBuilder();
  532. $query->insert('flow_checks')
  533. ->values([
  534. 'class' => $query->createNamedParameter($class),
  535. 'operator' => $query->createNamedParameter($operator),
  536. 'value' => $query->createNamedParameter($value),
  537. 'hash' => $query->createNamedParameter($hash),
  538. ]);
  539. $query->execute();
  540. return $query->getLastInsertId();
  541. }
  542. protected function addScope(int $operationId, ScopeContext $scope): void {
  543. $query = $this->connection->getQueryBuilder();
  544. $insertQuery = $query->insert('flow_operations_scope');
  545. $insertQuery->values([
  546. 'operation_id' => $query->createNamedParameter($operationId),
  547. 'type' => $query->createNamedParameter($scope->getScope()),
  548. 'value' => $query->createNamedParameter($scope->getScopeId()),
  549. ]);
  550. $insertQuery->execute();
  551. }
  552. public function formatOperation(array $operation): array {
  553. $checkIds = json_decode($operation['checks'], true);
  554. $checks = $this->getChecks($checkIds);
  555. $operation['checks'] = [];
  556. foreach ($checks as $check) {
  557. // Remove internal values
  558. unset($check['id']);
  559. unset($check['hash']);
  560. $operation['checks'][] = $check;
  561. }
  562. $operation['events'] = json_decode($operation['events'], true) ?? [];
  563. return $operation;
  564. }
  565. /**
  566. * @return IEntity[]
  567. */
  568. public function getEntitiesList(): array {
  569. $this->dispatcher->dispatchTyped(new RegisterEntitiesEvent($this));
  570. $this->legacyEventDispatcher->dispatch(IManager::EVENT_NAME_REG_ENTITY, new GenericEvent($this));
  571. return array_values(array_merge($this->getBuildInEntities(), $this->registeredEntities));
  572. }
  573. /**
  574. * @return IOperation[]
  575. */
  576. public function getOperatorList(): array {
  577. $this->dispatcher->dispatchTyped(new RegisterOperationsEvent($this));
  578. $this->legacyEventDispatcher->dispatch(IManager::EVENT_NAME_REG_OPERATION, new GenericEvent($this));
  579. return array_merge($this->getBuildInOperators(), $this->registeredOperators);
  580. }
  581. /**
  582. * @return ICheck[]
  583. */
  584. public function getCheckList(): array {
  585. $this->dispatcher->dispatchTyped(new RegisterChecksEvent($this));
  586. $this->legacyEventDispatcher->dispatch(IManager::EVENT_NAME_REG_CHECK, new GenericEvent($this));
  587. return array_merge($this->getBuildInChecks(), $this->registeredChecks);
  588. }
  589. public function registerEntity(IEntity $entity): void {
  590. $this->registeredEntities[get_class($entity)] = $entity;
  591. }
  592. public function registerOperation(IOperation $operator): void {
  593. $this->registeredOperators[get_class($operator)] = $operator;
  594. }
  595. public function registerCheck(ICheck $check): void {
  596. $this->registeredChecks[get_class($check)] = $check;
  597. }
  598. /**
  599. * @return IEntity[]
  600. */
  601. protected function getBuildInEntities(): array {
  602. try {
  603. return [
  604. File::class => $this->container->query(File::class),
  605. ];
  606. } catch (QueryException $e) {
  607. $this->logger->logException($e);
  608. return [];
  609. }
  610. }
  611. /**
  612. * @return IOperation[]
  613. */
  614. protected function getBuildInOperators(): array {
  615. try {
  616. return [
  617. // None yet
  618. ];
  619. } catch (QueryException $e) {
  620. $this->logger->logException($e);
  621. return [];
  622. }
  623. }
  624. /**
  625. * @return ICheck[]
  626. */
  627. protected function getBuildInChecks(): array {
  628. try {
  629. return [
  630. $this->container->query(FileMimeType::class),
  631. $this->container->query(FileName::class),
  632. $this->container->query(FileSize::class),
  633. $this->container->query(FileSystemTags::class),
  634. $this->container->query(RequestRemoteAddress::class),
  635. $this->container->query(RequestTime::class),
  636. $this->container->query(RequestURL::class),
  637. $this->container->query(RequestUserAgent::class),
  638. $this->container->query(UserGroupMembership::class),
  639. ];
  640. } catch (QueryException $e) {
  641. $this->logger->logException($e);
  642. return [];
  643. }
  644. }
  645. public function isUserScopeEnabled(): bool {
  646. return $this->config->getAppValue(Application::APP_ID, 'user_scope_disabled', 'no') === 'no';
  647. }
  648. }