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