* r55034#c3604 re-factored presently used curl options to back-end agnostic options.
[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 = HttpRequest::newRequest( $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, $opts = array() ) {
31 global $wgSyncHTTPTimeout;
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 = HttpRequest::newRequest( $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( self::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 {
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 = HttpRequest::newRequest( $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 $wgSessionsInMemcached, $wgSessionHandler, $wgSessionStarted;
148 wfDebug( __METHOD__ . "\n\n doSessionIdDownload :\n\n" );
149 // set session to the provided key:
150 session_id( $session_id );
151 //fire up mediaWiki session system:
152 wfSetupSession();
153
154 // start the session
155 if( session_start() === false ){
156 wfDebug( __METHOD__ . ' could not start session' );
157 }
158 // get all the vars we need from session_id
159 if( !isset( $_SESSION[ 'wsDownload' ][$upload_session_key] ) ){
160 wfDebug( __METHOD__ . ' Error:could not find upload session');
161 exit();
162 }
163 // setup the global user from the session key we just inherited
164 $wgUser = User::newFromSession();
165
166 // grab the session data to setup the request:
167 $sd =& $_SESSION['wsDownload'][$upload_session_key];
168
169 // update the wgServer var ( since cmd line thinks we are localhost when we are really orgServer)
170 if( isset( $sd['orgServer'] ) && $sd['orgServer'] ){
171 $wgServer = $sd['orgServer'];
172 }
173 // close down the session so we can other http queries can get session updates: (if not $wgSessionsInMemcached)
174 if( !$wgSessionsInMemcached )
175 session_write_close();
176
177 $req = HttpRequest::newRequest( $sd['url'], array(
178 'target_file_path' => $sd['target_file_path'],
179 'upload_session_key'=> $upload_session_key,
180 'timeout' => $wgAsyncHTTPTimeout,
181 'do_close_session_update' => true
182 ) );
183 // run the actual request .. (this can take some time)
184 wfDebug( __METHOD__ . 'do Session Download :: ' . $sd['url'] . ' tf: ' . $sd['target_file_path'] . "\n\n");
185 $status = $req->doRequest();
186 //wfDebug("done with req status is: ". $status->isOK(). ' '.$status->getWikiText(). "\n");
187
188 // start up the session again:
189 if( session_start() === false ){
190 wfDebug( __METHOD__ . ' ERROR:: Could not start session');
191 }
192 // grab the updated session data pointer
193 $sd =& $_SESSION['wsDownload'][$upload_session_key];
194 // if error update status:
195 if( !$status->isOK() ){
196 $sd['apiUploadResult'] = ApiFormatJson::getJsonEncode(
197 array( 'error' => $status->getWikiText() )
198 );
199 }
200 // if status okay process upload using fauxReq to api:
201 if( $status->isOK() ){
202 // setup the FauxRequest
203 $fauxReqData = $sd['mParams'];
204
205 // Fix boolean parameters
206 foreach( $fauxReqData as $k => $v ) {
207 if( $v === false )
208 unset( $fauxReqData[$k] );
209 }
210
211 $fauxReqData['action'] = 'upload';
212 $fauxReqData['format'] = 'json';
213 $fauxReqData['internalhttpsession'] = $upload_session_key;
214 // evil but no other clean way about it:
215 $faxReq = new FauxRequest( $fauxReqData, true );
216 $processor = new ApiMain( $faxReq, $wgEnableWriteAPI );
217
218 //init the mUpload var for the $processor
219 $processor->execute();
220 $processor->getResult()->cleanUpUTF8();
221 $printer = $processor->createPrinterByName( 'json' );
222 $printer->initPrinter( false );
223 ob_start();
224 $printer->execute();
225 $apiUploadResult = ob_get_clean();
226
227 // the status updates runner will grab the result form the session:
228 $sd['apiUploadResult'] = $apiUploadResult;
229 }
230 // close the session:
231 session_write_close();
232 }
233
234 /**
235 * Check if the URL can be served by localhost
236 * @param $url string Full url to check
237 * @return bool
238 */
239 public static function isLocalURL( $url ) {
240 global $wgCommandLineMode, $wgConf;
241 if ( $wgCommandLineMode ) {
242 return false;
243 }
244
245 // Extract host part
246 $matches = array();
247 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
248 $host = $matches[1];
249 // Split up dotwise
250 $domainParts = explode( '.', $host );
251 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
252 $domainParts = array_reverse( $domainParts );
253 for ( $i = 0; $i < count( $domainParts ); $i++ ) {
254 $domainPart = $domainParts[$i];
255 if ( $i == 0 ) {
256 $domain = $domainPart;
257 } else {
258 $domain = $domainPart . '.' . $domain;
259 }
260 if ( $wgConf->isLocalVHost( $domain ) ) {
261 return true;
262 }
263 }
264 }
265 return false;
266 }
267
268 /**
269 * Return a standard user-agent we can use for external requests.
270 */
271 public static function userAgent() {
272 global $wgVersion;
273 return "MediaWiki/$wgVersion";
274 }
275
276 /**
277 * Checks that the given URI is a valid one
278 * @param $uri Mixed: URI to check for validity
279 */
280 public static function isValidURI( $uri ){
281 return preg_match(
282 '/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
283 $uri,
284 $matches
285 );
286 }
287 }
288
289 class HttpRequest {
290 var $target_file_path;
291 var $upload_session_key;
292 function __construct( $url, $opt ){
293
294 global $wgSyncHTTPTimeout;
295 $this->url = $url;
296 // set the timeout to default sync timeout (unless the timeout option is provided)
297 $this->timeout = ( isset( $opt['timeout'] ) ) ? $opt['timeout'] : $wgSyncHTTPTimeout;
298 //check special key default
299 if($this->timeout == 'default'){
300 $opts['timeout'] = $wgSyncHTTPTimeout;
301 }
302
303 $this->method = ( isset( $opt['method'] ) ) ? $opt['method'] : 'GET';
304 $this->target_file_path = ( isset( $opt['target_file_path'] ) ) ? $opt['target_file_path'] : false;
305 $this->upload_session_key = ( isset( $opt['upload_session_key'] ) ) ? $opt['upload_session_key'] : false;
306 $this->headers_only = ( isset( $opt['headers_only'] ) ) ? $opt['headers_only'] : false;
307 $this->do_close_session_update = isset( $opt['do_close_session_update'] );
308 $this->postData = isset( $opt['postdata'] ) ? $opt['postdata'] : '';
309
310 $this->ssl_verifyhost = (isset( $opt['ssl_verifyhost'] ))? $opt['ssl_verifyhost']: false;
311
312 $this->cainfo = (isset( $opt['cainfo'] ))? $op['cainfo']: false;
313
314 }
315
316 public static function newRequest($url, $opt){
317 # select the handler (use curl if available)
318 if ( function_exists( 'curl_init' ) ) {
319 return new curlHttpRequest($url, $opt);
320 } else {
321 return new phpHttpRequest($url, $opt);
322 }
323 }
324
325 /**
326 * Get the contents of a file by HTTP
327 * @param $url string Full URL to act on
328 * @param $Opt associative array Optional array of options:
329 * 'method' => 'GET', 'POST' etc.
330 * 'target_file_path' => if curl should output to a target file
331 * 'adapter' => 'curl', 'soket'
332 */
333 public function doRequest() {
334 # Make sure we have a valid url
335 if( !Http::isValidURI( $this->url ) )
336 return Status::newFatal('bad-url');
337 //do the actual request:
338 return $this->doReq();
339 }
340 }
341 class curlHttpRequest extends HttpRequest {
342 public function doReq(){
343 global $wgHTTPProxy, $wgTitle;
344
345 $status = Status::newGood();
346 $c = curl_init( $this->url );
347
348 // proxy setup:
349 if ( Http::isLocalURL( $this->url ) ) {
350 curl_setopt( $c, CURLOPT_PROXY, 'localhost:80' );
351 } else if ( $wgHTTPProxy ) {
352 curl_setopt( $c, CURLOPT_PROXY, $wgHTTPProxy );
353 }
354
355 curl_setopt( $c, CURLOPT_TIMEOUT, $this->timeout );
356 curl_setopt( $c, CURLOPT_USERAGENT, Http::userAgent() );
357
358 if($this->ssl_verifyhost)
359 curl_setopt( $c, CURLOPT_SSL_VERIFYHOST, $this->ssl_verifyhost);
360
361 if($this->cainfo)
362 curl_setopt( $c, CURLOPT_CAINFO, $this->cainfo);
363
364 if ( $this->headers_only ) {
365 curl_setopt( $c, CURLOPT_NOBODY, true );
366 curl_setopt( $c, CURLOPT_HEADER, true );
367 } elseif ( $this->method == 'POST' ) {
368 curl_setopt( $c, CURLOPT_POST, true );
369 curl_setopt( $c, CURLOPT_POSTFIELDS, $this->postData );
370 // Suppress 'Expect: 100-continue' header, as some servers
371 // will reject it with a 417 and Curl won't auto retry
372 // with HTTP 1.0 fallback
373 curl_setopt( $c, CURLOPT_HTTPHEADER, array( 'Expect:' ) );
374 } else {
375 curl_setopt( $c, CURLOPT_CUSTOMREQUEST, $this->method );
376 }
377
378 # Set the referer to $wgTitle, even in command-line mode
379 # This is useful for interwiki transclusion, where the foreign
380 # server wants to know what the referring page is.
381 # $_SERVER['REQUEST_URI'] gives a less reliable indication of the
382 # referring page.
383 if ( is_object( $wgTitle ) ) {
384 curl_setopt( $c, CURLOPT_REFERER, $wgTitle->getFullURL() );
385 }
386
387 // set the write back function (if we are writing to a file)
388 if( $this->target_file_path ){
389 $cwrite = new simpleFileWriter( $this->target_file_path,
390 $this->upload_session_key,
391 $this->do_close_session_update
392 );
393 if( !$cwrite->status->isOK() ){
394 wfDebug( __METHOD__ . "ERROR in setting up simpleFileWriter\n" );
395 $status = $cwrite->status;
396 return $status;
397 }
398 curl_setopt( $c, CURLOPT_WRITEFUNCTION, array( $cwrite, 'callbackWriteBody' ) );
399 }
400
401 // start output grabber:
402 if( !$this->target_file_path )
403 ob_start();
404
405 //run the actual curl_exec:
406 try {
407 if ( false === curl_exec( $c ) ) {
408 $error_txt ='Error sending request: #' . curl_errno( $c ) .' '. curl_error( $c );
409 wfDebug( __METHOD__ . $error_txt . "\n" );
410 $status = Status::newFatal( $error_txt );
411 }
412 } catch ( Exception $e ) {
413 // do something with curl exec error?
414 }
415 // if direct request output the results to the stats value:
416 if( !$this->target_file_path && $status->isOK() ){
417 $status->value = ob_get_contents();
418 ob_end_clean();
419 }
420 // if we wrote to a target file close up or return error
421 if( $this->target_file_path ){
422 $cwrite->close();
423 if( !$cwrite->status->isOK() ){
424 return $cwrite->status;
425 }
426 }
427
428 if ( $this->headers_only ) {
429 $headers = explode( "\n", $status->value );
430 $headerArray = array();
431 foreach ( $headers as $header ) {
432 if ( !strlen( trim( $header ) ) )
433 continue;
434 $headerParts = explode( ':', $header, 2 );
435 if ( count( $headerParts ) == 1 ) {
436 $headerArray[] = trim( $header );
437 } else {
438 list( $key, $val ) = $headerParts;
439 $headerArray[trim( $key )] = trim( $val );
440 }
441 }
442 $status->value = $headerArray;
443 } else {
444 # Don't return the text of error messages, return false on error
445 $retcode = curl_getinfo( $c, CURLINFO_HTTP_CODE );
446 if ( $retcode != 200 ) {
447 wfDebug( __METHOD__ . ": HTTP return code $retcode\n" );
448 $status = Status::newFatal( "HTTP return code $retcode\n" );
449 }
450 # Don't return truncated output
451 $errno = curl_errno( $c );
452 if ( $errno != CURLE_OK ) {
453 $errstr = curl_error( $c );
454 wfDebug( __METHOD__ . ": CURL error code $errno: $errstr\n" );
455 $status = Status::newFatal( " CURL error code $errno: $errstr\n" );
456 }
457 }
458
459 curl_close( $c );
460 // return the result obj
461 return $status;
462 }
463 }
464 class phpHttpRequest extends HttpRequest {
465 public function doReq(){
466 global $wgTitle, $wgHTTPProxy;
467 # Check for php.ini allow_url_fopen
468 if( !ini_get( 'allow_url_fopen' ) ){
469 return Status::newFatal( 'allow_url_fopen needs to be enabled for http copy to work' );
470 }
471
472 // start with good status:
473 $status = Status::newGood();
474
475 if ( $this->headers_only ) {
476 $status->value = get_headers( $this->url, 1 );
477 return $status;
478 }
479
480 // setup the headers
481 $headers = array( "User-Agent: " . Http::userAgent() );
482 if ( is_object( $wgTitle ) ) {
483 $headers[] = "Referer: ". $wgTitle->getFullURL();
484 }
485
486 if( strcasecmp( $this->method, 'post' ) == 0 ) {
487 // Required for HTTP 1.0 POSTs
488 $headers[] = "Content-Length: 0";
489 }
490 $fcontext = stream_context_create ( array(
491 'http' => array(
492 'method' => $this->method,
493 'header' => implode( "\r\n", $headers ),
494 'timeout' => $this->timeout )
495 )
496 );
497 $fh = fopen( $this->url, "r", false, $fcontext);
498
499 // set the write back function (if we are writing to a file)
500 if( $this->target_file_path ){
501 $cwrite = new simpleFileWriter( $this->target_file_path, $this->upload_session_key, $this->do_close_session_update );
502 if( !$cwrite->status->isOK() ){
503 wfDebug( __METHOD__ . "ERROR in setting up simpleFileWriter\n" );
504 $status = $cwrite->status;
505 return $status;
506 }
507
508 // read $fh into the simpleFileWriter (grab in 64K chunks since its likely a ~large~ media file)
509 while ( !feof( $fh ) ) {
510 $contents = fread( $fh, 65536 );
511 $cwrite->callbackWriteBody( $fh, $contents );
512 }
513 $cwrite->close();
514 // check for simpleFileWriter error:
515 if( !$cwrite->status->isOK() ){
516 return $cwrite->status;
517 }
518 } else {
519 // read $fh into status->value
520 $status->value = @stream_get_contents( $fh );
521 }
522 //close the url file wrapper
523 fclose( $fh );
524
525 // check for "false"
526 if( $status->value === false ){
527 $status->error( 'file_get_contents-failed' );
528 }
529 return $status;
530 }
531
532 }
533
534 /**
535 * a simpleFileWriter with session id updates
536 */
537 class simpleFileWriter {
538 var $target_file_path;
539 var $status = null;
540 var $session_id = null;
541 var $session_update_interval = 0; // how often to update the session while downloading
542
543 function simpleFileWriter( $target_file_path, $upload_session_key, $do_close_session_update = false ){
544 $this->target_file_path = $target_file_path;
545 $this->upload_session_key = $upload_session_key;
546 $this->status = Status::newGood();
547 $this->do_close_session_update = $do_close_session_update;
548 // open the file:
549 $this->fp = fopen( $this->target_file_path, 'w' );
550 if( $this->fp === false ){
551 $this->status = Status::newFatal( 'HTTP::could-not-open-file-for-writing' );
552 }
553 // true start time
554 $this->prevTime = time();
555 }
556
557 public function callbackWriteBody( $ch, $data_packet ){
558 global $wgMaxUploadSize, $wgLang;
559
560 // write out the content
561 if( fwrite( $this->fp, $data_packet ) === false ){
562 wfDebug( __METHOD__ ." ::could-not-write-to-file\n" );
563 $this->status = Status::newFatal( 'HTTP::could-not-write-to-file' );
564 return 0;
565 }
566
567 // check file size:
568 clearstatcache();
569 $this->current_fsize = filesize( $this->target_file_path );
570
571 if( $this->current_fsize > $wgMaxUploadSize ){
572 wfDebug( __METHOD__ . " ::http download too large\n" );
573 $this->status = Status::newFatal( 'HTTP::file-has-grown-beyond-upload-limit-killing: downloaded more than ' .
574 $wgLang->formatSize( $wgMaxUploadSize ) . ' ' );
575 return 0;
576 }
577 // if more than session_update_interval second have passed update_session_progress
578 if( $this->do_close_session_update && $this->upload_session_key &&
579 ( ( time() - $this->prevTime ) > $this->session_update_interval ) ) {
580 $this->prevTime = time();
581 $session_status = $this->update_session_progress();
582 if( !$session_status->isOK() ){
583 $this->status = $session_status;
584 wfDebug( __METHOD__ . ' update session failed or was canceled');
585 return 0;
586 }
587 }
588 return strlen( $data_packet );
589 }
590
591 public function update_session_progress(){
592 global $wgSessionsInMemcached;
593 $status = Status::newGood();
594 // start the session (if necessary)
595 if( !$wgSessionsInMemcached ){
596 wfSuppressWarnings();
597 if( session_start() === false ){
598 wfDebug( __METHOD__ . ' could not start session' );
599 exit( 0 );
600 }
601 wfRestoreWarnings();
602 }
603 $sd =& $_SESSION['wsDownload'][ $this->upload_session_key ];
604 // check if the user canceled the request:
605 if( isset( $sd['user_cancel'] ) && $sd['user_cancel'] == true ){
606 //@@todo kill the download
607 return Status::newFatal( 'user-canceled-request' );
608 }
609 // update the progress bytes download so far:
610 $sd['loaded'] = $this->current_fsize;
611
612 // close down the session so we can other http queries can get session updates:
613 if( !$wgSessionsInMemcached )
614 session_write_close();
615
616 return $status;
617 }
618
619 public function close(){
620 // do a final session update:
621 if( $this->do_close_session_update ){
622 $this->update_session_progress();
623 }
624 // close up the file handle:
625 if( false === fclose( $this->fp ) ){
626 $this->status = Status::newFatal( 'HTTP::could-not-close-file' );
627 }
628 }
629
630 }