2
0

Class-CurlFetchWeb.php 10 KB

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