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)
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
;
22 wfDebug( 'http error: ' . $status->getWikiText() );
28 * Simple wrapper for Http::request( 'GET' )
30 public static function get( $url, $timeout = false, $opts = array() ) {
31 global $wgSyncHTTPTimeout;
33 $opts['timeout'] = $timeout;
34 return Http
::request( 'GET', $url, $opts );
38 * Simple wrapper for Http::request( 'POST' )
40 public static function post( $url, $opts = array() ) {
41 return Http
::request( 'POST', $url, $opts );
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() ){
52 $head = $headResponse->value
;
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++
);
60 return Status
::newFatal( 'upload-proto-error' );
63 return Status
::newFatal( 'upload-too-many-redirects' );
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] ) );
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 );
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 );
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();
94 * a non blocking request (generally an exit point in the application)
95 * should write to a file location and give updates
98 private static function initBackgroundDownload( $url, $target_file_path, $content_length = null ){
99 global $wgMaxUploadSize, $IP, $wgPhpCli, $wgServer;
100 $status = Status
::newGood();
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();
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;
112 if( $content_length )
113 $_SESSION['wsDownload'][$upload_session_key]['content_length'] = $content_length;
115 // set initial loaded bytes:
116 $_SESSION['wsDownload'][$upload_session_key]['loaded'] = 0;
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.
123 return Status
::newFatal( 'could not run background shell exec' );
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;
128 // return good status
132 static function getUploadSessionKey(){
133 $key = mt_rand( 0, 0x7fffffff );
134 $_SESSION['wsUploadData'][$key] = array();
139 * used to run a session based download. Is initiated via the shell.
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)
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:
155 if( session_start() === false ){
156 wfDebug( __METHOD__
. ' could not start session' );
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');
163 // setup the global user from the session key we just inherited
164 $wgUser = User
::newFromSession();
166 // grab the session data to setup the request:
167 $sd =& $_SESSION['wsDownload'][$upload_session_key];
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'];
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();
177 $req = new HttpRequest( $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
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");
188 // start up the session again:
189 if( session_start() === false ){
190 wfDebug( __METHOD__
. ' ERROR:: Could not start session');
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() )
200 // if status okay process upload using fauxReq to api:
201 if( $status->isOK() ){
202 // setup the FauxRequest
203 $fauxReqData = $sd['mParams'];
205 // Fix boolean parameters
206 foreach( $fauxReqData as $k => $v ) {
208 unset( $fauxReqData[$k] );
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 );
218 //init the mUpload var for the $processor
219 $processor->execute();
220 $processor->getResult()->cleanUpUTF8();
221 $printer = $processor->createPrinterByName( 'json' );
222 $printer->initPrinter( false );
225 $apiUploadResult = ob_get_clean();
227 // the status updates runner will grab the result form the session:
228 $sd['apiUploadResult'] = $apiUploadResult;
230 // close the session:
231 session_write_close();
235 * Check if the URL can be served by localhost
236 * @param $url string Full url to check
239 public static function isLocalURL( $url ) {
240 global $wgCommandLineMode, $wgConf;
241 if ( $wgCommandLineMode ) {
247 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
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];
256 $domain = $domainPart;
258 $domain = $domainPart . '.' . $domain;
260 if ( $wgConf->isLocalVHost( $domain ) ) {
269 * Return a standard user-agent we can use for external requests.
271 public static function userAgent() {
273 return "MediaWiki/$wgVersion";
278 var $target_file_path;
279 var $upload_session_key;
280 var $supportedCurlOpts = array(
281 'CURLOPT_SSL_VERIFYHOST',
284 'CURLOPT_FOLLOWLOCATION',
285 'CURLOPT_FAILONERROR'
287 function __construct( $url, $opt ){
288 global $wgSyncHTTPTimeout;
289 // double check that it's a valid url:
292 // set the timeout to default sync timeout (unless the timeout option is provided)
293 $this->timeout
= ( isset( $opt['timeout'] ) ) ?
$opt['timeout'] : $wgSyncHTTPTimeout;
294 //check special key default
295 if($this->timeout
== 'default'){
296 $opts['timeout'] = $wgSyncHTTPTimeout;
299 $this->method
= ( isset( $opt['method'] ) ) ?
$opt['method'] : 'GET';
300 $this->target_file_path
= ( isset( $opt['target_file_path'] ) ) ?
$opt['target_file_path'] : false;
301 $this->upload_session_key
= ( isset( $opt['upload_session_key'] ) ) ?
$opt['upload_session_key'] : false;
302 $this->headers_only
= ( isset( $opt['headers_only'] ) ) ?
$opt['headers_only'] : false;
303 $this->do_close_session_update
= isset( $opt['do_close_session_update'] );
304 $this->postData
= isset( $opt['postdata'] ) ?
$opt['postdata'] : '';
306 $this->curlOpt
= array();
307 //check for some curl options:
308 foreach($this->supportedCurlOpts
as $curlOpt){
309 if(isset($opt[ $curlOpt ])){
310 $this->curlOpt
[$curlOpt] = $opt[ $curlOpt ];
316 * Get the contents of a file by HTTP
317 * @param $url string Full URL to act on
318 * @param $Opt associative array Optional array of options:
319 * 'method' => 'GET', 'POST' etc.
320 * 'target_file_path' => if curl should output to a target file
321 * 'adapter' => 'curl', 'soket'
323 public function doRequest() {
324 # Make sure we have a valid url
325 if( !UploadFromUrl
::isValidURI( $this->url
) )
326 return Status
::newFatal('bad-url');
328 # Use curl if available
329 if ( function_exists( 'curl_init' ) ) {
330 return $this->doCurlReq();
332 return $this->doPhpReq();
336 private function doCurlReq(){
337 global $wgHTTPProxy, $wgTitle;
339 $status = Status
::newGood();
340 $c = curl_init( $this->url
);
343 if ( Http
::isLocalURL( $this->url
) ) {
344 curl_setopt( $c, CURLOPT_PROXY
, 'localhost:80' );
345 } else if ( $wgHTTPProxy ) {
346 curl_setopt( $c, CURLOPT_PROXY
, $wgHTTPProxy );
349 curl_setopt( $c, CURLOPT_TIMEOUT
, $this->timeout
);
350 curl_setopt( $c, CURLOPT_USERAGENT
, Http
::userAgent() );
352 //set any curl specific opts:
353 foreach($this->curlOpt
as $optKey => $optVal){
354 curl_setopt($c, constant( $optKey ), $optVal);
357 if ( $this->headers_only
) {
358 curl_setopt( $c, CURLOPT_NOBODY
, true );
359 curl_setopt( $c, CURLOPT_HEADER
, true );
360 } elseif ( $this->method
== 'POST' ) {
361 curl_setopt( $c, CURLOPT_POST
, true );
362 curl_setopt( $c, CURLOPT_POSTFIELDS
, $this->postData
);
363 // Suppress 'Expect: 100-continue' header, as some servers
364 // will reject it with a 417 and Curl won't auto retry
365 // with HTTP 1.0 fallback
366 curl_setopt( $c, CURLOPT_HTTPHEADER
, array( 'Expect:' ) );
368 curl_setopt( $c, CURLOPT_CUSTOMREQUEST
, $this->method
);
371 # Set the referer to $wgTitle, even in command-line mode
372 # This is useful for interwiki transclusion, where the foreign
373 # server wants to know what the referring page is.
374 # $_SERVER['REQUEST_URI'] gives a less reliable indication of the
376 if ( is_object( $wgTitle ) ) {
377 curl_setopt( $c, CURLOPT_REFERER
, $wgTitle->getFullURL() );
380 // set the write back function (if we are writing to a file)
381 if( $this->target_file_path
){
382 $cwrite = new simpleFileWriter( $this->target_file_path
,
383 $this->upload_session_key
,
384 $this->do_close_session_update
386 if( !$cwrite->status
->isOK() ){
387 wfDebug( __METHOD__
. "ERROR in setting up simpleFileWriter\n" );
388 $status = $cwrite->status
;
391 curl_setopt( $c, CURLOPT_WRITEFUNCTION
, array( $cwrite, 'callbackWriteBody' ) );
394 // start output grabber:
395 if( !$this->target_file_path
)
398 //run the actual curl_exec:
400 if ( false === curl_exec( $c ) ) {
401 $error_txt ='Error sending request: #' . curl_errno( $c ) .' '. curl_error( $c );
402 wfDebug( __METHOD__
. $error_txt . "\n" );
403 $status = Status
::newFatal( $error_txt );
405 } catch ( Exception
$e ) {
406 // do something with curl exec error?
408 // if direct request output the results to the stats value:
409 if( !$this->target_file_path
&& $status->isOK() ){
410 $status->value
= ob_get_contents();
413 // if we wrote to a target file close up or return error
414 if( $this->target_file_path
){
416 if( !$cwrite->status
->isOK() ){
417 return $cwrite->status
;
421 if ( $this->headers_only
) {
422 $headers = explode( "\n", $status->value
);
423 $headerArray = array();
424 foreach ( $headers as $header ) {
425 if ( !strlen( trim( $header ) ) )
427 $headerParts = explode( ':', $header, 2 );
428 if ( count( $headerParts ) == 1 ) {
429 $headerArray[] = trim( $header );
431 list( $key, $val ) = $headerParts;
432 $headerArray[trim( $key )] = trim( $val );
435 $status->value
= $headerArray;
437 # Don't return the text of error messages, return false on error
438 $retcode = curl_getinfo( $c, CURLINFO_HTTP_CODE
);
439 if ( $retcode != 200 ) {
440 wfDebug( __METHOD__
. ": HTTP return code $retcode\n" );
441 $status = Status
::newFatal( "HTTP return code $retcode\n" );
443 # Don't return truncated output
444 $errno = curl_errno( $c );
445 if ( $errno != CURLE_OK
) {
446 $errstr = curl_error( $c );
447 wfDebug( __METHOD__
. ": CURL error code $errno: $errstr\n" );
448 $status = Status
::newFatal( " CURL error code $errno: $errstr\n" );
454 // return the result obj
458 public function doPhpReq(){
459 global $wgTitle, $wgHTTPProxy;
460 # Check for php.ini allow_url_fopen
461 if( !ini_get( 'allow_url_fopen' ) ){
462 return Status
::newFatal( 'allow_url_fopen needs to be enabled for http copy to work' );
465 // start with good status:
466 $status = Status
::newGood();
468 if ( $this->headers_only
) {
469 $status->value
= get_headers( $this->url
, 1 );
474 $headers = array( "User-Agent: " . Http
::userAgent() );
475 if ( is_object( $wgTitle ) ) {
476 $headers[] = "Referer: ". $wgTitle->getFullURL();
479 if( strcasecmp( $this->method
, 'post' ) == 0 ) {
480 // Required for HTTP 1.0 POSTs
481 $headers[] = "Content-Length: 0";
483 $fcontext = stream_context_create ( array(
485 'method' => $this->method
,
486 'header' => implode( "\r\n", $headers ),
487 'timeout' => $this->timeout
)
490 $fh = fopen( $this->url
, "r", false, $fcontext);
492 // set the write back function (if we are writing to a file)
493 if( $this->target_file_path
){
494 $cwrite = new simpleFileWriter( $this->target_file_path
, $this->upload_session_key
, $this->do_close_session_update
);
495 if( !$cwrite->status
->isOK() ){
496 wfDebug( __METHOD__
. "ERROR in setting up simpleFileWriter\n" );
497 $status = $cwrite->status
;
501 // read $fh into the simpleFileWriter (grab in 64K chunks since its likely a ~large~ media file)
502 while ( !feof( $fh ) ) {
503 $contents = fread( $fh, 65536 );
504 $cwrite->callbackWriteBody( $fh, $contents );
507 // check for simpleFileWriter error:
508 if( !$cwrite->status
->isOK() ){
509 return $cwrite->status
;
512 // read $fh into status->value
513 $status->value
= @stream_get_contents
( $fh );
515 //close the url file wrapper
519 if( $status->value
=== false ){
520 $status->error( 'file_get_contents-failed' );
528 * a simpleFileWriter with session id updates
530 class simpleFileWriter
{
531 var $target_file_path;
533 var $session_id = null;
534 var $session_update_interval = 0; // how often to update the session while downloading
536 function simpleFileWriter( $target_file_path, $upload_session_key, $do_close_session_update = false ){
537 $this->target_file_path
= $target_file_path;
538 $this->upload_session_key
= $upload_session_key;
539 $this->status
= Status
::newGood();
540 $this->do_close_session_update
= $do_close_session_update;
542 $this->fp
= fopen( $this->target_file_path
, 'w' );
543 if( $this->fp
=== false ){
544 $this->status
= Status
::newFatal( 'HTTP::could-not-open-file-for-writing' );
547 $this->prevTime
= time();
550 public function callbackWriteBody( $ch, $data_packet ){
551 global $wgMaxUploadSize, $wgLang;
553 // write out the content
554 if( fwrite( $this->fp
, $data_packet ) === false ){
555 wfDebug( __METHOD__
." ::could-not-write-to-file\n" );
556 $this->status
= Status
::newFatal( 'HTTP::could-not-write-to-file' );
562 $this->current_fsize
= filesize( $this->target_file_path
);
564 if( $this->current_fsize
> $wgMaxUploadSize ){
565 wfDebug( __METHOD__
. " ::http download too large\n" );
566 $this->status
= Status
::newFatal( 'HTTP::file-has-grown-beyond-upload-limit-killing: downloaded more than ' .
567 $wgLang->formatSize( $wgMaxUploadSize ) . ' ' );
570 // if more than session_update_interval second have passed update_session_progress
571 if( $this->do_close_session_update
&& $this->upload_session_key
&&
572 ( ( time() - $this->prevTime
) > $this->session_update_interval
) ) {
573 $this->prevTime
= time();
574 $session_status = $this->update_session_progress();
575 if( !$session_status->isOK() ){
576 $this->status
= $session_status;
577 wfDebug( __METHOD__
. ' update session failed or was canceled');
581 return strlen( $data_packet );
584 public function update_session_progress(){
585 global $wgSessionsInMemcached;
586 $status = Status
::newGood();
587 // start the session (if necessary)
588 if( !$wgSessionsInMemcached ){
589 if( @session_start
() === false){
590 wfDebug( __METHOD__
. ' could not start session' );
594 $sd =& $_SESSION['wsDownload'][ $this->upload_session_key
];
595 // check if the user canceled the request:
596 if( isset( $sd['user_cancel'] ) && $sd['user_cancel'] == true ){
597 //@@todo kill the download
598 return Status
::newFatal( 'user-canceled-request' );
600 // update the progress bytes download so far:
601 $sd['loaded'] = $this->current_fsize
;
603 // close down the session so we can other http queries can get session updates:
604 if( !$wgSessionsInMemcached )
605 session_write_close();
610 public function close(){
611 // do a final session update:
612 if( $this->do_close_session_update
){
613 $this->update_session_progress();
615 // close up the file handle:
616 if( false === fclose( $this->fp
) ){
617 $this->status
= Status
::newFatal( 'HTTP::could-not-close-file' );