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