Validates a share request.

@param array $shareRequest

@return array
356450
private function validateShareRequest(array $shareRequest)
    {
        $errors = [];

        if (empty($shareRequest['questions']) || !is_array($shareRequest['questions'])) {
            $errors[] = [
                'path' => '/questions',
                'message' => 'should be a list of question ids',
            ];
        }

        if (empty($shareRequest['users']) || !is_array($shareRequest['users'])) {
            $errors[] = [
                'path' => '/users',
                'message' => 'should be a list of user ids',
            ];
        }

        if (!is_bool($shareRequest['adminRights'])) {
            $errors[] = [
                'path' => '/adminRights',
                'message' => 'should be boolean',
            ];
        }

        return $errors;
    }
978505
private function getAllowedMethods(ServerRequestInterface $request): array
    {
        $allowed = [];

        $requestPath = $request->getUri()->getPath();

        foreach (Method::all() as $method) {
            $matchThis = "$requestPath{}$method";

            if (preg_match($this->pattern, $matchThis, $matches) === 1) {
                $allowed[$method] = $this->getRoute($matches);
            }
        }

        return $allowed;
    }
132479
private function isValid(ServerRequestInterface $request): bool
    {
        $method = strtoupper($request->getMethod());

        if (in_array($method, ['GET', 'HEAD', 'CONNECT', 'TRACE', 'OPTIONS'], true)) {
            return true;
        }

        $data = $request->getParsedBody();

        return isset($data[$this->name]) && $data[$this->name] === '';
    }
646789
public function validateRequestHandshake(
        $request
    ) {
        if (!$request) {
            return false;
        }

        list($request, $headers) = $this->getRequestHeaders($request);
        // make a copy of the headers array to store all extra headers
        $extraHeaders = $headers;

        // parse the resulting url to separate query parameters from the path
        $url = parse_url($this->validateRequestLine($request));
        $path = isset($url['path']) ? $url['path'] : null;
        $urlParams = [];
        if (isset($url['query'])) {
            parse_str($url['query'], $urlParams);
        }

        if (empty($headers[self::HEADER_ORIGIN])) {
            throw new BadRequestException('No origin header');
        } else {
            unset($extraHeaders[self::HEADER_ORIGIN]);
        }

        $origin = $headers[self::HEADER_ORIGIN];

        if (!isset($headers[self::HEADER_UPGRADE])
            || strtolower($headers[self::HEADER_UPGRADE]) != self::UPGRADE_VALUE
        ) {
            throw new BadRequestException('Invalid upgrade header');
        } else {
            unset($extraHeaders[self::HEADER_UPGRADE]);
        }

        if (!isset($headers[self::HEADER_CONNECTION])
            || stripos($headers[self::HEADER_CONNECTION], self::CONNECTION_VALUE) === false
        ) {
            throw new BadRequestException('Invalid connection header');
        } else {
            unset($extraHeaders[self::HEADER_CONNECTION]);
        }

        if (!isset($headers[self::HEADER_HOST])) {
            // @todo Validate host == listening socket? Or would that break
            //        TCP proxies?
            throw new BadRequestException('No host header');
        } else {
            unset($extraHeaders[self::HEADER_HOST]);
        }

        if (!isset($headers[self::HEADER_VERSION])) {
            throw new BadRequestException('No version header received on handshake request');
        }

        if (!$this->acceptsVersion($headers[self::HEADER_VERSION])) {
            throw new BadRequestException('Unsupported version: ' . $headers[self::HEADER_VERSION]);
        } else {
            unset($extraHeaders[self::HEADER_VERSION]);
        }

        if (!isset($headers[self::HEADER_KEY])) {
            throw new BadRequestException('No key header received');
        }

        $key = trim($headers[self::HEADER_KEY]);

        if (!$key) {
            throw new BadRequestException('Invalid key');
        } else {
            unset($extraHeaders[self::HEADER_KEY]);
        }

        // Optional
        $protocol = null;
        if (isset($headers[self::HEADER_PROTOCOL])) {
            $protocol = $headers[self::HEADER_PROTOCOL];
            unset($extraHeaders[self::HEADER_PROTOCOL]);
        }

        $extensions = [];
        if (!empty($headers[self::HEADER_EXTENSIONS])) {
            $extensions = $headers[self::HEADER_EXTENSIONS];
            if (is_scalar($extensions)) {
                $extensions = [$extensions];
            }
        }
        unset($extraHeaders[self::HEADER_EXTENSIONS]);

        return [$path, $origin, $key, $extensions, $protocol, $extraHeaders, $urlParams];
    }
1318760
protected function inExceptArray($request)
  {
    foreach ($this->except as $except) {
      if ($request->is($except)) {
        return true;
      }
    }

    return false;
  }
245472
private function _convertValidateBillingAgreement($request) {
    
        $parameters = array();
        $parameters['Action'] = 'ValidateBillingAgreement';
        if ($request->isSetAmazonBillingAgreementId()) {
            $parameters['AmazonBillingAgreementId'] =  $request->getAmazonBillingAgreementId();
        }
        if ($request->isSetSellerId()) {
            $parameters['SellerId'] =  $request->getSellerId();
        }
    
        return $parameters;
    }
1183570
public function match(ServerRequestInterface $request, $path)
	{
	    if(isset($this->properties['method'])) {
	        if(!in_array(strtolower($request->getMethod()), $this->properties['method']))
	            return array(
	                'route' => false,
                    'parameter' => false,
                    'continue' => false
                );
        }

        if(isset($this->properties['path'])) {
            $result = $this->matchPath($path);

            if(!$result['matched'])
                return array(
                    'route' =>false,
                    'parameter' => $result['parameter'],
                    'continue' => $result['continue']
                );

            if($this->properties['validators']) {
                $flag = $this->matchValidators($request, $path, $result['parameter']);

                if($flag === false)
                    return array(
                        'route' => false,
                        'parameter' => false,
                        'continue' => false
                    );
            }

            return array(
                'route' => $this,
                'parameter' => $result['parameter'],
                'continue' => $result['continue']
            );
        }

        return array(
            'route'=>false,
            'parameter'=> array(),
            'continue'=> false
        );
	}
458048
public function prepareData(ServerRequest $request): array
    {
        $result = $request->getData();

        $event = new Event((string)EventName::MODEL_SEARCH_CHILD_ITEMS(), $this, [
            'criteria' => $result
        ]);
        EventManager::instance()->dispatch($event);

        $result = $event->result ? $event->result : $result;

        $value = Hash::get($result, 'criteria.query');

        // advanced search
        if (!$value) {
            return $result;
        }

        // basic search query, converted to search criteria
        $result['aggregator'] = 'OR';
        $basicSearch = new BasicSearch($this->table, $this->user);
        $result['criteria'] = $basicSearch->getCriteria($value);

        return $result;
    }
334858
public function sendverification(SS_HTTPRequest $request)
    {
        // If we don't allow verification emails, return an error
        if (!Users::config()->send_verification_email) {
            return $this->httpError(400);
        }

        $sent = false;

        if (Member::currentUserID()) {
            $member = Member::currentUser();
        } else {
            $member = Member::get()->byID($this->getRequest()->param("ID"));
        }

        if ($member && !$member->isVerified()) {
            $sent = $this->send_verification_email($member);
        }

        $this->customise(
            array(
            "Title" => _t('Users.AccountVerification', 'Account Verification'),
            "MetaTitle" => _t('Users.AccountVerification', 'Account Verification'),
            "Content" => $this->renderWith(
                "UsersSendVerificationContent",
                array("Sent" => $sent)
            ),
            "Sent" => $sent
            )
        );

        $this->extend("updateSendVerificationAction");

        return $this->renderWith(
            array(
            "Users_Register_sendverification",
            "Users",
            "Page"
            )
        );
    }
652233
public function decodeRequest(array $request)
    {
        foreach ($request as $key => $value) {
            if (is_array($value)) {
                $request[ $key ] = $this->decodeRequest($value);
            } elseif (strpos($key, '[')) {
                preg_match('/(.+?)\[(.+?)\]/', $key, $matches);
                list($match, $name, $subKey) = $matches;

                if (!isset($request[ $name ])) {
                    $request[ $name ] = array();
                }

                $request[ $name ][ $subKey ] = $value;
                unset($request[ $key ]);
            }
        }
        return $request;
    }
767460
private function checkForShare()
    {

        $ok = true;
        $doSaveResourceLink = true;

        $id = $this->resourceLink->primaryResourceLinkId;

        $shareRequest = isset($_POST['custom_share_key']) && !empty($_POST['custom_share_key']);
        if ($shareRequest) {
            if (!$this->allowSharing) {
                $ok = false;
                $this->reason = 'Your sharing request has been refused because sharing is not being permitted.';
            } else {
// Check if this is a new share key
                $shareKey = new ResourceLinkShareKey($this->resourceLink, $_POST['custom_share_key']);
                if (!is_null($shareKey->primaryConsumerKey) && !is_null($shareKey->primaryResourceLinkId)) {
// Update resource link with sharing primary resource link details
                    $key = $shareKey->primaryConsumerKey;
                    $id = $shareKey->primaryResourceLinkId;
                    $ok = ($key !== $this->consumer->getKey()) || ($id != $this->resourceLink->getId());
                    if ($ok) {
                        $this->resourceLink->primaryConsumerKey = $key;
                        $this->resourceLink->primaryResourceLinkId = $id;
                        $this->resourceLink->shareApproved = $shareKey->autoApprove;
                        $ok = $this->resourceLink->save();
                        if ($ok) {
                            $doSaveResourceLink = false;
                            $this->user->getResourceLink()->primaryConsumerKey = $key;
                            $this->user->getResourceLink()->primaryResourceLinkId = $id;
                            $this->user->getResourceLink()->shareApproved = $shareKey->autoApprove;
                            $this->user->getResourceLink()->updated = time();
// Remove share key
                            $shareKey->delete();
                        } else {
                            $this->reason = 'An error occurred initialising your share arrangement.';
                        }
                    } else {
                        $this->reason = 'It is not possible to share your resource link with yourself.';
                    }
                }
                if ($ok) {
                    $ok = !is_null($key);
                    if (!$ok) {
                        $this->reason = 'You have requested to share a resource link but none is available.';
                    } else {
                        $ok = (!is_null($this->user->getResourceLink()->shareApproved) && $this->user->getResourceLink()->shareApproved);
                        if (!$ok) {
                            $this->reason = 'Your share request is waiting to be approved.';
                        }
                    }
                }
            }
        } else {
// Check no share is in place
            $ok = is_null($id);
            if (!$ok) {
                $this->reason = 'You have not requested to share a resource link but an arrangement is currently in place.';
            }
        }

// Look up primary resource link
        if ($ok && !is_null($id)) {
            $consumer = new ToolConsumer($key, $this->dataConnector);
            $ok = !is_null($consumer->created);
            if ($ok) {
                $resourceLink = ResourceLink::fromConsumer($consumer, $id);
                $ok = !is_null($resourceLink->created);
            }
            if ($ok) {
                if ($doSaveResourceLink) {
                    $this->resourceLink->save();
                }
                $this->resourceLink = $resourceLink;
            } else {
                $this->reason = 'Unable to load resource link being shared.';
            }
        }

        return $ok;

    }
374039
protected function _validateToken(ServerRequest $request)
    {
        $cookie = $request->getCookie($this->_config['cookieName']);
        $post = $request->getData($this->_config['field']);
        $header = $request->getHeaderLine('X-CSRF-Token');

        if (!$cookie) {
            throw new InvalidCsrfTokenException(__d('cake', 'Missing CSRF token cookie'));
        }

        if (!Security::constantEquals($post, $cookie) && !Security::constantEquals($header, $cookie)) {
            throw new InvalidCsrfTokenException(__d('cake', 'CSRF token mismatch.'));
        }
    }
1104948
private function checkForShare(array $requestBody)
    {
        $doSaveResourceLink = true;

        $key = $this->resourceLink->primary_consumer_key;
        $id = $this->resourceLink->primary_resource_link_id;

        $shareRequest = isset($requestBody['custom_share_key']) && !empty($requestBody['custom_share_key']);
        if ($shareRequest) {
            if (!$this->allowSharing) {
                throw new Exception('Your sharing request has been refused because sharing is not being permitted');
            } else {
                // Check if this is a new share key
                $share_key = new ResourceLinkShareKey($this->resourceLink, $requestBody['custom_share_key']);
                if (!is_null($share_key->primary_consumer_key) && !is_null($share_key->primary_resource_link_id)) {
                    // Update resource link with sharing primary resource link details
                    $key = $share_key->primary_consumer_key;
                    $id = $share_key->primary_resource_link_id;

                    if ($key == $this->consumer->getKey() && $id == $this->resourceLink->getId()) {
                        throw new Exception('It is not possible to share your resource link with yourself');
                    }

                    $this->resourceLink->primary_consumer_key = $key;
                    $this->resourceLink->primary_resource_link_id = $id;
                    $this->resourceLink->share_approved = $share_key->auto_approve;

                    if (!$this->resourceLink->save()) {
                        throw new Exception('An error occurred initialising your share arrangement');
                    }

                    $doSaveResourceLink = false;
                    $this->user->getResourceLink()->primary_consumer_key = $key;
                    $this->user->getResourceLink()->primary_resource_link_id = $id;
                    $this->user->getResourceLink()->share_approved = $share_key->auto_approve;
                    $this->user->getResourceLink()->updated = time();
                    // Remove share key
                    $share_key->delete();
                }

                if (!is_null($key)) {
                    throw new Exception('You have requested to share a resource link but none is available');
                }

                if (is_null($this->user->getResourceLink()->share_approved) || !$this->user->getResourceLink()->share_approved) {
                    throw new Exception('Your share request is waiting to be approved');
                }
            }
        } else if (!is_null($key)) {
            // Check no share is in place
            throw new Exception('You have not requested to share a resource link but an arrangement is currently in place');
        }

        // Look up primary resource link
        if (!is_null($key)) {
            $consumer = new ToolConsumer($key, $this->storage);

            // TODO: Move to load function
            if (is_null($consumer->created)) {
                throw new Exception('Unable to load tool consumer');
            }

            $resource_link = new ResourceLink($consumer, $id);

            if (is_null($resource_link->created)) {
                throw new Exception('Unable to load resource link being shared');
            }

            if ($doSaveResourceLink) {
                $this->resourceLink->save();
            }
            $this->resourceLink = $resource_link;
        }
    }
488512
public function validate(common_http_Request $request, \common_http_Credentials $credentials = null) {
        $server = new OAuthServer($this->getDataStore());
		$method = new OAuthSignatureMethod_HMAC_SHA1();
        $server->add_signature_method($method);
        
        try {
            $oauthRequest = $this->getOauthRequest($request);
            $server->verify_request($oauthRequest);
        } catch (OAuthException $e) {
            throw new \common_http_InvalidSignatureException('Validation failed: '.$e->getMessage());
        }
    }
1361237
private static function sendRequest($req)
    {
        $rsp = Http::send($req);

        $ret = json_decode($rsp, true);

        if ($ret) {
            if (0 === $ret['code']) {
                return $ret;
            } else {
                return [
                    'code'    => $ret['code'],
                    'message' => $ret['message'],
                    'data'    => [],
                ];
            }
        } else {
            return [
                'code'    => self::COSAPI_NETWORK_ERROR,
                'message' => $rsp,
                'data'    => [],
            ];
        }
    }
299442
protected function inExceptArray($request)
    {
        foreach (config('admin.operation_log.except') as $except) {
            if ('/' !== $except) {
                $except = trim($except, '/');
            }

            $methods = [];

            if (Str::contains($except, ':')) {
                list($methods, $except) = explode(':', $except);
                $methods = explode(',', $methods);
            }

            $methods = array_map('strtoupper', $methods);

            if ($request->is($except) &&
                (empty($methods) || in_array($request->method(), $methods, true))) {
                return true;
            }
        }

        return false;
    }
1161808
protected function getOrValidateRequest(HTTPRequest $request = null)
    {
        if ($request instanceof HTTPRequest) {
            return $request;
        }
        if (Injector::inst()->has(HTTPRequest::class)) {
            return Injector::inst()->get(HTTPRequest::class);
        }
        return null;
    }