3 * Implements Special:UploadStash
5 * Web access for files temporarily stored by UploadStash.
7 * For example -- files that were uploaded with the UploadWizard extension are stored temporarily
8 * before committing them to the db. But we want to see their thumbnails and get other information
11 * Since this is based on the user's session, in effect this creates a private temporary file area.
12 * However, the URLs for the files cannot be shared.
15 * @ingroup SpecialPage
19 class SpecialUploadStash
extends UnlistedSpecialPage
{
23 // is the edit request authorized? boolean
24 private $isEditAuthorized;
26 // did the user request us to clear the stash? boolean
27 private $requestedClear;
29 // Since we are directly writing the file to STDOUT,
30 // we should not be reading in really big files and serving them out.
32 // We also don't want people using this as a file drop, even if they
35 // This service is really for thumbnails and other such previews while
37 const MAX_SERVE_BYTES
= 262144; // 256K
39 public function __construct() {
42 parent
::__construct( 'UploadStash', 'upload' );
44 $this->stash
= RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
45 } catch ( UploadStashNotAvailableException
$e ) {
49 $this->loadRequest( $wgRequest );
53 * Execute page -- can output a file directly or show a listing of them.
55 * @param $subPage String: subpage, e.g. in http://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part
56 * @return Boolean: success
58 public function execute( $subPage ) {
61 if ( !$this->userCanExecute( $wgUser ) ) {
62 $this->displayRestrictionError();
66 if ( !isset( $subPage ) ||
$subPage === '' ) {
67 return $this->showUploads();
70 return $this->showUpload( $subPage );
75 * If file available in stash, cats it out to the client as a simple HTTP response.
76 * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward.
78 * @param $key String: the key of a particular requested file
80 public function showUpload( $key ) {
83 // prevent callers from doing standard HTML output -- we'll take it from here
87 $params = $this->parseKey( $key );
88 if ( $params['type'] === 'thumb' ) {
89 return $this->outputThumbFromStash( $params['file'], $params['params'] );
91 return $this->outputLocalFile( $params['file'] );
93 } catch( UploadStashFileNotFoundException
$e ) {
95 $message = $e->getMessage();
96 } catch( UploadStashZeroLengthFileException
$e ) {
98 $message = $e->getMessage();
99 } catch( UploadStashBadPathException
$e ) {
101 $message = $e->getMessage();
102 } catch( SpecialUploadStashTooLargeException
$e ) {
104 $message = 'Cannot serve a file larger than ' . self
::MAX_SERVE_BYTES
. ' bytes. ' . $e->getMessage();
105 } catch( Exception
$e ) {
107 $message = $e->getMessage();
110 wfHttpError( $code, OutputPage
::getStatusMessage( $code ), $message );
115 * Parse the key passed to the SpecialPage. Returns an array containing
116 * the associated file object, the type ('file' or 'thumb') and if
117 * application the transform parameters
122 private function parseKey( $key ) {
123 $type = strtok( $key, '/' );
125 if ( $type !== 'file' && $type !== 'thumb' ) {
126 throw new UploadStashBadPathException( "Unknown type '$type'" );
128 $fileName = strtok( '/' );
129 $thumbPart = strtok( '/' );
130 $file = $this->stash
->getFile( $fileName );
131 if ( $type === 'thumb' ) {
132 $srcNamePos = strrpos( $thumbPart, $fileName );
133 if ( $srcNamePos === false ||
$srcNamePos < 1 ) {
134 throw new UploadStashBadPathException( 'Unrecognized thumb name' );
136 $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
138 $handler = $file->getHandler();
139 $params = $handler->parseParamString( $paramString );
140 return array( 'file' => $file, 'type' => $type, 'params' => $params );
143 return array( 'file' => $file, 'type' => $type );
150 * Get a thumbnail for file, either generated locally or remotely, and stream it out
151 * @param String $key: key for the file in the stash
152 * @param int $width: width of desired thumbnail
153 * @return boolean success
155 private function outputThumbFromStash( $file, $params ) {
157 // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb()
158 // 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
159 // happens to share it over NFS
160 global $wgUploadStashScalerBaseUrl;
163 if ( $wgUploadStashScalerBaseUrl ) {
164 $this->outputRemoteScaledThumb( $file, $params, $flags );
166 $this->outputLocallyScaledThumb( $file, $params, $flags );
174 * Scale a file (probably with a locally installed imagemagick, or similar) and output it to STDOUT.
175 * @param $file: File object
176 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
177 * @param $flags: scaling flags ( see File:: constants )
178 * @throws MWException
179 * @return boolean success
181 private function outputLocallyScaledThumb( $file, $params, $flags ) {
183 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
184 // on HTTP caching to ensure this doesn't happen.
186 $flags |
= File
::RENDER_NOW
;
188 $thumbnailImage = $file->transform( $params, $flags );
189 if ( !$thumbnailImage ) {
190 throw new MWException( 'Could not obtain thumbnail' );
193 // we should have just generated it locally
194 if ( ! $thumbnailImage->getPath() ) {
195 throw new UploadStashFileNotFoundException( "no local path for scaled item" );
198 // now we should construct a File, so we can get mime and other such info in a standard way
199 // n.b. mimetype may be different from original (ogx original -> jpeg thumb)
200 $thumbFile = new UnregisteredLocalFile( false, $this->stash
->repo
, $thumbnailImage->getPath(), false );
201 if ( ! $thumbFile ) {
202 throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
205 return $this->outputLocalFile( $thumbFile );
210 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation cluster, and output it to STDOUT.
211 * Note: unlike the usual thumbnail process, the web client never sees the cluster URL; we do the whole HTTP transaction to the scaler ourselves
212 * and cat the results out.
213 * 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
214 * propagated back to our filesystem. Instead we take the results of the HTTP request instead.
215 * Note: no caching is being done here, although we are instructing the client to cache it forever.
216 * @param $file: File object
217 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
218 * @param $flags: scaling flags ( see File:: constants )
219 * @throws MWException
220 * @return boolean success
222 private function outputRemoteScaledThumb( $file, $params, $flags ) {
224 // this global probably looks something like 'http://upload.wikimedia.org/wikipedia/test/thumb/temp'
225 // do not use trailing slash
226 global $wgUploadStashScalerBaseUrl;
228 $scalerThumbName = $file->getParamThumbName( $file->name
, $params );
229 $scalerThumbUrl = $wgUploadStashScalerBaseUrl . '/' . $file->getRel() . '/' . $scalerThumbName;
231 // make a curl call to the scaler to create a thumbnail
232 $httpOptions = array(
234 'timeout' => 'default'
236 $req = MWHttpRequest
::factory( $scalerThumbUrl, $httpOptions );
237 $status = $req->execute();
238 if ( ! $status->isOK() ) {
239 $errors = $status->getErrorsArray();
240 throw new MWException( "Fetching thumbnail failed: " . join( ", ", $errors ) );
242 $contentType = $req->getResponseHeader( "content-type" );
243 if ( ! $contentType ) {
244 throw new MWException( "Missing content-type header" );
246 return $this->outputContents( $req->getContent(), $contentType );
250 * Output HTTP response for file
251 * Side effect: writes HTTP response to STDOUT.
252 * XXX could use wfStreamfile (in includes/Streamfile.php), but for consistency with outputContents() doing it this way.
253 * XXX is mimeType really enough, or do we need encoding for full Content-Type header?
255 * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!)
257 private function outputLocalFile( $file ) {
258 if ( $file->getSize() > self
::MAX_SERVE_BYTES
) {
259 throw new SpecialUploadStashTooLargeException();
261 self
::outputFileHeaders( $file->getMimeType(), $file->getSize() );
262 readfile( $file->getPath() );
267 * Output HTTP response of raw content
268 * Side effect: writes HTTP response to STDOUT.
269 * @param String $content: content
270 * @param String $mimeType: mime type
272 private function outputContents( $content, $contentType ) {
273 $size = strlen( $content );
274 if ( $size > self
::MAX_SERVE_BYTES
) {
275 throw new SpecialUploadStashTooLargeException();
277 self
::outputFileHeaders( $contentType, $size );
283 * Output headers for streaming
284 * 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.
285 * Side effect: preps PHP to write headers to STDOUT.
286 * @param String $contentType : string suitable for content-type header
287 * @param String $size: length in bytes
289 private static function outputFileHeaders( $contentType, $size ) {
290 header( "Content-Type: $contentType", true );
291 header( 'Content-Transfer-Encoding: binary', true );
292 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
293 header( "Content-Length: $size", true );
298 * Initialize authorization & actions to take, from the request
299 * @param $request: WebRequest
301 private function loadRequest( $request ) {
303 if ( $request->wasPosted() ) {
305 $token = $request->getVal( 'wpEditToken' );
306 $this->isEditAuthorized
= $wgUser->matchEditToken( $token );
308 $this->requestedClear
= $request->getBool( 'clear' );
314 * Static callback for the HTMLForm in showUploads, to process
315 * Note the stash has to be recreated since this is being called in a static context.
316 * This works, because there really is only one stash per logged-in user, despite appearances.
320 public static function tryClearStashedUploads( $formData ) {
321 wfDebug( __METHOD__
. " form data : " . print_r( $formData, 1 ) );
322 if ( isset( $formData['clear'] ) and $formData['clear'] ) {
323 $stash = new UploadStash();
324 wfDebug( "stash has: " . print_r( $stash->listFiles(), 1 ) );
325 if ( ! $stash->clear() ) {
326 return Status
::newFatal( 'uploadstash-errclear' );
329 return Status
::newGood();
333 * Default action when we don't have a subpage -- just show links to the uploads we have,
334 * Also show a button to clear stashed files
335 * @param Status : $status - the result of processRequest
337 private function showUploads( $status = null ) {
339 if ( $status === null ) {
340 $status = Status
::newGood();
343 // sets the title, etc.
345 $this->outputHeader();
348 // create the form, which will also be used to execute a callback to process incoming form data
349 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
351 $form = new HTMLForm( array(
357 ), 'clearStashedUploads' );
358 $form->setSubmitCallback( array( __CLASS__
, 'tryClearStashedUploads' ) );
359 $form->setTitle( $this->getTitle() );
360 $form->addHiddenField( 'clear', true, array( 'type' => 'boolean' ) );
361 $form->setSubmitText( wfMsg( 'uploadstash-clear' ) );
363 $form->prepareForm();
364 $formResult = $form->tryAuthorizedSubmit();
367 // show the files + form, if there are any, or just say there are none
368 $refreshHtml = Html
::element( 'a', array( 'href' => $this->getTitle()->getLocalURL() ), wfMsg( 'uploadstash-refresh' ) );
369 $files = $this->stash
->listFiles();
370 if ( count( $files ) ) {
372 $fileListItemsHtml = '';
373 foreach ( $files as $file ) {
374 $fileListItemsHtml .= Html
::rawElement( 'li', array(),
375 Html
::element( 'a', array( 'href' =>
376 $this->getTitle( "file/$file" )->getLocalURL() ), $file )
379 $wgOut->addHtml( Html
::rawElement( 'ul', array(), $fileListItemsHtml ) );
380 $form->displayForm( $formResult );
381 $wgOut->addHtml( Html
::rawElement( 'p', array(), $refreshHtml ) );
383 $wgOut->addHtml( Html
::rawElement( 'p', array(),
384 Html
::element( 'span', array(), wfMsg( 'uploadstash-nofiles' ) )
394 class SpecialUploadStashTooLargeException
extends MWException
{};