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