Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / specials / SpecialUploadStash.php
blobe7f36ee57fb59451b24ed690fc5c0b8406fa38e1
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 $params = $handler->parseParamString( $paramString );
138 return array( 'file' => $file, 'type' => $type, 'params' => $params );
141 return array( 'file' => $file, 'type' => $type );
145 * Get a thumbnail for file, either generated locally or remotely, and stream it out
147 * @param $file
148 * @param $params array
150 * @return boolean success
152 private function outputThumbFromStash( $file, $params ) {
154 // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb()
155 // 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
156 // happens to share it over NFS
157 global $wgUploadStashScalerBaseUrl;
159 $flags = 0;
160 if ( $wgUploadStashScalerBaseUrl ) {
161 $this->outputRemoteScaledThumb( $file, $params, $flags );
162 } else {
163 $this->outputLocallyScaledThumb( $file, $params, $flags );
168 * Scale a file (probably with a locally installed imagemagick, or similar) and output it to STDOUT.
169 * @param $file File
170 * @param array $params Scaling parameters ( e.g. array( width => '50' ) );
171 * @param int $flags Scaling flags ( see File:: constants )
172 * @throws MWException
173 * @throws UploadStashFileNotFoundException
174 * @return boolean success
176 private function outputLocallyScaledThumb( $file, $params, $flags ) {
178 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
179 // on HTTP caching to ensure this doesn't happen.
181 $flags |= File::RENDER_NOW;
183 $thumbnailImage = $file->transform( $params, $flags );
184 if ( !$thumbnailImage ) {
185 throw new MWException( 'Could not obtain thumbnail' );
188 // we should have just generated it locally
189 if ( !$thumbnailImage->getStoragePath() ) {
190 throw new UploadStashFileNotFoundException( "no local path for scaled item" );
193 // now we should construct a File, so we can get mime and other such info in a standard way
194 // n.b. mimetype may be different from original (ogx original -> jpeg thumb)
195 $thumbFile = new UnregisteredLocalFile( false,
196 $this->stash->repo, $thumbnailImage->getStoragePath(), false );
197 if ( !$thumbFile ) {
198 throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
201 return $this->outputLocalFile( $thumbFile );
206 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation cluster, and output it to STDOUT.
207 * Note: unlike the usual thumbnail process, the web client never sees the cluster URL; we do the whole HTTP transaction to the scaler ourselves
208 * and cat the results out.
209 * 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
210 * propagated back to our filesystem. Instead we take the results of the HTTP request instead.
211 * Note: no caching is being done here, although we are instructing the client to cache it forever.
212 * @param $file: File object
213 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
214 * @param $flags: scaling flags ( see File:: constants )
215 * @throws MWException
216 * @return boolean success
218 private function outputRemoteScaledThumb( $file, $params, $flags ) {
220 // this global probably looks something like 'http://upload.wikimedia.org/wikipedia/test/thumb/temp'
221 // do not use trailing slash
222 global $wgUploadStashScalerBaseUrl;
223 $scalerBaseUrl = $wgUploadStashScalerBaseUrl;
225 if ( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
226 // this is apparently a protocol-relative URL, which makes no sense in this context,
227 // since this is used for communication that's internal to the application.
228 // default to http.
229 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL );
232 // We need to use generateThumbName() instead of thumbName(), because
233 // the suffix needs to match the file name for the remote thumbnailer
234 // to work
235 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
236 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
237 '/' . rawurlencode( $scalerThumbName );
239 // make a curl call to the scaler to create a thumbnail
240 $httpOptions = array(
241 'method' => 'GET',
242 'timeout' => 'default'
244 $req = MWHttpRequest::factory( $scalerThumbUrl, $httpOptions );
245 $status = $req->execute();
246 if ( ! $status->isOK() ) {
247 $errors = $status->getErrorsArray();
248 $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 );
249 $errorStr .= "\nurl = $scalerThumbUrl\n";
250 throw new MWException( $errorStr );
252 $contentType = $req->getResponseHeader( "content-type" );
253 if ( ! $contentType ) {
254 throw new MWException( "Missing content-type header" );
256 return $this->outputContents( $req->getContent(), $contentType );
260 * Output HTTP response for file
261 * Side effect: writes HTTP response to STDOUT.
263 * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!)
264 * @throws SpecialUploadStashTooLargeException
265 * @return bool
267 private function outputLocalFile( File $file ) {
268 if ( $file->getSize() > self::MAX_SERVE_BYTES ) {
269 throw new SpecialUploadStashTooLargeException();
271 return $file->getRepo()->streamFile( $file->getPath(),
272 array( 'Content-Transfer-Encoding: binary',
273 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' )
278 * Output HTTP response of raw content
279 * Side effect: writes HTTP response to STDOUT.
280 * @param string $content content
281 * @param string $contentType mime type
282 * @throws SpecialUploadStashTooLargeException
283 * @return bool
285 private function outputContents( $content, $contentType ) {
286 $size = strlen( $content );
287 if ( $size > self::MAX_SERVE_BYTES ) {
288 throw new SpecialUploadStashTooLargeException();
290 self::outputFileHeaders( $contentType, $size );
291 print $content;
292 return true;
296 * Output headers for streaming
297 * 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.
298 * Side effect: preps PHP to write headers to STDOUT.
299 * @param string $contentType : string suitable for content-type header
300 * @param string $size: length in bytes
302 private static function outputFileHeaders( $contentType, $size ) {
303 header( "Content-Type: $contentType", true );
304 header( 'Content-Transfer-Encoding: binary', true );
305 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
306 header( "Content-Length: $size", true );
310 * Static callback for the HTMLForm in showUploads, to process
311 * Note the stash has to be recreated since this is being called in a static context.
312 * This works, because there really is only one stash per logged-in user, despite appearances.
314 * @param array $formData
315 * @return Status
317 public static function tryClearStashedUploads( $formData ) {
318 if ( isset( $formData['Clear'] ) ) {
319 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
320 wfDebug( "stash has: " . print_r( $stash->listFiles(), true ) );
321 if ( ! $stash->clear() ) {
322 return Status::newFatal( 'uploadstash-errclear' );
325 return Status::newGood();
329 * Default action when we don't have a subpage -- just show links to the uploads we have,
330 * Also show a button to clear stashed files
331 * @return bool
333 private function showUploads() {
334 // sets the title, etc.
335 $this->setHeaders();
336 $this->outputHeader();
338 // create the form, which will also be used to execute a callback to process incoming form data
339 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
341 $form = new HTMLForm( array(
342 'Clear' => array(
343 'type' => 'hidden',
344 'default' => true,
345 'name' => 'clear',
347 ), $this->getContext(), 'clearStashedUploads' );
348 $form->setSubmitCallback( array( __CLASS__, 'tryClearStashedUploads' ) );
349 $form->setTitle( $this->getTitle() );
350 $form->setSubmitTextMsg( 'uploadstash-clear' );
352 $form->prepareForm();
353 $formResult = $form->tryAuthorizedSubmit();
355 // show the files + form, if there are any, or just say there are none
356 $refreshHtml = Html::element( 'a',
357 array( 'href' => $this->getTitle()->getLocalURL() ),
358 $this->msg( 'uploadstash-refresh' )->text() );
359 $files = $this->stash->listFiles();
360 if ( $files && count( $files ) ) {
361 sort( $files );
362 $fileListItemsHtml = '';
363 foreach ( $files as $file ) {
364 // TODO: Use Linker::link or even construct the list in plain wikitext
365 $fileListItemsHtml .= Html::rawElement( 'li', array(),
366 Html::element( 'a', array( 'href' =>
367 $this->getTitle( "file/$file" )->getLocalURL() ), $file )
370 $this->getOutput()->addHtml( Html::rawElement( 'ul', array(), $fileListItemsHtml ) );
371 $form->displayForm( $formResult );
372 $this->getOutput()->addHtml( Html::rawElement( 'p', array(), $refreshHtml ) );
373 } else {
374 $this->getOutput()->addHtml( Html::rawElement( 'p', array(),
375 Html::element( 'span', array(), $this->msg( 'uploadstash-nofiles' )->text() )
376 . ' '
377 . $refreshHtml
378 ) );
381 return true;
385 class SpecialUploadStashTooLargeException extends MWException {};