Follow-up r70037: Fix ApiUpload by passing a WebRequestUpload to the the initializer
[mediawiki.git] / includes / api / ApiUpload.php
blobfd8c493d06d5f7ac093f8149713eef1b35185f93
1 <?php
2 /**
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" );
29 /**
30 * @ingroup API
32 class ApiUpload extends ApiBase {
33 protected $mUpload = null;
34 protected $mParams;
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' );
57 // And this one is needed
58 if ( !isset( $this->mParams['filename'] ) ) {
59 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
63 if ( $this->mParams['sessionkey'] ) {
64 // Upload stashed in a previous request
65 $sessionData = $request->getSessionData( UploadBase::SESSION_KEYNAME );
66 if ( !UploadFromStash::isValidSessionKey( $this->mParams['sessionkey'], $sessionData ) ) {
67 $this->dieUsageMsg( array( 'invalid-session-key' ) );
70 $this->mUpload = new UploadFromStash();
71 $this->mUpload->initialize( $this->mParams['filename'],
72 $this->mParams['sessionkey'],
73 $sessionData[$this->mParams['sessionkey']] );
76 } elseif ( isset( $this->mParams['file'] ) ) {
77 $this->mUpload = new UploadFromFile();
78 $this->mUpload->initialize(
79 $this->mParams['filename'],
80 $request->getUpload( 'file' )
81 );
82 } elseif ( isset( $this->mParams['url'] ) ) {
83 // Make sure upload by URL is enabled:
84 if ( !$wgAllowCopyUploads ) {
85 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
88 $this->mUpload = new UploadFromUrl;
89 $async = $this->mParams['asyncdownload'] ? 'async' : null;
90 $this->checkPermissions( $wgUser );
92 $result = $this->mUpload->initialize(
93 $this->mParams['filename'],
94 $this->mParams['url'],
95 $this->mParams['comment'],
96 $this->mParams['watchlist'],
97 $this->mParams['ignorewarnings'],
98 $async );
100 if ( $async ) {
101 $this->getResult()->addValue( null,
102 $this->getModuleName(),
103 array( 'queued' => $result ) );
104 return;
107 $status = $this->mUpload->retrieveFileFromUrl();
108 if ( !$status->isGood() ) {
109 $this->getResult()->addValue( null,
110 $this->getModuleName(),
111 array( 'error' => $status ) );
112 return;
117 $this->checkPermissions( $wgUser );
119 if ( !isset( $this->mUpload ) ) {
120 $this->dieUsage( 'No upload module set', 'nomodule' );
123 // Perform the upload
124 $result = $this->performUpload();
126 // Cleanup any temporary mess
127 $this->mUpload->cleanupTempFile();
129 $this->getResult()->addValue( null, $this->getModuleName(), $result );
133 * Checks that the user has permissions to perform this upload.
134 * Dies with usage message on inadequate permissions.
135 * @param $user User The user to check.
137 protected function checkPermissions( $user ) {
138 // Check whether the user has the appropriate permissions to upload anyway
139 $permission = $this->mUpload->isAllowed( $user );
141 if ( $permission !== true ) {
142 if ( !$user->isLoggedIn() ) {
143 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
144 } else {
145 $this->dieUsageMsg( array( 'badaccess-groups' ) );
151 * Performs file verification, dies on error.
153 public function verifyUpload( ) {
154 $verification = $this->mUpload->verifyUpload( );
155 if ( $verification['status'] === UploadBase::OK ) {
156 return $verification;
159 $this->getVerificationError( $verification );
163 * Produce the usage error
165 * @param $verification array an associative array with the status
166 * key
168 public function getVerificationError( $verification ) {
169 // TODO: Move them to ApiBase's message map
170 switch( $verification['status'] ) {
171 case UploadBase::EMPTY_FILE:
172 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
173 break;
174 case UploadBase::FILE_TOO_LARGE:
175 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
176 break;
177 case UploadBase::FILETYPE_MISSING:
178 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
179 break;
180 case UploadBase::FILETYPE_BADTYPE:
181 global $wgFileExtensions;
182 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
183 0, array(
184 'filetype' => $verification['finalExt'],
185 'allowed' => $wgFileExtensions
186 ) );
187 break;
188 case UploadBase::MIN_LENGTH_PARTNAME:
189 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
190 break;
191 case UploadBase::ILLEGAL_FILENAME:
192 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
193 0, array( 'filename' => $verification['filtered'] ) );
194 break;
195 case UploadBase::OVERWRITE_EXISTING_FILE:
196 $this->dieUsage( 'Overwriting an existing file is not allowed', 'overwrite' );
197 break;
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'] ) );
202 break;
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'] ) );
206 break;
207 default:
208 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
209 0, array( 'code' => $verification['status'] ) );
210 break;
214 protected function checkForWarnings() {
215 $result = array();
217 if ( !$this->mParams['ignorewarnings'] ) {
218 $warnings = $this->mUpload->checkWarnings();
219 if ( $warnings ) {
220 // Add indices
221 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
223 if ( isset( $warnings['duplicate'] ) ) {
224 $dupes = array();
225 foreach ( $warnings['duplicate'] as $key => $dupe )
226 $dupes[] = $dupe->getName();
227 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
228 $warnings['duplicate'] = $dupes;
231 if ( isset( $warnings['exists'] ) ) {
232 $warning = $warnings['exists'];
233 unset( $warnings['exists'] );
234 $warnings[$warning['warning']] = $warning['file']->getName();
237 $result['result'] = 'Warning';
238 $result['warnings'] = $warnings;
240 $sessionKey = $this->mUpload->stashSession();
241 if ( !$sessionKey ) {
242 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
245 $result['sessionkey'] = $sessionKey;
247 return $result;
250 return;
253 protected function performUpload() {
254 global $wgUser;
255 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
256 if ( $permErrors !== true ) {
257 $this->dieUsageMsg( array( 'badaccess-groups' ) );
260 $this->verifyUpload();
262 $warnings = $this->checkForWarnings();
263 if ( isset( $warnings ) ) {
264 return $warnings;
267 // Use comment as initial page text by default
268 if ( is_null( $this->mParams['text'] ) ) {
269 $this->mParams['text'] = $this->mParams['comment'];
272 $file = $this->mUpload->getLocalFile();
273 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
275 // Deprecated parameters
276 if ( $this->mParams['watch'] ) {
277 $watch = true;
280 // No errors, no warnings: do the upload
281 $status = $this->mUpload->performUpload( $this->mParams['comment'],
282 $this->mParams['text'], $watch, $wgUser );
284 if ( !$status->isGood() ) {
285 $error = $status->getErrorsArray();
286 $this->getResult()->setIndexedTagName( $result['details'], 'error' );
288 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
291 $file = $this->mUpload->getLocalFile();
293 $result['result'] = 'Success';
294 $result['filename'] = $file->getName();
295 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
297 return $result;
300 public function mustBePosted() {
301 return true;
304 public function isWriteMode() {
305 return true;
308 public function getAllowedParams() {
309 $params = array(
310 'filename' => null,
311 'comment' => array(
312 ApiBase::PARAM_DFLT => ''
314 'text' => null,
315 'token' => null,
316 'watch' => array(
317 ApiBase::PARAM_DFLT => false,
318 ApiBase::PARAM_DEPRECATED => true,
320 'watchlist' => array(
321 ApiBase::PARAM_DFLT => 'preferences',
322 ApiBase::PARAM_TYPE => array(
323 'watch',
324 'preferences',
325 'nochange'
328 'ignorewarnings' => false,
329 'file' => null,
330 'url' => null,
331 'asyncdownload' => false,
332 'sessionkey' => null,
334 return $params;
337 public function getParamDescription() {
338 return array(
339 'filename' => 'Target filename',
340 'token' => 'Edit token. You can get one of these through prop=info',
341 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
342 'text' => 'Initial page text for new files',
343 'watch' => 'Watch the page',
344 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
345 'ignorewarnings' => 'Ignore any warnings',
346 'file' => 'File contents',
347 'url' => 'Url to fetch the file from',
348 'asyncdownload' => 'Make fetching a URL asyncronous',
349 'sessionkey' => array(
350 'Session key returned by a previous upload that failed due to warnings',
355 public function getDescription() {
356 return array(
357 'Upload a file, or get the status of pending uploads. Several methods are available:',
358 ' * Upload file contents directly, using the "file" parameter',
359 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
360 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
361 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
362 'sending the "file". Note also that queries using session keys must be',
363 'done in the same login session as the query that originally returned the key (i.e. do not',
364 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
368 public function getPossibleErrors() {
369 return array_merge( parent::getPossibleErrors(), array(
370 array( 'uploaddisabled' ),
371 array( 'invalid-session-key' ),
372 array( 'uploaddisabled' ),
373 array( 'badaccess-groups' ),
374 array( 'missingparam', 'filename' ),
375 array( 'mustbeloggedin', 'upload' ),
376 array( 'badaccess-groups' ),
377 array( 'badaccess-groups' ),
378 array( 'code' => 'fetchfileerror', 'info' => '' ),
379 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
380 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
381 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
382 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
383 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
384 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
385 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
386 ) );
389 public function getTokenSalt() {
390 return '';
393 protected function getExamples() {
394 return array(
395 'Upload from a URL:',
396 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
397 'Complete an upload that failed due to warnings:',
398 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
402 public function getVersion() {
403 return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';