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' );
56 * Execute page -- can output a file directly or show a listing of them.
58 * @param string $subPage Subpage, e.g. in
59 * http://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part
60 * @return bool Success
62 public function execute( $subPage ) {
63 $this->useTransactionalTimeLimit();
65 $this->stash
= RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
66 $this->checkPermissions();
68 if ( $subPage === null ||
$subPage === '' ) {
69 return $this->showUploads();
72 return $this->showUpload( $subPage );
76 * If file available in stash, cats it out to the client as a simple HTTP response.
77 * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward.
79 * @param string $key The key of a particular requested file
83 public function showUpload( $key ) {
84 // prevent callers from doing standard HTML output -- we'll take it from here
85 $this->getOutput()->disable();
88 $params = $this->parseKey( $key );
89 if ( $params['type'] === 'thumb' ) {
90 return $this->outputThumbFromStash( $params['file'], $params['params'] );
92 return $this->outputLocalFile( $params['file'] );
94 } catch ( UploadStashFileNotFoundException
$e ) {
96 $message = $e->getMessage();
97 } catch ( UploadStashZeroLengthFileException
$e ) {
99 $message = $e->getMessage();
100 } catch ( UploadStashBadPathException
$e ) {
102 $message = $e->getMessage();
103 } catch ( SpecialUploadStashTooLargeException
$e ) {
105 $message = 'Cannot serve a file larger than ' . self
::MAX_SERVE_BYTES
.
106 ' bytes. ' . $e->getMessage();
107 } catch ( Exception
$e ) {
109 $message = $e->getMessage();
112 throw new HttpError( $code, $message );
116 * Parse the key passed to the SpecialPage. Returns an array containing
117 * the associated file object, the type ('file' or 'thumb') and if
118 * application the transform parameters
121 * @throws UploadStashBadPathException
124 private function parseKey( $key ) {
125 $type = strtok( $key, '/' );
127 if ( $type !== 'file' && $type !== 'thumb' ) {
128 throw new UploadStashBadPathException( "Unknown type '$type'" );
130 $fileName = strtok( '/' );
131 $thumbPart = strtok( '/' );
132 $file = $this->stash
->getFile( $fileName );
133 if ( $type === 'thumb' ) {
134 $srcNamePos = strrpos( $thumbPart, $fileName );
135 if ( $srcNamePos === false ||
$srcNamePos < 1 ) {
136 throw new UploadStashBadPathException( 'Unrecognized thumb name' );
138 $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
140 $handler = $file->getHandler();
142 $params = $handler->parseParamString( $paramString );
144 return array( 'file' => $file, 'type' => $type, 'params' => $params );
146 throw new UploadStashBadPathException( 'No handler found for ' .
147 "mime {$file->getMimeType()} of file {$file->getPath()}" );
151 return array( 'file' => $file, 'type' => $type );
155 * Get a thumbnail for file, either generated locally or remotely, and stream it out
158 * @param array $params
160 * @return bool Success
162 private function outputThumbFromStash( $file, $params ) {
164 // this config option, if it exists, points to a "scaler", as you might find in
165 // the Wikimedia Foundation cluster. See outputRemoteScaledThumb(). This
166 // is part of our horrible NFS-based system, we create a file on a mount
167 // point here, but fetch the scaled file from somewhere else that
168 // happens to share it over NFS.
169 if ( $this->getConfig()->get( 'UploadStashScalerBaseUrl' ) ) {
170 $this->outputRemoteScaledThumb( $file, $params, $flags );
172 $this->outputLocallyScaledThumb( $file, $params, $flags );
177 * Scale a file (probably with a locally installed imagemagick, or similar)
178 * and output it to STDOUT.
180 * @param array $params Scaling parameters ( e.g. array( width => '50' ) );
181 * @param int $flags Scaling flags ( see File:: constants )
182 * @throws MWException|UploadStashFileNotFoundException
183 * @return bool Success
185 private function outputLocallyScaledThumb( $file, $params, $flags ) {
186 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
187 // on HTTP caching to ensure this doesn't happen.
189 $flags |
= File
::RENDER_NOW
;
191 $thumbnailImage = $file->transform( $params, $flags );
192 if ( !$thumbnailImage ) {
193 throw new MWException( 'Could not obtain thumbnail' );
196 // we should have just generated it locally
197 if ( !$thumbnailImage->getStoragePath() ) {
198 throw new UploadStashFileNotFoundException( "no local path for scaled item" );
201 // now we should construct a File, so we can get MIME and other such info in a standard way
202 // n.b. MIME type may be different from original (ogx original -> jpeg thumb)
203 $thumbFile = new UnregisteredLocalFile( false,
204 $this->stash
->repo
, $thumbnailImage->getStoragePath(), false );
206 throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
209 return $this->outputLocalFile( $thumbFile );
213 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation
214 * cluster, and output it to STDOUT.
215 * Note: Unlike the usual thumbnail process, the web client never sees the
216 * cluster URL; we do the whole HTTP transaction to the scaler ourselves
217 * and cat the results out.
218 * Note: We rely on NFS to have propagated the file contents to the scaler.
219 * However, we do not rely on the thumbnail being created in NFS and then
220 * propagated back to our filesystem. Instead we take the results of the
221 * HTTP request instead.
222 * Note: No caching is being done here, although we are instructing the
223 * client to cache it forever.
226 * @param array $params Scaling parameters ( e.g. array( width => '50' ) );
227 * @param int $flags Scaling flags ( see File:: constants )
228 * @throws MWException
229 * @return bool Success
231 private function outputRemoteScaledThumb( $file, $params, $flags ) {
232 // This option probably looks something like
233 // '//upload.wikimedia.org/wikipedia/test/thumb/temp'. Do not use
235 $scalerBaseUrl = $this->getConfig()->get( 'UploadStashScalerBaseUrl' );
237 if ( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
238 // this is apparently a protocol-relative URL, which makes no sense in this context,
239 // since this is used for communication that's internal to the application.
241 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL
);
244 // We need to use generateThumbName() instead of thumbName(), because
245 // the suffix needs to match the file name for the remote thumbnailer
247 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
248 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
249 '/' . rawurlencode( $scalerThumbName );
251 // make a curl call to the scaler to create a thumbnail
252 $httpOptions = array(
254 'timeout' => 5 // T90599 attempt to time out cleanly
256 $req = MWHttpRequest
::factory( $scalerThumbUrl, $httpOptions, __METHOD__
);
257 $status = $req->execute();
258 if ( !$status->isOK() ) {
259 $errors = $status->getErrorsArray();
260 $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 );
261 $errorStr .= "\nurl = $scalerThumbUrl\n";
262 throw new MWException( $errorStr );
264 $contentType = $req->getResponseHeader( "content-type" );
265 if ( !$contentType ) {
266 throw new MWException( "Missing content-type header" );
269 return $this->outputContents( $req->getContent(), $contentType );
273 * Output HTTP response for file
274 * Side effect: writes HTTP response to STDOUT.
276 * @param File $file File object with a local path (e.g. UnregisteredLocalFile,
277 * LocalFile. Oddly these don't share an ancestor!)
278 * @throws SpecialUploadStashTooLargeException
281 private function outputLocalFile( File
$file ) {
282 if ( $file->getSize() > self
::MAX_SERVE_BYTES
) {
283 throw new SpecialUploadStashTooLargeException();
286 return $file->getRepo()->streamFile( $file->getPath(),
287 array( 'Content-Transfer-Encoding: binary',
288 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' )
293 * Output HTTP response of raw content
294 * Side effect: writes HTTP response to STDOUT.
295 * @param string $content Content
296 * @param string $contentType MIME type
297 * @throws SpecialUploadStashTooLargeException
300 private function outputContents( $content, $contentType ) {
301 $size = strlen( $content );
302 if ( $size > self
::MAX_SERVE_BYTES
) {
303 throw new SpecialUploadStashTooLargeException();
305 self
::outputFileHeaders( $contentType, $size );
312 * Output headers for streaming
313 * @todo Unsure about encoding as binary; if we received from HTTP perhaps
314 * we should use that encoding, concatenated with semicolon to `$contentType` as it
316 * Side effect: preps PHP to write headers to STDOUT.
317 * @param string $contentType String suitable for content-type header
318 * @param string $size Length in bytes
320 private static function outputFileHeaders( $contentType, $size ) {
321 header( "Content-Type: $contentType", true );
322 header( 'Content-Transfer-Encoding: binary', true );
323 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
324 // Bug 53032 - It shouldn't be a problem here, but let's be safe and not cache
325 header( 'Cache-Control: private' );
326 header( "Content-Length: $size", true );
330 * Static callback for the HTMLForm in showUploads, to process
331 * Note the stash has to be recreated since this is being called in a static context.
332 * This works, because there really is only one stash per logged-in user, despite appearances.
334 * @param array $formData
335 * @param HTMLForm $form
338 public static function tryClearStashedUploads( $formData, $form ) {
339 if ( isset( $formData['Clear'] ) ) {
340 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $form->getUser() );
341 wfDebug( 'stash has: ' . print_r( $stash->listFiles(), true ) . "\n" );
343 if ( !$stash->clear() ) {
344 return Status
::newFatal( 'uploadstash-errclear' );
348 return Status
::newGood();
352 * Default action when we don't have a subpage -- just show links to the uploads we have,
353 * Also show a button to clear stashed files
356 private function showUploads() {
357 // sets the title, etc.
359 $this->outputHeader();
361 // create the form, which will also be used to execute a callback to process incoming form data
362 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
364 $context = new DerivativeContext( $this->getContext() );
365 $context->setTitle( $this->getPageTitle() ); // Remove subpage
366 $form = new HTMLForm( array(
372 ), $context, 'clearStashedUploads' );
373 $form->setSubmitCallback( array( __CLASS__
, 'tryClearStashedUploads' ) );
374 $form->setSubmitTextMsg( 'uploadstash-clear' );
376 $form->prepareForm();
377 $formResult = $form->tryAuthorizedSubmit();
379 // show the files + form, if there are any, or just say there are none
380 $refreshHtml = Html
::element( 'a',
381 array( 'href' => $this->getPageTitle()->getLocalURL() ),
382 $this->msg( 'uploadstash-refresh' )->text() );
383 $files = $this->stash
->listFiles();
384 if ( $files && count( $files ) ) {
386 $fileListItemsHtml = '';
387 foreach ( $files as $file ) {
388 // TODO: Use Linker::link or even construct the list in plain wikitext
389 $fileListItemsHtml .= Html
::rawElement( 'li', array(),
390 Html
::element( 'a', array( 'href' =>
391 $this->getPageTitle( "file/$file" )->getLocalURL() ), $file )
394 $this->getOutput()->addHtml( Html
::rawElement( 'ul', array(), $fileListItemsHtml ) );
395 $form->displayForm( $formResult );
396 $this->getOutput()->addHtml( Html
::rawElement( 'p', array(), $refreshHtml ) );
398 $this->getOutput()->addHtml( Html
::rawElement( 'p', array(),
399 Html
::element( 'span', array(), $this->msg( 'uploadstash-nofiles' )->text() )
409 class SpecialUploadStashTooLargeException
extends MWException
{