- foreach ($chapters as $chapter) {
- $sortItem = $keyMap->get('chapter:' . $chapter->id);
- $sortItem->model = $chapter;
+ if ($model instanceof Page) {
+ $parentPermission = ($currentParent instanceof Chapter) ? 'chapter-update' : 'book-update';
+ $hasCurrentParentPermission = userCan($parentPermission, $currentParent);
+
+ // This needs to check if there was an intended chapter location in the original sort map
+ // rather than inferring from the $newChapter since that variable may be null
+ // due to other reasons (Visibility).
+ $newParent = $sortMapItem->parentChapterId ? $newChapter : $newBook;
+ if (!$newParent) {
+ return false;
+ }
+
+ $hasPageEditPermission = userCan('page-update', $model);
+ $newParentInRightLocation = ($newParent instanceof Book || $newParent->book_id === $newBook->id);
+ $newParentPermission = ($newParent instanceof Chapter) ? 'chapter-update' : 'book-update';
+ $hasNewParentPermission = userCan($newParentPermission, $newParent);
+
+ $hasDeletePermissionIfMoving = (!$hasNewParent || userCan('page-delete', $model));
+ $hasCreatePermissionIfMoving = (!$hasNewParent || userCan('page-create', $newParent));
+
+ $hasPermission = $hasCurrentParentPermission
+ && $newParentInRightLocation
+ && $hasNewParentPermission
+ && $hasPageEditPermission
+ && $hasDeletePermissionIfMoving
+ && $hasCreatePermissionIfMoving;
+
+ if (!$hasPermission) {
+ return false;
+ }