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