46043a738f13ff60cedff074063023f39380c95e
[lhc/web/wiklou.git] / includes / api / ApiUpload.php
1 <?php
2 /**
3 *
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
37 /**
38 * @var UploadBase
39 */
40 protected $mUpload = null;
41
42 protected $mParams;
43
44 public function __construct( $main, $action ) {
45 parent::__construct( $main, $action );
46 }
47
48 public function execute() {
49 global $wgUser;
50
51 // Check whether upload is enabled
52 if ( !UploadBase::isEnabled() ) {
53 $this->dieUsageMsg( array( 'uploaddisabled' ) );
54 }
55
56 // Parameter handling
57 $this->mParams = $this->extractRequestParams();
58 $request = $this->getMain()->getRequest();
59 // Add the uploaded file to the params array
60 $this->mParams['file'] = $request->getFileName( 'file' );
61
62 // Select an upload module
63 if ( !$this->selectUploadModule() ) {
64 // This is not a true upload, but a status request or similar
65 return;
66 }
67 if ( !isset( $this->mUpload ) ) {
68 $this->dieUsage( 'No upload module set', 'nomodule' );
69 }
70
71 // First check permission to upload
72 $this->checkPermissions( $wgUser );
73
74 // Fetch the file
75 $status = $this->mUpload->fetchFile();
76 if ( !$status->isGood() ) {
77 $errors = $status->getErrorsArray();
78 $error = array_shift( $errors[0] );
79 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
80 }
81
82 // Check if the uploaded file is sane
83 $this->verifyUpload();
84
85
86 // Check if the user has the rights to modify or overwrite the requested title
87 // (This check is irrelevant if stashing is already requested, since the errors
88 // can always be fixed by changing the title)
89 if ( ! $this->mParams['stash'] ) {
90 $permErrors = $this->mUpload->verifyTitlePermissions( $wgUser );
91 if ( $permErrors !== true ) {
92 $this->dieRecoverableError( $permErrors[0], 'filename' );
93 }
94 }
95
96 // Prepare the API result
97 $result = array();
98
99 $warnings = $this->getApiWarnings();
100 if ( $warnings ) {
101 $result['result'] = 'Warning';
102 $result['warnings'] = $warnings;
103 // in case the warnings can be fixed with some further user action, let's stash this upload
104 // and return a key they can use to restart it
105 try {
106 $result['sessionkey'] = $this->performStash();
107 } catch ( MWException $e ) {
108 $result['warnings']['stashfailed'] = $e->getMessage();
109 }
110 } elseif ( $this->mParams['stash'] ) {
111 // Some uploads can request they be stashed, so as not to publish them immediately.
112 // In this case, a failure to stash ought to be fatal
113 try {
114 $result['result'] = 'Success';
115 $result['sessionkey'] = $this->performStash();
116 } catch ( MWException $e ) {
117 $this->dieUsage( $e->getMessage(), 'stashfailed' );
118 }
119 } else {
120 // This is the most common case -- a normal upload with no warnings
121 // $result will be formatted properly for the API already, with a status
122 $result = $this->performUpload();
123 }
124
125 if ( $result['result'] === 'Success' ) {
126 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
127 }
128
129 $this->getResult()->addValue( null, $this->getModuleName(), $result );
130
131 // Cleanup any temporary mess
132 $this->mUpload->cleanupTempFile();
133 }
134
135 /**
136 * Stash the file and return the session key
137 * Also re-raises exceptions with slightly more informative message strings (useful for API)
138 * @throws MWException
139 * @return {String} session key
140 */
141 function performStash() {
142 try {
143 $sessionKey = $this->mUpload->stashSessionFile()->getSessionKey();
144 } catch ( MWException $e ) {
145 throw new MWException( 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage() );
146 }
147 return $sessionKey;
148 }
149
150 /**
151 * Throw an error that the user can recover from by providing a better
152 * value for $parameter
153 *
154 * @param $error array Error array suitable for passing to dieUsageMsg()
155 * @param $parameter string Parameter that needs revising
156 * @param $data array Optional extra data to pass to the user
157 * @throws UsageException
158 */
159 function dieRecoverableError( $error, $parameter, $data = array() ) {
160 try {
161 $data['sessionkey'] = $this->performStash();
162 } catch ( MWException $e ) {
163 $data['stashfailed'] = $e->getMessage();
164 }
165 $data['invalidparameter'] = $parameter;
166
167 $parsed = $this->parseMsg( $error );
168 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
169 }
170
171 /**
172 * Select an upload module and set it to mUpload. Dies on failure. If the
173 * request was a status request and not a true upload, returns false;
174 * otherwise true
175 *
176 * @return bool
177 */
178 protected function selectUploadModule() {
179 $request = $this->getMain()->getRequest();
180
181 // One and only one of the following parameters is needed
182 $this->requireOnlyOneParameter( $this->mParams,
183 'sessionkey', 'file', 'url', 'statuskey' );
184
185 if ( $this->mParams['statuskey'] ) {
186 $this->checkAsyncDownloadEnabled();
187
188 // Status request for an async upload
189 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
190 if ( !isset( $sessionData['result'] ) ) {
191 $this->dieUsage( 'No result in session data', 'missingresult' );
192 }
193 if ( $sessionData['result'] == 'Warning' ) {
194 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
195 $sessionData['sessionkey'] = $this->mParams['statuskey'];
196 }
197 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
198 return false;
199
200 }
201
202 // The following modules all require the filename parameter to be set
203 if ( is_null( $this->mParams['filename'] ) ) {
204 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
205 }
206
207 if ( $this->mParams['sessionkey'] ) {
208 // Upload stashed in a previous request
209 $sessionData = $request->getSessionData( UploadBase::getSessionKeyName() );
210 if ( !UploadFromStash::isValidSessionKey( $this->mParams['sessionkey'], $sessionData ) ) {
211 $this->dieUsageMsg( array( 'invalid-session-key' ) );
212 }
213
214 $this->mUpload = new UploadFromStash();
215 $this->mUpload->initialize( $this->mParams['filename'],
216 $this->mParams['sessionkey'],
217 $sessionData[$this->mParams['sessionkey']] );
218
219 } elseif ( isset( $this->mParams['file'] ) ) {
220 $this->mUpload = new UploadFromFile();
221 $this->mUpload->initialize(
222 $this->mParams['filename'],
223 $request->getUpload( 'file' )
224 );
225 } elseif ( isset( $this->mParams['url'] ) ) {
226 // Make sure upload by URL is enabled:
227 if ( !UploadFromUrl::isEnabled() ) {
228 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
229 }
230
231 $async = false;
232 if ( $this->mParams['asyncdownload'] ) {
233 $this->checkAsyncDownloadEnabled();
234
235 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
236 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
237 'missing-ignorewarnings' );
238 }
239
240 if ( $this->mParams['leavemessage'] ) {
241 $async = 'async-leavemessage';
242 } else {
243 $async = 'async';
244 }
245 }
246 $this->mUpload = new UploadFromUrl;
247 $this->mUpload->initialize( $this->mParams['filename'],
248 $this->mParams['url'], $async );
249
250 }
251
252 return true;
253 }
254
255 /**
256 * Checks that the user has permissions to perform this upload.
257 * Dies with usage message on inadequate permissions.
258 * @param $user User The user to check.
259 */
260 protected function checkPermissions( $user ) {
261 // Check whether the user has the appropriate permissions to upload anyway
262 $permission = $this->mUpload->isAllowed( $user );
263
264 if ( $permission !== true ) {
265 if ( !$user->isLoggedIn() ) {
266 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
267 } else {
268 $this->dieUsageMsg( array( 'badaccess-groups' ) );
269 }
270 }
271 }
272
273 /**
274 * Performs file verification, dies on error.
275 */
276 protected function verifyUpload( ) {
277 global $wgFileExtensions;
278
279 $verification = $this->mUpload->verifyUpload( );
280 if ( $verification['status'] === UploadBase::OK ) {
281 return;
282 }
283
284 // TODO: Move them to ApiBase's message map
285 switch( $verification['status'] ) {
286 // Recoverable errors
287 case UploadBase::MIN_LENGTH_PARTNAME:
288 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
289 break;
290 case UploadBase::ILLEGAL_FILENAME:
291 $this->dieRecoverableError( 'illegal-filename', 'filename',
292 array( 'filename' => $verification['filtered'] ) );
293 break;
294 case UploadBase::FILETYPE_MISSING:
295 $this->dieRecoverableError( 'filetype-missing', 'filename' );
296 break;
297 case UploadBase::WINDOWS_NONASCII_FILENAME:
298 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
299 break;
300
301 // Unrecoverable errors
302 case UploadBase::EMPTY_FILE:
303 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
304 break;
305 case UploadBase::FILE_TOO_LARGE:
306 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
307 break;
308
309 case UploadBase::FILETYPE_BADTYPE:
310 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
311 0, array(
312 'filetype' => $verification['finalExt'],
313 'allowed' => $wgFileExtensions
314 ) );
315 break;
316 case UploadBase::VERIFICATION_ERROR:
317 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
318 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
319 0, array( 'details' => $verification['details'] ) );
320 break;
321 case UploadBase::HOOK_ABORTED:
322 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
323 'hookaborted', 0, array( 'error' => $verification['error'] ) );
324 break;
325 default:
326 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
327 0, array( 'code' => $verification['status'] ) );
328 break;
329 }
330 }
331
332
333 /**
334 * Check warnings if ignorewarnings is not set.
335 * Returns a suitable array for inclusion into API results if there were warnings
336 * Returns the empty array if there were no warnings
337 *
338 * @return array
339 */
340 protected function getApiWarnings() {
341 $warnings = array();
342
343 if ( !$this->mParams['ignorewarnings'] ) {
344 $warnings = $this->mUpload->checkWarnings();
345 }
346 return $this->transformWarnings( $warnings );
347 }
348
349 protected function transformWarnings( $warnings ) {
350 if ( $warnings ) {
351 // Add indices
352 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
353
354 if ( isset( $warnings['duplicate'] ) ) {
355 $dupes = array();
356 foreach ( $warnings['duplicate'] as $dupe ) {
357 $dupes[] = $dupe->getName();
358 }
359 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
360 $warnings['duplicate'] = $dupes;
361 }
362
363 if ( isset( $warnings['exists'] ) ) {
364 $warning = $warnings['exists'];
365 unset( $warnings['exists'] );
366 $warnings[$warning['warning']] = $warning['file']->getName();
367 }
368 }
369 return $warnings;
370 }
371
372
373 /**
374 * Perform the actual upload. Returns a suitable result array on success;
375 * dies on failure.
376 */
377 protected function performUpload() {
378 global $wgUser;
379
380 // Use comment as initial page text by default
381 if ( is_null( $this->mParams['text'] ) ) {
382 $this->mParams['text'] = $this->mParams['comment'];
383 }
384
385 $file = $this->mUpload->getLocalFile();
386 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
387
388 // Deprecated parameters
389 if ( $this->mParams['watch'] ) {
390 $watch = true;
391 }
392
393 // No errors, no warnings: do the upload
394 $status = $this->mUpload->performUpload( $this->mParams['comment'],
395 $this->mParams['text'], $watch, $wgUser );
396
397 if ( !$status->isGood() ) {
398 $error = $status->getErrorsArray();
399
400 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
401 // The upload can not be performed right now, because the user
402 // requested so
403 return array(
404 'result' => 'Queued',
405 'statuskey' => $error[0][1],
406 );
407 } else {
408 $this->getResult()->setIndexedTagName( $error, 'error' );
409
410 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
411 }
412 }
413
414 $file = $this->mUpload->getLocalFile();
415
416 $result['result'] = 'Success';
417 $result['filename'] = $file->getName();
418
419 return $result;
420 }
421
422 /**
423 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
424 */
425 protected function checkAsyncDownloadEnabled() {
426 global $wgAllowAsyncCopyUploads;
427 if ( !$wgAllowAsyncCopyUploads ) {
428 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
429 }
430 }
431
432 public function mustBePosted() {
433 return true;
434 }
435
436 public function isWriteMode() {
437 return true;
438 }
439
440 public function getAllowedParams() {
441 $params = array(
442 'filename' => array(
443 ApiBase::PARAM_TYPE => 'string',
444 ),
445 'comment' => array(
446 ApiBase::PARAM_DFLT => ''
447 ),
448 'text' => null,
449 'token' => null,
450 'watch' => array(
451 ApiBase::PARAM_DFLT => false,
452 ApiBase::PARAM_DEPRECATED => true,
453 ),
454 'watchlist' => array(
455 ApiBase::PARAM_DFLT => 'preferences',
456 ApiBase::PARAM_TYPE => array(
457 'watch',
458 'preferences',
459 'nochange'
460 ),
461 ),
462 'ignorewarnings' => false,
463 'file' => null,
464 'url' => null,
465 'sessionkey' => null,
466 'stash' => false,
467
468 'asyncdownload' => false,
469 'leavemessage' => false,
470 'statuskey' => null,
471 );
472
473 return $params;
474 }
475
476 public function getParamDescription() {
477 $params = array(
478 'filename' => 'Target filename',
479 'token' => 'Edit token. You can get one of these through prop=info',
480 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
481 'text' => 'Initial page text for new files',
482 'watch' => 'Watch the page',
483 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
484 'ignorewarnings' => 'Ignore any warnings',
485 'file' => 'File contents',
486 'url' => 'Url to fetch the file from',
487 'sessionkey' => 'Session key that identifies a previous upload that was stashed temporarily.',
488 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
489
490 'asyncdownload' => 'Make fetching a URL asynchronous',
491 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
492 'statuskey' => 'Fetch the upload status for this session key',
493 );
494
495 return $params;
496
497 }
498
499 public function getDescription() {
500 return array(
501 'Upload a file, or get the status of pending uploads. Several methods are available:',
502 ' * Upload file contents directly, using the "file" parameter',
503 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
504 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
505 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
506 'sending the "file". Note also that queries using session keys must be',
507 'done in the same login session as the query that originally returned the key (i.e. do not',
508 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
509 );
510 }
511
512 public function getPossibleErrors() {
513 return array_merge( parent::getPossibleErrors(),
514 $this->getRequireOnlyOneParameterErrorMessages( array( 'sessionkey', 'file', 'url', 'statuskey' ) ),
515 array(
516 array( 'uploaddisabled' ),
517 array( 'invalid-session-key' ),
518 array( 'uploaddisabled' ),
519 array( 'mustbeloggedin', 'upload' ),
520 array( 'badaccess-groups' ),
521 array( 'code' => 'fetchfileerror', 'info' => '' ),
522 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
523 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
524 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
525 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
526 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
527 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
528 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
529 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
530 )
531 );
532 }
533
534 public function needsToken() {
535 return true;
536 }
537
538 public function getTokenSalt() {
539 return '';
540 }
541
542 protected function getExamples() {
543 return array(
544 'Upload from a URL:',
545 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
546 'Complete an upload that failed due to warnings:',
547 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
548 );
549 }
550
551 public function getVersion() {
552 return __CLASS__ . ': $Id$';
553 }
554 }