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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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' ) );
48 $this->mParams
= $this->extractRequestParams();
49 $request = $this->getMain()->getRequest();
51 // Add the uploaded file to the params array
52 $this->mParams
['file'] = $request->getFileName( 'file' );
54 // One and only one of the following parameters is needed
55 $this->requireOnlyOneParameter( $this->mParams
,
56 'sessionkey', 'file', 'url' );
58 if ( $this->mParams
['sessionkey'] ) {
60 * Upload stashed in a previous request
62 // Check the session key
63 if ( !isset( $_SESSION[UploadBase
::getSessionKey()][$this->mParams
['sessionkey']] ) ) {
64 $this->dieUsageMsg( array( 'invalid-session-key' ) );
67 $this->mUpload
= new UploadFromStash();
68 $this->mUpload
->initialize( $this->mParams
['filename'],
69 $this->mParams
['sessionkey'],
70 $_SESSION[UploadBase
::getSessionKey()][$this->mParams
['sessionkey']] );
71 } elseif ( isset( $this->mParams
['filename'] ) ) {
73 * Upload from URL, etc.
74 * Parameter filename is required
76 if ( isset( $this->mParams
['file'] ) ) {
77 $this->mUpload
= new UploadFromFile();
78 $this->mUpload
->initialize(
79 $this->mParams
['filename'],
80 $request->getFileTempName( 'file' ),
81 $request->getFileSize( 'file' )
83 } elseif ( isset( $this->mParams
['url'] ) ) {
84 // make sure upload by URL is enabled:
85 if ( !$wgAllowCopyUploads ) {
86 $this->dieUsageMsg( array( 'uploaddisabled' ) );
89 // make sure the current user can upload
90 if ( !$wgUser->isAllowed( 'upload_by_url' ) ) {
91 $this->dieUsageMsg( array( 'badaccess-groups' ) );
94 $this->mUpload
= new UploadFromUrl();
95 $this->mUpload
->initialize( $this->mParams
['filename'],
96 $this->mParams
['url'] );
98 $status = $this->mUpload
->fetchFile();
99 if ( !$status->isOK() ) {
100 $this->dieUsage( $status->getWikiText(), 'fetchfileerror' );
104 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
107 if ( !isset( $this->mUpload
) ) {
108 $this->dieUsage( 'No upload module set', 'nomodule' );
111 // Check whether the user has the appropriate permissions to upload anyway
112 $permission = $this->mUpload
->isAllowed( $wgUser );
114 if ( $permission !== true ) {
115 if ( !$wgUser->isLoggedIn() ) {
116 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
118 $this->dieUsageMsg( array( 'badaccess-groups' ) );
121 // Perform the upload
122 $result = $this->performUpload();
124 // Cleanup any temporary mess
125 $this->mUpload
->cleanupTempFile();
127 $this->getResult()->addValue( null, $this->getModuleName(), $result );
131 * Performs file verification, dies on error.
133 * @param $flag integer passed to UploadBase::verifyUpload, set to
134 * UploadBase::EMPTY_FILE to skip the empty file check.
136 public function verifyUpload( $flag ) {
137 $verification = $this->mUpload
->verifyUpload( $flag );
138 if ( $verification['status'] === UploadBase
::OK
) {
139 return $verification;
142 $this->getVerificationError( $verification );
146 * Produce the usage error
148 * @param $verification array an associative array with the status
151 public function getVerificationError( $verification ) {
152 // TODO: Move them to ApiBase's message map
153 switch( $verification['status'] ) {
154 case UploadBase
::EMPTY_FILE
:
155 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
157 case UploadBase
::FILETYPE_MISSING
:
158 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
160 case UploadBase
::FILETYPE_BADTYPE
:
161 global $wgFileExtensions;
162 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
164 'filetype' => $verification['finalExt'],
165 'allowed' => $wgFileExtensions
168 case UploadBase
::MIN_LENGTH_PARTNAME
:
169 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
171 case UploadBase
::ILLEGAL_FILENAME
:
172 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
173 0, array( 'filename' => $verification['filtered'] ) );
175 case UploadBase
::OVERWRITE_EXISTING_FILE
:
176 $this->dieUsage( 'Overwriting an existing file is not allowed', 'overwrite' );
178 case UploadBase
::VERIFICATION_ERROR
:
179 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
180 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
181 0, array( 'details' => $verification['details'] ) );
183 case UploadBase
::HOOK_ABORTED
:
184 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
185 'hookaborted', 0, array( 'error' => $verification['error'] ) );
188 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
189 0, array( 'code' => $verification['status'] ) );
194 protected function checkForWarnings() {
197 if ( !$this->mParams
['ignorewarnings'] ) {
198 $warnings = $this->mUpload
->checkWarnings();
201 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
203 if ( isset( $warnings['duplicate'] ) ) {
205 foreach ( $warnings['duplicate'] as $key => $dupe )
206 $dupes[] = $dupe->getName();
207 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
208 $warnings['duplicate'] = $dupes;
211 if ( isset( $warnings['exists'] ) ) {
212 $warning = $warnings['exists'];
213 unset( $warnings['exists'] );
214 $warnings[$warning['warning']] = $warning['file']->getName();
217 $result['result'] = 'Warning';
218 $result['warnings'] = $warnings;
220 $sessionKey = $this->mUpload
->stashSession();
221 if ( !$sessionKey ) {
222 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
225 $result['sessionkey'] = $sessionKey;
233 protected function performUpload() {
235 $permErrors = $this->mUpload
->verifyPermissions( $wgUser );
236 if ( $permErrors !== true ) {
237 $this->dieUsageMsg( array( 'badaccess-groups' ) );
240 $this->verifyUpload();
242 $warnings = $this->checkForWarnings();
243 if( isset($warnings) ) return $warnings;
245 // Use comment as initial page text by default
246 if ( is_null( $this->mParams
['text'] ) ) {
247 $this->mParams
['text'] = $this->mParams
['comment'];
250 $file = $this->mUpload
->getLocalFile();
251 $watch = $this->getWatchlistValue( $params['watchlist'], $file->getTitle() );
253 // Deprecated parameters
254 if ( $this->mParams
['watch'] ) {
258 // No errors, no warnings: do the upload
259 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
260 $this->mParams
['text'], $watch, $wgUser );
262 if ( !$status->isGood() ) {
263 $error = $status->getErrorsArray();
264 $this->getResult()->setIndexedTagName( $result['details'], 'error' );
266 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
269 $file = $this->mUpload
->getLocalFile();
271 $result['result'] = 'Success';
272 $result['filename'] = $file->getName();
273 $result['imageinfo'] = $this->mUpload
->getImageInfo( $this->getResult() );
278 public function mustBePosted() {
282 public function isWriteMode() {
286 public function getAllowedParams() {
290 ApiBase
::PARAM_DFLT
=> ''
295 ApiBase
::PARAM_DFLT
=> false,
296 ApiBase
::PARAM_DEPRECATED
=> true,
298 'watchlist' => array(
299 ApiBase
::PARAM_DFLT
=> 'preferences',
300 ApiBase
::PARAM_TYPE
=> array(
306 'ignorewarnings' => false,
309 'sessionkey' => null,
314 public function getParamDescription() {
316 'filename' => 'Target filename',
317 'token' => 'Edit token. You can get one of these through prop=info',
318 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
319 'text' => 'Initial page text for new files',
320 'watch' => 'Watch the page',
321 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
322 'ignorewarnings' => 'Ignore any warnings',
323 'file' => 'File contents',
324 'url' => 'Url to fetch the file from',
325 'sessionkey' => array(
326 'Session key returned by a previous upload that failed due to warnings',
331 public function getDescription() {
333 'Upload a file, or get the status of pending uploads. Several methods are available:',
334 ' * Upload file contents directly, using the "file" parameter',
335 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
336 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
337 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
338 'sending the "file". Note also that queries using session keys must be',
339 'done in the same login session as the query that originally returned the key (i.e. do not',
340 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff.'
344 public function getPossibleErrors() {
345 return array_merge( parent
::getPossibleErrors(), array(
346 array( 'uploaddisabled' ),
347 array( 'invalid-session-key' ),
348 array( 'uploaddisabled' ),
349 array( 'badaccess-groups' ),
350 array( 'missingparam', 'filename' ),
351 array( 'mustbeloggedin', 'upload' ),
352 array( 'badaccess-groups' ),
353 array( 'badaccess-groups' ),
354 array( 'code' => 'fetchfileerror', 'info' => '' ),
355 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
356 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
357 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
358 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
359 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
360 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
361 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
365 public function getTokenSalt() {
369 protected function getExamples() {
371 'Upload from a URL:',
372 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
373 'Complete an upload that failed due to warnings:',
374 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
378 public function getVersion() {
379 return __CLASS__
. ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';