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
{
39 // Since we are directly writing the file to STDOUT,
40 // we should not be reading in really big files and serving them out.
42 // We also don't want people using this as a file drop, even if they
45 // This service is really for thumbnails and other such previews while
47 const MAX_SERVE_BYTES
= 1048576; // 1MB
49 public function __construct() {
50 parent
::__construct( 'UploadStash', 'upload' );
54 * Execute page -- can output a file directly or show a listing of them.
56 * @param string $subPage Subpage, e.g. in
57 * http://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part
58 * @return bool Success
60 public function execute( $subPage ) {
61 $this->stash
= RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
62 $this->checkPermissions();
64 if ( $subPage === null ||
$subPage === '' ) {
65 return $this->showUploads();
68 return $this->showUpload( $subPage );
72 * If file available in stash, cats it out to the client as a simple HTTP response.
73 * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward.
75 * @param string $key The key of a particular requested file
79 public function showUpload( $key ) {
80 // prevent callers from doing standard HTML output -- we'll take it from here
81 $this->getOutput()->disable();
84 $params = $this->parseKey( $key );
85 if ( $params['type'] === 'thumb' ) {
86 return $this->outputThumbFromStash( $params['file'], $params['params'] );
88 return $this->outputLocalFile( $params['file'] );
90 } catch ( UploadStashFileNotFoundException
$e ) {
92 $message = $e->getMessage();
93 } catch ( UploadStashZeroLengthFileException
$e ) {
95 $message = $e->getMessage();
96 } catch ( UploadStashBadPathException
$e ) {
98 $message = $e->getMessage();
99 } catch ( SpecialUploadStashTooLargeException
$e ) {
101 $message = 'Cannot serve a file larger than ' . self
::MAX_SERVE_BYTES
.
102 ' bytes. ' . $e->getMessage();
103 } catch ( Exception
$e ) {
105 $message = $e->getMessage();
108 throw new HttpError( $code, $message );
112 * Parse the key passed to the SpecialPage. Returns an array containing
113 * the associated file object, the type ('file' or 'thumb') and if
114 * application the transform parameters
117 * @throws UploadStashBadPathException
120 private function parseKey( $key ) {
121 $type = strtok( $key, '/' );
123 if ( $type !== 'file' && $type !== 'thumb' ) {
124 throw new UploadStashBadPathException( "Unknown type '$type'" );
126 $fileName = strtok( '/' );
127 $thumbPart = strtok( '/' );
128 $file = $this->stash
->getFile( $fileName );
129 if ( $type === 'thumb' ) {
130 $srcNamePos = strrpos( $thumbPart, $fileName );
131 if ( $srcNamePos === false ||
$srcNamePos < 1 ) {
132 throw new UploadStashBadPathException( 'Unrecognized thumb name' );
134 $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
136 $handler = $file->getHandler();
138 $params = $handler->parseParamString( $paramString );
140 return array( 'file' => $file, 'type' => $type, 'params' => $params );
142 throw new UploadStashBadPathException( 'No handler found for ' .
143 "mime {$file->getMimeType()} of file {$file->getPath()}" );
147 return array( 'file' => $file, 'type' => $type );
151 * Get a thumbnail for file, either generated locally or remotely, and stream it out
154 * @param array $params
156 * @return bool Success
158 private function outputThumbFromStash( $file, $params ) {
160 // this config option, if it exists, points to a "scaler", as you might find in
161 // the Wikimedia Foundation cluster. See outputRemoteScaledThumb(). This
162 // is part of our horrible NFS-based system, we create a file on a mount
163 // point here, but fetch the scaled file from somewhere else that
164 // happens to share it over NFS.
165 if ( $this->getConfig()->get( 'UploadStashScalerBaseUrl' ) ) {
166 $this->outputRemoteScaledThumb( $file, $params, $flags );
168 $this->outputLocallyScaledThumb( $file, $params, $flags );
173 * Scale a file (probably with a locally installed imagemagick, or similar)
174 * and output it to STDOUT.
176 * @param array $params Scaling parameters ( e.g. array( width => '50' ) );
177 * @param int $flags Scaling flags ( see File:: constants )
178 * @throws MWException|UploadStashFileNotFoundException
179 * @return bool Success
181 private function outputLocallyScaledThumb( $file, $params, $flags ) {
182 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
183 // on HTTP caching to ensure this doesn't happen.
185 $flags |
= File
::RENDER_NOW
;
187 $thumbnailImage = $file->transform( $params, $flags );
188 if ( !$thumbnailImage ) {
189 throw new MWException( 'Could not obtain thumbnail' );
192 // we should have just generated it locally
193 if ( !$thumbnailImage->getStoragePath() ) {
194 throw new UploadStashFileNotFoundException( "no local path for scaled item" );
197 // now we should construct a File, so we can get MIME and other such info in a standard way
198 // n.b. MIME type may be different from original (ogx original -> jpeg thumb)
199 $thumbFile = new UnregisteredLocalFile( false,
200 $this->stash
->repo
, $thumbnailImage->getStoragePath(), false );
202 throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
205 return $this->outputLocalFile( $thumbFile );
209 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation
210 * cluster, and output it to STDOUT.
211 * Note: Unlike the usual thumbnail process, the web client never sees the
212 * cluster URL; we do the whole HTTP transaction to the scaler ourselves
213 * and cat the results out.
214 * Note: We rely on NFS to have propagated the file contents to the scaler.
215 * However, we do not rely on the thumbnail being created in NFS and then
216 * propagated back to our filesystem. Instead we take the results of the
217 * HTTP request instead.
218 * Note: No caching is being done here, although we are instructing the
219 * client to cache it forever.
222 * @param array $params Scaling parameters ( e.g. array( width => '50' ) );
223 * @param int $flags Scaling flags ( see File:: constants )
224 * @throws MWException
225 * @return bool Success
227 private function outputRemoteScaledThumb( $file, $params, $flags ) {
228 // This option probably looks something like
229 // 'http://upload.wikimedia.org/wikipedia/test/thumb/temp'. Do not use
231 $scalerBaseUrl = $this->getConfig()->get( 'UploadStashScalerBaseUrl' );
233 if ( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
234 // this is apparently a protocol-relative URL, which makes no sense in this context,
235 // since this is used for communication that's internal to the application.
237 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL
);
240 // We need to use generateThumbName() instead of thumbName(), because
241 // the suffix needs to match the file name for the remote thumbnailer
243 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
244 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
245 '/' . rawurlencode( $scalerThumbName );
247 // make a curl call to the scaler to create a thumbnail
248 $httpOptions = array(
250 'timeout' => 5 // T90599 attempt to time out cleanly
252 $req = MWHttpRequest
::factory( $scalerThumbUrl, $httpOptions, __METHOD__
);
253 $status = $req->execute();
254 if ( !$status->isOK() ) {
255 $errors = $status->getErrorsArray();
256 $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 );
257 $errorStr .= "\nurl = $scalerThumbUrl\n";
258 throw new MWException( $errorStr );
260 $contentType = $req->getResponseHeader( "content-type" );
261 if ( !$contentType ) {
262 throw new MWException( "Missing content-type header" );
265 return $this->outputContents( $req->getContent(), $contentType );
269 * Output HTTP response for file
270 * Side effect: writes HTTP response to STDOUT.
272 * @param File $file File object with a local path (e.g. UnregisteredLocalFile,
273 * LocalFile. Oddly these don't share an ancestor!)
274 * @throws SpecialUploadStashTooLargeException
277 private function outputLocalFile( File
$file ) {
278 if ( $file->getSize() > self
::MAX_SERVE_BYTES
) {
279 throw new SpecialUploadStashTooLargeException();
282 return $file->getRepo()->streamFile( $file->getPath(),
283 array( 'Content-Transfer-Encoding: binary',
284 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' )
289 * Output HTTP response of raw content
290 * Side effect: writes HTTP response to STDOUT.
291 * @param string $content Content
292 * @param string $contentType MIME type
293 * @throws SpecialUploadStashTooLargeException
296 private function outputContents( $content, $contentType ) {
297 $size = strlen( $content );
298 if ( $size > self
::MAX_SERVE_BYTES
) {
299 throw new SpecialUploadStashTooLargeException();
301 self
::outputFileHeaders( $contentType, $size );
308 * Output headers for streaming
309 * @todo Unsure about encoding as binary; if we received from HTTP perhaps
310 * we should use that encoding, concatenated with semicolon to `$contentType` as it
312 * Side effect: preps PHP to write headers to STDOUT.
313 * @param string $contentType String suitable for content-type header
314 * @param string $size Length in bytes
316 private static function outputFileHeaders( $contentType, $size ) {
317 header( "Content-Type: $contentType", true );
318 header( 'Content-Transfer-Encoding: binary', true );
319 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
320 // Bug 53032 - It shouldn't be a problem here, but let's be safe and not cache
321 header( 'Cache-Control: private' );
322 header( "Content-Length: $size", true );
326 * Static callback for the HTMLForm in showUploads, to process
327 * Note the stash has to be recreated since this is being called in a static context.
328 * This works, because there really is only one stash per logged-in user, despite appearances.
330 * @param array $formData
331 * @param HTMLForm $form
334 public static function tryClearStashedUploads( $formData, $form ) {
335 if ( isset( $formData['Clear'] ) ) {
336 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $form->getUser() );
337 wfDebug( 'stash has: ' . print_r( $stash->listFiles(), true ) . "\n" );
339 if ( !$stash->clear() ) {
340 return Status
::newFatal( 'uploadstash-errclear' );
344 return Status
::newGood();
348 * Default action when we don't have a subpage -- just show links to the uploads we have,
349 * Also show a button to clear stashed files
352 private function showUploads() {
353 // sets the title, etc.
355 $this->outputHeader();
357 // create the form, which will also be used to execute a callback to process incoming form data
358 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
360 $context = new DerivativeContext( $this->getContext() );
361 $context->setTitle( $this->getPageTitle() ); // Remove subpage
362 $form = new HTMLForm( array(
368 ), $context, 'clearStashedUploads' );
369 $form->setSubmitCallback( array( __CLASS__
, 'tryClearStashedUploads' ) );
370 $form->setSubmitTextMsg( 'uploadstash-clear' );
372 $form->prepareForm();
373 $formResult = $form->tryAuthorizedSubmit();
375 // show the files + form, if there are any, or just say there are none
376 $refreshHtml = Html
::element( 'a',
377 array( 'href' => $this->getPageTitle()->getLocalURL() ),
378 $this->msg( 'uploadstash-refresh' )->text() );
379 $files = $this->stash
->listFiles();
380 if ( $files && count( $files ) ) {
382 $fileListItemsHtml = '';
383 foreach ( $files as $file ) {
384 // TODO: Use Linker::link or even construct the list in plain wikitext
385 $fileListItemsHtml .= Html
::rawElement( 'li', array(),
386 Html
::element( 'a', array( 'href' =>
387 $this->getPageTitle( "file/$file" )->getLocalURL() ), $file )
390 $this->getOutput()->addHtml( Html
::rawElement( 'ul', array(), $fileListItemsHtml ) );
391 $form->displayForm( $formResult );
392 $this->getOutput()->addHtml( Html
::rawElement( 'p', array(), $refreshHtml ) );
394 $this->getOutput()->addHtml( Html
::rawElement( 'p', array(),
395 Html
::element( 'span', array(), $this->msg( 'uploadstash-nofiles' )->text() )
405 class SpecialUploadStashTooLargeException
extends MWException
{