3 * Implements Special:UploadStash.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Web access for files temporarily stored by UploadStash.
26 * For example -- files that were uploaded with the UploadWizard extension are stored temporarily
27 * before committing them to the db. But we want to see their thumbnails and get other information
30 * Since this is based on the user's session, in effect this creates a private temporary file area.
31 * However, the URLs for the files cannot be shared.
33 * @ingroup SpecialPage
36 class SpecialUploadStash
extends UnlistedSpecialPage
{
41 * Since we are directly writing the file to STDOUT,
42 * we should not be reading in really big files and serving them out.
44 * We also don't want people using this as a file drop, even if they
47 * This service is really for thumbnails and other such previews while
50 const MAX_SERVE_BYTES
= 1048576; // 1MB
52 public function __construct() {
53 parent
::__construct( 'UploadStash', 'upload' );
56 public function doesWrites() {
61 * Execute page -- can output a file directly or show a listing of them.
63 * @param string $subPage Subpage, e.g. in
64 * https://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part
65 * @return bool Success
67 public function execute( $subPage ) {
68 $this->useTransactionalTimeLimit();
70 $this->stash
= RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
71 $this->checkPermissions();
73 if ( $subPage === null ||
$subPage === '' ) {
74 return $this->showUploads();
77 return $this->showUpload( $subPage );
81 * If file available in stash, cats it out to the client as a simple HTTP response.
82 * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward.
84 * @param string $key The key of a particular requested file
88 public function showUpload( $key ) {
89 // prevent callers from doing standard HTML output -- we'll take it from here
90 $this->getOutput()->disable();
93 $params = $this->parseKey( $key );
94 if ( $params['type'] === 'thumb' ) {
95 return $this->outputThumbFromStash( $params['file'], $params['params'] );
97 return $this->outputLocalFile( $params['file'] );
99 } catch ( UploadStashFileNotFoundException
$e ) {
101 $message = $e->getMessage();
102 } catch ( UploadStashZeroLengthFileException
$e ) {
104 $message = $e->getMessage();
105 } catch ( UploadStashBadPathException
$e ) {
107 $message = $e->getMessage();
108 } catch ( SpecialUploadStashTooLargeException
$e ) {
110 $message = $e->getMessage();
111 } catch ( Exception
$e ) {
113 $message = $e->getMessage();
116 throw new HttpError( $code, $message );
120 * Parse the key passed to the SpecialPage. Returns an array containing
121 * the associated file object, the type ('file' or 'thumb') and if
122 * application the transform parameters
125 * @throws UploadStashBadPathException
128 private function parseKey( $key ) {
129 $type = strtok( $key, '/' );
131 if ( $type !== 'file' && $type !== 'thumb' ) {
132 throw new UploadStashBadPathException(
133 wfMessage( 'uploadstash-bad-path-unknown-type', $type )
136 $fileName = strtok( '/' );
137 $thumbPart = strtok( '/' );
138 $file = $this->stash
->getFile( $fileName );
139 if ( $type === 'thumb' ) {
140 $srcNamePos = strrpos( $thumbPart, $fileName );
141 if ( $srcNamePos === false ||
$srcNamePos < 1 ) {
142 throw new UploadStashBadPathException(
143 wfMessage( 'uploadstash-bad-path-unrecognized-thumb-name' )
146 $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
148 $handler = $file->getHandler();
150 $params = $handler->parseParamString( $paramString );
152 return [ 'file' => $file, 'type' => $type, 'params' => $params ];
154 throw new UploadStashBadPathException(
155 wfMessage( 'uploadstash-bad-path-no-handler', $file->getMimeType(), $file->getPath() )
160 return [ 'file' => $file, 'type' => $type ];
164 * Get a thumbnail for file, either generated locally or remotely, and stream it out
167 * @param array $params
169 * @return bool Success
171 private function outputThumbFromStash( $file, $params ) {
173 // this config option, if it exists, points to a "scaler", as you might find in
174 // the Wikimedia Foundation cluster. See outputRemoteScaledThumb(). This
175 // is part of our horrible NFS-based system, we create a file on a mount
176 // point here, but fetch the scaled file from somewhere else that
177 // happens to share it over NFS.
178 if ( $this->getConfig()->get( 'UploadStashScalerBaseUrl' ) ) {
179 $this->outputRemoteScaledThumb( $file, $params, $flags );
181 $this->outputLocallyScaledThumb( $file, $params, $flags );
186 * Scale a file (probably with a locally installed imagemagick, or similar)
187 * and output it to STDOUT.
189 * @param array $params Scaling parameters ( e.g. [ width => '50' ] );
190 * @param int $flags Scaling flags ( see File:: constants )
191 * @throws MWException|UploadStashFileNotFoundException
192 * @return bool Success
194 private function outputLocallyScaledThumb( $file, $params, $flags ) {
195 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
196 // on HTTP caching to ensure this doesn't happen.
198 $flags |
= File
::RENDER_NOW
;
200 $thumbnailImage = $file->transform( $params, $flags );
201 if ( !$thumbnailImage ) {
202 throw new UploadStashFileNotFoundException(
203 wfMessage( 'uploadstash-file-not-found-no-thumb' )
207 // we should have just generated it locally
208 if ( !$thumbnailImage->getStoragePath() ) {
209 throw new UploadStashFileNotFoundException(
210 wfMessage( 'uploadstash-file-not-found-no-local-path' )
214 // now we should construct a File, so we can get MIME and other such info in a standard way
215 // n.b. MIME type may be different from original (ogx original -> jpeg thumb)
216 $thumbFile = new UnregisteredLocalFile( false,
217 $this->stash
->repo
, $thumbnailImage->getStoragePath(), false );
219 throw new UploadStashFileNotFoundException(
220 wfMessage( 'uploadstash-file-not-found-no-object' )
224 return $this->outputLocalFile( $thumbFile );
228 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation
229 * cluster, and output it to STDOUT.
230 * Note: Unlike the usual thumbnail process, the web client never sees the
231 * cluster URL; we do the whole HTTP transaction to the scaler ourselves
232 * and cat the results out.
233 * Note: We rely on NFS to have propagated the file contents to the scaler.
234 * However, we do not rely on the thumbnail being created in NFS and then
235 * propagated back to our filesystem. Instead we take the results of the
236 * HTTP request instead.
237 * Note: No caching is being done here, although we are instructing the
238 * client to cache it forever.
241 * @param array $params Scaling parameters ( e.g. [ width => '50' ] );
242 * @param int $flags Scaling flags ( see File:: constants )
243 * @throws MWException
244 * @return bool Success
246 private function outputRemoteScaledThumb( $file, $params, $flags ) {
247 // This option probably looks something like
248 // '//upload.wikimedia.org/wikipedia/test/thumb/temp'. Do not use
250 $scalerBaseUrl = $this->getConfig()->get( 'UploadStashScalerBaseUrl' );
252 if ( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
253 // this is apparently a protocol-relative URL, which makes no sense in this context,
254 // since this is used for communication that's internal to the application.
256 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL
);
259 // We need to use generateThumbName() instead of thumbName(), because
260 // the suffix needs to match the file name for the remote thumbnailer
262 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
263 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
264 '/' . rawurlencode( $scalerThumbName );
266 // make a curl call to the scaler to create a thumbnail
269 'timeout' => 5 // T90599 attempt to time out cleanly
271 $req = MWHttpRequest
::factory( $scalerThumbUrl, $httpOptions, __METHOD__
);
272 $status = $req->execute();
273 if ( !$status->isOK() ) {
274 $errors = $status->getErrorsArray();
275 throw new UploadStashFileNotFoundException(
277 'uploadstash-file-not-found-no-remote-thumb',
278 print_r( $errors, 1 ),
283 $contentType = $req->getResponseHeader( "content-type" );
284 if ( !$contentType ) {
285 throw new UploadStashFileNotFoundException(
286 wfMessage( 'uploadstash-file-not-found-missing-content-type' )
290 return $this->outputContents( $req->getContent(), $contentType );
294 * Output HTTP response for file
295 * Side effect: writes HTTP response to STDOUT.
297 * @param File $file File object with a local path (e.g. UnregisteredLocalFile,
298 * LocalFile. Oddly these don't share an ancestor!)
299 * @throws SpecialUploadStashTooLargeException
302 private function outputLocalFile( File
$file ) {
303 if ( $file->getSize() > self
::MAX_SERVE_BYTES
) {
304 throw new SpecialUploadStashTooLargeException(
305 wfMessage( 'uploadstash-file-too-large', self
::MAX_SERVE_BYTES
)
309 return $file->getRepo()->streamFile( $file->getPath(),
310 [ 'Content-Transfer-Encoding: binary',
311 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' ]
316 * Output HTTP response of raw content
317 * Side effect: writes HTTP response to STDOUT.
318 * @param string $content Content
319 * @param string $contentType MIME type
320 * @throws SpecialUploadStashTooLargeException
323 private function outputContents( $content, $contentType ) {
324 $size = strlen( $content );
325 if ( $size > self
::MAX_SERVE_BYTES
) {
326 throw new SpecialUploadStashTooLargeException(
327 wfMessage( 'uploadstash-file-too-large', self
::MAX_SERVE_BYTES
)
330 // Cancel output buffering and gzipping if set
331 wfResetOutputBuffers();
332 self
::outputFileHeaders( $contentType, $size );
339 * Output headers for streaming
340 * @todo Unsure about encoding as binary; if we received from HTTP perhaps
341 * we should use that encoding, concatenated with semicolon to `$contentType` as it
343 * Side effect: preps PHP to write headers to STDOUT.
344 * @param string $contentType String suitable for content-type header
345 * @param string $size Length in bytes
347 private static function outputFileHeaders( $contentType, $size ) {
348 header( "Content-Type: $contentType", true );
349 header( 'Content-Transfer-Encoding: binary', true );
350 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
351 // T55032 - It shouldn't be a problem here, but let's be safe and not cache
352 header( 'Cache-Control: private' );
353 header( "Content-Length: $size", true );
357 * Static callback for the HTMLForm in showUploads, to process
358 * Note the stash has to be recreated since this is being called in a static context.
359 * This works, because there really is only one stash per logged-in user, despite appearances.
361 * @param array $formData
362 * @param HTMLForm $form
365 public static function tryClearStashedUploads( $formData, $form ) {
366 if ( isset( $formData['Clear'] ) ) {
367 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $form->getUser() );
368 wfDebug( 'stash has: ' . print_r( $stash->listFiles(), true ) . "\n" );
370 if ( !$stash->clear() ) {
371 return Status
::newFatal( 'uploadstash-errclear' );
375 return Status
::newGood();
379 * Default action when we don't have a subpage -- just show links to the uploads we have,
380 * Also show a button to clear stashed files
383 private function showUploads() {
384 // sets the title, etc.
386 $this->outputHeader();
388 // create the form, which will also be used to execute a callback to process incoming form data
389 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
391 $context = new DerivativeContext( $this->getContext() );
392 $context->setTitle( $this->getPageTitle() ); // Remove subpage
393 $form = HTMLForm
::factory( 'ooui', [
399 ], $context, 'clearStashedUploads' );
400 $form->setSubmitDestructive();
401 $form->setSubmitCallback( [ __CLASS__
, 'tryClearStashedUploads' ] );
402 $form->setSubmitTextMsg( 'uploadstash-clear' );
404 $form->prepareForm();
405 $formResult = $form->tryAuthorizedSubmit();
407 // show the files + form, if there are any, or just say there are none
408 $refreshHtml = Html
::element( 'a',
409 [ 'href' => $this->getPageTitle()->getLocalURL() ],
410 $this->msg( 'uploadstash-refresh' )->text() );
411 $files = $this->stash
->listFiles();
412 if ( $files && count( $files ) ) {
414 $fileListItemsHtml = '';
415 $linkRenderer = $this->getLinkRenderer();
416 foreach ( $files as $file ) {
417 $itemHtml = $linkRenderer->makeKnownLink(
418 $this->getPageTitle( "file/$file" ),
422 $fileObj = $this->stash
->getFile( $file );
423 $thumb = $fileObj->generateThumbName( $file, [ 'width' => 220 ] );
425 $this->msg( 'word-separator' )->escaped() .
426 $this->msg( 'parentheses' )->rawParams(
427 $linkRenderer->makeKnownLink(
428 $this->getPageTitle( "thumb/$file/$thumb" ),
429 $this->msg( 'uploadstash-thumbnail' )->text()
432 } catch ( Exception
$e ) {
434 $fileListItemsHtml .= Html
::rawElement( 'li', [], $itemHtml );
436 $this->getOutput()->addHTML( Html
::rawElement( 'ul', [], $fileListItemsHtml ) );
437 $form->displayForm( $formResult );
438 $this->getOutput()->addHTML( Html
::rawElement( 'p', [], $refreshHtml ) );
440 $this->getOutput()->addHTML( Html
::rawElement( 'p', [],
441 Html
::element( 'span', [], $this->msg( 'uploadstash-nofiles' )->text() )
452 * @ingroup SpecialPage
455 class SpecialUploadStashTooLargeException
extends UploadStashException
{