MediaWiki  REL1_21
SpecialUploadStash.php
Go to the documentation of this file.
00001 <?php
00035 class SpecialUploadStash extends UnlistedSpecialPage {
00036         // UploadStash
00037         private $stash;
00038 
00039         // Since we are directly writing the file to STDOUT,
00040         // we should not be reading in really big files and serving them out.
00041         //
00042         // We also don't want people using this as a file drop, even if they
00043         // share credentials.
00044         //
00045         // This service is really for thumbnails and other such previews while
00046         // uploading.
00047         const MAX_SERVE_BYTES = 1048576; // 1MB
00048 
00049         public function __construct() {
00050                 parent::__construct( 'UploadStash', 'upload' );
00051                 try {
00052                         $this->stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
00053                 } catch ( UploadStashNotAvailableException $e ) {
00054                 }
00055         }
00056 
00063         public function execute( $subPage ) {
00064                 $this->checkPermissions();
00065 
00066                 if ( $subPage === null || $subPage === '' ) {
00067                         return $this->showUploads();
00068                 }
00069                 return $this->showUpload( $subPage );
00070         }
00071 
00080         public function showUpload( $key ) {
00081                 // prevent callers from doing standard HTML output -- we'll take it from here
00082                 $this->getOutput()->disable();
00083 
00084                 try {
00085                         $params = $this->parseKey( $key );
00086                         if ( $params['type'] === 'thumb' ) {
00087                                 return $this->outputThumbFromStash( $params['file'], $params['params'] );
00088                         } else {
00089                                 return $this->outputLocalFile( $params['file'] );
00090                         }
00091                 } catch( UploadStashFileNotFoundException $e ) {
00092                         $code = 404;
00093                         $message = $e->getMessage();
00094                 } catch( UploadStashZeroLengthFileException $e ) {
00095                         $code = 500;
00096                         $message = $e->getMessage();
00097                 } catch( UploadStashBadPathException $e ) {
00098                         $code = 500;
00099                         $message = $e->getMessage();
00100                 } catch( SpecialUploadStashTooLargeException $e ) {
00101                         $code = 500;
00102                         $message = 'Cannot serve a file larger than ' . self::MAX_SERVE_BYTES . ' bytes. ' . $e->getMessage();
00103                 } catch( Exception $e ) {
00104                         $code = 500;
00105                         $message = $e->getMessage();
00106                 }
00107 
00108                 throw new HttpError( $code, $message );
00109         }
00110 
00120         private function parseKey( $key ) {
00121                 $type = strtok( $key, '/' );
00122 
00123                 if ( $type !== 'file' && $type !== 'thumb' ) {
00124                         throw new UploadStashBadPathException( "Unknown type '$type'" );
00125                 }
00126                 $fileName = strtok( '/' );
00127                 $thumbPart = strtok( '/' );
00128                 $file = $this->stash->getFile( $fileName );
00129                 if ( $type === 'thumb' ) {
00130                         $srcNamePos = strrpos( $thumbPart, $fileName );
00131                         if ( $srcNamePos === false || $srcNamePos < 1 ) {
00132                                 throw new UploadStashBadPathException( 'Unrecognized thumb name' );
00133                         }
00134                         $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
00135 
00136                         $handler = $file->getHandler();
00137                         $params = $handler->parseParamString( $paramString );
00138                         return array( 'file' => $file, 'type' => $type, 'params' => $params );
00139                 }
00140 
00141                 return array( 'file' => $file, 'type' => $type );
00142         }
00143 
00152         private function outputThumbFromStash( $file, $params ) {
00153 
00154                 // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb()
00155                 // this is part of our horrible NFS-based system, we create a file on a mount point here, but fetch the scaled file from somewhere else that
00156                 // happens to share it over NFS
00157                 global $wgUploadStashScalerBaseUrl;
00158 
00159                 $flags = 0;
00160                 if ( $wgUploadStashScalerBaseUrl ) {
00161                         $this->outputRemoteScaledThumb( $file, $params, $flags );
00162                 } else {
00163                         $this->outputLocallyScaledThumb( $file, $params, $flags );
00164                 }
00165         }
00166 
00176         private function outputLocallyScaledThumb( $file, $params, $flags ) {
00177 
00178                 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
00179                 // on HTTP caching to ensure this doesn't happen.
00180 
00181                 $flags |= File::RENDER_NOW;
00182 
00183                 $thumbnailImage = $file->transform( $params, $flags );
00184                 if ( !$thumbnailImage ) {
00185                         throw new MWException( 'Could not obtain thumbnail' );
00186                 }
00187 
00188                 // we should have just generated it locally
00189                 if ( !$thumbnailImage->getStoragePath() ) {
00190                         throw new UploadStashFileNotFoundException( "no local path for scaled item" );
00191                 }
00192 
00193                 // now we should construct a File, so we can get mime and other such info in a standard way
00194                 // n.b. mimetype may be different from original (ogx original -> jpeg thumb)
00195                 $thumbFile = new UnregisteredLocalFile( false,
00196                         $this->stash->repo, $thumbnailImage->getStoragePath(), false );
00197                 if ( !$thumbFile ) {
00198                         throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
00199                 }
00200 
00201                 return $this->outputLocalFile( $thumbFile );
00202 
00203         }
00204 
00218         private function outputRemoteScaledThumb( $file, $params, $flags ) {
00219 
00220                 // this global probably looks something like 'http://upload.wikimedia.org/wikipedia/test/thumb/temp'
00221                 // do not use trailing slash
00222                 global $wgUploadStashScalerBaseUrl;
00223                 $scalerBaseUrl = $wgUploadStashScalerBaseUrl;
00224 
00225                 if( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
00226                         // this is apparently a protocol-relative URL, which makes no sense in this context,
00227                         // since this is used for communication that's internal to the application.
00228                         // default to http.
00229                         $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL );
00230                 }
00231 
00232                 // We need to use generateThumbName() instead of thumbName(), because
00233                 // the suffix needs to match the file name for the remote thumbnailer
00234                 // to work
00235                 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
00236                 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
00237                         '/' . rawurlencode( $scalerThumbName );
00238 
00239                 // make a curl call to the scaler to create a thumbnail
00240                 $httpOptions = array(
00241                         'method' => 'GET',
00242                         'timeout' => 'default'
00243                 );
00244                 $req = MWHttpRequest::factory( $scalerThumbUrl, $httpOptions );
00245                 $status = $req->execute();
00246                 if ( ! $status->isOK() ) {
00247                         $errors = $status->getErrorsArray();
00248                         $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 );
00249                         $errorStr .= "\nurl = $scalerThumbUrl\n";
00250                         throw new MWException( $errorStr );
00251                 }
00252                 $contentType = $req->getResponseHeader( "content-type" );
00253                 if ( ! $contentType ) {
00254                         throw new MWException( "Missing content-type header" );
00255                 }
00256                 return $this->outputContents( $req->getContent(), $contentType );
00257         }
00258 
00267         private function outputLocalFile( File $file ) {
00268                 if ( $file->getSize() > self::MAX_SERVE_BYTES ) {
00269                         throw new SpecialUploadStashTooLargeException();
00270                 }
00271                 return $file->getRepo()->streamFile( $file->getPath(),
00272                         array( 'Content-Transfer-Encoding: binary',
00273                                 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' )
00274                 );
00275         }
00276 
00285         private function outputContents( $content, $contentType ) {
00286                 $size = strlen( $content );
00287                 if ( $size > self::MAX_SERVE_BYTES ) {
00288                         throw new SpecialUploadStashTooLargeException();
00289                 }
00290                 self::outputFileHeaders( $contentType, $size );
00291                 print $content;
00292                 return true;
00293         }
00294 
00302         private static function outputFileHeaders( $contentType, $size ) {
00303                 header( "Content-Type: $contentType", true );
00304                 header( 'Content-Transfer-Encoding: binary', true );
00305                 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
00306                 // Bug 53032 - It shouldn't be a problem here, but let's be safe and not cache
00307                 header( 'Cache-Control: private' );
00308                 header( "Content-Length: $size", true );
00309         }
00310 
00318         public static function tryClearStashedUploads( $formData ) {
00319                 if ( isset( $formData['Clear'] ) ) {
00320                         $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
00321                         wfDebug( "stash has: " . print_r( $stash->listFiles(), true ) );
00322                         if ( ! $stash->clear() ) {
00323                                 return Status::newFatal( 'uploadstash-errclear' );
00324                         }
00325                 }
00326                 return Status::newGood();
00327         }
00328 
00334         private function showUploads() {
00335                 // sets the title, etc.
00336                 $this->setHeaders();
00337                 $this->outputHeader();
00338 
00339                 // create the form, which will also be used to execute a callback to process incoming form data
00340                 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
00341 
00342                 $form = new HTMLForm( array(
00343                         'Clear' => array(
00344                                 'type' => 'hidden',
00345                                 'default' => true,
00346                                 'name' => 'clear',
00347                         )
00348                 ), $this->getContext(), 'clearStashedUploads' );
00349                 $form->setSubmitCallback( array( __CLASS__, 'tryClearStashedUploads' ) );
00350                 $form->setTitle( $this->getTitle() );
00351                 $form->setSubmitTextMsg( 'uploadstash-clear' );
00352 
00353                 $form->prepareForm();
00354                 $formResult = $form->tryAuthorizedSubmit();
00355 
00356                 // show the files + form, if there are any, or just say there are none
00357                 $refreshHtml = Html::element( 'a',
00358                         array( 'href' => $this->getTitle()->getLocalURL() ),
00359                         $this->msg( 'uploadstash-refresh' )->text() );
00360                 $files = $this->stash->listFiles();
00361                 if ( $files && count( $files ) ) {
00362                         sort( $files );
00363                         $fileListItemsHtml = '';
00364                         foreach ( $files as $file ) {
00365                                 // TODO: Use Linker::link or even construct the list in plain wikitext
00366                                 $fileListItemsHtml .= Html::rawElement( 'li', array(),
00367                                         Html::element( 'a', array( 'href' =>
00368                                                 $this->getTitle( "file/$file" )->getLocalURL() ), $file )
00369                                 );
00370                         }
00371                         $this->getOutput()->addHtml( Html::rawElement( 'ul', array(), $fileListItemsHtml ) );
00372                         $form->displayForm( $formResult );
00373                         $this->getOutput()->addHtml( Html::rawElement( 'p', array(), $refreshHtml ) );
00374                 } else {
00375                         $this->getOutput()->addHtml( Html::rawElement( 'p', array(),
00376                                 Html::element( 'span', array(), $this->msg( 'uploadstash-nofiles' )->text() )
00377                                 . ' '
00378                                 . $refreshHtml
00379                         ) );
00380                 }
00381 
00382                 return true;
00383         }
00384 }
00385 
00386 class SpecialUploadStashTooLargeException extends MWException {};