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