remove debugging code *stab*
[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 #check for php.ini allow_url_fopen
409 if( !ini_get( 'allow_url_fopen' ) ){
410 return Status::newFatal( 'allow_url_fopen needs to be enabled for http copy to work' );
411 }
412
413 //start with good status:
414 $status = Status::newGood();
415
416 if ( $this->headers_only ) {
417 $status->value = get_headers( $this->url, 1 );
418 return $status;
419 }
420
421 //setup the headers
422 $headers = array( "User-Agent: " . Http :: userAgent() );
423 if ( is_object( $wgTitle ) ) {
424 $headers[] = "Referer: ". $wgTitle->getFullURL();
425 }
426
427 if( strcasecmp( $this->method, 'post' ) == 0 ) {
428 // Required for HTTP 1.0 POSTs
429 $headers[] = "Content-Length: 0";
430 }
431 $fcontext = stream_context_create ( array(
432 'http' => array(
433 'method' => $this->method,
434 'header' => implode( "\r\n", $headers ),
435 'timeout' => $this->timeout )
436 )
437 );
438
439 $fh = fopen( $this->url, "r", false, $fcontext);
440
441 // set the write back function (if we are writing to a file)
442 if( $this->target_file_path ){
443 $cwrite = new simpleFileWriter( $this->target_file_path, $this->upload_session_key );
444 if( !$cwrite->status->isOK() ){
445 wfDebug( __METHOD__ . "ERROR in setting up simpleFileWriter\n" );
446 $status = $cwrite->status;
447 return $status;
448 }
449 //read $fh into the simpleFileWriter (grab in 64K chunks since its likely a media file)
450 while ( !feof( $fh )) {
451 $contents = fread($fh, 65536);
452 $cwrite->callbackWriteBody($fh, $contents );
453 }
454
455 $cwrite->close();
456 //check for simpleFileWriter error:
457 if( !$cwrite->status->isOK() ){
458 return $cwrite->status;
459 }
460 } else {
461 //read $fh into status->value
462 $status->value = @stream_get_contents( $fh );
463 }
464 //close the url file wrapper
465 fclose( $fh );
466
467 //check for "false"
468 if( $status->value === false ){
469 $status->error( 'file_get_contents-failed' );
470 }
471 return $status;
472 }
473
474 }
475
476 /**
477 * a simpleFileWriter with session id updates
478 */
479 class simpleFileWriter {
480 var $target_file_path;
481 var $status = null;
482 var $session_id = null;
483 var $session_update_interval = 0; // how often to update the session while downloading
484
485 function simpleFileWriter( $target_file_path, $upload_session_key ){
486 $this->target_file_path = $target_file_path;
487 $this->upload_session_key = $upload_session_key;
488 $this->status = Status::newGood();
489 // open the file:
490 $this->fp = fopen( $this->target_file_path, 'w' );
491 if( $this->fp === false ){
492 $this->status = Status::newFatal( 'HTTP::could-not-open-file-for-writing' );
493 }
494 // true start time
495 $this->prevTime = time();
496 }
497
498 public function callbackWriteBody($ch, $data_packet){
499 global $wgMaxUploadSize;
500
501 // write out the content
502 if( fwrite( $this->fp, $data_packet ) === false ){
503 wfDebug( __METHOD__ ." ::could-not-write-to-file\n" );
504 $this->status = Status::newFatal( 'HTTP::could-not-write-to-file' );
505 return 0;
506 }
507
508 // check file size:
509 clearstatcache();
510 $this->current_fsize = filesize( $this->target_file_path );
511
512 if( $this->current_fsize > $wgMaxUploadSize ){
513 wfDebug( __METHOD__ . " ::http download too large\n" );
514 $this->status = Status::newFatal( 'HTTP::file-has-grown-beyond-upload-limit-killing: downloaded more than ' .
515 Language::formatSize( $wgMaxUploadSize ) . ' ' );
516 return 0;
517 }
518
519 // if more than session_update_interval second have passed update_session_progress
520 if( $this->upload_session_key && ( ( time() - $this->prevTime ) > $this->session_update_interval ) ) {
521 $this->prevTime = time();
522 $session_status = $this->update_session_progress();
523 if( !$session_status->isOK() ){
524 $this->status = $session_status;
525 wfDebug( __METHOD__ . ' update session failed or was canceled');
526 return 0;
527 }
528 }
529 return strlen( $data_packet );
530 }
531
532 public function update_session_progress(){
533 $status = Status::newGood();
534 // start the session
535 if( session_start() === false){
536 wfDebug( __METHOD__ . ' could not start session' );
537 exit( 0 );
538 }
539 $sd =& $_SESSION['wsDownload'][$this->upload_session_key];
540 // check if the user canceled the request:
541 if( isset( $sd['user_cancel'] ) && $sd['user_cancel'] == true ){
542 // kill the download
543 return Status::newFatal( 'user-canceled-request' );
544 }
545 // update the progress bytes download so far:
546 $sd['loaded'] = $this->current_fsize;
547 wfDebug( __METHOD__ . ': set session loaded amount to: ' . $sd['loaded'] . "\n");
548 // close down the session so we can other http queries can get session updates:
549 session_write_close();
550 return $status;
551 }
552
553 public function close(){
554 // do a final session update:
555 $this->update_session_progress();
556 // close up the file handle:
557 if( false === fclose( $this->fp ) ){
558 $this->status = Status::newFatal( 'HTTP::could-not-close-file' );
559 }
560 }
561
562 }