* addressed r53282#c3209 moved conditional inclusion of $wgExtensionMessages in mwScr...
[lhc/web/wiklou.git] / includes / HttpFunctions.php
1 <?php
2 /**
3 * HTTP handling class
4 * @defgroup HTTP HTTP
5 * @file
6 * @ingroup HTTP
7 */
8
9 class Http {
10 const SYNC_DOWNLOAD = 1; // syncronys upload (in a single request)
11 const ASYNC_DOWNLOAD = 2; // asynchronous upload we should spawn out another process and monitor progress if possible)
12
13 var $body = '';
14 public static function request($method, $url, $opts = Array() ){
15 $opts['method'] = ( strtoupper( $method ) == 'GET' || strtoupper( $method ) == 'POST' ) ? strtoupper( $method ) : null;
16 $req = new HttpRequest( $url, $opts );
17 $status = $req->doRequest();
18 if( $status->isOK() ){
19 return $status->value;
20 } else {
21 wfDebug( 'http error: ' . $status->getWikiText() );
22 return false;
23 }
24 }
25 /**
26 * Simple wrapper for Http::request( 'GET' )
27 */
28 public static function get( $url, $timeout = false ) {
29 $opts = Array();
30 if( $timeout )
31 $opts['timeout'] = $timeout;
32 return Http::request( 'GET', $url, $opts );
33 }
34
35 /**
36 * Simple wrapper for Http::request( 'POST' )
37 */
38 public static function post( $url, $opts = array() ) {
39 return Http::request( 'POST', $url, $opts );
40 }
41
42 public static function doDownload( $url, $target_file_path , $dl_mode = self::SYNC_DOWNLOAD , $redirectCount = 0 ){
43 global $wgPhpCli, $wgMaxUploadSize, $wgMaxRedirects;
44 // do a quick check to HEAD to insure the file size is not > $wgMaxUploadSize
45 $head = @get_headers( $url, 1 );
46
47
48 // check for redirects:
49 if( isset( $head['Location'] ) && strrpos( $head[0], '302' ) !== false ){
50 if( $redirectCount < $wgMaxRedirects ){
51 if( UploadFromUrl::isValidURI( $head['Location'] ) ){
52 return self::doDownload( $head['Location'], $target_file_path , $dl_mode, $redirectCount++ );
53 } else {
54 return Status::newFatal( 'upload-proto-error' );
55 }
56 } else {
57 return Status::newFatal( 'upload-too-many-redirects' );
58 }
59 }
60 // we did not get a 200 ok response:
61 if( strrpos( $head[0], '200 OK' ) === false ){
62 return Status::newFatal( 'upload-http-error', htmlspecialchars( $head[0] ) );
63 }
64
65 $content_length = ( isset( $head['Content-Length'] ) ) ? $head['Content-Length'] : null;
66 if( $content_length ){
67 if( $content_length > $wgMaxUploadSize ){
68 return Status::newFatal( 'requested file length ' . $content_length . ' is greater than $wgMaxUploadSize: ' . $wgMaxUploadSize );
69 }
70 }
71
72 // check if we can find phpCliPath (for doing a background shell request to php to do the download:
73 if( $wgPhpCli && wfShellExecEnabled() && $dl_mode == self::ASYNC_DOWNLOAD ){
74 wfDebug( __METHOD__ . "\ASYNC_DOWNLOAD\n" );
75 // setup session and shell call:
76 return self::initBackgroundDownload( $url, $target_file_path, $content_length );
77 } else if( $dl_mode == self::SYNC_DOWNLOAD ){
78 wfDebug( __METHOD__ . "\nSYNC_DOWNLOAD\n" );
79 // SYNC_DOWNLOAD download as much as we can in the time we have to execute
80 $opts['method'] = 'GET';
81 $opts['target_file_path'] = $target_file_path;
82 $req = new HttpRequest( $url, $opts );
83 return $req->doRequest();
84 }
85 }
86
87 /**
88 * a non blocking request (generally an exit point in the application)
89 * should write to a file location and give updates
90 *
91 */
92 private function initBackgroundDownload( $url, $target_file_path, $content_length = null ){
93 global $wgMaxUploadSize, $IP, $wgPhpCli;
94 $status = Status::newGood();
95
96 // generate a session id with all the details for the download (pid, target_file_path )
97 $upload_session_key = self::getUploadSessionKey();
98 $session_id = session_id();
99
100 // store the url and target path:
101 $_SESSION['wsDownload'][$upload_session_key]['url'] = $url;
102 $_SESSION['wsDownload'][$upload_session_key]['target_file_path'] = $target_file_path;
103
104 if( $content_length )
105 $_SESSION['wsDownload'][$upload_session_key]['content_length'] = $content_length;
106
107 // set initial loaded bytes:
108 $_SESSION['wsDownload'][$upload_session_key]['loaded'] = 0;
109
110 // run the background download request:
111 $cmd = $wgPhpCli . ' ' . $IP . "/maintenance/http_session_download.php --sid {$session_id} --usk {$upload_session_key}";
112 $pid = wfShellBackgroundExec( $cmd, $retval );
113 // the pid is not of much use since we won't be visiting this same apache any-time soon.
114 if( !$pid )
115 return Status::newFatal( 'could not run background shell exec' );
116
117 // update the status value with the $upload_session_key (for the user to check on the status of the upload)
118 $status->value = $upload_session_key;
119
120 // return good status
121 return $status;
122 }
123
124 function getUploadSessionKey(){
125 $key = mt_rand( 0, 0x7fffffff );
126 $_SESSION['wsUploadData'][$key] = array();
127 return $key;
128 }
129
130 /**
131 * used to run a session based download. Is initiated via the shell.
132 *
133 * @param $session_id String: the session id to grab download details from
134 * @param $upload_session_key String: the key of the given upload session
135 * (a given client could have started a few http uploads at once)
136 */
137 public static function doSessionIdDownload( $session_id, $upload_session_key ){
138 global $wgUser, $wgEnableWriteAPI, $wgAsyncHTTPTimeout;
139 wfDebug( __METHOD__ . "\n\ndoSessionIdDownload\n\n" );
140 // set session to the provided key:
141 session_id( $session_id );
142 // start the session
143 if( session_start() === false ){
144 wfDebug( __METHOD__ . ' could not start session' );
145 }
146 //get all the vars we need from session_id
147 if(!isset($_SESSION[ 'wsDownload' ][$upload_session_key])){
148 wfDebug( __METHOD__ .' Error:could not find upload session');
149 exit();
150 }
151 // setup the global user from the session key we just inherited
152 $wgUser = User::newFromSession();
153
154 // grab the session data to setup the request:
155 $sd =& $_SESSION['wsDownload'][$upload_session_key];
156 // close down the session so we can other http queries can get session updates:
157 session_write_close();
158
159 $req = new HttpRequest( $sd['url'], array(
160 'target_file_path' => $sd['target_file_path'],
161 'upload_session_key'=> $upload_session_key,
162 'timeout' => $wgAsyncHTTPTimeout
163 ) );
164 // run the actual request .. (this can take some time)
165 wfDebug( __METHOD__ . "do Request: " . $sd['url'] . ' tf: ' . $sd['target_file_path'] );
166 $status = $req->doRequest();
167 //wfDebug("done with req status is: ". $status->isOK(). ' '.$status->getWikiText(). "\n");
168
169 // start up the session again:
170 if( session_start() === false ){
171 wfDebug( __METHOD__ . ' ERROR:: Could not start session');
172 }
173 // grab the updated session data pointer
174 $sd =& $_SESSION['wsDownload'][$upload_session_key];
175 // if error update status:
176 if( !$status->isOK() ){
177 $sd['apiUploadResult'] = ApiFormatJson::getJsonEncode(
178 array( 'error' => $status->getWikiText() )
179 );
180 }
181 // if status okay process upload using fauxReq to api:
182 if( $status->isOK() ){
183 // setup the FauxRequest
184 $fauxReqData = $sd['mParams'];
185 $fauxReqData['action'] = 'upload';
186 $fauxReqData['format'] = 'json';
187 $fauxReqData['internalhttpsession'] = $upload_session_key;
188
189 // evil but no other clean way about it:
190 $faxReq = new FauxRequest( $fauxReqData, true );
191 $processor = new ApiMain( $faxReq, $wgEnableWriteAPI );
192
193 //init the mUpload var for the $processor
194 $processor->execute();
195 $processor->getResult()->cleanUpUTF8();
196 $printer = $processor->createPrinterByName( 'json' );
197 $printer->initPrinter( false );
198 ob_start();
199 $printer->execute();
200 $apiUploadResult = ob_get_clean();
201
202 wfDebug( __METHOD__ . "\n\n got api result:: $apiUploadResult \n" );
203 // the status updates runner will grab the result form the session:
204 $sd['apiUploadResult'] = $apiUploadResult;
205 }
206 // close the session:
207 session_write_close();
208 }
209
210 /**
211 * Check if the URL can be served by localhost
212 * @param $url string Full url to check
213 * @return bool
214 */
215 public static function isLocalURL( $url ) {
216 global $wgCommandLineMode, $wgConf;
217 if ( $wgCommandLineMode ) {
218 return false;
219 }
220
221 // Extract host part
222 $matches = array();
223 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
224 $host = $matches[1];
225 // Split up dotwise
226 $domainParts = explode( '.', $host );
227 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
228 $domainParts = array_reverse( $domainParts );
229 for ( $i = 0; $i < count( $domainParts ); $i++ ) {
230 $domainPart = $domainParts[$i];
231 if ( $i == 0 ) {
232 $domain = $domainPart;
233 } else {
234 $domain = $domainPart . '.' . $domain;
235 }
236 if ( $wgConf->isLocalVHost( $domain ) ) {
237 return true;
238 }
239 }
240 }
241 return false;
242 }
243
244 /**
245 * Return a standard user-agent we can use for external requests.
246 */
247 public static function userAgent() {
248 global $wgVersion;
249 return "MediaWiki/$wgVersion";
250 }
251 }
252 class HttpRequest{
253 var $target_file_path;
254 var $upload_session_key;
255
256 function __construct( $url, $opt ){
257 global $wgSyncHTTPTimeout;
258 $this->url = $url;
259 // set the timeout to default sync timeout (unless the timeout option is provided)
260 $this->timeout = ( isset( $opt['timeout'] ) ) ? $opt['timeout'] : $wgSyncHTTPTimeout;
261 $this->method = ( isset( $opt['method'] ) ) ? $opt['method'] : 'GET';
262 $this->target_file_path = ( isset( $opt['target_file_path'] ) ) ? $opt['target_file_path'] : false;
263 $this->upload_session_key = ( isset( $opt['upload_session_key'] ) ) ? $opt['upload_session_key'] : false;
264 }
265
266 /**
267 * Get the contents of a file by HTTP
268 * @param $url string Full URL to act on
269 * @param $Opt associative array Optional array of options:
270 * 'method' => 'GET', 'POST' etc.
271 * 'target_file_path' => if curl should output to a target file
272 * 'adapter' => 'curl', 'soket'
273 */
274 public function doRequest() {
275 # Use curl if available
276 if ( function_exists( 'curl_init' ) ) {
277 return $this->doCurlReq();
278 } else {
279 return $this->doPhpReq();
280 }
281 }
282
283 private function doCurlReq(){
284 global $wgHTTPProxy, $wgTitle;
285
286 $status = Status::newGood();
287 $c = curl_init( $this->url );
288
289 // proxy setup:
290 if ( Http::isLocalURL( $this->url ) ) {
291 curl_setopt( $c, CURLOPT_PROXY, 'localhost:80' );
292 } else if ( $wgHTTPProxy ) {
293 curl_setopt( $c, CURLOPT_PROXY, $wgHTTPProxy );
294 }
295
296 curl_setopt( $c, CURLOPT_TIMEOUT, $this->timeout );
297 curl_setopt( $c, CURLOPT_USERAGENT, Http::userAgent() );
298
299 if ( $this->method == 'POST' ) {
300 curl_setopt( $c, CURLOPT_POST, true );
301 curl_setopt( $c, CURLOPT_POSTFIELDS, '' );
302 } else {
303 curl_setopt( $c, CURLOPT_CUSTOMREQUEST, $this->method );
304 }
305
306 # Set the referer to $wgTitle, even in command-line mode
307 # This is useful for interwiki transclusion, where the foreign
308 # server wants to know what the referring page is.
309 # $_SERVER['REQUEST_URI'] gives a less reliable indication of the
310 # referring page.
311 if ( is_object( $wgTitle ) ) {
312 curl_setopt( $c, CURLOPT_REFERER, $wgTitle->getFullURL() );
313 }
314
315 // set the write back function (if we are writing to a file)
316 if( $this->target_file_path ){
317 $cwrite = new simpleFileWriter( $this->target_file_path, $this->upload_session_key );
318 if( !$cwrite->status->isOK() ){
319 wfDebug( __METHOD__ . "ERROR in setting up simpleFileWriter\n" );
320 $status = $cwrite->status;
321 }
322 curl_setopt( $c, CURLOPT_WRITEFUNCTION, array( $cwrite, 'callbackWriteBody' ) );
323 }
324
325 // start output grabber:
326 if( !$this->target_file_path )
327 ob_start();
328
329 //run the actual curl_exec:
330 try {
331 if ( false === curl_exec( $c ) ) {
332 $error_txt ='Error sending request: #' . curl_errno( $c ) .' '. curl_error( $c );
333 wfDebug( __METHOD__ . $error_txt . "\n" );
334 $status = Status::newFatal( $error_txt );
335 }
336 } catch ( Exception $e ) {
337 // do something with curl exec error?
338 }
339 // if direct request output the results to the stats value:
340 if( !$this->target_file_path && $status->isOK() ){
341 $status->value = ob_get_contents();
342 ob_end_clean();
343 }
344 // if we wrote to a target file close up or return error
345 if( $this->target_file_path ){
346 $cwrite->close();
347 if( !$cwrite->status->isOK() ){
348 return $cwrite->status;
349 }
350 }
351
352 # Don't return the text of error messages, return false on error
353 $retcode = curl_getinfo( $c, CURLINFO_HTTP_CODE );
354 if ( $retcode != 200 ) {
355 wfDebug( __METHOD__ . ": HTTP return code $retcode\n" );
356 $status = Status::newFatal( "HTTP return code $retcode\n" );
357 }
358 # Don't return truncated output
359 $errno = curl_errno( $c );
360 if ( $errno != CURLE_OK ) {
361 $errstr = curl_error( $c );
362 wfDebug( __METHOD__ . ": CURL error code $errno: $errstr\n" );
363 $status = Status::newFatal( " CURL error code $errno: $errstr\n" );
364 }
365 curl_close( $c );
366
367 // return the result obj
368 return $status;
369 }
370
371 public function doPhpReq(){
372 #$use file_get_contents...
373 # This doesn't have local fetch capabilities...
374
375 $headers = array( "User-Agent: " . Http :: userAgent() );
376 if( strcasecmp( $method, 'post' ) == 0 ) {
377 // Required for HTTP 1.0 POSTs
378 $headers[] = "Content-Length: 0";
379 }
380 $opts = array(
381 'http' => array(
382 'method' => $method,
383 'header' => implode( "\r\n", $headers ),
384 'timeout' => $timeout ) );
385 $ctx = stream_context_create( $opts );
386
387 $status = new Status;
388 $status->value = file_get_contents( $url, false, $ctx );
389 if( !$status->value ){
390 $status->error( 'file_get_contents-failed' );
391 }
392 return $status;
393 }
394
395 }
396
397 /**
398 * a simpleFileWriter with session id updates
399 */
400 class simpleFileWriter {
401 var $target_file_path;
402 var $status = null;
403 var $session_id = null;
404 var $session_update_interval = 0; // how often to update the session while downloading
405
406 function simpleFileWriter( $target_file_path, $upload_session_key ){
407 $this->target_file_path = $target_file_path;
408 $this->upload_session_key = $upload_session_key;
409 $this->status = Status::newGood();
410 // open the file:
411 $this->fp = fopen( $this->target_file_path, 'w' );
412 if( $this->fp === false ){
413 $this->status = Status::newFatal( 'HTTP::could-not-open-file-for-writing' );
414 }
415 // true start time
416 $this->prevTime = time();
417 }
418
419 public function callbackWriteBody($ch, $data_packet){
420 global $wgMaxUploadSize;
421
422 // write out the content
423 if( fwrite( $this->fp, $data_packet ) === false ){
424 wfDebug( __METHOD__ ." ::could-not-write-to-file\n" );
425 $this->status = Status::newFatal( 'HTTP::could-not-write-to-file' );
426 return 0;
427 }
428
429 // check file size:
430 clearstatcache();
431 $this->current_fsize = filesize( $this->target_file_path );
432
433 if( $this->current_fsize > $wgMaxUploadSize ){
434 wfDebug( __METHOD__ . " ::http download too large\n" );
435 $this->status = Status::newFatal( 'HTTP::file-has-grown-beyond-upload-limit-killing: downloaded more than ' .
436 Language::formatSize( $wgMaxUploadSize ) . ' ' );
437 return 0;
438 }
439
440 // if more than session_update_interval second have passed update_session_progress
441 if( $this->upload_session_key && ( ( time() - $this->prevTime ) > $this->session_update_interval ) ) {
442 $this->prevTime = time();
443 $session_status = $this->update_session_progress();
444 if( !$session_status->isOK() ){
445 $this->status = $session_status;
446 wfDebug( __METHOD__ . ' update session failed or was canceled');
447 return 0;
448 }
449 }
450 return strlen( $data_packet );
451 }
452
453 public function update_session_progress(){
454 $status = Status::newGood();
455 // start the session
456 if( session_start() === false){
457 wfDebug( __METHOD__ . ' could not start session' );
458 exit( 0 );
459 }
460 $sd =& $_SESSION['wsDownload'][$this->upload_session_key];
461 // check if the user canceled the request:
462 if( $sd['user_cancel'] == true ){
463 // kill the download
464 return Status::newFatal( 'user-canceled-request' );
465 }
466 // update the progress bytes download so far:
467 $sd['loaded'] = $this->current_fsize;
468 wfDebug( __METHOD__ . ': set session loaded amount to: ' . $sd['loaded'] . "\n");
469 // close down the session so we can other http queries can get session updates:
470 session_write_close();
471 return $status;
472 }
473
474 public function close(){
475 // do a final session update:
476 $this->update_session_progress();
477 // close up the file handle:
478 if( false === fclose( $this->fp ) ){
479 $this->status = Status::newFatal( 'HTTP::could-not-close-file' );
480 }
481 }
482
483 }