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' );
52 $this->stash
= RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
53 } catch ( UploadStashNotAvailableException
$e ) {
58 * Execute page -- can output a file directly or show a listing of them.
60 * @param string $subPage subpage, e.g. in http://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part
61 * @return Boolean: success
63 public function execute( $subPage ) {
64 $this->checkPermissions();
66 if ( $subPage === null ||
$subPage === '' ) {
67 return $this->showUploads();
70 return $this->showUpload( $subPage );
74 * If file available in stash, cats it out to the client as a simple HTTP response.
75 * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward.
77 * @param string $key the key of a particular requested file
81 public function showUpload( $key ) {
82 // prevent callers from doing standard HTML output -- we'll take it from here
83 $this->getOutput()->disable();
86 $params = $this->parseKey( $key );
87 if ( $params['type'] === 'thumb' ) {
88 return $this->outputThumbFromStash( $params['file'], $params['params'] );
90 return $this->outputLocalFile( $params['file'] );
92 } catch ( UploadStashFileNotFoundException
$e ) {
94 $message = $e->getMessage();
95 } catch ( UploadStashZeroLengthFileException
$e ) {
97 $message = $e->getMessage();
98 } catch ( UploadStashBadPathException
$e ) {
100 $message = $e->getMessage();
101 } catch ( SpecialUploadStashTooLargeException
$e ) {
103 $message = 'Cannot serve a file larger than ' . self
::MAX_SERVE_BYTES
. ' bytes. ' . $e->getMessage();
104 } catch ( Exception
$e ) {
106 $message = $e->getMessage();
109 throw new HttpError( $code, $message );
113 * Parse the key passed to the SpecialPage. Returns an array containing
114 * the associated file object, the type ('file' or 'thumb') and if
115 * application the transform parameters
118 * @throws UploadStashBadPathException
121 private function parseKey( $key ) {
122 $type = strtok( $key, '/' );
124 if ( $type !== 'file' && $type !== 'thumb' ) {
125 throw new UploadStashBadPathException( "Unknown type '$type'" );
127 $fileName = strtok( '/' );
128 $thumbPart = strtok( '/' );
129 $file = $this->stash
->getFile( $fileName );
130 if ( $type === 'thumb' ) {
131 $srcNamePos = strrpos( $thumbPart, $fileName );
132 if ( $srcNamePos === false ||
$srcNamePos < 1 ) {
133 throw new UploadStashBadPathException( 'Unrecognized thumb name' );
135 $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
137 $handler = $file->getHandler();
139 $params = $handler->parseParamString( $paramString );
141 return array( 'file' => $file, 'type' => $type, 'params' => $params );
143 throw new UploadStashBadPathException( 'No handler found for ' .
144 "mime {$file->getMimeType()} of file {$file->getPath()}" );
148 return array( 'file' => $file, 'type' => $type );
152 * Get a thumbnail for file, either generated locally or remotely, and stream it out
155 * @param $params array
157 * @return boolean success
159 private function outputThumbFromStash( $file, $params ) {
161 // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb()
162 // this is part of our horrible NFS-based system, we create a file on a mount point here, but fetch the scaled file from somewhere else that
163 // happens to share it over NFS
164 global $wgUploadStashScalerBaseUrl;
167 if ( $wgUploadStashScalerBaseUrl ) {
168 $this->outputRemoteScaledThumb( $file, $params, $flags );
170 $this->outputLocallyScaledThumb( $file, $params, $flags );
175 * Scale a file (probably with a locally installed imagemagick, or similar) and output it to STDOUT.
177 * @param array $params Scaling parameters ( e.g. array( width => '50' ) );
178 * @param int $flags Scaling flags ( see File:: constants )
179 * @throws MWException
180 * @throws UploadStashFileNotFoundException
181 * @return boolean success
183 private function outputLocallyScaledThumb( $file, $params, $flags ) {
185 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
186 // on HTTP caching to ensure this doesn't happen.
188 $flags |
= File
::RENDER_NOW
;
190 $thumbnailImage = $file->transform( $params, $flags );
191 if ( !$thumbnailImage ) {
192 throw new MWException( 'Could not obtain thumbnail' );
195 // we should have just generated it locally
196 if ( !$thumbnailImage->getStoragePath() ) {
197 throw new UploadStashFileNotFoundException( "no local path for scaled item" );
200 // now we should construct a File, so we can get mime and other such info in a standard way
201 // n.b. mimetype may be different from original (ogx original -> jpeg thumb)
202 $thumbFile = new UnregisteredLocalFile( false,
203 $this->stash
->repo
, $thumbnailImage->getStoragePath(), false );
205 throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
208 return $this->outputLocalFile( $thumbFile );
212 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation cluster, and output it to STDOUT.
213 * Note: unlike the usual thumbnail process, the web client never sees the cluster URL; we do the whole HTTP transaction to the scaler ourselves
214 * and cat the results out.
215 * Note: We rely on NFS to have propagated the file contents to the scaler. 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 HTTP request instead.
217 * Note: no caching is being done here, although we are instructing the client to cache it forever.
219 * @param array $params Scaling parameters ( e.g. array( width => '50' ) );
220 * @param $flags Scaling flags ( see File:: constants )
221 * @throws MWException
222 * @return boolean success
224 private function outputRemoteScaledThumb( $file, $params, $flags ) {
226 // this global probably looks something like 'http://upload.wikimedia.org/wikipedia/test/thumb/temp'
227 // do not use trailing slash
228 global $wgUploadStashScalerBaseUrl;
229 $scalerBaseUrl = $wgUploadStashScalerBaseUrl;
231 if ( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
232 // this is apparently a protocol-relative URL, which makes no sense in this context,
233 // since this is used for communication that's internal to the application.
235 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL
);
238 // We need to use generateThumbName() instead of thumbName(), because
239 // the suffix needs to match the file name for the remote thumbnailer
241 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
242 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
243 '/' . rawurlencode( $scalerThumbName );
245 // make a curl call to the scaler to create a thumbnail
246 $httpOptions = array(
248 'timeout' => 'default'
250 $req = MWHttpRequest
::factory( $scalerThumbUrl, $httpOptions );
251 $status = $req->execute();
252 if ( !$status->isOK() ) {
253 $errors = $status->getErrorsArray();
254 $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 );
255 $errorStr .= "\nurl = $scalerThumbUrl\n";
256 throw new MWException( $errorStr );
258 $contentType = $req->getResponseHeader( "content-type" );
259 if ( !$contentType ) {
260 throw new MWException( "Missing content-type header" );
263 return $this->outputContents( $req->getContent(), $contentType );
267 * Output HTTP response for file
268 * Side effect: writes HTTP response to STDOUT.
270 * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!)
271 * @throws SpecialUploadStashTooLargeException
274 private function outputLocalFile( File
$file ) {
275 if ( $file->getSize() > self
::MAX_SERVE_BYTES
) {
276 throw new SpecialUploadStashTooLargeException();
279 return $file->getRepo()->streamFile( $file->getPath(),
280 array( 'Content-Transfer-Encoding: binary',
281 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' )
286 * Output HTTP response of raw content
287 * Side effect: writes HTTP response to STDOUT.
288 * @param string $content content
289 * @param string $contentType mime type
290 * @throws SpecialUploadStashTooLargeException
293 private function outputContents( $content, $contentType ) {
294 $size = strlen( $content );
295 if ( $size > self
::MAX_SERVE_BYTES
) {
296 throw new SpecialUploadStashTooLargeException();
298 self
::outputFileHeaders( $contentType, $size );
305 * Output headers for streaming
306 * XXX unsure about encoding as binary; if we received from HTTP perhaps we should use that encoding, concatted with semicolon to mimeType as it usually is.
307 * Side effect: preps PHP to write headers to STDOUT.
308 * @param string $contentType String suitable for content-type header
309 * @param string $size Length in bytes
311 private static function outputFileHeaders( $contentType, $size ) {
312 header( "Content-Type: $contentType", true );
313 header( 'Content-Transfer-Encoding: binary', true );
314 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
315 // Bug 53032 - It shouldn't be a problem here, but let's be safe and not cache
316 header( 'Cache-Control: private' );
317 header( "Content-Length: $size", true );
321 * Static callback for the HTMLForm in showUploads, to process
322 * Note the stash has to be recreated since this is being called in a static context.
323 * This works, because there really is only one stash per logged-in user, despite appearances.
325 * @param array $formData
328 public static function tryClearStashedUploads( $formData ) {
329 if ( isset( $formData['Clear'] ) ) {
330 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
331 wfDebug( "stash has: " . print_r( $stash->listFiles(), true ) );
333 if ( !$stash->clear() ) {
334 return Status
::newFatal( 'uploadstash-errclear' );
338 return Status
::newGood();
342 * Default action when we don't have a subpage -- just show links to the uploads we have,
343 * Also show a button to clear stashed files
346 private function showUploads() {
347 // sets the title, etc.
349 $this->outputHeader();
351 // create the form, which will also be used to execute a callback to process incoming form data
352 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
354 $context = new DerivativeContext( $this->getContext() );
355 $context->setTitle( $this->getPageTitle() ); // Remove subpage
356 $form = new HTMLForm( array(
362 ), $context, 'clearStashedUploads' );
363 $form->setSubmitCallback( array( __CLASS__
, 'tryClearStashedUploads' ) );
364 $form->setSubmitTextMsg( 'uploadstash-clear' );
366 $form->prepareForm();
367 $formResult = $form->tryAuthorizedSubmit();
369 // show the files + form, if there are any, or just say there are none
370 $refreshHtml = Html
::element( 'a',
371 array( 'href' => $this->getPageTitle()->getLocalURL() ),
372 $this->msg( 'uploadstash-refresh' )->text() );
373 $files = $this->stash
->listFiles();
374 if ( $files && count( $files ) ) {
376 $fileListItemsHtml = '';
377 foreach ( $files as $file ) {
378 // TODO: Use Linker::link or even construct the list in plain wikitext
379 $fileListItemsHtml .= Html
::rawElement( 'li', array(),
380 Html
::element( 'a', array( 'href' =>
381 $this->getPageTitle( "file/$file" )->getLocalURL() ), $file )
384 $this->getOutput()->addHtml( Html
::rawElement( 'ul', array(), $fileListItemsHtml ) );
385 $form->displayForm( $formResult );
386 $this->getOutput()->addHtml( Html
::rawElement( 'p', array(), $refreshHtml ) );
388 $this->getOutput()->addHtml( Html
::rawElement( 'p', array(),
389 Html
::element( 'span', array(), $this->msg( 'uploadstash-nofiles' )->text() )
399 class SpecialUploadStashTooLargeException
extends MWException
{