Update some deprecated code
[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 if ( !$this->userCanExecute( $this->getUser() ) ) {
49 $this->displayRestrictionError();
50 return false;
51 }
52
53 if ( $subPage === null || $subPage === '' ) {
54 return $this->showUploads();
55 }
56 return $this->showUpload( $subPage );
57 }
58
59 /**
60 * If file available in stash, cats it out to the client as a simple HTTP response.
61 * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward.
62 *
63 * @param $key String: the key of a particular requested file
64 */
65 public function showUpload( $key ) {
66 // prevent callers from doing standard HTML output -- we'll take it from here
67 $this->getOutput()->disable();
68
69 try {
70 $params = $this->parseKey( $key );
71 if ( $params['type'] === 'thumb' ) {
72 return $this->outputThumbFromStash( $params['file'], $params['params'] );
73 } else {
74 return $this->outputLocalFile( $params['file'] );
75 }
76 } catch( UploadStashFileNotFoundException $e ) {
77 $code = 404;
78 $message = $e->getMessage();
79 } catch( UploadStashZeroLengthFileException $e ) {
80 $code = 500;
81 $message = $e->getMessage();
82 } catch( UploadStashBadPathException $e ) {
83 $code = 500;
84 $message = $e->getMessage();
85 } catch( SpecialUploadStashTooLargeException $e ) {
86 $code = 500;
87 $message = 'Cannot serve a file larger than ' . self::MAX_SERVE_BYTES . ' bytes. ' . $e->getMessage();
88 } catch( Exception $e ) {
89 $code = 500;
90 $message = $e->getMessage();
91 }
92
93 throw new HttpError( $code, $message );
94 }
95
96 /**
97 * Parse the key passed to the SpecialPage. Returns an array containing
98 * the associated file object, the type ('file' or 'thumb') and if
99 * application the transform parameters
100 *
101 * @param string $key
102 * @return array
103 */
104 private function parseKey( $key ) {
105 $type = strtok( $key, '/' );
106
107 if ( $type !== 'file' && $type !== 'thumb' ) {
108 throw new UploadStashBadPathException( "Unknown type '$type'" );
109 }
110 $fileName = strtok( '/' );
111 $thumbPart = strtok( '/' );
112 $file = $this->stash->getFile( $fileName );
113 if ( $type === 'thumb' ) {
114 $srcNamePos = strrpos( $thumbPart, $fileName );
115 if ( $srcNamePos === false || $srcNamePos < 1 ) {
116 throw new UploadStashBadPathException( 'Unrecognized thumb name' );
117 }
118 $paramString = substr( $thumbPart, 0, $srcNamePos - 1 );
119
120 $handler = $file->getHandler();
121 $params = $handler->parseParamString( $paramString );
122 return array( 'file' => $file, 'type' => $type, 'params' => $params );
123 }
124
125 return array( 'file' => $file, 'type' => $type );
126 }
127
128 /**
129 * Get a thumbnail for file, either generated locally or remotely, and stream it out
130 *
131 * @param $file
132 * @param $params array
133 *
134 * @return boolean success
135 */
136 private function outputThumbFromStash( $file, $params ) {
137
138 // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb()
139 // 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
140 // happens to share it over NFS
141 global $wgUploadStashScalerBaseUrl;
142
143 $flags = 0;
144 if ( $wgUploadStashScalerBaseUrl ) {
145 $this->outputRemoteScaledThumb( $file, $params, $flags );
146 } else {
147 $this->outputLocallyScaledThumb( $file, $params, $flags );
148 }
149 }
150
151 /**
152 * Scale a file (probably with a locally installed imagemagick, or similar) and output it to STDOUT.
153 * @param $file: File object
154 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
155 * @param $flags: scaling flags ( see File:: constants )
156 * @throws MWException
157 * @return boolean success
158 */
159 private function outputLocallyScaledThumb( $file, $params, $flags ) {
160
161 // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely
162 // on HTTP caching to ensure this doesn't happen.
163
164 $flags |= File::RENDER_NOW;
165
166 $thumbnailImage = $file->transform( $params, $flags );
167 if ( !$thumbnailImage ) {
168 throw new MWException( 'Could not obtain thumbnail' );
169 }
170
171 // we should have just generated it locally
172 if ( ! $thumbnailImage->getPath() ) {
173 throw new UploadStashFileNotFoundException( "no local path for scaled item" );
174 }
175
176 // now we should construct a File, so we can get mime and other such info in a standard way
177 // n.b. mimetype may be different from original (ogx original -> jpeg thumb)
178 $thumbFile = new UnregisteredLocalFile( false, $this->stash->repo, $thumbnailImage->getPath(), false );
179 if ( ! $thumbFile ) {
180 throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" );
181 }
182
183 return $this->outputLocalFile( $thumbFile );
184
185 }
186
187 /**
188 * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation cluster, and output it to STDOUT.
189 * Note: unlike the usual thumbnail process, the web client never sees the cluster URL; we do the whole HTTP transaction to the scaler ourselves
190 * and cat the results out.
191 * 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
192 * propagated back to our filesystem. Instead we take the results of the HTTP request instead.
193 * Note: no caching is being done here, although we are instructing the client to cache it forever.
194 * @param $file: File object
195 * @param $params: scaling parameters ( e.g. array( width => '50' ) );
196 * @param $flags: scaling flags ( see File:: constants )
197 * @throws MWException
198 * @return boolean success
199 */
200 private function outputRemoteScaledThumb( $file, $params, $flags ) {
201
202 // this global probably looks something like 'http://upload.wikimedia.org/wikipedia/test/thumb/temp'
203 // do not use trailing slash
204 global $wgUploadStashScalerBaseUrl;
205 $scalerBaseUrl = $wgUploadStashScalerBaseUrl;
206
207 if( preg_match( '/^\/\//', $scalerBaseUrl ) ) {
208 // this is apparently a protocol-relative URL, which makes no sense in this context,
209 // since this is used for communication that's internal to the application.
210 // default to http.
211 $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL );
212 }
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 = $scalerBaseUrl . '/' . $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->getErrorsArray();
230 $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 );
231 $errorStr .= "\nurl = $scalerThumbUrl\n";
232 throw new MWException( $errorStr );
233 }
234 $contentType = $req->getResponseHeader( "content-type" );
235 if ( ! $contentType ) {
236 throw new MWException( "Missing content-type header" );
237 }
238 return $this->outputContents( $req->getContent(), $contentType );
239 }
240
241 /**
242 * Output HTTP response for file
243 * Side effect: writes HTTP response to STDOUT.
244 * XXX could use wfStreamfile (in includes/Streamfile.php), but for consistency with outputContents() doing it this way.
245 * XXX is mimeType really enough, or do we need encoding for full Content-Type header?
246 *
247 * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!)
248 */
249 private function outputLocalFile( $file ) {
250 if ( $file->getSize() > self::MAX_SERVE_BYTES ) {
251 throw new SpecialUploadStashTooLargeException();
252 }
253 self::outputFileHeaders( $file->getMimeType(), $file->getSize() );
254 readfile( $file->getPath() );
255 return true;
256 }
257
258 /**
259 * Output HTTP response of raw content
260 * Side effect: writes HTTP response to STDOUT.
261 * @param String $content: content
262 * @param String $mimeType: mime type
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 */
311 private function showUploads( $status = null ) {
312 if ( $status === null ) {
313 $status = Status::newGood();
314 }
315
316 // sets the title, etc.
317 $this->setHeaders();
318 $this->outputHeader();
319
320 // create the form, which will also be used to execute a callback to process incoming form data
321 // this design is extremely dubious, but supposedly HTMLForm is our standard now?
322
323 $form = new HTMLForm( array(
324 'Clear' => array(
325 'type' => 'hidden',
326 'default' => true,
327 'name' => 'clear',
328 )
329 ), $this->getContext(), 'clearStashedUploads' );
330 $form->setSubmitCallback( array( __CLASS__ , 'tryClearStashedUploads' ) );
331 $form->setTitle( $this->getTitle() );
332 $form->setSubmitText( wfMsg( 'uploadstash-clear' ) );
333
334 $form->prepareForm();
335 $formResult = $form->tryAuthorizedSubmit();
336
337 // show the files + form, if there are any, or just say there are none
338 $refreshHtml = Html::element( 'a',
339 array( 'href' => $this->getTitle()->getLocalURL() ),
340 wfMsg( 'uploadstash-refresh' ) );
341 $files = $this->stash->listFiles();
342 if ( $files && count( $files ) ) {
343 sort( $files );
344 $fileListItemsHtml = '';
345 foreach ( $files as $file ) {
346 // TODO: Use Linker::link or even construct the list in plain wikitext
347 $fileListItemsHtml .= Html::rawElement( 'li', array(),
348 Html::element( 'a', array( 'href' =>
349 $this->getTitle( "file/$file" )->getLocalURL() ), $file )
350 );
351 }
352 $this->getOutput()->addHtml( Html::rawElement( 'ul', array(), $fileListItemsHtml ) );
353 $form->displayForm( $formResult );
354 $this->getOutput()->addHtml( Html::rawElement( 'p', array(), $refreshHtml ) );
355 } else {
356 $this->getOutput()->addHtml( Html::rawElement( 'p', array(),
357 Html::element( 'span', array(), wfMsg( 'uploadstash-nofiles' ) )
358 . ' '
359 . $refreshHtml
360 ) );
361 }
362
363 return true;
364 }
365 }
366
367 class SpecialUploadStashTooLargeException extends MWException {};