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)
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
;
21 wfDebug( 'http error: ' . $status->getWikiText() );
26 * Simple wrapper for Http::request( 'GET' )
28 public static function get( $url, $timeout = false) {
31 $opts['timeout'] = $timeout;
32 return Http
::request( 'GET', $url, $opts );
36 * Simple wrapper for Http::request( 'POST' )
38 public static function post( $url, $opts = array() ) {
39 return Http
::request( 'POST', $url, $opts );
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 $head = get_headers( $url, 1 );
47 // check for redirects:
48 if( isset( $head['Location'] ) && strrpos( $head[0], '302' ) !== false ){
49 if( $redirectCount < $wgMaxRedirects ){
50 if( UploadFromUrl
::isValidURI( $head['Location'] ) ){
51 return self
::doDownload( $head['Location'], $target_file_path , $dl_mode, $redirectCount++
);
53 return Status
::newFatal( 'upload-proto-error' );
56 return Status
::newFatal( 'upload-too-many-redirects' );
59 // we did not get a 200 ok response:
60 if( strrpos( $head[0], '200 OK' ) === false ){
61 return Status
::newFatal( 'upload-http-error', htmlspecialchars( $head[0] ) );
64 $content_length = ( isset( $head['Content-Length'] ) ) ?
$head['Content-Length'] : null;
65 if( $content_length ){
66 if( $content_length > $wgMaxUploadSize ){
67 return Status
::newFatal( 'requested file length ' . $content_length . ' is greater than $wgMaxUploadSize: ' . $wgMaxUploadSize );
71 // check if we can find phpCliPath (for doing a background shell request to php to do the download:
72 if( $wgPhpCli && wfShellExecEnabled() && $dl_mode == self
::ASYNC_DOWNLOAD
){
73 wfDebug( __METHOD__
. "\ASYNC_DOWNLOAD\n" );
74 // setup session and shell call:
75 return self
::initBackgroundDownload( $url, $target_file_path, $content_length );
76 } else if( $dl_mode == self
::SYNC_DOWNLOAD
){
77 wfDebug( __METHOD__
. "\nSYNC_DOWNLOAD\n" );
78 // SYNC_DOWNLOAD download as much as we can in the time we have to execute
79 $opts['method'] = 'GET';
80 $opts['target_file_path'] = $target_file_path;
81 $req = new HttpRequest( $url, $opts );
82 return $req->doRequest();
87 * a non blocking request (generally an exit point in the application)
88 * should write to a file location and give updates
91 private function initBackgroundDownload( $url, $target_file_path, $content_length = null ){
92 global $wgMaxUploadSize, $IP, $wgPhpCli;
93 $status = Status
::newGood();
95 // generate a session id with all the details for the download (pid, target_file_path )
96 $upload_session_key = self
::getUploadSessionKey();
97 $session_id = session_id();
99 // store the url and target path:
100 $_SESSION['wsDownload'][$upload_session_key]['url'] = $url;
101 $_SESSION['wsDownload'][$upload_session_key]['target_file_path'] = $target_file_path;
103 if( $content_length )
104 $_SESSION['wsDownload'][$upload_session_key]['content_length'] = $content_length;
106 // set initial loaded bytes:
107 $_SESSION['wsDownload'][$upload_session_key]['loaded'] = 0;
109 // run the background download request:
110 $cmd = $wgPhpCli . ' ' . $IP . "/maintenance/http_session_download.php --sid {$session_id} --usk {$upload_session_key}";
111 $pid = wfShellBackgroundExec( $cmd, $retval );
112 // the pid is not of much use since we won't be visiting this same apache any-time soon.
114 return Status
::newFatal( 'could not run background shell exec' );
116 // update the status value with the $upload_session_key (for the user to check on the status of the upload)
117 $status->value
= $upload_session_key;
119 // return good status
123 function getUploadSessionKey(){
124 $key = mt_rand( 0, 0x7fffffff );
125 $_SESSION['wsUploadData'][$key] = array();
130 * used to run a session based download. Is initiated via the shell.
132 * @param $session_id String: the session id to grab download details from
133 * @param $upload_session_key String: the key of the given upload session
134 * (a given client could have started a few http uploads at once)
136 public static function doSessionIdDownload( $session_id, $upload_session_key ){
137 global $wgUser, $wgEnableWriteAPI, $wgAsyncHTTPTimeout;
138 wfDebug( __METHOD__
. "\n\ndoSessionIdDownload\n\n" );
139 // set session to the provided key:
140 session_id( $session_id );
142 if( session_start() === false ){
143 wfDebug( __METHOD__
. ' could not start session' );
145 //get all the vars we need from session_id
146 if(!isset($_SESSION[ 'wsDownload' ][$upload_session_key])){
147 wfDebug( __METHOD__
.' Error:could not find upload session');
150 // setup the global user from the session key we just inherited
151 $wgUser = User
::newFromSession();
153 // grab the session data to setup the request:
154 $sd =& $_SESSION['wsDownload'][$upload_session_key];
155 // close down the session so we can other http queries can get session updates:
156 session_write_close();
158 $req = new HttpRequest( $sd['url'], array(
159 'target_file_path' => $sd['target_file_path'],
160 'upload_session_key'=> $upload_session_key,
161 'timeout' => $wgAsyncHTTPTimeout
163 // run the actual request .. (this can take some time)
164 wfDebug( __METHOD__
. "do Request: " . $sd['url'] . ' tf: ' . $sd['target_file_path'] );
165 $status = $req->doRequest();
166 //wfDebug("done with req status is: ". $status->isOK(). ' '.$status->getWikiText(). "\n");
168 // start up the session again:
169 if( session_start() === false ){
170 wfDebug( __METHOD__
. ' ERROR:: Could not start session');
172 // grab the updated session data pointer
173 $sd =& $_SESSION['wsDownload'][$upload_session_key];
174 // if error update status:
175 if( !$status->isOK() ){
176 $sd['apiUploadResult'] = ApiFormatJson
::getJsonEncode(
177 array( 'error' => $status->getWikiText() )
180 // if status okay process upload using fauxReq to api:
181 if( $status->isOK() ){
182 // setup the FauxRequest
183 $fauxReqData = $sd['mParams'];
184 $fauxReqData['action'] = 'upload';
185 $fauxReqData['format'] = 'json';
186 $fauxReqData['internalhttpsession'] = $upload_session_key;
188 // evil but no other clean way about it:
189 $faxReq = new FauxRequest( $fauxReqData, true );
190 $processor = new ApiMain( $faxReq, $wgEnableWriteAPI );
192 //init the mUpload var for the $processor
193 $processor->execute();
194 $processor->getResult()->cleanUpUTF8();
195 $printer = $processor->createPrinterByName( 'json' );
196 $printer->initPrinter( false );
199 $apiUploadResult = ob_get_clean();
201 wfDebug( __METHOD__
. "\n\n got api result:: $apiUploadResult \n" );
202 // the status updates runner will grab the result form the session:
203 $sd['apiUploadResult'] = $apiUploadResult;
205 // close the session:
206 session_write_close();
210 * Check if the URL can be served by localhost
211 * @param $url string Full url to check
214 public static function isLocalURL( $url ) {
215 global $wgCommandLineMode, $wgConf;
216 if ( $wgCommandLineMode ) {
222 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
225 $domainParts = explode( '.', $host );
226 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
227 $domainParts = array_reverse( $domainParts );
228 for ( $i = 0; $i < count( $domainParts ); $i++
) {
229 $domainPart = $domainParts[$i];
231 $domain = $domainPart;
233 $domain = $domainPart . '.' . $domain;
235 if ( $wgConf->isLocalVHost( $domain ) ) {
244 * Return a standard user-agent we can use for external requests.
246 public static function userAgent() {
248 return "MediaWiki/$wgVersion";
252 var $target_file_path;
253 var $upload_session_key;
255 function __construct( $url, $opt ){
256 global $wgSyncHTTPTimeout;
258 // set the timeout to default sync timeout (unless the timeout option is provided)
259 $this->timeout
= ( isset( $opt['timeout'] ) ) ?
$opt['timeout'] : $wgSyncHTTPTimeout;
260 $this->method
= ( isset( $opt['method'] ) ) ?
$opt['method'] : 'GET';
261 $this->target_file_path
= ( isset( $opt['target_file_path'] ) ) ?
$opt['target_file_path'] : false;
262 $this->upload_session_key
= ( isset( $opt['upload_session_key'] ) ) ?
$opt['upload_session_key'] : false;
266 * Get the contents of a file by HTTP
267 * @param $url string Full URL to act on
268 * @param $Opt associative array Optional array of options:
269 * 'method' => 'GET', 'POST' etc.
270 * 'target_file_path' => if curl should output to a target file
271 * 'adapter' => 'curl', 'soket'
273 public function doRequest() {
274 # Use curl if available
275 if ( function_exists( 'curl_init' ) ) {
276 return $this->doCurlReq();
278 return $this->doPhpReq();
282 private function doCurlReq(){
283 global $wgHTTPProxy, $wgTitle;
285 $status = Status
::newGood();
286 $c = curl_init( $this->url
);
289 if ( Http
::isLocalURL( $this->url
) ) {
290 curl_setopt( $c, CURLOPT_PROXY
, 'localhost:80' );
291 } else if ( $wgHTTPProxy ) {
292 curl_setopt( $c, CURLOPT_PROXY
, $wgHTTPProxy );
295 curl_setopt( $c, CURLOPT_TIMEOUT
, $this->timeout
);
296 curl_setopt( $c, CURLOPT_USERAGENT
, Http
::userAgent() );
298 if ( $this->method
== 'POST' ) {
299 curl_setopt( $c, CURLOPT_POST
, true );
300 curl_setopt( $c, CURLOPT_POSTFIELDS
, '' );
302 curl_setopt( $c, CURLOPT_CUSTOMREQUEST
, $this->method
);
305 # Set the referer to $wgTitle, even in command-line mode
306 # This is useful for interwiki transclusion, where the foreign
307 # server wants to know what the referring page is.
308 # $_SERVER['REQUEST_URI'] gives a less reliable indication of the
310 if ( is_object( $wgTitle ) ) {
311 curl_setopt( $c, CURLOPT_REFERER
, $wgTitle->getFullURL() );
314 // set the write back function (if we are writing to a file)
315 if( $this->target_file_path
){
316 $cwrite = new simpleFileWriter( $this->target_file_path
, $this->upload_session_key
);
317 if( !$cwrite->status
->isOK() ){
318 wfDebug( __METHOD__
. "ERROR in setting up simpleFileWriter\n" );
319 $status = $cwrite->status
;
321 curl_setopt( $c, CURLOPT_WRITEFUNCTION
, array( $cwrite, 'callbackWriteBody' ) );
324 // start output grabber:
325 if( !$this->target_file_path
)
328 //run the actual curl_exec:
330 if ( false === curl_exec( $c ) ) {
331 $error_txt ='Error sending request: #' . curl_errno( $c ) .' '. curl_error( $c );
332 wfDebug( __METHOD__
. $error_txt . "\n" );
333 $status = Status
::newFatal( $error_txt );
335 } catch ( Exception
$e ) {
336 // do something with curl exec error?
338 // if direct request output the results to the stats value:
339 if( !$this->target_file_path
&& $status->isOK() ){
340 $status->value
= ob_get_contents();
343 // if we wrote to a target file close up or return error
344 if( $this->target_file_path
){
346 if( !$cwrite->status
->isOK() ){
347 return $cwrite->status
;
351 # Don't return the text of error messages, return false on error
352 $retcode = curl_getinfo( $c, CURLINFO_HTTP_CODE
);
353 if ( $retcode != 200 ) {
354 wfDebug( __METHOD__
. ": HTTP return code $retcode\n" );
355 $status = Status
::newFatal( "HTTP return code $retcode\n" );
357 # Don't return truncated output
358 $errno = curl_errno( $c );
359 if ( $errno != CURLE_OK
) {
360 $errstr = curl_error( $c );
361 wfDebug( __METHOD__
. ": CURL error code $errno: $errstr\n" );
362 $status = Status
::newFatal( " CURL error code $errno: $errstr\n" );
366 // return the result obj
370 public function doPhpReq(){
371 #$use file_get_contents...
372 # This doesn't have local fetch capabilities...
374 $headers = array( "User-Agent: " . Http
:: userAgent() );
375 if( strcasecmp( $method, 'post' ) == 0 ) {
376 // Required for HTTP 1.0 POSTs
377 $headers[] = "Content-Length: 0";
382 'header' => implode( "\r\n", $headers ),
383 'timeout' => $timeout ) );
384 $ctx = stream_context_create( $opts );
386 $status->value
= file_get_contents( $url, false, $ctx );
387 if( !$status->value
){
388 $status->error( 'file_get_contents-failed' );
396 * a simpleFileWriter with session id updates
398 class simpleFileWriter
{
399 var $target_file_path;
401 var $session_id = null;
402 var $session_update_interval = 0; // how often to update the session while downloading
404 function simpleFileWriter( $target_file_path, $upload_session_key ){
405 $this->target_file_path
= $target_file_path;
406 $this->upload_session_key
= $upload_session_key;
407 $this->status
= Status
::newGood();
409 $this->fp
= fopen( $this->target_file_path
, 'w' );
410 if( $this->fp
=== false ){
411 $this->status
= Status
::newFatal( 'HTTP::could-not-open-file-for-writing' );
414 $this->prevTime
= time();
417 public function callbackWriteBody($ch, $data_packet){
418 global $wgMaxUploadSize;
420 // write out the content
421 if( fwrite( $this->fp
, $data_packet ) === false ){
422 wfDebug( __METHOD__
." ::could-not-write-to-file\n" );
423 $this->status
= Status
::newFatal( 'HTTP::could-not-write-to-file' );
429 $this->current_fsize
= filesize( $this->target_file_path
);
431 if( $this->current_fsize
> $wgMaxUploadSize ){
432 wfDebug( __METHOD__
. " ::http download too large\n" );
433 $this->status
= Status
::newFatal( 'HTTP::file-has-grown-beyond-upload-limit-killing: downloaded more than ' .
434 Language
::formatSize( $wgMaxUploadSize ) . ' ' );
438 // if more than session_update_interval second have passed update_session_progress
439 if( $this->upload_session_key
&& ( ( time() - $this->prevTime
) > $this->session_update_interval
) ) {
440 $this->prevTime
= time();
441 $session_status = $this->update_session_progress();
442 if( !$session_status->isOK() ){
443 $this->status
= $session_status;
444 wfDebug( __METHOD__
. ' update session failed or was canceled');
448 return strlen( $data_packet );
451 public function update_session_progress(){
452 $status = Status
::newGood();
454 if( session_start() === false){
455 wfDebug( __METHOD__
. ' could not start session' );
458 $sd =& $_SESSION['wsDownload'][$this->upload_session_key
];
459 // check if the user canceled the request:
460 if( $sd['user_cancel'] == true ){
462 return Status
::newFatal( 'user-canceled-request' );
464 // update the progress bytes download so far:
465 $sd['loaded'] = $this->current_fsize
;
466 wfDebug( __METHOD__
. ': set session loaded amount to: ' . $sd['loaded'] . "\n");
467 // close down the session so we can other http queries can get session updates:
468 session_write_close();
472 public function close(){
473 // do a final session update:
474 $this->update_session_progress();
475 // close up the file handle:
476 if( false === fclose( $this->fp
) ){
477 $this->status
= Status
::newFatal( 'HTTP::could-not-close-file' );