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