Prepare cURL with the given request

@param \apiTalk\Request $requst

@return void
428401
protected function prepareRequest(Request $request)
    {
        $curl = curl_init();
        
        // TODO Timeout and Follow Redirect settings
        $options = array(
            CURLOPT_RETURNTRANSFER    => true,
            CURLOPT_HEADER            => true,
            CURLOPT_CONNECTTIMEOUT_MS => 1000,
            CURLOPT_TIMEOUT_MS        => 3000,
            CURLOPT_CUSTOMREQUEST     => $request->getMethod(),
            CURLOPT_URL               => $request->getUri(),
            CURLOPT_HTTPHEADER        => $request->getHeaders(),
            CURLOPT_HTTPGET           => false,
            CURLOPT_NOBODY            => false,
            CURLOPT_POST              => false,
            CURLOPT_POSTFIELDS        => null,           
        );

        switch ($request->getMethod()) {
            case Request::METHOD_HEAD:
                $options[CURLOPT_NOBODY] = true;
                
                $query = http_build_query($request->getParameters());
                if (!empty($query)) {
                    $options[CURLOPT_URL] = $request->getUri().'?'.$query;
                }
                break;

            case Request::METHOD_GET:
                $options[CURLOPT_HTTPGET] = true;
                
                $query = http_build_query($request->getParameters());
                if (!empty($query)) {
                    $options[CURLOPT_URL] = $request->getUri().'?'.$query;
                }
                break;

            case Request::METHOD_POST:
            case Request::METHOD_PUT:
                $options[CURLOPT_POST] = true;
                $options[CURLOPT_POSTFIELDS] = http_build_query($request->getParameters());
                break;
        }
        
        curl_setopt_array($curl, $options);
        
        return $curl;
    }
747016
protected function prepareToHandleNewRequest(ehough_shortstop_api_HttpRequest $request)
    {
        $isDebugEnabled = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);

        if ($isDebugEnabled) {

            $this->_logger->debug('Initializing cURL');
        }

        $this->_handle = curl_init($request->getUrl()->toString());
        $this->_setCurlOptions($request);

        if ($isDebugEnabled) {

            $this->_logger->debug('cURL initialized');
        }
    }
934351
protected function prepareHeaders()
    {
        // Need to let curl set the content type when posting. Our own content type
        // value would overwrite that.
        if ($this->method === HttpMethods::POST && !empty($this->headers["Content-Type"])) {
            unset($this->headers["Content-Type"]);
        }
        
        curl_setopt($this->curl, CURLOPT_USERAGENT, $this->userAgent);
        if (!empty($this->headers)) {
            $headers = $this->getHeadersBuilder()->normalize($this->headers);
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
        }
    }
38620
protected function prepareRequest($request) {
    $request->header('X-M2X-KEY', $this->apiKey);
    $request->header('User-Agent', $this->userAgent);
    return $request;
  }
25831
protected function preinit($req)
    {
        if ($req === null) {
            $req = new \stdClass;
            $req->attrs = new \stdClass;
            $req->attrs->inputDone = true;
            $req->attrs->paramsDone = true;
            $req->attrs->chunked = false;
        }

        $this->attrs = $req->attrs;

        if ($this->upstream->pool->config->expose->value) {
            $this->header('X-Powered-By: phpDaemon/' . Daemon::$version);
        }

        $this->attrs->input->setRequest($this);

        $this->parseParams();
    }
3247
public function put($params = null)
    {
        $handle = $this->preparePut($params);
        return $this->curlGetResponse($handle);
    }
1210473
protected function prepareRequest(): void
    {
        // HTTP method
        $method = Request::getMethod();
        $this->method = strtoupper($method);

        // get path
        // %module% / %controller% / %id% / %relation% / %id%
        $path = Router::getCleanUri();

        $this->params = explode('/', rtrim($path, '/'));

        // module
        $this->module = array_shift($this->params);

        // controller
        $this->controller = array_shift($this->params);

        $data = Request::getParams();

        unset($data['_method'], $data['_module'], $data['_controller']);

        $this->data = array_merge($data, $this->data);

        $primary = $this->crud->getPrimaryKey();

        $this->primary = array_intersect_key($this->data, array_flip($primary));
    }
309821
protected function prepare_response() {
        try {
            if (!empty($this->function->returns_desc)) {
                $validatedvalues = external_api::clean_returnvalue($this->function->returns_desc, $this->returns);
                $encodingoptions = array(
                    "encoding" => "UTF-8",
                    "verbosity" => "no_white_space",
                    // See MDL-54868.
                    "escaping" => ["markup"]
                );
                // We can now convert the response to the requested XML-RPC format.
                $this->response = xmlrpc_encode_request(null, $validatedvalues, $encodingoptions);
            }
        } catch (invalid_response_exception $ex) {
            $this->response = $this->generate_error($ex);
        }
    }
648135
private function initialize($params = array())
	{
		if (count($params) > 0)
		{
			foreach ($params as $key => $value)
			{
				if (isset($this->{$key}))
				{
					$this->{$key} = $value;
				}
				else if (strpos($key, 'CURLOPT_') === 0) 
				{
					curl_setopt($this->ch, $key, $value);    
				}
			}
		}
	}
1086505
private function setupCurl(&$curl)
    {

        $header = array();

        switch ($this->postFormat) {
            case 'json':
                $header['content'] = 'Content-Type: application/json';
                break;

            default:
                $header['content'] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8';
                break;
        }

        switch ($this->authMode) {
            case 'webauth':
                curl_setopt($curl, CURLOPT_USERPWD, $this->authModeSettings->login . ":" . $this->authModeSettings->password);
                break;

            case 'jwt':
                $header['token'] = 'X-ACCESS-TOKEN: ' . $this->authModeSettings->token;
                // $header['token'] = 'Authorization: Bearer ' . $this->authModeSettings->token;
                break;

            case 'bearer':
                $header['token'] = 'Authorization: Bearer ' . $this->authModeSettings->token;
                break;

            default:
                # code...
                break;
        }

        
        $this->debugValues->header = $header;
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }
741484
private function _setupCurl()
    {
        $requestParams = http_build_query($this->requestParams);

        $this->uri = $this->action;
        if ($this->method == 'GET') {
            $this->uri .= '?'.$requestParams;
        }

        $this->curl = curl_init($this->uri);

        if ($this->method == 'POST') {
            // POST requests
            curl_setopt($this->curl, CURLOPT_POST, true);
            curl_setopt($this->curl, CURLOPT_POSTFIELDS, $requestParams);
        }

        // We want to receive the returned data
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
        // Setup custom user agent
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->formatUserAgentInfo());
    }
612920
public function sendRequest(Http\Request $request)
    {
        if (!extension_loaded('curl')) {
            throw new Http\Exception('CurlEngine requires the PHP CURL extension to be installed and loaded.', 1346319808);
        }

        $requestUri = $request->getUri();
        $curlHandle = curl_init((string)$requestUri);

        curl_setopt_array($curlHandle, $this->options);

        // Send an empty Expect header in order to avoid chunked data transfer (which we can't handle yet).
        // If we don't set this, cURL will set "Expect: 100-continue" for requests larger than 1024 bytes.
        curl_setopt($curlHandle, CURLOPT_HTTPHEADER, ['Expect:']);

        // If the content is a stream resource, use cURL's INFILE feature to stream it
        $content = $request->getContent();
        if (is_resource($content)) {
            curl_setopt_array($curlHandle,
                [
                    CURLOPT_INFILE => $content,
                    CURLOPT_INFILESIZE => $request->getHeader('Content-Length'),
                ]
            );
        }

        switch ($request->getMethod()) {
            case 'GET':
                if ($request->getContent()) {
                    // workaround because else the request would implicitly fall into POST:
                    curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, 'GET');
                    if (!is_resource($content)) {
                        curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $content);
                    }
                }
            break;
            case 'POST':
                curl_setopt($curlHandle, CURLOPT_POST, true);
                if (!is_resource($content)) {
                    $body = $content !== '' ? $content : http_build_query($request->getArguments());
                    curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $body);
                }
            break;
            case 'PUT':
                curl_setopt($curlHandle, CURLOPT_PUT, true);
                if (!is_resource($content) && $content !== '') {
                    $inFileHandler = fopen('php://temp', 'r+');
                    fwrite($inFileHandler, $request->getContent());
                    rewind($inFileHandler);
                    curl_setopt_array($curlHandle, [
                        CURLOPT_INFILE => $inFileHandler,
                        CURLOPT_INFILESIZE => strlen($request->getContent()),
                    ]);
                }
            break;
            case 'HEAD':
                if (!is_resource($content)) {
                    $body = $content !== '' ? $content : http_build_query($request->getArguments());
                    curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $body);
                }
                curl_setopt($curlHandle, CURLOPT_NOBODY, true);
            break;
            default:
                if (!is_resource($content)) {
                    $body = $content !== '' ? $content : http_build_query($request->getArguments());
                    curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $body);
                }
                curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, $request->getMethod());
        }

        $preparedHeaders = [];
        foreach ($request->getHeaders()->getAll() as $fieldName => $values) {
            foreach ($values as $value) {
                $preparedHeaders[] = $fieldName . ': ' . $value;
            }
        }
        curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $preparedHeaders);

        // curl_setopt($curlHandle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP && CURLPROTO_HTTPS);
        // CURLOPT_UPLOAD

        if ($requestUri->getPort() !== null) {
            curl_setopt($curlHandle, CURLOPT_PORT, $requestUri->getPort());
        }

        if (count($request->getCookies()) > 0) {
            $cookies = [];
            foreach ($request->getCookies() as $cookie) {
                $cookies[] = $cookie->getName() . '=' . $cookie->getValue();
            }
            curl_setopt($curlHandle, CURLOPT_COOKIE, implode('; ', $cookies));
        }

        $curlResult = curl_exec($curlHandle);
        if ($curlResult === false) {
            throw new CurlEngineException(sprintf('cURL reported error code %s with message "%s". Last requested URL was "%s" (%s).', curl_errno($curlHandle), curl_error($curlHandle), curl_getinfo($curlHandle, CURLINFO_EFFECTIVE_URL), $request->getMethod()), 1338906040);
        } elseif (strlen($curlResult) === 0) {
            return false;
        }
        curl_close($curlHandle);

        $response = Http\Helper\ResponseInformationHelper::createFromRaw($curlResult);
        try {
            while (substr($response->getContent(), 0, 5) === 'HTTP/' || $response->getStatusCode() === 100) {
                $response = Http\Response::createFromRaw($response->getContent(), $response);
            }
        } catch (\InvalidArgumentException $e) {
        }

        return $response;
    }
758239
public static function crearDesdeSwoole(\swoole_http_request $req)
    {
        // Preparamos Metodo
        $metodo = $req->server['request_method'];

        // Preparamos URL
        $url = 'http';
        if (!empty($req->server['https']) && $req->server['https'] !== 'off') {
            $url .= 's';
        } elseif ($req->server['server_port'] == 443) {
            $url .= 's';
        }

        $url .= '://' . $req->header['host'];
        $url .= $req->server['request_uri'];
        if (isset($req->server['query_string'])) {
            $url .= '?' . $req->server['query_string'];
        }

        // Preparamos parámetros según método
        $parametros = [];
        if (!empty($req->post)) {
            $parametros = $req->post;
        }
        if ($metodo != 'GET' && isset($req->header['content-type'])) {
            $parametros = self::procesarParametros($req->rawContent(), $req->header['content-type'], $parametros);
        }

        // Preparamos cabeceras
        $cabeceras = [];
        foreach($req->header as $nombre => $valor) {
            $nombre = str_replace(' ', '-', ucwords(str_replace('-', ' ', $nombre)));
            if (isset($cabeceras[$nombre])) {
                if (is_array($cabeceras[$nombre])) {
                    $cabeceras[$nombre][] = $valor;
                } else {
                    $cabeceras[$nombre] = [$cabeceras[$nombre], $valor];
                }
            } else {
                $cabeceras[$nombre] = $valor;
            }
        }


        // Preparamos galletas
        $galletas = [];
        if (!empty($req->cookie)) {
            $galletas = $req->cookie;
        }

        // Preparamos arhivos
        $archivos = [];
        if (!empty($req->files)) {
            $archivos = $req->files;
        }

        // Iniciamos instancia de petición con los datos ya preparados
        $peticion = new Peticion($url, $metodo, $parametros, $cabeceras, $galletas, $archivos);

        // Preparamos IP del cliente
        $peticion->cliente_ip = $req->server['remote_addr'];
        if (isset($req->server['x-client-ip'])) {
            $peticion->cliente_ip = $req->server['x-client-ip'];
        } elseif (isset($req->server['x-real-ip'])) {
            $peticion->cliente_ip = $req->server['x-real-ip'];
        } elseif (isset($_SERVER['x-forwarded-for'])) {
            $peticion->cliente_ip = trim(explode(',', $_SERVER['x-forwarded-for'])[0]);
        }

        // Retornamos instancia iniciada
        return $peticion;
    }
227951
public function init(String $url = NULL) : CURL
    {
        if( $url !== NULL && ! IS::URL($url) )
        {
            $url = Request::getSiteURL($url);
        }

        $this->init = curl_init($url);

        return $this;
    }
1373295
protected function preparePutRequest(Request $request, $data)
    {
        $request->setOption(CURLOPT_CUSTOMREQUEST, 'PUT');
        if ($data !== null) {
            $request->setOption(CURLOPT_POSTFIELDS, $data);
        }
    }
1128698
private function prepareCurl()
    {
        $curl = new Curl();
        $curl->setOption(CURLOPT_USERAGENT, 'B2BackblazeClient');
        $curl->setVerifyPeer(false);
        $curl->setTimeout($this->timeout);

        return $curl;
    }
922767
private function prepareCurl()
    {
        $ch = $this->getCurl();

        // Set cURL opts
        curl_setopt($ch, CURLOPT_URL, self::EXPO_API_URL);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'accept: application/json',
            'content-type: application/json',
        ]);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        return $ch;
    }