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|null $subPage Subpage, e.g. in
64 * https://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part
66 public function execute( $subPage ) {
67 $this->useTransactionalTimeLimit();
69 $this->stash
= RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
70 $this->checkPermissions();
72 if ( $subPage === null ||
$subPage === '' ) {
75 $this->showUpload( $subPage );
80 * If file available in stash, cats it out to the client as a simple HTTP response.
81 * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward.
83 * @param string $key The key of a particular requested file
86 public function showUpload( $key ) {
87 // prevent callers from doing standard HTML output -- we'll take it from here
88 $this->getOutput()->disable();
91 $params = $this->parseKey( $key );
92 if ( $params['type'] === 'thumb' ) {
93 $this->outputThumbFromStash( $params['file'], $params['params'] );
95 $this->outputLocalFile( $params['file'] );
98 } catch ( UploadStashFileNotFoundException
$e ) {
100 $message = $e->getMessage();
101 } catch ( UploadStashZeroLengthFileException
$e ) {
103 $message = $e->getMessage();
104 } catch ( UploadStashBadPathException
$e ) {
106 $message = $e->getMessage();
107 } catch ( SpecialUploadStashTooLargeException
$e ) {
109 $message = $e->getMessage();
110 } catch ( Exception
$e ) {
112 $message = $e->getMessage();
115 throw new HttpError( $code, $message );
119 * Parse the key passed to the SpecialPage. Returns an array containing
120 * the associated file object, the type ('file' or 'thumb') and if
121 * application the transform parameters
124 * @throws UploadStashBadPathException
127 private function parseKey( $key ) {
128 $type = strtok( $key, '/' );
130 if ( $type !== 'file' && $type !== 'thumb' ) {
131 throw new UploadStashBadPathException(
132 $this->msg( 'uploadstash-bad-path-unknown-type', $type )
135 $fileName = strtok( '/' );
136 $thumbPart = strtok( '/' );
137 $file = $this->stash
->getFile( $fileName );
138 if ( $type === 'thumb' ) {
139 $srcNamePos = strrpos( $thumbPart, $fileName );
140 if ( $srcNamePos === false ||
$srcNamePos < 1 ) {
141 throw new UploadStashBadPathException(
142 $this->msg( 'uploadstash-bad-path-unrecognized-thumb-name' )
145 $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
147 $handler = $file->getHandler();
149 $params = $handler->parseParamString( $paramString );
151 return [ 'file' => $file, 'type' => $type, 'params' => $params ];
153 throw new UploadStashBadPathException(
154 $this->msg( 'uploadstash-bad-path-no-handler', $file->getMimeType(), $file->getPath() )
159 return [ 'file' => $file, 'type' => $type ];
163 * Get a thumbnail for file, either generated locally or remotely, and stream it out
166 * @param array $params
168 private function outputThumbFromStash( $file, $params ) {
170 // this config option, if it exists, points to a "scaler", as you might find in
171 // the Wikimedia Foundation cluster. See outputRemoteScaledThumb(). This
172 // is part of our horrible NFS-based system, we create a file on a mount
173 // point here, but fetch the scaled file from somewhere else that
174 // happens to share it over NFS.
175 if ( $this->getConfig()->get( 'UploadStashScalerBaseUrl' ) ) {
176 $this->outputRemoteScaledThumb( $file, $params, $flags );
178 $this->outputLocallyScaledThumb( $file, $params, $flags );
183 * Scale a file (probably with a locally installed imagemagick, or similar)
184 * and output it to STDOUT.
186 * @param array $params Scaling parameters ( e.g. [ width => '50' ] );
187 * @param int $flags Scaling flags ( see File:: constants )
188 * @throws MWException|UploadStashFileNotFoundException
190 private function outputLocallyScaledThumb( $file, $params, $flags ) {
191 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
192 // on HTTP caching to ensure this doesn't happen.
194 $flags |
= File
::RENDER_NOW
;
196 $thumbnailImage = $file->transform( $params, $flags );
197 if ( !$thumbnailImage ) {
198 throw new UploadStashFileNotFoundException(
199 $this->msg( 'uploadstash-file-not-found-no-thumb' )
203 // we should have just generated it locally
204 if ( !$thumbnailImage->getStoragePath() ) {
205 throw new UploadStashFileNotFoundException(
206 $this->msg( 'uploadstash-file-not-found-no-local-path' )
210 // now we should construct a File, so we can get MIME and other such info in a standard way
211 // n.b. MIME type may be different from original (ogx original -> jpeg thumb)
212 $thumbFile = new UnregisteredLocalFile( false,
213 $this->stash
->repo
, $thumbnailImage->getStoragePath(), false );
215 throw new UploadStashFileNotFoundException(
216 $this->msg( 'uploadstash-file-not-found-no-object' )
220 $this->outputLocalFile( $thumbFile );
224 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation
225 * cluster, and output it to STDOUT.
226 * Note: Unlike the usual thumbnail process, the web client never sees the
227 * cluster URL; we do the whole HTTP transaction to the scaler ourselves
228 * and cat the results out.
229 * Note: We rely on NFS to have propagated the file contents to the scaler.
230 * However, we do not rely on the thumbnail being created in NFS and then
231 * propagated back to our filesystem. Instead we take the results of the
232 * HTTP request instead.
233 * Note: No caching is being done here, although we are instructing the
234 * client to cache it forever.
237 * @param array $params Scaling parameters ( e.g. [ width => '50' ] );
238 * @param int $flags Scaling flags ( see File:: constants )
239 * @throws MWException
241 private function outputRemoteScaledThumb( $file, $params, $flags ) {
242 // This option probably looks something like
243 // '//upload.wikimedia.org/wikipedia/test/thumb/temp'. Do not use
245 $scalerBaseUrl = $this->getConfig()->get( 'UploadStashScalerBaseUrl' );
247 if ( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
248 // this is apparently a protocol-relative URL, which makes no sense in this context,
249 // since this is used for communication that's internal to the application.
251 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL
);
254 // We need to use generateThumbName() instead of thumbName(), because
255 // the suffix needs to match the file name for the remote thumbnailer
257 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
258 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
259 '/' . rawurlencode( $scalerThumbName );
261 // If a thumb proxy is set up for the repo, we favor that, as that will
262 // keep the request internal
263 $thumbProxyUrl = $file->getRepo()->getThumbProxyUrl();
265 if ( strlen( $thumbProxyUrl ) ) {
266 $scalerThumbUrl = $thumbProxyUrl . 'temp/' . $file->getUrlRel() .
267 '/' . rawurlencode( $scalerThumbName );
270 // make an http request based on wgUploadStashScalerBaseUrl to lazy-create
274 'timeout' => 5 // T90599 attempt to time out cleanly
276 $req = MWHttpRequest
::factory( $scalerThumbUrl, $httpOptions, __METHOD__
);
278 $secret = $file->getRepo()->getThumbProxySecret();
280 // Pass a secret key shared with the proxied service if any
281 if ( strlen( $secret ) ) {
282 $req->setHeader( 'X-Swift-Secret', $secret );
285 $status = $req->execute();
286 if ( !$status->isOK() ) {
287 $errors = $status->getErrorsArray();
288 throw new UploadStashFileNotFoundException(
290 'uploadstash-file-not-found-no-remote-thumb',
291 print_r( $errors, 1 ),
296 $contentType = $req->getResponseHeader( "content-type" );
297 if ( !$contentType ) {
298 throw new UploadStashFileNotFoundException(
299 $this->msg( 'uploadstash-file-not-found-missing-content-type' )
303 $this->outputContents( $req->getContent(), $contentType );
307 * Output HTTP response for file
308 * Side effect: writes HTTP response to STDOUT.
310 * @param File $file File object with a local path (e.g. UnregisteredLocalFile,
311 * LocalFile. Oddly these don't share an ancestor!)
312 * @throws SpecialUploadStashTooLargeException
314 private function outputLocalFile( File
$file ) {
315 if ( $file->getSize() > self
::MAX_SERVE_BYTES
) {
316 throw new SpecialUploadStashTooLargeException(
317 $this->msg( 'uploadstash-file-too-large', self
::MAX_SERVE_BYTES
)
321 $file->getRepo()->streamFileWithStatus( $file->getPath(),
322 [ 'Content-Transfer-Encoding: binary',
323 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' ]
328 * Output HTTP response of raw content
329 * Side effect: writes HTTP response to STDOUT.
330 * @param string $content
331 * @param string $contentType MIME type
332 * @throws SpecialUploadStashTooLargeException
334 private function outputContents( $content, $contentType ) {
335 $size = strlen( $content );
336 if ( $size > self
::MAX_SERVE_BYTES
) {
337 throw new SpecialUploadStashTooLargeException(
338 $this->msg( 'uploadstash-file-too-large', self
::MAX_SERVE_BYTES
)
341 // Cancel output buffering and gzipping if set
342 wfResetOutputBuffers();
343 self
::outputFileHeaders( $contentType, $size );
348 * Output headers for streaming
349 * @todo Unsure about encoding as binary; if we received from HTTP perhaps
350 * we should use that encoding, concatenated with semicolon to `$contentType` as it
352 * Side effect: preps PHP to write headers to STDOUT.
353 * @param string $contentType String suitable for content-type header
354 * @param string $size Length in bytes
356 private static function outputFileHeaders( $contentType, $size ) {
357 header( "Content-Type: $contentType", true );
358 header( 'Content-Transfer-Encoding: binary', true );
359 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
360 // T55032 - It shouldn't be a problem here, but let's be safe and not cache
361 header( 'Cache-Control: private' );
362 header( "Content-Length: $size", true );
366 * Static callback for the HTMLForm in showUploads, to process
367 * Note the stash has to be recreated since this is being called in a static context.
368 * This works, because there really is only one stash per logged-in user, despite appearances.
370 * @param array $formData
371 * @param HTMLForm $form
374 public static function tryClearStashedUploads( $formData, $form ) {
375 if ( isset( $formData['Clear'] ) ) {
376 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $form->getUser() );
377 wfDebug( 'stash has: ' . print_r( $stash->listFiles(), true ) . "\n" );
379 if ( !$stash->clear() ) {
380 return Status
::newFatal( 'uploadstash-errclear' );
384 return Status
::newGood();
388 * Default action when we don't have a subpage -- just show links to the uploads we have,
389 * Also show a button to clear stashed files
391 private function showUploads() {
392 // sets the title, etc.
394 $this->outputHeader();
396 // create the form, which will also be used to execute a callback to process incoming form data
397 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
399 $context = new DerivativeContext( $this->getContext() );
400 $context->setTitle( $this->getPageTitle() ); // Remove subpage
401 $form = HTMLForm
::factory( 'ooui', [
407 ], $context, 'clearStashedUploads' );
408 $form->setSubmitDestructive();
409 $form->setSubmitCallback( [ __CLASS__
, 'tryClearStashedUploads' ] );
410 $form->setSubmitTextMsg( 'uploadstash-clear' );
412 $form->prepareForm();
413 $formResult = $form->tryAuthorizedSubmit();
415 // show the files + form, if there are any, or just say there are none
416 $refreshHtml = Html
::element( 'a',
417 [ 'href' => $this->getPageTitle()->getLocalURL() ],
418 $this->msg( 'uploadstash-refresh' )->text() );
419 $files = $this->stash
->listFiles();
420 if ( $files && count( $files ) ) {
422 $fileListItemsHtml = '';
423 $linkRenderer = $this->getLinkRenderer();
424 foreach ( $files as $file ) {
425 $itemHtml = $linkRenderer->makeKnownLink(
426 $this->getPageTitle( "file/$file" ),
430 $fileObj = $this->stash
->getFile( $file );
431 $thumb = $fileObj->generateThumbName( $file, [ 'width' => 220 ] );
433 $this->msg( 'word-separator' )->escaped() .
434 $this->msg( 'parentheses' )->rawParams(
435 $linkRenderer->makeKnownLink(
436 $this->getPageTitle( "thumb/$file/$thumb" ),
437 $this->msg( 'uploadstash-thumbnail' )->text()
440 } catch ( Exception
$e ) {
442 $fileListItemsHtml .= Html
::rawElement( 'li', [], $itemHtml );
444 $this->getOutput()->addHTML( Html
::rawElement( 'ul', [], $fileListItemsHtml ) );
445 $form->displayForm( $formResult );
446 $this->getOutput()->addHTML( Html
::rawElement( 'p', [], $refreshHtml ) );
448 $this->getOutput()->addHTML( Html
::rawElement( 'p', [],
449 Html
::element( 'span', [], $this->msg( 'uploadstash-nofiles' )->text() )