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