LIMIT_SML2, LIMIT_BIG2 are in ApiBase, not ApiMain
[lhc/web/wiklou.git] / includes / api / ApiUpload.php
1 <?php
2 /**
3 * Created on Aug 21, 2008
4 * API for MediaWiki 1.8+
5 *
6 * Copyright © 2008 - 2010 Bryan Tong Minh <Bryan.TongMinh@Gmail.com>
7 *
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.
12 *
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.
17 *
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
22 */
23
24 if ( !defined( 'MEDIAWIKI' ) ) {
25 // Eclipse helper - will be ignored in production
26 require_once( "ApiBase.php" );
27 }
28
29 /**
30 * @ingroup API
31 */
32 class ApiUpload extends ApiBase {
33 protected $mUpload = null;
34 protected $mParams;
35
36 public function __construct( $main, $action ) {
37 parent::__construct( $main, $action );
38 }
39
40 public function execute() {
41 global $wgUser, $wgAllowCopyUploads;
42
43 // Check whether upload is enabled
44 if ( !UploadBase::isEnabled() ) {
45 $this->dieUsageMsg( array( 'uploaddisabled' ) );
46 }
47
48 $this->mParams = $this->extractRequestParams();
49 $request = $this->getMain()->getRequest();
50
51 // Add the uploaded file to the params array
52 $this->mParams['file'] = $request->getFileName( 'file' );
53
54 // One and only one of the following parameters is needed
55 $this->requireOnlyOneParameter( $this->mParams,
56 'sessionkey', 'file', 'url' );
57
58 if ( $this->mParams['sessionkey'] ) {
59 /**
60 * Upload stashed in a previous request
61 */
62 // Check the session key
63 if ( !isset( $_SESSION[UploadBase::getSessionKey()][$this->mParams['sessionkey']] ) ) {
64 $this->dieUsageMsg( array( 'invalid-session-key' ) );
65 }
66
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'] ) ) {
72 /**
73 * Upload from URL, etc.
74 * Parameter filename is required
75 */
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' )
82 );
83 } elseif ( isset( $this->mParams['url'] ) ) {
84 // make sure upload by URL is enabled:
85 if ( !$wgAllowCopyUploads ) {
86 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
87 }
88
89 // make sure the current user can upload
90 if ( !$wgUser->isAllowed( 'upload_by_url' ) ) {
91 $this->dieUsageMsg( array( 'badaccess-groups' ) );
92 }
93
94 $this->mUpload = new UploadFromUrl;
95 $async = $this->mParams['asyncdownload'] ? 'async' : null;
96
97 $result = $this->mUpload->initialize( $this->mParams['filename'],
98 $this->mParams['url'],
99 $this->mParams['comment'],
100 $this->mParams['watchlist'],
101 $this->mParams['ignorewarnings'],
102 $async );
103
104 $this->checkPermissions( $wgUser );
105 if ( $async ) {
106 $this->getResult()->addValue( null,
107 $this->getModuleName(),
108 array( 'queued' => $result ) );
109 return;
110 }
111
112 $status = $this->mUpload->retrieveFileFromUrl();
113 if ( !$status->isGood() ) {
114 $this->getResult()->addValue( null,
115 $this->getModuleName(),
116 array( 'error' => $status ) );
117 return;
118 }
119 }
120 } else {
121 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
122 }
123
124 $this->checkPermissions( $wgUser );
125
126 if ( !isset( $this->mUpload ) ) {
127 $this->dieUsage( 'No upload module set', 'nomodule' );
128 }
129
130 // Perform the upload
131 $result = $this->performUpload();
132
133 // Cleanup any temporary mess
134 $this->mUpload->cleanupTempFile();
135
136 $this->getResult()->addValue( null, $this->getModuleName(), $result );
137 }
138
139 /**
140 * Checks that the user has permissions to perform this upload.
141 * Dies with usage message on inadequate permissions.
142 * @param $user User The user to check.
143 */
144 protected function checkPermissions( $user ) {
145 // Check whether the user has the appropriate permissions to upload anyway
146 $permission = $this->mUpload->isAllowed( $user );
147
148 if ( $permission !== true ) {
149 if ( !$user->isLoggedIn() ) {
150 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
151 } else {
152 $this->dieUsageMsg( array( 'badaccess-groups' ) );
153 }
154 }
155 }
156
157 /**
158 * Performs file verification, dies on error.
159 *
160 * @param $flag integer passed to UploadBase::verifyUpload, set to
161 * UploadBase::EMPTY_FILE to skip the empty file check.
162 */
163 public function verifyUpload( $flag ) {
164 $verification = $this->mUpload->verifyUpload( $flag );
165 if ( $verification['status'] === UploadBase::OK ) {
166 return $verification;
167 }
168
169 $this->getVerificationError( $verification );
170 }
171
172 /**
173 * Produce the usage error
174 *
175 * @param $verification array an associative array with the status
176 * key
177 */
178 public function getVerificationError( $verification ) {
179 // TODO: Move them to ApiBase's message map
180 switch( $verification['status'] ) {
181 case UploadBase::EMPTY_FILE:
182 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
183 break;
184 case UploadBase::FILE_TOO_LARGE:
185 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
186 break;
187 case UploadBase::FILETYPE_MISSING:
188 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
189 break;
190 case UploadBase::FILETYPE_BADTYPE:
191 global $wgFileExtensions;
192 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
193 0, array(
194 'filetype' => $verification['finalExt'],
195 'allowed' => $wgFileExtensions
196 ) );
197 break;
198 case UploadBase::MIN_LENGTH_PARTNAME:
199 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
200 break;
201 case UploadBase::ILLEGAL_FILENAME:
202 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
203 0, array( 'filename' => $verification['filtered'] ) );
204 break;
205 case UploadBase::OVERWRITE_EXISTING_FILE:
206 $this->dieUsage( 'Overwriting an existing file is not allowed', 'overwrite' );
207 break;
208 case UploadBase::VERIFICATION_ERROR:
209 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
210 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
211 0, array( 'details' => $verification['details'] ) );
212 break;
213 case UploadBase::HOOK_ABORTED:
214 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
215 'hookaborted', 0, array( 'error' => $verification['error'] ) );
216 break;
217 default:
218 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
219 0, array( 'code' => $verification['status'] ) );
220 break;
221 }
222 }
223
224 protected function checkForWarnings() {
225 $result = array();
226
227 if ( !$this->mParams['ignorewarnings'] ) {
228 $warnings = $this->mUpload->checkWarnings();
229 if ( $warnings ) {
230 // Add indices
231 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
232
233 if ( isset( $warnings['duplicate'] ) ) {
234 $dupes = array();
235 foreach ( $warnings['duplicate'] as $key => $dupe )
236 $dupes[] = $dupe->getName();
237 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
238 $warnings['duplicate'] = $dupes;
239 }
240
241 if ( isset( $warnings['exists'] ) ) {
242 $warning = $warnings['exists'];
243 unset( $warnings['exists'] );
244 $warnings[$warning['warning']] = $warning['file']->getName();
245 }
246
247 $result['result'] = 'Warning';
248 $result['warnings'] = $warnings;
249
250 $sessionKey = $this->mUpload->stashSession();
251 if ( !$sessionKey ) {
252 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
253 }
254
255 $result['sessionkey'] = $sessionKey;
256
257 return $result;
258 }
259 }
260 return;
261 }
262
263 protected function performUpload() {
264 global $wgUser;
265 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
266 if ( $permErrors !== true ) {
267 $this->dieUsageMsg( array( 'badaccess-groups' ) );
268 }
269
270 $this->verifyUpload();
271
272 $warnings = $this->checkForWarnings();
273 if ( isset( $warnings ) ) {
274 return $warnings;
275 }
276
277 // Use comment as initial page text by default
278 if ( is_null( $this->mParams['text'] ) ) {
279 $this->mParams['text'] = $this->mParams['comment'];
280 }
281
282 $file = $this->mUpload->getLocalFile();
283 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
284
285 // Deprecated parameters
286 if ( $this->mParams['watch'] ) {
287 $watch = true;
288 }
289
290 // No errors, no warnings: do the upload
291 $status = $this->mUpload->performUpload( $this->mParams['comment'],
292 $this->mParams['text'], $watch, $wgUser );
293
294 if ( !$status->isGood() ) {
295 $error = $status->getErrorsArray();
296 $this->getResult()->setIndexedTagName( $result['details'], 'error' );
297
298 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
299 }
300
301 $file = $this->mUpload->getLocalFile();
302
303 $result['result'] = 'Success';
304 $result['filename'] = $file->getName();
305 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
306
307 return $result;
308 }
309
310 public function mustBePosted() {
311 return true;
312 }
313
314 public function isWriteMode() {
315 return true;
316 }
317
318 public function getAllowedParams() {
319 $params = array(
320 'filename' => null,
321 'comment' => array(
322 ApiBase::PARAM_DFLT => ''
323 ),
324 'text' => null,
325 'token' => null,
326 'watch' => array(
327 ApiBase::PARAM_DFLT => false,
328 ApiBase::PARAM_DEPRECATED => true,
329 ),
330 'watchlist' => array(
331 ApiBase::PARAM_DFLT => 'preferences',
332 ApiBase::PARAM_TYPE => array(
333 'watch',
334 'preferences',
335 'nochange'
336 ),
337 ),
338 'ignorewarnings' => false,
339 'file' => null,
340 'url' => null,
341 'asyncdownload' => false,
342 'sessionkey' => null,
343 );
344 return $params;
345 }
346
347 public function getParamDescription() {
348 return array(
349 'filename' => 'Target filename',
350 'token' => 'Edit token. You can get one of these through prop=info',
351 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
352 'text' => 'Initial page text for new files',
353 'watch' => 'Watch the page',
354 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
355 'ignorewarnings' => 'Ignore any warnings',
356 'file' => 'File contents',
357 'url' => 'Url to fetch the file from',
358 'asyncdownload' => 'Make fetching a URL asyncronous',
359 'sessionkey' => array(
360 'Session key returned by a previous upload that failed due to warnings',
361 ),
362 );
363 }
364
365 public function getDescription() {
366 return array(
367 'Upload a file, or get the status of pending uploads. Several methods are available:',
368 ' * Upload file contents directly, using the "file" parameter',
369 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
370 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
371 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
372 'sending the "file". Note also that queries using session keys must be',
373 'done in the same login session as the query that originally returned the key (i.e. do not',
374 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
375 );
376 }
377
378 public function getPossibleErrors() {
379 return array_merge( parent::getPossibleErrors(), array(
380 array( 'uploaddisabled' ),
381 array( 'invalid-session-key' ),
382 array( 'uploaddisabled' ),
383 array( 'badaccess-groups' ),
384 array( 'missingparam', 'filename' ),
385 array( 'mustbeloggedin', 'upload' ),
386 array( 'badaccess-groups' ),
387 array( 'badaccess-groups' ),
388 array( 'code' => 'fetchfileerror', 'info' => '' ),
389 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
390 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
391 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
392 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
393 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
394 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
395 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
396 ) );
397 }
398
399 public function getTokenSalt() {
400 return '';
401 }
402
403 protected function getExamples() {
404 return array(
405 'Upload from a URL:',
406 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
407 'Complete an upload that failed due to warnings:',
408 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
409 );
410 }
411
412 public function getVersion() {
413 return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';
414 }
415 }