Class-CurlFetchWeb.php 10 KB

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