9dd78efa3de564b8d76e7bf96a5686620e0974d0
[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 if ( !$this->userCanExecute( $this->getUser() ) ) {
50 $this->displayRestrictionError();
51 return;
52 }
53
54 if ( $subPage === null || $subPage === '' ) {
55 return $this->showUploads();
56 } else {
57 return $this->showUpload( $subPage );
58 }
59 }
60
61
62 /**
63 * If file available in stash, cats it out to the client as a simple HTTP response.
64 * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward.
65 *
66 * @param $key String: the key of a particular requested file
67 */
68 public function showUpload( $key ) {
69 // prevent callers from doing standard HTML output -- we'll take it from here
70 $this->getOutput()->disable();
71
72 try {
73 $params = $this->parseKey( $key );
74 if ( $params['type'] === 'thumb' ) {
75 return $this->outputThumbFromStash( $params['file'], $params['params'] );
76 } else {
77 return $this->outputLocalFile( $params['file'] );
78 }
79 } catch( UploadStashFileNotFoundException $e ) {
80 $code = 404;
81 $message = $e->getMessage();
82 } catch( UploadStashZeroLengthFileException $e ) {
83 $code = 500;
84 $message = $e->getMessage();
85 } catch( UploadStashBadPathException $e ) {
86 $code = 500;
87 $message = $e->getMessage();
88 } catch( SpecialUploadStashTooLargeException $e ) {
89 $code = 500;
90 $message = 'Cannot serve a file larger than ' . self::MAX_SERVE_BYTES . ' bytes. ' . $e->getMessage();
91 } catch( Exception $e ) {
92 $code = 500;
93 $message = $e->getMessage();
94 }
95
96 throw new HttpError( $code, $message );
97 }
98
99 /**
100 * Parse the key passed to the SpecialPage. Returns an array containing
101 * the associated file object, the type ('file' or 'thumb') and if
102 * application the transform parameters
103 *
104 * @param string $key
105 * @return array
106 */
107 private function parseKey( $key ) {
108 $type = strtok( $key, '/' );
109
110 if ( $type !== 'file' && $type !== 'thumb' ) {
111 throw new UploadStashBadPathException( "Unknown type '$type'" );
112 }
113 $fileName = strtok( '/' );
114 $thumbPart = strtok( '/' );
115 $file = $this->stash->getFile( $fileName );
116 if ( $type === 'thumb' ) {
117 $srcNamePos = strrpos( $thumbPart, $fileName );
118 if ( $srcNamePos === false || $srcNamePos < 1 ) {
119 throw new UploadStashBadPathException( 'Unrecognized thumb name' );
120 }
121 $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
122
123 $handler = $file->getHandler();
124 $params = $handler->parseParamString( $paramString );
125 return array( 'file' => $file, 'type' => $type, 'params' => $params );
126 }
127
128 return array( 'file' => $file, 'type' => $type );
129 }
130
131 /**
132 * Get a thumbnail for file, either generated locally or remotely, and stream it out
133 *
134 * @param $file
135 * @param $params array
136 *
137 * @return boolean success
138 */
139 private function outputThumbFromStash( $file, $params ) {
140
141 // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb()
142 // 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
143 // happens to share it over NFS
144 global $wgUploadStashScalerBaseUrl;
145
146 $flags = 0;
147 if ( $wgUploadStashScalerBaseUrl ) {
148 $this->outputRemoteScaledThumb( $file, $params, $flags );
149 } else {
150 $this->outputLocallyScaledThumb( $file, $params, $flags );
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 $scalerBaseUrl = $wgUploadStashScalerBaseUrl;
209
210 if( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
211 // this is apparently a protocol-relative URL, which makes no sense in this context,
212 // since this is used for communication that's internal to the application.
213 // default to http.
214 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL );
215 }
216
217 // We need to use generateThumbName() instead of thumbName(), because
218 // the suffix needs to match the file name for the remote thumbnailer
219 // to work
220 $scalerThumbName = $file->generateThumbName( $file->getName(), $params );
221 $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() .
222 '/' . rawurlencode( $scalerThumbName );
223
224 // make a curl call to the scaler to create a thumbnail
225 $httpOptions = array(
226 'method' => 'GET',
227 'timeout' => 'default'
228 );
229 $req = MWHttpRequest::factory( $scalerThumbUrl, $httpOptions );
230 $status = $req->execute();
231 if ( ! $status->isOK() ) {
232 $errors = $status->getErrorsArray();
233 $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 );
234 $errorStr .= "\nurl = $scalerThumbUrl\n";
235 throw new MWException( $errorStr );
236 }
237 $contentType = $req->getResponseHeader( "content-type" );
238 if ( ! $contentType ) {
239 throw new MWException( "Missing content-type header" );
240 }
241 return $this->outputContents( $req->getContent(), $contentType );
242 }
243
244 /**
245 * Output HTTP response for file
246 * Side effect: writes HTTP response to STDOUT.
247 * XXX could use wfStreamfile (in includes/Streamfile.php), but for consistency with outputContents() doing it this way.
248 * XXX is mimeType really enough, or do we need encoding for full Content-Type header?
249 *
250 * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!)
251 */
252 private function outputLocalFile( $file ) {
253 if ( $file->getSize() > self::MAX_SERVE_BYTES ) {
254 throw new SpecialUploadStashTooLargeException();
255 }
256 self::outputFileHeaders( $file->getMimeType(), $file->getSize() );
257 readfile( $file->getPath() );
258 return true;
259 }
260
261 /**
262 * Output HTTP response of raw content
263 * Side effect: writes HTTP response to STDOUT.
264 * @param String $content: content
265 * @param String $mimeType: mime type
266 */
267 private function outputContents( $content, $contentType ) {
268 $size = strlen( $content );
269 if ( $size > self::MAX_SERVE_BYTES ) {
270 throw new SpecialUploadStashTooLargeException();
271 }
272 self::outputFileHeaders( $contentType, $size );
273 print $content;
274 return true;
275 }
276
277 /**
278 * Output headers for streaming
279 * 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.
280 * Side effect: preps PHP to write headers to STDOUT.
281 * @param String $contentType : string suitable for content-type header
282 * @param String $size: length in bytes
283 */
284 private static function outputFileHeaders( $contentType, $size ) {
285 header( "Content-Type: $contentType", true );
286 header( 'Content-Transfer-Encoding: binary', true );
287 header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true );
288 header( "Content-Length: $size", true );
289 }
290
291 /**
292 * Static callback for the HTMLForm in showUploads, to process
293 * Note the stash has to be recreated since this is being called in a static context.
294 * This works, because there really is only one stash per logged-in user, despite appearances.
295 *
296 * @return Status
297 */
298 public static function tryClearStashedUploads( $formData ) {
299 if ( isset( $formData['Clear'] ) ) {
300 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
301 wfDebug( "stash has: " . print_r( $stash->listFiles(), true ) );
302 if ( ! $stash->clear() ) {
303 return Status::newFatal( 'uploadstash-errclear' );
304 }
305 }
306 return Status::newGood();
307 }
308
309 /**
310 * Default action when we don't have a subpage -- just show links to the uploads we have,
311 * Also show a button to clear stashed files
312 * @param Status : $status - the result of processRequest
313 */
314 private function showUploads( $status = null ) {
315 if ( $status === null ) {
316 $status = Status::newGood();
317 }
318
319 // sets the title, etc.
320 $this->setHeaders();
321 $this->outputHeader();
322
323 // create the form, which will also be used to execute a callback to process incoming form data
324 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
325
326 $form = new HTMLForm( array(
327 'Clear' => array(
328 'type' => 'hidden',
329 'default' => true,
330 'name' => 'clear',
331 )
332 ), $this->getContext(), 'clearStashedUploads' );
333 $form->setSubmitCallback( array( __CLASS__ , 'tryClearStashedUploads' ) );
334 $form->setTitle( $this->getTitle() );
335 $form->setSubmitText( wfMsg( 'uploadstash-clear' ) );
336
337 $form->prepareForm();
338 $formResult = $form->tryAuthorizedSubmit();
339
340 // show the files + form, if there are any, or just say there are none
341 $refreshHtml = Html::element( 'a',
342 array( 'href' => $this->getTitle()->getLocalURL() ),
343 wfMsg( 'uploadstash-refresh' ) );
344 $files = $this->stash->listFiles();
345 if ( $files && count( $files ) ) {
346 sort( $files );
347 $fileListItemsHtml = '';
348 foreach ( $files as $file ) {
349 // TODO: Use Linker::link or even construct the list in plain wikitext
350 $fileListItemsHtml .= Html::rawElement( 'li', array(),
351 Html::element( 'a', array( 'href' =>
352 $this->getTitle( "file/$file" )->getLocalURL() ), $file )
353 );
354 }
355 $this->getOutput()->addHtml( Html::rawElement( 'ul', array(), $fileListItemsHtml ) );
356 $form->displayForm( $formResult );
357 $this->getOutput()->addHtml( Html::rawElement( 'p', array(), $refreshHtml ) );
358 } else {
359 $this->getOutput()->addHtml( Html::rawElement( 'p', array(),
360 Html::element( 'span', array(), wfMsg( 'uploadstash-nofiles' ) )
361 . ' '
362 . $refreshHtml
363 ) );
364 }
365
366 return true;
367 }
368 }
369
370 class SpecialUploadStashTooLargeException extends MWException {};