3 * Created on Aug 21, 2008
4 * API for MediaWiki 1.8+
6 * Copyright © 2008 - 2010 Bryan Tong Minh <Bryan.TongMinh@Gmail.com>
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
24 if ( !defined( 'MEDIAWIKI' ) ) {
25 // Eclipse helper - will be ignored in production
26 require_once( "ApiBase.php" );
32 class ApiUpload
extends ApiBase
{
33 protected $mUpload = null;
36 public function __construct( $main, $action ) {
37 parent
::__construct( $main, $action );
40 public function execute() {
43 // Check whether upload is enabled
44 if ( !UploadBase
::isEnabled() ) {
45 $this->dieUsageMsg( array( 'uploaddisabled' ) );
49 $this->mParams
= $this->extractRequestParams();
50 $request = $this->getMain()->getRequest();
51 // Add the uploaded file to the params array
52 $this->mParams
['file'] = $request->getFileName( 'file' );
54 // Select an upload module
55 $this->selectUploadModule();
56 if ( !isset( $this->mUpload
) ) {
57 $this->dieUsage( 'No upload module set', 'nomodule' );
60 // First check permission to upload
61 $this->checkPermissions( $wgUser );
64 $status = $this->mUpload
->fetchFile();
65 if ( !$status->isGood() ) {
66 $errors = $status->getErrorsArray();
67 $error = array_shift( $errors[0] );
68 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
71 // Check if the uploaded file is sane
72 $this->verifyUpload();
74 // Check permission to upload this file
75 $permErrors = $this->mUpload
->verifyPermissions( $wgUser );
76 if ( $permErrors !== true ) {
77 // Todo: stash the upload and allow choosing a new name
78 $this->dieUsageMsg( array( 'badaccess-groups' ) );
81 // Check warnings if necessary
82 $warnings = $this->checkForWarnings();
84 $this->getResult()->addValue( null, $this->getModuleName(), $warnings );
87 $result = $this->performUpload();
88 $this->getResult()->addValue( null, $this->getModuleName(), $result );
91 // Cleanup any temporary mess
92 $this->mUpload
->cleanupTempFile();
96 * Select an upload module and set it to mUpload. Dies on failure.
98 protected function selectUploadModule() {
99 $request = $this->getMain()->getRequest();
101 // One and only one of the following parameters is needed
102 $this->requireOnlyOneParameter( $this->mParams
,
103 'sessionkey', 'file', 'url' );
105 if ( $this->mParams
['sessionkey'] ) {
106 // Upload stashed in a previous request
107 $sessionData = $request->getSessionData( UploadBase
::getSessionKeyName() );
108 if ( !UploadFromStash
::isValidSessionKey( $this->mParams
['sessionkey'], $sessionData ) ) {
109 $this->dieUsageMsg( array( 'invalid-session-key' ) );
112 $this->mUpload
= new UploadFromStash();
113 $this->mUpload
->initialize( $this->mParams
['filename'],
114 $this->mParams
['sessionkey'],
115 $sessionData[$this->mParams
['sessionkey']] );
118 } elseif ( isset( $this->mParams
['file'] ) ) {
119 $this->mUpload
= new UploadFromFile();
120 $this->mUpload
->initialize(
121 $this->mParams
['filename'],
122 $request->getUpload( 'file' )
124 } elseif ( isset( $this->mParams
['url'] ) ) {
125 // Make sure upload by URL is enabled:
126 if ( !UploadFromUrl
::isEnabled() ) {
127 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
131 if ( $this->mParams
['asyncdownload'] ) {
132 if ( $this->mParams
['leavemessage'] ) {
133 $async = 'async-leavemessage';
138 $this->mUpload
= new UploadFromUrl
;
139 $this->mUpload
->initialize( $this->mParams
['filename'],
140 $this->mParams
['url'], $async );
146 * Checks that the user has permissions to perform this upload.
147 * Dies with usage message on inadequate permissions.
148 * @param $user User The user to check.
150 protected function checkPermissions( $user ) {
151 // Check whether the user has the appropriate permissions to upload anyway
152 $permission = $this->mUpload
->isAllowed( $user );
154 if ( $permission !== true ) {
155 if ( !$user->isLoggedIn() ) {
156 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
158 $this->dieUsageMsg( array( 'badaccess-groups' ) );
164 * Performs file verification, dies on error.
166 protected function verifyUpload( ) {
167 $verification = $this->mUpload
->verifyUpload( );
168 if ( $verification['status'] === UploadBase
::OK
) {
172 // TODO: Move them to ApiBase's message map
173 switch( $verification['status'] ) {
174 case UploadBase
::EMPTY_FILE
:
175 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
177 case UploadBase
::FILE_TOO_LARGE
:
178 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
180 case UploadBase
::FILETYPE_MISSING
:
181 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
183 case UploadBase
::FILETYPE_BADTYPE
:
184 global $wgFileExtensions;
185 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
187 'filetype' => $verification['finalExt'],
188 'allowed' => $wgFileExtensions
191 case UploadBase
::MIN_LENGTH_PARTNAME
:
192 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
194 case UploadBase
::ILLEGAL_FILENAME
:
195 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
196 0, array( 'filename' => $verification['filtered'] ) );
198 case UploadBase
::VERIFICATION_ERROR
:
199 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
200 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
201 0, array( 'details' => $verification['details'] ) );
203 case UploadBase
::HOOK_ABORTED
:
204 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
205 'hookaborted', 0, array( 'error' => $verification['error'] ) );
208 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
209 0, array( 'code' => $verification['status'] ) );
215 * Check warnings if ignorewarnings is not set.
216 * Returns a suitable result array if there were warnings
218 protected function checkForWarnings() {
221 if ( !$this->mParams
['ignorewarnings'] ) {
222 $warnings = $this->mUpload
->checkWarnings();
225 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
227 if ( isset( $warnings['duplicate'] ) ) {
229 foreach ( $warnings['duplicate'] as $key => $dupe )
230 $dupes[] = $dupe->getName();
231 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
232 $warnings['duplicate'] = $dupes;
235 if ( isset( $warnings['exists'] ) ) {
236 $warning = $warnings['exists'];
237 unset( $warnings['exists'] );
238 $warnings[$warning['warning']] = $warning['file']->getName();
241 $result['result'] = 'Warning';
242 $result['warnings'] = $warnings;
244 $sessionKey = $this->mUpload
->stashSession();
245 if ( !$sessionKey ) {
246 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
249 $result['sessionkey'] = $sessionKey;
258 * Perform the actual upload. Returns a suitable result array on success;
261 protected function performUpload() {
264 // Use comment as initial page text by default
265 if ( is_null( $this->mParams
['text'] ) ) {
266 $this->mParams
['text'] = $this->mParams
['comment'];
269 $file = $this->mUpload
->getLocalFile();
270 $watch = $this->getWatchlistValue( $this->mParams
['watchlist'], $file->getTitle() );
272 // Deprecated parameters
273 if ( $this->mParams
['watch'] ) {
277 // No errors, no warnings: do the upload
278 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
279 $this->mParams
['text'], $watch, $wgUser );
281 if ( !$status->isGood() ) {
282 $error = $status->getErrorsArray();
284 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
285 // The upload can not be performed right now, because the user
288 'result' => 'Queued',
289 'sessionkey' => $error[0][1],
292 $this->getResult()->setIndexedTagName( $error, 'error' );
294 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
298 $file = $this->mUpload
->getLocalFile();
300 $result['result'] = 'Success';
301 $result['filename'] = $file->getName();
302 $result['imageinfo'] = $this->mUpload
->getImageInfo( $this->getResult() );
307 public function mustBePosted() {
311 public function isWriteMode() {
315 public function getAllowedParams() {
318 ApiBase
::PARAM_TYPE
=> 'string',
319 ApiBase
::PARAM_REQUIRED
=> true
322 ApiBase
::PARAM_DFLT
=> ''
327 ApiBase
::PARAM_DFLT
=> false,
328 ApiBase
::PARAM_DEPRECATED
=> true,
330 'watchlist' => array(
331 ApiBase
::PARAM_DFLT
=> 'preferences',
332 ApiBase
::PARAM_TYPE
=> array(
338 'ignorewarnings' => false,
342 'sessionkey' => null,
345 global $wgAllowAsyncCopyUploads;
346 if ( $wgAllowAsyncCopyUploads ) {
348 'asyncdownload' => false,
349 'leavemessage' => false,
355 public function getParamDescription() {
357 'filename' => 'Target filename',
358 'token' => 'Edit token. You can get one of these through prop=info',
359 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
360 'text' => 'Initial page text for new files',
361 'watch' => 'Watch the page',
362 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
363 'ignorewarnings' => 'Ignore any warnings',
364 'file' => 'File contents',
365 'url' => 'Url to fetch the file from',
366 'sessionkey' => 'Session key returned by a previous upload that failed due to warnings',
369 global $wgAllowAsyncCopyUploads;
370 if ( $wgAllowAsyncCopyUploads ) {
372 'asyncdownload' => 'Make fetching a URL asynchronous',
373 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
381 public function getDescription() {
383 'Upload a file, or get the status of pending uploads. Several methods are available:',
384 ' * Upload file contents directly, using the "file" parameter',
385 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
386 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
387 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
388 'sending the "file". Note also that queries using session keys must be',
389 'done in the same login session as the query that originally returned the key (i.e. do not',
390 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
394 public function getPossibleErrors() {
395 return array_merge( parent
::getPossibleErrors(), array(
396 array( 'uploaddisabled' ),
397 array( 'invalid-session-key' ),
398 array( 'uploaddisabled' ),
399 array( 'badaccess-groups' ),
400 array( 'missingparam', 'filename' ),
401 array( 'mustbeloggedin', 'upload' ),
402 array( 'badaccess-groups' ),
403 array( 'badaccess-groups' ),
404 array( 'code' => 'fetchfileerror', 'info' => '' ),
405 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
406 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
407 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
408 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
409 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
410 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
411 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
415 public function getTokenSalt() {
419 protected function getExamples() {
421 'Upload from a URL:',
422 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
423 'Complete an upload that failed due to warnings:',
424 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
428 public function getVersion() {
429 return __CLASS__
. ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';