Process the $_POST superglobal to spoof the results of a decoder

@return array
325919
protected function parsePost()
    {
        $ret = $_POST ?: [];
        if (isset($_FILES)) {
            foreach ($_FILES as $name => $info) {
                if (is_array($info["name"])) {
                    $len = count($info["name"]);
                    for ($i = 0; $i < $len; $i++) {
                        $file = $this->createUploadedFile([
                            "name" => $info["name"][$i] ?? "",
                            "type" => $info["type"][$i] ?? "",
                            "tmp_name" => $info["tmp_name"][$i] ?? "",
                            "error" => $info["error"][$i] ?? 0,
                            "size" => $info["size"][$i] ?? 0,
                        ]);
                        \sndsgd\Arr::addValue($ret, $name, $file);
                    }
                } else {
                    $file = $this->createUploadedFile($info);
                    \sndsgd\Arr::addValue($ret, $name, $file);
                }
            }
        }
        return $ret;
    }
785487
protected function getSubmittedFormValues()
    {
        $result = [];
        $formName = $this->getFormObject()->getName();
        $originalRequest = $this->getControllerContext()
            ->getRequest()
            ->getOriginalRequest();

        if (null !== $originalRequest
            && $originalRequest->hasArgument($formName)
        ) {
            $result = $originalRequest->getArgument($formName);
        }

        return $result;
    }
182326
public function getPostFromInput()
    {
        $ct = $_SERVER['CONTENT_TYPE'];
        $position = stripos($ct, "boundary=");
        $jsonCheck = "application/json";

        $input = file_get_contents("php://input");

        $this->rawData = $input;

        $postVars = array();
        if ($position !== false) {

            $exp = explode("boundary=", $ct);
            if (isset($exp[1])) {
                $boundary = trim($exp[1]);

                $variables = explode("--" . $boundary, $input);

                foreach ($variables as $var) {
                    $var = urldecode($var);
                    if (trim($var) != "" && trim($var) != "--") {
                        preg_match('/Content-Disposition:[ _]*form-data;[ _]*name="([^\"]*)"(.*)/si', $var, $result);
                        $postVars[trim($result[1])] = trim($result[2]);
                    }
                }
            }
        } else if (substr($ct, 0, strlen($jsonCheck)) === $jsonCheck) {
            $postVars = json_decode($input, true);
        } else {
            parse_str($input, $postVars);
        }

        if (count($_POST) > 0 && count($postVars) === 0) {
            $postVars = $_POST;
        }

        return $postVars;
    }
1367175
protected function handlePOST()
    {
        $payload = $this->getPayloadData();
        $login = $this->request->getParameterAsBool('login');
        $registrar = new Registrar();

        $password = array_get($payload, 'new_password', array_get($payload, 'password'));
        $data = [
            'username'              => array_get($payload, 'username'),
            'first_name'            => array_get($payload, 'first_name'),
            'last_name'             => array_get($payload, 'last_name'),
            'name'                  => array_get($payload, 'name'),
            'email'                 => array_get($payload, 'email'),
            'phone'                 => array_get($payload, 'phone'),
            'security_question'     => array_get($payload, 'security_question'),
            'security_answer'       => array_get($payload, 'security_answer'),
            'password'              => $password,
            'password_confirmation' => array_get($payload, 'password_confirmation', $password)
        ];

        if (empty($data['first_name'])) {
            /** @noinspection PhpUnusedLocalVariableInspection */
            list($username, $domain) = explode('@', $data['email']);
            $data['first_name'] = $username;
        }
        if (empty($data['last_name'])) {
            $names = explode('.', $data['first_name']);
            if (isset($names[1])) {
                $data['last_name'] = $names[1];
                $data['first_name'] = $names[0];
            } else {
                $data['last_name'] = $names[0];
            }
        }
        if (empty($data['name'])) {
            $data['name'] = $data['first_name'] . ' ' . $data['last_name'];
        }

        $data = array_filter($data, function ($value) {
            return !is_null($value);
        });

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = $registrar->validator($data);

        if ($validator->fails()) {
            $messages = $validator->errors()->getMessages();

            throw new BadRequestException('Validation failed', null, null, $messages);
        } else {
            $user = $registrar->create($data, $this->getServiceId());

            if ($login) {
                if ($user->confirm_code !== 'y' && !is_null($user->confirm_code)) {
                    return ['success' => true, 'confirmation_required' => true];
                } else {
                    $appId = Session::get('app.id');
                    Session::setUserInfoWithJWT($user, false, $appId);

                    return ['success' => true, 'session_token' => Session::getSessionToken()];
                }
            } else {
                return ['success' => true];
            }
        }
    }
703629
private function processTagRules(): array
    {
        $processedTagRules = $this->getTagRules();

        array_walk($processedTagRules, function (&$tagRule) {
            $tagRule = array_map(function ($valueOrCallback) {
                return is_callable($valueOrCallback, true)
                    ? Closure::fromCallable($valueOrCallback)->call($this)
                    : $valueOrCallback;
            }, $tagRule);
        });

        return $processedTagRules;
    }
984575
public function extractCalls()
    {
        $calls = array();
        
        if ('form' == $this->callType) {
            $calls[] = new Call($this->post, 'form');
        } else {                        
            $decoded = json_decode($this->rawPost);
            $decoded = !is_array($decoded) ? array($decoded) : $decoded;
            
            array_walk_recursive($decoded, array($this, 'parseRawToArray'));

            if ($this->requestDecode)
                array_walk_recursive($decoded, array($this, 'decode'));

            foreach ($decoded as $call) {
                $calls[] = new Call((array)$call, 'single');
            }
        }
        
        return $calls;
    }
1098574
public function process()
    {

        // Initialize the query library we are using
        $class = new \ReflectionClass($this->queryLibrary);

        // Set the query pointer to the new instance of the library
        $this->query = $class->newInstance();

        unset($class);

        // Define the return
        $results = [];

        // @todo: Add break up into loop to split large arrays into smaller chunks

        // Do server challenge(s) first, if any
        $this->doChallenges();

        // Do packets for server(s) and get query responses
        $this->doQueries();

        // Now we should have some information to process for each server
        foreach ($this->servers as $server) {
            /* @var $server \GameQ\Server */

            // Parse the responses for this server
            $result = $this->doParseResponse($server);

            // Apply the filters
            $result = array_merge($result, $this->doApplyFilters($result, $server));

            // Sort the keys so they are alphabetical and nicer to look at
            ksort($result);

            // Add the result to the results array
            $results[$server->id()] = $result;
        }

        return $results;
    }
1152394
protected function getFormValues() {
    $input = array();
    foreach ($this->getInputParameters() as $parameter) {
      if (isset($_POST[$parameter['name']])) {
        $input[$parameter['name']] = $_POST[$parameter['name']];
      }
    }
    return $input;
  }
112058
public function processResponse()
    {
        // No response, assume offline
        if (empty($this->packets_response)) {
            return [
                'gq_address'    => $this->realIp,
                'gq_port_query' => $this->realPortQuery,
            ];
        }

        // Implode and rip out the JSON
        preg_match('/\{(.*)\}/ms', implode('', $this->packets_response), $matches);

        // Return should be JSON, let's validate
        if (!isset($matches[0]) || ($json = json_decode($matches[0])) === null) {
            throw new Exception("JSON response from Gtan protocol is invalid.");
        }

        $result = new Result();

        // Server is always dedicated
        $result->add('dedicated', 1);

        $result->add('gq_address', $this->realIp);
        $result->add('gq_port_query', $this->realPortQuery);

        // Add server items
        $result->add('hostname', $json->ServerName);
        $result->add('serverversion', $json->ServerVersion);
        $result->add('map', ((!empty($json->Map)) ? $json->Map : 'Los Santos/Blaine Country'));
        $result->add('mod', $json->Gamemode);
        $result->add('password', (int)$json->Passworded);
        $result->add('numplayers', $json->CurrentPlayers);
        $result->add('maxplayers', $json->MaxPlayers);

        return $result->fetch();
    }
1335726
protected function handlePOST()
    {
        if (empty($payload = $this->getPayloadData())) {
            throw new BadRequestException('No data supplied for operation.');
        }

        $data = [
            'username'          => array_get($payload, 'username'),
            'first_name'        => array_get($payload, 'first_name'),
            'last_name'         => array_get($payload, 'last_name'),
            'name'              => array_get($payload, 'name'),
            'email'             => array_get($payload, 'email'),
            'phone'             => array_get($payload, 'phone'),
            'security_question' => array_get($payload, 'security_question'),
            'security_answer'   => array_get($payload, 'security_answer'),
            'default_app_id'    => array_get($payload, 'default_app_id')
        ];

        $data = array_filter($data, function ($value) {
            return !is_null($value);
        });

        $user = Session::user();

        if (empty($user)) {
            throw new NotFoundException('No user session found.');
        }

        $oldToken = Session::getSessionToken();
        $email = $user->email;
        $user->update($data);

        if (!empty($oldToken) && $email !== array_get($data, 'email', $email)) {
            // Email change invalidates token. Need to create a new token.
            $forever = JWTUtilities::isForever($oldToken);
            Session::setUserInfoWithJWT($user, $forever);
            $newToken = Session::getSessionToken();

            return ['success' => true, 'session_token' => $newToken];
        }

        return ['success' => true];
    }
903266
protected function GetErrorCodesFromResponse()
    {
        $sReturnMessage = false;
        $oGlobal = TGlobal::instance();
        $this->sRefNo = $oGlobal->GetUserData('refno');
        $sReturnState = $oGlobal->GetUserData('status');
        if ($this->bIsCorrectPaymentType()) {
            $oBasket = TShopBasket::GetInstance();
            if ($this->sRefNo == crc32($oBasket->sBasketIdentifier.'__'.$this->GetRefNoPaymentId().'__'.$this->sRefNoCount)) {
                if ('error' == $sReturnState) {
                    $sResponseHash = $this->GetSecurityHash($this->GetTestLiveModeParameter('sign'), $oGlobal->GetUserData('merchantId'), $oGlobal->GetUserData('amount'), $oGlobal->GetUserData('currency'), $oGlobal->GetUserData('refno'));
                    if ($sResponseHash == $oGlobal->GetUserData('sign')) {
                        $sReturnMessage = $oGlobal->GetUserData('errorDetail');
                        $sReturnMessage = $this->TransformDataTransMessages($oGlobal->GetUserData('errorCode'));
                    } else {
                        $sReturnMessage = 'ERROR_PAYMENT_DATA_TRANS_SECURITY_CHECK_ERROR';
                    }
                } elseif ('cancel' == $sReturnState) {
                    $sResponseHash = $this->GetSecurityHash($this->GetTestLiveModeParameter('sign'), $oGlobal->GetUserData('merchantId'), $oGlobal->GetUserData('amount'), $oGlobal->GetUserData('currency'), $oGlobal->GetUserData('refno'));
                    if ($sResponseHash == $oGlobal->GetUserData('sign')) {
                        $sReturnMessage = 'ERROR_PAYMENT_DATA_TRANS_PAYMENT_CANCEL';
                    } else {
                        $sReturnMessage = 'ERROR_PAYMENT_DATA_TRANS_SECURITY_CHECK_ERROR';
                    }
                } else {
                    $sTransactionId = $oGlobal->GetUserData('uppTransactionId');
                    $sAuthorisedAmount = $oGlobal->GetUserData('amount');
                    $sResponseHash = $this->GetSecurityHash($this->GetTestLiveModeParameter('sign2'), $oGlobal->GetUserData('merchantId'), $oGlobal->GetUserData('amount'), $oGlobal->GetUserData('currency'), $oGlobal->GetUserData('uppTransactionId'));
                    if ($sResponseHash == $oGlobal->GetUserData('sign2')) {
                        if (strlen($sTransactionId) <= 0 || strlen($sAuthorisedAmount) <= 0) {
                            $sReturnMessage = 'ERROR_PAYMENT_DATA_TRANS_MISSING_PARAMETER_IN_RESPONSE';
                            TTools::WriteLogEntrySimple('Payment DataTrans: Beim Autorisierungsresponse wurden benötigte Daten nicht zurückgegeben', 1, __FILE__, __LINE__);
                        } else {
                            $this->sTransactionId = $sTransactionId;
                            $this->sAuthorisedAmount = $sAuthorisedAmount;
                        }
                    } else {
                        $sReturnMessage = 'ERROR_PAYMENT_DATA_TRANS_SECURITY_CHECK_ERROR';
                    }
                }
            } else {
                $sReturnMessage = 'ERROR_PAYMENT_DATA_TRANS_REFERENCE_NUMER_NOT_VALID';
            }
        } else {
            $sReturnMessage = 'ERROR_PAYMENT_DATA_TRANS_PAYMEN_SELECTION_NOT_VALID';
        }

        return $sReturnMessage;
    }
248933
function jsonSerialize()
    {
        $result = [
            'force_reply' => $this->forceReply
        ];

        if ($this->selective !== null) {
            $result['selective'] = $this->selective;
        }

        return $result;
    }
698081
public function decodePair(string $keyValuePair): array
    {
        # more than a handful of clients like to use '+' characters
        # when encoding data that is (almost) compliant with rfc 3986
        # this is a hack that allows for it
        if (strpos($keyValuePair, "+") !== false) {
            $keyValuePair = str_replace("+", " ", $keyValuePair);
        }

        $parts = explode("=", $keyValuePair, 2);
        $key = rawurldecode($parts[0]);

        # interpret a key with an empty value as `null`
        $value = (count($parts) === 1) ? null : rawurldecode($parts[1]);
        return [$key, $value];
    }
142574
private function process()
    {
        $inputs = $this->inputs;
        $rules = $this->rules;
        $attributes = $this->attributes;
        $filters = $this->filters;
        $messages = $this->messages;

        foreach ($rules as $name => $rule) {
            // Check for a subrule syntax: rule[key].
            if (preg_match('/(.+)'.preg_quote($this->delimiters[0]).'(.+)'.preg_quote($this->delimiters[1]).'/', $name, $matches)) {
                $realName = $matches[1];
                $subName = $matches[2];

                if (! isset($inputs[$realName]) or ! is_array($inputs[$realName])) continue;

                // An all modifier is found: rule[*].
                if ($subName == '*') {
                    $subInputs = $inputs[$realName];

                    foreach ($subInputs as $subKey => $subValue) {
                        $inputs[$realName.'_'.$subKey] = $subValue;

                        $rules = $this->fixRules($rules, $rule, $name, $realName, $subKey);
                        $messages = $this->fixMessages($messages, $name, $realName, $subKey);

                        if (isset($attributes[$name])) {
                            $attributes = $this->fixRules($attributes, $attributes[$name], $name, $realName, $subKey);
                        }

                        if (isset($filters[$name])) {
                            $filters = $this->fixRules($filters, $filters[$name], $name, $realName, $subKey);
                        }
                    }

                    $messages = $this->removeMessage($messages);

                    unset($inputs[$realName]);
                    unset($rules[$name]);

                    if (isset($attributes[$name])) {
                        unset($attributes[$name]);
                    }

                    if (isset($filters[$name])) {
                        unset($filters[$name]);
                    }
                }
                // A specific subrule is found.
                elseif (isset($inputs[$realName][$subName])) {
                    $rules[$realName.'_'.$subName] = $rule;
                    $inputs[$realName.'_'.$subName] = $inputs[$realName][$subName];
                    $rules = $this->fixRules($rules, $rule, $name, $realName, $subName);

                    if (isset($attributes[$name])) {
                        $attributes = $this->fixRules($attributes, $attributes[$name], $name, $realName, $subName);
                        unset($attributes[$name]);
                    }

                    if (isset($filters[$name])) {
                        $filters = $this->fixRules($filters, $filters[$name], $name, $realName, $subName);
                        unset($filters[$name]);
                    }

                    unset($rules[$name]);
                    unset($inputs[$realName][$subName]);

                    if (! count($inputs[$realName])) {
                        unset($inputs[$realName]);
                    }

                    $messages = $this->fixMessages($messages, $name, $realName, $subName);
                    $messages = $this->removeMessage($messages);
                }
            }
        }

        $this->inputs = $inputs;
        $this->rules = $rules;
        $this->attributes = $attributes;
        $this->filters = $filters;
        $this->messages = $messages;
    }
265753
protected function processResponse()
    {
        $body = $this->response->getBody();

        // Look for UTF-8 BOM and remove.
        if (0 === strpos(bin2hex(substr($body, 0, 4)), 'efbbbf')) {
            $body = substr($body, 3);
        }

        $parsedResponse = \json_decode($body);

        // Test if return a valid JSON.
        if (JSON_ERROR_NONE !== json_last_error()) {
            $message = function_exists('json_last_error_msg') ? json_last_error_msg() : 'Invalid JSON returned';
            throw new HttpClientException(
                sprintf('JSON ERROR: %s', $message),
                $this->response->getCode(),
                $this->request,
                $this->response
            );
        }

        $this->lookForErrors($parsedResponse);

        return $parsedResponse;
    }
1084326
public function processResponse()
    {
        if (empty($this->packets_response)) {
            return [];
        }

        // Implode and rip out the JSON
        preg_match('/\{(.*)\}/ms', implode('', $this->packets_response), $matches);

        // Return should be JSON, let's validate
        if (!isset($matches[0]) || ($json = json_decode($matches[0])) === null) {
            throw new Exception("JSON response from Eco server is invalid.");
        }

        $result = new Result();

        // Server is always dedicated
        $result->add('dedicated', 1);

        foreach ($json->Info as $info => $setting) {
            $result->add(strtolower($info), $setting);
        }

        return $result->fetch();
    }
699487
public function processResponse()
    {

        // Results that will be returned
        $results = [ ];

        // Get the length of the server code so we can figure out how much to read later
        $serverCodeLength = strlen($this->server_code);

        // We need to pre-sort these for split packets so we can do extra work where needed
        foreach ($this->packets_response as $response) {
            // Make new buffer
            $buffer = new Buffer($response);

            // Check the header, should be SAMP
            if (($header = $buffer->read(4)) !== 'SAMP') {
                throw new Exception(__METHOD__ . " header response '{$header}' is not valid");
            }

            // Check to make sure the server response code matches what we sent
            if ($buffer->read($serverCodeLength) !== $this->server_code) {
                throw new Exception(__METHOD__ . " code check failed.");
            }

            // Figure out what packet response this is for
            $response_type = $buffer->read(1);

            // Figure out which packet response this is
            if (!array_key_exists($response_type, $this->responses)) {
                throw new Exception(__METHOD__ . " response type '{$response_type}' is not valid");
            }

            // Now we need to call the proper method
            $results = array_merge(
                $results,
                call_user_func_array([ $this, $this->responses[$response_type] ], [ $buffer ])
            );

            unset($buffer);
        }

        return $results;
    }