Send the request to the server - decode and return the response

@param  object   $mnet_peer      A mnet_peer object with details of the
remote host we're connecting to
@return mixed                    A PHP variable, as returned by the
remote function
977982
function send($mnet_peer) {
        global $CFG, $DB;


        if (!$this->permission_to_call($mnet_peer)) {
            mnet_debug("tried and wasn't allowed to call a method on $mnet_peer->wwwroot");
            return false;
        }

        $this->requesttext = xmlrpc_encode_request($this->method, $this->params, array("encoding" => "utf-8", "escaping" => "markup"));
        $this->signedrequest = mnet_sign_message($this->requesttext);
        $this->encryptedrequest = mnet_encrypt_message($this->signedrequest, $mnet_peer->public_key);

        $httprequest = $this->prepare_http_request($mnet_peer);
        curl_setopt($httprequest, CURLOPT_POSTFIELDS, $this->encryptedrequest);

        $timestamp_send    = time();
        mnet_debug("about to send the curl request");
        $this->rawresponse = curl_exec($httprequest);
        mnet_debug("managed to complete a curl request");
        $timestamp_receive = time();

        if ($this->rawresponse === false) {
            $this->error[] = curl_errno($httprequest) .':'. curl_error($httprequest);
            return false;
        }
        curl_close($httprequest);

        $this->rawresponse = trim($this->rawresponse);

        $mnet_peer->touch();

        $crypt_parser = new mnet_encxml_parser();
        $crypt_parser->parse($this->rawresponse);

        // If we couldn't parse the message, or it doesn't seem to have encrypted contents,
        // give the most specific error msg available & return
        if (!$crypt_parser->payload_encrypted) {
            if (! empty($crypt_parser->remoteerror)) {
                $this->error[] = '4: remote server error: ' . $crypt_parser->remoteerror;
            } else if (! empty($crypt_parser->error)) {
                $crypt_parser_error = $crypt_parser->error[0];

                $message = '3:XML Parse error in payload: '.$crypt_parser_error['string']."\n";
                if (array_key_exists('lineno', $crypt_parser_error)) {
                    $message .= 'At line number: '.$crypt_parser_error['lineno']."\n";
                }
                if (array_key_exists('line', $crypt_parser_error)) {
                    $message .= 'Which reads: '.$crypt_parser_error['line']."\n";
                }
                $this->error[] = $message;
            } else {
                $this->error[] = '1:Payload not encrypted ';
            }

            $crypt_parser->free_resource();
            return false;
        }

        $key  = array_pop($crypt_parser->cipher);
        $data = array_pop($crypt_parser->cipher);

        $crypt_parser->free_resource();

        // Initialize payload var
        $decryptedenvelope = '';

        //                                          &$decryptedenvelope
        $isOpen = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), $this->mnet->get_private_key());

        if (!$isOpen) {
            // Decryption failed... let's try our archived keys
            $openssl_history = get_config('mnet', 'openssl_history');
            if(empty($openssl_history)) {
                $openssl_history = array();
                set_config('openssl_history', serialize($openssl_history), 'mnet');
            } else {
                $openssl_history = unserialize($openssl_history);
            }
            foreach($openssl_history as $keyset) {
                $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']);
                $isOpen      = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), $keyresource);
                if ($isOpen) {
                    // It's an older code, sir, but it checks out
                    break;
                }
            }
        }

        if (!$isOpen) {
            trigger_error("None of our keys could open the payload from host {$mnet_peer->wwwroot} with id {$mnet_peer->id}.");
            $this->error[] = '3:No key match';
            return false;
        }

        if (strpos(substr($decryptedenvelope, 0, 100), '<signedMessage>')) {
            $sig_parser = new mnet_encxml_parser();
            $sig_parser->parse($decryptedenvelope);
        } else {
            $this->error[] = '2:Payload not signed: ' . $decryptedenvelope;
            return false;
        }

        // Margin of error is the time it took the request to complete.
        $margin_of_error  = $timestamp_receive - $timestamp_send;

        // Guess the time gap between sending the request and the remote machine
        // executing the time() function. Marginally better than nothing.
        $hysteresis       = ($margin_of_error) / 2;

        $remote_timestamp = $sig_parser->remote_timestamp - $hysteresis;
        $time_offset      = $remote_timestamp - $timestamp_send;
        if ($time_offset > 0) {
            $threshold = get_config('mnet', 'drift_threshold');
            if(empty($threshold)) {
                // We decided 15 seconds was a pretty good arbitrary threshold
                // for time-drift between servers, but you can customize this in
                // the config_plugins table. It's not advised though.
                set_config('drift_threshold', 15, 'mnet');
                $threshold = 15;
            }
            if ($time_offset > $threshold) {
                $this->error[] = '6:Time gap with '.$mnet_peer->name.' ('.$time_offset.' seconds) is greater than the permitted maximum of '.$threshold.' seconds';
                return false;
            }
        }

        $this->xmlrpcresponse = base64_decode($sig_parser->data_object);
        $this->response       = xmlrpc_decode($this->xmlrpcresponse);

        // xmlrpc errors are pushed onto the $this->error stack
        if (is_array($this->response) && array_key_exists('faultCode', $this->response)) {
            // The faultCode 7025 means we tried to connect with an old SSL key
            // The faultString is the new key - let's save it and try again
            // The re_key attribute stops us from getting into a loop
            if($this->response['faultCode'] == 7025 && empty($mnet_peer->re_key)) {
                mnet_debug('recieved an old-key fault, so trying to get the new key and update our records');
                // If the new certificate doesn't come thru clean_param() unmolested, error out
                if($this->response['faultString'] != clean_param($this->response['faultString'], PARAM_PEM)) {
                    $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
                }
                $record                     = new stdClass();
                $record->id                 = $mnet_peer->id;
                $record->public_key         = $this->response['faultString'];
                $details                    = openssl_x509_parse($record->public_key);
                if(!isset($details['validTo_time_t'])) {
                    $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
                }
                $record->public_key_expires = $details['validTo_time_t'];
                $DB->update_record('mnet_host', $record);

                // Create a new peer object populated with the new info & try re-sending the request
                $rekeyed_mnet_peer = new mnet_peer();
                $rekeyed_mnet_peer->set_id($record->id);
                $rekeyed_mnet_peer->re_key = true;
                return $this->send($rekeyed_mnet_peer);
            }
            if (!empty($CFG->mnet_rpcdebug)) {
                if (get_string_manager()->string_exists('error'.$this->response['faultCode'], 'mnet')) {
                    $guidance = get_string('error'.$this->response['faultCode'], 'mnet');
                } else {
                    $guidance = '';
                }
            } else {
                $guidance = '';
            }
            $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'] ."\n".$guidance;
        }

        // ok, it's signed, but is it signed with the right certificate ?
        // do this *after* we check for an out of date key
        $verified = openssl_verify($this->xmlrpcresponse, base64_decode($sig_parser->signature), $mnet_peer->public_key);
        if ($verified != 1) {
            $this->error[] = 'Invalid signature';
        }

        return empty($this->error);
    }
629536
protected function _receive($timeout = null)
    {
        $this->checkConnection();

        if ($timeout !== null) {
            stream_set_timeout($this->_connection, $timeout);
        }

        $response = fgets($this->_connection, 1024);
        $info = stream_get_meta_data($this->_connection);

        if (!empty($info['timed_out'])) {
            throw new SMTPException(__('%s has timed out', array($this->_host)));
        } elseif ($response === false) {
            throw new SMTPException(__('Could not read from %s', array($this->_host)));
        }

        return $response;
    }
364016
private function decode_response( $git, $response ) {
		switch ( $git ) {
			case 'github':
			case 'gitlab':
				$response = isset( $response->content ) ? base64_decode( $response->content ) : $response;
				break;
			case 'bbserver':
				$response = isset( $response->lines ) ? $this->bbserver_recombine_response( $response ) : $response;
				break;
		}

		return $response;
	}
102013
public function server()
    {
        $this->prepareInput();

        $encryptStr = !empty($_GET['echostr']) ? $_GET['echostr'] : $this->encryptStr;

        $input = array(
            $encryptStr,
            $this->token,
            $this->input->get('timestamp'),
            $this->input->get('nonce'),
        );

        if ($this->input->get('msg_signature')
            && $this->signature($input) !== $this->input->get('msg_signature')
        ) {
            throw new Exception('Bad Request', 400);
        }

        if ($this->input->get('echostr')) {

            $xml = $this->getCrypt()->decrypt($this->input->get('echostr'), $this->appId);
            
            return strip_tags($xml);
        }

        return $this->response($this->handleRequest());

    }
684069
public function recaptcha($response, $ipClient = null)
    {
        if ($this->getOptions()->getGRecaptchaKey()) {
            $client = new \Zend\Http\Client($this->getOptions()->getGRecaptchaUrl());
            $client->setParameterPost(array(
                'secret'  => $this->getOptions()->getGRecaptchaKey(),
                'response' => $response,
                'remoteip'   => $ipClient,
            ));
            $client->setMethod(\Zend\Http\Request::METHOD_POST);
    
            $result = $client->send();
            if ($result) {
                $jsonResult = \Zend\Json\Json::decode($result->getBody());
                if ($jsonResult->success) {
                    return true;
                }
            }
        }

        return false;
    }
395381
public static function getClientIp(\Psr\Http\Message\ServerRequestInterface $p_request = null)
    {
        //Just get the headers if we can or else use the SERVER global
        if ($p_request !== null) {
            $headers = $p_request->getHeaders();
        } else {
            if (function_exists('apache_request_headers')) {
                $headers = apache_request_headers();
            } else {
                $headers = $_SERVER;
            }
        }
        //Get the forwarded IP if it exists
        if (array_key_exists('X-Forwarded-For', $headers) &&
            filter_var($headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            $the_ip = $headers['X-Forwarded-For'];
        } else {
            if (array_key_exists('HTTP_X_FORWARDED_FOR', $headers) &&
                filter_var($headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
                $the_ip = $headers['HTTP_X_FORWARDED_FOR'];
            } else {
                if (array_key_exists('X-ClientSide', $headers)) {
                    $parts  = explode(':', $headers['X-ClientSide']);
                    $the_ip = $parts[0];
                } else {
                    $the_ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
                }
            }
        }
        return $the_ip;
    }
636666
function _sendRequest($myorder) {
    $myorder["host"] = "secure.linkpt.net";
    if (MODULE_PAYMENT_LINKPOINT_API_TRANSACTION_MODE == 'DevelopersTest') {
      $myorder["host"]     = "staging.linkpt.net";
    }
    $myorder["port"]       = "1129";
    $myorder["keyfile"]    =(DIR_FS_CATALOG . DIR_WS_MODULES . 'payment/linkpoint_api/' . MODULE_PAYMENT_LINKPOINT_API_LOGIN . '.pem');
    $myorder["configfile"] = MODULE_PAYMENT_LINKPOINT_API_LOGIN;        // This is your store number
    // set to ECI and UNSPECIFIED for ecommerce transactions:
    $myorder["transactionorigin"] = "ECI";
    $myorder["terminaltype"]      = "UNSPECIFIED";
    // debug - for testing communication only
    if (MODULE_PAYMENT_LINKPOINT_API_DEBUG != 'Off') {
    }
    if (MODULE_PAYMENT_LINKPOINT_API_CODE_DEBUG=='debug') {
      $myorder["debugging"] = "true";  // for development only - not intended for production use
      $myorder["debug"]     = "true";  // for development only - not intended for production use
      $myorder["webspace"]  = "true";  // for development only - not intended for production use
    }

    include(DIR_FS_CATALOG . DIR_WS_MODULES . 'payment/linkpoint_api/class.linkpoint_api.php');
    $mylphp = new lphp;

    // Send transaction, using cURL
    $result = $mylphp->curl_process($myorder);

    // do debug output
    $errorMessage = date('M-d-Y h:i:s') . "\n=================================\n\n" . ($mylphp->commError !='' ? $mylphp->commError . "\n\n" : '') . 'Response Code: ' . $result["r_approved"] . ' ' . $result["r_error"] . "\n\n=================================\n\n" . 'Sending to Gateway: ' . "\n" . $mylphp->sendData . "\n\n" . 'Result: ' . substr(print_r($result, true), 5) . "\n\n";
    if ($mylphp->commError != '') $errorMessage .= $mylphp->commError . "\n" . 'CURL info: ' . print_r($mylphp->commInfo, true) . "\n";
    if (CURL_PROXY_REQUIRED == 'True') $errorMessage .= 'Using CURL Proxy: [' . CURL_PROXY_SERVER_DETAILS . ']  with Proxy Tunnel: ' .($proxy_tunnel_flag ? 'On' : 'Off') . "\n";
    $failure = (!is_array($result) || $result["r_approved"] != "APPROVED") ? true : false;

    // handle logging
    if (strstr(MODULE_PAYMENT_LINKPOINT_API_DEBUG, 'Log')) {
      $this->_log($errorMessage, $myorder["oid"] . ($failure ? '_FAILED' : ''));
//      $this->_log($errorMessage . print_r($myorder, true) . print_r($mylphp->xmlString, true), $myorder["oid"] . ($failure ? '_FAILED' : ''));
    }
    if (strstr(MODULE_PAYMENT_LINKPOINT_API_DEBUG, 'Email') || ($failure && strstr(MODULE_PAYMENT_LINKPOINT_API_DEBUG, 'Alert'))) {
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, 'Linkpoint Debug Data' . ($failure ? ' - FAILURE' : ''), $errorMessage, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorMessage)), 'debug');
    }
    //DEBUG ONLY:$this->_log($errorMessage /*. print_r($myorder, true) . print_r($mylphp->xmlString, true)*/, $myorder["oid"]);
    if ($myorder['debugging'] == 'true') exit;
    return $result;
  }
391015
def sendrawtransaction(cls, rawtxn: str) -> str:
        ''''''

        if cls.is_testnet:
            url = 'https://testnet-explorer.peercoin.net/api/sendrawtransaction?hex={0}'.format(rawtxn)
        else:
            url = 'https://explorer.peercoin.net/api/sendrawtransaction?hex={0}'.format(rawtxn)

        resp = urllib.request.urlopen(url)
        return resp.read().decode('utf-8')
369731
public static function receive($rawInput=null){
        if($rawInput == null)
            throw new Error('The raw input must be set');
        $values =  json_decode( $rawInput, TRUE );
        if ($values != null) {
            return self::constructFrom($values, get_class(), null);
        } else {
            throw new Error('There was a problem decoding the webhook');
        }
    }
599309
public function process(
        ServerRequestInterface $p_request,
        RequestHandlerInterface $p_handler
    ): ResponseInterface {
        try {
            if ($this->checkRequest($p_request)) {
                return $this->encodeResponse(
                    $p_handler->handle(
                        $this->decodeRequest($p_request)
                    )
                );
            } else {
                if ($this->override) {
                    return $p_handler->handle($p_request);
                }
            }
        } catch (\Exception $ex) {
            return $this->createErrorResponse($ex);
        }
        return $this->createUnsupportedRequestResponse();
    }
875604
public function callAPIService($nvpstr){
        if($nvpstr == ""){
            throw new PaypalException('Paypal api call failed with nvpstr: '.$nvpstr);
        }
        $url = $this->getAPI_ENDPOINT();
        $response = $this->_nh->doPost($url, $nvpstr, 443);
        if(!empty($response)){
            list($info, $header, $body) = $response;
            if($info['http_code'] == 200 && !empty($body)){
                $nvpArray = $this->deformatNVP($body);
                if($nvpArray['ACK'] == "Success"){
                    return $nvpArray;
                }
                else{
                    throw new PaypalException('PayPal API call fail, result array: '.print_r($nvpArray, true));
                }
            }
            else{
                throw new PaypalException('Error in remote server response: '.print_r($info, true));
            }
        
        }
        else{
            throw new PaypalException('Remote server response is empty '.print_r($response, true));
        }
    }
47777
protected function sendRequest()
    {
        // Get AccessManager.
        $accessManager = $this->getAccessManager();

        // Make a Watson Bridge.
        $watsonBridge = $this->makeBridge();

        // Get Url We post to Watson to Get Profile.
        $postUrl = $accessManager->getProfileResourcePath();

        // Append query string if needed
        if (! empty($this->getQuery())) {
            $postUrl .= '?'.$this->getQuery();
        }

        // Cross the Bridge and return the Response.
        return $watsonBridge->post($postUrl, $this->getContainer()->getContentsForRequest());
    }
677623
static function sendUDP($server_ip, $server_port, $data, $timeout = 30)
    {
        $client = stream_socket_client("udp://$server_ip:$server_port", $errno, $errstr, $timeout);
        if (!$client)
        {
            echo "ERROR: $errno - $errstr<br />\n";
        }
        else
        {
            fwrite($client, $data);
            fclose($client);
        }
    }
52212
protected function sendPayRequest()
    {
        $this->newTransaction();

        $username = $this->config->get('gateway.asanpardakht.username');
        $password = $this->config->get('gateway.asanpardakht.password');
        $orderId = $this->transactionId();
        $price = $this->amount;
        $localDate = date("Ymd His");
        $additionalData = "";
        $callBackUrl = $this->getCallback();
        $req = "1,{$username},{$password},{$orderId},{$price},{$localDate},{$additionalData},{$callBackUrl},0";

        $encryptedRequest = $this->encrypt($req);
        $params = array(
            'merchantConfigurationID' => $this->config->get('gateway.asanpardakht.merchantConfigId'),
            'encryptedRequest' => $encryptedRequest
        );

        try {
            $soap = new SoapClient($this->serverUrl);
            $response = $soap->RequestOperation($params);

        } catch (\SoapFault $e) {
            $this->transactionFailed();
            $this->newLog('SoapFault', $e->getMessage());
            throw $e;
        }


        $response = $response->RequestOperationResult;
        $responseCode = explode(",", $response)[0];
        if ($responseCode != '0') {
            $this->transactionFailed();
            $this->newLog($response, AsanpardakhtException::getMessageByCode($response));
            throw new AsanpardakhtException($response);
        }
        $this->refId = substr($response, 2);
        $this->transactionSetRefId();
    }
664582
protected function getResponse($prompt = null)
    {
        $isError = false;
        $buffer = '';
        do {
            // process one character at a time
            try {
                $character = $this->socket->read(1);
            } catch (Exception $e) {
                throw new TelnetException('failed reading from socket', 0, $e);
            }

            if (in_array($character, [$this->NULL, $this->DC1])) {
                break;
            }

            if ($this->interpretAsCommand->interpret($character, $this->socket)) {
                continue;
            }

            $buffer .= $character;

            // check for prompt
            if ($this->promptMatcher->isMatch($prompt ?: $this->prompt, $buffer, $this->lineEnding)) {
                break;
            }

            // check for error prompt
            if ($this->promptMatcher->isMatch($this->promptError, $buffer, $this->lineEnding)) {
                $isError = true;
                break;
            }
        } while (true);

        return new TelnetResponse(
            $isError,
            $this->promptMatcher->getResponseText(),
            $this->promptMatcher->getMatches()
        );
    }
560846
public function send() {
        $curlUrl = $this->url;
        if ($this->params) {
            $queryString = http_build_query($this->params);
            $separator = parse_url($curlUrl, PHP_URL_QUERY) ? '&' : '?';
            $curlUrl .= $separator . $queryString;
        }

        // Mock the request if self::$mock exists
        if (self::$mock) {
            if (self::$mock['url'] == $curlUrl && self::$mock['method'] == $this->method) {
                return self::$mock['response'];
            }
            return null;
        }

        // Open and configure curl connection
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $curlUrl);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
        $headers = array(
            'User-Agent: SiftScience/v' . $this->version . ' sift-php/' . Sift::VERSION
        );
        if ($this->auth) {
            curl_setopt($ch, CURLOPT_USERPWD, $this->auth);
        }

        // HTTP-method-specific configuration.
        if ($this->method == self::POST) {
            if (function_exists('json_encode')) {
                $jsonString = json_encode($this->body);
            } else {
                require_once(dirname(__FILE__) . '/Services_JSON-1.0.3/JSON.php');
                $json = new Services_JSON();
                $jsonString = $json->encodeUnsafe($this->body);
            }

            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonString);
            array_push($headers, 'Content-Type: application/json',
                'Content-Length: ' . strlen($jsonString)
            );

        } else if ($this->method == self::DELETE) {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        }

        foreach ($this->curl_opts as $option => $value) {
            if ($option !== CURLOPT_HTTPHEADER) {
                curl_setopt($ch, $option, $value);
            } else {
                $headers = array_merge($headers, $value);
            }
        }

        // Send the request using curl and parse result
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErrno = curl_errno($ch);
        $curlError = curl_error($ch);
        curl_close($ch);

        return new SiftResponse($result, $httpStatusCode, $this, $curlErrno, $curlError);
    }
879011
public function onPacket($pct)
    {
        if ($this->cleaned) {
            return;
        }
        $m = isset($pct['method']) ? $pct['method'] : null;
        $args = isset($pct['arguments']) ? $pct['arguments'] : [];
        if (isset($pct['callbacks']) && is_array($pct['callbacks'])) {
            foreach ($pct['callbacks'] as $id => $path) {
                static::setPath($args, $path, [$this, 'remote_' . $id]);
            }
        }
        if (isset($pct['links']) && is_array($pct['links'])) {
            foreach ($pct['links'] as $link) {
                static::setPath($args, $link['to'], static::getPath($args, $link['from']));
            }
        }
        try {
            if (is_string($m)) {
                if (isset($this->localMethods[$m])) {
                    $this->localMethods[$m](...$args);
                } elseif (method_exists($this, $m . 'Method')) {
                    $func = [$this, $m . 'Method'];
                    $func(...$args);
                } else {
                    $this->handleException(new UndefinedMethodCalled(
                        'DNode: local method ' . json_encode($m) . ' does not exist. Packet: ' . json_encode($pct)
                    ));
                }
            } elseif (is_int($m)) {
                if (isset($this->callbacks[$m])) {
                    if (!$this->callbacks[$m](...$args)) {
                        unset($this->callbacks[$m]);
                    }
                } elseif (isset($this->persistentCallbacks[$m])) {
                    $this->persistentCallbacks[$m](...$args);
                } else {
                    $this->handleException(new UndefinedMethodCalled(
                        'DNode: local callback # ' . $m . ' is not registered. Packet: ' . json_encode($pct)
                    ));
                }
            } else {
                $this->handleException(new ProtocolError(
                    'DNode: \'method\' must be string or integer. Packet: ' . json_encode($pct)
                ));
            }
        } catch (\Throwable $exception) {
        }
    }