Standardised file description headers, added @file
[mediawiki.git] / includes / api / ApiUpload.php
blobcf69ce0ffcf39c34f7a5ad62d0b093f15806a4ae
1 <?php
2 /**
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
24 * @file
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( "ApiBase.php" );
32 /**
33 * @ingroup API
35 class ApiUpload extends ApiBase {
36 protected $mUpload = null;
37 protected $mParams;
39 public function __construct( $main, $action ) {
40 parent::__construct( $main, $action );
43 public function execute() {
44 global $wgUser;
46 // Check whether upload is enabled
47 if ( !UploadBase::isEnabled() ) {
48 $this->dieUsageMsg( array( 'uploaddisabled' ) );
51 // Parameter handling
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 );
66 // Fetch the file
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();
86 if ( $warnings ) {
87 $this->getResult()->addValue( null, $this->getModuleName(), $warnings );
88 } else {
89 // Perform the upload
90 $result = $this->performUpload();
91 $this->getResult()->addValue( null, $this->getModuleName(), $result );
94 // Cleanup any temporary mess
95 $this->mUpload->cleanupTempFile();
98 /**
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' ) );
133 $async = false;
134 if ( $this->mParams['asyncdownload'] ) {
135 if ( $this->mParams['leavemessage'] ) {
136 $async = 'async-leavemessage';
137 } else {
138 $async = 'async';
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' ) );
160 } else {
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 ) {
172 return;
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' );
179 break;
180 case UploadBase::FILE_TOO_LARGE:
181 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
182 break;
183 case UploadBase::FILETYPE_MISSING:
184 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
185 break;
186 case UploadBase::FILETYPE_BADTYPE:
187 global $wgFileExtensions;
188 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
189 0, array(
190 'filetype' => $verification['finalExt'],
191 'allowed' => $wgFileExtensions
192 ) );
193 break;
194 case UploadBase::MIN_LENGTH_PARTNAME:
195 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
196 break;
197 case UploadBase::ILLEGAL_FILENAME:
198 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
199 0, array( 'filename' => $verification['filtered'] ) );
200 break;
201 case UploadBase::VERIFICATION_ERROR:
202 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
203 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
204 0, array( 'details' => $verification['details'] ) );
205 break;
206 case UploadBase::HOOK_ABORTED:
207 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
208 'hookaborted', 0, array( 'error' => $verification['error'] ) );
209 break;
210 default:
211 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
212 0, array( 'code' => $verification['status'] ) );
213 break;
218 * Check warnings if ignorewarnings is not set.
219 * Returns a suitable result array if there were warnings
221 protected function checkForWarnings() {
222 $result = array();
224 if ( !$this->mParams['ignorewarnings'] ) {
225 $warnings = $this->mUpload->checkWarnings();
226 if ( $warnings ) {
227 // Add indices
228 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
230 if ( isset( $warnings['duplicate'] ) ) {
231 $dupes = array();
232 foreach ( $warnings['duplicate'] as $key => $dupe )
233 $dupes[] = $dupe->getName();
234 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
235 $warnings['duplicate'] = $dupes;
238 if ( isset( $warnings['exists'] ) ) {
239 $warning = $warnings['exists'];
240 unset( $warnings['exists'] );
241 $warnings[$warning['warning']] = $warning['file']->getName();
244 $result['result'] = 'Warning';
245 $result['warnings'] = $warnings;
247 $sessionKey = $this->mUpload->stashSession();
248 if ( !$sessionKey ) {
249 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
252 $result['sessionkey'] = $sessionKey;
254 return $result;
257 return;
261 * Perform the actual upload. Returns a suitable result array on success;
262 * dies on failure.
264 protected function performUpload() {
265 global $wgUser;
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();
287 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
288 // The upload can not be performed right now, because the user
289 // requested so
290 return array(
291 'result' => 'Queued',
292 'sessionkey' => $error[0][1],
294 } else {
295 $this->getResult()->setIndexedTagName( $error, 'error' );
297 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
301 $file = $this->mUpload->getLocalFile();
303 $result['result'] = 'Success';
304 $result['filename'] = $file->getName();
305 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
307 return $result;
310 public function mustBePosted() {
311 return true;
314 public function isWriteMode() {
315 return true;
318 public function getAllowedParams() {
319 $params = array(
320 'filename' => array(
321 ApiBase::PARAM_TYPE => 'string',
322 ApiBase::PARAM_REQUIRED => true
324 'comment' => array(
325 ApiBase::PARAM_DFLT => ''
327 'text' => null,
328 'token' => null,
329 'watch' => array(
330 ApiBase::PARAM_DFLT => false,
331 ApiBase::PARAM_DEPRECATED => true,
333 'watchlist' => array(
334 ApiBase::PARAM_DFLT => 'preferences',
335 ApiBase::PARAM_TYPE => array(
336 'watch',
337 'preferences',
338 'nochange'
341 'ignorewarnings' => false,
342 'file' => null,
343 'url' => null,
345 'sessionkey' => null,
348 global $wgAllowAsyncCopyUploads;
349 if ( $wgAllowAsyncCopyUploads ) {
350 $params += array(
351 'asyncdownload' => false,
352 'leavemessage' => false,
355 return $params;
358 public function getParamDescription() {
359 $params = array(
360 'filename' => 'Target filename',
361 'token' => 'Edit token. You can get one of these through prop=info',
362 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
363 'text' => 'Initial page text for new files',
364 'watch' => 'Watch the page',
365 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
366 'ignorewarnings' => 'Ignore any warnings',
367 'file' => 'File contents',
368 'url' => 'Url to fetch the file from',
369 'sessionkey' => 'Session key returned by a previous upload that failed due to warnings',
372 global $wgAllowAsyncCopyUploads;
373 if ( $wgAllowAsyncCopyUploads ) {
374 $params += array(
375 'asyncdownload' => 'Make fetching a URL asynchronous',
376 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
380 return $params;
384 public function getDescription() {
385 return array(
386 'Upload a file, or get the status of pending uploads. Several methods are available:',
387 ' * Upload file contents directly, using the "file" parameter',
388 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
389 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
390 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
391 'sending the "file". Note also that queries using session keys must be',
392 'done in the same login session as the query that originally returned the key (i.e. do not',
393 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
397 public function getPossibleErrors() {
398 return array_merge( parent::getPossibleErrors(), array(
399 array( 'uploaddisabled' ),
400 array( 'invalid-session-key' ),
401 array( 'uploaddisabled' ),
402 array( 'badaccess-groups' ),
403 array( 'mustbeloggedin', 'upload' ),
404 array( 'badaccess-groups' ),
405 array( 'badaccess-groups' ),
406 array( 'code' => 'fetchfileerror', 'info' => '' ),
407 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
408 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
409 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
410 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
411 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
412 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
413 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
414 ) );
417 public function getTokenSalt() {
418 return '';
421 protected function getExamples() {
422 return array(
423 'Upload from a URL:',
424 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
425 'Complete an upload that failed due to warnings:',
426 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
430 public function getVersion() {
431 return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';