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() {
41 global $wgUser, $wgAllowCopyUploads;
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' );
104 // And this one is needed
105 if ( !isset( $this->mParams
['filename'] ) ) {
106 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
109 if ( $this->mParams
['sessionkey'] ) {
110 // Upload stashed in a previous request
111 $sessionData = $request->getSessionData( UploadBase
::getSessionKeyName() );
112 if ( !UploadFromStash
::isValidSessionKey( $this->mParams
['sessionkey'], $sessionData ) ) {
113 $this->dieUsageMsg( array( 'invalid-session-key' ) );
116 $this->mUpload
= new UploadFromStash();
117 $this->mUpload
->initialize( $this->mParams
['filename'],
118 $this->mParams
['sessionkey'],
119 $sessionData[$this->mParams
['sessionkey']] );
122 } elseif ( isset( $this->mParams
['file'] ) ) {
123 $this->mUpload
= new UploadFromFile();
124 $this->mUpload
->initialize(
125 $this->mParams
['filename'],
126 $request->getUpload( 'file' )
128 } elseif ( isset( $this->mParams
['url'] ) ) {
129 // Make sure upload by URL is enabled:
130 if ( !UploadFromUrl
::isEnabled() ) {
131 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
135 if ( $this->mParams
['asyncdownload'] ) {
136 if ( $this->mParams
['leavemessage'] ) {
137 $async = 'async-leavemessage';
142 $this->mUpload
= new UploadFromUrl
;
143 $this->mUpload
->initialize( $this->mParams
['filename'],
144 $this->mParams
['url'], $async );
150 * Checks that the user has permissions to perform this upload.
151 * Dies with usage message on inadequate permissions.
152 * @param $user User The user to check.
154 protected function checkPermissions( $user ) {
155 // Check whether the user has the appropriate permissions to upload anyway
156 $permission = $this->mUpload
->isAllowed( $user );
158 if ( $permission !== true ) {
159 if ( !$user->isLoggedIn() ) {
160 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
162 $this->dieUsageMsg( array( 'badaccess-groups' ) );
168 * Performs file verification, dies on error.
170 protected function verifyUpload( ) {
171 $verification = $this->mUpload
->verifyUpload( );
172 if ( $verification['status'] === UploadBase
::OK
) {
176 // TODO: Move them to ApiBase's message map
177 switch( $verification['status'] ) {
178 case UploadBase
::EMPTY_FILE
:
179 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
181 case UploadBase
::FILE_TOO_LARGE
:
182 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
184 case UploadBase
::FILETYPE_MISSING
:
185 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
187 case UploadBase
::FILETYPE_BADTYPE
:
188 global $wgFileExtensions;
189 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
191 'filetype' => $verification['finalExt'],
192 'allowed' => $wgFileExtensions
195 case UploadBase
::MIN_LENGTH_PARTNAME
:
196 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
198 case UploadBase
::ILLEGAL_FILENAME
:
199 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
200 0, array( 'filename' => $verification['filtered'] ) );
202 case UploadBase
::VERIFICATION_ERROR
:
203 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
204 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
205 0, array( 'details' => $verification['details'] ) );
207 case UploadBase
::HOOK_ABORTED
:
208 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
209 'hookaborted', 0, array( 'error' => $verification['error'] ) );
212 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
213 0, array( 'code' => $verification['status'] ) );
219 * Check warnings if ignorewarnings is not set.
220 * Returns a suitable result array if there were warnings
222 protected function checkForWarnings() {
225 if ( !$this->mParams
['ignorewarnings'] ) {
226 $warnings = $this->mUpload
->checkWarnings();
229 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
231 if ( isset( $warnings['duplicate'] ) ) {
233 foreach ( $warnings['duplicate'] as $key => $dupe )
234 $dupes[] = $dupe->getName();
235 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
236 $warnings['duplicate'] = $dupes;
239 if ( isset( $warnings['exists'] ) ) {
240 $warning = $warnings['exists'];
241 unset( $warnings['exists'] );
242 $warnings[$warning['warning']] = $warning['file']->getName();
245 $result['result'] = 'Warning';
246 $result['warnings'] = $warnings;
248 $sessionKey = $this->mUpload
->stashSession();
249 if ( !$sessionKey ) {
250 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
253 $result['sessionkey'] = $sessionKey;
262 * Perform the actual upload. Returns a suitable result array on success;
265 protected function performUpload() {
268 // Use comment as initial page text by default
269 if ( is_null( $this->mParams
['text'] ) ) {
270 $this->mParams
['text'] = $this->mParams
['comment'];
273 $file = $this->mUpload
->getLocalFile();
274 $watch = $this->getWatchlistValue( $this->mParams
['watchlist'], $file->getTitle() );
276 // Deprecated parameters
277 if ( $this->mParams
['watch'] ) {
281 // No errors, no warnings: do the upload
282 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
283 $this->mParams
['text'], $watch, $wgUser );
285 if ( !$status->isGood() ) {
286 $error = $status->getErrorsArray();
288 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
289 // The upload can not be performed right now, because the user
292 'result' => 'Queued',
293 'sessionkey' => $error[0][1],
296 $this->getResult()->setIndexedTagName( $error, 'error' );
298 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
302 $file = $this->mUpload
->getLocalFile();
304 $result['result'] = 'Success';
305 $result['filename'] = $file->getName();
306 $result['imageinfo'] = $this->mUpload
->getImageInfo( $this->getResult() );
311 public function mustBePosted() {
315 public function isWriteMode() {
319 public function getAllowedParams() {
323 ApiBase
::PARAM_DFLT
=> ''
328 ApiBase
::PARAM_DFLT
=> false,
329 ApiBase
::PARAM_DEPRECATED
=> true,
331 'watchlist' => array(
332 ApiBase
::PARAM_DFLT
=> 'preferences',
333 ApiBase
::PARAM_TYPE
=> array(
339 'ignorewarnings' => false,
343 'sessionkey' => null,
346 global $wgAllowAsyncCopyUploads;
347 if ( $wgAllowAsyncCopyUploads ) {
349 'asyncdownload' => false,
350 'leavemessage' => false,
356 public function getParamDescription() {
358 'filename' => 'Target filename',
359 'token' => 'Edit token. You can get one of these through prop=info',
360 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
361 'text' => 'Initial page text for new files',
362 'watch' => 'Watch the page',
363 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
364 'ignorewarnings' => 'Ignore any warnings',
365 'file' => 'File contents',
366 'url' => 'Url to fetch the file from',
367 'sessionkey' => 'Session key returned by a previous upload that failed due to warnings',
370 global $wgAllowAsyncCopyUploads;
371 if ( $wgAllowAsyncCopyUploads ) {
373 'asyncdownload' => 'Make fetching a URL asynchronous',
374 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
382 public function getDescription() {
384 'Upload a file, or get the status of pending uploads. Several methods are available:',
385 ' * Upload file contents directly, using the "file" parameter',
386 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
387 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
388 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
389 'sending the "file". Note also that queries using session keys must be',
390 'done in the same login session as the query that originally returned the key (i.e. do not',
391 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
395 public function getPossibleErrors() {
396 return array_merge( parent
::getPossibleErrors(), array(
397 array( 'uploaddisabled' ),
398 array( 'invalid-session-key' ),
399 array( 'uploaddisabled' ),
400 array( 'badaccess-groups' ),
401 array( 'missingparam', 'filename' ),
402 array( 'mustbeloggedin', 'upload' ),
403 array( 'badaccess-groups' ),
404 array( 'badaccess-groups' ),
405 array( 'code' => 'fetchfileerror', 'info' => '' ),
406 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
407 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
408 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
409 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
410 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
411 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
412 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
416 public function getTokenSalt() {
420 protected function getExamples() {
422 'Upload from a URL:',
423 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
424 'Complete an upload that failed due to warnings:',
425 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
429 public function getVersion() {
430 return __CLASS__
. ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';