PageRenderTime 2249ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 1ms

/src/Symfony/Component/Security/Acl/Dbal/AclProvider.php

https://github.com/Exercise/symfony
PHP | 637 lines | 408 code | 82 blank | 147 comment | 56 complexity | fcc56b6688c06721d34a3c6a68d95795 MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Security\Acl\Dbal;
  11. use Doctrine\DBAL\Driver\Connection;
  12. use Doctrine\DBAL\Driver\Statement;
  13. use Symfony\Component\Security\Acl\Model\AclInterface;
  14. use Symfony\Component\Security\Acl\Domain\Acl;
  15. use Symfony\Component\Security\Acl\Domain\Entry;
  16. use Symfony\Component\Security\Acl\Domain\FieldEntry;
  17. use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
  18. use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
  19. use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
  20. use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
  21. use Symfony\Component\Security\Acl\Exception\NotAllAclsFoundException;
  22. use Symfony\Component\Security\Acl\Model\AclCacheInterface;
  23. use Symfony\Component\Security\Acl\Model\AclProviderInterface;
  24. use Symfony\Component\Security\Acl\Model\ObjectIdentityInterface;
  25. use Symfony\Component\Security\Acl\Model\PermissionGrantingStrategyInterface;
  26. /**
  27. * An ACL provider implementation.
  28. *
  29. * This provider assumes that all ACLs share the same PermissionGrantingStrategy.
  30. *
  31. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  32. */
  33. class AclProvider implements AclProviderInterface
  34. {
  35. const MAX_BATCH_SIZE = 30;
  36. protected $cache;
  37. protected $connection;
  38. protected $loadedAces;
  39. protected $loadedAcls;
  40. protected $options;
  41. private $permissionGrantingStrategy;
  42. /**
  43. * Constructor.
  44. *
  45. * @param Connection $connection
  46. * @param PermissionGrantingStrategyInterface $permissionGrantingStrategy
  47. * @param array $options
  48. * @param AclCacheInterface $cache
  49. */
  50. public function __construct(Connection $connection, PermissionGrantingStrategyInterface $permissionGrantingStrategy, array $options, AclCacheInterface $cache = null)
  51. {
  52. $this->cache = $cache;
  53. $this->connection = $connection;
  54. $this->loadedAces = array();
  55. $this->loadedAcls = array();
  56. $this->options = $options;
  57. $this->permissionGrantingStrategy = $permissionGrantingStrategy;
  58. }
  59. /**
  60. * {@inheritDoc}
  61. */
  62. public function findChildren(ObjectIdentityInterface $parentOid, $directChildrenOnly = false)
  63. {
  64. $sql = $this->getFindChildrenSql($parentOid, $directChildrenOnly);
  65. $children = array();
  66. foreach ($this->connection->executeQuery($sql)->fetchAll() as $data) {
  67. $children[] = new ObjectIdentity($data['object_identifier'], $data['class_type']);
  68. }
  69. return $children;
  70. }
  71. /**
  72. * {@inheritDoc}
  73. */
  74. public function findAcl(ObjectIdentityInterface $oid, array $sids = array())
  75. {
  76. return $this->findAcls(array($oid), $sids)->offsetGet($oid);
  77. }
  78. /**
  79. * {@inheritDoc}
  80. */
  81. public function findAcls(array $oids, array $sids = array())
  82. {
  83. $result = new \SplObjectStorage();
  84. $currentBatch = array();
  85. $oidLookup = array();
  86. for ($i=0,$c=count($oids); $i<$c; $i++) {
  87. $oid = $oids[$i];
  88. $oidLookupKey = $oid->getIdentifier().$oid->getType();
  89. $oidLookup[$oidLookupKey] = $oid;
  90. $aclFound = false;
  91. // check if result already contains an ACL
  92. if ($result->contains($oid)) {
  93. $aclFound = true;
  94. }
  95. // check if this ACL has already been hydrated
  96. if (!$aclFound && isset($this->loadedAcls[$oid->getType()][$oid->getIdentifier()])) {
  97. $acl = $this->loadedAcls[$oid->getType()][$oid->getIdentifier()];
  98. if (!$acl->isSidLoaded($sids)) {
  99. // FIXME: we need to load ACEs for the missing SIDs. This is never
  100. // reached by the default implementation, since we do not
  101. // filter by SID
  102. throw new \RuntimeException('This is not supported by the default implementation.');
  103. } else {
  104. $result->attach($oid, $acl);
  105. $aclFound = true;
  106. }
  107. }
  108. // check if we can locate the ACL in the cache
  109. if (!$aclFound && null !== $this->cache) {
  110. $acl = $this->cache->getFromCacheByIdentity($oid);
  111. if (null !== $acl) {
  112. if ($acl->isSidLoaded($sids)) {
  113. // check if any of the parents has been loaded since we need to
  114. // ensure that there is only ever one ACL per object identity
  115. $parentAcl = $acl->getParentAcl();
  116. while (null !== $parentAcl) {
  117. $parentOid = $parentAcl->getObjectIdentity();
  118. if (isset($this->loadedAcls[$parentOid->getType()][$parentOid->getIdentifier()])) {
  119. $acl->setParentAcl($this->loadedAcls[$parentOid->getType()][$parentOid->getIdentifier()]);
  120. break;
  121. } else {
  122. $this->loadedAcls[$parentOid->getType()][$parentOid->getIdentifier()] = $parentAcl;
  123. $this->updateAceIdentityMap($parentAcl);
  124. }
  125. $parentAcl = $parentAcl->getParentAcl();
  126. }
  127. $this->loadedAcls[$oid->getType()][$oid->getIdentifier()] = $acl;
  128. $this->updateAceIdentityMap($acl);
  129. $result->attach($oid, $acl);
  130. $aclFound = true;
  131. } else {
  132. $this->cache->evictFromCacheByIdentity($oid);
  133. foreach ($this->findChildren($oid) as $childOid) {
  134. $this->cache->evictFromCacheByIdentity($childOid);
  135. }
  136. }
  137. }
  138. }
  139. // looks like we have to load the ACL from the database
  140. if (!$aclFound) {
  141. $currentBatch[] = $oid;
  142. }
  143. // Is it time to load the current batch?
  144. if ((self::MAX_BATCH_SIZE === count($currentBatch) || ($i + 1) === $c) && count($currentBatch) > 0) {
  145. $loadedBatch = $this->lookupObjectIdentities($currentBatch, $sids, $oidLookup);
  146. foreach ($loadedBatch as $loadedOid) {
  147. $loadedAcl = $loadedBatch->offsetGet($loadedOid);
  148. if (null !== $this->cache) {
  149. $this->cache->putInCache($loadedAcl);
  150. }
  151. if (isset($oidLookup[$loadedOid->getIdentifier().$loadedOid->getType()])) {
  152. $result->attach($loadedOid, $loadedAcl);
  153. }
  154. }
  155. $currentBatch = array();
  156. }
  157. }
  158. // check that we got ACLs for all the identities
  159. foreach ($oids as $oid) {
  160. if (!$result->contains($oid)) {
  161. if (1 === count($oids)) {
  162. throw new AclNotFoundException(sprintf('No ACL found for %s.', $oid));
  163. }
  164. $partialResultException = new NotAllAclsFoundException('The provider could not find ACLs for all object identities.');
  165. $partialResultException->setPartialResult($result);
  166. throw $partialResultException;
  167. }
  168. }
  169. return $result;
  170. }
  171. /**
  172. * Constructs the query used for looking up object identities and associated
  173. * ACEs, and security identities.
  174. *
  175. * @param array $ancestorIds
  176. * @return string
  177. */
  178. protected function getLookupSql(array $ancestorIds)
  179. {
  180. // FIXME: add support for filtering by sids (right now we select all sids)
  181. $sql = <<<SELECTCLAUSE
  182. SELECT
  183. o.id as acl_id,
  184. o.object_identifier,
  185. o.parent_object_identity_id,
  186. o.entries_inheriting,
  187. c.class_type,
  188. e.id as ace_id,
  189. e.object_identity_id,
  190. e.field_name,
  191. e.ace_order,
  192. e.mask,
  193. e.granting,
  194. e.granting_strategy,
  195. e.audit_success,
  196. e.audit_failure,
  197. s.username,
  198. s.identifier as security_identifier
  199. FROM
  200. {$this->options['oid_table_name']} o
  201. INNER JOIN {$this->options['class_table_name']} c ON c.id = o.class_id
  202. LEFT JOIN {$this->options['entry_table_name']} e ON (
  203. e.class_id = o.class_id AND (e.object_identity_id = o.id OR {$this->connection->getDatabasePlatform()->getIsNullExpression('e.object_identity_id')})
  204. )
  205. LEFT JOIN {$this->options['sid_table_name']} s ON (
  206. s.id = e.security_identity_id
  207. )
  208. WHERE (o.id =
  209. SELECTCLAUSE;
  210. $sql .= implode(' OR o.id = ', $ancestorIds).')';
  211. return $sql;
  212. }
  213. protected function getAncestorLookupSql(array $batch)
  214. {
  215. $sql = <<<SELECTCLAUSE
  216. SELECT a.ancestor_id
  217. FROM
  218. {$this->options['oid_table_name']} o
  219. INNER JOIN {$this->options['class_table_name']} c ON c.id = o.class_id
  220. INNER JOIN {$this->options['oid_ancestors_table_name']} a ON a.object_identity_id = o.id
  221. WHERE (
  222. SELECTCLAUSE;
  223. $where = '(o.object_identifier = %s AND c.class_type = %s)';
  224. for ($i=0,$c=count($batch); $i<$c; $i++) {
  225. $sql .= sprintf(
  226. $where,
  227. $this->connection->quote($batch[$i]->getIdentifier()),
  228. $this->connection->quote($batch[$i]->getType())
  229. );
  230. if ($i+1 < $c) {
  231. $sql .= ' OR ';
  232. }
  233. }
  234. $sql .= ')';
  235. return $sql;
  236. }
  237. /**
  238. * Constructs the SQL for retrieving child object identities for the given
  239. * object identities.
  240. *
  241. * @param ObjectIdentityInterface $oid
  242. * @param Boolean $directChildrenOnly
  243. * @return string
  244. */
  245. protected function getFindChildrenSql(ObjectIdentityInterface $oid, $directChildrenOnly)
  246. {
  247. if (false === $directChildrenOnly) {
  248. $query = <<<FINDCHILDREN
  249. SELECT o.object_identifier, c.class_type
  250. FROM
  251. {$this->options['oid_table_name']} as o
  252. INNER JOIN {$this->options['class_table_name']} as c ON c.id = o.class_id
  253. INNER JOIN {$this->options['oid_ancestors_table_name']} as a ON a.object_identity_id = o.id
  254. WHERE
  255. a.ancestor_id = %d AND a.object_identity_id != a.ancestor_id
  256. FINDCHILDREN;
  257. } else {
  258. $query = <<<FINDCHILDREN
  259. SELECT o.object_identifier, c.class_type
  260. FROM {$this->options['oid_table_name']} as o
  261. INNER JOIN {$this->options['class_table_name']} as c ON c.id = o.class_id
  262. WHERE o.parent_object_identity_id = %d
  263. FINDCHILDREN;
  264. }
  265. return sprintf($query, $this->retrieveObjectIdentityPrimaryKey($oid));
  266. }
  267. /**
  268. * Constructs the SQL for retrieving the primary key of the given object
  269. * identity.
  270. *
  271. * @param ObjectIdentityInterface $oid
  272. * @return string
  273. */
  274. protected function getSelectObjectIdentityIdSql(ObjectIdentityInterface $oid)
  275. {
  276. $query = <<<QUERY
  277. SELECT o.id
  278. FROM %s o
  279. INNER JOIN %s c ON c.id = o.class_id
  280. WHERE o.object_identifier = %s AND c.class_type = %s
  281. QUERY;
  282. return sprintf(
  283. $query,
  284. $this->options['oid_table_name'],
  285. $this->options['class_table_name'],
  286. $this->connection->quote($oid->getIdentifier()),
  287. $this->connection->quote($oid->getType())
  288. );
  289. }
  290. /**
  291. * Returns the primary key of the passed object identity.
  292. *
  293. * @param ObjectIdentityInterface $oid
  294. * @return integer
  295. */
  296. protected final function retrieveObjectIdentityPrimaryKey(ObjectIdentityInterface $oid)
  297. {
  298. return $this->connection->executeQuery($this->getSelectObjectIdentityIdSql($oid))->fetchColumn();
  299. }
  300. /**
  301. * This method is called when an ACL instance is retrieved from the cache.
  302. *
  303. * @param AclInterface $acl
  304. */
  305. private function updateAceIdentityMap(AclInterface $acl)
  306. {
  307. foreach (array('classAces', 'classFieldAces', 'objectAces', 'objectFieldAces') as $property) {
  308. $reflection = new \ReflectionProperty($acl, $property);
  309. $reflection->setAccessible(true);
  310. $value = $reflection->getValue($acl);
  311. if ('classAces' === $property || 'objectAces' === $property) {
  312. $this->doUpdateAceIdentityMap($value);
  313. } else {
  314. foreach ($value as $field => $aces) {
  315. $this->doUpdateAceIdentityMap($value[$field]);
  316. }
  317. }
  318. $reflection->setValue($acl, $value);
  319. $reflection->setAccessible(false);
  320. }
  321. }
  322. /**
  323. * Retrieves all the ids which need to be queried from the database
  324. * including the ids of parent ACLs.
  325. *
  326. * @param array $batch
  327. *
  328. * @return array
  329. */
  330. private function getAncestorIds(array $batch)
  331. {
  332. $sql = $this->getAncestorLookupSql($batch);
  333. $ancestorIds = array();
  334. foreach ($this->connection->executeQuery($sql)->fetchAll() as $data) {
  335. // FIXME: skip ancestors which are cached
  336. $ancestorIds[] = $data['ancestor_id'];
  337. }
  338. return $ancestorIds;
  339. }
  340. /**
  341. * Does either overwrite the passed ACE, or saves it in the global identity
  342. * map to ensure every ACE only gets instantiated once.
  343. *
  344. * @param array &$aces
  345. */
  346. private function doUpdateAceIdentityMap(array &$aces)
  347. {
  348. foreach ($aces as $index => $ace) {
  349. if (isset($this->loadedAces[$ace->getId()])) {
  350. $aces[$index] = $this->loadedAces[$ace->getId()];
  351. } else {
  352. $this->loadedAces[$ace->getId()] = $ace;
  353. }
  354. }
  355. }
  356. /**
  357. * This method is called for object identities which could not be retrieved
  358. * from the cache, and for which thus a database query is required.
  359. *
  360. * @param array $batch
  361. * @param array $sids
  362. * @param array $oidLookup
  363. *
  364. * @return \SplObjectStorage mapping object identities to ACL instances
  365. */
  366. private function lookupObjectIdentities(array $batch, array $sids, array $oidLookup)
  367. {
  368. $ancestorIds = $this->getAncestorIds($batch);
  369. if (!$ancestorIds) {
  370. throw new AclNotFoundException('There is no ACL for the given object identity.');
  371. }
  372. $sql = $this->getLookupSql($ancestorIds);
  373. $stmt = $this->connection->executeQuery($sql);
  374. return $this->hydrateObjectIdentities($stmt, $oidLookup, $sids);
  375. }
  376. /**
  377. * This method is called to hydrate ACLs and ACEs.
  378. *
  379. * This method was designed for performance; thus, a lot of code has been
  380. * inlined at the cost of readability, and maintainability.
  381. *
  382. * Keep in mind that changes to this method might severely reduce the
  383. * performance of the entire ACL system.
  384. *
  385. * @param Statement $stmt
  386. * @param array $oidLookup
  387. * @param array $sids
  388. * @throws \RuntimeException
  389. * @return \SplObjectStorage
  390. */
  391. private function hydrateObjectIdentities(Statement $stmt, array $oidLookup, array $sids)
  392. {
  393. $parentIdToFill = new \SplObjectStorage();
  394. $acls = $aces = $emptyArray = array();
  395. $oidCache = $oidLookup;
  396. $result = new \SplObjectStorage();
  397. $loadedAces =& $this->loadedAces;
  398. $loadedAcls =& $this->loadedAcls;
  399. $permissionGrantingStrategy = $this->permissionGrantingStrategy;
  400. // we need these to set protected properties on hydrated objects
  401. $aclReflection = new \ReflectionClass('Symfony\Component\Security\Acl\Domain\Acl');
  402. $aclClassAcesProperty = $aclReflection->getProperty('classAces');
  403. $aclClassAcesProperty->setAccessible(true);
  404. $aclClassFieldAcesProperty = $aclReflection->getProperty('classFieldAces');
  405. $aclClassFieldAcesProperty->setAccessible(true);
  406. $aclObjectAcesProperty = $aclReflection->getProperty('objectAces');
  407. $aclObjectAcesProperty->setAccessible(true);
  408. $aclObjectFieldAcesProperty = $aclReflection->getProperty('objectFieldAces');
  409. $aclObjectFieldAcesProperty->setAccessible(true);
  410. $aclParentAclProperty = $aclReflection->getProperty('parentAcl');
  411. $aclParentAclProperty->setAccessible(true);
  412. // fetchAll() consumes more memory than consecutive calls to fetch(),
  413. // but it is faster
  414. foreach ($stmt->fetchAll(\PDO::FETCH_NUM) as $data) {
  415. list($aclId,
  416. $objectIdentifier,
  417. $parentObjectIdentityId,
  418. $entriesInheriting,
  419. $classType,
  420. $aceId,
  421. $objectIdentityId,
  422. $fieldName,
  423. $aceOrder,
  424. $mask,
  425. $granting,
  426. $grantingStrategy,
  427. $auditSuccess,
  428. $auditFailure,
  429. $username,
  430. $securityIdentifier) = $data;
  431. // has the ACL been hydrated during this hydration cycle?
  432. if (isset($acls[$aclId])) {
  433. $acl = $acls[$aclId];
  434. // has the ACL been hydrated during any previous cycle, or was possibly loaded
  435. // from cache?
  436. } elseif (isset($loadedAcls[$classType][$objectIdentifier])) {
  437. $acl = $loadedAcls[$classType][$objectIdentifier];
  438. // keep reference in local array (saves us some hash calculations)
  439. $acls[$aclId] = $acl;
  440. // attach ACL to the result set; even though we do not enforce that every
  441. // object identity has only one instance, we must make sure to maintain
  442. // referential equality with the oids passed to findAcls()
  443. if (!isset($oidCache[$objectIdentifier.$classType])) {
  444. $oidCache[$objectIdentifier.$classType] = $acl->getObjectIdentity();
  445. }
  446. $result->attach($oidCache[$objectIdentifier.$classType], $acl);
  447. // so, this hasn't been hydrated yet
  448. } else {
  449. // create object identity if we haven't done so yet
  450. $oidLookupKey = $objectIdentifier.$classType;
  451. if (!isset($oidCache[$oidLookupKey])) {
  452. $oidCache[$oidLookupKey] = new ObjectIdentity($objectIdentifier, $classType);
  453. }
  454. $acl = new Acl((integer) $aclId, $oidCache[$oidLookupKey], $permissionGrantingStrategy, $emptyArray, !!$entriesInheriting);
  455. // keep a local, and global reference to this ACL
  456. $loadedAcls[$classType][$objectIdentifier] = $acl;
  457. $acls[$aclId] = $acl;
  458. // try to fill in parent ACL, or defer until all ACLs have been hydrated
  459. if (null !== $parentObjectIdentityId) {
  460. if (isset($acls[$parentObjectIdentityId])) {
  461. $aclParentAclProperty->setValue($acl, $acls[$parentObjectIdentityId]);
  462. } else {
  463. $parentIdToFill->attach($acl, $parentObjectIdentityId);
  464. }
  465. }
  466. $result->attach($oidCache[$oidLookupKey], $acl);
  467. }
  468. // check if this row contains an ACE record
  469. if (null !== $aceId) {
  470. // have we already hydrated ACEs for this ACL?
  471. if (!isset($aces[$aclId])) {
  472. $aces[$aclId] = array($emptyArray, $emptyArray, $emptyArray, $emptyArray);
  473. }
  474. // has this ACE already been hydrated during a previous cycle, or
  475. // possible been loaded from cache?
  476. // It is important to only ever have one ACE instance per actual row since
  477. // some ACEs are shared between ACL instances
  478. if (!isset($loadedAces[$aceId])) {
  479. if (!isset($sids[$key = ($username?'1':'0').$securityIdentifier])) {
  480. if ($username) {
  481. $sids[$key] = new UserSecurityIdentity(
  482. substr($securityIdentifier, 1 + $pos = strpos($securityIdentifier, '-')),
  483. substr($securityIdentifier, 0, $pos)
  484. );
  485. } else {
  486. $sids[$key] = new RoleSecurityIdentity($securityIdentifier);
  487. }
  488. }
  489. if (null === $fieldName) {
  490. $loadedAces[$aceId] = new Entry((integer) $aceId, $acl, $sids[$key], $grantingStrategy, (integer) $mask, !!$granting, !!$auditFailure, !!$auditSuccess);
  491. } else {
  492. $loadedAces[$aceId] = new FieldEntry((integer) $aceId, $acl, $fieldName, $sids[$key], $grantingStrategy, (integer) $mask, !!$granting, !!$auditFailure, !!$auditSuccess);
  493. }
  494. }
  495. $ace = $loadedAces[$aceId];
  496. // assign ACE to the correct property
  497. if (null === $objectIdentityId) {
  498. if (null === $fieldName) {
  499. $aces[$aclId][0][$aceOrder] = $ace;
  500. } else {
  501. $aces[$aclId][1][$fieldName][$aceOrder] = $ace;
  502. }
  503. } else {
  504. if (null === $fieldName) {
  505. $aces[$aclId][2][$aceOrder] = $ace;
  506. } else {
  507. $aces[$aclId][3][$fieldName][$aceOrder] = $ace;
  508. }
  509. }
  510. }
  511. }
  512. // We do not sort on database level since we only want certain subsets to be sorted,
  513. // and we are going to read the entire result set anyway.
  514. // Sorting on DB level increases query time by an order of magnitude while it is
  515. // almost negligible when we use PHPs array sort functions.
  516. foreach ($aces as $aclId => $aceData) {
  517. $acl = $acls[$aclId];
  518. ksort($aceData[0]);
  519. $aclClassAcesProperty->setValue($acl, $aceData[0]);
  520. foreach (array_keys($aceData[1]) as $fieldName) {
  521. ksort($aceData[1][$fieldName]);
  522. }
  523. $aclClassFieldAcesProperty->setValue($acl, $aceData[1]);
  524. ksort($aceData[2]);
  525. $aclObjectAcesProperty->setValue($acl, $aceData[2]);
  526. foreach (array_keys($aceData[3]) as $fieldName) {
  527. ksort($aceData[3][$fieldName]);
  528. }
  529. $aclObjectFieldAcesProperty->setValue($acl, $aceData[3]);
  530. }
  531. // fill-in parent ACLs where this hasn't been done yet cause the parent ACL was not
  532. // yet available
  533. $processed = 0;
  534. foreach ($parentIdToFill as $acl) {
  535. $parentId = $parentIdToFill->offsetGet($acl);
  536. // let's see if we have already hydrated this
  537. if (isset($acls[$parentId])) {
  538. $aclParentAclProperty->setValue($acl, $acls[$parentId]);
  539. $processed += 1;
  540. continue;
  541. }
  542. }
  543. // reset reflection changes
  544. $aclClassAcesProperty->setAccessible(false);
  545. $aclClassFieldAcesProperty->setAccessible(false);
  546. $aclObjectAcesProperty->setAccessible(false);
  547. $aclObjectFieldAcesProperty->setAccessible(false);
  548. $aclParentAclProperty->setAccessible(false);
  549. // this should never be true if the database integrity hasn't been compromised
  550. if ($processed < count($parentIdToFill)) {
  551. throw new \RuntimeException('Not all parent ids were populated. This implies an integrity problem.');
  552. }
  553. return $result;
  554. }
  555. }