Prepare CURL object

@throws BuildException
489491
public function init()
    {
        $this->cookiesFile = tempnam(sys_get_temp_dir(), 'WikiPublish.' . uniqid('', true) . '.cookies');

        $this->curl = curl_init();
        if (false === is_resource($this->curl)) {
            throw new BuildException('Curl init failed (' . $this->apiUrl . ')');
        }

        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->curl, CURLOPT_COOKIEJAR, $this->cookiesFile);
        curl_setopt($this->curl, CURLOPT_COOKIEFILE, $this->cookiesFile);
    }
199645
private function prepareRequest($curl, $curlOptions) {
        // set cookie
        if (!empty($this->cookiePath) || !empty($curlOptions['cookie'])) {
            $this->addCurlOption('cookiejar', $this->cookiePath);
            $this->addCurlOption('cookiefile', $this->cookiePath);
        }

        // set proxy
        if (!empty($this->proxy) || !empty($curlOptions['proxy'])) {
            $this->addCurlOptions($this->proxy);
        }

        $this->addCurlOptions($curlOptions);
        // set headers
        if (empty($this->requestHeaders)){
            $this->appendRequestHeaders(array(
                ['User-Agent', $this->curlOptions['CURLOPT_USERAGENT']],
                ['Accept-Charset', 'UTF-8']
            ));
        }

        self::applyCurlOption($curl, $this->curlOptions);
        curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, 'handleResponseHeaders'));
        curl_setopt($curl, CURLOPT_HTTPHEADER, self::prepareRequestHeaders($this->requestHeaders));

        if ($this->debug){
            var_dump($this->curlOptions);
            var_dump($this->requestHeaders);
        }
        return $curl;
    }
319727
protected function prepareCurlOptions()
    {
        $opts = array();
        $url = $this->url;

        // CURLOPT_RESOLVE
        if ($this->ip) {
            $host = parse_url($url, PHP_URL_HOST);
            $url = substr_replace($url, $this->ip, strpos($url, $host), strlen($host));
            $this->headers['Host'] = $host;
        }

        switch ($this->method) {
            case 'GET' :
                $postData = false;
                break;

            case 'POST' :
                $postData = true;
                $opts[CURLOPT_POST] = 1;
                break;

            case 'DELETE':
            case 'PUT':
            case 'PATCH':
                $postData = true;
                $opts[CURLOPT_CUSTOMREQUEST] = $this->method;
                break;

            default:
                $postData = false;
                $opts[CURLOPT_CUSTOMREQUEST] = $this->method;
        }

        if ($this->data) {
            $data = is_string($this->data) ? $this->data : http_build_query($this->data);
            if ($postData) {
                $opts[CURLOPT_POSTFIELDS] = $data;
            } else {
                if (false === strpos($url, '?')) {
                    $url .= '?' . $data;
                } else {
                    $url .= '&' . $data;
                }
            }
        }

        if ($this->files) {
            $postFields = isset($opts[CURLOPT_POSTFIELDS]) ? $opts[CURLOPT_POSTFIELDS] : '';
            $opts[CURLOPT_POSTFIELDS] = $this->addFileField($postFields, $this->files);
        }

        if ($this->timeout > 0) {
            $opts[CURLOPT_TIMEOUT_MS] = $this->timeout;
        }

        if ($this->referer) {
            // Automatic use current request URL as referer URL
            if (true === $this->referer) {
                $opts[CURLOPT_REFERER] = $this->url;
            } else {
                $opts[CURLOPT_REFERER] = $this->referer;
            }
        }

        if ($this->userAgent) {
            $opts[CURLOPT_USERAGENT] = $this->userAgent;
        }

        if ($this->cookies) {
            $cookies = array();
            foreach ($this->cookies as $key => $value) {
                $cookies[] = $key . '=' . urlencode($value);
            }
            $opts[CURLOPT_COOKIE] = implode('; ', $cookies);
        }

        if ($this->contentType) {
            $this->headers['Content-Type'] = $this->contentType;
        }

        // Custom headers will overwrite other options
        if ($this->headers) {
            $headers = array();
            foreach ($this->headers as $key => $value) {
                $headers[] = $key . ': ' . $value;
            }
            $opts[CURLOPT_HTTPHEADER] = $headers;
        }

        $opts[CURLOPT_HEADER] = $this->header;
        $opts[CURLOPT_URL] = $url;

        $this->curlOptions += $opts + $this->defaultCurlOptions;
        return $this->curlOptions;
    }
35103
protected function prepareData()
    {
        if (!empty($this->data)) {
            if ($this->method === HttpMethods::GET) {
                $this->url = Utils::appendUrlQuery($this->url, $this->data);
            } else if ($this->method === HttpMethods::POST) {
                curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data);
            }
        }
    }
1132292
private function executeCurl ()
    {
        $result = curl_exec($this->cURL);

        if (!$result)
        {
            throw new CurlException($this->cURL);
        }

        return $result;
    }
262720
public function main()
    {
        if (!isset($this->url)) {
            throw new BuildException("Required attribute 'url' is missing");
        }

        try {
            $this->processResponse($this->createRequest()->send());
        } catch (HTTP_Request2_MessageException $e) {
            throw new BuildException($e);
        }
    }
636035
public function initialize() {
        $this->handler = curl_init();

        $this->setOption(CURLOPT_URL, $this->requestUrl)
             ->setOption(CURLOPT_VERBOSE, 0)
             ->setOption(CURLOPT_HEADER, 0);
    }
574391
public function execute()
    {
        if (!is_resource($this->handle)) {
            throw new RuntimeException('Curl handle has been closed, just open it before execute...');
        }

        curl_setopt_array($this->handle, array_filter($this->options));
        $return = curl_exec($this->handle);

        if ($return === false) {
            throw ExceptionFactory::build(
                curl_errno($this->handle),
                curl_error($this->handle)
            );
        }

        return $return;
    }
367356
public function main()
    {
        if ($this->function === null && $this->expression === null) {
            throw new BuildException(
                "You must specify a function to execute or PHP expression to evalute.",
                $this->getLocation()
            );
        }

        if ($this->function !== null && $this->expression !== null) {
            throw new BuildException("You can specify function or expression, but not both.", $this->getLocation());
        }

        if ($this->expression !== null && !empty($this->params)) {
            throw new BuildException(
                "You cannot use nested <param> tags when evaluationg a PHP expression.",
                $this->getLocation()
            );
        }

        if ($this->function !== null) {
            $this->callFunction();
        } elseif ($this->expression !== null) {
            $this->evalExpression();
        }
    }
145457
public function main()
    {

        // Apparently casting to (string) no longer invokes __toString() automatically.
        if (is_object($this->classpath)) {
            $classpath = $this->classpath->__toString();
        }

        if (empty($classpath)) {
            throw new BuildException("Provided classpath was empty.");
        }

        $curr_parts = Phing::explodeIncludePath();
        $add_parts = Phing::explodeIncludePath($classpath);
        $new_parts = array_diff($add_parts, $curr_parts);

        if ($new_parts) {
            $this->updateIncludePath($new_parts, $curr_parts);
        }
    }
1186868
protected function prepare()
    {
        if ($this->dir === null) {
            $this->dir = $this->getProject()->getBasedir();
        }

        if ($this->commandline->getExecutable() === null) {
            throw new BuildException(
                'ExecTask: Please provide "executable"'
            );
        }

        // expand any symbolic links first
        try {
            if (!$this->dir->getCanonicalFile()->exists()) {
                throw new BuildException(
                    "The directory '" . (string) $this->dir . "' does not exist"
                );
            }
            if (!$this->dir->getCanonicalFile()->isDirectory()) {
                throw new BuildException(
                    "'" . (string) $this->dir . "' is not a directory"
                );
            }
        } catch (IOException $e) {
            throw new BuildException(
                "'" . (string) $this->dir . "' is not a readable directory"
            );
        }
        $this->currdir = getcwd();
        @chdir($this->dir->getPath());

        $this->commandline->setEscape($this->escape);
    }
693692
private function prepareData()
    {
        $data = [];
        foreach (get_object_vars($this) as $property => $value) {
            if (in_array($property, ['apiHost', 'debug'])) {
                continue;
            }

            if ($property == 'format') {
                $data[$value] = '';
            } elseif (is_bool($value) && $value) {
                $data[$property] = '';
            } elseif (!is_null($value) && !is_bool($value)) {
                if (is_array($value)) {
                    foreach ($value as $key => $val) {
                        $value[$key] = $val;
                    }
                } else {
                    $value = $value;
                }

                $data[$property] = $value;
            }
        }

        if (empty($data) && $this->debug) {
            throw new \Exception('Query have not data');
        }

        $data = http_build_query($data);

        return $data;
    }
764381
public function build(): CompileScriptRequest
	{
		$instance = new CompileScriptRequest();
		if ($this->expression === null) {
			throw new BuilderException('Property [expression] is required.');
		}
		$instance->expression = $this->expression;
		if ($this->sourceURL === null) {
			throw new BuilderException('Property [sourceURL] is required.');
		}
		$instance->sourceURL = $this->sourceURL;
		if ($this->persistScript === null) {
			throw new BuilderException('Property [persistScript] is required.');
		}
		$instance->persistScript = $this->persistScript;
		$instance->executionContextId = $this->executionContextId;
		return $instance;
	}
556754
public function buildResponse($result) {
        if ($result === false) {
            if ($curlErrorNumber = curl_errno($this->_ch)) {
                $curlErrorString = curl_error($this->_ch);
                $this->_error($curlErrorString);

                $exception = new ConnectionErrorException('Unable to connect to "'.$this->uri.'": '
                        . $curlErrorNumber . ' ' . $curlErrorString);

                $exception->setCurlErrorNumber($curlErrorNumber)
                    ->setCurlErrorString($curlErrorString);

                throw $exception;
            }

            $this->_error('Unable to connect to "'.$this->uri.'".');
            throw new ConnectionErrorException('Unable to connect to "'.$this->uri.'".');
        }

        $info = curl_getinfo($this->_ch);

        // Remove the "HTTP/1.x 200 Connection established" string and any other headers added by proxy
        $proxy_regex = "/HTTP\/1\.[01] 200 Connection established.*?\r\n\r\n/si";
        if ($this->hasProxy() && preg_match($proxy_regex, $result)) {
            $result = preg_replace($proxy_regex, '', $result);
        }

        $response = explode("\r\n\r\n", $result, 2 + $info['redirect_count']);

        $body = array_pop($response);
        $headers = array_pop($response);

        return new Response($body, $headers, $this, $info);
    }
901722
static private function _buildPost(&$data)
    {
        if (is_array($data)) {
            foreach ($data as &$value) {
                if (is_string($value) && $value[0] === '@' && class_exists('CURLFile', false)) {
                    $filename = realpath(trim($value, '@'));
                    file_exists($filename) && $value = new CURLFile($filename);
                }
            }
        }
        return $data;
    }
1199495
protected function call()
    {
        // Check if the curl object is set
        if (!$this->isInit()) {
            // If it isn't, we do it right now
            $this->init();
        }

        $options = array();
        // Set basic authentication if enabled
        if ($this->authentication instanceof BasicAuthentication) {
            $options['auth'] = array(
                $this->authentication->getUsername(),
                $this->authentication->getPassword()
            );
        }

        $request = $this->getHttpClient()->createRequest(
            $this->getHttpMethod(),
            $this->getEndpoint(),
            array_merge(
                $options,
                array('headers' => $this->getHeaders())
            )
        );

        foreach ($this->getEndpointParameters() as $key => $value) {
            $request->getQuery()->set($key, $value);
        }

        if (($body = $this->getBody()) !== null) {
            $request->setBody(\GuzzleHttp\Stream\Stream::factory($body));
        }

        try {
            $response = $this->getHttpClient()->send($request);
        } catch (ClientException $e) {// Check if not found
            if ($e->getResponse()->getStatusCode() === StatusCodes::HTTP_NOT_FOUND) {
                throw new HttpNotFoundException();
            }

            // Check if unauthorized
            if ($e->getResponse()->getStatusCode() === StatusCodes::HTTP_UNAUTHORIZED) {
                throw new UnauthorizedException();
            }

            throw $e;
        }

        $this->setHttpStatusCode($response->getStatusCode());

        if ($this->getAccept() == 'application/json') {
            $this->setData($response->json());
        } else {
            $this->setData($response->getBody(true));
        }
    }
1237024
private static function _buildHttpData($data, $build = true)
    {
        if (!is_array($data)) return $data;
        foreach ($data as $key => $value) if (is_object($value) && $value instanceof \CURLFile) {
            $build = false;
        } elseif (is_object($value) && isset($value->datatype) && $value->datatype === 'MY_CURL_FILE') {
            $build = false;
            $mycurl = new MyCurlFile((array)$value);
            $data[$key] = $mycurl->get();
            array_push(self::$cache_curl, $mycurl->tempname);
        } elseif (is_string($value) && class_exists('CURLFile', false) && stripos($value, '@') === 0) {
            if (($filename = realpath(trim($value, '@'))) && file_exists($filename)) {
                $build = false;
                $data[$key] = self::createCurlFile($filename);
            }
        }
        return $build ? http_build_query($data) : $data;
    }