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( $request = null ) {
42 parent
::__construct( 'UploadStash', 'upload' );
44 $this->stash
= RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
45 } catch ( UploadStashNotAvailableException
$e ) {
49 $this->loadRequest( is_null( $request ) ?
$wgRequest : $request );
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 if ( preg_match( '/^(\d+)px-(.*)$/', $key, $matches ) ) {
88 list( /* full match */, $width, $key ) = $matches;
89 return $this->outputThumbFromStash( $key, $width );
91 return $this->outputFileFromStash( $key );
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 * Get a file from stash and stream it out. Rely on parent to catch exceptions and transform them into HTTP
116 * @param String: $key - key of this file in the stash, which probably looks like a filename with extension.
119 private function outputFileFromStash( $key ) {
120 $file = $this->stash
->getFile( $key );
121 return $this->outputLocalFile( $file );
126 * Get a thumbnail for file, either generated locally or remotely, and stream it out
127 * @param String $key: key for the file in the stash
128 * @param int $width: width of desired thumbnail
129 * @return boolean success
131 private function outputThumbFromStash( $key, $width ) {
133 // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb()
134 // 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
135 // happens to share it over NFS
136 global $wgUploadStashScalerBaseUrl;
138 // let exceptions propagate to caller.
139 $file = $this->stash
->getFile( $key );
141 // OK, we're here and no exception was thrown,
142 // so the original file must exist.
144 // let's get ready to transform the original -- these are standard
145 $params = array( 'width' => $width );
148 return $wgUploadStashScalerBaseUrl ?
$this->outputRemoteScaledThumb( $file, $params, $flags )
149 : $this->outputLocallyScaledThumb( $file, $params, $flags );
155 * Scale a file (probably with a locally installed imagemagick, or similar) and output it to STDOUT.
156 * @param $file: File object
157 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
158 * @param $flags: scaling flags ( see File:: constants )
159 * @throws MWException
160 * @return boolean success
162 private function outputLocallyScaledThumb( $file, $params, $flags ) {
164 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
165 // on HTTP caching to ensure this doesn't happen.
167 $flags |
= File
::RENDER_NOW
;
169 $thumbnailImage = $file->transform( $params, $flags );
170 if ( !$thumbnailImage ) {
171 throw new MWException( 'Could not obtain thumbnail' );
174 // we should have just generated it locally
175 if ( ! $thumbnailImage->getPath() ) {
176 throw new UploadStashFileNotFoundException( "no local path for scaled item" );
179 // now we should construct a File, so we can get mime and other such info in a standard way
180 // n.b. mimetype may be different from original (ogx original -> jpeg thumb)
181 $thumbFile = new UnregisteredLocalFile( false, $this->stash
->repo
, $thumbnailImage->getPath(), false );
182 if ( ! $thumbFile ) {
183 throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
186 return $this->outputLocalFile( $thumbFile );
191 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation cluster, and output it to STDOUT.
192 * Note: unlike the usual thumbnail process, the web client never sees the cluster URL; we do the whole HTTP transaction to the scaler ourselves
193 * and cat the results out.
194 * 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
195 * propagated back to our filesystem. Instead we take the results of the HTTP request instead.
196 * Note: no caching is being done here, although we are instructing the client to cache it forever.
197 * @param $file: File object
198 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
199 * @param $flags: scaling flags ( see File:: constants )
200 * @throws MWException
201 * @return boolean success
203 private function outputRemoteScaledThumb( $file, $params, $flags ) {
205 // this global probably looks something like 'http://upload.wikimedia.org/wikipedia/test/thumb/temp'
206 // do not use trailing slash
207 global $wgUploadStashScalerBaseUrl;
209 $scalerThumbName = $file->getParamThumbName( $file->name
, $params );
210 $scalerThumbUrl = $wgUploadStashScalerBaseUrl . '/' . $file->getRel() . '/' . $scalerThumbName;
212 // make a curl call to the scaler to create a thumbnail
213 $httpOptions = array(
215 'timeout' => 'default'
217 $req = MWHttpRequest
::factory( $scalerThumbUrl, $httpOptions );
218 $status = $req->execute();
219 if ( ! $status->isOK() ) {
220 $errors = $status->getErrorsArray();
221 throw new MWException( "Fetching thumbnail failed: " . join( ", ", $errors ) );
223 $contentType = $req->getResponseHeader( "content-type" );
224 if ( ! $contentType ) {
225 throw new MWException( "Missing content-type header" );
227 return $this->outputContents( $req->getContent(), $contentType );
231 * Output HTTP response for file
232 * Side effect: writes HTTP response to STDOUT.
233 * XXX could use wfStreamfile (in includes/Streamfile.php), but for consistency with outputContents() doing it this way.
234 * XXX is mimeType really enough, or do we need encoding for full Content-Type header?
236 * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!)
238 private function outputLocalFile( $file ) {
239 if ( $file->getSize() > self
::MAX_SERVE_BYTES
) {
240 throw new SpecialUploadStashTooLargeException();
242 self
::outputFileHeaders( $file->getMimeType(), $file->getSize() );
243 readfile( $file->getPath() );
248 * Output HTTP response of raw content
249 * Side effect: writes HTTP response to STDOUT.
250 * @param String $content: content
251 * @param String $mimeType: mime type
253 private function outputContents( $content, $contentType ) {
254 $size = strlen( $content );
255 if ( $size > self
::MAX_SERVE_BYTES
) {
256 throw new SpecialUploadStashTooLargeException();
258 self
::outputFileHeaders( $contentType, $size );
264 * Output headers for streaming
265 * 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.
266 * Side effect: preps PHP to write headers to STDOUT.
267 * @param String $contentType : string suitable for content-type header
268 * @param String $size: length in bytes
270 private static function outputFileHeaders( $contentType, $size ) {
271 header( "Content-Type: $contentType", true );
272 header( 'Content-Transfer-Encoding: binary', true );
273 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
274 header( "Content-Length: $size", true );
279 * Initialize authorization & actions to take, from the request
280 * @param $request: WebRequest
282 private function loadRequest( $request ) {
284 if ( $request->wasPosted() ) {
286 $token = $request->getVal( 'wpEditToken' );
287 $this->isEditAuthorized
= $wgUser->matchEditToken( $token );
289 $this->requestedClear
= $request->getBool( 'clear' );
295 * Static callback for the HTMLForm in showUploads, to process
296 * Note the stash has to be recreated since this is being called in a static context.
297 * This works, because there really is only one stash per logged-in user, despite appearances.
301 public static function tryClearStashedUploads( $formData ) {
302 wfDebug( __METHOD__
. " form data : " . print_r( $formData, 1 ) );
303 if ( isset( $formData['clear'] ) and $formData['clear'] ) {
304 $stash = new UploadStash();
305 wfDebug( "stash has: " . print_r( $stash->listFiles(), 1 ) );
306 if ( ! $stash->clear() ) {
307 return Status
::newFatal( 'uploadstash-errclear' );
310 return Status
::newGood();
314 * Default action when we don't have a subpage -- just show links to the uploads we have,
315 * Also show a button to clear stashed files
316 * @param Status : $status - the result of processRequest
318 private function showUploads( $status = null ) {
320 if ( $status === null ) {
321 $status = Status
::newGood();
324 // sets the title, etc.
326 $this->outputHeader();
329 // create the form, which will also be used to execute a callback to process incoming form data
330 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
332 $form = new HTMLForm( array(
338 ), 'clearStashedUploads' );
339 $form->setSubmitCallback( array( __CLASS__
, 'tryClearStashedUploads' ) );
340 $form->setTitle( $this->getTitle() );
341 $form->addHiddenField( 'clear', true, array( 'type' => 'boolean' ) );
342 $form->setSubmitText( wfMsg( 'uploadstash-clear' ) );
344 $form->prepareForm();
345 $formResult = $form->tryAuthorizedSubmit();
348 // show the files + form, if there are any, or just say there are none
349 $refreshHtml = Html
::element( 'a', array( 'href' => $this->getTitle()->getLocalURL() ), wfMsg( 'uploadstash-refresh' ) );
350 $files = $this->stash
->listFiles();
351 if ( count( $files ) ) {
353 $fileListItemsHtml = '';
354 foreach ( $files as $file ) {
355 $fileListItemsHtml .= Html
::rawElement( 'li', array(),
356 Html
::element( 'a', array( 'href' => $this->getTitle( $file )->getLocalURL() ), $file )
359 $wgOut->addHtml( Html
::rawElement( 'ul', array(), $fileListItemsHtml ) );
360 $form->displayForm( $formResult );
361 $wgOut->addHtml( Html
::rawElement( 'p', array(), $refreshHtml ) );
363 $wgOut->addHtml( Html
::rawElement( 'p', array(),
364 Html
::element( 'span', array(), wfMsg( 'uploadstash-nofiles' ) )
374 class SpecialUploadStashTooLargeException
extends MWException
{};