@param ServerRequestInterface $request
@param Document               $document

@throws PermissionDeniedException

@return mixed
769602
protected function data(ServerRequestInterface $request, Document $document)
    {
        $data = $request->getParsedBody();
        $updatedAnswer = $data['answer'];
        $actor = $request->getAttribute('actor');
        $answer = Answer::find(array_get($request->getQueryParams(), 'id'));

        if ($actor->can('edit.polls') || ($actor->id === Question::find($answer->poll_id)->user_id && $actor->can('selfEditPolls'))) {
            $answer->answer = $updatedAnswer;
            $this->validator->assertValid(['answer' => $updatedAnswer]);
            $answer->save();

            return $answer;
        } else {
            throw new PermissionDeniedException();
        }
    }
905278
public function enableShardingForDbByDocumentName(string $documentName) : void
    {
        $dbName  = $this->dm->getDocumentDatabase($documentName)->getDatabaseName();
        $adminDb = $this->dm->getClient()->selectDatabase('admin');

        try {
            $adminDb->command(['enableSharding' => $dbName]);
        } catch (ServerException $e) {
            // Don't throw an exception if sharding is already enabled; there's just no other way to check this
            if ($e->getCode() !== self::CODE_SHARDING_ALREADY_INITIALIZED) {
                throw MongoDBException::failedToEnableSharding($dbName, $e->getMessage());
            }
        } catch (RuntimeException $e) {
            throw MongoDBException::failedToEnableSharding($dbName, $e->getMessage());
        }
    }
477689
private function checkPermission(Node $node, $permission)
    {
        if (false === $this->authorizationChecker->isGranted($permission, $node)) {
            throw new AccessDeniedException();
        }
    }
1371725
public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $user_id = (int) $request->getParsedBody()['user_id'];

        $user = $this->user_service->find($user_id);

        if ($user === null) {
            throw new NotFoundHttpException('User ID ' . $user_id . ' not found');
        }

        if (Auth::isAdmin($user)) {
            throw new AccessDeniedHttpException('Cannot delete an administrator');
        }

        Log::addAuthenticationLog('Deleted user: ' . $user->userName());
        $this->user_service->delete($user);

        return response('', StatusCodeInterface::STATUS_NO_CONTENT);
    }
1005787
protected function data(ServerRequestInterface $request, Document $document)
    {
        $voteArray = [
            'poll_id' => array_get($request->getQueryParams(), 'poll_id'),
            'user_id' => array_get($request->getQueryParams(), 'user_id'),
        ];

        return $this->fields->findVote($voteArray['poll_id'], $voteArray['user_id']);
    }
581330
protected function getDocumentFromID($request)
    {
        $doc = null;

        $id = Convert::raw2sql($request->param('ID'));
        if (strpos($id, 'version') === 0) {
            // Versioned document
            $id = $this->getDocumentIdFromSlug(str_replace('version', '', $id));
            $doc = DataObject::get_by_id('DMSDocument_versions', $id);
            $this->extend('updateVersionFromID', $doc, $request);
        } else {
            // Normal document
            $doc = DataObject::get_by_id('DMSDocument', $this->getDocumentIdFromSlug($id));
            $this->extend('updateDocumentFromID', $doc, $request);
        }

        return $doc;
    }
126609
public function partialReplaceSingle($id, $document) {
		$request = new CPS_PartialReplaceRequest($id, $document);
		$this->_lastResponse = $this->_connection->sendRequest($request);
		return count($this->_lastResponse->getModifiedIds());
	}
34596
protected function delete(ServerRequestInterface $request)
    {
        $actor = $request->getAttribute('actor');
        $answer = Answer::find(array_get($request->getQueryParams(), 'id'));

        if ($actor->can('edit.polls') || ($actor->id == Question::find($answer->poll_id)->user_id && $actor->can('selfEditPolls'))) {
            $this->fields->deleteAnswer($answer->id);
        } else {
            throw new PermissionDeniedException();
        }
    }
404549
public function getAdminAction(ServerRequestInterface $request, UserInterface $user, Tree $tree = null): ResponseInterface
    {
        // We need a tree to work with.
        if ($tree === null) {
            throw new NotFoundHttpException();
        }

        // Admins only.
        if (!Auth::isAdmin($user)) {
            throw new AccessDeniedHttpException();
        }

        $plugin = $request->get('plugin', '');
        $xref   = $request->get('xref', '');

        $plugins = $this->getPluginList();
        $plugin  = $plugins[$plugin] ?? null;

        $curr_xref = '';
        $prev_xref = '';
        $next_xref = '';

        // Don't do any processing until a plugin is chosen.
        if ($plugin !== null) {
            $plugin->getOptions($request);

            $all_data = $this->allData($plugin, $tree);

            // Make sure that our requested record really does need updating.
            // It may have been updated in another session, or may not have
            // been specified at all.
            if (array_key_exists($xref, $all_data) && $plugin->doesRecordNeedUpdate($this->getRecord($all_data[$xref], $tree))) {
                $curr_xref = $xref;
            }

            // The requested record doesn't need updating - find one that does
            if ($curr_xref === '') {
                $curr_xref = $this->findNextXref($plugin, $xref, $all_data, $tree);
            }
            if ($curr_xref === '') {
                $curr_xref = $this->findPrevXref($plugin, $xref, $all_data, $tree);
            }

            // If we've found a record to update, get details and look for the next/prev
            if ($curr_xref !== '') {
                $prev_xref = $this->findPrevXref($plugin, $xref, $all_data, $tree);
                $next_xref = $this->findNextXref($plugin, $xref, $all_data, $tree);
            }
        }

        return $this->viewResponse('modules/batch_update/admin', [
            'auto_accept' => (bool) $user->getPreference('auto_accept'),
            'plugins'     => $plugins,
            'curr_xref'   => $curr_xref,
            'next_xref'   => $next_xref,
            'plugin'      => $plugin,
            'record'      => GedcomRecord::getInstance($curr_xref, $tree),
            'prev_xref'   => $prev_xref,
            'title'       => I18N::translate('Batch update'),
            'tree'        => $tree,
            'trees'       => Tree::getNameList(),
        ]);
    }
1109506
public function grant(DataObject $node, $perm, DataObject $to, $grant = 'GRANT')
    {
        // make sure we can !!
        if (!$this->checkPerm($node, 'ChangePermissions')) {
            throw new PermissionDeniedException("You do not have permission to do that");
        }

        $role = DataObject::get_one('AccessRole', '"Title" = \'' . Convert::raw2sql($perm) . '\'');

        $composedOf = array($perm);
        if ($role && $role->exists()) {
            $composedOf = $role->Composes->getValues();
        }

        $type = $to instanceof Member ? 'Member' : get_class($to);
        $filter = array(
            'Type'            => $type,
            'AuthorityID'    => $to->ID,
            'ItemID'        => $node->ID,
            'ItemType'        => $node->class,
            'Grant'            => $grant,
        );
        
        $list = DataList::create('AccessAuthority')->filter($filter);
        $existing = $list->first();
        if (!$existing || !$existing->exists()) {
            $existing = new AccessAuthority;
            $existing->Type = $type;
            $existing->AuthorityID = $to->ID;
            $existing->ItemID = $node->ID;
            $existing->ItemType = $node->class;
            $existing->Grant = $grant;
            $existing->Role = $role ? $role->Title : '';
        }

        $currentRoles = $existing->Perms->getValues();
        if (!$currentRoles) {
            $new = $composedOf;
        } else {
            $new = array_merge($currentRoles, $composedOf);
        }

        $new = array_unique($new);
        $existing->Perms = $new;
        $existing->write();

        $this->clearPermCacheFor($node);

        return $existing;
    }
785088
protected function delete(ServerRequestInterface $request)
    {
        $pollId = array_get($request->getQueryParams(), 'id');

        $actor = $request->getAttribute('actor');

        if ($actor->can('edit.polls') || ($actor->id == Question::find($pollId)->user_id && $actor->can('selfEditPolls'))) {
            return $this->fields->deletePoll($pollId);
        } else {
            throw new PermissionDeniedException();
        }
    }
963253
protected function data(ServerRequestInterface $request, Document $document)
    {
        $postId = array_get($request->getQueryParams(), 'post');
        $actor = $request->getAttribute('actor');
        $file = array_get($request->getUploadedFiles(), 'image');

        return $this->bus->dispatch(
            new UploadImage($postId, $file, $actor)
        );
    }
874062
public function insertSingle($id, $document) {
		$request = new CPS_InsertRequest($id, $document);
		$this->_lastResponse = $this->_connection->sendRequest($request);
		return count($this->_lastResponse->getModifiedIds());
	}
386332
private function validateDocumentRegistration($document, $locale, NodeInterface $node, $oid, $uuid)
    {
        if (null === $uuid) {
            throw new DocumentManagerException(sprintf(
                'Node "%s" of type "%s" has no UUID. Only referencable nodes can be registered by the document manager',
                $node->getPath(), $node->getPrimaryNodeType()->getName()
            ));
        }

        $documentNodeKey = $this->getNodeLocaleKey($node->getIdentifier(), $locale);
        if (array_key_exists($uuid, $this->nodeMap) && array_key_exists($documentNodeKey, $this->nodeDocumentMap)) {
            $registeredDocument = $this->nodeDocumentMap[$documentNodeKey];

            throw new \RuntimeException(sprintf(
                'Document "%s" (%s) is already registered for node "%s" (%s) when trying to register document "%s" (%s)',
                spl_object_hash($registeredDocument),
                get_class($registeredDocument),
                $uuid,
                $node->getPath(),
                $oid,
                get_class($document)
            ));
        }
    }
405872
public function grantAccess($object, UserInterface $user = null, $permission = Permissions::PERMISSIONS_VIEW, $new = true, $parent = null)
    {
        $objectIdentity = $this->getObjectIdentity($object);

        if (!$objectIdentity) {
            $this->logger->addDebug('could not create ObjectIdentity for object of class ' . get_class($objectIdentity));
        } else {
            $acl = $this->getAcl($objectIdentity, $new);

            // grant permission
            if (null === ($mask = $this->getMask($permission)) && !$parent) {
                $this->logger->addCritical('if permission is set to \'ignore\’ you have to pass in a parent object to inherit from');
                throw new \InvalidArgumentException('if permission is set to \'ignore\’ you have to pass in a parent object to inherit from');
            }

            if ($mask) {
                // if no user is given, get the one currently logged in
                if (!$user) {
                    $user = $this->sc->getToken()->getUser();
                }

                $securityIdentity = UserSecurityIdentity::fromAccount($user);
                $acl->insertObjectAce($securityIdentity, $mask);
            }

            // inherit?
            if ($parent && is_object($parent)) {
                $parentIdentity = $this->getObjectIdentity($parent);
                $parentAcl = $this->getAcl($parentIdentity, false);
                $acl->setParentAcl($parentAcl);
            }

            $this->aclProvider->updateAcl($acl);
            $this->logger->addDebug('updated acl for ' . get_class($object));
        }

        // cascade
        if ($object instanceof AclParent) {
            if ($objectIdentity) {
                $parent = $object;
            } elseif (!$parent) {
                // there's no parent to inherit from
                // and we can't create an object identity
                // for the current object
                // so we're not able to inherit from anything
                return true;
            }
            $this->logger->addDebug('cascading ACL to children of ' . get_class($parent));
            foreach ($object->getAclChildren() as $child) {
                if ($child) {
                    $this->grantInheritedAccess($child, $parent);
                }
            }
        }

        return true;
    }
401744
protected function decodeDocument(ServerRequestInterface $serverRequest)
    {
        if (!http_contains_body($serverRequest)) {
            return null;
        }

        return new Document(json_decode((string) $serverRequest->getBody()));
    }
177339
public function removePermissions(DataObject $node, $perm, DataObject $userOrGroup, $grant = 'GRANT')
    {
        if (!$this->checkPerm($node, 'ChangePermissions')) {
            throw new PermissionDeniedException("You do not have permission to do that");
        }

        $composedOf = $perm;
        if (!is_array($perm)) {
            $role = DataObject::get_one('AccessRole', '"Title" = \'' . Convert::raw2sql($perm) . '\'');
            $composedOf = array($perm);
            if ($role && $role->exists()) {
                $composedOf = $role->Composes->getValues();
            }
        }
        
        $type = $userOrGroup instanceof Member ? 'Member' : get_class($userOrGroup);
        $filter = array(
            'Type' => $type,
            'AuthorityID' => $userOrGroup->ID,
            'ItemID' => $node->ID,
            'ItemType' => $node->class,
            'Grant' => $grant,
        );

        $existing = DataList::create('AccessAuthority')->filter($filter)->first();
        
        if (!$existing || !$existing->exists()) {
            return;
        }

        $current = $existing->Perms->getValues();
        if (is_array($current) && count($current)) {
            $new = array_diff($current, $composedOf);
            $existing->Perms = $new;
            $existing->write();
            
            $this->clearPermCacheFor($node);
            
            if (!count($new)) {
                try {
                    $this->removeAuthority($node, $existing);
                } catch (Exception $e) {
                    // oh well
                }
            }
        }
    }