1: <?php
2:
3: namespace Charcoal\User\Acl;
4:
5:
6: use PDO;
7: use PDOException;
8:
9:
10: use Psr\Log\LoggerAwareInterface;
11: use Psr\Log\LoggerAwareTrait;
12:
13:
14: use Zend\Permissions\Acl\Acl;
15: use Zend\Permissions\Acl\Role\GenericRole;
16:
17: 18: 19:
20: class Manager implements LoggerAwareInterface
21: {
22: use LoggerAwareTrait;
23:
24: 25: 26: 27: 28: 29:
30: public function __construct(array $data)
31: {
32: $this->setLogger($data['logger']);
33: }
34:
35: 36: 37: 38: 39: 40:
41: public function loadPermissions(Acl &$acl, array $permissions, $resource = '')
42: {
43: foreach ($permissions as $role => $rolePermissions) {
44: $this->addRoleAndPermissions($acl, $role, $rolePermissions, $resource);
45: }
46: }
47:
48: 49: 50: 51: 52: 53: 54:
55: public function loadDatabasePermissions(Acl &$acl, PDO $db, $table, $resource = '')
56: {
57:
58: $table = preg_replace('/[^A-Za-z0-9_]/', '', $table);
59:
60: $q = '
61: SELECT
62: `ident`,
63: `parent`,
64: `denied`,
65: `allowed`,
66: `superuser`
67: FROM
68: `'.$table.'`
69: ORDER BY
70: `position` ASC';
71:
72: $this->logger->debug($q);
73:
74:
75: try {
76: $sth = $db->query($q);
77: while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
78: $this->addRoleAndPermissions($acl, $row['ident'], $row, $resource);
79: }
80: } catch (PDOException $e) {
81: $this->logger->warning('Can not fetch ACL roles: '.$e->getMessage());
82: }
83: }
84:
85: 86: 87: 88: 89: 90: 91:
92: private function addRoleAndPermissions(Acl &$acl, $role, array $permissions, $resource)
93: {
94: if (!$acl->hasRole($role)) {
95:
96: $parentRole = isset($permissions['parent']) ? $permissions['parent'] : null;
97: $parentRole = $parentRole ?: null;
98: $newRole = new GenericRole($role);
99: $acl->addRole($newRole, $parentRole);
100: }
101:
102: if (isset($permissions['superuser']) && $permissions['superuser']) {
103: $acl->allow($role);
104:
105: return;
106: }
107:
108: if (isset($permissions['allowed'])) {
109: if (is_string($permissions['allowed'])) {
110: $allowedPermissions = explode(',', $permissions['allowed']);
111: } else {
112: $allowedPermissions = $permissions['allowed'];
113: }
114: foreach ($allowedPermissions as $allowed) {
115: $acl->allow($role, $resource, $allowed);
116: }
117: }
118:
119: if (isset($permissions['denied'])) {
120: if (is_string($permissions['denied'])) {
121: $deniedPermissions = explode(',', $permissions['denied']);
122: } else {
123: $deniedPermissions = $permissions['denied'];
124: }
125: foreach ($deniedPermissions as $denied) {
126: $acl->deny($role, $resource, $denied);
127: }
128: }
129: }
130: }
131: