From 9bf2f103e20957164b936715101141712887d214 Mon Sep 17 00:00:00 2001 From: Nikolai Plath Date: Tue, 12 Jun 2012 12:36:34 -0500 Subject: [PATCH] Add a tiny cURL helper (@todo use the J! one) --- .../com_patchtester/helpers/curl.php | 195 ++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 administrator/components/com_patchtester/helpers/curl.php diff --git a/administrator/components/com_patchtester/helpers/curl.php b/administrator/components/com_patchtester/helpers/curl.php new file mode 100644 index 0000000..83a6a0b --- /dev/null +++ b/administrator/components/com_patchtester/helpers/curl.php @@ -0,0 +1,195 @@ +curlOptions = (array)$options; + + return $this; + } + + /** + * Read URL contents. + * + * @throws Exception + * + * @return object The cURL response. + */ + public function fetch() + { + $ch = curl_init(); + + curl_setopt_array($ch, $this->curlOptions); + + curl_setopt($ch, CURLOPT_URL, $this->_uri); + + if ( ! array_key_exists(CURLOPT_SSL_VERIFYHOST, $this->curlOptions)) + { + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); + } + + if ( ! array_key_exists(CURLOPT_SSL_VERIFYPEER, $this->curlOptions)) + { + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + } + + if ( ! array_key_exists(CURLOPT_FOLLOWLOCATION, $this->curlOptions)) + { + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + } + + if ( ! array_key_exists(CURLOPT_MAXREDIRS, $this->curlOptions)) + { + curl_setopt($ch, CURLOPT_MAXREDIRS, 10); + } + + if ( ! array_key_exists(CURLOPT_TIMEOUT, $this->curlOptions)) + { + curl_setopt($ch, CURLOPT_TIMEOUT, 120); + } + + if ( ! array_key_exists(CURLOPT_RETURNTRANSFER, $this->curlOptions)) + { + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + } + + if ($this->target) + { + // Write the response to a file + $fp = fopen($this->target, 'w'); + + if ( ! $fp) + { + throw new Exception('Can not open target file at: '.$this->target); + } + + // Use CURLOPT_FILE to speed things up + curl_setopt($ch, CURLOPT_FILE, $fp); + } + else + { + // Return the response + if ( ! array_key_exists(CURLOPT_RETURNTRANSFER, $this->curlOptions)) + { + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + } + } + + $response = curl_exec($ch); + + if (curl_errno($ch)) + { + throw new Exception('Curl Error: '.curl_error($ch)); + } + + $info = curl_getinfo($ch); + + if (isset($info['http_code']) && $info['http_code'] != 200) + { + $response = false; + } + + curl_close($ch); + + $return = JArrayHelper::toObject($info); + $return->body = $response; + + return $return; + } + + /** + * Save the response to a file. + * + * @param string $target Target path + * + * @return boolean true on success + * + * @throws Exception + */ + public function saveToFile($target) + { + $this->target = $target; + + $response = $this->fetch(); + + if (false === $response) + { + throw new Exception('File cannot be downloaded'); + } + + return true; + } +}