PageRenderTime 55ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/functions-http.php

https://gitlab.com/Slind/YOURLS
PHP | 369 lines | 164 code | 54 blank | 151 comment | 37 complexity | 36a280ef77f5ab6f91a6f0b55d7c6296 MD5 | raw file
  1. <?php
  2. /**
  3. * Functions that relate to HTTP requests
  4. *
  5. */
  6. /**
  7. * On functions using the 3rd party library Requests:
  8. *
  9. * The goal here is to provide convenient wrapper functions to the Requests library. There are
  10. * 2 types of functions for each METHOD, where METHOD is 'get' or 'post' (implement more as needed)
  11. * - yourls_http_METHOD() :
  12. * Return a complete Response object (with ->body, ->headers, ->status_code, etc...) or
  13. * a simple string (error message)
  14. * - yourls_http_METHOD_body() :
  15. * Return a string (response body) or null if there was an error
  16. *
  17. * @since 1.7
  18. */
  19. /**
  20. * Perform a GET request, return response object or error string message
  21. *
  22. * Notable object properties: body, headers, status_code
  23. *
  24. * @since 1.7
  25. * @see yourls_http_request
  26. * @return mixed Response object, or error string
  27. */
  28. function yourls_http_get( $url, $headers = array(), $data = array(), $options = array() ) {
  29. return yourls_http_request( 'GET', $url, $headers, $data, $options );
  30. }
  31. /**
  32. * Perform a GET request, return body or null if there was an error
  33. *
  34. * @since 1.7
  35. * @see yourls_http_request
  36. * @return mixed String (page body) or null if error
  37. */
  38. function yourls_http_get_body( $url, $headers = array(), $data = array(), $options = array() ) {
  39. $return = yourls_http_get( $url, $headers, $data, $options );
  40. return isset( $return->body ) ? $return->body : null;
  41. }
  42. /**
  43. * Perform a POST request, return response object
  44. *
  45. * Notable object properties: body, headers, status_code
  46. *
  47. * @since 1.7
  48. * @see yourls_http_request
  49. * @return mixed Response object, or error string
  50. */
  51. function yourls_http_post( $url, $headers = array(), $data = array(), $options = array() ) {
  52. return yourls_http_request( 'POST', $url, $headers, $data, $options );
  53. }
  54. /**
  55. * Perform a POST request, return body
  56. *
  57. * Wrapper for yourls_http_request()
  58. *
  59. * @since 1.7
  60. * @see yourls_http_request
  61. * @return mixed String (page body) or null if error
  62. */
  63. function yourls_http_post_body( $url, $headers = array(), $data = array(), $options = array() ) {
  64. $return = yourls_http_post( $url, $headers, $data, $options );
  65. return isset( $return->body ) ? $return->body : null;
  66. }
  67. /**
  68. * Check if a proxy is defined for HTTP requests
  69. *
  70. * @uses YOURLS_PROXY
  71. * @since 1.7
  72. * @return bool true if a proxy is defined, false otherwise
  73. */
  74. function yourls_http_proxy_is_defined() {
  75. return yourls_apply_filter( 'http_proxy_is_defined', defined( 'YOURLS_PROXY' ) );
  76. }
  77. /**
  78. * Default HTTP requests options for YOURLS
  79. *
  80. * For a list of all available options, see function request() in /includes/Requests/Requests.php
  81. *
  82. * @uses YOURLS_PROXY
  83. * @uses YOURLS_PROXY_USERNAME
  84. * @uses YOURLS_PROXY_PASSWORD
  85. * @since 1.7
  86. * @return array Options
  87. */
  88. function yourls_http_default_options() {
  89. $options = array(
  90. 'timeout' => yourls_apply_filter( 'http_default_options_timeout', 3 ),
  91. 'useragent' => yourls_http_user_agent(),
  92. 'follow_redirects' => true,
  93. 'redirects' => 3,
  94. );
  95. if( yourls_http_proxy_is_defined() ) {
  96. if( defined( 'YOURLS_PROXY_USERNAME' ) && defined( 'YOURLS_PROXY_PASSWORD' ) ) {
  97. $options['proxy'] = array( YOURLS_PROXY, YOURLS_PROXY_USERNAME, YOURLS_PROXY_PASSWORD );
  98. } else {
  99. $options['proxy'] = YOURLS_PROXY;
  100. }
  101. }
  102. return yourls_apply_filter( 'http_default_options', $options );
  103. }
  104. /**
  105. * Whether URL should be sent through the proxy server.
  106. *
  107. * Concept stolen from WordPress. The idea is to allow some URLs, including localhost and the YOURLS install itself,
  108. * to be requested directly and bypassing any defined proxy.
  109. *
  110. * @uses YOURLS_PROXY
  111. * @uses YOURLS_PROXY_BYPASS_HOSTS
  112. * @since 1.7
  113. * @param string $url URL to check
  114. * @return bool true to request through proxy, false to request directly
  115. */
  116. function yourls_send_through_proxy( $url ) {
  117. // Allow plugins to short-circuit the whole function
  118. $pre = yourls_apply_filter( 'shunt_send_through_proxy', null, $url );
  119. if ( null !== $pre )
  120. return $pre;
  121. $check = @parse_url( $url );
  122. // Malformed URL, can not process, but this could mean ssl, so let through anyway.
  123. if ( $check === false )
  124. return true;
  125. // Self and loopback URLs are considered local (':' is parse_url() host on '::1')
  126. $home = parse_url( YOURLS_SITE );
  127. $local = array( 'localhost', '127.0.0.1', '127.1', '[::1]', ':', $home['host'] );
  128. if( in_array( $check['host'], $local ) )
  129. return false;
  130. if ( !defined( 'YOURLS_PROXY_BYPASS_HOSTS' ) )
  131. return true;
  132. // Check YOURLS_PROXY_BYPASS_HOSTS
  133. static $bypass_hosts;
  134. static $wildcard_regex = false;
  135. if ( null == $bypass_hosts ) {
  136. $bypass_hosts = preg_split( '|,\s*|', YOURLS_PROXY_BYPASS_HOSTS );
  137. if ( false !== strpos( YOURLS_PROXY_BYPASS_HOSTS, '*' ) ) {
  138. $wildcard_regex = array();
  139. foreach ( $bypass_hosts as $host )
  140. $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
  141. $wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i';
  142. }
  143. }
  144. if ( !empty( $wildcard_regex ) )
  145. return !preg_match( $wildcard_regex, $check['host'] );
  146. else
  147. return !in_array( $check['host'], $bypass_hosts );
  148. }
  149. /**
  150. * Perform a HTTP request, return response object
  151. *
  152. * @since 1.7
  153. * @param string $var Stuff
  154. * @return string Result
  155. */
  156. function yourls_http_request( $type, $url, $headers, $data, $options ) {
  157. yourls_http_load_library();
  158. $options = array_merge( yourls_http_default_options(), $options );
  159. if( yourls_http_proxy_is_defined() && !yourls_send_through_proxy( $url ) )
  160. unset( $options['proxy'] );
  161. try {
  162. $result = Requests::request( $url, $headers, $data, $type, $options );
  163. } catch( Requests_Exception $e ) {
  164. $result = yourls_debug_log( $e->getMessage() . ' (' . $type . ' on ' . $url . ')' );
  165. };
  166. return $result;
  167. }
  168. /**
  169. * Check if Requests class is defined, include Requests library if need be
  170. *
  171. * All HTTP functions should perform that check prior to any operation. This is to avoid
  172. * include()-ing all the Requests files on every YOURLS instance disregarding whether needed or not.
  173. *
  174. * @since 1.7
  175. */
  176. function yourls_http_load_library() {
  177. if ( !class_exists( 'Requests', false ) ) {
  178. require_once dirname( __FILE__ ) . '/Requests/Requests.php';
  179. Requests::register_autoloader();
  180. }
  181. }
  182. /**
  183. * Return funky user agent string
  184. *
  185. * @since 1.5
  186. * @return string UA string
  187. */
  188. function yourls_http_user_agent() {
  189. return yourls_apply_filter( 'http_user_agent', 'YOURLS v'.YOURLS_VERSION.' +http://yourls.org/ (running on '.YOURLS_SITE.')' );
  190. }
  191. /**
  192. * Check api.yourls.org if there's a newer version of YOURLS
  193. *
  194. * This function collects various stats to help us improve YOURLS. See the blog post about it:
  195. * http://blog.yourls.org/2014/01/on-yourls-1-7-and-api-yourls-org/
  196. * Results of requests sent to api.yourls.org are stored in option 'core_version_checks' and is an object
  197. * with the following properties:
  198. * - failed_attempts : number of consecutive failed attempts
  199. * - last_attempt : time() of last attempt
  200. * - last_result : content retrieved from api.yourls.org during previous check
  201. * - version_checked : installed YOURLS version that was last checked
  202. *
  203. * @since 1.7
  204. * @return mixed JSON data if api.yourls.org successfully requested, false otherwise
  205. */
  206. function yourls_check_core_version() {
  207. global $ydb, $yourls_user_passwords;
  208. $checks = yourls_get_option( 'core_version_checks' );
  209. // Invalidate check data when YOURLS version changes
  210. if ( is_object( $checks ) && YOURLS_VERSION != $checks->version_checked ) {
  211. $checks = false;
  212. }
  213. if( !is_object( $checks ) ) {
  214. $checks = new stdClass;
  215. $checks->failed_attempts = 0;
  216. $checks->last_attempt = 0;
  217. $checks->last_result = '';
  218. $checks->version_checked = YOURLS_VERSION;
  219. }
  220. // Config file location ('u' for '/user' or 'i' for '/includes')
  221. $conf_loc = str_replace( YOURLS_ABSPATH, '', YOURLS_CONFIGFILE );
  222. $conf_loc = str_replace( '/config.php', '', $conf_loc );
  223. $conf_loc = ( $conf_loc == '/user' ? 'u' : 'i' );
  224. // The collection of stuff to report
  225. $stuff = array(
  226. // Globally uniquish site identifier
  227. 'md5' => md5( YOURLS_SITE . YOURLS_ABSPATH ),
  228. // Install information
  229. 'failed_attempts' => $checks->failed_attempts,
  230. 'yourls_site' => defined( 'YOURLS_SITE' ) ? YOURLS_SITE : 'unknown',
  231. 'yourls_version' => defined( 'YOURLS_VERSION' ) ? YOURLS_VERSION : 'unknown',
  232. 'php_version' => phpversion(),
  233. 'mysql_version' => $ydb->mysql_version(),
  234. 'locale' => yourls_get_locale(),
  235. // custom DB driver if any, and useful common PHP extensions
  236. 'db_driver' => defined( 'YOURLS_DB_DRIVER' ) ? YOURLS_DB_DRIVER : 'unset',
  237. 'db_ext_pdo' => extension_loaded( 'pdo_mysql' ) ? 1 : 0,
  238. 'db_ext_mysql' => extension_loaded( 'mysql' ) ? 1 : 0,
  239. 'db_ext_mysqli' => extension_loaded( 'mysqli' ) ? 1 : 0,
  240. 'ext_curl' => extension_loaded( 'curl' ) ? 1 : 0,
  241. // Config information
  242. 'num_users' => count( $yourls_user_passwords ),
  243. 'config_location' => $conf_loc,
  244. 'yourls_private' => defined( 'YOURLS_PRIVATE' ) && YOURLS_PRIVATE ? 1 : 0,
  245. 'yourls_unique' => defined( 'YOURLS_UNIQUE_URLS' ) && YOURLS_UNIQUE_URLS ? 1 : 0,
  246. 'yourls_url_convert' => defined( 'YOURLS_URL_CONVERT' ) ? YOURLS_URL_CONVERT : 'unknown',
  247. 'num_active_plugins' => yourls_has_active_plugins(),
  248. 'num_pages' => defined( 'YOURLS_PAGEDIR' ) ? count( (array) glob( YOURLS_PAGEDIR .'/*.php') ) : 0,
  249. );
  250. $stuff = yourls_apply_filter( 'version_check_stuff', $stuff );
  251. // Send it in
  252. $url = 'https://api.yourls.org/core/version/1.0/';
  253. $req = yourls_http_post( $url, array(), $stuff );
  254. $checks->last_attempt = time();
  255. $checks->version_checked = YOURLS_VERSION;
  256. // Unexpected results ?
  257. if( is_string( $req ) or !$req->success ) {
  258. $checks->failed_attempts = $checks->failed_attempts + 1;
  259. yourls_update_option( 'core_version_checks', $checks );
  260. return false;
  261. }
  262. // Parse response
  263. $json = json_decode( trim( $req->body ) );
  264. if( isset( $json->latest ) && isset( $json->zipurl ) ) {
  265. // All went OK - mark this down
  266. $checks->failed_attempts = 0;
  267. $checks->last_result = $json;
  268. yourls_update_option( 'core_version_checks', $checks );
  269. return $json;
  270. }
  271. // Request returned actual result, but not what we expected
  272. return false;
  273. }
  274. /**
  275. * Determine if we want to check for a newer YOURLS version (and check if applicable)
  276. *
  277. * Currently checks are performed every 24h and only when someone is visiting an admin page.
  278. * In the future (1.8?) maybe check with cronjob emulation instead.
  279. *
  280. * @since 1.7
  281. * @return bool true if a check was needed and successfully performed, false otherwise
  282. */
  283. function yourls_maybe_check_core_version() {
  284. // Allow plugins to short-circuit the whole function
  285. $pre = yourls_apply_filter( 'shunt_maybe_check_core_version', null );
  286. if ( null !== $pre )
  287. return $pre;
  288. if( defined( 'YOURLS_NO_VERSION_CHECK' ) && YOURLS_NO_VERSION_CHECK )
  289. return false;
  290. if( !yourls_is_admin() )
  291. return false;
  292. $checks = yourls_get_option( 'core_version_checks' );
  293. /* We don't want to check if :
  294. - last_result is set (a previous check was performed)
  295. - and it was less than 24h ago (or less than 2h ago if it wasn't successful)
  296. - and version checked matched version running
  297. Otherwise, we want to check.
  298. */
  299. if( !empty( $checks->last_result )
  300. AND
  301. (
  302. ( $checks->failed_attempts == 0 && ( ( time() - $checks->last_attempt ) < 24 * 3600 ) )
  303. OR
  304. ( $checks->failed_attempts > 0 && ( ( time() - $checks->last_attempt ) < 2 * 3600 ) )
  305. )
  306. AND ( $checks->version_checked == YOURLS_VERSION )
  307. )
  308. return false;
  309. // We want to check if there's a new version
  310. $new_check = yourls_check_core_version();
  311. // Could not check for a new version, and we don't have ancient data
  312. if( false == $new_check && !isset( $checks->last_result->latest ) )
  313. return false;
  314. return true;
  315. }