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 ) {
51 if ( !$this->userCanExecute( $wgUser ) ) {
52 $this->displayRestrictionError();
56 if ( $subPage === null ||
$subPage === '' ) {
57 return $this->showUploads();
59 return $this->showUpload( $subPage );
65 * If file available in stash, cats it out to the client as a simple HTTP response.
66 * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward.
68 * @param $key String: the key of a particular requested file
70 public function showUpload( $key ) {
71 // prevent callers from doing standard HTML output -- we'll take it from here
72 $this->getOutput()->disable();
75 $params = $this->parseKey( $key );
76 if ( $params['type'] === 'thumb' ) {
77 return $this->outputThumbFromStash( $params['file'], $params['params'] );
79 return $this->outputLocalFile( $params['file'] );
81 } catch( UploadStashFileNotFoundException
$e ) {
83 $message = $e->getMessage();
84 } catch( UploadStashZeroLengthFileException
$e ) {
86 $message = $e->getMessage();
87 } catch( UploadStashBadPathException
$e ) {
89 $message = $e->getMessage();
90 } catch( SpecialUploadStashTooLargeException
$e ) {
92 $message = 'Cannot serve a file larger than ' . self
::MAX_SERVE_BYTES
. ' bytes. ' . $e->getMessage();
93 } catch( Exception
$e ) {
95 $message = $e->getMessage();
98 throw new HttpError( $code, $message );
102 * Parse the key passed to the SpecialPage. Returns an array containing
103 * the associated file object, the type ('file' or 'thumb') and if
104 * application the transform parameters
109 private function parseKey( $key ) {
110 $type = strtok( $key, '/' );
112 if ( $type !== 'file' && $type !== 'thumb' ) {
113 throw new UploadStashBadPathException( "Unknown type '$type'" );
115 $fileName = strtok( '/' );
116 $thumbPart = strtok( '/' );
117 $file = $this->stash
->getFile( $fileName );
118 if ( $type === 'thumb' ) {
119 $srcNamePos = strrpos( $thumbPart, $fileName );
120 if ( $srcNamePos === false ||
$srcNamePos < 1 ) {
121 throw new UploadStashBadPathException( 'Unrecognized thumb name' );
123 $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
125 $handler = $file->getHandler();
126 $params = $handler->parseParamString( $paramString );
127 return array( 'file' => $file, 'type' => $type, 'params' => $params );
130 return array( 'file' => $file, 'type' => $type );
134 * Get a thumbnail for file, either generated locally or remotely, and stream it out
137 * @param $params array
139 * @return boolean success
141 private function outputThumbFromStash( $file, $params ) {
143 // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb()
144 // 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
145 // happens to share it over NFS
146 global $wgUploadStashScalerBaseUrl;
149 if ( $wgUploadStashScalerBaseUrl ) {
150 $this->outputRemoteScaledThumb( $file, $params, $flags );
152 $this->outputLocallyScaledThumb( $file, $params, $flags );
157 * Scale a file (probably with a locally installed imagemagick, or similar) and output it to STDOUT.
158 * @param $file: File object
159 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
160 * @param $flags: scaling flags ( see File:: constants )
161 * @throws MWException
162 * @return boolean success
164 private function outputLocallyScaledThumb( $file, $params, $flags ) {
166 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
167 // on HTTP caching to ensure this doesn't happen.
169 $flags |
= File
::RENDER_NOW
;
171 $thumbnailImage = $file->transform( $params, $flags );
172 if ( !$thumbnailImage ) {
173 throw new MWException( 'Could not obtain thumbnail' );
176 // we should have just generated it locally
177 if ( ! $thumbnailImage->getPath() ) {
178 throw new UploadStashFileNotFoundException( "no local path for scaled item" );
181 // now we should construct a File, so we can get mime and other such info in a standard way
182 // n.b. mimetype may be different from original (ogx original -> jpeg thumb)
183 $thumbFile = new UnregisteredLocalFile( false, $this->stash
->repo
, $thumbnailImage->getPath(), false );
184 if ( ! $thumbFile ) {
185 throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
188 return $this->outputLocalFile( $thumbFile );
193 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation cluster, and output it to STDOUT.
194 * Note: unlike the usual thumbnail process, the web client never sees the cluster URL; we do the whole HTTP transaction to the scaler ourselves
195 * and cat the results out.
196 * 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
197 * propagated back to our filesystem. Instead we take the results of the HTTP request instead.
198 * Note: no caching is being done here, although we are instructing the client to cache it forever.
199 * @param $file: File object
200 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
201 * @param $flags: scaling flags ( see File:: constants )
202 * @throws MWException
203 * @return boolean success
205 private function outputRemoteScaledThumb( $file, $params, $flags ) {
207 // this global probably looks something like 'http://upload.wikimedia.org/wikipedia/test/thumb/temp'
208 // do not use trailing slash
209 global $wgUploadStashScalerBaseUrl;
210 $scalerBaseUrl = $wgUploadStashScalerBaseUrl;
212 if( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
213 // this is apparently a protocol-relative URL, which makes no sense in this context,
214 // since this is used for communication that's internal to the application.
216 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL
);
219 // We need to use generateThumbName() instead of thumbName(), because
220 // the suffix needs to match the file name for the remote thumbnailer
222 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
223 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
224 '/' . rawurlencode( $scalerThumbName );
226 // make a curl call to the scaler to create a thumbnail
227 $httpOptions = array(
229 'timeout' => 'default'
231 $req = MWHttpRequest
::factory( $scalerThumbUrl, $httpOptions );
232 $status = $req->execute();
233 if ( ! $status->isOK() ) {
234 $errors = $status->getErrorsArray();
235 $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 );
236 $errorStr .= "\nurl = $scalerThumbUrl\n";
237 throw new MWException( $errorStr );
239 $contentType = $req->getResponseHeader( "content-type" );
240 if ( ! $contentType ) {
241 throw new MWException( "Missing content-type header" );
243 return $this->outputContents( $req->getContent(), $contentType );
247 * Output HTTP response for file
248 * Side effect: writes HTTP response to STDOUT.
249 * XXX could use wfStreamfile (in includes/Streamfile.php), but for consistency with outputContents() doing it this way.
250 * XXX is mimeType really enough, or do we need encoding for full Content-Type header?
252 * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!)
254 private function outputLocalFile( $file ) {
255 if ( $file->getSize() > self
::MAX_SERVE_BYTES
) {
256 throw new SpecialUploadStashTooLargeException();
258 self
::outputFileHeaders( $file->getMimeType(), $file->getSize() );
259 readfile( $file->getPath() );
264 * Output HTTP response of raw content
265 * Side effect: writes HTTP response to STDOUT.
266 * @param String $content: content
267 * @param String $mimeType: mime type
269 private function outputContents( $content, $contentType ) {
270 $size = strlen( $content );
271 if ( $size > self
::MAX_SERVE_BYTES
) {
272 throw new SpecialUploadStashTooLargeException();
274 self
::outputFileHeaders( $contentType, $size );
280 * Output headers for streaming
281 * 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.
282 * Side effect: preps PHP to write headers to STDOUT.
283 * @param String $contentType : string suitable for content-type header
284 * @param String $size: length in bytes
286 private static function outputFileHeaders( $contentType, $size ) {
287 header( "Content-Type: $contentType", true );
288 header( 'Content-Transfer-Encoding: binary', true );
289 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
290 header( "Content-Length: $size", true );
294 * Static callback for the HTMLForm in showUploads, to process
295 * Note the stash has to be recreated since this is being called in a static context.
296 * This works, because there really is only one stash per logged-in user, despite appearances.
300 public static function tryClearStashedUploads( $formData ) {
301 if ( isset( $formData['Clear'] ) ) {
302 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
303 wfDebug( "stash has: " . print_r( $stash->listFiles(), true ) );
304 if ( ! $stash->clear() ) {
305 return Status
::newFatal( 'uploadstash-errclear' );
308 return Status
::newGood();
312 * Default action when we don't have a subpage -- just show links to the uploads we have,
313 * Also show a button to clear stashed files
314 * @param Status : $status - the result of processRequest
316 private function showUploads( $status = null ) {
317 if ( $status === null ) {
318 $status = Status
::newGood();
321 // sets the title, etc.
323 $this->outputHeader();
325 // create the form, which will also be used to execute a callback to process incoming form data
326 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
328 $form = new HTMLForm( array(
334 ), $this->getContext(), 'clearStashedUploads' );
335 $form->setSubmitCallback( array( __CLASS__
, 'tryClearStashedUploads' ) );
336 $form->setTitle( $this->getTitle() );
337 $form->setSubmitText( wfMsg( 'uploadstash-clear' ) );
339 $form->prepareForm();
340 $formResult = $form->tryAuthorizedSubmit();
342 // show the files + form, if there are any, or just say there are none
343 $refreshHtml = Html
::element( 'a',
344 array( 'href' => $this->getTitle()->getLocalURL() ),
345 wfMsg( 'uploadstash-refresh' ) );
346 $files = $this->stash
->listFiles();
347 if ( $files && count( $files ) ) {
349 $fileListItemsHtml = '';
350 foreach ( $files as $file ) {
351 // TODO: Use Linker::link or even construct the list in plain wikitext
352 $fileListItemsHtml .= Html
::rawElement( 'li', array(),
353 Html
::element( 'a', array( 'href' =>
354 $this->getTitle( "file/$file" )->getLocalURL() ), $file )
357 $this->getOutput()->addHtml( Html
::rawElement( 'ul', array(), $fileListItemsHtml ) );
358 $form->displayForm( $formResult );
359 $this->getOutput()->addHtml( Html
::rawElement( 'p', array(), $refreshHtml ) );
361 $this->getOutput()->addHtml( Html
::rawElement( 'p', array(),
362 Html
::element( 'span', array(), wfMsg( 'uploadstash-nofiles' ) )
372 class SpecialUploadStashTooLargeException
extends MWException
{};