/
Group.php
432 lines (368 loc) · 13 KB
/
Group.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
<?php
/**
* A security group.
*
* @package sapphire
* @subpackage security
*/
class Group extends DataObject {
static $db = array(
"Title" => "Varchar",
"Description" => "Text",
"Code" => "Varchar",
"Locked" => "Boolean",
"Sort" => "Int",
"IPRestrictions" => "Text",
"HtmlEditorConfig" => "Varchar"
);
static $has_one = array(
"Parent" => "Group",
);
static $has_many = array(
"Permissions" => "Permission",
"Groups" => "Group"
);
static $many_many = array(
"Members" => "Member",
"Roles" => "PermissionRole",
);
static $extensions = array(
"Hierarchy",
);
function getAllParents() {
$doSet = new DataObjectSet();
$parentID = $this->ParentID;
while($parentID) {
$parent = DataObject::get_by_id('Group', $parentID);
$doSet->push($parent);
$parentID = $parent->ParentID;
}
return $doSet;
}
/**
* Caution: Only call on instances, not through a singleton.
*
* @return FieldSet
*/
public function getCMSFields() {
$fields = new FieldSet(
new TabSet("Root",
new Tab(_t('SecurityAdmin.MEMBERS', 'Members'),
new TextField("Title", $this->fieldLabel('Title')),
$memberList = new MemberTableField(
$this,
"Members",
$this,
null,
false
)
),
$permissionsTab = new Tab(_t('SecurityAdmin.PERMISSIONS', 'Permissions'),
new LiteralField(
"",
"<p>" .
_t('SecurityAdmin.ADVANCEDONLY',
"This section is for advanced users only.
See <a href=\"http://doc.silverstripe.com/doku.php?id=permissions:codes\" target=\"_blank\">this page</a>
for more information."
) .
"</p>"
),
new DropdownField('HtmlEditorConfig', 'HTML Editor Configuration', HtmlEditorConfig::get_available_configs_map()),
new PermissionCheckboxSetField(
'Permissions',
'Permissions',
'Permission',
'GroupID',
$this)
),
new Tab(_t('Security.IPADDRESSES', 'IP Addresses'),
new LiteralField("", _t('SecurityAdmin.IPADDRESSESHELP',"<p>You can restrict this group to a particular
IP address range (one range per line). <br />Ranges can be in any of the following forms: <br />
203.96.152.12<br />
203.96.152/24<br />
203.96/16<br />
203/8<br /><br />If you enter one or more IP address ranges in this box, then members will only get
the rights of being in this group if they log on from one of the valid IP addresses. It won't prevent
people from logging in. This is because the same user might have to log in to access parts of the
system without IP address restrictions.")),
new TextareaField("IPRestrictions", "IP Ranges", 10)
)
)
);
if(!Permission::check('EDIT_PERMISSIONS')) {
$fields->removeFieldFromTab('Root', 'Permissions');
$fields->removeFieldFromTab('Root', 'IP Addresses');
} else {
// $parentGroups = $this->getAllParents();
// if ($parentGroups) {
// foreach ($parentGroups as $parent) {
// if ($parent->Permissions()->Count()) {
// $permissionsTab->push(new HeaderField('PermissionHeader-'.$parent->ID, 'Permissions inherited from '.$parent->Title));
// $permissionsTab->push(new LiteralField('PermissionList-'.$parent->ID, join(', ', $parent->Permissions()->column('Code'))));
// }
// }
// }
}
if(Permission::check('APPLY_ROLES') && DataObject::get('PermissionRole')) {
$fields->addFieldToTab('Root.' . _t('SecurityAdmin.ROLES', 'Roles'),
new LiteralField(
"",
"<p>" .
_t('SecurityAdmin.ROLESDESCRIPTION',
"This section allows you to add roles to this group. Roles are logical groupings of permissions, which can be editied in the Roles tab"
) .
"</p>"
)
);
$roleData = Permission::check('ADMIN') ? DataObject::get('PermissionRole') : DataObject::get('PermissionRole', 'OnlyAdminCanApply = 0');
$fields->addFieldToTab('Root.' . _t('SecurityAdmin.ROLES', 'Roles'), new CheckboxSetField('Roles', 'Roles', $roleData));
// $parentGroups = $this->getAllParents();
// if ($parentGroups) {
// foreach ($parentGroups as $parent) {
// if ($parent->Roles()->Count()) {
// $fields->addFieldToTab('Root.' . _t('SecurityAdmin.ROLES', 'Roles'), new HeaderField('RolesHeader-'.$parent->ID, 'Roles inherited from '.$parent->Title));
// $fields->addFieldToTab('Root.' . _t('SecurityAdmin.ROLES', 'Roles'), new LiteralField('RolesList-'.$parent->ID, join(', ', $parent->Roles()->column('Title'))));
// }
// }
// }
}
$memberList->setController($this);
$memberList->setPermissions(array('show', 'edit', 'delete', 'export', 'add'));
$memberList->setParentClass('Group');
$memberList->setPopupCaption(_t('SecurityAdmin.VIEWUSER', 'View User'));
$fields->push($idField = new HiddenField("ID"));
$this->extend('updateCMSFields', $fields);
return $fields;
}
/**
*
* @param boolean $includerelations a boolean value to indicate if the labels returned include relation fields
*
*/
function fieldLabels($includerelations = true) {
$labels = parent::fieldLabels($includerelations);
$labels['Title'] = _t('SecurityAdmin.GROUPNAME', 'Group name');
$labels['Description'] = _t('Group.Description', 'Description');
$labels['Code'] = _t('Group.Code', 'Group Code', PR_MEDIUM, 'Programmatical code identifying a group');
$labels['Locked'] = _t('Group.Locked', 'Locked?', PR_MEDIUM, 'Group is locked in the security administration area');
$labels['Sort'] = _t('Group.Sort', 'Sort Order');
$labels['IPRestrictions'] = _t('Group.IPRestrictions', 'IP Address Restrictions');
if($includerelations){
$labels['Parent'] = _t('Group.Parent', 'Parent Group', PR_MEDIUM, 'One group has one parent group');
$labels['Permissions'] = _t('Group.has_many_Permissions', 'Permissions', PR_MEDIUM, 'One group has many permissions');
$labels['Members'] = _t('Group.many_many_Members', 'Members', PR_MEDIUM, 'One group has many members');
}
return $labels;
}
/**
* Add a member to a group.
*
* @param DataObject $member
* @param string $groupcode
*/
static function addToGroupByName($member, $groupcode) {
$group = DataObject::get_one('Group', "\"Code\" = '" . Convert::raw2sql($groupcode). "'");
if($group) {
$member->Groups()->add($group);
$member->write();
}
}
/**
* Overloaded getter.
*
* @TODO Where is this used, why is this overloaded?
*
* @param $limit string SQL
* @param $offset int
* @param $filter string SQL
* @param $sort string SQL
* @param $join string SQL
* @return ComponentSet
*/
public function Members($limit = "", $offset = "", $filter = "", $sort = "", $join = "") {
$table = "Group_Members";
if($filter) $filter = is_array($filter) ? $filter : array($filter);
if( is_numeric( $limit ) ) {
if( is_numeric( $offset ) )
$limit = "$limit OFFSET $offset";
else
$limit = "$limit OFFSET 0";
} else {
$limit = "";
}
// Get all of groups that this group contains
$groupFamily = implode(", ", $this->collateFamilyIDs());
$filter[] = "\"$table\".\"GroupID\" IN ($groupFamily)";
$join .= " INNER JOIN \"$table\" ON \"$table\".\"MemberID\" = \"Member\".\"ID\"" . Convert::raw2sql($join);
$result = singleton("Member")->instance_get(
$filter,
$sort,
$join,
$limit,
"ComponentSet" // datatype
);
if(!$result) $result = new ComponentSet();
$result->setComponentInfo("many-to-many", $this, "Group", $table, "Member");
foreach($result as $item) $item->GroupID = $this->ID;
return $result;
}
public function map($filter = "", $sort = "", $blank="") {
$ret = new SQLMap(singleton('Group')->extendedSQL($filter, $sort));
if($blank){
$blankGroup = new Group();
$blankGroup->Title = $blank;
$blankGroup->ID = 0;
$ret->getItems()->shift($blankGroup);
}
return $ret;
}
/**
* Return a set of this record's "family" of IDs - the IDs of
* this record and all its descendants.
* @return array
*/
public function collateFamilyIDs() {
$familyIDs = array();
$chunkToAdd = array(array("ID" => $this->ID));
while($chunkToAdd) {
$idList = array();
foreach($chunkToAdd as $item) {
$idList[] = $item['ID'];
$familyIDs[] = $item['ID'];
}
$idList = implode(',', $idList);
// Get the children of *all* the groups identified in the previous chunk.
// This minimises the number of SQL queries necessary
$sql = $this->extendedSQL("\"ParentID\" IN ($idList)", "");
$dbResult = $sql->execute();
$chunkToAdd = array();
foreach($dbResult as $item) $chunkToAdd[] = $item;
}
return $familyIDs;
}
/**
* Returns an array of the IDs of this group and all its parents
*/
public function collateAncestorIDs() {
$parent = $this;
while(isset($parent)) {
$items[] = $parent->ID;
$parent = $parent->Parent;
}
return $items;
}
/**
* Override this so groups are ordered in the CMS
*/
public function stageChildren() {
return DataObject::get('Group', "\"Group\".\"ParentID\" = " . (int)$this->ID . " AND \"Group\".\"ID\" != " . (int)$this->ID, '"Sort"');
}
public function getTreeTitle() {
if($this->hasMethod('alternateTreeTitle')) return $this->alternateTreeTitle();
else return $this->Title;
}
/**
* Overloaded to ensure the code is always descent.
*/
public function setCode($val){
$this->setField("Code",SiteTree::generateURLSegment($val));
}
function onBeforeWrite() {
parent::onBeforeWrite();
if(stripos($this->Code, 'new-') === 0) {
$this->setCode($this->Title);
}
}
/**
* Checks for permission-code CMS_ACCESS_SecurityAdmin.
* If the group has ADMIN permissions, it requires the user to have ADMIN permissions as well.
*
* @param $member Member
* @return boolean
*/
public function canEdit($member = null) {
if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) $member = Member::currentUser();
// DEPRECATED 2.3: use canView() instead
$results = $this->extend('alternateCanView', $member);
if($results && is_array($results)) if(!min($results)) return false;
// decorated access checks
$results = $this->extend('canEdit', $member);
if($results && is_array($results)) if(!min($results)) return false;
if(
// either we have an ADMIN
(bool)Permission::checkMember($member, "ADMIN")
|| (
// or a privileged CMS user and a group without ADMIN permissions.
// without this check, a user would be able to add himself to an administrators group
// with just access to the "Security" admin interface
Permission::checkMember($member, "CMS_ACCESS_SecurityAdmin") &&
!DataObject::get("Permission", "GroupID = $this->ID AND Code = 'ADMIN'")
)
) {
return true;
}
return false;
}
/**
* Checks for permission-code CMS_ACCESS_SecurityAdmin.
*
* @param $member Member
* @return boolean
*/
public function canView($member = null) {
if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) $member = Member::currentUser();
// DEPRECATED 2.3: use canView() instead
$results = $this->extend('alternateCanView', $member);
if($results && is_array($results)) if(!min($results)) return false;
// decorated access checks
$results = $this->extend('canView', $member);
if($results && is_array($results)) if(!min($results)) return false;
// user needs access to CMS_ACCESS_SecurityAdmin
if(Permission::checkMember($member, "CMS_ACCESS_SecurityAdmin")) return true;
return false;
}
public function canDelete($member = null) {
if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) $member = Member::currentUser();
// decorated access checks
$results = $this->extend('canDelete', $member);
if($results && is_array($results)) if(!min($results)) return false;
return $this->canEdit($member);
}
/**
* Returns all of the children for the CMS Tree.
* Filters to only those groups that the current user can edit
*/
function AllChildrenIncludingDeleted() {
$extInstance = $this->extInstance('Hierarchy');
$extInstance->setOwner($this);
$children = $extInstance->AllChildrenIncludingDeleted();
$extInstance->clearOwner();
$filteredChildren = new DataObjectSet();
if($children) foreach($children as $child) {
if($child->canView()) $filteredChildren->push($child);
}
return $filteredChildren;
}
/**
* Returns true if the given IP address is granted access to this group.
* For unrestricted groups, this always returns true.
*/
function allowedIPAddress($ip) {
if(!$this->IPRestrictions) return true;
if(!$ip) return false;
$ipPatterns = explode("\n", $this->IPRestrictions);
foreach($ipPatterns as $ipPattern) {
$ipPattern = trim($ipPattern);
if(preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/', $ipPattern, $matches)) {
if($ip == $ipPattern) return true;
} else if(preg_match('/^([0-9]+\.[0-9]+\.[0-9]+)\/24$/', $ipPattern, $matches)
|| preg_match('/^([0-9]+\.[0-9]+)\/16$/', $ipPattern, $matches)
|| preg_match('/^([0-9]+)\/8$/', $ipPattern, $matches)) {
if(substr($ip, 0, strlen($matches[1])) == $matches[1]) return true;
}
}
return false;
}
}
?>