Switch some HTMLForms in special pages to OOUI
[lhc/web/wiklou.git] / includes / specials / SpecialUploadStash.php
1 <?php
2 /**
3 * Implements Special:UploadStash.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup SpecialPage
22 * @ingroup Upload
23 */
24
25 /**
26 * Web access for files temporarily stored by UploadStash.
27 *
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.
31 *
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.
34 */
35 class SpecialUploadStash extends UnlistedSpecialPage {
36 // UploadStash
37 private $stash;
38
39 // Since we are directly writing the file to STDOUT,
40 // we should not be reading in really big files and serving them out.
41 //
42 // We also don't want people using this as a file drop, even if they
43 // share credentials.
44 //
45 // This service is really for thumbnails and other such previews while
46 // uploading.
47 const MAX_SERVE_BYTES = 1048576; // 1MB
48
49 public function __construct() {
50 parent::__construct( 'UploadStash', 'upload' );
51 }
52
53 /**
54 * Execute page -- can output a file directly or show a listing of them.
55 *
56 * @param string $subPage Subpage, e.g. in
57 * http://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part
58 * @return bool Success
59 */
60 public function execute( $subPage ) {
61 $this->stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
62 $this->checkPermissions();
63
64 if ( $subPage === null || $subPage === '' ) {
65 return $this->showUploads();
66 }
67
68 return $this->showUpload( $subPage );
69 }
70
71 /**
72 * If file available in stash, cats it out to the client as a simple HTTP response.
73 * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward.
74 *
75 * @param string $key The key of a particular requested file
76 * @throws HttpError
77 * @return bool
78 */
79 public function showUpload( $key ) {
80 // prevent callers from doing standard HTML output -- we'll take it from here
81 $this->getOutput()->disable();
82
83 try {
84 $params = $this->parseKey( $key );
85 if ( $params['type'] === 'thumb' ) {
86 return $this->outputThumbFromStash( $params['file'], $params['params'] );
87 } else {
88 return $this->outputLocalFile( $params['file'] );
89 }
90 } catch ( UploadStashFileNotFoundException $e ) {
91 $code = 404;
92 $message = $e->getMessage();
93 } catch ( UploadStashZeroLengthFileException $e ) {
94 $code = 500;
95 $message = $e->getMessage();
96 } catch ( UploadStashBadPathException $e ) {
97 $code = 500;
98 $message = $e->getMessage();
99 } catch ( SpecialUploadStashTooLargeException $e ) {
100 $code = 500;
101 $message = 'Cannot serve a file larger than ' . self::MAX_SERVE_BYTES .
102 ' bytes. ' . $e->getMessage();
103 } catch ( Exception $e ) {
104 $code = 500;
105 $message = $e->getMessage();
106 }
107
108 throw new HttpError( $code, $message );
109 }
110
111 /**
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
115 *
116 * @param string $key
117 * @throws UploadStashBadPathException
118 * @return array
119 */
120 private function parseKey( $key ) {
121 $type = strtok( $key, '/' );
122
123 if ( $type !== 'file' && $type !== 'thumb' ) {
124 throw new UploadStashBadPathException( "Unknown type '$type'" );
125 }
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' );
133 }
134 $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
135
136 $handler = $file->getHandler();
137 if ( $handler ) {
138 $params = $handler->parseParamString( $paramString );
139
140 return array( 'file' => $file, 'type' => $type, 'params' => $params );
141 } else {
142 throw new UploadStashBadPathException( 'No handler found for ' .
143 "mime {$file->getMimeType()} of file {$file->getPath()}" );
144 }
145 }
146
147 return array( 'file' => $file, 'type' => $type );
148 }
149
150 /**
151 * Get a thumbnail for file, either generated locally or remotely, and stream it out
152 *
153 * @param File $file
154 * @param array $params
155 *
156 * @return bool Success
157 */
158 private function outputThumbFromStash( $file, $params ) {
159 $flags = 0;
160 // this config option, if it exists, points to a "scaler", as you might find in
161 // the Wikimedia Foundation cluster. See outputRemoteScaledThumb(). This
162 // is part of our horrible NFS-based system, we create a file on a mount
163 // point here, but fetch the scaled file from somewhere else that
164 // happens to share it over NFS.
165 if ( $this->getConfig()->get( 'UploadStashScalerBaseUrl' ) ) {
166 $this->outputRemoteScaledThumb( $file, $params, $flags );
167 } else {
168 $this->outputLocallyScaledThumb( $file, $params, $flags );
169 }
170 }
171
172 /**
173 * Scale a file (probably with a locally installed imagemagick, or similar)
174 * and output it to STDOUT.
175 * @param File $file
176 * @param array $params Scaling parameters ( e.g. array( width => '50' ) );
177 * @param int $flags Scaling flags ( see File:: constants )
178 * @throws MWException|UploadStashFileNotFoundException
179 * @return bool Success
180 */
181 private function outputLocallyScaledThumb( $file, $params, $flags ) {
182 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
183 // on HTTP caching to ensure this doesn't happen.
184
185 $flags |= File::RENDER_NOW;
186
187 $thumbnailImage = $file->transform( $params, $flags );
188 if ( !$thumbnailImage ) {
189 throw new MWException( 'Could not obtain thumbnail' );
190 }
191
192 // we should have just generated it locally
193 if ( !$thumbnailImage->getStoragePath() ) {
194 throw new UploadStashFileNotFoundException( "no local path for scaled item" );
195 }
196
197 // now we should construct a File, so we can get MIME and other such info in a standard way
198 // n.b. MIME type may be different from original (ogx original -> jpeg thumb)
199 $thumbFile = new UnregisteredLocalFile( false,
200 $this->stash->repo, $thumbnailImage->getStoragePath(), false );
201 if ( !$thumbFile ) {
202 throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
203 }
204
205 return $this->outputLocalFile( $thumbFile );
206 }
207
208 /**
209 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation
210 * cluster, and output it to STDOUT.
211 * Note: Unlike the usual thumbnail process, the web client never sees the
212 * 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.
215 * However, we do not rely on the thumbnail being created in NFS and then
216 * propagated back to our filesystem. Instead we take the results of the
217 * HTTP request instead.
218 * Note: No caching is being done here, although we are instructing the
219 * client to cache it forever.
220 *
221 * @param File $file
222 * @param array $params Scaling parameters ( e.g. array( width => '50' ) );
223 * @param int $flags Scaling flags ( see File:: constants )
224 * @throws MWException
225 * @return bool Success
226 */
227 private function outputRemoteScaledThumb( $file, $params, $flags ) {
228 // This option probably looks something like
229 // '//upload.wikimedia.org/wikipedia/test/thumb/temp'. Do not use
230 // trailing slash.
231 $scalerBaseUrl = $this->getConfig()->get( 'UploadStashScalerBaseUrl' );
232
233 if ( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
234 // this is apparently a protocol-relative URL, which makes no sense in this context,
235 // since this is used for communication that's internal to the application.
236 // default to http.
237 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL );
238 }
239
240 // We need to use generateThumbName() instead of thumbName(), because
241 // the suffix needs to match the file name for the remote thumbnailer
242 // to work
243 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
244 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
245 '/' . rawurlencode( $scalerThumbName );
246
247 // make a curl call to the scaler to create a thumbnail
248 $httpOptions = array(
249 'method' => 'GET',
250 'timeout' => 5 // T90599 attempt to time out cleanly
251 );
252 $req = MWHttpRequest::factory( $scalerThumbUrl, $httpOptions, __METHOD__ );
253 $status = $req->execute();
254 if ( !$status->isOK() ) {
255 $errors = $status->getErrorsArray();
256 $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 );
257 $errorStr .= "\nurl = $scalerThumbUrl\n";
258 throw new MWException( $errorStr );
259 }
260 $contentType = $req->getResponseHeader( "content-type" );
261 if ( !$contentType ) {
262 throw new MWException( "Missing content-type header" );
263 }
264
265 return $this->outputContents( $req->getContent(), $contentType );
266 }
267
268 /**
269 * Output HTTP response for file
270 * Side effect: writes HTTP response to STDOUT.
271 *
272 * @param File $file File object with a local path (e.g. UnregisteredLocalFile,
273 * LocalFile. Oddly these don't share an ancestor!)
274 * @throws SpecialUploadStashTooLargeException
275 * @return bool
276 */
277 private function outputLocalFile( File $file ) {
278 if ( $file->getSize() > self::MAX_SERVE_BYTES ) {
279 throw new SpecialUploadStashTooLargeException();
280 }
281
282 return $file->getRepo()->streamFile( $file->getPath(),
283 array( 'Content-Transfer-Encoding: binary',
284 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' )
285 );
286 }
287
288 /**
289 * Output HTTP response of raw content
290 * Side effect: writes HTTP response to STDOUT.
291 * @param string $content Content
292 * @param string $contentType MIME type
293 * @throws SpecialUploadStashTooLargeException
294 * @return bool
295 */
296 private function outputContents( $content, $contentType ) {
297 $size = strlen( $content );
298 if ( $size > self::MAX_SERVE_BYTES ) {
299 throw new SpecialUploadStashTooLargeException();
300 }
301 self::outputFileHeaders( $contentType, $size );
302 print $content;
303
304 return true;
305 }
306
307 /**
308 * Output headers for streaming
309 * @todo Unsure about encoding as binary; if we received from HTTP perhaps
310 * we should use that encoding, concatenated with semicolon to `$contentType` as it
311 * usually is.
312 * Side effect: preps PHP to write headers to STDOUT.
313 * @param string $contentType String suitable for content-type header
314 * @param string $size Length in bytes
315 */
316 private static function outputFileHeaders( $contentType, $size ) {
317 header( "Content-Type: $contentType", true );
318 header( 'Content-Transfer-Encoding: binary', true );
319 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
320 // Bug 53032 - It shouldn't be a problem here, but let's be safe and not cache
321 header( 'Cache-Control: private' );
322 header( "Content-Length: $size", true );
323 }
324
325 /**
326 * Static callback for the HTMLForm in showUploads, to process
327 * Note the stash has to be recreated since this is being called in a static context.
328 * This works, because there really is only one stash per logged-in user, despite appearances.
329 *
330 * @param array $formData
331 * @param HTMLForm $form
332 * @return Status
333 */
334 public static function tryClearStashedUploads( $formData, $form ) {
335 if ( isset( $formData['Clear'] ) ) {
336 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $form->getUser() );
337 wfDebug( 'stash has: ' . print_r( $stash->listFiles(), true ) . "\n" );
338
339 if ( !$stash->clear() ) {
340 return Status::newFatal( 'uploadstash-errclear' );
341 }
342 }
343
344 return Status::newGood();
345 }
346
347 /**
348 * Default action when we don't have a subpage -- just show links to the uploads we have,
349 * Also show a button to clear stashed files
350 * @return bool
351 */
352 private function showUploads() {
353 // sets the title, etc.
354 $this->setHeaders();
355 $this->outputHeader();
356
357 // create the form, which will also be used to execute a callback to process incoming form data
358 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
359
360 $context = new DerivativeContext( $this->getContext() );
361 $context->setTitle( $this->getPageTitle() ); // Remove subpage
362 $form = new HTMLForm( array(
363 'Clear' => array(
364 'type' => 'hidden',
365 'default' => true,
366 'name' => 'clear',
367 )
368 ), $context, 'clearStashedUploads' );
369 $form->setSubmitCallback( array( __CLASS__, 'tryClearStashedUploads' ) );
370 $form->setSubmitTextMsg( 'uploadstash-clear' );
371
372 $form->prepareForm();
373 $formResult = $form->tryAuthorizedSubmit();
374
375 // show the files + form, if there are any, or just say there are none
376 $refreshHtml = Html::element( 'a',
377 array( 'href' => $this->getPageTitle()->getLocalURL() ),
378 $this->msg( 'uploadstash-refresh' )->text() );
379 $files = $this->stash->listFiles();
380 if ( $files && count( $files ) ) {
381 sort( $files );
382 $fileListItemsHtml = '';
383 foreach ( $files as $file ) {
384 // TODO: Use Linker::link or even construct the list in plain wikitext
385 $fileListItemsHtml .= Html::rawElement( 'li', array(),
386 Html::element( 'a', array( 'href' =>
387 $this->getPageTitle( "file/$file" )->getLocalURL() ), $file )
388 );
389 }
390 $this->getOutput()->addHtml( Html::rawElement( 'ul', array(), $fileListItemsHtml ) );
391 $form->displayForm( $formResult );
392 $this->getOutput()->addHtml( Html::rawElement( 'p', array(), $refreshHtml ) );
393 } else {
394 $this->getOutput()->addHtml( Html::rawElement( 'p', array(),
395 Html::element( 'span', array(), $this->msg( 'uploadstash-nofiles' )->text() )
396 . ' '
397 . $refreshHtml
398 ) );
399 }
400
401 return true;
402 }
403 }
404
405 class SpecialUploadStashTooLargeException extends MWException {
406 }