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