77a291fdc71b292425d556c4c653c0f5470ce746
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
{
36 protected $mUpload = null;
39 public function __construct( $main, $action ) {
40 parent
::__construct( $main, $action );
43 public function execute() {
46 // Check whether upload is enabled
47 if ( !UploadBase
::isEnabled() ) {
48 $this->dieUsageMsg( array( 'uploaddisabled' ) );
52 $this->mParams
= $this->extractRequestParams();
53 $request = $this->getMain()->getRequest();
54 // Add the uploaded file to the params array
55 $this->mParams
['file'] = $request->getFileName( 'file' );
57 // Select an upload module
58 if ( !$this->selectUploadModule() ) {
59 // This is not a true upload, but a status request or similar
62 if ( !isset( $this->mUpload
) ) {
63 $this->dieUsage( 'No upload module set', 'nomodule' );
66 // First check permission to upload
67 $this->checkPermissions( $wgUser );
70 $status = $this->mUpload
->fetchFile();
71 if ( !$status->isGood() ) {
72 $errors = $status->getErrorsArray();
73 $error = array_shift( $errors[0] );
74 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
77 // Check if the uploaded file is sane
78 $this->verifyUpload();
80 // Check permission to upload this file
81 $permErrors = $this->mUpload
->verifyPermissions( $wgUser );
82 if ( $permErrors !== true ) {
83 // TODO: stash the upload and allow choosing a new name
84 $this->dieUsageMsg( array( 'badaccess-groups' ) );
87 // Prepare the API result
90 $warnings = $this->getApiWarnings();
92 $result['result'] = 'Warning';
93 $result['warnings'] = $warnings;
94 // in case the warnings can be fixed with some further user action, let's stash this upload
95 // and return a key they can use to restart it
97 $result['sessionkey'] = $this->performStash();
98 } catch ( MWException
$e ) {
99 $result['warnings']['stashfailed'] = $e->getMessage();
101 } elseif ( $this->mParams
['stash'] ) {
102 // Some uploads can request they be stashed, so as not to publish them immediately.
103 // In this case, a failure to stash ought to be fatal
105 $result['result'] = 'Success';
106 $result['sessionkey'] = $this->performStash();
107 } catch ( MWException
$e ) {
108 $this->dieUsage( $e->getMessage(), 'stashfailed' );
111 // This is the most common case -- a normal upload with no warnings
112 // $result will be formatted properly for the API already, with a status
113 $result = $this->performUpload();
116 if ( $result['result'] === 'Success' ) {
117 $result['imageinfo'] = $this->mUpload
->getImageInfo( $this->getResult() );
120 $this->getResult()->addValue( null, $this->getModuleName(), $result );
122 // Cleanup any temporary mess
123 $this->mUpload
->cleanupTempFile();
127 * Stash the file and return the session key
128 * Also re-raises exceptions with slightly more informative message strings (useful for API)
129 * @throws MWException
130 * @return {String} session key
132 function performStash() {
134 $sessionKey = $this->mUpload
->stashSessionFile()->getSessionKey();
135 } catch ( MWException
$e ) {
136 throw new MWException( 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage() );
143 * Select an upload module and set it to mUpload. Dies on failure. If the
144 * request was a status request and not a true upload, returns false;
149 protected function selectUploadModule() {
150 $request = $this->getMain()->getRequest();
152 // One and only one of the following parameters is needed
153 $this->requireOnlyOneParameter( $this->mParams
,
154 'sessionkey', 'file', 'url', 'statuskey' );
156 if ( $this->mParams
['statuskey'] ) {
157 $this->checkAsyncDownloadEnabled();
159 // Status request for an async upload
160 $sessionData = UploadFromUrlJob
::getSessionData( $this->mParams
['statuskey'] );
161 if ( !isset( $sessionData['result'] ) ) {
162 $this->dieUsage( 'No result in session data', 'missingresult' );
164 if ( $sessionData['result'] == 'Warning' ) {
165 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
166 $sessionData['sessionkey'] = $this->mParams
['statuskey'];
168 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
173 // The following modules all require the filename parameter to be set
174 if ( is_null( $this->mParams
['filename'] ) ) {
175 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
178 if ( $this->mParams
['sessionkey'] ) {
179 // Upload stashed in a previous request
180 $sessionData = $request->getSessionData( UploadBase
::getSessionKeyName() );
181 if ( !UploadFromStash
::isValidSessionKey( $this->mParams
['sessionkey'], $sessionData ) ) {
182 $this->dieUsageMsg( array( 'invalid-session-key' ) );
185 $this->mUpload
= new UploadFromStash();
186 $this->mUpload
->initialize( $this->mParams
['filename'],
187 $this->mParams
['sessionkey'],
188 $sessionData[$this->mParams
['sessionkey']] );
190 } elseif ( isset( $this->mParams
['file'] ) ) {
191 $this->mUpload
= new UploadFromFile();
192 $this->mUpload
->initialize(
193 $this->mParams
['filename'],
194 $request->getUpload( 'file' )
196 } elseif ( isset( $this->mParams
['url'] ) ) {
197 // Make sure upload by URL is enabled:
198 if ( !UploadFromUrl
::isEnabled() ) {
199 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
203 if ( $this->mParams
['asyncdownload'] ) {
204 $this->checkAsyncDownloadEnabled();
206 if ( $this->mParams
['leavemessage'] && !$this->mParams
['ignorewarnings'] ) {
207 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
208 'missing-ignorewarnings' );
211 if ( $this->mParams
['leavemessage'] ) {
212 $async = 'async-leavemessage';
217 $this->mUpload
= new UploadFromUrl
;
218 $this->mUpload
->initialize( $this->mParams
['filename'],
219 $this->mParams
['url'], $async );
227 * Checks that the user has permissions to perform this upload.
228 * Dies with usage message on inadequate permissions.
229 * @param $user User The user to check.
231 protected function checkPermissions( $user ) {
232 // Check whether the user has the appropriate permissions to upload anyway
233 $permission = $this->mUpload
->isAllowed( $user );
235 if ( $permission !== true ) {
236 if ( !$user->isLoggedIn() ) {
237 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
239 $this->dieUsageMsg( array( 'badaccess-groups' ) );
245 * Performs file verification, dies on error.
247 protected function verifyUpload( ) {
248 global $wgFileExtensions;
250 $verification = $this->mUpload
->verifyUpload( );
251 if ( $verification['status'] === UploadBase
::OK
) {
255 // TODO: Move them to ApiBase's message map
256 switch( $verification['status'] ) {
257 case UploadBase
::EMPTY_FILE
:
258 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
260 case UploadBase
::FILE_TOO_LARGE
:
261 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
263 case UploadBase
::FILETYPE_MISSING
:
264 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
266 case UploadBase
::FILETYPE_BADTYPE
:
267 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
269 'filetype' => $verification['finalExt'],
270 'allowed' => $wgFileExtensions
273 case UploadBase
::MIN_LENGTH_PARTNAME
:
274 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
276 case UploadBase
::ILLEGAL_FILENAME
:
277 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
278 0, array( 'filename' => $verification['filtered'] ) );
280 case UploadBase
::VERIFICATION_ERROR
:
281 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
282 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
283 0, array( 'details' => $verification['details'] ) );
285 case UploadBase
::HOOK_ABORTED
:
286 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
287 'hookaborted', 0, array( 'error' => $verification['error'] ) );
290 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
291 0, array( 'code' => $verification['status'] ) );
298 * Check warnings if ignorewarnings is not set.
299 * Returns a suitable array for inclusion into API results if there were warnings
300 * Returns the empty array if there were no warnings
304 protected function getApiWarnings() {
307 if ( !$this->mParams
['ignorewarnings'] ) {
308 $warnings = $this->mUpload
->checkWarnings();
311 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
313 if ( isset( $warnings['duplicate'] ) ) {
315 foreach ( $warnings['duplicate'] as $dupe ) {
316 $dupes[] = $dupe->getName();
318 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
319 $warnings['duplicate'] = $dupes;
322 if ( isset( $warnings['exists'] ) ) {
323 $warning = $warnings['exists'];
324 unset( $warnings['exists'] );
325 $warnings[$warning['warning']] = $warning['file']->getName();
334 * Perform the actual upload. Returns a suitable result array on success;
337 protected function performUpload() {
340 // Use comment as initial page text by default
341 if ( is_null( $this->mParams
['text'] ) ) {
342 $this->mParams
['text'] = $this->mParams
['comment'];
345 $file = $this->mUpload
->getLocalFile();
346 $watch = $this->getWatchlistValue( $this->mParams
['watchlist'], $file->getTitle() );
348 // Deprecated parameters
349 if ( $this->mParams
['watch'] ) {
353 // No errors, no warnings: do the upload
354 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
355 $this->mParams
['text'], $watch, $wgUser );
357 if ( !$status->isGood() ) {
358 $error = $status->getErrorsArray();
360 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
361 // The upload can not be performed right now, because the user
364 'result' => 'Queued',
365 'statuskey' => $error[0][1],
368 $this->getResult()->setIndexedTagName( $error, 'error' );
370 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
374 $file = $this->mUpload
->getLocalFile();
376 $result['result'] = 'Success';
377 $result['filename'] = $file->getName();
384 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
386 protected function checkAsyncDownloadEnabled() {
387 global $wgAllowAsyncCopyUploads;
388 if ( !$wgAllowAsyncCopyUploads ) {
389 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
393 public function mustBePosted() {
397 public function isWriteMode() {
401 public function getAllowedParams() {
404 ApiBase
::PARAM_TYPE
=> 'string',
407 ApiBase
::PARAM_DFLT
=> ''
412 ApiBase
::PARAM_DFLT
=> false,
413 ApiBase
::PARAM_DEPRECATED
=> true,
415 'watchlist' => array(
416 ApiBase
::PARAM_DFLT
=> 'preferences',
417 ApiBase
::PARAM_TYPE
=> array(
423 'ignorewarnings' => false,
426 'sessionkey' => null,
429 'asyncdownload' => false,
430 'leavemessage' => false,
437 public function getParamDescription() {
439 'filename' => 'Target filename',
440 'token' => 'Edit token. You can get one of these through prop=info',
441 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
442 'text' => 'Initial page text for new files',
443 'watch' => 'Watch the page',
444 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
445 'ignorewarnings' => 'Ignore any warnings',
446 'file' => 'File contents',
447 'url' => 'Url to fetch the file from',
448 'sessionkey' => 'Session key that identifies a previous upload that was stashed temporarily.',
449 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
451 'asyncdownload' => 'Make fetching a URL asynchronous',
452 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
453 'statuskey' => 'Fetch the upload status for this session key',
460 public function getDescription() {
462 'Upload a file, or get the status of pending uploads. Several methods are available:',
463 ' * Upload file contents directly, using the "file" parameter',
464 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
465 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
466 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
467 'sending the "file". Note also that queries using session keys must be',
468 'done in the same login session as the query that originally returned the key (i.e. do not',
469 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
473 public function getPossibleErrors() {
474 return array_merge( parent
::getPossibleErrors(), array(
475 array( 'uploaddisabled' ),
476 array( 'invalid-session-key' ),
477 array( 'uploaddisabled' ),
478 array( 'mustbeloggedin', 'upload' ),
479 array( 'badaccess-groups' ),
480 array( 'code' => 'fetchfileerror', 'info' => '' ),
481 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
482 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
483 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
484 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
485 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
486 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
487 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
488 array( 'code' => 'missingparam', 'info' => 'One of the parameters sessionkey, file, url, statuskey is required' ),
489 array( 'code' => 'invalidparammix', 'info' => 'The parameters sessionkey, file, url, statuskey can not be used together' ),
490 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
494 public function needsToken() {
498 public function getTokenSalt() {
502 protected function getExamples() {
504 'Upload from a URL:',
505 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
506 'Complete an upload that failed due to warnings:',
507 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
511 public function getVersion() {
512 return __CLASS__
. ': $Id$';