1 <?php
2 /**
3 * Permission.php
4 *
5 * @author Elvyrra SAS
6 * @license http://rem.mit-license.org/ MIT
7 */
8
9 namespace Hawk;
10
11 /**
12 * This class describes the permission model
13 *
14 * @package BaseModels
15 */
16 class Permission extends Model{
17 /**
18 * The associated table
19 */
20 protected static $tablename = "Permission";
21
22 /**
23 * The id of the permission giving rights on all permissions
24 */
25 const ALL_PRIVILEGES_ID = 1;
26
27 /**
28 * The name of the permission giving rights on all permissions
29 */
30 const ALL_PRIVILEGES_NAME = 'admin.all';
31
32
33 /**
34 * Get all permissions, grouped by plugin name
35 *
36 * @return array The list of permissions, indexed by the plugins names, where each element is an array contaning the plugin permissions
37 */
38 public static function getAllGroupByPlugin(){
39 $permissions = self::getAll();
40 $groups = array();
41 foreach($permissions as $permission){
42 if(!isset($groups[$permission->plugin])) {
43 $groups[$permission->plugin] = array();
44 }
45
46 $groups[$permission->plugin][] = $permission;
47 }
48
49 return $groups;
50 }
51
52
53 /**
54 * Get all the permissions for a given plugin
55 *
56 * @param string $plugin The plugin name
57 *
58 * @return array The list of found permissions
59 */
60 public static function getPluginPermissions($plugin){
61 return self::getListByExample(new DBExample(array('plugin' => $plugin)));
62 }
63
64
65 /**
66 * Get a permission by it name, formatted as <plugin>.<permissionName>
67 *
68 * @param string $name The permission name
69 *
70 * @return Permission The found permission
71 */
72 public static function getByName($name){
73 list($plugin, $key) = explode('.', $name);
74
75 return self::getByExample(new DBExample(array('plugin' => $plugin, 'key' => $key)));
76 }
77
78
79 /**
80 * Add a new permission in the database
81 *
82 * @param string $name The permission name, formatted as "<plugin>.<key>"
83 * @param int $default The default value for this permission
84 * @param int $availableForGuest Defines if the permission can be set to true for guest users
85 *
86 * @return Permission The created permission
87 */
88 public static function add($name, $default = 1, $availableForGuest = 0){
89 list($plugin, $key) = explode('.', $name);
90 $permission = parent::add(
91 array(
92 'plugin' => $plugin,
93 'key' => $key,
94 'availableForGuests' => $availableForGuest
95 )
96 );
97
98 $roles = Role::getAll();
99 foreach($roles as $role){
100 $value = $role->id == Role::GUEST_ROLE_ID ? ($availableForGuest ? $default : 0) : $default;
101 RolePermission::add(
102 array(
103 'roleId' => $role->id,
104 'permissionId' => $permission->id,
105 'value' => $value
106 )
107 );
108 }
109
110 return $permission;
111 }
112 }