3 * API for MediaWiki 1.8+
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 // Check warnings if necessary
88 $warnings = $this->checkForWarnings();
90 $this->getResult()->addValue( null, $this->getModuleName(), $warnings );
93 $result = $this->performUpload();
94 $this->getResult()->addValue( null, $this->getModuleName(), $result );
97 // Cleanup any temporary mess
98 $this->mUpload
->cleanupTempFile();
102 * Select an upload module and set it to mUpload. Dies on failure. If the
103 * request was a status request and not a true upload, returns false;
108 protected function selectUploadModule() {
109 $request = $this->getMain()->getRequest();
111 // One and only one of the following parameters is needed
112 $this->requireOnlyOneParameter( $this->mParams
,
113 'sessionkey', 'file', 'url', 'statuskey' );
115 if ( $this->mParams
['statuskey'] ) {
116 // Status request for an async upload
117 $sessionData = UploadFromUrlJob
::getSessionData( $this->mParams
['statuskey'] );
118 if ( !isset( $sessionData['result'] ) ) {
121 if ( $sessionData['result'] == 'Warning' ) {
122 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
123 $sessionData['sessionkey'] = $this->mParams
['statuskey'];
125 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
130 // The following modules all require the filename parameter to be set
131 if ( is_null( $this->mParams
['filename'] ) ) {
132 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
135 if ( $this->mParams
['sessionkey'] ) {
136 // Upload stashed in a previous request
137 $sessionData = $request->getSessionData( UploadBase
::getSessionKeyName() );
138 if ( !UploadFromStash
::isValidSessionKey( $this->mParams
['sessionkey'], $sessionData ) ) {
139 $this->dieUsageMsg( array( 'invalid-session-key' ) );
142 $this->mUpload
= new UploadFromStash();
143 $this->mUpload
->initialize( $this->mParams
['filename'],
144 $this->mParams
['sessionkey'],
145 $sessionData[$this->mParams
['sessionkey']] );
148 } elseif ( isset( $this->mParams
['file'] ) ) {
149 $this->mUpload
= new UploadFromFile();
150 $this->mUpload
->initialize(
151 $this->mParams
['filename'],
152 $request->getUpload( 'file' )
154 } elseif ( isset( $this->mParams
['url'] ) ) {
155 // Make sure upload by URL is enabled:
156 if ( !UploadFromUrl
::isEnabled() ) {
157 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
161 if ( $this->mParams
['asyncdownload'] ) {
162 if ( $this->mParams
['leavemessage'] && !$this->mParams
['ignorewarnings'] ) {
163 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
164 'missing-ignorewarnings' );
167 if ( $this->mParams
['leavemessage'] ) {
168 $async = 'async-leavemessage';
173 $this->mUpload
= new UploadFromUrl
;
174 $this->mUpload
->initialize( $this->mParams
['filename'],
175 $this->mParams
['url'], $async );
183 * Checks that the user has permissions to perform this upload.
184 * Dies with usage message on inadequate permissions.
185 * @param $user User The user to check.
187 protected function checkPermissions( $user ) {
188 // Check whether the user has the appropriate permissions to upload anyway
189 $permission = $this->mUpload
->isAllowed( $user );
191 if ( $permission !== true ) {
192 if ( !$user->isLoggedIn() ) {
193 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
195 $this->dieUsageMsg( array( 'badaccess-groups' ) );
201 * Performs file verification, dies on error.
203 protected function verifyUpload( ) {
204 global $wgFileExtensions;
206 $verification = $this->mUpload
->verifyUpload( );
207 if ( $verification['status'] === UploadBase
::OK
) {
211 // TODO: Move them to ApiBase's message map
212 switch( $verification['status'] ) {
213 case UploadBase
::EMPTY_FILE
:
214 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
216 case UploadBase
::FILE_TOO_LARGE
:
217 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
219 case UploadBase
::FILETYPE_MISSING
:
220 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
222 case UploadBase
::FILETYPE_BADTYPE
:
223 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
225 'filetype' => $verification['finalExt'],
226 'allowed' => $wgFileExtensions
229 case UploadBase
::MIN_LENGTH_PARTNAME
:
230 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
232 case UploadBase
::ILLEGAL_FILENAME
:
233 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
234 0, array( 'filename' => $verification['filtered'] ) );
236 case UploadBase
::VERIFICATION_ERROR
:
237 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
238 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
239 0, array( 'details' => $verification['details'] ) );
241 case UploadBase
::HOOK_ABORTED
:
242 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
243 'hookaborted', 0, array( 'error' => $verification['error'] ) );
246 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
247 0, array( 'code' => $verification['status'] ) );
253 * Check warnings if ignorewarnings is not set.
254 * Returns a suitable result array if there were warnings
256 protected function checkForWarnings() {
259 if ( !$this->mParams
['ignorewarnings'] ) {
260 $warnings = $this->mUpload
->checkWarnings();
262 $result['result'] = 'Warning';
263 $result['warnings'] = $this->transformWarnings( $warnings );
265 $sessionKey = $this->mUpload
->stashSession();
266 if ( !$sessionKey ) {
267 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
270 $result['sessionkey'] = $sessionKey;
279 * Transforms a warnings array returned by mUpload->checkWarnings() into
280 * something that can be directly used as API result
282 protected function transformWarnings( $warnings ) {
284 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
286 if ( isset( $warnings['duplicate'] ) ) {
288 foreach ( $warnings['duplicate'] as $key => $dupe ) {
289 $dupes[] = $dupe->getName();
291 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
292 $warnings['duplicate'] = $dupes;
295 if ( isset( $warnings['exists'] ) ) {
296 $warning = $warnings['exists'];
297 unset( $warnings['exists'] );
298 $warnings[$warning['warning']] = $warning['file']->getName();
305 * Perform the actual upload. Returns a suitable result array on success;
308 protected function performUpload() {
311 // Use comment as initial page text by default
312 if ( is_null( $this->mParams
['text'] ) ) {
313 $this->mParams
['text'] = $this->mParams
['comment'];
316 $file = $this->mUpload
->getLocalFile();
317 $watch = $this->getWatchlistValue( $this->mParams
['watchlist'], $file->getTitle() );
319 // Deprecated parameters
320 if ( $this->mParams
['watch'] ) {
324 // No errors, no warnings: do the upload
325 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
326 $this->mParams
['text'], $watch, $wgUser );
328 if ( !$status->isGood() ) {
329 $error = $status->getErrorsArray();
331 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
332 // The upload can not be performed right now, because the user
335 'result' => 'Queued',
336 'statuskey' => $error[0][1],
339 $this->getResult()->setIndexedTagName( $error, 'error' );
341 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
345 $file = $this->mUpload
->getLocalFile();
347 $result['result'] = 'Success';
348 $result['filename'] = $file->getName();
349 $result['imageinfo'] = $this->mUpload
->getImageInfo( $this->getResult() );
354 public function mustBePosted() {
358 public function isWriteMode() {
362 public function getAllowedParams() {
365 ApiBase
::PARAM_TYPE
=> 'string',
368 ApiBase
::PARAM_DFLT
=> ''
373 ApiBase
::PARAM_DFLT
=> false,
374 ApiBase
::PARAM_DEPRECATED
=> true,
376 'watchlist' => array(
377 ApiBase
::PARAM_DFLT
=> 'preferences',
378 ApiBase
::PARAM_TYPE
=> array(
384 'ignorewarnings' => false,
388 'sessionkey' => null,
391 global $wgAllowAsyncCopyUploads;
392 if ( $wgAllowAsyncCopyUploads ) {
394 'asyncdownload' => false,
395 'leavemessage' => false,
402 public function getParamDescription() {
404 'filename' => 'Target filename',
405 'token' => 'Edit token. You can get one of these through prop=info',
406 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
407 'text' => 'Initial page text for new files',
408 'watch' => 'Watch the page',
409 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
410 'ignorewarnings' => 'Ignore any warnings',
411 'file' => 'File contents',
412 'url' => 'Url to fetch the file from',
413 'sessionkey' => 'Session key returned by a previous upload that failed due to warnings',
416 global $wgAllowAsyncCopyUploads;
417 if ( $wgAllowAsyncCopyUploads ) {
419 'asyncdownload' => 'Make fetching a URL asynchronous',
420 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
421 'statuskey' => 'Fetch the upload status for this session key',
429 public function getDescription() {
431 'Upload a file, or get the status of pending uploads. Several methods are available:',
432 ' * Upload file contents directly, using the "file" parameter',
433 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
434 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
435 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
436 'sending the "file". Note also that queries using session keys must be',
437 'done in the same login session as the query that originally returned the key (i.e. do not',
438 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
442 public function getPossibleErrors() {
443 return array_merge( parent
::getPossibleErrors(), array(
444 array( 'uploaddisabled' ),
445 array( 'invalid-session-key' ),
446 array( 'uploaddisabled' ),
447 array( 'badaccess-groups' ),
448 array( 'mustbeloggedin', 'upload' ),
449 array( 'badaccess-groups' ),
450 array( 'badaccess-groups' ),
451 array( 'code' => 'fetchfileerror', 'info' => '' ),
452 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
453 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
454 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
455 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
456 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
457 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
458 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
462 public function getTokenSalt() {
466 protected function getExamples() {
468 'Upload from a URL:',
469 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
470 'Complete an upload that failed due to warnings:',
471 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
475 public function getVersion() {
476 return __CLASS__
. ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';