X-Git-Url: https://scripts.mit.edu/gitweb/autoinstallsdev/mediawiki.git/blobdiff_plain/19e297c21b10b1b8a3acad5e73fc71dcb35db44a..6932310fd58ebef145fa01eb76edf7150284d8ea:/includes/specials/SpecialUploadStash.php diff --git a/includes/specials/SpecialUploadStash.php b/includes/specials/SpecialUploadStash.php index 48a41a5e..b0bb595e 100644 --- a/includes/specials/SpecialUploadStash.php +++ b/includes/specials/SpecialUploadStash.php @@ -1,7 +1,28 @@ stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash(); - } catch ( UploadStashNotAvailableException $e ) { - return null; - } + } - $this->loadRequest( is_null( $request ) ? $wgRequest : $request ); + public function doesWrites() { + return true; } /** * Execute page -- can output a file directly or show a listing of them. * - * @param $subPage String: subpage, e.g. in http://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part - * @return Boolean: success + * @param string $subPage Subpage, e.g. in + * https://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part + * @return bool Success */ public function execute( $subPage ) { - global $wgUser; + $this->useTransactionalTimeLimit(); - if ( !$this->userCanExecute( $wgUser ) ) { - $this->displayRestrictionError(); - return; - } + $this->stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $this->getUser() ); + $this->checkPermissions(); - if ( !isset( $subPage ) || $subPage === '' ) { + if ( $subPage === null || $subPage === '' ) { return $this->showUploads(); } return $this->showUpload( $subPage ); } - /** * If file available in stash, cats it out to the client as a simple HTTP response. * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward. * - * @param $key String: the key of a particular requested file + * @param string $key The key of a particular requested file + * @throws HttpError + * @return bool */ public function showUpload( $key ) { - global $wgOut; - // prevent callers from doing standard HTML output -- we'll take it from here - $wgOut->disable(); + $this->getOutput()->disable(); try { $params = $this->parseKey( $key ); @@ -90,33 +95,34 @@ class SpecialUploadStash extends UnlistedSpecialPage { } else { return $this->outputLocalFile( $params['file'] ); } - } catch( UploadStashFileNotFoundException $e ) { - $code = 404; + } catch ( UploadStashFileNotFoundException $e ) { + $code = 404; $message = $e->getMessage(); - } catch( UploadStashZeroLengthFileException $e ) { + } catch ( UploadStashZeroLengthFileException $e ) { $code = 500; $message = $e->getMessage(); - } catch( UploadStashBadPathException $e ) { + } catch ( UploadStashBadPathException $e ) { $code = 500; $message = $e->getMessage(); - } catch( SpecialUploadStashTooLargeException $e ) { + } catch ( SpecialUploadStashTooLargeException $e ) { $code = 500; - $message = 'Cannot serve a file larger than ' . self::MAX_SERVE_BYTES . ' bytes. ' . $e->getMessage(); - } catch( Exception $e ) { + $message = 'Cannot serve a file larger than ' . self::MAX_SERVE_BYTES . + ' bytes. ' . $e->getMessage(); + } catch ( Exception $e ) { $code = 500; $message = $e->getMessage(); } - wfHttpError( $code, OutputPage::getStatusMessage( $code ), $message ); - return false; + throw new HttpError( $code, $message ); } - + /** - * Parse the key passed to the SpecialPage. Returns an array containing - * the associated file object, the type ('file' or 'thumb') and if + * Parse the key passed to the SpecialPage. Returns an array containing + * the associated file object, the type ('file' or 'thumb') and if * application the transform parameters - * + * * @param string $key + * @throws UploadStashBadPathException * @return array */ private function parseKey( $key ) { @@ -132,57 +138,58 @@ class SpecialUploadStash extends UnlistedSpecialPage { $srcNamePos = strrpos( $thumbPart, $fileName ); if ( $srcNamePos === false || $srcNamePos < 1 ) { throw new UploadStashBadPathException( 'Unrecognized thumb name' ); - } + } $paramString = substr( $thumbPart, 0, $srcNamePos - 1 ); - + $handler = $file->getHandler(); - $params = $handler->parseParamString( $paramString ); - return array( 'file' => $file, 'type' => $type, 'params' => $params ); - } - - return array( 'file' => $file, 'type' => $type ); - } - + if ( $handler ) { + $params = $handler->parseParamString( $paramString ); + return [ 'file' => $file, 'type' => $type, 'params' => $params ]; + } else { + throw new UploadStashBadPathException( 'No handler found for ' . + "mime {$file->getMimeType()} of file {$file->getPath()}" ); + } + } + return [ 'file' => $file, 'type' => $type ]; + } /** * Get a thumbnail for file, either generated locally or remotely, and stream it out - * @param String $key: key for the file in the stash - * @param int $width: width of desired thumbnail - * @return boolean success - */ + * + * @param File $file + * @param array $params + * + * @return bool Success + */ private function outputThumbFromStash( $file, $params ) { - - // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb() - // 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 - // happens to share it over NFS - global $wgUploadStashScalerBaseUrl; - $flags = 0; - if ( $wgUploadStashScalerBaseUrl ) { + // this config option, if it exists, points to a "scaler", as you might find in + // the Wikimedia Foundation cluster. See outputRemoteScaledThumb(). 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 + // happens to share it over NFS. + if ( $this->getConfig()->get( 'UploadStashScalerBaseUrl' ) ) { $this->outputRemoteScaledThumb( $file, $params, $flags ); } else { $this->outputLocallyScaledThumb( $file, $params, $flags ); } - - } - /** - * Scale a file (probably with a locally installed imagemagick, or similar) and output it to STDOUT. - * @param $file: File object - * @param $params: scaling parameters ( e.g. array( width => '50' ) ); - * @param $flags: scaling flags ( see File:: constants ) - * @throws MWException - * @return boolean success + * Scale a file (probably with a locally installed imagemagick, or similar) + * and output it to STDOUT. + * @param File $file + * @param array $params Scaling parameters ( e.g. [ width => '50' ] ); + * @param int $flags Scaling flags ( see File:: constants ) + * @throws MWException|UploadStashFileNotFoundException + * @return bool Success */ private function outputLocallyScaledThumb( $file, $params, $flags ) { - // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely // on HTTP caching to ensure this doesn't happen. - + $flags |= File::RENDER_NOW; $thumbnailImage = $file->transform( $params, $flags ); @@ -191,204 +198,234 @@ class SpecialUploadStash extends UnlistedSpecialPage { } // we should have just generated it locally - if ( ! $thumbnailImage->getPath() ) { + if ( !$thumbnailImage->getStoragePath() ) { throw new UploadStashFileNotFoundException( "no local path for scaled item" ); } - // now we should construct a File, so we can get mime and other such info in a standard way - // n.b. mimetype may be different from original (ogx original -> jpeg thumb) - $thumbFile = new UnregisteredLocalFile( false, $this->stash->repo, $thumbnailImage->getPath(), false ); - if ( ! $thumbFile ) { + // now we should construct a File, so we can get MIME and other such info in a standard way + // n.b. MIME type may be different from original (ogx original -> jpeg thumb) + $thumbFile = new UnregisteredLocalFile( false, + $this->stash->repo, $thumbnailImage->getStoragePath(), false ); + if ( !$thumbFile ) { throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" ); } return $this->outputLocalFile( $thumbFile ); - } - + /** - * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation cluster, and output it to STDOUT. - * Note: unlike the usual thumbnail process, the web client never sees the cluster URL; we do the whole HTTP transaction to the scaler ourselves - * and cat the results out. - * Note: We rely on NFS to have propagated the file contents to the scaler. However, we do not rely on the thumbnail being created in NFS and then - * propagated back to our filesystem. Instead we take the results of the HTTP request instead. - * Note: no caching is being done here, although we are instructing the client to cache it forever. - * @param $file: File object - * @param $params: scaling parameters ( e.g. array( width => '50' ) ); - * @param $flags: scaling flags ( see File:: constants ) + * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation + * cluster, and output it to STDOUT. + * Note: Unlike the usual thumbnail process, the web client never sees the + * cluster URL; we do the whole HTTP transaction to the scaler ourselves + * and cat the results out. + * Note: We rely on NFS to have propagated the file contents to the scaler. + * However, we do not rely on the thumbnail being created in NFS and then + * propagated back to our filesystem. Instead we take the results of the + * HTTP request instead. + * Note: No caching is being done here, although we are instructing the + * client to cache it forever. + * + * @param File $file + * @param array $params Scaling parameters ( e.g. [ width => '50' ] ); + * @param int $flags Scaling flags ( see File:: constants ) * @throws MWException - * @return boolean success + * @return bool Success */ private function outputRemoteScaledThumb( $file, $params, $flags ) { - - // this global probably looks something like 'http://upload.wikimedia.org/wikipedia/test/thumb/temp' - // do not use trailing slash - global $wgUploadStashScalerBaseUrl; - - $scalerThumbName = $file->getParamThumbName( $file->name, $params ); - $scalerThumbUrl = $wgUploadStashScalerBaseUrl . '/' . $file->getRel() . '/' . $scalerThumbName; - + // This option probably looks something like + // '//upload.wikimedia.org/wikipedia/test/thumb/temp'. Do not use + // trailing slash. + $scalerBaseUrl = $this->getConfig()->get( 'UploadStashScalerBaseUrl' ); + + if ( preg_match( '/^\/\//', $scalerBaseUrl ) ) { + // this is apparently a protocol-relative URL, which makes no sense in this context, + // since this is used for communication that's internal to the application. + // default to http. + $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL ); + } + + // We need to use generateThumbName() instead of thumbName(), because + // the suffix needs to match the file name for the remote thumbnailer + // to work + $scalerThumbName = $file->generateThumbName( $file->getName(), $params ); + $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() . + '/' . rawurlencode( $scalerThumbName ); + // make a curl call to the scaler to create a thumbnail - $httpOptions = array( + $httpOptions = [ 'method' => 'GET', - 'timeout' => 'default' - ); - $req = MWHttpRequest::factory( $scalerThumbUrl, $httpOptions ); + 'timeout' => 5 // T90599 attempt to time out cleanly + ]; + $req = MWHttpRequest::factory( $scalerThumbUrl, $httpOptions, __METHOD__ ); $status = $req->execute(); - if ( ! $status->isOK() ) { - $errors = $status->getErrorsArray(); - throw new MWException( "Fetching thumbnail failed: " . join( ", ", $errors ) ); + if ( !$status->isOK() ) { + $errors = $status->getErrorsArray(); + $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 ); + $errorStr .= "\nurl = $scalerThumbUrl\n"; + throw new MWException( $errorStr ); } $contentType = $req->getResponseHeader( "content-type" ); - if ( ! $contentType ) { + if ( !$contentType ) { throw new MWException( "Missing content-type header" ); } + return $this->outputContents( $req->getContent(), $contentType ); } /** * Output HTTP response for file * Side effect: writes HTTP response to STDOUT. - * XXX could use wfStreamfile (in includes/Streamfile.php), but for consistency with outputContents() doing it this way. - * XXX is mimeType really enough, or do we need encoding for full Content-Type header? * - * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!) + * @param File $file File object with a local path (e.g. UnregisteredLocalFile, + * LocalFile. Oddly these don't share an ancestor!) + * @throws SpecialUploadStashTooLargeException + * @return bool */ - private function outputLocalFile( $file ) { + private function outputLocalFile( File $file ) { if ( $file->getSize() > self::MAX_SERVE_BYTES ) { throw new SpecialUploadStashTooLargeException(); - } - self::outputFileHeaders( $file->getMimeType(), $file->getSize() ); - readfile( $file->getPath() ); - return true; + } + + return $file->getRepo()->streamFile( $file->getPath(), + [ 'Content-Transfer-Encoding: binary', + 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' ] + ); } - /** + /** * Output HTTP response of raw content * Side effect: writes HTTP response to STDOUT. - * @param String $content: content - * @param String $mimeType: mime type + * @param string $content Content + * @param string $contentType MIME type + * @throws SpecialUploadStashTooLargeException + * @return bool */ private function outputContents( $content, $contentType ) { $size = strlen( $content ); if ( $size > self::MAX_SERVE_BYTES ) { throw new SpecialUploadStashTooLargeException(); } + // Cancel output buffering and gzipping if set + wfResetOutputBuffers(); self::outputFileHeaders( $contentType, $size ); - print $content; + print $content; + return true; } - /** + /** * Output headers for streaming - * XXX unsure about encoding as binary; if we received from HTTP perhaps we should use that encoding, concatted with semicolon to mimeType as it usually is. + * @todo Unsure about encoding as binary; if we received from HTTP perhaps + * we should use that encoding, concatenated with semicolon to `$contentType` as it + * usually is. * Side effect: preps PHP to write headers to STDOUT. - * @param String $contentType : string suitable for content-type header - * @param String $size: length in bytes + * @param string $contentType String suitable for content-type header + * @param string $size Length in bytes */ private static function outputFileHeaders( $contentType, $size ) { header( "Content-Type: $contentType", true ); header( 'Content-Transfer-Encoding: binary', true ); header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true ); - header( "Content-Length: $size", true ); - } - - - /** - * Initialize authorization & actions to take, from the request - * @param $request: WebRequest - */ - private function loadRequest( $request ) { - global $wgUser; - if ( $request->wasPosted() ) { - - $token = $request->getVal( 'wpEditToken' ); - $this->isEditAuthorized = $wgUser->matchEditToken( $token ); - - $this->requestedClear = $request->getBool( 'clear' ); - - } + // T55032 - It shouldn't be a problem here, but let's be safe and not cache + header( 'Cache-Control: private' ); + header( "Content-Length: $size", true ); } /** - * Static callback for the HTMLForm in showUploads, to process + * Static callback for the HTMLForm in showUploads, to process * Note the stash has to be recreated since this is being called in a static context. * This works, because there really is only one stash per logged-in user, despite appearances. * + * @param array $formData + * @param HTMLForm $form * @return Status - */ - public static function tryClearStashedUploads( $formData ) { - wfDebug( __METHOD__ . " form data : " . print_r( $formData, 1 ) ); - if ( isset( $formData['clear'] ) and $formData['clear'] ) { - $stash = new UploadStash(); - wfDebug( "stash has: " . print_r( $stash->listFiles(), 1 ) ); - if ( ! $stash->clear() ) { + */ + public static function tryClearStashedUploads( $formData, $form ) { + if ( isset( $formData['Clear'] ) ) { + $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $form->getUser() ); + wfDebug( 'stash has: ' . print_r( $stash->listFiles(), true ) . "\n" ); + + if ( !$stash->clear() ) { return Status::newFatal( 'uploadstash-errclear' ); } } + return Status::newGood(); } /** * Default action when we don't have a subpage -- just show links to the uploads we have, * Also show a button to clear stashed files - * @param Status : $status - the result of processRequest - */ - private function showUploads( $status = null ) { - global $wgOut; - if ( $status === null ) { - $status = Status::newGood(); - } - + * @return bool + */ + private function showUploads() { // sets the title, etc. $this->setHeaders(); $this->outputHeader(); - // create the form, which will also be used to execute a callback to process incoming form data // this design is extremely dubious, but supposedly HTMLForm is our standard now? - $form = new HTMLForm( array( - 'Clear' => array( - 'type' => 'hidden', + $context = new DerivativeContext( $this->getContext() ); + $context->setTitle( $this->getPageTitle() ); // Remove subpage + $form = HTMLForm::factory( 'ooui', [ + 'Clear' => [ + 'type' => 'hidden', 'default' => true, 'name' => 'clear', - ) - ), 'clearStashedUploads' ); - $form->setSubmitCallback( array( __CLASS__, 'tryClearStashedUploads' ) ); - $form->setTitle( $this->getTitle() ); - $form->addHiddenField( 'clear', true, array( 'type' => 'boolean' ) ); - $form->setSubmitText( wfMsg( 'uploadstash-clear' ) ); + ] + ], $context, 'clearStashedUploads' ); + $form->setSubmitDestructive(); + $form->setSubmitCallback( [ __CLASS__, 'tryClearStashedUploads' ] ); + $form->setSubmitTextMsg( 'uploadstash-clear' ); - $form->prepareForm(); - $formResult = $form->tryAuthorizedSubmit(); - + $form->prepareForm(); + $formResult = $form->tryAuthorizedSubmit(); // show the files + form, if there are any, or just say there are none - $refreshHtml = Html::element( 'a', array( 'href' => $this->getTitle()->getLocalURL() ), wfMsg( 'uploadstash-refresh' ) ); + $refreshHtml = Html::element( 'a', + [ 'href' => $this->getPageTitle()->getLocalURL() ], + $this->msg( 'uploadstash-refresh' )->text() ); $files = $this->stash->listFiles(); - if ( count( $files ) ) { + if ( $files && count( $files ) ) { sort( $files ); $fileListItemsHtml = ''; + $linkRenderer = $this->getLinkRenderer(); foreach ( $files as $file ) { - $fileListItemsHtml .= Html::rawElement( 'li', array(), - Html::element( 'a', array( 'href' => - $this->getTitle( "file/$file" )->getLocalURL() ), $file ) + $itemHtml = $linkRenderer->makeKnownLink( + $this->getPageTitle( "file/$file" ), + $file ); + try { + $fileObj = $this->stash->getFile( $file ); + $thumb = $fileObj->generateThumbName( $file, [ 'width' => 220 ] ); + $itemHtml .= + $this->msg( 'word-separator' )->escaped() . + $this->msg( 'parentheses' )->rawParams( + $linkRenderer->makeKnownLink( + $this->getPageTitle( "thumb/$file/$thumb" ), + $this->msg( 'uploadstash-thumbnail' )->text() + ) + )->escaped(); + } catch ( Exception $e ) { + } + $fileListItemsHtml .= Html::rawElement( 'li', [], $itemHtml ); } - $wgOut->addHtml( Html::rawElement( 'ul', array(), $fileListItemsHtml ) ); - $form->displayForm( $formResult ); - $wgOut->addHtml( Html::rawElement( 'p', array(), $refreshHtml ) ); + $this->getOutput()->addHTML( Html::rawElement( 'ul', [], $fileListItemsHtml ) ); + $form->displayForm( $formResult ); + $this->getOutput()->addHTML( Html::rawElement( 'p', [], $refreshHtml ) ); } else { - $wgOut->addHtml( Html::rawElement( 'p', array(), - Html::element( 'span', array(), wfMsg( 'uploadstash-nofiles' ) ) - . ' ' + $this->getOutput()->addHTML( Html::rawElement( 'p', [], + Html::element( 'span', [], $this->msg( 'uploadstash-nofiles' )->text() ) + . ' ' . $refreshHtml ) ); } - + return true; } } -class SpecialUploadStashTooLargeException extends MWException {}; +class SpecialUploadStashTooLargeException extends MWException { +}