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