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 $this->selectUploadModule();
59 if ( !isset( $this->mUpload
) ) {
60 $this->dieUsage( 'No upload module set', 'nomodule' );
63 // First check permission to upload
64 $this->checkPermissions( $wgUser );
67 $status = $this->mUpload
->fetchFile();
68 if ( !$status->isGood() ) {
69 $errors = $status->getErrorsArray();
70 $error = array_shift( $errors[0] );
71 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
74 // Check if the uploaded file is sane
75 $this->verifyUpload();
77 // Check permission to upload this file
78 $permErrors = $this->mUpload
->verifyPermissions( $wgUser );
79 if ( $permErrors !== true ) {
80 // Todo: stash the upload and allow choosing a new name
81 $this->dieUsageMsg( array( 'badaccess-groups' ) );
84 // Check warnings if necessary
85 $warnings = $this->checkForWarnings();
87 $this->getResult()->addValue( null, $this->getModuleName(), $warnings );
90 $result = $this->performUpload();
91 $this->getResult()->addValue( null, $this->getModuleName(), $result );
94 // Cleanup any temporary mess
95 $this->mUpload
->cleanupTempFile();
99 * Select an upload module and set it to mUpload. Dies on failure.
101 protected function selectUploadModule() {
102 $request = $this->getMain()->getRequest();
104 // One and only one of the following parameters is needed
105 $this->requireOnlyOneParameter( $this->mParams
,
106 'sessionkey', 'file', 'url' );
108 if ( $this->mParams
['sessionkey'] ) {
109 // Upload stashed in a previous request
110 $sessionData = $request->getSessionData( UploadBase
::getSessionKeyName() );
111 if ( !UploadFromStash
::isValidSessionKey( $this->mParams
['sessionkey'], $sessionData ) ) {
112 $this->dieUsageMsg( array( 'invalid-session-key' ) );
115 $this->mUpload
= new UploadFromStash();
116 $this->mUpload
->initialize( $this->mParams
['filename'],
117 $this->mParams
['sessionkey'],
118 $sessionData[$this->mParams
['sessionkey']] );
121 } elseif ( isset( $this->mParams
['file'] ) ) {
122 $this->mUpload
= new UploadFromFile();
123 $this->mUpload
->initialize(
124 $this->mParams
['filename'],
125 $request->getUpload( 'file' )
127 } elseif ( isset( $this->mParams
['url'] ) ) {
128 // Make sure upload by URL is enabled:
129 if ( !UploadFromUrl
::isEnabled() ) {
130 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
134 if ( $this->mParams
['asyncdownload'] ) {
135 if ( $this->mParams
['leavemessage'] ) {
136 $async = 'async-leavemessage';
141 $this->mUpload
= new UploadFromUrl
;
142 $this->mUpload
->initialize( $this->mParams
['filename'],
143 $this->mParams
['url'], $async );
149 * Checks that the user has permissions to perform this upload.
150 * Dies with usage message on inadequate permissions.
151 * @param $user User The user to check.
153 protected function checkPermissions( $user ) {
154 // Check whether the user has the appropriate permissions to upload anyway
155 $permission = $this->mUpload
->isAllowed( $user );
157 if ( $permission !== true ) {
158 if ( !$user->isLoggedIn() ) {
159 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
161 $this->dieUsageMsg( array( 'badaccess-groups' ) );
167 * Performs file verification, dies on error.
169 protected function verifyUpload( ) {
170 global $wgFileExtensions;
172 $verification = $this->mUpload
->verifyUpload( );
173 if ( $verification['status'] === UploadBase
::OK
) {
177 // TODO: Move them to ApiBase's message map
178 switch( $verification['status'] ) {
179 case UploadBase
::EMPTY_FILE
:
180 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
182 case UploadBase
::FILE_TOO_LARGE
:
183 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
185 case UploadBase
::FILETYPE_MISSING
:
186 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
188 case UploadBase
::FILETYPE_BADTYPE
:
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() {
322 ApiBase
::PARAM_TYPE
=> 'string',
323 ApiBase
::PARAM_REQUIRED
=> true
326 ApiBase
::PARAM_DFLT
=> ''
331 ApiBase
::PARAM_DFLT
=> false,
332 ApiBase
::PARAM_DEPRECATED
=> true,
334 'watchlist' => array(
335 ApiBase
::PARAM_DFLT
=> 'preferences',
336 ApiBase
::PARAM_TYPE
=> array(
342 'ignorewarnings' => false,
346 'sessionkey' => null,
349 global $wgAllowAsyncCopyUploads;
350 if ( $wgAllowAsyncCopyUploads ) {
352 'asyncdownload' => false,
353 'leavemessage' => false,
359 public function getParamDescription() {
361 'filename' => 'Target filename',
362 'token' => 'Edit token. You can get one of these through prop=info',
363 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
364 'text' => 'Initial page text for new files',
365 'watch' => 'Watch the page',
366 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
367 'ignorewarnings' => 'Ignore any warnings',
368 'file' => 'File contents',
369 'url' => 'Url to fetch the file from',
370 'sessionkey' => 'Session key returned by a previous upload that failed due to warnings',
373 global $wgAllowAsyncCopyUploads;
374 if ( $wgAllowAsyncCopyUploads ) {
376 'asyncdownload' => 'Make fetching a URL asynchronous',
377 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
385 public function getDescription() {
387 'Upload a file, or get the status of pending uploads. Several methods are available:',
388 ' * Upload file contents directly, using the "file" parameter',
389 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
390 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
391 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
392 'sending the "file". Note also that queries using session keys must be',
393 'done in the same login session as the query that originally returned the key (i.e. do not',
394 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
398 public function getPossibleErrors() {
399 return array_merge( parent
::getPossibleErrors(), array(
400 array( 'uploaddisabled' ),
401 array( 'invalid-session-key' ),
402 array( 'uploaddisabled' ),
403 array( 'badaccess-groups' ),
404 array( 'mustbeloggedin', 'upload' ),
405 array( 'badaccess-groups' ),
406 array( 'badaccess-groups' ),
407 array( 'code' => 'fetchfileerror', 'info' => '' ),
408 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
409 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
410 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
411 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
412 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
413 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
414 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
418 public function getTokenSalt() {
422 protected function getExamples() {
424 'Upload from a URL:',
425 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
426 'Complete an upload that failed due to warnings:',
427 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
431 public function getVersion() {
432 return __CLASS__
. ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';