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 );
62 // Check permission to upload this file
63 $permErrors = $this->mUpload
->verifyPermissions( $wgUser );
64 if ( $permErrors !== true ) {
65 // Todo: more specific error message
66 $this->dieUsageMsg( array( 'badaccess-groups' ) );
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 warnings if necessary
81 $warnings = $this->checkForWarnings();
83 $this->getResult()->addValue( null, $this->getModuleName(), $warnings );
86 $result = $this->performUpload();
87 $this->getResult()->addValue( null, $this->getModuleName(), $result );
90 // Cleanup any temporary mess
91 $this->mUpload
->cleanupTempFile();
95 * Select an upload module and set it to mUpload. Dies on failure.
97 protected function selectUploadModule() {
98 $request = $this->getMain()->getRequest();
100 // One and only one of the following parameters is needed
101 $this->requireOnlyOneParameter( $this->mParams
,
102 'sessionkey', 'file', 'url' );
103 // And this one is needed
104 if ( !isset( $this->mParams
['filename'] ) ) {
105 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
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 $verification = $this->mUpload
->verifyUpload( );
171 if ( $verification['status'] === UploadBase
::OK
) {
175 // TODO: Move them to ApiBase's message map
176 switch( $verification['status'] ) {
177 case UploadBase
::EMPTY_FILE
:
178 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
180 case UploadBase
::FILE_TOO_LARGE
:
181 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
183 case UploadBase
::FILETYPE_MISSING
:
184 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
186 case UploadBase
::FILETYPE_BADTYPE
:
187 global $wgFileExtensions;
188 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
190 'filetype' => $verification['finalExt'],
191 'allowed' => $wgFileExtensions
194 case UploadBase
::MIN_LENGTH_PARTNAME
:
195 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
197 case UploadBase
::ILLEGAL_FILENAME
:
198 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
199 0, array( 'filename' => $verification['filtered'] ) );
201 case UploadBase
::OVERWRITE_EXISTING_FILE
:
202 $this->dieUsage( 'Overwriting an existing file is not allowed', 'overwrite' );
204 case UploadBase
::VERIFICATION_ERROR
:
205 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
206 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
207 0, array( 'details' => $verification['details'] ) );
209 case UploadBase
::HOOK_ABORTED
:
210 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
211 'hookaborted', 0, array( 'error' => $verification['error'] ) );
214 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
215 0, array( 'code' => $verification['status'] ) );
221 * Check warnings if ignorewarnings is not set.
222 * Returns a suitable result array if there were warnings
224 protected function checkForWarnings() {
227 if ( !$this->mParams
['ignorewarnings'] ) {
228 $warnings = $this->mUpload
->checkWarnings();
231 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
233 if ( isset( $warnings['duplicate'] ) ) {
235 foreach ( $warnings['duplicate'] as $key => $dupe )
236 $dupes[] = $dupe->getName();
237 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
238 $warnings['duplicate'] = $dupes;
241 if ( isset( $warnings['exists'] ) ) {
242 $warning = $warnings['exists'];
243 unset( $warnings['exists'] );
244 $warnings[$warning['warning']] = $warning['file']->getName();
247 $result['result'] = 'Warning';
248 $result['warnings'] = $warnings;
250 $sessionKey = $this->mUpload
->stashSession();
251 if ( !$sessionKey ) {
252 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
255 $result['sessionkey'] = $sessionKey;
264 * Perform the actual upload. Returns a suitable result array on success;
267 protected function performUpload() {
270 // Use comment as initial page text by default
271 if ( is_null( $this->mParams
['text'] ) ) {
272 $this->mParams
['text'] = $this->mParams
['comment'];
275 $file = $this->mUpload
->getLocalFile();
276 $watch = $this->getWatchlistValue( $this->mParams
['watchlist'], $file->getTitle() );
278 // Deprecated parameters
279 if ( $this->mParams
['watch'] ) {
283 // No errors, no warnings: do the upload
284 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
285 $this->mParams
['text'], $watch, $wgUser );
287 if ( !$status->isGood() ) {
288 $error = $status->getErrorsArray();
289 $this->getResult()->setIndexedTagName( $error, 'error' );
291 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
294 $file = $this->mUpload
->getLocalFile();
296 $result['result'] = 'Success';
297 $result['filename'] = $file->getName();
298 $result['imageinfo'] = $this->mUpload
->getImageInfo( $this->getResult() );
303 public function mustBePosted() {
307 public function isWriteMode() {
311 public function getAllowedParams() {
315 ApiBase
::PARAM_DFLT
=> ''
320 ApiBase
::PARAM_DFLT
=> false,
321 ApiBase
::PARAM_DEPRECATED
=> true,
323 'watchlist' => array(
324 ApiBase
::PARAM_DFLT
=> 'preferences',
325 ApiBase
::PARAM_TYPE
=> array(
331 'ignorewarnings' => false,
334 'asyncdownload' => false,
335 'leavemessage' => false,
336 'sessionkey' => null,
341 public function getParamDescription() {
343 'filename' => 'Target filename',
344 'token' => 'Edit token. You can get one of these through prop=info',
345 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
346 'text' => 'Initial page text for new files',
347 'watch' => 'Watch the page',
348 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
349 'ignorewarnings' => 'Ignore any warnings',
350 'file' => 'File contents',
351 'url' => 'Url to fetch the file from',
352 'asyncdownload' => 'Make fetching a URL asyncronous',
353 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
354 'sessionkey' => 'Session key returned by a previous upload that failed due to warnings',
358 public function getDescription() {
360 'Upload a file, or get the status of pending uploads. Several methods are available:',
361 ' * Upload file contents directly, using the "file" parameter',
362 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
363 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
364 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
365 'sending the "file". Note also that queries using session keys must be',
366 'done in the same login session as the query that originally returned the key (i.e. do not',
367 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
371 public function getPossibleErrors() {
372 return array_merge( parent
::getPossibleErrors(), array(
373 array( 'uploaddisabled' ),
374 array( 'invalid-session-key' ),
375 array( 'uploaddisabled' ),
376 array( 'badaccess-groups' ),
377 array( 'missingparam', 'filename' ),
378 array( 'mustbeloggedin', 'upload' ),
379 array( 'badaccess-groups' ),
380 array( 'badaccess-groups' ),
381 array( 'code' => 'fetchfileerror', 'info' => '' ),
382 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
383 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
384 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
385 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
386 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
387 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
388 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
392 public function getTokenSalt() {
396 protected function getExamples() {
398 'Upload from a URL:',
399 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
400 'Complete an upload that failed due to warnings:',
401 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
405 public function getVersion() {
406 return __CLASS__
. ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';