PageRenderTime 48ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

/system/cms/libraries/Curl.php

https://github.com/JamieLomas/pyrocms
PHP | 356 lines | 244 code | 64 blank | 48 comment | 24 complexity | 713259bb459ac396ac810f83e24c3e10 MD5 | raw file
  1. <?php defined('BASEPATH') OR exit('No direct script access allowed');
  2. /**
  3. * CodeIgniter Curl Class
  4. *
  5. * Work with remote servers via cURL much easier than using the native PHP bindings.
  6. *
  7. * @package CodeIgniter
  8. * @subpackage Libraries
  9. * @category Libraries
  10. * @author Philip Sturgeon
  11. * @license http://philsturgeon.co.uk/code/dbad-license
  12. * @link http://philsturgeon.co.uk/code/codeigniter-curl
  13. */
  14. class Curl {
  15. private $_ci; // CodeIgniter instance
  16. private $response; // Contains the cURL response for debug
  17. private $session; // Contains the cURL handler for a session
  18. private $url; // URL of the session
  19. private $options = array(); // Populates curl_setopt_array
  20. private $headers = array(); // Populates extra HTTP headers
  21. public $error_code; // Error code returned as an int
  22. public $error_string; // Error message returned as a string
  23. public $info; // Returned after request (elapsed time, etc)
  24. function __construct($url = '')
  25. {
  26. $this->_ci = & get_instance();
  27. log_message('debug', 'cURL Class Initialized');
  28. if (!$this->is_enabled())
  29. {
  30. log_message('error', 'cURL Class - PHP was not built with cURL enabled. Rebuild PHP with --with-curl to use cURL.');
  31. }
  32. $url AND $this->create($url);
  33. }
  34. function __call($method, $arguments)
  35. {
  36. if (in_array($method, array('simple_get', 'simple_post', 'simple_put', 'simple_delete')))
  37. {
  38. // Take off the "simple_" and past get/post/put/delete to _simple_call
  39. $verb = str_replace('simple_', '', $method);
  40. array_unshift($arguments, $verb);
  41. return call_user_func_array(array($this, '_simple_call'), $arguments);
  42. }
  43. }
  44. /* =================================================================================
  45. * SIMPLE METHODS
  46. * Using these methods you can make a quick and easy cURL call with one line.
  47. * ================================================================================= */
  48. // Return a get request results
  49. public function _simple_call($method, $url, $params = array(), $options = array())
  50. {
  51. // If a URL is provided, create new session
  52. $this->create($url);
  53. $this->{$method}($params, $options);
  54. // Add in the specific options provided
  55. $this->options($options);
  56. return $this->execute();
  57. }
  58. public function simple_ftp_get($url, $file_path, $username = '', $password = '')
  59. {
  60. // If there is no ftp:// or any protocol entered, add ftp://
  61. if (!preg_match('!^(ftp|sftp)://! i', $url))
  62. {
  63. $url = 'ftp://' . $url;
  64. }
  65. // Use an FTP login
  66. if ($username != '')
  67. {
  68. $auth_string = $username;
  69. if ($password != '')
  70. {
  71. $auth_string .= ':' . $password;
  72. }
  73. // Add the user auth string after the protocol
  74. $url = str_replace('://', '://' . $auth_string . '@', $url);
  75. }
  76. // Add the filepath
  77. $url .= $file_path;
  78. $this->option(CURLOPT_BINARYTRANSFER, TRUE);
  79. $this->option(CURLOPT_VERBOSE, TRUE);
  80. return $this->execute();
  81. }
  82. /* =================================================================================
  83. * ADVANCED METHODS
  84. * Use these methods to build up more complex queries
  85. * ================================================================================= */
  86. public function post($params = array(), $options = array())
  87. {
  88. // If its an array (instead of a query string) then format it correctly
  89. if (is_array($params))
  90. {
  91. $params = http_build_query($params, NULL, '&');
  92. }
  93. // Add in the specific options provided
  94. $this->options($options);
  95. $this->http_method('post');
  96. $this->option(CURLOPT_POST, TRUE);
  97. $this->option(CURLOPT_POSTFIELDS, $params);
  98. }
  99. public function put($params = array(), $options = array())
  100. {
  101. // If its an array (instead of a query string) then format it correctly
  102. if (is_array($params))
  103. {
  104. $params = http_build_query($params, NULL, '&');
  105. }
  106. // Add in the specific options provided
  107. $this->options($options);
  108. $this->http_method('put');
  109. $this->option(CURLOPT_POSTFIELDS, $params);
  110. // Override method, I think this overrides $_POST with PUT data but... we'll see eh?
  111. $this->option(CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
  112. }
  113. public function delete($params, $options = array())
  114. {
  115. // If its an array (instead of a query string) then format it correctly
  116. if (is_array($params))
  117. {
  118. $params = http_build_query($params, NULL, '&');
  119. }
  120. // Add in the specific options provided
  121. $this->options($options);
  122. $this->http_method('delete');
  123. $this->option(CURLOPT_POSTFIELDS, $params);
  124. }
  125. public function set_cookies($params = array())
  126. {
  127. if (is_array($params))
  128. {
  129. $params = http_build_query($params, NULL, '&');
  130. }
  131. $this->option(CURLOPT_COOKIE, $params);
  132. return $this;
  133. }
  134. public function http_header($header, $content = NULL)
  135. {
  136. $this->headers[] = $content ? $header . ': ' . $content : $header;
  137. }
  138. public function http_method($method)
  139. {
  140. $this->options[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
  141. return $this;
  142. }
  143. public function http_login($username = '', $password = '', $type = 'any')
  144. {
  145. $this->option(CURLOPT_HTTPAUTH, constant('CURLAUTH_' . strtoupper($type)));
  146. $this->option(CURLOPT_USERPWD, $username . ':' . $password);
  147. return $this;
  148. }
  149. public function proxy($url = '', $port = 80)
  150. {
  151. $this->option(CURLOPT_HTTPPROXYTUNNEL, TRUE);
  152. $this->option(CURLOPT_PROXY, $url . ':' . $port);
  153. return $this;
  154. }
  155. public function proxy_login($username = '', $password = '')
  156. {
  157. $this->option(CURLOPT_PROXYUSERPWD, $username . ':' . $password);
  158. return $this;
  159. }
  160. public function ssl($verify_peer = TRUE, $verify_host = 2, $path_to_cert = NULL)
  161. {
  162. if ($verify_peer)
  163. {
  164. $this->option(CURLOPT_SSL_VERIFYPEER, TRUE);
  165. $this->option(CURLOPT_SSL_VERIFYHOST, $verify_host);
  166. $this->option(CURLOPT_CAINFO, $path_to_cert);
  167. }
  168. else
  169. {
  170. $this->option(CURLOPT_SSL_VERIFYPEER, FALSE);
  171. }
  172. return $this;
  173. }
  174. public function options($options = array())
  175. {
  176. // Merge options in with the rest - done as array_merge() does not overwrite numeric keys
  177. foreach ($options as $option_code => $option_value)
  178. {
  179. $this->option($option_code, $option_value);
  180. }
  181. // Set all options provided
  182. curl_setopt_array($this->session, $this->options);
  183. return $this;
  184. }
  185. public function option($code, $value)
  186. {
  187. if (is_string($code) && !is_numeric($code))
  188. {
  189. $code = constant('CURLOPT_' . strtoupper($code));
  190. }
  191. $this->options[$code] = $value;
  192. return $this;
  193. }
  194. // Start a session from a URL
  195. public function create($url)
  196. {
  197. // Reset the class
  198. $this->set_defaults();
  199. // If no a protocol in URL, assume its a CI link
  200. if (!preg_match('!^\w+://! i', $url))
  201. {
  202. $this->_ci->load->helper('url');
  203. $url = site_url($url);
  204. }
  205. $this->url = $url;
  206. $this->session = curl_init($this->url);
  207. return $this;
  208. }
  209. // End a session and return the results
  210. public function execute()
  211. {
  212. // Set two default options, and merge any extra ones in
  213. if (!isset($this->options[CURLOPT_TIMEOUT]))
  214. $this->options[CURLOPT_TIMEOUT] = 30;
  215. if (!isset($this->options[CURLOPT_RETURNTRANSFER]))
  216. $this->options[CURLOPT_RETURNTRANSFER] = TRUE;
  217. if (!isset($this->options[CURLOPT_FAILONERROR]))
  218. $this->options[CURLOPT_FAILONERROR] = TRUE;
  219. // Only set follow location if not running securely
  220. if (!ini_get('safe_mode') && !ini_get('open_basedir'))
  221. {
  222. // Ok, follow location is not set already so lets set it to true
  223. if (!isset($this->options[CURLOPT_FOLLOWLOCATION]))
  224. {
  225. $this->options[CURLOPT_FOLLOWLOCATION] = TRUE;
  226. }
  227. }
  228. if (!empty($this->headers))
  229. {
  230. $this->option(CURLOPT_HTTPHEADER, $this->headers);
  231. }
  232. $this->options();
  233. // Execute the request & and hide all output
  234. $this->response = curl_exec($this->session);
  235. $this->info = curl_getinfo($this->session);
  236. // Request failed
  237. if ($this->response === FALSE)
  238. {
  239. $this->error_code = curl_errno($this->session);
  240. $this->error_string = curl_error($this->session);
  241. curl_close($this->session);
  242. $this->session = NULL;
  243. return FALSE;
  244. }
  245. // Request successful
  246. else
  247. {
  248. curl_close($this->session);
  249. $this->session = NULL;
  250. return $this->response;
  251. }
  252. }
  253. public function is_enabled()
  254. {
  255. return function_exists('curl_init');
  256. }
  257. public function debug()
  258. {
  259. echo "=============================================<br/>\n";
  260. echo "<h2>CURL Test</h2>\n";
  261. echo "=============================================<br/>\n";
  262. echo "<h3>Response</h3>\n";
  263. echo "<code>" . nl2br(htmlentities($this->response)) . "</code><br/>\n\n";
  264. if ($this->error_string)
  265. {
  266. echo "=============================================<br/>\n";
  267. echo "<h3>Errors</h3>";
  268. echo "<strong>Code:</strong> " . $this->error_code . "<br/>\n";
  269. echo "<strong>Message:</strong> " . $this->error_string . "<br/>\n";
  270. }
  271. echo "=============================================<br/>\n";
  272. echo "<h3>Info</h3>";
  273. echo "<pre>";
  274. print_r($this->info);
  275. echo "</pre>";
  276. }
  277. public function debug_request()
  278. {
  279. return array(
  280. 'url' => $this->url
  281. );
  282. }
  283. private function set_defaults()
  284. {
  285. $this->response = '';
  286. $this->info = array();
  287. $this->options = array();
  288. $this->error_code = 0;
  289. $this->error_string = '';
  290. }
  291. }
  292. /* End of file Curl.php */