/
InheritedPermissions.php
827 lines (743 loc) · 25.4 KB
/
InheritedPermissions.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
<?php
namespace SilverStripe\Security;
use InvalidArgumentException;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\ORM\DataList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\Hierarchy\Hierarchy;
use SilverStripe\Versioned\Versioned;
use Psr\SimpleCache\CacheInterface;
use SilverStripe\Core\Cache\MemberCacheFlusher;
/**
* Calculates batch permissions for nested objects for:
* - canView: Supports 'Anyone' type
* - canEdit
* - canDelete: Includes special logic for ensuring parent objects can only be deleted if their children can
* be deleted also.
*/
class InheritedPermissions implements PermissionChecker, MemberCacheFlusher
{
use Injectable;
/**
* Delete permission
*/
public const DELETE = 'delete';
/**
* View permission
*/
public const VIEW = 'view';
/**
* Edit permission
*/
public const EDIT = 'edit';
/**
* Anyone canView permission
*/
public const ANYONE = 'Anyone';
/**
* Restrict to logged in users
*/
public const LOGGED_IN_USERS = 'LoggedInUsers';
/**
* @TODO - rename this to ONLY_THESE_GROUPS
* Restrict to specific groups
*/
public const ONLY_THESE_USERS = 'OnlyTheseUsers';
/**
* Restrict to specific members
*/
public const ONLY_THESE_MEMBERS = 'OnlyTheseMembers';
/**
* Inherit from parent
*/
public const INHERIT = 'Inherit';
/**
* Class name
*
* @var string
*/
protected $baseClass = null;
/**
* Object for evaluating top level permissions designed as "Inherit"
*
* @var DefaultPermissionChecker
*/
protected $defaultPermissions = null;
/**
* Global permissions required to edit.
* If empty no global permissions are required
*
* @var array
*/
protected $globalEditPermissions = [];
/**
* Cache of permissions
*
* @var array
*/
protected $cachePermissions = [];
/**
* @var CacheInterface
*/
protected $cacheService;
/**
* Construct new permissions object
*
* @param string $baseClass Base class
* @param CacheInterface $cache
*/
public function __construct($baseClass, CacheInterface $cache = null)
{
if (!is_a($baseClass, DataObject::class, true)) {
throw new InvalidArgumentException('Invalid DataObject class: ' . $baseClass);
}
$this->baseClass = $baseClass;
$this->cacheService = $cache;
return $this;
}
/**
* Commits the cache
*/
public function __destruct()
{
// Ensure back-end cache is updated
if (!empty($this->cachePermissions) && $this->cacheService) {
foreach ($this->cachePermissions as $key => $permissions) {
$this->cacheService->set($key, $permissions);
}
// Prevent double-destruct
$this->cachePermissions = [];
}
}
/**
* Clear the cache for this instance only
*
* @param array $memberIDs A list of member IDs
*/
public function flushMemberCache($memberIDs = null)
{
if (!$this->cacheService) {
return;
}
// Hard flush, e.g. flush=1
if (!$memberIDs) {
$this->cacheService->clear();
}
if ($memberIDs && is_array($memberIDs)) {
foreach ([self::VIEW, self::EDIT, self::DELETE] as $type) {
foreach ($memberIDs as $memberID) {
$key = $this->generateCacheKey($type, $memberID);
$this->cacheService->delete($key);
}
}
}
}
/**
* @param DefaultPermissionChecker $callback
* @return $this
*/
public function setDefaultPermissions(DefaultPermissionChecker $callback)
{
$this->defaultPermissions = $callback;
return $this;
}
/**
* Global permissions required to edit
*
* @param array $permissions
* @return $this
*/
public function setGlobalEditPermissions($permissions)
{
$this->globalEditPermissions = $permissions;
return $this;
}
/**
* @return array
*/
public function getGlobalEditPermissions()
{
return $this->globalEditPermissions;
}
/**
* Get root permissions handler, or null if no handler
*
* @return DefaultPermissionChecker|null
*/
public function getDefaultPermissions()
{
return $this->defaultPermissions;
}
/**
* Get base class
*
* @return string
*/
public function getBaseClass()
{
return $this->baseClass;
}
/**
* Force pre-calculation of a list of permissions for optimisation
*
* @param string $permission
* @param array $ids
*/
public function prePopulatePermissionCache($permission = 'edit', $ids = [])
{
switch ($permission) {
case self::EDIT:
$this->canEditMultiple($ids, Security::getCurrentUser(), false);
break;
case self::VIEW:
$this->canViewMultiple($ids, Security::getCurrentUser(), false);
break;
case self::DELETE:
$this->canDeleteMultiple($ids, Security::getCurrentUser(), false);
break;
default:
throw new InvalidArgumentException("Invalid permission type $permission");
}
}
/**
* This method is NOT a full replacement for the individual can*() methods, e.g. {@link canEdit()}. Rather than
* checking (potentially slow) PHP logic, it relies on the database group associations, e.g. the "CanEditType" field
* plus the "SiteTree_EditorGroups" many-many table. By batch checking multiple records, we can combine the queries
* efficiently.
*
* Caches based on $typeField data. To invalidate the cache, use {@link SiteTree::reset()} or set the $useCached
* property to FALSE.
*
* @param string $type Either edit, view, or create
* @param array $ids Array of IDs
* @param Member $member Member
* @param array $globalPermission If the member doesn't have this permission code, don't bother iterating deeper
* @param bool $useCached Enables use of cache. Cache will be populated even if this is false.
* @return array A map of permissions, keys are ID numbers, and values are boolean permission checks
* ID keys to boolean values
*/
protected function batchPermissionCheck(
$type,
$ids,
Member $member = null,
$globalPermission = [],
$useCached = true
) {
// Validate ids
$ids = array_filter($ids ?? [], 'is_numeric');
if (empty($ids)) {
return [];
}
// Default result: nothing editable
$result = array_fill_keys($ids ?? [], false);
// Validate member permission
// Only VIEW allows anonymous (Anyone) permissions
$memberID = $member ? (int)$member->ID : 0;
if (!$memberID && $type !== self::VIEW) {
return $result;
}
// Look in the cache for values
$cacheKey = $this->generateCacheKey($type, $memberID);
$cachePermissions = $this->getCachePermissions($cacheKey);
if ($useCached && $cachePermissions) {
$cachedValues = array_intersect_key($cachePermissions ?? [], $result);
// If we can't find everything in the cache, then look up the remainder separately
$uncachedIDs = array_keys(array_diff_key($result ?? [], $cachePermissions));
if ($uncachedIDs) {
$uncachedValues = $this->batchPermissionCheck($type, $uncachedIDs, $member, $globalPermission, false);
return $cachedValues + $uncachedValues;
}
return $cachedValues;
}
// If a member doesn't have a certain permission then they can't edit anything
if ($globalPermission && !Permission::checkMember($member, $globalPermission)) {
return $result;
}
// Get the groups that the given member belongs to
$groupIDsSQLList = '0';
if ($memberID) {
$groupIDs = $member->Groups()->column("ID");
$groupIDsSQLList = implode(", ", $groupIDs) ?: '0';
}
// Check if record is versioned
if ($this->isVersioned()) {
// Check all records for each stage and merge
$combinedStageResult = [];
foreach ([Versioned::DRAFT, Versioned::LIVE] as $stage) {
$stageRecords = Versioned::get_by_stage($this->getBaseClass(), $stage)
->byIDs($ids);
// Exclude previously calculated records from later stage calculations
if ($combinedStageResult) {
$stageRecords = $stageRecords->exclude('ID', array_keys($combinedStageResult ?? []));
}
$stageResult = $this->batchPermissionCheckForStage(
$type,
$globalPermission,
$stageRecords,
$groupIDsSQLList,
$member
);
// Note: Draft stage takes precedence over live, but only if draft exists
$combinedStageResult = $combinedStageResult + $stageResult;
}
} else {
// Unstaged result
$stageRecords = DataObject::get($this->getBaseClass())->byIDs($ids);
$combinedStageResult = $this->batchPermissionCheckForStage(
$type,
$globalPermission,
$stageRecords,
$groupIDsSQLList,
$member
);
}
// Cache the results
if (empty($this->cachePermissions[$cacheKey])) {
$this->cachePermissions[$cacheKey] = [];
}
if ($combinedStageResult) {
$this->cachePermissions[$cacheKey] = $combinedStageResult + $this->cachePermissions[$cacheKey];
}
return $combinedStageResult;
}
/**
* @param string $type
* @param array $globalPermission List of global permissions
* @param DataList $stageRecords List of records to check for this stage
* @param string $groupIDsSQLList Group IDs this member belongs to
* @param Member $member
* @return array
*/
protected function batchPermissionCheckForStage(
$type,
$globalPermission,
DataList $stageRecords,
$groupIDsSQLList,
Member $member = null
) {
// Initialise all IDs to false
$result = array_fill_keys($stageRecords->column('ID') ?? [], false);
// Get the uninherited permissions
$typeField = $this->getPermissionField($type);
$baseTable = DataObject::getSchema()->baseDataTable($this->getBaseClass());
if ($member && $member->ID) {
if (!Permission::checkMember($member, 'ADMIN')) {
// Determine if this member matches any of the group or other rules
$groupJoinTable = $this->getGroupJoinTable($type);
$memberJoinTable = $this->getMemberJoinTable($type);
$uninheritedPermissions = $stageRecords
->where([
"(\"$typeField\" IN (?, ?)"
. " OR (\"$typeField\" = ? AND \"$groupJoinTable\".\"{$baseTable}ID\" IS NOT NULL)"
. " OR (\"$typeField\" = ? AND \"$memberJoinTable\".\"{$baseTable}ID\" IS NOT NULL)"
. ")"
=> [
self::ANYONE,
self::LOGGED_IN_USERS,
self::ONLY_THESE_USERS,
self::ONLY_THESE_MEMBERS,
]
])
->leftJoin(
$groupJoinTable,
"\"$groupJoinTable\".\"{$baseTable}ID\" = \"{$baseTable}\".\"ID\" AND " . "\"$groupJoinTable\".\"GroupID\" IN ($groupIDsSQLList)"
)->leftJoin(
$memberJoinTable,
"\"$memberJoinTable\".\"{$baseTable}ID\" = \"{$baseTable}\".\"ID\" AND " . "\"$memberJoinTable\".\"MemberID\" = {$member->ID}"
)->column('ID');
} else {
$uninheritedPermissions = $stageRecords->column('ID');
}
} else {
// Only view pages with ViewType = Anyone if not logged in
$uninheritedPermissions = $stageRecords
->filter($typeField, self::ANYONE)
->column('ID');
}
if ($uninheritedPermissions) {
// Set all the relevant items in $result to true
$result = array_fill_keys($uninheritedPermissions ?? [], true) + $result;
}
// This looks for any of our subjects who has their permission set to "inherited" in the CMS.
// We group these and run a batch permission check on all parents. This gives us the result
// of whether the user has permission to edit this object.
$groupedByParent = [];
$potentiallyInherited = $stageRecords->filter($typeField, self::INHERIT)
->orderBy("\"{$baseTable}\".\"ID\"")
->dataQuery()
->query()
->setSelect([
"\"{$baseTable}\".\"ID\"",
"\"{$baseTable}\".\"ParentID\""
])
->execute();
foreach ($potentiallyInherited as $item) {
/** @var DataObject|Hierarchy $item */
if ($item['ParentID']) {
if (!isset($groupedByParent[$item['ParentID']])) {
$groupedByParent[$item['ParentID']] = [];
}
$groupedByParent[$item['ParentID']][] = $item['ID'];
} else {
// Fail over to default permission check for Inherit and ParentID = 0
$result[$item['ID']] = $this->checkDefaultPermissions($type, $member);
}
}
// Copy permissions from parent to child
if (!empty($groupedByParent)) {
$actuallyInherited = $this->batchPermissionCheck(
$type,
array_keys($groupedByParent ?? []),
$member,
$globalPermission
);
if ($actuallyInherited) {
$parentIDs = array_keys(array_filter($actuallyInherited ?? []));
foreach ($parentIDs as $parentID) {
// Set all the relevant items in $result to true
$result = array_fill_keys($groupedByParent[$parentID] ?? [], true) + $result;
}
}
}
return $result;
}
/**
* @param array $ids
* @param Member|null $member
* @param bool $useCached
* @return array
*/
public function canEditMultiple($ids, Member $member = null, $useCached = true)
{
return $this->batchPermissionCheck(
self::EDIT,
$ids,
$member,
$this->getGlobalEditPermissions(),
$useCached
);
}
/**
* @param array $ids
* @param Member|null $member
* @param bool $useCached
* @return array
*/
public function canViewMultiple($ids, Member $member = null, $useCached = true)
{
return $this->batchPermissionCheck(self::VIEW, $ids, $member, [], $useCached);
}
/**
* @param array $ids
* @param Member|null $member
* @param bool $useCached
* @return array
*/
public function canDeleteMultiple($ids, Member $member = null, $useCached = true)
{
// Validate ids
$ids = array_filter($ids ?? [], 'is_numeric');
if (empty($ids)) {
return [];
}
$result = array_fill_keys($ids ?? [], false);
// Validate member permission
if (!$member || !$member->ID) {
return $result;
}
$deletable = [];
// Look in the cache for values
$cacheKey = "delete-{$member->ID}";
$cachePermissions = $this->getCachePermissions($cacheKey);
if ($useCached && $cachePermissions) {
$cachedValues = array_intersect_key($cachePermissions[$cacheKey] ?? [], $result);
// If we can't find everything in the cache, then look up the remainder separately
$uncachedIDs = array_keys(array_diff_key($result ?? [], $cachePermissions[$cacheKey]));
if ($uncachedIDs) {
$uncachedValues = $this->canDeleteMultiple($uncachedIDs, $member, false);
return $cachedValues + $uncachedValues;
}
return $cachedValues;
}
// You can only delete pages that you can edit
$editableIDs = array_keys(array_filter($this->canEditMultiple($ids, $member) ?? []));
if ($editableIDs) {
// You can only delete pages whose children you can delete
$childRecords = DataObject::get($this->baseClass)
->filter('ParentID', $editableIDs);
// Find out the children that can be deleted
$children = $childRecords->map("ID", "ParentID");
$childIDs = $children->keys();
if ($childIDs) {
$deletableChildren = $this->canDeleteMultiple($childIDs, $member);
// Get a list of all the parents that have no undeletable children
$deletableParents = array_fill_keys($editableIDs ?? [], true);
foreach ($deletableChildren as $id => $canDelete) {
if (!$canDelete) {
unset($deletableParents[$children[$id]]);
}
}
// Use that to filter the list of deletable parents that have children
$deletableParents = array_keys($deletableParents ?? []);
// Also get the $ids that don't have children
$parents = array_unique($children->values() ?? []);
$deletableLeafNodes = array_diff($editableIDs ?? [], $parents);
// Combine the two
$deletable = array_merge($deletableParents, $deletableLeafNodes);
} else {
$deletable = $editableIDs;
}
}
// Convert the array of deletable IDs into a map of the original IDs with true/false as the value
return array_fill_keys($deletable ?? [], true) + array_fill_keys($ids ?? [], false);
}
/**
* @param int $id
* @param Member|null $member
* @return bool|mixed
*/
public function canDelete($id, Member $member = null)
{
// No ID: Check default permission
if (!$id) {
return $this->checkDefaultPermissions(self::DELETE, $member);
}
// Regular canEdit logic is handled by canEditMultiple
$results = $this->canDeleteMultiple(
[$id],
$member
);
// Check if in result
return isset($results[$id]) ? $results[$id] : false;
}
/**
* @param int $id
* @param Member|null $member
* @return bool|mixed
*/
public function canEdit($id, Member $member = null)
{
// No ID: Check default permission
if (!$id) {
return $this->checkDefaultPermissions(self::EDIT, $member);
}
// Regular canEdit logic is handled by canEditMultiple
$results = $this->canEditMultiple(
[$id],
$member
);
// Check if in result
return isset($results[$id]) ? $results[$id] : false;
}
/**
* @param int $id
* @param Member|null $member
* @return bool|mixed
*/
public function canView($id, Member $member = null)
{
// No ID: Check default permission
if (!$id) {
return $this->checkDefaultPermissions(self::VIEW, $member);
}
// Regular canView logic is handled by canViewMultiple
$results = $this->canViewMultiple(
[$id],
$member
);
// Check if in result
return isset($results[$id]) ? $results[$id] : false;
}
/**
* Get field to check for permission type for the given check.
* Defaults to those provided by {@see InheritedPermissionsExtension)
*
* @param string $type
* @return string
*/
protected function getPermissionField($type)
{
switch ($type) {
case self::DELETE:
// Delete uses edit type - Drop through
case self::EDIT:
return 'CanEditType';
case self::VIEW:
return 'CanViewType';
default:
throw new InvalidArgumentException("Invalid argument type $type");
}
}
/**
* Get join table for type
* Defaults to those provided by {@see InheritedPermissionsExtension)
*
* @param string $type
* @return string
*/
protected function getJoinTable($type)
{
return $this->getGroupJoinTable($type);
}
/**
* Get group join table for type
* Defaults to those provided by {@see InheritedPermissionsExtension)
*
* @param string $type
* @return string
*/
protected function getGroupJoinTable($type)
{
switch ($type) {
case self::DELETE:
// Delete uses edit type - Drop through
case self::EDIT:
return $this->getEditorGroupsTable();
case self::VIEW:
return $this->getViewerGroupsTable();
default:
throw new InvalidArgumentException("Invalid argument type $type");
}
}
/**
* Get member join table for type
* Defaults to those provided by {@see InheritedPermissionsExtension)
*
* @param string $type
* @return string
*/
protected function getMemberJoinTable($type)
{
switch ($type) {
case self::DELETE:
// Delete uses edit type - Drop through
case self::EDIT:
return $this->getEditorMembersTable();
case self::VIEW:
return $this->getViewerMembersTable();
default:
throw new InvalidArgumentException("Invalid argument type $type");
}
}
/**
* Determine default permission for a givion check
*
* @param string $type Method to check
* @param Member $member
* @return bool
*/
protected function checkDefaultPermissions($type, Member $member = null)
{
$defaultPermissions = $this->getDefaultPermissions();
if (!$defaultPermissions) {
return false;
}
switch ($type) {
case self::VIEW:
return $defaultPermissions->canView($member);
case self::EDIT:
return $defaultPermissions->canEdit($member);
case self::DELETE:
return $defaultPermissions->canDelete($member);
default:
return false;
}
}
/**
* Check if this model has versioning
*
* @return bool
*/
protected function isVersioned()
{
if (!class_exists(Versioned::class)) {
return false;
}
/** @var Versioned|DataObject $singleton */
$singleton = DataObject::singleton($this->getBaseClass());
return $singleton->hasExtension(Versioned::class) && $singleton->hasStages();
}
/**
* @return $this
*/
public function clearCache()
{
$this->cachePermissions = [];
return $this;
}
/**
* Get table to use for editor groups relation
*
* @return string
*/
protected function getEditorGroupsTable()
{
$table = DataObject::getSchema()->tableName($this->baseClass);
return "{$table}_EditorGroups";
}
/**
* Get table to use for viewer groups relation
*
* @return string
*/
protected function getViewerGroupsTable()
{
$table = DataObject::getSchema()->tableName($this->baseClass);
return "{$table}_ViewerGroups";
}
/**
* Get table to use for editor members relation
*
* @return string
*/
protected function getEditorMembersTable()
{
$table = DataObject::getSchema()->tableName($this->baseClass);
return "{$table}_EditorMembers";
}
/**
* Get table to use for viewer members relation
*
* @return string
*/
protected function getViewerMembersTable()
{
$table = DataObject::getSchema()->tableName($this->baseClass);
return "{$table}_ViewerMembers";
}
/**
* Gets the permission from cache
*
* @param string $cacheKey
* @return mixed
*/
protected function getCachePermissions($cacheKey)
{
// Check local cache
if (isset($this->cachePermissions[$cacheKey])) {
return $this->cachePermissions[$cacheKey];
}
// Check persistent cache
if ($this->cacheService) {
$result = $this->cacheService->get($cacheKey);
// Warm local cache
if ($result) {
$this->cachePermissions[$cacheKey] = $result;
return $result;
}
}
return null;
}
/**
* Creates a cache key for a member and type
*
* @param string $type
* @param int $memberID
* @return string
*/
protected function generateCacheKey($type, $memberID)
{
$classKey = str_replace('\\', '-', $this->baseClass ?? '');
return "{$type}-{$classKey}-{$memberID}";
}
}