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() {
49 // Check whether upload is enabled
50 if ( !UploadBase
::isEnabled() ) {
51 $this->dieUsageMsg( 'uploaddisabled' );
54 $user = $this->getUser();
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 $this->mParams
['chunk'] = $request->getFileName( 'chunk' );
63 // Copy the session key to the file key, for backward compatibility.
64 if( !$this->mParams
['filekey'] && $this->mParams
['sessionkey'] ) {
65 $this->mParams
['filekey'] = $this->mParams
['sessionkey'];
68 // Select an upload module
69 if ( !$this->selectUploadModule() ) {
70 // This is not a true upload, but a status request or similar
73 if ( !isset( $this->mUpload
) ) {
74 $this->dieUsage( 'No upload module set', 'nomodule' );
77 // First check permission to upload
78 $this->checkPermissions( $user );
81 $status = $this->mUpload
->fetchFile();
82 if ( !$status->isGood() ) {
83 $errors = $status->getErrorsArray();
84 $error = array_shift( $errors[0] );
85 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
88 // Check if the uploaded file is sane
89 if ( $this->mParams
['chunk'] ) {
90 $maxSize = $this->mUpload
->getMaxUploadSize( );
91 if( $this->mParams
['filesize'] > $maxSize ) {
92 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
95 $this->verifyUpload();
99 // Check if the user has the rights to modify or overwrite the requested title
100 // (This check is irrelevant if stashing is already requested, since the errors
101 // can always be fixed by changing the title)
102 if ( ! $this->mParams
['stash'] ) {
103 $permErrors = $this->mUpload
->verifyTitlePermissions( $user );
104 if ( $permErrors !== true ) {
105 $this->dieRecoverableError( $permErrors[0], 'filename' );
109 // Prepare the API result
112 $warnings = $this->getApiWarnings();
114 $result['result'] = 'Warning';
115 $result['warnings'] = $warnings;
116 // in case the warnings can be fixed with some further user action, let's stash this upload
117 // and return a key they can use to restart it
119 $result['filekey'] = $this->performStash();
120 $result['sessionkey'] = $result['filekey']; // backwards compatibility
121 } catch ( MWException
$e ) {
122 $result['warnings']['stashfailed'] = $e->getMessage();
124 } elseif ( $this->mParams
['chunk'] ) {
125 $result['result'] = 'Continue';
126 $chunk = $request->getFileTempName( 'chunk' );
127 $chunkSize = $request->getUpload( 'chunk' )->getSize();
128 if ($this->mParams
['offset'] == 0) {
129 $result['filekey'] = $this->performStash();
131 $status = $this->mUpload
->appendChunk($chunk, $chunkSize,
132 $this->mParams
['offset']);
133 if ( !$status->isGood() ) {
134 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
136 $result['filekey'] = $this->mParams
['filekey'];
137 if($this->mParams
['offset'] +
$chunkSize == $this->mParams
['filesize']) {
138 $this->mUpload
->finalizeFile();
139 $result['result'] = 'Success';
143 $result['offset'] = $this->mParams
['offset'] +
$chunkSize;
144 } elseif ( $this->mParams
['stash'] ) {
145 // Some uploads can request they be stashed, so as not to publish them immediately.
146 // In this case, a failure to stash ought to be fatal
148 $result['result'] = 'Success';
149 $result['filekey'] = $this->performStash();
150 $result['sessionkey'] = $result['filekey']; // backwards compatibility
151 } catch ( MWException
$e ) {
152 $this->dieUsage( $e->getMessage(), 'stashfailed' );
155 // This is the most common case -- a normal upload with no warnings
156 // $result will be formatted properly for the API already, with a status
157 $result = $this->performUpload();
160 if ( $result['result'] === 'Success' ) {
161 $result['imageinfo'] = $this->mUpload
->getImageInfo( $this->getResult() );
164 $this->getResult()->addValue( null, $this->getModuleName(), $result );
166 // Cleanup any temporary mess
167 $this->mUpload
->cleanupTempFile();
171 * Stash the file and return the file key
172 * Also re-raises exceptions with slightly more informative message strings (useful for API)
173 * @throws MWException
174 * @return String file key
176 function performStash() {
178 $stashFile = $this->mUpload
->stashFile();
181 throw new MWException( 'Invalid stashed file' );
183 $fileKey = $stashFile->getFileKey();
184 } catch ( MWException
$e ) {
185 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
186 wfDebug( __METHOD__
. ' ' . $message . "\n");
187 throw new MWException( $message );
193 * Throw an error that the user can recover from by providing a better
194 * value for $parameter
196 * @param $error array Error array suitable for passing to dieUsageMsg()
197 * @param $parameter string Parameter that needs revising
198 * @param $data array Optional extra data to pass to the user
199 * @throws UsageException
201 function dieRecoverableError( $error, $parameter, $data = array() ) {
203 $data['filekey'] = $this->performStash();
204 $data['sessionkey'] = $data['filekey'];
205 } catch ( MWException
$e ) {
206 $data['stashfailed'] = $e->getMessage();
208 $data['invalidparameter'] = $parameter;
210 $parsed = $this->parseMsg( $error );
211 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
215 * Select an upload module and set it to mUpload. Dies on failure. If the
216 * request was a status request and not a true upload, returns false;
221 protected function selectUploadModule() {
222 $request = $this->getMain()->getRequest();
224 // chunk or one and only one of the following parameters is needed
225 if( !$this->mParams
['chunk'] ) {
226 $this->requireOnlyOneParameter( $this->mParams
,
227 'filekey', 'file', 'url', 'statuskey' );
230 if ( $this->mParams
['statuskey'] ) {
231 $this->checkAsyncDownloadEnabled();
233 // Status request for an async upload
234 $sessionData = UploadFromUrlJob
::getSessionData( $this->mParams
['statuskey'] );
235 if ( !isset( $sessionData['result'] ) ) {
236 $this->dieUsage( 'No result in session data', 'missingresult' );
238 if ( $sessionData['result'] == 'Warning' ) {
239 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
240 $sessionData['sessionkey'] = $this->mParams
['statuskey'];
242 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
247 // The following modules all require the filename parameter to be set
248 if ( is_null( $this->mParams
['filename'] ) ) {
249 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
252 if ( $this->mParams
['filekey'] ) {
253 // Upload stashed in a previous request
254 if ( !UploadFromStash
::isValidKey( $this->mParams
['filekey'] ) ) {
255 $this->dieUsageMsg( 'invalid-file-key' );
258 $this->mUpload
= new UploadFromStash( $this->getUser() );
260 $this->mUpload
->initialize( $this->mParams
['filekey'], $this->mParams
['filename'] );
262 } elseif ( isset( $this->mParams
['chunk'] ) ) {
263 // Start new Chunk upload
264 $this->mUpload
= new UploadFromFile();
265 $this->mUpload
->initialize(
266 $this->mParams
['filename'],
267 $request->getUpload( 'chunk' )
269 } elseif ( isset( $this->mParams
['file'] ) ) {
270 $this->mUpload
= new UploadFromFile();
271 $this->mUpload
->initialize(
272 $this->mParams
['filename'],
273 $request->getUpload( 'file' )
275 } elseif ( isset( $this->mParams
['url'] ) ) {
276 // Make sure upload by URL is enabled:
277 if ( !UploadFromUrl
::isEnabled() ) {
278 $this->dieUsageMsg( 'copyuploaddisabled' );
282 if ( $this->mParams
['asyncdownload'] ) {
283 $this->checkAsyncDownloadEnabled();
285 if ( $this->mParams
['leavemessage'] && !$this->mParams
['ignorewarnings'] ) {
286 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
287 'missing-ignorewarnings' );
290 if ( $this->mParams
['leavemessage'] ) {
291 $async = 'async-leavemessage';
296 $this->mUpload
= new UploadFromUrl
;
297 $this->mUpload
->initialize( $this->mParams
['filename'],
298 $this->mParams
['url'], $async );
306 * Checks that the user has permissions to perform this upload.
307 * Dies with usage message on inadequate permissions.
308 * @param $user User The user to check.
310 protected function checkPermissions( $user ) {
311 // Check whether the user has the appropriate permissions to upload anyway
312 $permission = $this->mUpload
->isAllowed( $user );
314 if ( $permission !== true ) {
315 if ( !$user->isLoggedIn() ) {
316 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
318 $this->dieUsageMsg( 'badaccess-groups' );
324 * Performs file verification, dies on error.
326 protected function verifyUpload( ) {
327 global $wgFileExtensions;
329 $verification = $this->mUpload
->verifyUpload( );
330 if ( $verification['status'] === UploadBase
::OK
) {
334 // TODO: Move them to ApiBase's message map
335 switch( $verification['status'] ) {
336 // Recoverable errors
337 case UploadBase
::MIN_LENGTH_PARTNAME
:
338 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
340 case UploadBase
::ILLEGAL_FILENAME
:
341 $this->dieRecoverableError( 'illegal-filename', 'filename',
342 array( 'filename' => $verification['filtered'] ) );
344 case UploadBase
::FILENAME_TOO_LONG
:
345 $this->dieRecoverableError( 'filename-toolong', 'filename' );
347 case UploadBase
::FILETYPE_MISSING
:
348 $this->dieRecoverableError( 'filetype-missing', 'filename' );
350 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
351 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
354 // Unrecoverable errors
355 case UploadBase
::EMPTY_FILE
:
356 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
358 case UploadBase
::FILE_TOO_LARGE
:
359 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
362 case UploadBase
::FILETYPE_BADTYPE
:
363 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
365 'filetype' => $verification['finalExt'],
366 'allowed' => $wgFileExtensions
369 case UploadBase
::VERIFICATION_ERROR
:
370 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
371 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
372 0, array( 'details' => $verification['details'] ) );
374 case UploadBase
::HOOK_ABORTED
:
375 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
376 'hookaborted', 0, array( 'error' => $verification['error'] ) );
379 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
380 0, array( 'code' => $verification['status'] ) );
387 * Check warnings if ignorewarnings is not set.
388 * Returns a suitable array for inclusion into API results if there were warnings
389 * Returns the empty array if there were no warnings
393 protected function getApiWarnings() {
396 if ( !$this->mParams
['ignorewarnings'] ) {
397 $warnings = $this->mUpload
->checkWarnings();
399 return $this->transformWarnings( $warnings );
402 protected function transformWarnings( $warnings ) {
405 $result = $this->getResult();
406 $result->setIndexedTagName( $warnings, 'warning' );
408 if ( isset( $warnings['duplicate'] ) ) {
410 foreach ( $warnings['duplicate'] as $dupe ) {
411 $dupes[] = $dupe->getName();
413 $result->setIndexedTagName( $dupes, 'duplicate' );
414 $warnings['duplicate'] = $dupes;
417 if ( isset( $warnings['exists'] ) ) {
418 $warning = $warnings['exists'];
419 unset( $warnings['exists'] );
420 $warnings[$warning['warning']] = $warning['file']->getName();
428 * Perform the actual upload. Returns a suitable result array on success;
433 protected function performUpload() {
434 // Use comment as initial page text by default
435 if ( is_null( $this->mParams
['text'] ) ) {
436 $this->mParams
['text'] = $this->mParams
['comment'];
439 $file = $this->mUpload
->getLocalFile();
440 $watch = $this->getWatchlistValue( $this->mParams
['watchlist'], $file->getTitle() );
442 // Deprecated parameters
443 if ( $this->mParams
['watch'] ) {
447 // No errors, no warnings: do the upload
448 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
449 $this->mParams
['text'], $watch, $this->getUser() );
451 if ( !$status->isGood() ) {
452 $error = $status->getErrorsArray();
454 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
455 // The upload can not be performed right now, because the user
458 'result' => 'Queued',
459 'statuskey' => $error[0][1],
462 $this->getResult()->setIndexedTagName( $error, 'error' );
464 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
468 $file = $this->mUpload
->getLocalFile();
470 $result['result'] = 'Success';
471 $result['filename'] = $file->getName();
477 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
479 protected function checkAsyncDownloadEnabled() {
480 global $wgAllowAsyncCopyUploads;
481 if ( !$wgAllowAsyncCopyUploads ) {
482 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
486 public function mustBePosted() {
490 public function isWriteMode() {
494 public function getAllowedParams() {
497 ApiBase
::PARAM_TYPE
=> 'string',
500 ApiBase
::PARAM_DFLT
=> ''
505 ApiBase
::PARAM_DFLT
=> false,
506 ApiBase
::PARAM_DEPRECATED
=> true,
508 'watchlist' => array(
509 ApiBase
::PARAM_DFLT
=> 'preferences',
510 ApiBase
::PARAM_TYPE
=> array(
516 'ignorewarnings' => false,
520 'sessionkey' => array(
521 ApiBase
::PARAM_DFLT
=> null,
522 ApiBase
::PARAM_DEPRECATED
=> true,
530 'asyncdownload' => false,
531 'leavemessage' => false,
538 public function getParamDescription() {
540 'filename' => 'Target filename',
541 'token' => 'Edit token. You can get one of these through prop=info',
542 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
543 'text' => 'Initial page text for new files',
544 'watch' => 'Watch the page',
545 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
546 'ignorewarnings' => 'Ignore any warnings',
547 'file' => 'File contents',
548 'url' => 'Url to fetch the file from',
549 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
550 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
551 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
553 'chunk' => 'Chunk contents',
554 'offset' => 'Offset of chunk in bytes',
555 'filesize' => 'Filesize of entire upload',
557 'asyncdownload' => 'Make fetching a URL asynchronous',
558 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
559 'statuskey' => 'Fetch the upload status for this file key',
566 public function getDescription() {
568 'Upload a file, or get the status of pending uploads. Several methods are available:',
569 ' * Upload file contents directly, using the "file" parameter',
570 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
571 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
572 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
573 'sending the "file". Also you must get and send an edit token before doing any upload stuff'
577 public function getPossibleErrors() {
578 return array_merge( parent
::getPossibleErrors(),
579 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
581 array( 'uploaddisabled' ),
582 array( 'invalid-file-key' ),
583 array( 'uploaddisabled' ),
584 array( 'mustbeloggedin', 'upload' ),
585 array( 'badaccess-groups' ),
586 array( 'code' => 'fetchfileerror', 'info' => '' ),
587 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
588 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
589 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
590 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
591 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
592 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
593 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
594 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
599 public function needsToken() {
603 public function getTokenSalt() {
607 public function getExamples() {
609 'Upload from a URL:',
610 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
611 'Complete an upload that failed due to warnings:',
612 ' api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1',
616 public function getHelpUrls() {
617 return 'http://www.mediawiki.org/wiki/API:Upload';
620 public function getVersion() {
621 return __CLASS__
. ': $Id$';