DifferenceEngine cleanup
[mediawiki.git] / includes / specials / SpecialUploadStash.php
blob87b644280d37a8b008d6278f5768ad6d0caaa179
1 <?php
2 /**
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
20 * @file
21 * @ingroup SpecialPage
22 * @ingroup Upload
25 /**
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
30 * about them.
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 {
36 // UploadStash
37 private $stash;
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
43 // share credentials.
45 // This service is really for thumbnails and other such previews while
46 // uploading.
47 const MAX_SERVE_BYTES = 1048576; // 1MB
49 public function __construct() {
50 parent::__construct( 'UploadStash', 'upload' );
51 try {
52 $this->stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
53 } catch ( UploadStashNotAvailableException $e ) {
57 /**
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();
69 return $this->showUpload( $subPage );
72 /**
73 * If file available in stash, cats it out to the client as a simple HTTP response.
74 * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward.
76 * @param string $key the key of a particular requested file
77 * @throws HttpError
78 * @return bool
80 public function showUpload( $key ) {
81 // prevent callers from doing standard HTML output -- we'll take it from here
82 $this->getOutput()->disable();
84 try {
85 $params = $this->parseKey( $key );
86 if ( $params['type'] === 'thumb' ) {
87 return $this->outputThumbFromStash( $params['file'], $params['params'] );
88 } else {
89 return $this->outputLocalFile( $params['file'] );
91 } catch ( UploadStashFileNotFoundException $e ) {
92 $code = 404;
93 $message = $e->getMessage();
94 } catch ( UploadStashZeroLengthFileException $e ) {
95 $code = 500;
96 $message = $e->getMessage();
97 } catch ( UploadStashBadPathException $e ) {
98 $code = 500;
99 $message = $e->getMessage();
100 } catch ( SpecialUploadStashTooLargeException $e ) {
101 $code = 500;
102 $message = 'Cannot serve a file larger than ' . self::MAX_SERVE_BYTES . ' bytes. ' . $e->getMessage();
103 } catch ( Exception $e ) {
104 $code = 500;
105 $message = $e->getMessage();
108 throw new HttpError( $code, $message );
112 * Parse the key passed to the SpecialPage. Returns an array containing
113 * the associated file object, the type ('file' or 'thumb') and if
114 * application the transform parameters
116 * @param string $key
117 * @throws UploadStashBadPathException
118 * @return array
120 private function parseKey( $key ) {
121 $type = strtok( $key, '/' );
123 if ( $type !== 'file' && $type !== 'thumb' ) {
124 throw new UploadStashBadPathException( "Unknown type '$type'" );
126 $fileName = strtok( '/' );
127 $thumbPart = strtok( '/' );
128 $file = $this->stash->getFile( $fileName );
129 if ( $type === 'thumb' ) {
130 $srcNamePos = strrpos( $thumbPart, $fileName );
131 if ( $srcNamePos === false || $srcNamePos < 1 ) {
132 throw new UploadStashBadPathException( 'Unrecognized thumb name' );
134 $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
136 $handler = $file->getHandler();
137 if ( $handler ) {
138 $params = $handler->parseParamString( $paramString );
139 return array( 'file' => $file, 'type' => $type, 'params' => $params );
140 } else {
141 throw new UploadStashBadPathException( 'No handler found for ' .
142 "mime {$file->getMimeType()} of file {$file->getPath()}" );
146 return array( 'file' => $file, 'type' => $type );
150 * Get a thumbnail for file, either generated locally or remotely, and stream it out
152 * @param $file
153 * @param $params array
155 * @return boolean success
157 private function outputThumbFromStash( $file, $params ) {
159 // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb()
160 // 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
161 // happens to share it over NFS
162 global $wgUploadStashScalerBaseUrl;
164 $flags = 0;
165 if ( $wgUploadStashScalerBaseUrl ) {
166 $this->outputRemoteScaledThumb( $file, $params, $flags );
167 } else {
168 $this->outputLocallyScaledThumb( $file, $params, $flags );
173 * Scale a file (probably with a locally installed imagemagick, or similar) and output it to STDOUT.
174 * @param $file File
175 * @param array $params Scaling parameters ( e.g. array( width => '50' ) );
176 * @param int $flags Scaling flags ( see File:: constants )
177 * @throws MWException
178 * @throws UploadStashFileNotFoundException
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->getStoragePath() ) {
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,
201 $this->stash->repo, $thumbnailImage->getStoragePath(), false );
202 if ( !$thumbFile ) {
203 throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
206 return $this->outputLocalFile( $thumbFile );
211 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation cluster, and output it to STDOUT.
212 * Note: unlike the usual thumbnail process, the web client never sees the cluster URL; we do the whole HTTP transaction to the scaler ourselves
213 * and cat the results out.
214 * 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
215 * propagated back to our filesystem. Instead we take the results of the HTTP request instead.
216 * Note: no caching is being done here, although we are instructing the client to cache it forever.
217 * @param $file: File object
218 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
219 * @param $flags: scaling flags ( see File:: constants )
220 * @throws MWException
221 * @return boolean success
223 private function outputRemoteScaledThumb( $file, $params, $flags ) {
225 // this global probably looks something like 'http://upload.wikimedia.org/wikipedia/test/thumb/temp'
226 // do not use trailing slash
227 global $wgUploadStashScalerBaseUrl;
228 $scalerBaseUrl = $wgUploadStashScalerBaseUrl;
230 if ( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
231 // this is apparently a protocol-relative URL, which makes no sense in this context,
232 // since this is used for communication that's internal to the application.
233 // default to http.
234 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL );
237 // We need to use generateThumbName() instead of thumbName(), because
238 // the suffix needs to match the file name for the remote thumbnailer
239 // to work
240 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
241 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
242 '/' . rawurlencode( $scalerThumbName );
244 // make a curl call to the scaler to create a thumbnail
245 $httpOptions = array(
246 'method' => 'GET',
247 'timeout' => 'default'
249 $req = MWHttpRequest::factory( $scalerThumbUrl, $httpOptions );
250 $status = $req->execute();
251 if ( ! $status->isOK() ) {
252 $errors = $status->getErrorsArray();
253 $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 );
254 $errorStr .= "\nurl = $scalerThumbUrl\n";
255 throw new MWException( $errorStr );
257 $contentType = $req->getResponseHeader( "content-type" );
258 if ( ! $contentType ) {
259 throw new MWException( "Missing content-type header" );
261 return $this->outputContents( $req->getContent(), $contentType );
265 * Output HTTP response for file
266 * Side effect: writes HTTP response to STDOUT.
268 * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!)
269 * @throws SpecialUploadStashTooLargeException
270 * @return bool
272 private function outputLocalFile( File $file ) {
273 if ( $file->getSize() > self::MAX_SERVE_BYTES ) {
274 throw new SpecialUploadStashTooLargeException();
276 return $file->getRepo()->streamFile( $file->getPath(),
277 array( 'Content-Transfer-Encoding: binary',
278 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' )
283 * Output HTTP response of raw content
284 * Side effect: writes HTTP response to STDOUT.
285 * @param string $content content
286 * @param string $contentType mime type
287 * @throws SpecialUploadStashTooLargeException
288 * @return bool
290 private function outputContents( $content, $contentType ) {
291 $size = strlen( $content );
292 if ( $size > self::MAX_SERVE_BYTES ) {
293 throw new SpecialUploadStashTooLargeException();
295 self::outputFileHeaders( $contentType, $size );
296 print $content;
297 return true;
301 * Output headers for streaming
302 * 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.
303 * Side effect: preps PHP to write headers to STDOUT.
304 * @param string $contentType : string suitable for content-type header
305 * @param string $size: length in bytes
307 private static function outputFileHeaders( $contentType, $size ) {
308 header( "Content-Type: $contentType", true );
309 header( 'Content-Transfer-Encoding: binary', true );
310 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
311 header( "Content-Length: $size", true );
315 * Static callback for the HTMLForm in showUploads, to process
316 * Note the stash has to be recreated since this is being called in a static context.
317 * This works, because there really is only one stash per logged-in user, despite appearances.
319 * @param array $formData
320 * @return Status
322 public static function tryClearStashedUploads( $formData ) {
323 if ( isset( $formData['Clear'] ) ) {
324 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
325 wfDebug( "stash has: " . print_r( $stash->listFiles(), true ) );
326 if ( ! $stash->clear() ) {
327 return Status::newFatal( 'uploadstash-errclear' );
330 return Status::newGood();
334 * Default action when we don't have a subpage -- just show links to the uploads we have,
335 * Also show a button to clear stashed files
336 * @return bool
338 private function showUploads() {
339 // sets the title, etc.
340 $this->setHeaders();
341 $this->outputHeader();
343 // create the form, which will also be used to execute a callback to process incoming form data
344 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
346 $context = new DerivativeContext( $this->getContext() );
347 $context->setTitle( $this->getTitle() ); // Remove subpage
348 $form = new HTMLForm( array(
349 'Clear' => array(
350 'type' => 'hidden',
351 'default' => true,
352 'name' => 'clear',
354 ), $context, 'clearStashedUploads' );
355 $form->setSubmitCallback( array( __CLASS__, 'tryClearStashedUploads' ) );
356 $form->setSubmitTextMsg( 'uploadstash-clear' );
358 $form->prepareForm();
359 $formResult = $form->tryAuthorizedSubmit();
361 // show the files + form, if there are any, or just say there are none
362 $refreshHtml = Html::element( 'a',
363 array( 'href' => $this->getTitle()->getLocalURL() ),
364 $this->msg( 'uploadstash-refresh' )->text() );
365 $files = $this->stash->listFiles();
366 if ( $files && count( $files ) ) {
367 sort( $files );
368 $fileListItemsHtml = '';
369 foreach ( $files as $file ) {
370 // TODO: Use Linker::link or even construct the list in plain wikitext
371 $fileListItemsHtml .= Html::rawElement( 'li', array(),
372 Html::element( 'a', array( 'href' =>
373 $this->getTitle( "file/$file" )->getLocalURL() ), $file )
376 $this->getOutput()->addHtml( Html::rawElement( 'ul', array(), $fileListItemsHtml ) );
377 $form->displayForm( $formResult );
378 $this->getOutput()->addHtml( Html::rawElement( 'p', array(), $refreshHtml ) );
379 } else {
380 $this->getOutput()->addHtml( Html::rawElement( 'p', array(),
381 Html::element( 'span', array(), $this->msg( 'uploadstash-nofiles' )->text() )
382 . ' '
383 . $refreshHtml
384 ) );
387 return true;
391 class SpecialUploadStashTooLargeException extends MWException {};