Clean up the running mess that is r64866, r65040, and then r67277. Implement and...
[lhc/web/wiklou.git] / includes / specials / SpecialUploadStash.php
1 <?php
2 /**
3 * Implements Special:UploadStash
4 *
5 * Web access for files temporarily stored by UploadStash.
6 *
7 * For example -- files that were uploaded with the UploadWizard extension are stored temporarily
8 * before committing them to the db. But we want to see their thumbnails and get other information
9 * about them.
10 *
11 * Since this is based on the user's session, in effect this creates a private temporary file area.
12 * However, the URLs for the files cannot be shared.
13 *
14 * @file
15 * @ingroup SpecialPage
16 * @ingroup Upload
17 */
18
19 class SpecialUploadStash extends UnlistedSpecialPage {
20 // UploadStash
21 private $stash;
22
23 // is the edit request authorized? boolean
24 private $isEditAuthorized;
25
26 // did the user request us to clear the stash? boolean
27 private $requestedClear;
28
29 // Since we are directly writing the file to STDOUT,
30 // we should not be reading in really big files and serving them out.
31 //
32 // We also don't want people using this as a file drop, even if they
33 // share credentials.
34 //
35 // This service is really for thumbnails and other such previews while
36 // uploading.
37 const MAX_SERVE_BYTES = 262144; // 256K
38
39 public function __construct( $request = null ) {
40 global $wgRequest;
41
42 parent::__construct( 'UploadStash', 'upload' );
43 try {
44 $this->stash = new UploadStash( );
45 } catch ( UploadStashNotAvailableException $e ) {
46 return null;
47 }
48
49 $this->loadRequest( is_null( $request ) ? $wgRequest : $request );
50 }
51
52 /**
53 * Execute page -- can output a file directly or show a listing of them.
54 *
55 * @param $subPage String: subpage, e.g. in http://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part
56 * @return Boolean: success
57 */
58 public function execute( $subPage ) {
59 global $wgOut, $wgUser;
60
61 if ( !$this->userCanExecute( $wgUser ) ) {
62 $this->displayRestrictionError();
63 return;
64 }
65
66 if ( !isset( $subPage ) || $subPage === '' ) {
67 return $this->showUploads();
68 }
69
70 return $this->showUpload( $subPage );
71 }
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 $key String: the key of a particular requested file
79 */
80 public function showUpload( $key ) {
81 global $wgOut;
82
83 // prevent callers from doing standard HTML output -- we'll take it from here
84 $wgOut->disable();
85
86 try {
87 if ( preg_match( '/^(\d+)px-(.*)$/', $key, $matches ) ) {
88 list( /* full match */, $width, $key ) = $matches;
89 return $this->outputThumbFromStash( $key, $width );
90 } else {
91 return $this->outputFileFromStash( $key );
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 . ' bytes. ' . $e->getMessage();
105 } catch( Exception $e ) {
106 $code = 500;
107 $message = $e->getMessage();
108 }
109
110 wfHttpError( $code, OutputPage::getStatusMessage( $code ), $message );
111 return false;
112 }
113
114 /**
115 * Get a file from stash and stream it out. Rely on parent to catch exceptions and transform them into HTTP
116 * @param String: $key - key of this file in the stash, which probably looks like a filename with extension.
117 * @return boolean
118 */
119 private function outputFileFromStash( $key ) {
120 $file = $this->stash->getFile( $key );
121 return $this->outputLocalFile( $file );
122 }
123
124
125 /**
126 * Get a thumbnail for file, either generated locally or remotely, and stream it out
127 * @param String $key: key for the file in the stash
128 * @param int $width: width of desired thumbnail
129 * @return boolean success
130 */
131 private function outputThumbFromStash( $key, $width ) {
132
133 // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb()
134 // 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
135 // happens to share it over NFS
136 global $wgUploadStashScalerBaseUrl;
137
138 // let exceptions propagate to caller.
139 $file = $this->stash->getFile( $key );
140
141 // OK, we're here and no exception was thrown,
142 // so the original file must exist.
143
144 // let's get ready to transform the original -- these are standard
145 $params = array( 'width' => $width );
146 $flags = 0;
147
148 return $wgUploadStashScalerBaseUrl ? $this->outputRemoteScaledThumb( $file, $params, $flags )
149 : $this->outputLocallyScaledThumb( $file, $params, $flags );
150
151 }
152
153
154 /**
155 * Scale a file (probably with a locally installed imagemagick, or similar) and output it to STDOUT.
156 * @param $file: File object
157 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
158 * @param $flags: scaling flags ( see File:: constants )
159 * @throws MWException
160 * @return boolean success
161 */
162 private function outputLocallyScaledThumb( $file, $params, $flags ) {
163
164 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
165 // on HTTP caching to ensure this doesn't happen.
166
167 $flags |= File::RENDER_NOW;
168
169 $thumbnailImage = $file->transform( $params, $flags );
170 if ( !$thumbnailImage ) {
171 throw new MWException( 'Could not obtain thumbnail' );
172 }
173
174 // we should have just generated it locally
175 if ( ! $thumbnailImage->getPath() ) {
176 throw new UploadStashFileNotFoundException( "no local path for scaled item" );
177 }
178
179 // now we should construct a File, so we can get mime and other such info in a standard way
180 // n.b. mimetype may be different from original (ogx original -> jpeg thumb)
181 $thumbFile = new UnregisteredLocalFile( false, $this->stash->repo, $thumbnailImage->getPath(), false );
182 if ( ! $thumbFile ) {
183 throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
184 }
185
186 return $this->outputLocalFile( $thumbFile );
187
188 }
189
190 /**
191 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation cluster, and output it to STDOUT.
192 * Note: unlike the usual thumbnail process, the web client never sees the cluster URL; we do the whole HTTP transaction to the scaler ourselves
193 * and cat the results out.
194 * 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
195 * propagated back to our filesystem. Instead we take the results of the HTTP request instead.
196 * Note: no caching is being done here, although we are instructing the client to cache it forever.
197 * @param $file: File object
198 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
199 * @param $flags: scaling flags ( see File:: constants )
200 * @throws MWException
201 * @return boolean success
202 */
203 private function outputRemoteScaledThumb( $file, $params, $flags ) {
204
205 // this global probably looks something like 'http://upload.wikimedia.org/wikipedia/test/thumb/temp'
206 // do not use trailing slash
207 global $wgUploadStashScalerBaseUrl;
208
209 $scalerThumbName = $file->getParamThumbName( $file->name, $params );
210 $scalerThumbUrl = $wgUploadStashScalerBaseUrl . '/' . $file->getRel() . '/' . $scalerThumbName;
211
212 // make a curl call to the scaler to create a thumbnail
213 $httpOptions = array(
214 'method' => 'GET',
215 'timeout' => 'default'
216 );
217 $req = MWHttpRequest::factory( $scalerThumbUrl, $httpOptions );
218 $status = $req->execute();
219 if ( ! $status->isOK() ) {
220 $errors = $status->getErrorsArray();
221 throw new MWException( "Fetching thumbnail failed: " . join( ", ", $errors ) );
222 }
223 $contentType = $req->getResponseHeader( "content-type" );
224 if ( ! $contentType ) {
225 throw new MWException( "Missing content-type header" );
226 }
227 return $this->outputContents( $req->getContent(), $contentType );
228 }
229
230 /**
231 * Output HTTP response for file
232 * Side effect: writes HTTP response to STDOUT.
233 * XXX could use wfStreamfile (in includes/Streamfile.php), but for consistency with outputContents() doing it this way.
234 * XXX is mimeType really enough, or do we need encoding for full Content-Type header?
235 *
236 * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!)
237 */
238 private function outputLocalFile( $file ) {
239 if ( $file->getSize() > self::MAX_SERVE_BYTES ) {
240 throw new SpecialUploadStashTooLargeException();
241 }
242 self::outputFileHeaders( $file->getMimeType(), $file->getSize() );
243 readfile( $file->getPath() );
244 return true;
245 }
246
247 /**
248 * Output HTTP response of raw content
249 * Side effect: writes HTTP response to STDOUT.
250 * @param String $content: content
251 * @param String $mimeType: mime type
252 */
253 private function outputContents( $content, $contentType ) {
254 $size = strlen( $content );
255 if ( $size > self::MAX_SERVE_BYTES ) {
256 throw new SpecialUploadStashTooLargeException();
257 }
258 self::outputFileHeaders( $contentType, $size );
259 print $content;
260 return true;
261 }
262
263 /**
264 * Output headers for streaming
265 * 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.
266 * Side effect: preps PHP to write headers to STDOUT.
267 * @param String $contentType : string suitable for content-type header
268 * @param String $size: length in bytes
269 */
270 private static function outputFileHeaders( $contentType, $size ) {
271 header( "Content-Type: $contentType", true );
272 header( 'Content-Transfer-Encoding: binary', true );
273 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
274 header( "Content-Length: $size", true );
275 }
276
277
278 /**
279 * Initialize authorization & actions to take, from the request
280 * @param $request: WebRequest
281 */
282 private function loadRequest( $request ) {
283 global $wgUser;
284 if ( $request->wasPosted() ) {
285
286 $token = $request->getVal( 'wpEditToken' );
287 $this->isEditAuthorized = $wgUser->matchEditToken( $token );
288
289 $this->requestedClear = $request->getBool( 'clear' );
290
291 }
292 }
293
294 /**
295 * Static callback for the HTMLForm in showUploads, to process
296 * Note the stash has to be recreated since this is being called in a static context.
297 * This works, because there really is only one stash per logged-in user, despite appearances.
298 *
299 * @return Status
300 */
301 public static function tryClearStashedUploads( $formData ) {
302 wfDebug( __METHOD__ . " form data : " . print_r( $formData, 1 ) );
303 if ( isset( $formData['clear'] ) and $formData['clear'] ) {
304 $stash = new UploadStash();
305 wfDebug( "stash has: " . print_r( $stash->listFiles(), 1 ) );
306 if ( ! $stash->clear() ) {
307 return Status::newFatal( 'uploadstash-errclear' );
308 }
309 }
310 return Status::newGood();
311 }
312
313 /**
314 * Default action when we don't have a subpage -- just show links to the uploads we have,
315 * Also show a button to clear stashed files
316 * @param Status : $status - the result of processRequest
317 */
318 private function showUploads( $status = null ) {
319 global $wgOut;
320 if ( $status === null ) {
321 $status = Status::newGood();
322 }
323
324 // sets the title, etc.
325 $this->setHeaders();
326 $this->outputHeader();
327
328
329 // create the form, which will also be used to execute a callback to process incoming form data
330 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
331
332 $form = new HTMLForm( array(
333 'Clear' => array(
334 'type' => 'hidden',
335 'default' => true,
336 'name' => 'clear',
337 )
338 ), 'clearStashedUploads' );
339 $form->setSubmitCallback( array( __CLASS__, 'tryClearStashedUploads' ) );
340 $form->setTitle( $this->getTitle() );
341 $form->addHiddenField( 'clear', true, array( 'type' => 'boolean' ) );
342 $form->setSubmitText( wfMsg( 'uploadstash-clear' ) );
343
344 $form->prepareForm();
345 $formResult = $form->tryAuthorizedSubmit();
346
347
348 // show the files + form, if there are any, or just say there are none
349 $refreshHtml = Html::element( 'a', array( 'href' => $this->getTitle()->getLocalURL() ), wfMsg( 'uploadstash-refresh' ) );
350 $files = $this->stash->listFiles();
351 if ( count( $files ) ) {
352 sort( $files );
353 $fileListItemsHtml = '';
354 foreach ( $files as $file ) {
355 $fileListItemsHtml .= Html::rawElement( 'li', array(),
356 Html::element( 'a', array( 'href' => $this->getTitle( $file )->getLocalURL() ), $file )
357 );
358 }
359 $wgOut->addHtml( Html::rawElement( 'ul', array(), $fileListItemsHtml ) );
360 $form->displayForm( $formResult );
361 $wgOut->addHtml( Html::rawElement( 'p', array(), $refreshHtml ) );
362 } else {
363 $wgOut->addHtml( Html::rawElement( 'p', array(),
364 Html::element( 'span', array(), wfMsg( 'uploadstash-nofiles' ) )
365 . ' '
366 . $refreshHtml
367 ) );
368 }
369
370 return true;
371 }
372 }
373
374 class SpecialUploadStashTooLargeException extends MWException {};