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 // Since we are directly writing the file to STDOUT,
24 // we should not be reading in really big files and serving them out.
26 // We also don't want people using this as a file drop, even if they
29 // This service is really for thumbnails and other such previews while
31 const MAX_SERVE_BYTES
= 1048576; // 1MB
33 public function __construct() {
34 parent
::__construct( 'UploadStash', 'upload' );
36 $this->stash
= RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
37 } catch ( UploadStashNotAvailableException
$e ) {
43 * Execute page -- can output a file directly or show a listing of them.
45 * @param $subPage String: subpage, e.g. in http://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part
46 * @return Boolean: success
48 public function execute( $subPage ) {
49 if ( !$this->userCanExecute( $this->getUser() ) ) {
50 $this->displayRestrictionError();
54 if ( $subPage === null ||
$subPage === '' ) {
55 return $this->showUploads();
57 return $this->showUpload( $subPage );
63 * If file available in stash, cats it out to the client as a simple HTTP response.
64 * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward.
66 * @param $key String: the key of a particular requested file
68 public function showUpload( $key ) {
69 // prevent callers from doing standard HTML output -- we'll take it from here
70 $this->getOutput()->disable();
73 $params = $this->parseKey( $key );
74 if ( $params['type'] === 'thumb' ) {
75 return $this->outputThumbFromStash( $params['file'], $params['params'] );
77 return $this->outputLocalFile( $params['file'] );
79 } catch( UploadStashFileNotFoundException
$e ) {
81 $message = $e->getMessage();
82 } catch( UploadStashZeroLengthFileException
$e ) {
84 $message = $e->getMessage();
85 } catch( UploadStashBadPathException
$e ) {
87 $message = $e->getMessage();
88 } catch( SpecialUploadStashTooLargeException
$e ) {
90 $message = 'Cannot serve a file larger than ' . self
::MAX_SERVE_BYTES
. ' bytes. ' . $e->getMessage();
91 } catch( Exception
$e ) {
93 $message = $e->getMessage();
96 throw new HttpError( $code, $message );
100 * Parse the key passed to the SpecialPage. Returns an array containing
101 * the associated file object, the type ('file' or 'thumb') and if
102 * application the transform parameters
107 private function parseKey( $key ) {
108 $type = strtok( $key, '/' );
110 if ( $type !== 'file' && $type !== 'thumb' ) {
111 throw new UploadStashBadPathException( "Unknown type '$type'" );
113 $fileName = strtok( '/' );
114 $thumbPart = strtok( '/' );
115 $file = $this->stash
->getFile( $fileName );
116 if ( $type === 'thumb' ) {
117 $srcNamePos = strrpos( $thumbPart, $fileName );
118 if ( $srcNamePos === false ||
$srcNamePos < 1 ) {
119 throw new UploadStashBadPathException( 'Unrecognized thumb name' );
121 $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
123 $handler = $file->getHandler();
124 $params = $handler->parseParamString( $paramString );
125 return array( 'file' => $file, 'type' => $type, 'params' => $params );
128 return array( 'file' => $file, 'type' => $type );
132 * Get a thumbnail for file, either generated locally or remotely, and stream it out
135 * @param $params array
137 * @return boolean success
139 private function outputThumbFromStash( $file, $params ) {
141 // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb()
142 // 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
143 // happens to share it over NFS
144 global $wgUploadStashScalerBaseUrl;
147 if ( $wgUploadStashScalerBaseUrl ) {
148 $this->outputRemoteScaledThumb( $file, $params, $flags );
150 $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;
208 $scalerBaseUrl = $wgUploadStashScalerBaseUrl;
210 if( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
211 // this is apparently a protocol-relative URL, which makes no sense in this context,
212 // since this is used for communication that's internal to the application.
214 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL
);
217 // We need to use generateThumbName() instead of thumbName(), because
218 // the suffix needs to match the file name for the remote thumbnailer
220 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
221 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
222 '/' . rawurlencode( $scalerThumbName );
224 // make a curl call to the scaler to create a thumbnail
225 $httpOptions = array(
227 'timeout' => 'default'
229 $req = MWHttpRequest
::factory( $scalerThumbUrl, $httpOptions );
230 $status = $req->execute();
231 if ( ! $status->isOK() ) {
232 $errors = $status->getErrorsArray();
233 $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 );
234 $errorStr .= "\nurl = $scalerThumbUrl\n";
235 throw new MWException( $errorStr );
237 $contentType = $req->getResponseHeader( "content-type" );
238 if ( ! $contentType ) {
239 throw new MWException( "Missing content-type header" );
241 return $this->outputContents( $req->getContent(), $contentType );
245 * Output HTTP response for file
246 * Side effect: writes HTTP response to STDOUT.
247 * XXX could use wfStreamfile (in includes/Streamfile.php), but for consistency with outputContents() doing it this way.
248 * XXX is mimeType really enough, or do we need encoding for full Content-Type header?
250 * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!)
252 private function outputLocalFile( $file ) {
253 if ( $file->getSize() > self
::MAX_SERVE_BYTES
) {
254 throw new SpecialUploadStashTooLargeException();
256 self
::outputFileHeaders( $file->getMimeType(), $file->getSize() );
257 readfile( $file->getPath() );
262 * Output HTTP response of raw content
263 * Side effect: writes HTTP response to STDOUT.
264 * @param String $content: content
265 * @param String $mimeType: mime type
267 private function outputContents( $content, $contentType ) {
268 $size = strlen( $content );
269 if ( $size > self
::MAX_SERVE_BYTES
) {
270 throw new SpecialUploadStashTooLargeException();
272 self
::outputFileHeaders( $contentType, $size );
278 * Output headers for streaming
279 * 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.
280 * Side effect: preps PHP to write headers to STDOUT.
281 * @param String $contentType : string suitable for content-type header
282 * @param String $size: length in bytes
284 private static function outputFileHeaders( $contentType, $size ) {
285 header( "Content-Type: $contentType", true );
286 header( 'Content-Transfer-Encoding: binary', true );
287 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
288 header( "Content-Length: $size", true );
292 * Static callback for the HTMLForm in showUploads, to process
293 * Note the stash has to be recreated since this is being called in a static context.
294 * This works, because there really is only one stash per logged-in user, despite appearances.
298 public static function tryClearStashedUploads( $formData ) {
299 if ( isset( $formData['Clear'] ) ) {
300 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
301 wfDebug( "stash has: " . print_r( $stash->listFiles(), true ) );
302 if ( ! $stash->clear() ) {
303 return Status
::newFatal( 'uploadstash-errclear' );
306 return Status
::newGood();
310 * Default action when we don't have a subpage -- just show links to the uploads we have,
311 * Also show a button to clear stashed files
312 * @param Status : $status - the result of processRequest
314 private function showUploads( $status = null ) {
315 if ( $status === null ) {
316 $status = Status
::newGood();
319 // sets the title, etc.
321 $this->outputHeader();
323 // create the form, which will also be used to execute a callback to process incoming form data
324 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
326 $form = new HTMLForm( array(
332 ), $this->getContext(), 'clearStashedUploads' );
333 $form->setSubmitCallback( array( __CLASS__
, 'tryClearStashedUploads' ) );
334 $form->setTitle( $this->getTitle() );
335 $form->setSubmitText( wfMsg( 'uploadstash-clear' ) );
337 $form->prepareForm();
338 $formResult = $form->tryAuthorizedSubmit();
340 // show the files + form, if there are any, or just say there are none
341 $refreshHtml = Html
::element( 'a',
342 array( 'href' => $this->getTitle()->getLocalURL() ),
343 wfMsg( 'uploadstash-refresh' ) );
344 $files = $this->stash
->listFiles();
345 if ( $files && count( $files ) ) {
347 $fileListItemsHtml = '';
348 foreach ( $files as $file ) {
349 // TODO: Use Linker::link or even construct the list in plain wikitext
350 $fileListItemsHtml .= Html
::rawElement( 'li', array(),
351 Html
::element( 'a', array( 'href' =>
352 $this->getTitle( "file/$file" )->getLocalURL() ), $file )
355 $this->getOutput()->addHtml( Html
::rawElement( 'ul', array(), $fileListItemsHtml ) );
356 $form->displayForm( $formResult );
357 $this->getOutput()->addHtml( Html
::rawElement( 'p', array(), $refreshHtml ) );
359 $this->getOutput()->addHtml( Html
::rawElement( 'p', array(),
360 Html
::element( 'span', array(), wfMsg( 'uploadstash-nofiles' ) )
370 class SpecialUploadStashTooLargeException
extends MWException
{};