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