Example #1
0
 /**
  * revert all ::setopt() operation
  *
  * @return $this
  */
 public function reset()
 {
     if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
         curl_reset($this->_curl);
     }
     return $this;
 }
Example #2
0
 public static function curlPrepare($url, $options = false)
 {
     if (empty(self::$curl)) {
         self::$curl = curl_init($url);
     } else {
         if (function_exists('curl_reset')) {
             curl_reset(self::$curl);
         } else {
             curl_close(self::$curl);
             self::$curl = null;
             self::$curl = curl_init($url);
         }
     }
     curl_setopt(self::$curl, CURLOPT_HEADER, false);
     curl_setopt(self::$curl, CURLOPT_RETURNTRANSFER, true);
     curl_setopt(self::$curl, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt(self::$curl, CURLOPT_SSL_VERIFYHOST, false);
     curl_setopt(self::$curl, CURLOPT_FOLLOWLOCATION, true);
     curl_setopt(self::$curl, CURLOPT_MAXREDIRS, 5);
     curl_setopt(self::$curl, CURLOPT_ENCODING, '');
     curl_setopt(self::$curl, CURLOPT_USERAGENT, 'Curl');
     if ($url) {
         $url = str_ireplace(' ', '%20', $url);
         curl_setopt(self::$curl, CURLOPT_URL, $url);
     }
     if (!empty($options) && is_array($options)) {
         foreach ($options as $option => $value) {
             curl_setopt(self::$curl, $option, $value);
         }
     }
     return self::$curl;
 }
 public function call($uri, $method = 'GET', $content = null)
 {
     $url = $this->getServer() . '/' . ltrim($uri, '/');
     curl_reset($this->_handle);
     curl_setopt($this->_handle, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($this->_handle, CURLOPT_HEADER, 1);
     curl_setopt($this->_handle, CURLOPT_URL, $url);
     curl_setopt($this->_handle, CURLOPT_USERAGENT, self::USERAGENT);
     curl_setopt($this->_handle, CURLOPT_CONNECTTIMEOUT, self::CONNECTTIMEOUT);
     curl_setopt($this->_handle, CURLOPT_TIMEOUT, self::TIMEOUT);
     curl_setopt($this->_handle, CURLOPT_SSL_VERIFYPEER, $this->_verifypeer);
     curl_setopt($this->_handle, CURLOPT_COOKIEFILE, '');
     curl_setopt($this->_handle, CURLINFO_HEADER_OUT, true);
     if ($method == 'GET') {
         curl_setopt($this->_handle, CURLOPT_HTTPGET, 1);
     } elseif ($method == 'POST') {
         curl_setopt($this->_handle, CURLOPT_POST, 1);
         curl_setopt($this->_handle, CURLOPT_POSTFIELDS, $content);
     } elseif ($method == 'PUT') {
         curl_setopt($this->_handle, CURLOPT_PUT, 1);
         curl_setopt($this->_handle, CURLOPT_INFILE, $content);
         curl_setopt($this->_handle, CURLOPT_INFILESIZE, filesize($content));
     } else {
         return false;
     }
     $res = curl_exec($this->_handle);
     if ($res === false) {
         return false;
     }
     $data = array('url' => curl_getinfo($this->_handle, CURLINFO_EFFECTIVE_URL), 'http_code' => curl_getinfo($this->_handle, CURLINFO_HTTP_CODE), 'total_time' => curl_getinfo($this->_handle, CURLINFO_TOTAL_TIME), 'request_header' => explode("\r\n", curl_getinfo($this->_handle, CURLINFO_HEADER_OUT)), 'header' => explode("\r\n", substr($res, 0, curl_getinfo($this->_handle, CURLINFO_HEADER_SIZE))), 'body' => substr($res, curl_getinfo($this->_handle, CURLINFO_HEADER_SIZE)));
     return $data;
 }
Example #4
0
 /**
  * Execute the request
  * @return [type]
  */
 private function sendRequest()
 {
     $output = curl_exec($this->handle);
     curl_reset($this->handle);
     // clear options
     $this->options = [];
     return $output;
 }
Example #5
0
 protected function sendInternal(CurlConfig $config, $startTime = null, $retryCount = 1)
 {
     if (empty($config->url)) {
         throw new InvalidConfigException("You can't send a request without setting the url first.");
     }
     if ($startTime === null) {
         $startTime = time();
     }
     if (!is_resource($this->handle)) {
         $this->handle = curl_init();
     } else {
         curl_reset($this->handle);
     }
     if (!empty($config->cookies)) {
         curl_setopt($this->handle, CURLOPT_COOKIE, http_build_query($config->cookies, '', '; ', PHP_QUERY_RFC3986));
     }
     if (!empty($config->headers)) {
         $headers = [];
         foreach ($config->headers as $name => $value) {
             $headers[] = "{$name}: {$value}";
         }
         curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers);
     }
     if (!empty($config->referer)) {
         curl_setopt($this->handle, CURLOPT_REFERER, $config->referer);
     }
     curl_setopt_array($this->handle, [CURLOPT_ENCODING => 'gzip,deflate', CURLOPT_URL => $config->url, CURLOPT_POST => $config->method === self::METHOD_POST, CURLOPT_USERAGENT => $config->userAgent, CURLOPT_AUTOREFERER => $config->autoReferer, CURLOPT_FOLLOWLOCATION => $config->followRedirects, CURLOPT_MAXREDIRS => $config->maxRedirects, CURLOPT_CONNECTTIMEOUT => (int) $config->connectTimeout, CURLOPT_TIMEOUT => (int) $config->globalTimeout, CURLOPT_HEADER => true, CURLOPT_NOBODY => $config->headersOnly, CURLOPT_RETURNTRANSFER => true, CURLOPT_FORBID_REUSE => !$config->reuseConnection, CURLOPT_MAX_RECV_SPEED_LARGE => $config->maxReceiveSpeed, CURLOPT_MAX_SEND_SPEED_LARGE => $config->maxSendSpeed, CURLOPT_LOW_SPEED_LIMIT => $config->lowSpeedLimit, CURLOPT_LOW_SPEED_TIME => $config->lowSpeedTime, CURLOPT_SSL_VERIFYHOST => $config->sslVerifyHost, CURLOPT_SSL_VERIFYPEER => $config->sslVerifyPeer, CURLOPT_FAILONERROR => false, CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS]);
     if ($config->proxy !== null) {
         $proxy = $config->getProxyInfo();
         curl_setopt_array($this->handle, [CURLOPT_PROXY => $proxy['ip'], CURLOPT_PROXYPORT => $proxy['port'], CURLOPT_PROXYTYPE => $proxy['type'], CURLOPT_PROXYUSERPWD => $proxy['login']]);
     }
     if ($config->progressHandler !== null && !$config->headersOnly) {
         curl_setopt_array($this->handle, [CURLOPT_NOPROGRESS => false, CURLOPT_PROGRESSFUNCTION => function ($curl, $dltotal, $dlnow, $ultotal, $ulnow) use($config) {
             return call_user_func_array($config->progressHandler, [$dltotal, $dlnow, $ultotal, $ulnow]);
         }]);
     }
     $response = new CurlResponse($this->handle, clone $config, curl_exec($this->handle));
     if ($response->getFailed()) {
         if ($config->throwException && $response->getTooManyRedirects()) {
             throw new TooManyRedirectsException($response, "The request failed due to too many redirects.", $response->errorNumber);
         } elseif ($config->throwException && $response->aborted) {
             throw new RequestAbortedException($response, "The request was aborted.", $response->errorNumber);
         } elseif ($config->retryHandler !== null && call_user_func_array($config->retryHandler, [$config, $response, $retryCount, time() - $startTime])) {
             $this->sendInternal($config, $startTime, ++$retryCount);
         } elseif ($config->throwException) {
             if ($response->getTimedOut()) {
                 throw new RequestTimedOutException($response, "The request timed out.", $response->errorNumber);
             } else {
                 throw new RequestFailedException($response, sprintf("The request failed: %s (#%d)", $response->error, $response->errorNumber), $response->errorNumber);
             }
         }
     } elseif (!empty($config->expectedHttpCodes) && !in_array($response->getHttpCode(), $config->expectedHttpCodes)) {
         throw new UnexpectedHttpCodeException($response, "Received an unexpected http code: {$response->getHttpCode()}", $response->errorNumber);
     }
     return $response;
 }
Example #6
0
/** \brief Reset cURL handle and set default options.
 *
 * \return Returns nothing on success. Otherwise an error message will be
 *  displayed and PHP dies.
 */
function curl_reset_handle($curl_handle)
{
    // reset cURL handle
    curl_reset($curl_handle);
    // enable cookie engine
    $options = array(CURLOPT_COOKIESESSION => true, CURLOPT_COOKIEJAR => "/dev/null");
    if (!curl_setopt_array($curl_handle, $options)) {
        error(500, "cURL Cookie-engine konnte nicht initialisiert werden.");
    }
}
Example #7
0
 protected function resetResourceOptions()
 {
     if (PHP_VERSION >= 5.5 && \function_exists('curl_reset')) {
         \curl_reset($this->curlResource);
     } else {
         \curl_close($this->curlResource);
         $this->curlResource = \curl_init();
     }
     return $this;
 }
Example #8
0
 public function release(EasyHandle $easy)
 {
     $resource = $easy->handle;
     unset($easy->handle);
     if (count($this->handles) >= $this->maxHandles) {
         curl_close($resource);
     } else {
         curl_reset($resource);
         $this->handles[] = $resource;
     }
 }
Example #9
0
 private static function GetCurl()
 {
     static $registeredShutdown = false;
     if (is_null(static::$curl_handle)) {
         static::$curl_handle = curl_init();
     } else {
         curl_reset(static::$curl_handle);
     }
     if (!$registeredShutdown) {
         $registeredShutdown = true;
         register_shutdown_function([HTTP::class, 'CloseCurl']);
     }
     return static::$curl_handle;
 }
Example #10
0
 public function request(RequestInterface $request)
 {
     if (is_resource($this->handler)) {
         curl_reset($this->handler);
     } else {
         $this->handler = curl_init();
     }
     $options = $this->createRequestOptions($request);
     foreach ($options as $option => $value) {
         curl_setopt($this->handler, $option, $value);
     }
     $raw = curl_exec($this->handler);
     if (curl_errno($this->handler) > 0) {
         throw new CurlException(curl_errno($this->handler), curl_error($this->handler), $request);
     } else {
         return $raw;
     }
 }
Example #11
0
 public function release(EasyHandle $easy)
 {
     $resource = $easy->handle;
     unset($easy->handle);
     if (count($this->handles) >= $this->maxHandles) {
         curl_close($resource);
     } else {
         // Remove all callback functions as they can hold onto references
         // and are not cleaned up by curl_reset. Using curl_setopt_array
         // does not work for some reason, so removing each one
         // individually.
         curl_setopt($resource, CURLOPT_HEADERFUNCTION, null);
         curl_setopt($resource, CURLOPT_READFUNCTION, null);
         curl_setopt($resource, CURLOPT_WRITEFUNCTION, null);
         curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, null);
         curl_reset($resource);
         $this->handles[] = $resource;
     }
 }
Example #12
0
 /**
  * POST form, returning contents
  * @param string $url
  * @opt_param string|array $data
  * @opt_param bool $debug
  * @return string $html
  */
 public function post($url, $data = false, $debug = false)
 {
     $ch = curl_init();
     curl_reset($ch);
     curl_setopt($ch, CURLOPT_URL, $url);
     if (preg_match("/^https/", $url)) {
         curl_setopt($ch, CURLOPT_PORT, 443);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     }
     curl_setopt($ch, CURLOPT_HEADER, true);
     curl_setopt($ch, CURLOPT_NOBODY, false);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_POST, false);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
     curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
     $headers = array();
     foreach ($this->headers as $key => $value) {
         $headers[] = $key . ": " . $value;
     }
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     // dEBUGGING ...
     if ($debug) {
         $fh = fopen('postdebug.log', 'a');
         curl_setopt($ch, CURLOPT_VERBOSE, $debug);
         curl_setopt($ch, CURLOPT_STDERR, $fh);
     }
     $response = curl_exec($ch);
     $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
     $header_string = substr($response, 0, $header_size);
     $body = substr($response, $header_size);
     $this->response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     if (curl_errno($ch)) {
         throw new CurlException("Curl error on {$url}: " . curl_error($ch));
     } else {
         return $body;
     }
 }
Example #13
0
 public function downloadCurl($url, $fresh_connect = false)
 {
     if (!function_exists('curl_init')) {
         die('cURL is not installed');
     }
     $ch = curl_init();
     if ($fresh_connect) {
         curl_reset($ch);
         curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
         curl_setopt($ch, CURL_FORBID_REUSE, 1);
     }
     curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_REFERER, "http://www.google.com");
     curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_ENCODING, "UTF-8");
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_TIMEOUT, 10);
     $output = curl_exec($ch);
     curl_close($ch);
     return $output;
 }
Example #14
0
 /**
  * @return void
  */
 public function reset()
 {
     $this->handle && curl_reset($this->handle);
 }
Example #15
0
 /**
  * Reset all options of a libcurl session handle
  *
  * @author Art <*****@*****.**>
  * @return Curl
  * @link   http://php.net/manual/en/function.curl-reset.php
  */
 function reset()
 {
     Log::debug('Reset Curl');
     curl_reset($this->ch);
     curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
     return $this;
 }
Example #16
0
 /**
  * Check PHP version and reset handle option if possible
  * @return boolean
  */
 public function reset()
 {
     if (is_resource($this->handle)) {
         curl_reset($this->handle);
         $this->setDefaults();
         return true;
     }
     return false;
 }
Example #17
0
 private function request()
 {
     $response = curl_exec($this->conn);
     if ($response === false) {
         $response = curl_error($this->conn);
     }
     curl_reset($this->conn);
     return $response;
 }
Example #18
0
 /**
  * Reset the current curl handle.
  *
  * @return $this
  */
 public function resetHandle()
 {
     if (gettype($this->ch) == 'resource' and get_resource_type($this->ch) == 'curl') {
         curl_reset($this->ch);
     }
     $this->postfields = [];
     $this->poststring = '';
     $this->headers = [];
     $this->response = null;
     $this->url = null;
     return $this;
 }
Example #19
0
 /**
  * @param Request $request
  *
  * @throws ConnectionException
  * @throws RequestException
  *
  * @return Response
  */
 public function request(Request $request) : Response
 {
     if (!$this->resource) {
         $this->resource = curl_init();
     }
     // options
     $options = [CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true];
     // gzip, deflate
     if ($this->options[self::OPTIONS_ACCEPT_ENCODING]) {
         if ($this->options[self::OPTIONS_ACCEPT_ENCODING] == true) {
             $options[CURLOPT_ENCODING] = '';
             //force curl to send all Accept-Encoding available
         } else {
             $options[CURLOPT_ENCODING] = $this->options[self::OPTIONS_ACCEPT_ENCODING];
         }
     }
     // ssl
     if (isset($this->options[self::OPTIONS_SSL_VERIFY]) && $this->options[self::OPTIONS_SSL_VERIFY] === false) {
         $options[CURLOPT_SSL_VERIFYHOST] = false;
         $options[CURLOPT_SSL_VERIFYPEER] = false;
     }
     // timeout
     if ($this->options[self::OPTIONS_TIMEOUT]) {
         $options[CURLOPT_TIMEOUT_MS] = $this->options[self::OPTIONS_TIMEOUT];
     }
     if ($this->options[self::OPTIONS_CONNECT_TIMEOUT]) {
         $options[CURLOPT_CONNECTTIMEOUT_MS] = $this->options[self::OPTIONS_CONNECT_TIMEOUT];
     }
     // proxy
     if (!empty($this->options[self::OPTIONS_PROXY])) {
         $options[CURLOPT_PROXY] = $this->options[self::OPTIONS_PROXY];
     }
     // proxy
     if (!empty($this->options[self::OPTIONS_FOLLOW_REDIRECTION])) {
         $options[CURLOPT_FOLLOWLOCATION] = $this->options[self::OPTIONS_FOLLOW_REDIRECTION];
         if (!empty($this->options[self::OPTIONS_MAX_REDIRECTION])) {
             $options[CURLOPT_MAXREDIRS] = $this->options[self::OPTIONS_MAX_REDIRECTION];
         }
     }
     // debug temporary files
     if (!empty($this->options[self::OPTIONS_DEBUG])) {
         $options[CURLOPT_VERBOSE] = true;
         $options[CURLOPT_STDERR] = fopen('php://temp', 'rw');
     }
     // headers handling
     $headers = array_merge($this->defaultHeader, $request->getHeaders());
     // add cookie to current headers
     if ($request->getCookies()) {
         $cookies = [];
         foreach ($request->getCookies() as $name => $cookie) {
             $cookies[] = $name . '=' . urlencode($cookie->getValue());
         }
         $headers['Cookie'] = implode('; ', $cookies);
     }
     if ($headers) {
         $finalHeaders = [];
         foreach ($headers as $name => $value) {
             $finalHeaders[] = $name . ': ' . $value;
         }
         $options[CURLOPT_HTTPHEADER] = $finalHeaders;
     }
     // handle post
     $options[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
     if ($request->getMethod() != 'GET') {
         if ($request->getPayload()) {
             $options[CURLOPT_POSTFIELDS] = $request->getPayload();
         } elseif ($request->getHeader('Content-Type') == 'multipart/form-data') {
             // as an array(): The data will be sent as multipart/form-data
             // which is not always accepted by the serve
             // There are "@" issue on multipart POST requests.
             $options[CURLOPT_SAFE_UPLOAD] = true;
             $options[CURLOPT_POSTFIELDS] = $request->getPosts();
         } else {
             // as url encoded string: The data will be sent as application/x-www-form-urlencoded,
             // which is the default encoding for submitted html form data.
             $options[CURLOPT_POSTFIELDS] = http_build_query($request->getPosts());
         }
     }
     // progress
     if ($this->progress) {
         $options[CURLOPT_NOPROGRESS] = false;
         $options[CURLOPT_PROGRESSFUNCTION] = $this->progress;
         $options[CURLOPT_BUFFERSIZE] = 1024;
     }
     // user & password
     if ($request->getUri()->getUser()) {
         $options[CURLOPT_USERPWD] = $request->getUri()->getUser() . ($request->getUri()->getPassword() ? ':' . $request->getUri()->getPassword() : '');
     }
     // final options
     $options[CURLOPT_URL] = $request->getUri()->get(false);
     curl_reset($this->resource);
     curl_setopt_array($this->resource, $options);
     // send request
     $requestEvent = new TimerEvent($this->options[self::OPTIONS_EVENTS_PREFIX] . '.request');
     $response = curl_exec($this->resource);
     $infos = curl_getinfo($this->resource);
     // request event
     $requestEvent->addData(['method' => $request->getMethod(), 'url' => $request->getUri()->get(false), 'code' => $infos['http_code'], 'header size' => $infos['header_size'], 'request size' => $infos['request_size']]);
     self::emit($requestEvent);
     // generate events for all duration
     $data = ['method' => $request->getMethod(), 'url' => $request->getUri()->get(false), 'code' => $infos['http_code']];
     $event = new ManualTimerEvent($this->options[self::OPTIONS_EVENTS_PREFIX] . '.nameLookup', $data);
     $event->setDuration($infos['namelookup_time'])->setStart($requestEvent->getStart());
     self::emit($event);
     $event = new ManualTimerEvent($this->options[self::OPTIONS_EVENTS_PREFIX] . '.connect', $data);
     $event->setDuration($infos['connect_time'])->setStart($requestEvent->getStart() + $infos['namelookup_time']);
     self::emit($event);
     // debug log
     if (!empty($this->options[self::OPTIONS_DEBUG])) {
         rewind($options[CURLOPT_STDERR]);
         $log = stream_get_contents($options[CURLOPT_STDERR]);
         if (isset($options[CURLOPT_POSTFIELDS]) && is_array($options[CURLOPT_POSTFIELDS])) {
             $log .= json_encode($log) . "\r\n";
         } elseif (isset($options[CURLOPT_POSTFIELDS])) {
             $log .= $options[CURLOPT_POSTFIELDS] . "\r\n";
         }
         if ($response) {
             $log = $log . "\r\n" . htmlentities(explode("\r\n\r\n", $response)[1]);
         }
         self::logger()->debug($log);
     }
     // connection error
     if ($response === false) {
         $code = curl_errno($this->resource);
         $message = curl_error($this->resource);
         throw new ConnectionException($request, $message, $code);
     }
     // final response
     $response = new Response($response);
     if ($response->getStatus() >= 400) {
         throw new RequestException($request, $response, $response->getStatus());
     }
     return $response;
 }
Example #20
0
 /**
  * Reset all options of a libcurl session handle
  */
 public function reset()
 {
     curl_reset($this->_ch);
 }
Example #21
0
 public function reset()
 {
     curl_reset($this->_ch);
     $this->_responseHeaders = [];
     $this->_requestHeaders = [];
     $this->setHttpHeaders([]);
     $this->_data = null;
     return $this;
 }
Example #22
0
 private function releaseEasyHandle($handle)
 {
     $id = (int) $handle;
     if (count($this->ownedHandles) > $this->maxHandles) {
         curl_close($this->handles[$id]);
         unset($this->handles[$id], $this->ownedHandles[$id]);
     } else {
         // curl_reset doesn't clear these out for some reason
         curl_setopt_array($handle, [CURLOPT_HEADERFUNCTION => null, CURLOPT_WRITEFUNCTION => null, CURLOPT_READFUNCTION => null, CURLOPT_PROGRESSFUNCTION => null]);
         curl_reset($handle);
         $this->ownedHandles[$id] = false;
     }
 }
Example #23
0
 /**
  * Contact Google and check that the given authcode is valid to release the endpoint data
  * we have. We do this by getting an email and checking we are happy with the email
  * @param type $authCode
  */
 public static function AuthenticateCode($authCode)
 {
     $post_data = 'code=' . $authCode;
     $post_data .= '&client_id=868600881793-qleonnq3jr662ffhr6vdchetl8vqmjv5.apps.googleusercontent.com';
     $post_data .= '&client_secret=pc9YAOxPDaiSWwcLYR6jetOF';
     $post_data .= '&redirect_uri=urn:ietf:wg:oauth:2.0:oob';
     $post_data .= '&grant_type=authorization_code';
     $ch = curl_init();
     //$f = fopen('c:\request.txt', 'w');
     curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v3/token');
     curl_setopt($ch, CURLOPT_POST, TRUE);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
     //curl_setopt($ch, CURLOPT_STDERR, $f );
     $raw_response = curl_exec($ch);
     Yii::info('Get token raw response: ' . $raw_response, 'luke');
     if ($raw_response == false) {
         return false;
     }
     $response = json_decode($raw_response, true);
     if (array_key_exists("error", $response)) {
         \Yii::error('Get Token error: ' . $response["error"], 'luke');
         return false;
     }
     /* Example response. For this test, we only care about the access_token
        * {
           "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
           "expires_in":3920,
           "token_type":"Bearer",
           "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
         }
        */
     $accessToken = $response['access_token'];
     curl_reset($ch);
     curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' . $accessToken);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
     curl_setopt($ch, CURLOPT_VERBOSE, 1);
     $raw_response = curl_exec($ch);
     \Yii::info('Raw response: ' . $raw_response, 'luke');
     if ($raw_response == false) {
         \Yii::info('Raw response is false', 'luke');
         return false;
     }
     $person = json_decode($raw_response, true);
     if (array_key_exists("error", $person)) {
         \Yii::error('Token info error: ' . $person["error"], 'luke');
         return false;
     }
     //\Yii::info('Person: '.print_r($person),'luke');
     $firstEmail = $person["email"];
     \Yii::info('Email: ' . $firstEmail, 'luke');
     return $firstEmail == "*****@*****.**";
 }
Example #24
0
 /**
  * {@inheritdoc}
  */
 public function sendRequest($url, $method, array $options = array(), $payload = '')
 {
     if (!$this->assertUrl($url)) {
         return $this->invalidArgumentException('Invalid url given: ' . $url);
     }
     if (!$this->assertString($payload)) {
         return $this->invalidArgumentException('Invalid payload given: ' . $payload);
     }
     if (!$this->assertHttpMethod($method)) {
         return $this->invalidArgumentException('Invalid http method given: ' . $method);
     }
     $this->curlOptionsHandler->setOptions($options);
     $this->curlOptionsHandler->setOption(CURLOPT_RETURNTRANSFER, true);
     $this->setUrl($url);
     $this->setMethod($method);
     $this->setPayload($payload);
     curl_setopt_array($this->curl, $this->curlOptionsHandler->getOptions());
     $curlResponse = $this->execute();
     $curlMetaData = (object) curl_getinfo($this->curl);
     $this->curlOptionsHandler->reset();
     function_exists('curl_reset') ? curl_reset($this->curl) : curl_setopt_array($this->curl, $this->curlOptionsHandler->getOptions());
     return $this->createResponse($curlResponse, $curlMetaData);
 }
Example #25
0
 /**
  * Reset a cURL session.
  *
  * @link http://www.php.net/manual/en/function.curl-reset.php
  * @param resource $curlHandle A cURL handle returned by curl_init().
  */
 public static function curlReset($curlHandle)
 {
     \curl_reset($curlHandle);
     self::$requests[(int) $curlHandle] = new Request('GET', null);
     self::$curlOptions[(int) $curlHandle] = array();
 }
Example #26
0
 /**
  * Perform an http call. This method is used by the resource specific classes. Please use the $payments property to
  * perform operations on payments.
  *
  * @see $payments
  * @see $isuers
  *
  * @param $http_method
  * @param $api_method
  * @param $http_body
  *
  * @return string
  * @throws Mollie_API_Exception
  *
  * @codeCoverageIgnore
  */
 public function performHttpCall($http_method, $api_method, $http_body = NULL)
 {
     if (empty($this->api_key)) {
         throw new Mollie_API_Exception("You have not set an API key or OAuth access token. Please use setApiKey() to set the API key.");
     }
     if (empty($this->ch) || !function_exists("curl_reset")) {
         /*
          * Initialize a cURL handle.
          */
         $this->ch = curl_init();
     } else {
         /*
          * Reset the earlier used cURL handle.
          */
         curl_reset($this->ch);
     }
     $url = $this->api_endpoint . "/" . self::API_VERSION . "/" . $api_method;
     curl_setopt($this->ch, CURLOPT_URL, $url);
     curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($this->ch, CURLOPT_TIMEOUT, 10);
     curl_setopt($this->ch, CURLOPT_ENCODING, "");
     $user_agent = join(' ', $this->version_strings);
     if ($this->usesOAuth()) {
         $user_agent .= " OAuth/2.0";
     }
     $request_headers = array("Accept: application/json", "Authorization: Bearer {$this->api_key}", "User-Agent: {$user_agent}", "X-Mollie-Client-Info: " . php_uname(), "Expect:");
     curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $http_method);
     if ($http_body !== NULL) {
         $request_headers[] = "Content-Type: application/json";
         curl_setopt($this->ch, CURLOPT_POST, 1);
         curl_setopt($this->ch, CURLOPT_POSTFIELDS, $http_body);
     }
     curl_setopt($this->ch, CURLOPT_HTTPHEADER, $request_headers);
     curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 2);
     curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, TRUE);
     /*
      * On some servers, the list of installed certificates is outdated or not present at all (the ca-bundle.crt
      * is not installed). So we tell cURL which certificates we trust.
      */
     curl_setopt($this->ch, CURLOPT_CAINFO, $this->pem_path);
     $body = curl_exec($this->ch);
     if (strpos(curl_error($this->ch), "certificate subject name 'mollie.nl' does not match target host") !== FALSE) {
         /*
          * On some servers, the wildcard SSL certificate is not processed correctly. This happens with OpenSSL 0.9.7
          * from 2003.
          */
         $request_headers[] = "X-Mollie-Debug: old OpenSSL found";
         curl_setopt($this->ch, CURLOPT_HTTPHEADER, $request_headers);
         curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0);
         $body = curl_exec($this->ch);
     }
     $this->last_http_response_status_code = (int) curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
     if (curl_errno($this->ch)) {
         $message = "Unable to communicate with Mollie (" . curl_errno($this->ch) . "): " . curl_error($this->ch) . ".";
         curl_close($this->ch);
         $this->ch = NULL;
         throw new Mollie_API_Exception($message);
     }
     if (!function_exists("curl_reset")) {
         /*
          * Keep it open if supported by PHP, else close the handle.
          */
         curl_close($this->ch);
         $this->ch = NULL;
     }
     return $body;
 }
 /**
  * Utility function used to create the curl object with common settings
  */
 private function create_curl($s_url, $request_method = 'GET', $query_params = array())
 {
     # Create the signed signature...
     $signed_query = Pusher::build_auth_query_string($this->settings['auth_key'], $this->settings['secret'], $request_method, $s_url, $query_params);
     $full_url = $this->settings['scheme'] . '://' . $this->settings['host'] . ':' . $this->settings['port'] . $s_url . '?' . $signed_query;
     $this->log('curl_init( ' . $full_url . ' )');
     // Create or reuse existing curl handle
     static $ch;
     if (null === $ch) {
         $ch = curl_init();
     }
     if ($ch === false) {
         throw new PusherException('Could not initialise cURL!');
     }
     // curl handle is not reusable unless reset
     if (function_exists('curl_reset')) {
         curl_reset($ch);
     }
     # Set cURL opts and execute request
     curl_setopt($ch, CURLOPT_URL, $full_url);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Expect:"));
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_TIMEOUT, $this->settings['timeout']);
     return $ch;
 }
Example #28
0
 public function resetConnection()
 {
     $this->command = null;
     $this->options = [];
     $this->path = '';
     $this->query = '';
     $this->requestBody = '';
     $this->responseHeaders = [];
     $this->responseBody = '';
     if (version_compare(PHP_VERSION, '5.5.0') >= 0) {
         curl_reset($this->connection);
     } else {
         curl_close($this->connection);
         $this->connection = null;
     }
 }
Example #29
0
 /**
  * send http request
  * @param  array $rq http请求信息
  *                   url        : 请求的url地址
  *                   method     : 请求方法,'get', 'post', 'put', 'delete', 'head'
  *                   data       : 请求数据,如有设置,则method为post
  *                   header     : 需要设置的http头部
  *                   host       : 请求头部host
  *                   timeout    : 请求超时时间
  *                   cert       : ca文件路径
  *                   ssl_version: SSL版本号
  * @return string    http请求响应
  */
 public static function send($rq)
 {
     if (self::$_curlHandler) {
         if (function_exists('curl_reset')) {
             curl_reset(self::$_curlHandler);
         } else {
             my_curl_reset(self::$_curlHandler);
         }
     } else {
         self::$_curlHandler = curl_init();
     }
     curl_setopt(self::$_curlHandler, CURLOPT_URL, $rq['url']);
     switch (true) {
         case isset($rq['method']) && in_array(strtolower($rq['method']), array('get', 'post', 'put', 'delete', 'head')):
             $method = strtoupper($rq['method']);
             break;
         case isset($rq['data']):
             $method = 'POST';
             break;
         default:
             $method = 'GET';
     }
     $header = isset($rq['header']) ? $rq['header'] : array();
     $header[] = 'Method:' . $method;
     $header[] = 'User-Agent:' . Conf::getUA();
     $header[] = 'Connection: keep-alive';
     if ('POST' == $method) {
         $header[] = 'Expect: ';
     }
     isset($rq['host']) && ($header[] = 'Host:' . $rq['host']);
     curl_setopt(self::$_curlHandler, CURLOPT_HTTPHEADER, $header);
     curl_setopt(self::$_curlHandler, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt(self::$_curlHandler, CURLOPT_CUSTOMREQUEST, $method);
     isset($rq['timeout']) && curl_setopt(self::$_curlHandler, CURLOPT_TIMEOUT, $rq['timeout']);
     isset($rq['data']) && in_array($method, array('POST', 'PUT')) && curl_setopt(self::$_curlHandler, CURLOPT_POSTFIELDS, $rq['data']);
     $ssl = substr($rq['url'], 0, 8) == "https://" ? true : false;
     if (isset($rq['cert'])) {
         curl_setopt(self::$_curlHandler, CURLOPT_SSL_VERIFYPEER, true);
         curl_setopt(self::$_curlHandler, CURLOPT_CAINFO, $rq['cert']);
         curl_setopt(self::$_curlHandler, CURLOPT_SSL_VERIFYHOST, 2);
         if (isset($rq['ssl_version'])) {
             curl_setopt(self::$_curlHandler, CURLOPT_SSLVERSION, $rq['ssl_version']);
         } else {
             curl_setopt(self::$_curlHandler, CURLOPT_SSLVERSION, 4);
         }
     } else {
         if ($ssl) {
             curl_setopt(self::$_curlHandler, CURLOPT_SSL_VERIFYPEER, false);
             //true any ca
             curl_setopt(self::$_curlHandler, CURLOPT_SSL_VERIFYHOST, 1);
             //check only host
             if (isset($rq['ssl_version'])) {
                 curl_setopt(self::$_curlHandler, CURLOPT_SSLVERSION, $rq['ssl_version']);
             } else {
                 curl_setopt(self::$_curlHandler, CURLOPT_SSLVERSION, 4);
             }
         }
     }
     $ret = curl_exec(self::$_curlHandler);
     self::$_httpInfo = curl_getinfo(self::$_curlHandler);
     //curl_close(self::$_curlHandler);
     return $ret;
 }
Example #30
0
 /**
  * Perform an http call. This method is used by the resource specific classes. Please use the $payments property to
  * perform operations on payments.
  *
  * @see $payments
  * @see $isuers
  *
  * @param $http_method
  * @param $api_method
  * @param $http_body
  *
  * @return string
  * @throws Mollie_API_Exception
  *
  * @codeCoverageIgnore
  */
 public function performHttpCall($http_method, $api_method, $http_body = NULL)
 {
     if (empty($this->api_key)) {
         throw new Mollie_API_Exception("You have not set an API key. Please use setApiKey() to set the API key.");
     }
     if (empty($this->ch) || !function_exists("curl_reset")) {
         /*
          * Initialize a cURL handle.
          */
         $this->ch = curl_init();
     } else {
         /*
          * Reset the earlier used cURL handle.
          */
         curl_reset($this->ch);
     }
     $url = $this->api_endpoint . "/" . self::API_VERSION . "/" . $api_method;
     curl_setopt($this->ch, CURLOPT_URL, $url);
     curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($this->ch, CURLOPT_ENCODING, "");
     curl_setopt($this->ch, CURLOPT_TIMEOUT, 10);
     $user_agent = join(' ', $this->version_strings);
     $request_headers = array("Accept: application/json", "Authorization: Bearer {$this->api_key}", "User-Agent: {$user_agent}", "X-Mollie-Client-Info: " . php_uname());
     curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $http_method);
     if ($http_body !== NULL) {
         $request_headers[] = "Content-Type: application/json";
         curl_setopt($this->ch, CURLOPT_POST, 1);
         curl_setopt($this->ch, CURLOPT_POSTFIELDS, $http_body);
     }
     curl_setopt($this->ch, CURLOPT_HTTPHEADER, $request_headers);
     curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 2);
     curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, TRUE);
     /*
      * On some servers, the list of installed certificates is outdated or not present at all (the ca-bundle.crt
      * is not installed). So we tell cURL which certificates we trust.
      */
     curl_setopt($this->ch, CURLOPT_CAINFO, realpath(dirname(__FILE__) . "/cacert.pem"));
     $body = curl_exec($this->ch);
     if (curl_errno($this->ch) == CURLE_SSL_CACERT || curl_errno($this->ch) == CURLE_SSL_PEER_CERTIFICATE || curl_errno($this->ch) == 77) {
         if (strpos(curl_error($this->ch), "error setting certificate verify locations") !== FALSE) {
             /*
              * Error setting CA-file. Could be missing, or there is a bug in OpenSSL with too long paths.
              * We give up. Don't do any peer validations.
              *
              * @internal #MOL017891004
              */
             array_shift($request_headers);
             $request_headers[] = "X-Mollie-Debug: unable to use shipped root certificaties, no peer validation.";
             curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE);
             $body = curl_exec($this->ch);
         }
     }
     if (strpos(curl_error($this->ch), "certificate subject name 'mollie.nl' does not match target host") !== FALSE) {
         /*
          * On some servers, the wildcard SSL certificate is not processed correctly. This happens with OpenSSL 0.9.7
          * from 2003.
          */
         $request_headers[] = "X-Mollie-Debug: old OpenSSL found";
         curl_setopt($this->ch, CURLOPT_HTTPHEADER, $request_headers);
         curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0);
         $body = curl_exec($this->ch);
     }
     if (curl_errno($this->ch)) {
         $message = "Unable to communicate with Mollie (" . curl_errno($this->ch) . "): " . curl_error($this->ch) . ".";
         curl_close($this->ch);
         $this->ch = NULL;
         throw new Mollie_API_Exception($message);
     }
     if (!function_exists("curl_reset")) {
         /*
          * Keep it open if supported by PHP, else close the handle.
          */
         curl_close($this->ch);
         $this->ch = NULL;
     }
     return $body;
 }