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