Added a workaround for the lack of RequestContext in 1.17, so this code can be rolled...
[lhc/web/wiklou.git] / includes / api / ApiUpload.php
1 <?php
2 /**
3 *
4 *
5 * Created on Aug 21, 2008
6 *
7 * Copyright © 2008 - 2010 Bryan Tong Minh <Bryan.TongMinh@Gmail.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( "ApiBase.php" );
30 }
31
32 /**
33 * @ingroup API
34 */
35 class ApiUpload extends ApiBase {
36
37 /**
38 * @var UploadBase
39 */
40 protected $mUpload = null;
41
42 protected $mParams;
43
44 public function __construct( $main, $action ) {
45 parent::__construct( $main, $action );
46 }
47
48 public function execute() {
49 global $wgUser;
50
51 // Check whether upload is enabled
52 if ( !UploadBase::isEnabled() ) {
53 $this->dieUsageMsg( 'uploaddisabled' );
54 }
55
56 // Parameter handling
57 $this->mParams = $this->extractRequestParams();
58 $request = $this->getMain()->getRequest();
59 // Add the uploaded file to the params array
60 $this->mParams['file'] = $request->getFileName( 'file' );
61
62 // Copy the session key to the file key, for backward compatibility.
63 if( !$this->mParams['filekey'] && $this->mParams['sessionkey'] ) {
64 $this->mParams['filekey'] = $this->mParams['sessionkey'];
65 }
66
67 // Select an upload module
68 if ( !$this->selectUploadModule() ) {
69 // This is not a true upload, but a status request or similar
70 return;
71 }
72 if ( !isset( $this->mUpload ) ) {
73 $this->dieUsage( 'No upload module set', 'nomodule' );
74 }
75
76 // First check permission to upload
77 $this->checkPermissions( $wgUser );
78
79 // Fetch the file
80 $status = $this->mUpload->fetchFile();
81 if ( !$status->isGood() ) {
82 $errors = $status->getErrorsArray();
83 $error = array_shift( $errors[0] );
84 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
85 }
86
87 // Check if the uploaded file is sane
88 $this->verifyUpload();
89
90
91 // Check if the user has the rights to modify or overwrite the requested title
92 // (This check is irrelevant if stashing is already requested, since the errors
93 // can always be fixed by changing the title)
94 if ( ! $this->mParams['stash'] ) {
95 $permErrors = $this->mUpload->verifyTitlePermissions( $wgUser );
96 if ( $permErrors !== true ) {
97 $this->dieRecoverableError( $permErrors[0], 'filename' );
98 }
99 }
100
101 // Prepare the API result
102 $result = array();
103
104 $warnings = $this->getApiWarnings();
105 if ( $warnings ) {
106 $result['result'] = 'Warning';
107 $result['warnings'] = $warnings;
108 // in case the warnings can be fixed with some further user action, let's stash this upload
109 // and return a key they can use to restart it
110 try {
111 $result['filekey'] = $this->performStash();
112 $result['sessionkey'] = $result['filekey']; // backwards compatibility
113 } catch ( MWException $e ) {
114 $result['warnings']['stashfailed'] = $e->getMessage();
115 }
116 } elseif ( $this->mParams['stash'] ) {
117 // Some uploads can request they be stashed, so as not to publish them immediately.
118 // In this case, a failure to stash ought to be fatal
119 try {
120 $result['result'] = 'Success';
121 $result['filekey'] = $this->performStash();
122 $result['sessionkey'] = $result['filekey']; // backwards compatibility
123 } catch ( MWException $e ) {
124 $this->dieUsage( $e->getMessage(), 'stashfailed' );
125 }
126 } else {
127 // This is the most common case -- a normal upload with no warnings
128 // $result will be formatted properly for the API already, with a status
129 $result = $this->performUpload();
130 }
131
132 if ( $result['result'] === 'Success' ) {
133 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
134 }
135
136 $this->getResult()->addValue( null, $this->getModuleName(), $result );
137
138 // Cleanup any temporary mess
139 $this->mUpload->cleanupTempFile();
140 }
141
142 /**
143 * Stash the file and return the file key
144 * Also re-raises exceptions with slightly more informative message strings (useful for API)
145 * @throws MWException
146 * @return String file key
147 */
148 function performStash() {
149 try {
150 $fileKey = $this->mUpload->stashFile()->getFileKey();
151 } catch ( MWException $e ) {
152 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
153 wfDebug( __METHOD__ . ' ' . $message . "\n");
154 throw new MWException( $message );
155 }
156 return $fileKey;
157 }
158
159 /**
160 * Throw an error that the user can recover from by providing a better
161 * value for $parameter
162 *
163 * @param $error array Error array suitable for passing to dieUsageMsg()
164 * @param $parameter string Parameter that needs revising
165 * @param $data array Optional extra data to pass to the user
166 * @throws UsageException
167 */
168 function dieRecoverableError( $error, $parameter, $data = array() ) {
169 try {
170 $data['filekey'] = $this->performStash();
171 $data['sessionkey'] = $data['filekey'];
172 } catch ( MWException $e ) {
173 $data['stashfailed'] = $e->getMessage();
174 }
175 $data['invalidparameter'] = $parameter;
176
177 $parsed = $this->parseMsg( $error );
178 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
179 }
180
181 /**
182 * Select an upload module and set it to mUpload. Dies on failure. If the
183 * request was a status request and not a true upload, returns false;
184 * otherwise true
185 *
186 * @return bool
187 */
188 protected function selectUploadModule() {
189 $request = $this->getMain()->getRequest();
190
191 // One and only one of the following parameters is needed
192 $this->requireOnlyOneParameter( $this->mParams,
193 'filekey', 'file', 'url', 'statuskey' );
194
195 if ( $this->mParams['statuskey'] ) {
196 $this->checkAsyncDownloadEnabled();
197
198 // Status request for an async upload
199 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
200 if ( !isset( $sessionData['result'] ) ) {
201 $this->dieUsage( 'No result in session data', 'missingresult' );
202 }
203 if ( $sessionData['result'] == 'Warning' ) {
204 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
205 $sessionData['sessionkey'] = $this->mParams['statuskey'];
206 }
207 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
208 return false;
209
210 }
211
212 // The following modules all require the filename parameter to be set
213 if ( is_null( $this->mParams['filename'] ) ) {
214 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
215 }
216
217 if ( $this->mParams['filekey'] ) {
218 // Upload stashed in a previous request
219 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
220 $this->dieUsageMsg( 'invalid-file-key' );
221 }
222
223 if( class_exists( 'RequestContext' ) ) {
224 // context allows access to the current user without creating new $wgUser references
225 $context = $this->createContext();
226 $this->mUpload = new UploadFromStash( $context->getUser() );
227 } else {
228 // this is here to maintain 1.17 compatibility, so these changes can
229 // be merged into production
230 // remove this after we've moved to 1.18
231 global $wgUser;
232 $this->mUpload = new UploadFromStash( $wgUser );
233 }
234
235 $this->mUpload->initialize( $this->mParams['filekey'], $this->mParams['filename'] );
236
237 } elseif ( isset( $this->mParams['file'] ) ) {
238 $this->mUpload = new UploadFromFile();
239 $this->mUpload->initialize(
240 $this->mParams['filename'],
241 $request->getUpload( 'file' )
242 );
243 } elseif ( isset( $this->mParams['url'] ) ) {
244 // Make sure upload by URL is enabled:
245 if ( !UploadFromUrl::isEnabled() ) {
246 $this->dieUsageMsg( 'copyuploaddisabled' );
247 }
248
249 $async = false;
250 if ( $this->mParams['asyncdownload'] ) {
251 $this->checkAsyncDownloadEnabled();
252
253 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
254 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
255 'missing-ignorewarnings' );
256 }
257
258 if ( $this->mParams['leavemessage'] ) {
259 $async = 'async-leavemessage';
260 } else {
261 $async = 'async';
262 }
263 }
264 $this->mUpload = new UploadFromUrl;
265 $this->mUpload->initialize( $this->mParams['filename'],
266 $this->mParams['url'], $async );
267
268 }
269
270 return true;
271 }
272
273 /**
274 * Checks that the user has permissions to perform this upload.
275 * Dies with usage message on inadequate permissions.
276 * @param $user User The user to check.
277 */
278 protected function checkPermissions( $user ) {
279 // Check whether the user has the appropriate permissions to upload anyway
280 $permission = $this->mUpload->isAllowed( $user );
281
282 if ( $permission !== true ) {
283 if ( !$user->isLoggedIn() ) {
284 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
285 } else {
286 $this->dieUsageMsg( 'badaccess-groups' );
287 }
288 }
289 }
290
291 /**
292 * Performs file verification, dies on error.
293 */
294 protected function verifyUpload( ) {
295 global $wgFileExtensions;
296
297 $verification = $this->mUpload->verifyUpload( );
298 if ( $verification['status'] === UploadBase::OK ) {
299 return;
300 }
301
302 // TODO: Move them to ApiBase's message map
303 switch( $verification['status'] ) {
304 // Recoverable errors
305 case UploadBase::MIN_LENGTH_PARTNAME:
306 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
307 break;
308 case UploadBase::ILLEGAL_FILENAME:
309 $this->dieRecoverableError( 'illegal-filename', 'filename',
310 array( 'filename' => $verification['filtered'] ) );
311 break;
312 case UploadBase::FILETYPE_MISSING:
313 $this->dieRecoverableError( 'filetype-missing', 'filename' );
314 break;
315 case UploadBase::WINDOWS_NONASCII_FILENAME:
316 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
317 break;
318
319 // Unrecoverable errors
320 case UploadBase::EMPTY_FILE:
321 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
322 break;
323 case UploadBase::FILE_TOO_LARGE:
324 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
325 break;
326
327 case UploadBase::FILETYPE_BADTYPE:
328 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
329 0, array(
330 'filetype' => $verification['finalExt'],
331 'allowed' => $wgFileExtensions
332 ) );
333 break;
334 case UploadBase::VERIFICATION_ERROR:
335 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
336 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
337 0, array( 'details' => $verification['details'] ) );
338 break;
339 case UploadBase::HOOK_ABORTED:
340 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
341 'hookaborted', 0, array( 'error' => $verification['error'] ) );
342 break;
343 default:
344 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
345 0, array( 'code' => $verification['status'] ) );
346 break;
347 }
348 }
349
350
351 /**
352 * Check warnings if ignorewarnings is not set.
353 * Returns a suitable array for inclusion into API results if there were warnings
354 * Returns the empty array if there were no warnings
355 *
356 * @return array
357 */
358 protected function getApiWarnings() {
359 $warnings = array();
360
361 if ( !$this->mParams['ignorewarnings'] ) {
362 $warnings = $this->mUpload->checkWarnings();
363 }
364 return $this->transformWarnings( $warnings );
365 }
366
367 protected function transformWarnings( $warnings ) {
368 if ( $warnings ) {
369 // Add indices
370 $result = $this->getResult();
371 $result->setIndexedTagName( $warnings, 'warning' );
372
373 if ( isset( $warnings['duplicate'] ) ) {
374 $dupes = array();
375 foreach ( $warnings['duplicate'] as $dupe ) {
376 $dupes[] = $dupe->getName();
377 }
378 $result->setIndexedTagName( $dupes, 'duplicate' );
379 $warnings['duplicate'] = $dupes;
380 }
381
382 if ( isset( $warnings['exists'] ) ) {
383 $warning = $warnings['exists'];
384 unset( $warnings['exists'] );
385 $warnings[$warning['warning']] = $warning['file']->getName();
386 }
387 }
388 return $warnings;
389 }
390
391
392 /**
393 * Perform the actual upload. Returns a suitable result array on success;
394 * dies on failure.
395 */
396 protected function performUpload() {
397 global $wgUser;
398
399 // Use comment as initial page text by default
400 if ( is_null( $this->mParams['text'] ) ) {
401 $this->mParams['text'] = $this->mParams['comment'];
402 }
403
404 $file = $this->mUpload->getLocalFile();
405 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
406
407 // Deprecated parameters
408 if ( $this->mParams['watch'] ) {
409 $watch = true;
410 }
411
412 // No errors, no warnings: do the upload
413 $status = $this->mUpload->performUpload( $this->mParams['comment'],
414 $this->mParams['text'], $watch, $wgUser );
415
416 if ( !$status->isGood() ) {
417 $error = $status->getErrorsArray();
418
419 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
420 // The upload can not be performed right now, because the user
421 // requested so
422 return array(
423 'result' => 'Queued',
424 'statuskey' => $error[0][1],
425 );
426 } else {
427 $this->getResult()->setIndexedTagName( $error, 'error' );
428
429 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
430 }
431 }
432
433 $file = $this->mUpload->getLocalFile();
434
435 $result['result'] = 'Success';
436 $result['filename'] = $file->getName();
437
438 return $result;
439 }
440
441 /**
442 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
443 */
444 protected function checkAsyncDownloadEnabled() {
445 global $wgAllowAsyncCopyUploads;
446 if ( !$wgAllowAsyncCopyUploads ) {
447 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
448 }
449 }
450
451 public function mustBePosted() {
452 return true;
453 }
454
455 public function isWriteMode() {
456 return true;
457 }
458
459 public function getAllowedParams() {
460 $params = array(
461 'filename' => array(
462 ApiBase::PARAM_TYPE => 'string',
463 ),
464 'comment' => array(
465 ApiBase::PARAM_DFLT => ''
466 ),
467 'text' => null,
468 'token' => null,
469 'watch' => array(
470 ApiBase::PARAM_DFLT => false,
471 ApiBase::PARAM_DEPRECATED => true,
472 ),
473 'watchlist' => array(
474 ApiBase::PARAM_DFLT => 'preferences',
475 ApiBase::PARAM_TYPE => array(
476 'watch',
477 'preferences',
478 'nochange'
479 ),
480 ),
481 'ignorewarnings' => false,
482 'file' => null,
483 'url' => null,
484 'filekey' => null,
485 'sessionkey' => array(
486 ApiBase::PARAM_DFLT => null,
487 ApiBase::PARAM_DEPRECATED => true,
488 ),
489 'stash' => false,
490
491 'asyncdownload' => false,
492 'leavemessage' => false,
493 'statuskey' => null,
494 );
495
496 return $params;
497 }
498
499 public function getParamDescription() {
500 $params = array(
501 'filename' => 'Target filename',
502 'token' => 'Edit token. You can get one of these through prop=info',
503 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
504 'text' => 'Initial page text for new files',
505 'watch' => 'Watch the page',
506 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
507 'ignorewarnings' => 'Ignore any warnings',
508 'file' => 'File contents',
509 'url' => 'Url to fetch the file from',
510 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
511 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
512 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
513
514 'asyncdownload' => 'Make fetching a URL asynchronous',
515 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
516 'statuskey' => 'Fetch the upload status for this file key',
517 );
518
519 return $params;
520
521 }
522
523 public function getDescription() {
524 return array(
525 'Upload a file, or get the status of pending uploads. Several methods are available:',
526 ' * Upload file contents directly, using the "file" parameter',
527 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
528 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
529 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
530 'sending the "file". Also you must get and send an edit token before doing any upload stuff'
531 );
532 }
533
534 public function getPossibleErrors() {
535 return array_merge( parent::getPossibleErrors(),
536 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
537 array(
538 array( 'uploaddisabled' ),
539 array( 'invalid-file-key' ),
540 array( 'uploaddisabled' ),
541 array( 'mustbeloggedin', 'upload' ),
542 array( 'badaccess-groups' ),
543 array( 'code' => 'fetchfileerror', 'info' => '' ),
544 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
545 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
546 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
547 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
548 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
549 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
550 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
551 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
552 )
553 );
554 }
555
556 public function needsToken() {
557 return true;
558 }
559
560 public function getTokenSalt() {
561 return '';
562 }
563
564 protected function getExamples() {
565 return array(
566 'Upload from a URL:',
567 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
568 'Complete an upload that failed due to warnings:',
569 ' api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1',
570 );
571 }
572
573 public function getHelpUrls() {
574 return 'http://www.mediawiki.org/wiki/API:Upload';
575 }
576
577 public function getVersion() {
578 return __CLASS__ . ': $Id$';
579 }
580 }