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