Merge "Rewrite pref cleanup script"
[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 wfMessage( '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 wfMessage( '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 wfMessage( '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 * @return bool Success
170 */
171 private function outputThumbFromStash( $file, $params ) {
172 $flags = 0;
173 // this config option, if it exists, points to a "scaler", as you might find in
174 // the Wikimedia Foundation cluster. See outputRemoteScaledThumb(). This
175 // is part of our horrible NFS-based system, we create a file on a mount
176 // point here, but fetch the scaled file from somewhere else that
177 // happens to share it over NFS.
178 if ( $this->getConfig()->get( 'UploadStashScalerBaseUrl' ) ) {
179 $this->outputRemoteScaledThumb( $file, $params, $flags );
180 } else {
181 $this->outputLocallyScaledThumb( $file, $params, $flags );
182 }
183 }
184
185 /**
186 * Scale a file (probably with a locally installed imagemagick, or similar)
187 * and output it to STDOUT.
188 * @param File $file
189 * @param array $params Scaling parameters ( e.g. [ width => '50' ] );
190 * @param int $flags Scaling flags ( see File:: constants )
191 * @throws MWException|UploadStashFileNotFoundException
192 * @return bool Success
193 */
194 private function outputLocallyScaledThumb( $file, $params, $flags ) {
195 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
196 // on HTTP caching to ensure this doesn't happen.
197
198 $flags |= File::RENDER_NOW;
199
200 $thumbnailImage = $file->transform( $params, $flags );
201 if ( !$thumbnailImage ) {
202 throw new UploadStashFileNotFoundException(
203 wfMessage( 'uploadstash-file-not-found-no-thumb' )
204 );
205 }
206
207 // we should have just generated it locally
208 if ( !$thumbnailImage->getStoragePath() ) {
209 throw new UploadStashFileNotFoundException(
210 wfMessage( 'uploadstash-file-not-found-no-local-path' )
211 );
212 }
213
214 // now we should construct a File, so we can get MIME and other such info in a standard way
215 // n.b. MIME type may be different from original (ogx original -> jpeg thumb)
216 $thumbFile = new UnregisteredLocalFile( false,
217 $this->stash->repo, $thumbnailImage->getStoragePath(), false );
218 if ( !$thumbFile ) {
219 throw new UploadStashFileNotFoundException(
220 wfMessage( 'uploadstash-file-not-found-no-object' )
221 );
222 }
223
224 return $this->outputLocalFile( $thumbFile );
225 }
226
227 /**
228 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation
229 * cluster, and output it to STDOUT.
230 * Note: Unlike the usual thumbnail process, the web client never sees the
231 * cluster URL; we do the whole HTTP transaction to the scaler ourselves
232 * and cat the results out.
233 * Note: We rely on NFS to have propagated the file contents to the scaler.
234 * However, we do not rely on the thumbnail being created in NFS and then
235 * propagated back to our filesystem. Instead we take the results of the
236 * HTTP request instead.
237 * Note: No caching is being done here, although we are instructing the
238 * client to cache it forever.
239 *
240 * @param File $file
241 * @param array $params Scaling parameters ( e.g. [ width => '50' ] );
242 * @param int $flags Scaling flags ( see File:: constants )
243 * @throws MWException
244 * @return bool Success
245 */
246 private function outputRemoteScaledThumb( $file, $params, $flags ) {
247 // This option probably looks something like
248 // '//upload.wikimedia.org/wikipedia/test/thumb/temp'. Do not use
249 // trailing slash.
250 $scalerBaseUrl = $this->getConfig()->get( 'UploadStashScalerBaseUrl' );
251
252 if ( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
253 // this is apparently a protocol-relative URL, which makes no sense in this context,
254 // since this is used for communication that's internal to the application.
255 // default to http.
256 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL );
257 }
258
259 // We need to use generateThumbName() instead of thumbName(), because
260 // the suffix needs to match the file name for the remote thumbnailer
261 // to work
262 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
263 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
264 '/' . rawurlencode( $scalerThumbName );
265
266 // make a curl call to the scaler to create a thumbnail
267 $httpOptions = [
268 'method' => 'GET',
269 'timeout' => 5 // T90599 attempt to time out cleanly
270 ];
271 $req = MWHttpRequest::factory( $scalerThumbUrl, $httpOptions, __METHOD__ );
272 $status = $req->execute();
273 if ( !$status->isOK() ) {
274 $errors = $status->getErrorsArray();
275 throw new UploadStashFileNotFoundException(
276 wfMessage(
277 'uploadstash-file-not-found-no-remote-thumb',
278 print_r( $errors, 1 ),
279 $scalerThumbUrl
280 )
281 );
282 }
283 $contentType = $req->getResponseHeader( "content-type" );
284 if ( !$contentType ) {
285 throw new UploadStashFileNotFoundException(
286 wfMessage( 'uploadstash-file-not-found-missing-content-type' )
287 );
288 }
289
290 return $this->outputContents( $req->getContent(), $contentType );
291 }
292
293 /**
294 * Output HTTP response for file
295 * Side effect: writes HTTP response to STDOUT.
296 *
297 * @param File $file File object with a local path (e.g. UnregisteredLocalFile,
298 * LocalFile. Oddly these don't share an ancestor!)
299 * @throws SpecialUploadStashTooLargeException
300 * @return bool
301 */
302 private function outputLocalFile( File $file ) {
303 if ( $file->getSize() > self::MAX_SERVE_BYTES ) {
304 throw new SpecialUploadStashTooLargeException(
305 wfMessage( 'uploadstash-file-too-large', self::MAX_SERVE_BYTES )
306 );
307 }
308
309 return $file->getRepo()->streamFile( $file->getPath(),
310 [ 'Content-Transfer-Encoding: binary',
311 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' ]
312 );
313 }
314
315 /**
316 * Output HTTP response of raw content
317 * Side effect: writes HTTP response to STDOUT.
318 * @param string $content
319 * @param string $contentType MIME type
320 * @throws SpecialUploadStashTooLargeException
321 * @return bool
322 */
323 private function outputContents( $content, $contentType ) {
324 $size = strlen( $content );
325 if ( $size > self::MAX_SERVE_BYTES ) {
326 throw new SpecialUploadStashTooLargeException(
327 wfMessage( 'uploadstash-file-too-large', self::MAX_SERVE_BYTES )
328 );
329 }
330 // Cancel output buffering and gzipping if set
331 wfResetOutputBuffers();
332 self::outputFileHeaders( $contentType, $size );
333 print $content;
334
335 return true;
336 }
337
338 /**
339 * Output headers for streaming
340 * @todo Unsure about encoding as binary; if we received from HTTP perhaps
341 * we should use that encoding, concatenated with semicolon to `$contentType` as it
342 * usually is.
343 * Side effect: preps PHP to write headers to STDOUT.
344 * @param string $contentType String suitable for content-type header
345 * @param string $size Length in bytes
346 */
347 private static function outputFileHeaders( $contentType, $size ) {
348 header( "Content-Type: $contentType", true );
349 header( 'Content-Transfer-Encoding: binary', true );
350 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
351 // T55032 - It shouldn't be a problem here, but let's be safe and not cache
352 header( 'Cache-Control: private' );
353 header( "Content-Length: $size", true );
354 }
355
356 /**
357 * Static callback for the HTMLForm in showUploads, to process
358 * Note the stash has to be recreated since this is being called in a static context.
359 * This works, because there really is only one stash per logged-in user, despite appearances.
360 *
361 * @param array $formData
362 * @param HTMLForm $form
363 * @return Status
364 */
365 public static function tryClearStashedUploads( $formData, $form ) {
366 if ( isset( $formData['Clear'] ) ) {
367 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $form->getUser() );
368 wfDebug( 'stash has: ' . print_r( $stash->listFiles(), true ) . "\n" );
369
370 if ( !$stash->clear() ) {
371 return Status::newFatal( 'uploadstash-errclear' );
372 }
373 }
374
375 return Status::newGood();
376 }
377
378 /**
379 * Default action when we don't have a subpage -- just show links to the uploads we have,
380 * Also show a button to clear stashed files
381 * @return bool
382 */
383 private function showUploads() {
384 // sets the title, etc.
385 $this->setHeaders();
386 $this->outputHeader();
387
388 // create the form, which will also be used to execute a callback to process incoming form data
389 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
390
391 $context = new DerivativeContext( $this->getContext() );
392 $context->setTitle( $this->getPageTitle() ); // Remove subpage
393 $form = HTMLForm::factory( 'ooui', [
394 'Clear' => [
395 'type' => 'hidden',
396 'default' => true,
397 'name' => 'clear',
398 ]
399 ], $context, 'clearStashedUploads' );
400 $form->setSubmitDestructive();
401 $form->setSubmitCallback( [ __CLASS__, 'tryClearStashedUploads' ] );
402 $form->setSubmitTextMsg( 'uploadstash-clear' );
403
404 $form->prepareForm();
405 $formResult = $form->tryAuthorizedSubmit();
406
407 // show the files + form, if there are any, or just say there are none
408 $refreshHtml = Html::element( 'a',
409 [ 'href' => $this->getPageTitle()->getLocalURL() ],
410 $this->msg( 'uploadstash-refresh' )->text() );
411 $files = $this->stash->listFiles();
412 if ( $files && count( $files ) ) {
413 sort( $files );
414 $fileListItemsHtml = '';
415 $linkRenderer = $this->getLinkRenderer();
416 foreach ( $files as $file ) {
417 $itemHtml = $linkRenderer->makeKnownLink(
418 $this->getPageTitle( "file/$file" ),
419 $file
420 );
421 try {
422 $fileObj = $this->stash->getFile( $file );
423 $thumb = $fileObj->generateThumbName( $file, [ 'width' => 220 ] );
424 $itemHtml .=
425 $this->msg( 'word-separator' )->escaped() .
426 $this->msg( 'parentheses' )->rawParams(
427 $linkRenderer->makeKnownLink(
428 $this->getPageTitle( "thumb/$file/$thumb" ),
429 $this->msg( 'uploadstash-thumbnail' )->text()
430 )
431 )->escaped();
432 } catch ( Exception $e ) {
433 }
434 $fileListItemsHtml .= Html::rawElement( 'li', [], $itemHtml );
435 }
436 $this->getOutput()->addHTML( Html::rawElement( 'ul', [], $fileListItemsHtml ) );
437 $form->displayForm( $formResult );
438 $this->getOutput()->addHTML( Html::rawElement( 'p', [], $refreshHtml ) );
439 } else {
440 $this->getOutput()->addHTML( Html::rawElement( 'p', [],
441 Html::element( 'span', [], $this->msg( 'uploadstash-nofiles' )->text() )
442 . ' '
443 . $refreshHtml
444 ) );
445 }
446
447 return true;
448 }
449 }
450
451 /**
452 * @ingroup SpecialPage
453 * @ingroup Upload
454 */
455 class SpecialUploadStashTooLargeException extends UploadStashException {
456 }