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