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