Merge "Only show config-install-success on command line installer where it makes...
[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 $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 // make an http request based on wgUploadStashScalerBaseUrl to lazy-create
265 // 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 $this->msg(
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 $this->msg( '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 $this->msg( '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
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 $this->msg( '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 }