5 * Created on Aug 21, 2008
7 * Copyright © 2008 - 2010 Bryan Tong Minh <Bryan.TongMinh@Gmail.com>
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.
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.
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
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( "ApiBase.php" );
35 class ApiUpload
extends ApiBase
{
40 protected $mUpload = null;
44 public function __construct( $main, $action ) {
45 parent
::__construct( $main, $action );
48 public function execute() {
51 // Check whether upload is enabled
52 if ( !UploadBase
::isEnabled() ) {
53 $this->dieUsageMsg( 'uploaddisabled' );
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' );
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'];
67 // Select an upload module
68 if ( !$this->selectUploadModule() ) {
69 // This is not a true upload, but a status request or similar
72 if ( !isset( $this->mUpload
) ) {
73 $this->dieUsage( 'No upload module set', 'nomodule' );
76 // First check permission to upload
77 $this->checkPermissions( $wgUser );
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] );
87 // Check if the uploaded file is sane
88 $this->verifyUpload();
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' );
101 // Prepare the API result
104 $warnings = $this->getApiWarnings();
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
111 $result['filekey'] = $this->performStash();
112 $result['sessionkey'] = $result['filekey']; // backwards compatibility
113 } catch ( MWException
$e ) {
114 $result['warnings']['stashfailed'] = $e->getMessage();
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
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' );
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();
132 if ( $result['result'] === 'Success' ) {
133 $result['imageinfo'] = $this->mUpload
->getImageInfo( $this->getResult() );
136 $this->getResult()->addValue( null, $this->getModuleName(), $result );
138 // Cleanup any temporary mess
139 $this->mUpload
->cleanupTempFile();
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
148 function performStash() {
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 );
160 * Throw an error that the user can recover from by providing a better
161 * value for $parameter
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
168 function dieRecoverableError( $error, $parameter, $data = array() ) {
170 $data['filekey'] = $this->performStash();
171 $data['sessionkey'] = $data['filekey'];
172 } catch ( MWException
$e ) {
173 $data['stashfailed'] = $e->getMessage();
175 $data['invalidparameter'] = $parameter;
177 $parsed = $this->parseMsg( $error );
178 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
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;
188 protected function selectUploadModule() {
189 $request = $this->getMain()->getRequest();
191 // One and only one of the following parameters is needed
192 $this->requireOnlyOneParameter( $this->mParams
,
193 'filekey', 'file', 'url', 'statuskey' );
195 if ( $this->mParams
['statuskey'] ) {
196 $this->checkAsyncDownloadEnabled();
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' );
203 if ( $sessionData['result'] == 'Warning' ) {
204 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
205 $sessionData['sessionkey'] = $this->mParams
['statuskey'];
207 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
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' ) );
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' );
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() );
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
232 $this->mUpload
= new UploadFromStash( $wgUser );
235 $this->mUpload
->initialize( $this->mParams
['filekey'], $this->mParams
['filename'] );
237 } elseif ( isset( $this->mParams
['file'] ) ) {
238 $this->mUpload
= new UploadFromFile();
239 $this->mUpload
->initialize(
240 $this->mParams
['filename'],
241 $request->getUpload( 'file' )
243 } elseif ( isset( $this->mParams
['url'] ) ) {
244 // Make sure upload by URL is enabled:
245 if ( !UploadFromUrl
::isEnabled() ) {
246 $this->dieUsageMsg( 'copyuploaddisabled' );
250 if ( $this->mParams
['asyncdownload'] ) {
251 $this->checkAsyncDownloadEnabled();
253 if ( $this->mParams
['leavemessage'] && !$this->mParams
['ignorewarnings'] ) {
254 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
255 'missing-ignorewarnings' );
258 if ( $this->mParams
['leavemessage'] ) {
259 $async = 'async-leavemessage';
264 $this->mUpload
= new UploadFromUrl
;
265 $this->mUpload
->initialize( $this->mParams
['filename'],
266 $this->mParams
['url'], $async );
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.
278 protected function checkPermissions( $user ) {
279 // Check whether the user has the appropriate permissions to upload anyway
280 $permission = $this->mUpload
->isAllowed( $user );
282 if ( $permission !== true ) {
283 if ( !$user->isLoggedIn() ) {
284 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
286 $this->dieUsageMsg( 'badaccess-groups' );
292 * Performs file verification, dies on error.
294 protected function verifyUpload( ) {
295 global $wgFileExtensions;
297 $verification = $this->mUpload
->verifyUpload( );
298 if ( $verification['status'] === UploadBase
::OK
) {
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' );
308 case UploadBase
::ILLEGAL_FILENAME
:
309 $this->dieRecoverableError( 'illegal-filename', 'filename',
310 array( 'filename' => $verification['filtered'] ) );
312 case UploadBase
::FILETYPE_MISSING
:
313 $this->dieRecoverableError( 'filetype-missing', 'filename' );
315 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
316 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
319 // Unrecoverable errors
320 case UploadBase
::EMPTY_FILE
:
321 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
323 case UploadBase
::FILE_TOO_LARGE
:
324 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
327 case UploadBase
::FILETYPE_BADTYPE
:
328 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
330 'filetype' => $verification['finalExt'],
331 'allowed' => $wgFileExtensions
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'] ) );
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'] ) );
344 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
345 0, array( 'code' => $verification['status'] ) );
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
358 protected function getApiWarnings() {
361 if ( !$this->mParams
['ignorewarnings'] ) {
362 $warnings = $this->mUpload
->checkWarnings();
364 return $this->transformWarnings( $warnings );
367 protected function transformWarnings( $warnings ) {
370 $result = $this->getResult();
371 $result->setIndexedTagName( $warnings, 'warning' );
373 if ( isset( $warnings['duplicate'] ) ) {
375 foreach ( $warnings['duplicate'] as $dupe ) {
376 $dupes[] = $dupe->getName();
378 $result->setIndexedTagName( $dupes, 'duplicate' );
379 $warnings['duplicate'] = $dupes;
382 if ( isset( $warnings['exists'] ) ) {
383 $warning = $warnings['exists'];
384 unset( $warnings['exists'] );
385 $warnings[$warning['warning']] = $warning['file']->getName();
393 * Perform the actual upload. Returns a suitable result array on success;
396 protected function performUpload() {
399 // Use comment as initial page text by default
400 if ( is_null( $this->mParams
['text'] ) ) {
401 $this->mParams
['text'] = $this->mParams
['comment'];
404 $file = $this->mUpload
->getLocalFile();
405 $watch = $this->getWatchlistValue( $this->mParams
['watchlist'], $file->getTitle() );
407 // Deprecated parameters
408 if ( $this->mParams
['watch'] ) {
412 // No errors, no warnings: do the upload
413 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
414 $this->mParams
['text'], $watch, $wgUser );
416 if ( !$status->isGood() ) {
417 $error = $status->getErrorsArray();
419 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
420 // The upload can not be performed right now, because the user
423 'result' => 'Queued',
424 'statuskey' => $error[0][1],
427 $this->getResult()->setIndexedTagName( $error, 'error' );
429 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
433 $file = $this->mUpload
->getLocalFile();
435 $result['result'] = 'Success';
436 $result['filename'] = $file->getName();
442 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
444 protected function checkAsyncDownloadEnabled() {
445 global $wgAllowAsyncCopyUploads;
446 if ( !$wgAllowAsyncCopyUploads ) {
447 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
451 public function mustBePosted() {
455 public function isWriteMode() {
459 public function getAllowedParams() {
462 ApiBase
::PARAM_TYPE
=> 'string',
465 ApiBase
::PARAM_DFLT
=> ''
470 ApiBase
::PARAM_DFLT
=> false,
471 ApiBase
::PARAM_DEPRECATED
=> true,
473 'watchlist' => array(
474 ApiBase
::PARAM_DFLT
=> 'preferences',
475 ApiBase
::PARAM_TYPE
=> array(
481 'ignorewarnings' => false,
485 'sessionkey' => array(
486 ApiBase
::PARAM_DFLT
=> null,
487 ApiBase
::PARAM_DEPRECATED
=> true,
491 'asyncdownload' => false,
492 'leavemessage' => false,
499 public function getParamDescription() {
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.',
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',
523 public function getDescription() {
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'
534 public function getPossibleErrors() {
535 return array_merge( parent
::getPossibleErrors(),
536 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
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' ),
556 public function needsToken() {
560 public function getTokenSalt() {
564 protected function getExamples() {
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',
573 public function getHelpUrls() {
574 return 'http://www.mediawiki.org/wiki/API:Upload';
577 public function getVersion() {
578 return __CLASS__
. ': $Id$';