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' );
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( $wgUser );
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( $wgUser );
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->getFileSize( 'chunk' );
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'] = 'Done';
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 $fileKey = $this->mUpload
->stashFile()->getFileKey();
179 } catch ( MWException
$e ) {
180 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
181 wfDebug( __METHOD__
. ' ' . $message . "\n");
182 throw new MWException( $message );
188 * Throw an error that the user can recover from by providing a better
189 * value for $parameter
191 * @param $error array Error array suitable for passing to dieUsageMsg()
192 * @param $parameter string Parameter that needs revising
193 * @param $data array Optional extra data to pass to the user
194 * @throws UsageException
196 function dieRecoverableError( $error, $parameter, $data = array() ) {
198 $data['filekey'] = $this->performStash();
199 $data['sessionkey'] = $data['filekey'];
200 } catch ( MWException
$e ) {
201 $data['stashfailed'] = $e->getMessage();
203 $data['invalidparameter'] = $parameter;
205 $parsed = $this->parseMsg( $error );
206 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
210 * Select an upload module and set it to mUpload. Dies on failure. If the
211 * request was a status request and not a true upload, returns false;
216 protected function selectUploadModule() {
217 $request = $this->getMain()->getRequest();
219 // chunk or one and only one of the following parameters is needed
220 if(!$this->mParams
['chunk'])
221 $this->requireOnlyOneParameter( $this->mParams
,
222 'filekey', 'file', 'url', 'statuskey' );
224 if ( $this->mParams
['statuskey'] ) {
225 $this->checkAsyncDownloadEnabled();
227 // Status request for an async upload
228 $sessionData = UploadFromUrlJob
::getSessionData( $this->mParams
['statuskey'] );
229 if ( !isset( $sessionData['result'] ) ) {
230 $this->dieUsage( 'No result in session data', 'missingresult' );
232 if ( $sessionData['result'] == 'Warning' ) {
233 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
234 $sessionData['sessionkey'] = $this->mParams
['statuskey'];
236 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
241 // The following modules all require the filename parameter to be set
242 if ( is_null( $this->mParams
['filename'] ) ) {
243 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
246 if ( $this->mParams
['filekey'] ) {
247 // Upload stashed in a previous request
248 if ( !UploadFromStash
::isValidKey( $this->mParams
['filekey'] ) ) {
249 $this->dieUsageMsg( 'invalid-file-key' );
252 if( class_exists( 'RequestContext' ) ) {
253 // context allows access to the current user without creating new $wgUser references
254 $context = $this->createContext();
255 $this->mUpload
= new UploadFromStash( $context->getUser() );
257 // this is here to maintain 1.17 compatibility, so these changes can
258 // be merged into production
259 // remove this after we've moved to 1.18
261 $this->mUpload
= new UploadFromStash( $wgUser );
264 $this->mUpload
->initialize( $this->mParams
['filekey'], $this->mParams
['filename'] );
266 } elseif ( isset( $this->mParams
['chunk'] ) ) {
267 // Start new Chunk upload
268 $this->mUpload
= new UploadFromFile();
269 $this->mUpload
->initialize(
270 $this->mParams
['filename'],
271 $request->getUpload( 'chunk' )
273 } elseif ( isset( $this->mParams
['file'] ) ) {
274 $this->mUpload
= new UploadFromFile();
275 $this->mUpload
->initialize(
276 $this->mParams
['filename'],
277 $request->getUpload( 'file' )
279 } elseif ( isset( $this->mParams
['url'] ) ) {
280 // Make sure upload by URL is enabled:
281 if ( !UploadFromUrl
::isEnabled() ) {
282 $this->dieUsageMsg( 'copyuploaddisabled' );
286 if ( $this->mParams
['asyncdownload'] ) {
287 $this->checkAsyncDownloadEnabled();
289 if ( $this->mParams
['leavemessage'] && !$this->mParams
['ignorewarnings'] ) {
290 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
291 'missing-ignorewarnings' );
294 if ( $this->mParams
['leavemessage'] ) {
295 $async = 'async-leavemessage';
300 $this->mUpload
= new UploadFromUrl
;
301 $this->mUpload
->initialize( $this->mParams
['filename'],
302 $this->mParams
['url'], $async );
310 * Checks that the user has permissions to perform this upload.
311 * Dies with usage message on inadequate permissions.
312 * @param $user User The user to check.
314 protected function checkPermissions( $user ) {
315 // Check whether the user has the appropriate permissions to upload anyway
316 $permission = $this->mUpload
->isAllowed( $user );
318 if ( $permission !== true ) {
319 if ( !$user->isLoggedIn() ) {
320 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
322 $this->dieUsageMsg( 'badaccess-groups' );
328 * Performs file verification, dies on error.
330 protected function verifyUpload( ) {
331 global $wgFileExtensions;
333 $verification = $this->mUpload
->verifyUpload( );
334 if ( $verification['status'] === UploadBase
::OK
) {
338 // TODO: Move them to ApiBase's message map
339 switch( $verification['status'] ) {
340 // Recoverable errors
341 case UploadBase
::MIN_LENGTH_PARTNAME
:
342 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
344 case UploadBase
::ILLEGAL_FILENAME
:
345 $this->dieRecoverableError( 'illegal-filename', 'filename',
346 array( 'filename' => $verification['filtered'] ) );
348 case UploadBase
::FILETYPE_MISSING
:
349 $this->dieRecoverableError( 'filetype-missing', 'filename' );
351 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
352 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
355 // Unrecoverable errors
356 case UploadBase
::EMPTY_FILE
:
357 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
359 case UploadBase
::FILE_TOO_LARGE
:
360 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
363 case UploadBase
::FILETYPE_BADTYPE
:
364 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
366 'filetype' => $verification['finalExt'],
367 'allowed' => $wgFileExtensions
370 case UploadBase
::VERIFICATION_ERROR
:
371 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
372 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
373 0, array( 'details' => $verification['details'] ) );
375 case UploadBase
::HOOK_ABORTED
:
376 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
377 'hookaborted', 0, array( 'error' => $verification['error'] ) );
380 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
381 0, array( 'code' => $verification['status'] ) );
388 * Check warnings if ignorewarnings is not set.
389 * Returns a suitable array for inclusion into API results if there were warnings
390 * Returns the empty array if there were no warnings
394 protected function getApiWarnings() {
397 if ( !$this->mParams
['ignorewarnings'] ) {
398 $warnings = $this->mUpload
->checkWarnings();
400 return $this->transformWarnings( $warnings );
403 protected function transformWarnings( $warnings ) {
406 $result = $this->getResult();
407 $result->setIndexedTagName( $warnings, 'warning' );
409 if ( isset( $warnings['duplicate'] ) ) {
411 foreach ( $warnings['duplicate'] as $dupe ) {
412 $dupes[] = $dupe->getName();
414 $result->setIndexedTagName( $dupes, 'duplicate' );
415 $warnings['duplicate'] = $dupes;
418 if ( isset( $warnings['exists'] ) ) {
419 $warning = $warnings['exists'];
420 unset( $warnings['exists'] );
421 $warnings[$warning['warning']] = $warning['file']->getName();
429 * Perform the actual upload. Returns a suitable result array on success;
432 protected function performUpload() {
435 // Use comment as initial page text by default
436 if ( is_null( $this->mParams
['text'] ) ) {
437 $this->mParams
['text'] = $this->mParams
['comment'];
440 $file = $this->mUpload
->getLocalFile();
441 $watch = $this->getWatchlistValue( $this->mParams
['watchlist'], $file->getTitle() );
443 // Deprecated parameters
444 if ( $this->mParams
['watch'] ) {
448 // No errors, no warnings: do the upload
449 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
450 $this->mParams
['text'], $watch, $wgUser );
452 if ( !$status->isGood() ) {
453 $error = $status->getErrorsArray();
455 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
456 // The upload can not be performed right now, because the user
459 'result' => 'Queued',
460 'statuskey' => $error[0][1],
463 $this->getResult()->setIndexedTagName( $error, 'error' );
465 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
469 $file = $this->mUpload
->getLocalFile();
471 $result['result'] = 'Success';
472 $result['filename'] = $file->getName();
478 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
480 protected function checkAsyncDownloadEnabled() {
481 global $wgAllowAsyncCopyUploads;
482 if ( !$wgAllowAsyncCopyUploads ) {
483 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
487 public function mustBePosted() {
491 public function isWriteMode() {
495 public function getAllowedParams() {
498 ApiBase
::PARAM_TYPE
=> 'string',
501 ApiBase
::PARAM_DFLT
=> ''
506 ApiBase
::PARAM_DFLT
=> false,
507 ApiBase
::PARAM_DEPRECATED
=> true,
509 'watchlist' => array(
510 ApiBase
::PARAM_DFLT
=> 'preferences',
511 ApiBase
::PARAM_TYPE
=> array(
517 'ignorewarnings' => false,
521 'sessionkey' => array(
522 ApiBase
::PARAM_DFLT
=> null,
523 ApiBase
::PARAM_DEPRECATED
=> true,
531 'asyncdownload' => false,
532 'leavemessage' => false,
539 public function getParamDescription() {
541 'filename' => 'Target filename',
542 'token' => 'Edit token. You can get one of these through prop=info',
543 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
544 'text' => 'Initial page text for new files',
545 'watch' => 'Watch the page',
546 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
547 'ignorewarnings' => 'Ignore any warnings',
548 'file' => 'File contents',
549 'url' => 'Url to fetch the file from',
550 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
551 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
552 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
554 'chunk' => 'Chunk contents',
555 'offset' => 'Offset of chunk in bytes',
556 'filesize' => 'Filesize of entire upload',
558 'asyncdownload' => 'Make fetching a URL asynchronous',
559 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
560 'statuskey' => 'Fetch the upload status for this file key',
567 public function getDescription() {
569 'Upload a file, or get the status of pending uploads. Several methods are available:',
570 ' * Upload file contents directly, using the "file" parameter',
571 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
572 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
573 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
574 'sending the "file". Also you must get and send an edit token before doing any upload stuff'
578 public function getPossibleErrors() {
579 return array_merge( parent
::getPossibleErrors(),
580 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
582 array( 'uploaddisabled' ),
583 array( 'invalid-file-key' ),
584 array( 'uploaddisabled' ),
585 array( 'mustbeloggedin', 'upload' ),
586 array( 'badaccess-groups' ),
587 array( 'code' => 'fetchfileerror', 'info' => '' ),
588 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
589 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
590 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
591 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
592 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
593 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
594 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
595 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
600 public function needsToken() {
604 public function getTokenSalt() {
608 protected function getExamples() {
610 'Upload from a URL:',
611 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
612 'Complete an upload that failed due to warnings:',
613 ' api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1',
617 public function getHelpUrls() {
618 return 'http://www.mediawiki.org/wiki/API:Upload';
621 public function getVersion() {
622 return __CLASS__
. ': $Id$';