1 <?php
2
3 /*
4 * This file is part of the Icybee package.
5 *
6 * (c) Olivier Laviale <olivier.laviale@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Icybee\Modules\Users\Roles;
13
14 /**
15 * A user role.
16 */
17 class Role extends \ICanBoogie\ActiveRecord
18 {
19 const RID = 'rid';
20 const NAME = 'name';
21 const PERMS = 'perms';
22 const SERIALIZED_PERMS = 'serialized_perms';
23 const GUEST_RID = 1;
24 const USER_RID = 2;
25
26 static public $permission_levels = array
27 (
28 'none' => Module::PERMISSION_NONE,
29 'access' => Module::PERMISSION_ACCESS,
30 'create' => Module::PERMISSION_CREATE,
31 'maintain' => Module::PERMISSION_MAINTAIN,
32 'manage' => Module::PERMISSION_MANAGE,
33 'administer' => Module::PERMISSION_ADMINISTER
34 );
35
36 public $rid;
37 public $name;
38 public $serialized_perms;
39
40 public function __construct($model='users.roles')
41 {
42 parent::__construct($model);
43 }
44
45 /**
46 * TODO-20130121: This is a workaround to include `perms` in the array so that is is same by
47 * the model. What we should do is map perms to serialized perms, and maybe create a
48 * Permissions object for this purpose.
49 */
50 public function to_array()
51 {
52 return parent::to_array() + array
53 (
54 'perms' => $this->perms
55 );
56 }
57
58 protected function lazy_get_perms()
59 {
60 return (array) json_decode($this->serialized_perms, true);
61 }
62
63 public function has_permission($access, $module=null)
64 {
65 // \ICanBoogie\log('has permission ? access: <em>\1</em>, module: <em>\2</em>', $access, (string) $module);
66
67 $perms = $this->perms;
68
69 #
70 # check 'as is' for permissions like 'modify own module';
71 #
72
73 if (is_string($access))
74 {
75 if (isset($perms[$access]))
76 {
77 return true;
78 }
79
80 if (isset(self::$permission_levels[$access]))
81 {
82 $access = self::$permission_levels[$access];
83 }
84 else
85 {
86 #
87 # the special permission is not defined in our permission
88 # and since it's not a standard permission level we can
89 # return false
90 #
91
92 return false;
93 }
94 }
95
96 #
97 # check modules based permission level
98 #
99
100 if (is_object($module))
101 {
102 $module = (string) $module;
103 }
104
105 if (isset($perms[$module]))
106 {
107 $level = $perms[$module];
108
109 if ($level >= $access)
110 {
111 #
112 # we return the real permission level, not 'true'
113 #
114
115 return $level;
116 }
117 }
118
119 #
120 # if the permission level was not defined in the module scope
121 # we check the global scope
122 #
123
124 else if (isset($perms['all']))
125 {
126 $level = $perms['all'];
127
128 if ($level >= $access)
129 {
130 #
131 # we return the real permission level, not 'true'
132 #
133
134 return $level;
135 }
136 }
137
138 return false;
139 }
140 }