Class-CurlFetchWeb.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2012 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.1 Alpha 1
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. /**
  15. * Simple cURL class to fetch a web page
  16. * Properly redirects even with safe mode and basedir restrictions
  17. * Can provide simple post options to a page
  18. *
  19. * Load class
  20. * Initiate as
  21. * - $fetch_data = new cURL_fetch_web_data();
  22. * - optionaly pass an array of cURL options and redirect count
  23. * - cURL_fetch_web_data(cURL options array, Max redirects);
  24. * - $fetch_data = new cURL_fetch_web_data(array(CURLOPT_SSL_VERIFYPEER => 1), 5);
  25. *
  26. * Make the call
  27. * - $fetch_data('http://www.simplemachines.org'); // fetch a page
  28. * - $fetch_data('http://www.simplemachines.org', array('user' => 'name', 'password' => 'password')); // post to a page
  29. * - $fetch_data('http://www.simplemachines.org', parameter1&parameter2&parameter3); // post to a page
  30. *
  31. * Get the data
  32. * - $fetch_data->result('body'); // just the page content
  33. * - $fetch_data->result(); // an array of results, body, header, http result codes
  34. * - $fetch_data->result_raw(); // show all results of all calls (in the event of a redirect)
  35. * - $fetch_data->result_raw(0); // show all results of call x
  36. *
  37. * @package SMF
  38. * @author Simple Machines http://www.simplemachines.org
  39. * @copyright 2012 Simple Machines
  40. * @license http://www.simplemachines.org/about/smf/license.php BSD
  41. *
  42. * @version 2.1 Alpha 1
  43. */
  44. if (!defined('SMF'))
  45. die('Hacking attempt...');
  46. class curl_fetch_web_data
  47. {
  48. private $default_options = array(
  49. CURLOPT_RETURNTRANSFER => 1, // Get returned value as a string (don't output it)
  50. CURLOPT_HEADER => 1, // We need the headers to do our own redirect
  51. CURLOPT_FOLLOWLOCATION => 0, // Don't follow, we will do it ourselves so safe mode and open_basedir will dig it
  52. CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko Firefox/11.0', // set a normal looking useragent
  53. CURLOPT_CONNECTTIMEOUT => 15, // Don't wait forever on a connection
  54. CURLOPT_TIMEOUT => 90, // A page should load in this amount of time
  55. CURLOPT_MAXREDIRS => 5, // stop after this many redirects
  56. CURLOPT_ENCODING => 'gzip,deflate', // accept gzip and decode it
  57. CURLOPT_SSL_VERIFYPEER => 0, // stop cURL from verifying the peer's certificate
  58. CURLOPT_SSL_VERIFYHOST => 0, // stop cURL from verifying the peer's host
  59. CURLOPT_POST => 0, // no post data unless its passed
  60. );
  61. /**
  62. * Start the curl object
  63. * - allow for user override values
  64. *
  65. * @param type $options, cURL options as an array
  66. * @param type $max_redirect, use to overide the default of 3
  67. */
  68. public function __construct($options = array(), $max_redirect = 3)
  69. {
  70. // Initialize class variables
  71. $this->max_redirect = intval($max_redirect);
  72. $this->user_options = $options;
  73. }
  74. /**
  75. * Main calling function,
  76. * - will request the page data from a given $url
  77. * - optionally will post data to the page form if post data is supplied
  78. * - passed arrays will be converted to a post string joined with &'s
  79. * - calls set_options to set the curl opts array values based on the defaults and user input
  80. *
  81. * @param type $url, the site we are going to fetch
  82. * @param type $post_data, any post data as form name => value
  83. */
  84. public function get_url_data($url, $post_data = array())
  85. {
  86. // POSTing some data perhaps?
  87. if (!empty($post_data) && is_array($post_data))
  88. $this->post_data = $this->build_post_data($post_data);
  89. elseif (!empty($post_data))
  90. $this->post_data = trim($post_data);
  91. // set the options and get it
  92. $this->set_options();
  93. $this->curl_request(str_replace(' ', '%20', $url));
  94. return $this;
  95. }
  96. /**
  97. * Makes the actual cURL call
  98. * - stores responses (url, code, error, headers, body) in the response array
  99. * - detects 301, 302, 307 codes and will redirect to the given response header location
  100. *
  101. * @param type $url, site to fetch
  102. * @param type $redirect, flag to indicate if this was a redirect request or not
  103. * @return boolean
  104. */
  105. private function curl_request($url, $redirect = false)
  106. {
  107. // we do have a url I hope
  108. if ($url == '')
  109. return false;
  110. else
  111. $this->options[CURLOPT_URL] = $url;
  112. // if we have not already been redirected, set it up so we can if needed
  113. if (!$redirect)
  114. {
  115. $this->current_redirect = 1;
  116. $this->response = array();
  117. }
  118. // Initialize the curl object and make the call
  119. $cr = curl_init();
  120. curl_setopt_array($cr, $this->options);
  121. curl_exec($cr);
  122. // Get what was returned
  123. $curl_info = curl_getinfo($cr);
  124. $curl_content = curl_multi_getcontent($cr);
  125. $url = $curl_info['url']; // Last effective URL
  126. $http_code = $curl_info['http_code']; // Last HTTP code
  127. $body = (!curl_error($cr)) ? substr($curl_content, $curl_info['header_size']) : false;
  128. $error = (curl_error($cr)) ? curl_error($cr) : false;
  129. // close this request
  130. curl_close($cr);
  131. // store this 'loops' data, someone may want all of these :O
  132. $this->response[] = array(
  133. 'url' => $url,
  134. 'code' => $http_code,
  135. 'error' => $error,
  136. 'headers' => isset($this->headers) ? $this->headers : false,
  137. 'body' => $body,
  138. );
  139. // If this a redirect with a location header and we have not given up, then do it again
  140. if (preg_match('~30[127]~i', $http_code) === 1 && $this->headers['location'] != '' && $this->current_redirect <= $this->max_redirect)
  141. {
  142. $this->current_redirect++;
  143. $header_location = $this->get_redirect_url($url, $this->headers['location']);
  144. $this->redirect($header_location, $url);
  145. }
  146. }
  147. /**
  148. * Used if being redirected to ensure we have a fully qualified address
  149. *
  150. * @param type $last_url, where we went to
  151. * @param type $new_url, where we were redirected to
  152. * @return new url location
  153. */
  154. private function get_redirect_url($last_url = '', $new_url = '')
  155. {
  156. // Get the elements for these urls
  157. $last_url_parse = parse_url($last_url);
  158. $new_url_parse = parse_url($new_url);
  159. // redirect headers are often incomplete or relative so we need to make sure they are fully qualified
  160. $new_url_parse['scheme'] = isset($new_url_parse['scheme']) ? $new_url_parse['scheme'] : $last_url_parse['scheme'];
  161. $new_url_parse['host'] = isset($new_url_parse['host']) ? $new_url_parse['host'] : $last_url_parse['host'];
  162. $new_url_parse['path'] = isset($new_url_parse['path']) ? $new_url_parse['path'] : $last_url_parse['path'];
  163. $new_url_parse['query'] = isset($new_url_parse['query']) ? $new_url_parse['query'] : '';
  164. // Build the new URL that was in the http header
  165. return $new_url_parse['scheme'] . '://' . $new_url_parse['host'] . $new_url_parse['path'] . (!empty($new_url_parse['query']) ? '?' . $new_url_parse['query'] : '');
  166. }
  167. /**
  168. * Used to return the results to the calling program
  169. * - called as ->result() will return the full final array
  170. * - called as ->result('body') to just return the page source of the result
  171. *
  172. * @param type $area, used to return an area such as body, header, error
  173. * @return type
  174. */
  175. public function result($area = '')
  176. {
  177. $max_result = count($this->response) - 1;
  178. // just return a specifed area or the entire result?
  179. if ($area == '')
  180. return $this->response[$max_result];
  181. else
  182. return isset($this->response[$max_result][$area]) ? $this->response[$max_result][$area] : $this->response[$max_result];
  183. }
  184. /**
  185. * Will return all results from all loops (redirects)
  186. * - Can be called as ->result_raw(x) where x is a specific loop results.
  187. * - Call as ->result_raw() for everything.
  188. *
  189. * @param type $response_number
  190. * @return type
  191. */
  192. public function result_raw($response_number = '')
  193. {
  194. if (!is_numeric($response_number))
  195. return $this->response;
  196. else
  197. {
  198. $response_number = min($response_number, count($this->response) - 1);
  199. return $this->response[$response_number];
  200. }
  201. }
  202. /**
  203. * Takes supplied POST data and url encodes it
  204. * - forms the date (for post) in to a string var=xyz&var2=abc&var3=123
  205. * - drops vars with @ since we don't support sending files (uploading)
  206. *
  207. * @param type $post_data
  208. * @return type
  209. */
  210. private function build_post_data($post_data)
  211. {
  212. if (is_array($post_data))
  213. {
  214. $postvars = array();
  215. // build the post data, drop ones with leading @'s since those can be used to send files, we don't support that.
  216. foreach ($post_data as $name => $value)
  217. $postvars[] = $name . '=' . urlencode($value[0] == '@' ? '' : $value);
  218. return implode('&', $postvars);
  219. }
  220. else
  221. return $post_data;
  222. }
  223. /**
  224. * Sets the final cURL options for the current call
  225. * - overwrites our default values with user supplied ones or appends new user ones to what we have
  226. * - sets the callback function now that $this is existing
  227. *
  228. */
  229. private function set_options()
  230. {
  231. // Callback to parse the returned headers, if any
  232. $this->default_options[CURLOPT_HEADERFUNCTION] = array($this, 'header_callback');
  233. // Any user options to account for
  234. if (is_array($this->user_options))
  235. {
  236. $keys = array_merge(array_keys($this->default_options), array_keys($this->user_options));
  237. $vals = array_merge($this->default_options, $this->user_options);
  238. $this->options = array_combine($keys, $vals);
  239. }
  240. else
  241. $this->options = $this->default_options;
  242. // POST data options, here we don't allow any overide
  243. if (isset($this->post_data))
  244. {
  245. $this->options[CURLOPT_POST] = 1;
  246. $this->options[CURLOPT_POSTFIELDS] = $this->post_data;
  247. }
  248. }
  249. /**
  250. * Called to initiate a redirect from a 301, 302 or 307 header
  251. * - resets the cURL options for the loop, sets the referrer flag
  252. *
  253. * @param type $target_url
  254. * @param type $referer_url
  255. */
  256. private function redirect($target_url, $referer_url)
  257. {
  258. // no no I last saw that over there ... really, 301, 302, 307
  259. $this->set_options();
  260. $this->options[CURLOPT_REFERER] = $referer_url;
  261. $this->curl_request($target_url, true);
  262. }
  263. /**
  264. * Callback function to parse returned headers
  265. * - lowercases everything to make it consistent
  266. *
  267. * @param type $cr
  268. * @param type $header
  269. * @return type
  270. */
  271. private function header_callback($cr, $header)
  272. {
  273. $_header = trim($header);
  274. $temp = explode(': ', $_header, 2);
  275. // set proper headers only
  276. if (isset($temp[0]) && isset($temp[1]))
  277. $this->headers[strtolower($temp[0])] = strtolower(trim($temp[1]));
  278. // return the length of what was passed unless you want a Failed writing header error ;)
  279. return strlen($header);
  280. }
  281. }