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( array( '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 // Select an upload module
63 if ( !$this->selectUploadModule() ) {
64 // This is not a true upload, but a status request or similar
67 if ( !isset( $this->mUpload
) ) {
68 $this->dieUsage( 'No upload module set', 'nomodule' );
71 // First check permission to upload
72 $this->checkPermissions( $wgUser );
75 $status = $this->mUpload
->fetchFile();
76 if ( !$status->isGood() ) {
77 $errors = $status->getErrorsArray();
78 $error = array_shift( $errors[0] );
79 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
82 // Check if the uploaded file is sane
83 $this->verifyUpload();
85 // Check permission to upload this file
86 $permErrors = $this->mUpload
->verifyPermissions( $wgUser );
87 if ( $permErrors !== true ) {
88 // TODO: stash the upload and allow choosing a new name
89 $this->dieUsageMsg( array( 'badaccess-groups' ) );
92 // Prepare the API result
95 $warnings = $this->getApiWarnings();
97 $result['result'] = 'Warning';
98 $result['warnings'] = $warnings;
99 // in case the warnings can be fixed with some further user action, let's stash this upload
100 // and return a key they can use to restart it
102 $result['sessionkey'] = $this->performStash();
103 } catch ( MWException
$e ) {
104 $result['warnings']['stashfailed'] = $e->getMessage();
106 } elseif ( $this->mParams
['stash'] ) {
107 // Some uploads can request they be stashed, so as not to publish them immediately.
108 // In this case, a failure to stash ought to be fatal
110 $result['result'] = 'Success';
111 $result['sessionkey'] = $this->performStash();
112 } catch ( MWException
$e ) {
113 $this->dieUsage( $e->getMessage(), 'stashfailed' );
116 // This is the most common case -- a normal upload with no warnings
117 // $result will be formatted properly for the API already, with a status
118 $result = $this->performUpload();
121 if ( $result['result'] === 'Success' ) {
122 $result['imageinfo'] = $this->mUpload
->getImageInfo( $this->getResult() );
125 $this->getResult()->addValue( null, $this->getModuleName(), $result );
127 // Cleanup any temporary mess
128 $this->mUpload
->cleanupTempFile();
132 * Stash the file and return the session key
133 * Also re-raises exceptions with slightly more informative message strings (useful for API)
134 * @throws MWException
135 * @return {String} session key
137 function performStash() {
139 $sessionKey = $this->mUpload
->stashSessionFile()->getSessionKey();
140 } catch ( MWException
$e ) {
141 throw new MWException( 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage() );
147 * Select an upload module and set it to mUpload. Dies on failure. If the
148 * request was a status request and not a true upload, returns false;
153 protected function selectUploadModule() {
154 $request = $this->getMain()->getRequest();
156 // One and only one of the following parameters is needed
157 $this->requireOnlyOneParameter( $this->mParams
,
158 'sessionkey', 'file', 'url', 'statuskey' );
160 if ( $this->mParams
['statuskey'] ) {
161 $this->checkAsyncDownloadEnabled();
163 // Status request for an async upload
164 $sessionData = UploadFromUrlJob
::getSessionData( $this->mParams
['statuskey'] );
165 if ( !isset( $sessionData['result'] ) ) {
166 $this->dieUsage( 'No result in session data', 'missingresult' );
168 if ( $sessionData['result'] == 'Warning' ) {
169 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
170 $sessionData['sessionkey'] = $this->mParams
['statuskey'];
172 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
177 // The following modules all require the filename parameter to be set
178 if ( is_null( $this->mParams
['filename'] ) ) {
179 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
182 if ( $this->mParams
['sessionkey'] ) {
183 // Upload stashed in a previous request
184 $sessionData = $request->getSessionData( UploadBase
::getSessionKeyName() );
185 if ( !UploadFromStash
::isValidSessionKey( $this->mParams
['sessionkey'], $sessionData ) ) {
186 $this->dieUsageMsg( array( 'invalid-session-key' ) );
189 $this->mUpload
= new UploadFromStash();
190 $this->mUpload
->initialize( $this->mParams
['filename'],
191 $this->mParams
['sessionkey'],
192 $sessionData[$this->mParams
['sessionkey']] );
194 } elseif ( isset( $this->mParams
['file'] ) ) {
195 $this->mUpload
= new UploadFromFile();
196 $this->mUpload
->initialize(
197 $this->mParams
['filename'],
198 $request->getUpload( 'file' )
200 } elseif ( isset( $this->mParams
['url'] ) ) {
201 // Make sure upload by URL is enabled:
202 if ( !UploadFromUrl
::isEnabled() ) {
203 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
207 if ( $this->mParams
['asyncdownload'] ) {
208 $this->checkAsyncDownloadEnabled();
210 if ( $this->mParams
['leavemessage'] && !$this->mParams
['ignorewarnings'] ) {
211 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
212 'missing-ignorewarnings' );
215 if ( $this->mParams
['leavemessage'] ) {
216 $async = 'async-leavemessage';
221 $this->mUpload
= new UploadFromUrl
;
222 $this->mUpload
->initialize( $this->mParams
['filename'],
223 $this->mParams
['url'], $async );
231 * Checks that the user has permissions to perform this upload.
232 * Dies with usage message on inadequate permissions.
233 * @param $user User The user to check.
235 protected function checkPermissions( $user ) {
236 // Check whether the user has the appropriate permissions to upload anyway
237 $permission = $this->mUpload
->isAllowed( $user );
239 if ( $permission !== true ) {
240 if ( !$user->isLoggedIn() ) {
241 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
243 $this->dieUsageMsg( array( 'badaccess-groups' ) );
249 * Performs file verification, dies on error.
251 protected function verifyUpload( ) {
252 global $wgFileExtensions;
254 $verification = $this->mUpload
->verifyUpload( );
255 if ( $verification['status'] === UploadBase
::OK
) {
259 // TODO: Move them to ApiBase's message map
260 switch( $verification['status'] ) {
261 case UploadBase
::EMPTY_FILE
:
262 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
264 case UploadBase
::FILE_TOO_LARGE
:
265 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
267 case UploadBase
::FILETYPE_MISSING
:
268 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
270 case UploadBase
::FILETYPE_BADTYPE
:
271 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
273 'filetype' => $verification['finalExt'],
274 'allowed' => $wgFileExtensions
277 case UploadBase
::MIN_LENGTH_PARTNAME
:
278 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
280 case UploadBase
::ILLEGAL_FILENAME
:
281 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
282 0, array( 'filename' => $verification['filtered'] ) );
284 case UploadBase
::VERIFICATION_ERROR
:
285 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
286 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
287 0, array( 'details' => $verification['details'] ) );
289 case UploadBase
::HOOK_ABORTED
:
290 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
291 'hookaborted', 0, array( 'error' => $verification['error'] ) );
294 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
295 0, array( 'code' => $verification['status'] ) );
302 * Check warnings if ignorewarnings is not set.
303 * Returns a suitable array for inclusion into API results if there were warnings
304 * Returns the empty array if there were no warnings
308 protected function getApiWarnings() {
311 if ( !$this->mParams
['ignorewarnings'] ) {
312 $warnings = $this->mUpload
->checkWarnings();
315 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
317 if ( isset( $warnings['duplicate'] ) ) {
319 foreach ( $warnings['duplicate'] as $dupe ) {
320 $dupes[] = $dupe->getName();
322 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
323 $warnings['duplicate'] = $dupes;
326 if ( isset( $warnings['exists'] ) ) {
327 $warning = $warnings['exists'];
328 unset( $warnings['exists'] );
329 $warnings[$warning['warning']] = $warning['file']->getName();
338 * Perform the actual upload. Returns a suitable result array on success;
341 protected function performUpload() {
344 // Use comment as initial page text by default
345 if ( is_null( $this->mParams
['text'] ) ) {
346 $this->mParams
['text'] = $this->mParams
['comment'];
349 $file = $this->mUpload
->getLocalFile();
350 $watch = $this->getWatchlistValue( $this->mParams
['watchlist'], $file->getTitle() );
352 // Deprecated parameters
353 if ( $this->mParams
['watch'] ) {
357 // No errors, no warnings: do the upload
358 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
359 $this->mParams
['text'], $watch, $wgUser );
361 if ( !$status->isGood() ) {
362 $error = $status->getErrorsArray();
364 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
365 // The upload can not be performed right now, because the user
368 'result' => 'Queued',
369 'statuskey' => $error[0][1],
372 $this->getResult()->setIndexedTagName( $error, 'error' );
374 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
378 $file = $this->mUpload
->getLocalFile();
380 $result['result'] = 'Success';
381 $result['filename'] = $file->getName();
387 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
389 protected function checkAsyncDownloadEnabled() {
390 global $wgAllowAsyncCopyUploads;
391 if ( !$wgAllowAsyncCopyUploads ) {
392 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
396 public function mustBePosted() {
400 public function isWriteMode() {
404 public function getAllowedParams() {
407 ApiBase
::PARAM_TYPE
=> 'string',
410 ApiBase
::PARAM_DFLT
=> ''
415 ApiBase
::PARAM_DFLT
=> false,
416 ApiBase
::PARAM_DEPRECATED
=> true,
418 'watchlist' => array(
419 ApiBase
::PARAM_DFLT
=> 'preferences',
420 ApiBase
::PARAM_TYPE
=> array(
426 'ignorewarnings' => false,
429 'sessionkey' => null,
432 'asyncdownload' => false,
433 'leavemessage' => false,
440 public function getParamDescription() {
442 'filename' => 'Target filename',
443 'token' => 'Edit token. You can get one of these through prop=info',
444 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
445 'text' => 'Initial page text for new files',
446 'watch' => 'Watch the page',
447 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
448 'ignorewarnings' => 'Ignore any warnings',
449 'file' => 'File contents',
450 'url' => 'Url to fetch the file from',
451 'sessionkey' => 'Session key that identifies a previous upload that was stashed temporarily.',
452 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
454 'asyncdownload' => 'Make fetching a URL asynchronous',
455 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
456 'statuskey' => 'Fetch the upload status for this session key',
463 public function getDescription() {
465 'Upload a file, or get the status of pending uploads. Several methods are available:',
466 ' * Upload file contents directly, using the "file" parameter',
467 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
468 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
469 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
470 'sending the "file". Note also that queries using session keys must be',
471 'done in the same login session as the query that originally returned the key (i.e. do not',
472 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
476 public function getPossibleErrors() {
477 return array_merge( parent
::getPossibleErrors(),
478 $this->getRequireOnlyOneParameterErrorMessages( array( 'sessionkey', 'file', 'url', 'statuskey' ) ),
480 array( 'uploaddisabled' ),
481 array( 'invalid-session-key' ),
482 array( 'uploaddisabled' ),
483 array( 'mustbeloggedin', 'upload' ),
484 array( 'badaccess-groups' ),
485 array( 'code' => 'fetchfileerror', 'info' => '' ),
486 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
487 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
488 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
489 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
490 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
491 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
492 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
493 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
498 public function needsToken() {
502 public function getTokenSalt() {
506 protected function getExamples() {
508 'Upload from a URL:',
509 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
510 'Complete an upload that failed due to warnings:',
511 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
515 public function getVersion() {
516 return __CLASS__
. ': $Id$';