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