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