]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-http.php
Move api.y.org stuff to functions-http.php
[Github/YOURLS.git] / includes / functions-http.php
1 <?php
2 /**
3  * Functions that relate to HTTP requests
4  *
5  */
6  
7 /**
8  * On functions using the 3rd party library Requests: 
9  *
10  * The goal here is to provide convenient wrapper functions to the Requests library. There are
11  * 2 types of functions for each METHOD, where METHOD is 'get' or 'post' (implement more as needed)
12  *     - yourls_http_METHOD() :
13  *         Return a complete Response object (with ->body, ->headers, ->status_code, etc...) or
14  *         a simple string (error message)
15  *     - yourls_http_METHOD_body() :
16  *         Return a string (response body) or null if there was an error
17  *
18  * TODO: global $ydb->debug_log should store the error message if any
19  *
20  * @since 1.7
21  */
22
23 /**
24  * Perform a GET request, return response object or error string message
25  *
26  * Notable object properties: body, headers, status_code
27  *
28  * @since 1.7
29  * @see yourls_http_request
30  * @return mixed Response object, or error string
31  */
32 function yourls_http_get( $url, $headers = array(), $data = array(), $options = array() ) {
33         return yourls_http_request( 'GET', $url, $headers, $data, $options );
34 }
35
36 /**
37  * Perform a GET request, return body or null if there was an error
38  *
39  * @since 1.7
40  * @see yourls_http_request
41  * @return mixed String (page body) or null if error
42  */
43 function yourls_http_get_body( $url, $headers = array(), $data = array(), $options = array() ) {
44         $return = yourls_http_get( $url, $headers, $data, $options );
45         return isset( $return->body ) ? $return->body : null;
46 }
47
48 /**
49  * Perform a POST request, return response object
50  *
51  * Notable object properties: body, headers, status_code
52  *
53  * @since 1.7
54  * @see yourls_http_request
55  * @return mixed Response object, or error string
56  */
57 function yourls_http_post( $url, $headers = array(), $data = array(), $options = array() ) {
58         return yourls_http_request( 'POST', $url, $headers, $data, $options );
59 }
60
61 /**
62  * Perform a POST request, return body
63  *
64  * Wrapper for yourls_http_request()
65  *
66  * @since 1.7
67  * @see yourls_http_request
68  * @return mixed String (page body) or null if error
69  */
70 function yourls_http_post_body( $url, $headers = array(), $data = array(), $options = array() ) {
71         $return = yourls_http_post( $url, $headers, $data, $options );
72         return isset( $return->body ) ? $return->body : null;
73 }
74
75 /**
76  * Default HTTP requests options for YOURLS
77  *
78  * For a list of all available options, see function request() in /includes/Requests/Requests.php
79  *
80  * @since 1.7
81  * @return array Options
82  */
83 function yourls_http_default_options() {
84         $options = array(
85                 'timeout'          => yourls_apply_filter( 'http_default_options_timeout', 3 ),
86                 'useragent'        => yourls_http_user_agent(),
87                 'follow_redirects' => true,
88                 'redirects'        => 3,
89         );
90
91         return yourls_apply_filter( 'http_default_options', $options ); 
92 }
93
94 /**
95  * Perform a HTTP request, return response object
96  *
97  * @since 1.7
98  * @param string $var Stuff
99  * @return string Result
100  */
101 function yourls_http_request( $type, $url, $headers, $data, $options ) {
102         yourls_http_load_library();
103         
104         $options = array_merge( yourls_http_default_options(), $options );
105         
106         try {
107                 $result = Requests::request( $url, $headers, $data, $type, $options );
108         } catch( Requests_Exception $e ) {
109                 $result = $e->getMessage();
110         };
111         
112         return $result;
113 }
114
115 /**
116  * Check if Requests class is defined, include Requests library if need be
117  *
118  * All HTTP functions should perform that check prior to any operation. This is to avoid
119  * include()-ing all the Requests files on every YOURLS instance disregarding whether needed or not.
120  *
121  * @since 1.7
122  */
123 function yourls_http_load_library() {
124         if ( !class_exists( 'Requests', false ) ) {
125                 require_once dirname( __FILE__ ) . '/Requests/Requests.php';
126                 Requests::register_autoloader();
127         }
128 }
129
130 /**
131  * Deprecated. Get remote content via a GET request using best transport available
132  * Returns $content (might be an error message) or false if no transport available
133  *
134  */
135 function yourls_get_remote_content( $url,  $maxlen = 4096, $timeout = 5 ) {
136         yourls_deprecated_function( __FUNCTION__, '1.7', 'yourls_http_get' );
137         return yourls_http_get_body( $url );
138 }
139
140 /**
141  * Return funky user agent string
142  *
143  */
144 function yourls_http_user_agent() {
145         return yourls_apply_filter( 'http_user_agent', 'YOURLS v'.YOURLS_VERSION.' +http://yourls.org/ (running on '.YOURLS_SITE.')' );
146 }
147
148 /**
149  * Check api.yourls.org if there's a newer version of YOURLS
150  *
151  * This function collects various stats to help us improve YOURLS. See https://gist.github.com/ozh/5518761
152  * Results of requests sent to api.yourls.org are stored in option 'core_version_checks' and is an object
153  * with the following properties:
154  *    - failed_attempts : number of consecutive failed attempts
155  *    - last_attempt    : time() of last attempt
156  *    - last_result     : content retrieved from api.yourls.org during previous check
157  *    - version_checked : installed YOURLS version that was last checked
158  *
159  * @since 1.7
160  * @return boolean True if api.yourls.org successfully requested, false otherwise
161  */
162 function yourls_check_core_version() {
163
164         if( defined( 'YOURLS_NO_VERSION_CHECK' ) && YOURLS_NO_VERSION_CHECK )
165                 return false;
166                 
167         global $ydb, $yourls_user_passwords;
168         
169         $checks = yourls_get_option( 'core_version_checks' );
170         
171         // Invalidate check data when YOURLS version changes
172         if ( is_object( $checks ) && YOURLS_VERSION != $checks->version_checked ) {
173                 $checks = false;
174         }
175         
176         if( !is_object( $checks ) ) {
177                 $checks = new stdClass;
178                 $checks->failed_attempts = 0;
179                 $checks->last_attempt    = 0;
180                 $checks->last_result     = '';
181                 $checks->version_checked = YOURLS_VERSION;
182         }
183
184         // Config file location ('u' for '/user' or 'i' for '/includes')
185         $conf_loc = str_replace( YOURLS_ABSPATH, '', YOURLS_CONFIGFILE );
186         $conf_loc = str_replace( '/config.php', '', $conf_loc );
187         $conf_loc = ( $conf_loc == '/user' ? 'u' : 'i' );
188                 
189         // The collection of stuff to report
190         $stuff = array(
191                 'md5'                => md5( YOURLS_SITE . YOURLS_ABSPATH ),  // globally unique site identifier
192
193                 'failed_attempts'    => $checks->failed_attempts,
194                 'yourls_site'        => YOURLS_SITE,
195                 'yourls_version'     => YOURLS_VERSION,
196                 'php_version'        => phpversion(),
197                 'mysql_version'      => $ydb->mysql_version(),
198                 'locale'             => yourls_get_locale(),
199
200                 'db_driver'          => YOURLS_DB_DRIVER,
201                 'db_ext_pdo'         => extension_loaded( 'pdo_mysql' ) ? 1 : 0,
202                 'db_ext_mysql'       => extension_loaded( 'mysql' )     ? 1 : 0,
203                 'db_ext_mysqli'      => extension_loaded( 'mysqli' )    ? 1 : 0,
204                 'ext_curl'           => extension_loaded( 'curl' )      ? 1 : 0,
205
206                 'num_users'          => count( $yourls_user_passwords ),
207                 'config_location'    => $conf_loc,
208                 'yourls_private'     => YOURLS_PRIVATE     ? 1 : 0,
209                 'yourls_unique'      => YOURLS_UNIQUE_URLS ? 1 : 0,
210                 'yourls_url_convert' => YOURLS_URL_CONVERT,
211                 'num_active_plugins' => yourls_has_active_plugins(),
212         );
213         
214         $stuff = yourls_apply_filter( 'version_check_stuff', $stuff );
215         
216         // Send it in
217         $checks->last_attempt = time();
218         $url = 'https://api.yourls.org/core/version/1.0/';
219         $req = yourls_http_post( $url, array(), $stuff );
220         
221         // Unexpected results ?
222         if( is_string( $req ) or !$req->success ) {
223                 $checks->failed_attempts = $checks->failed_attempts + 1;
224                 $checks->last_result     = '';
225                 yourls_update_option( 'core_version_checks', $checks );
226                 return false;
227         }
228         
229         // Parse response
230         $json = json_decode( trim( $req->body ) );
231         
232         if( isset( $json->latest ) && isset( $json->zipurl ) ) {
233                 // All went OK - mark this down
234                 $checks->failed_attempts = 0;
235                 $checks->last_result     = $json;
236                 $checks->version_checked = YOURLS_VERSION;
237                 yourls_update_option( 'core_version_checks', $checks );
238                 
239                 return true;
240         }
241         
242         // Request returned actual result, but not what we expected
243         return false;   
244 }
245
246
247 /**
248  * Determine if we need to check for a newer YOURLS version
249  *
250  * Longer description
251  *
252  * @since
253  * @param unknown_type $a    TODO
254  * @return unknown           TODO
255  */
256 function yourls_maybe_check_core_version() {
257
258         /* Let's check if :
259          - we're viewing an admin page
260          AND one of these cases:
261          - last_result not set
262          - failed_attempts = 0 && last_attempt > 24h  ( 24 * 3600 > ( time() - $check->last_attempt )
263          - failed_attempts > 0 && last_attempt >  2h
264          - version_checked != YOURLS_VERSION
265          
266          In the future, maybe check with cronjob emulation instead of limiting to when viewing an admin page
267         */
268         
269
270 }