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
21 * @ingroup SpecialPage
26 * Web access for files temporarily stored by UploadStash.
28 * For example -- files that were uploaded with the UploadWizard extension are stored temporarily
29 * before committing them to the db. But we want to see their thumbnails and get other information
32 * Since this is based on the user's session, in effect this creates a private temporary file area.
33 * However, the URLs for the files cannot be shared.
35 class SpecialUploadStash
extends UnlistedSpecialPage
{
40 * Since we are directly writing the file to STDOUT,
41 * we should not be reading in really big files and serving them out.
43 * We also don't want people using this as a file drop, even if they
46 * This service is really for thumbnails and other such previews while
49 const MAX_SERVE_BYTES
= 1048576; // 1MB
51 public function __construct() {
52 parent
::__construct( 'UploadStash', 'upload' );
55 public function doesWrites() {
60 * Execute page -- can output a file directly or show a listing of them.
62 * @param string $subPage Subpage, e.g. in
63 * https://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part
64 * @return bool Success
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 === '' ) {
73 return $this->showUploads();
76 return $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
87 public function showUpload( $key ) {
88 // prevent callers from doing standard HTML output -- we'll take it from here
89 $this->getOutput()->disable();
92 $params = $this->parseKey( $key );
93 if ( $params['type'] === 'thumb' ) {
94 return $this->outputThumbFromStash( $params['file'], $params['params'] );
96 return $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 wfMessage( '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 wfMessage( '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 wfMessage( '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 * @return bool Success
170 private function outputThumbFromStash( $file, $params ) {
172 // this config option, if it exists, points to a "scaler", as you might find in
173 // the Wikimedia Foundation cluster. See outputRemoteScaledThumb(). This
174 // is part of our horrible NFS-based system, we create a file on a mount
175 // point here, but fetch the scaled file from somewhere else that
176 // happens to share it over NFS.
177 if ( $this->getConfig()->get( 'UploadStashScalerBaseUrl' ) ) {
178 $this->outputRemoteScaledThumb( $file, $params, $flags );
180 $this->outputLocallyScaledThumb( $file, $params, $flags );
185 * Scale a file (probably with a locally installed imagemagick, or similar)
186 * and output it to STDOUT.
188 * @param array $params Scaling parameters ( e.g. [ width => '50' ] );
189 * @param int $flags Scaling flags ( see File:: constants )
190 * @throws MWException|UploadStashFileNotFoundException
191 * @return bool Success
193 private function outputLocallyScaledThumb( $file, $params, $flags ) {
194 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
195 // on HTTP caching to ensure this doesn't happen.
197 $flags |
= File
::RENDER_NOW
;
199 $thumbnailImage = $file->transform( $params, $flags );
200 if ( !$thumbnailImage ) {
201 throw new UploadStashFileNotFoundException(
202 wfMessage( 'uploadstash-file-not-found-no-thumb' )
206 // we should have just generated it locally
207 if ( !$thumbnailImage->getStoragePath() ) {
208 throw new UploadStashFileNotFoundException(
209 wfMessage( 'uploadstash-file-not-found-no-local-path' )
213 // now we should construct a File, so we can get MIME and other such info in a standard way
214 // n.b. MIME type may be different from original (ogx original -> jpeg thumb)
215 $thumbFile = new UnregisteredLocalFile( false,
216 $this->stash
->repo
, $thumbnailImage->getStoragePath(), false );
218 throw new UploadStashFileNotFoundException(
219 wfMessage( 'uploadstash-file-not-found-no-object' )
223 return $this->outputLocalFile( $thumbFile );
227 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation
228 * cluster, and output it to STDOUT.
229 * Note: Unlike the usual thumbnail process, the web client never sees the
230 * cluster URL; we do the whole HTTP transaction to the scaler ourselves
231 * and cat the results out.
232 * Note: We rely on NFS to have propagated the file contents to the scaler.
233 * However, we do not rely on the thumbnail being created in NFS and then
234 * propagated back to our filesystem. Instead we take the results of the
235 * HTTP request instead.
236 * Note: No caching is being done here, although we are instructing the
237 * client to cache it forever.
240 * @param array $params Scaling parameters ( e.g. [ width => '50' ] );
241 * @param int $flags Scaling flags ( see File:: constants )
242 * @throws MWException
243 * @return bool Success
245 private function outputRemoteScaledThumb( $file, $params, $flags ) {
246 // This option probably looks something like
247 // '//upload.wikimedia.org/wikipedia/test/thumb/temp'. Do not use
249 $scalerBaseUrl = $this->getConfig()->get( 'UploadStashScalerBaseUrl' );
251 if ( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
252 // this is apparently a protocol-relative URL, which makes no sense in this context,
253 // since this is used for communication that's internal to the application.
255 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL
);
258 // We need to use generateThumbName() instead of thumbName(), because
259 // the suffix needs to match the file name for the remote thumbnailer
261 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
262 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
263 '/' . rawurlencode( $scalerThumbName );
265 // make a curl call to the scaler to create a thumbnail
268 'timeout' => 5 // T90599 attempt to time out cleanly
270 $req = MWHttpRequest
::factory( $scalerThumbUrl, $httpOptions, __METHOD__
);
271 $status = $req->execute();
272 if ( !$status->isOK() ) {
273 $errors = $status->getErrorsArray();
274 throw new UploadStashFileNotFoundException(
276 'uploadstash-file-not-found-no-remote-thumb',
277 print_r( $errors, 1 ),
282 $contentType = $req->getResponseHeader( "content-type" );
283 if ( !$contentType ) {
284 throw new UploadStashFileNotFoundException(
285 wfMessage( 'uploadstash-file-not-found-missing-content-type' )
289 return $this->outputContents( $req->getContent(), $contentType );
293 * Output HTTP response for file
294 * Side effect: writes HTTP response to STDOUT.
296 * @param File $file File object with a local path (e.g. UnregisteredLocalFile,
297 * LocalFile. Oddly these don't share an ancestor!)
298 * @throws SpecialUploadStashTooLargeException
301 private function outputLocalFile( File
$file ) {
302 if ( $file->getSize() > self
::MAX_SERVE_BYTES
) {
303 throw new SpecialUploadStashTooLargeException(
304 wfMessage( 'uploadstash-file-too-large', self
::MAX_SERVE_BYTES
)
308 return $file->getRepo()->streamFile( $file->getPath(),
309 [ 'Content-Transfer-Encoding: binary',
310 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' ]
315 * Output HTTP response of raw content
316 * Side effect: writes HTTP response to STDOUT.
317 * @param string $content Content
318 * @param string $contentType MIME type
319 * @throws SpecialUploadStashTooLargeException
322 private function outputContents( $content, $contentType ) {
323 $size = strlen( $content );
324 if ( $size > self
::MAX_SERVE_BYTES
) {
325 throw new SpecialUploadStashTooLargeException(
326 wfMessage( 'uploadstash-file-too-large', self
::MAX_SERVE_BYTES
)
329 // Cancel output buffering and gzipping if set
330 wfResetOutputBuffers();
331 self
::outputFileHeaders( $contentType, $size );
338 * Output headers for streaming
339 * @todo Unsure about encoding as binary; if we received from HTTP perhaps
340 * we should use that encoding, concatenated with semicolon to `$contentType` as it
342 * Side effect: preps PHP to write headers to STDOUT.
343 * @param string $contentType String suitable for content-type header
344 * @param string $size Length in bytes
346 private static function outputFileHeaders( $contentType, $size ) {
347 header( "Content-Type: $contentType", true );
348 header( 'Content-Transfer-Encoding: binary', true );
349 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
350 // T55032 - It shouldn't be a problem here, but let's be safe and not cache
351 header( 'Cache-Control: private' );
352 header( "Content-Length: $size", true );
356 * Static callback for the HTMLForm in showUploads, to process
357 * Note the stash has to be recreated since this is being called in a static context.
358 * This works, because there really is only one stash per logged-in user, despite appearances.
360 * @param array $formData
361 * @param HTMLForm $form
364 public static function tryClearStashedUploads( $formData, $form ) {
365 if ( isset( $formData['Clear'] ) ) {
366 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $form->getUser() );
367 wfDebug( 'stash has: ' . print_r( $stash->listFiles(), true ) . "\n" );
369 if ( !$stash->clear() ) {
370 return Status
::newFatal( 'uploadstash-errclear' );
374 return Status
::newGood();
378 * Default action when we don't have a subpage -- just show links to the uploads we have,
379 * Also show a button to clear stashed files
382 private function showUploads() {
383 // sets the title, etc.
385 $this->outputHeader();
387 // create the form, which will also be used to execute a callback to process incoming form data
388 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
390 $context = new DerivativeContext( $this->getContext() );
391 $context->setTitle( $this->getPageTitle() ); // Remove subpage
392 $form = HTMLForm
::factory( 'ooui', [
398 ], $context, 'clearStashedUploads' );
399 $form->setSubmitDestructive();
400 $form->setSubmitCallback( [ __CLASS__
, 'tryClearStashedUploads' ] );
401 $form->setSubmitTextMsg( 'uploadstash-clear' );
403 $form->prepareForm();
404 $formResult = $form->tryAuthorizedSubmit();
406 // show the files + form, if there are any, or just say there are none
407 $refreshHtml = Html
::element( 'a',
408 [ 'href' => $this->getPageTitle()->getLocalURL() ],
409 $this->msg( 'uploadstash-refresh' )->text() );
410 $files = $this->stash
->listFiles();
411 if ( $files && count( $files ) ) {
413 $fileListItemsHtml = '';
414 $linkRenderer = $this->getLinkRenderer();
415 foreach ( $files as $file ) {
416 $itemHtml = $linkRenderer->makeKnownLink(
417 $this->getPageTitle( "file/$file" ),
421 $fileObj = $this->stash
->getFile( $file );
422 $thumb = $fileObj->generateThumbName( $file, [ 'width' => 220 ] );
424 $this->msg( 'word-separator' )->escaped() .
425 $this->msg( 'parentheses' )->rawParams(
426 $linkRenderer->makeKnownLink(
427 $this->getPageTitle( "thumb/$file/$thumb" ),
428 $this->msg( 'uploadstash-thumbnail' )->text()
431 } catch ( Exception
$e ) {
433 $fileListItemsHtml .= Html
::rawElement( 'li', [], $itemHtml );
435 $this->getOutput()->addHTML( Html
::rawElement( 'ul', [], $fileListItemsHtml ) );
436 $form->displayForm( $formResult );
437 $this->getOutput()->addHTML( Html
::rawElement( 'p', [], $refreshHtml ) );
439 $this->getOutput()->addHTML( Html
::rawElement( 'p', [],
440 Html
::element( 'span', [], $this->msg( 'uploadstash-nofiles' )->text() )
450 class SpecialUploadStashTooLargeException
extends UploadStashException
{