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