Remove the $request parameter fro SpecialUploadStash::__construct(). This parameter...
[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() {
40 global $wgRequest;
41
42 parent::__construct( 'UploadStash', 'upload' );
43 try {
44 $this->stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
45 } catch ( UploadStashNotAvailableException $e ) {
46 return null;
47 }
48
49 $this->loadRequest( $wgRequest );
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 $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 $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 . ' 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 * 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 * @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 $params = $handler->parseParamString( $paramString );
140 return array( 'file' => $file, 'type' => $type, 'params' => $params );
141 }
142
143 return array( 'file' => $file, 'type' => $type );
144 }
145
146
147
148
149 /**
150 * Get a thumbnail for file, either generated locally or remotely, and stream it out
151 * @param String $key: key for the file in the stash
152 * @param int $width: width of desired thumbnail
153 * @return boolean success
154 */
155 private function outputThumbFromStash( $file, $params ) {
156
157 // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb()
158 // 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
159 // happens to share it over NFS
160 global $wgUploadStashScalerBaseUrl;
161
162 $flags = 0;
163 if ( $wgUploadStashScalerBaseUrl ) {
164 $this->outputRemoteScaledThumb( $file, $params, $flags );
165 } else {
166 $this->outputLocallyScaledThumb( $file, $params, $flags );
167 }
168
169
170 }
171
172
173 /**
174 * Scale a file (probably with a locally installed imagemagick, or similar) and output it to STDOUT.
175 * @param $file: File object
176 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
177 * @param $flags: scaling flags ( see File:: constants )
178 * @throws MWException
179 * @return boolean success
180 */
181 private function outputLocallyScaledThumb( $file, $params, $flags ) {
182
183 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
184 // on HTTP caching to ensure this doesn't happen.
185
186 $flags |= File::RENDER_NOW;
187
188 $thumbnailImage = $file->transform( $params, $flags );
189 if ( !$thumbnailImage ) {
190 throw new MWException( 'Could not obtain thumbnail' );
191 }
192
193 // we should have just generated it locally
194 if ( ! $thumbnailImage->getPath() ) {
195 throw new UploadStashFileNotFoundException( "no local path for scaled item" );
196 }
197
198 // now we should construct a File, so we can get mime and other such info in a standard way
199 // n.b. mimetype may be different from original (ogx original -> jpeg thumb)
200 $thumbFile = new UnregisteredLocalFile( false, $this->stash->repo, $thumbnailImage->getPath(), false );
201 if ( ! $thumbFile ) {
202 throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
203 }
204
205 return $this->outputLocalFile( $thumbFile );
206
207 }
208
209 /**
210 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation cluster, and output it to STDOUT.
211 * Note: unlike the usual thumbnail process, the web client never sees the cluster URL; we do the whole HTTP transaction to the scaler ourselves
212 * and cat the results out.
213 * 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
214 * propagated back to our filesystem. Instead we take the results of the HTTP request instead.
215 * Note: no caching is being done here, although we are instructing the client to cache it forever.
216 * @param $file: File object
217 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
218 * @param $flags: scaling flags ( see File:: constants )
219 * @throws MWException
220 * @return boolean success
221 */
222 private function outputRemoteScaledThumb( $file, $params, $flags ) {
223
224 // this global probably looks something like 'http://upload.wikimedia.org/wikipedia/test/thumb/temp'
225 // do not use trailing slash
226 global $wgUploadStashScalerBaseUrl;
227
228 $scalerThumbName = $file->getParamThumbName( $file->name, $params );
229 $scalerThumbUrl = $wgUploadStashScalerBaseUrl . '/' . $file->getRel() . '/' . $scalerThumbName;
230
231 // make a curl call to the scaler to create a thumbnail
232 $httpOptions = array(
233 'method' => 'GET',
234 'timeout' => 'default'
235 );
236 $req = MWHttpRequest::factory( $scalerThumbUrl, $httpOptions );
237 $status = $req->execute();
238 if ( ! $status->isOK() ) {
239 $errors = $status->getErrorsArray();
240 throw new MWException( "Fetching thumbnail failed: " . join( ", ", $errors ) );
241 }
242 $contentType = $req->getResponseHeader( "content-type" );
243 if ( ! $contentType ) {
244 throw new MWException( "Missing content-type header" );
245 }
246 return $this->outputContents( $req->getContent(), $contentType );
247 }
248
249 /**
250 * Output HTTP response for file
251 * Side effect: writes HTTP response to STDOUT.
252 * XXX could use wfStreamfile (in includes/Streamfile.php), but for consistency with outputContents() doing it this way.
253 * XXX is mimeType really enough, or do we need encoding for full Content-Type header?
254 *
255 * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!)
256 */
257 private function outputLocalFile( $file ) {
258 if ( $file->getSize() > self::MAX_SERVE_BYTES ) {
259 throw new SpecialUploadStashTooLargeException();
260 }
261 self::outputFileHeaders( $file->getMimeType(), $file->getSize() );
262 readfile( $file->getPath() );
263 return true;
264 }
265
266 /**
267 * Output HTTP response of raw content
268 * Side effect: writes HTTP response to STDOUT.
269 * @param String $content: content
270 * @param String $mimeType: mime type
271 */
272 private function outputContents( $content, $contentType ) {
273 $size = strlen( $content );
274 if ( $size > self::MAX_SERVE_BYTES ) {
275 throw new SpecialUploadStashTooLargeException();
276 }
277 self::outputFileHeaders( $contentType, $size );
278 print $content;
279 return true;
280 }
281
282 /**
283 * Output headers for streaming
284 * 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.
285 * Side effect: preps PHP to write headers to STDOUT.
286 * @param String $contentType : string suitable for content-type header
287 * @param String $size: length in bytes
288 */
289 private static function outputFileHeaders( $contentType, $size ) {
290 header( "Content-Type: $contentType", true );
291 header( 'Content-Transfer-Encoding: binary', true );
292 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
293 header( "Content-Length: $size", true );
294 }
295
296
297 /**
298 * Initialize authorization & actions to take, from the request
299 * @param $request: WebRequest
300 */
301 private function loadRequest( $request ) {
302 global $wgUser;
303 if ( $request->wasPosted() ) {
304
305 $token = $request->getVal( 'wpEditToken' );
306 $this->isEditAuthorized = $wgUser->matchEditToken( $token );
307
308 $this->requestedClear = $request->getBool( 'clear' );
309
310 }
311 }
312
313 /**
314 * Static callback for the HTMLForm in showUploads, to process
315 * Note the stash has to be recreated since this is being called in a static context.
316 * This works, because there really is only one stash per logged-in user, despite appearances.
317 *
318 * @return Status
319 */
320 public static function tryClearStashedUploads( $formData ) {
321 wfDebug( __METHOD__ . " form data : " . print_r( $formData, 1 ) );
322 if ( isset( $formData['clear'] ) and $formData['clear'] ) {
323 $stash = new UploadStash();
324 wfDebug( "stash has: " . print_r( $stash->listFiles(), 1 ) );
325 if ( ! $stash->clear() ) {
326 return Status::newFatal( 'uploadstash-errclear' );
327 }
328 }
329 return Status::newGood();
330 }
331
332 /**
333 * Default action when we don't have a subpage -- just show links to the uploads we have,
334 * Also show a button to clear stashed files
335 * @param Status : $status - the result of processRequest
336 */
337 private function showUploads( $status = null ) {
338 global $wgOut;
339 if ( $status === null ) {
340 $status = Status::newGood();
341 }
342
343 // sets the title, etc.
344 $this->setHeaders();
345 $this->outputHeader();
346
347
348 // create the form, which will also be used to execute a callback to process incoming form data
349 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
350
351 $form = new HTMLForm( array(
352 'Clear' => array(
353 'type' => 'hidden',
354 'default' => true,
355 'name' => 'clear',
356 )
357 ), 'clearStashedUploads' );
358 $form->setSubmitCallback( array( __CLASS__, 'tryClearStashedUploads' ) );
359 $form->setTitle( $this->getTitle() );
360 $form->addHiddenField( 'clear', true, array( 'type' => 'boolean' ) );
361 $form->setSubmitText( wfMsg( 'uploadstash-clear' ) );
362
363 $form->prepareForm();
364 $formResult = $form->tryAuthorizedSubmit();
365
366
367 // show the files + form, if there are any, or just say there are none
368 $refreshHtml = Html::element( 'a', array( 'href' => $this->getTitle()->getLocalURL() ), wfMsg( 'uploadstash-refresh' ) );
369 $files = $this->stash->listFiles();
370 if ( count( $files ) ) {
371 sort( $files );
372 $fileListItemsHtml = '';
373 foreach ( $files as $file ) {
374 $fileListItemsHtml .= Html::rawElement( 'li', array(),
375 Html::element( 'a', array( 'href' =>
376 $this->getTitle( "file/$file" )->getLocalURL() ), $file )
377 );
378 }
379 $wgOut->addHtml( Html::rawElement( 'ul', array(), $fileListItemsHtml ) );
380 $form->displayForm( $formResult );
381 $wgOut->addHtml( Html::rawElement( 'p', array(), $refreshHtml ) );
382 } else {
383 $wgOut->addHtml( Html::rawElement( 'p', array(),
384 Html::element( 'span', array(), wfMsg( 'uploadstash-nofiles' ) )
385 . ' '
386 . $refreshHtml
387 ) );
388 }
389
390 return true;
391 }
392 }
393
394 class SpecialUploadStashTooLargeException extends MWException {};