(bug 35885) remove api version string and parameter
[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 // Check if async mode is actually supported
55 $this->mParams['async'] = ( $this->mParams['async'] && !wfIsWindows() );
56 // Add the uploaded file to the params array
57 $this->mParams['file'] = $request->getFileName( 'file' );
58 $this->mParams['chunk'] = $request->getFileName( 'chunk' );
59
60 // Copy the session key to the file key, for backward compatibility.
61 if( !$this->mParams['filekey'] && $this->mParams['sessionkey'] ) {
62 $this->mParams['filekey'] = $this->mParams['sessionkey'];
63 }
64
65 // Select an upload module
66 if ( !$this->selectUploadModule() ) {
67 return; // not a true upload, but a status request or similar
68 } elseif ( !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 (usually a no-op)
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 if ( !$this->mUpload->getTitle() ) {
90 $this->dieUsage( 'Invalid file title supplied', 'internal-error' );
91 }
92 } elseif ( $this->mParams['async'] ) {
93 // defer verification to background process
94 } else {
95 $this->verifyUpload();
96 }
97
98 // Check if the user has the rights to modify or overwrite the requested title
99 // (This check is irrelevant if stashing is already requested, since the errors
100 // can always be fixed by changing the title)
101 if ( !$this->mParams['stash'] ) {
102 $permErrors = $this->mUpload->verifyTitlePermissions( $user );
103 if ( $permErrors !== true ) {
104 $this->dieRecoverableError( $permErrors[0], 'filename' );
105 }
106 }
107
108 // Get the result based on the current upload context:
109 $result = $this->getContextResult();
110 if ( $result['result'] === 'Success' ) {
111 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
112 }
113
114 $this->getResult()->addValue( null, $this->getModuleName(), $result );
115
116 // Cleanup any temporary mess
117 $this->mUpload->cleanupTempFile();
118 }
119
120 /**
121 * Get an uplaod result based on upload context
122 * @return array
123 */
124 private function getContextResult(){
125 $warnings = $this->getApiWarnings();
126 if ( $warnings && !$this->mParams['ignorewarnings'] ) {
127 // Get warnings formated in result array format
128 return $this->getWarningsResult( $warnings );
129 } elseif ( $this->mParams['chunk'] ) {
130 // Add chunk, and get result
131 return $this->getChunkResult( $warnings );
132 } elseif ( $this->mParams['stash'] ) {
133 // Stash the file and get stash result
134 return $this->getStashResult( $warnings );
135 }
136 // This is the most common case -- a normal upload with no warnings
137 // performUpload will return a formatted properly for the API with status
138 return $this->performUpload( $warnings );
139 }
140
141 /**
142 * Get Stash Result, throws an expetion if the file could not be stashed.
143 * @param $warnings array Array of Api upload warnings
144 * @return array
145 */
146 private function getStashResult( $warnings ){
147 $result = array ();
148 // Some uploads can request they be stashed, so as not to publish them immediately.
149 // In this case, a failure to stash ought to be fatal
150 try {
151 $result['result'] = 'Success';
152 $result['filekey'] = $this->performStash();
153 $result['sessionkey'] = $result['filekey']; // backwards compatibility
154 if ( $warnings && count( $warnings ) > 0 ) {
155 $result['warnings'] = $warnings;
156 }
157 } catch ( MWException $e ) {
158 $this->dieUsage( $e->getMessage(), 'stashfailed' );
159 }
160 return $result;
161 }
162
163 /**
164 * Get Warnings Result
165 * @param $warnings array Array of Api upload warnings
166 * @return array
167 */
168 private function getWarningsResult( $warnings ){
169 $result = array();
170 $result['result'] = 'Warning';
171 $result['warnings'] = $warnings;
172 // in case the warnings can be fixed with some further user action, let's stash this upload
173 // and return a key they can use to restart it
174 try {
175 $result['filekey'] = $this->performStash();
176 $result['sessionkey'] = $result['filekey']; // backwards compatibility
177 } catch ( MWException $e ) {
178 $result['warnings']['stashfailed'] = $e->getMessage();
179 }
180 return $result;
181 }
182
183 /**
184 * Get the result of a chunk upload.
185 * @param $warnings array Array of Api upload warnings
186 * @return array
187 */
188 private function getChunkResult( $warnings ) {
189 global $IP;
190
191 $result = array();
192
193 $result['result'] = 'Continue';
194 if ( $warnings && count( $warnings ) > 0 ) {
195 $result['warnings'] = $warnings;
196 }
197 $request = $this->getMain()->getRequest();
198 $chunkPath = $request->getFileTempname( 'chunk' );
199 $chunkSize = $request->getUpload( 'chunk' )->getSize();
200 if ($this->mParams['offset'] == 0) {
201 $result['filekey'] = $this->performStash();
202 } else {
203 $status = $this->mUpload->addChunk(
204 $chunkPath, $chunkSize, $this->mParams['offset'] );
205 if ( !$status->isGood() ) {
206 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
207 return array();
208 }
209
210 // Check we added the last chunk:
211 if( $this->mParams['offset'] + $chunkSize == $this->mParams['filesize'] ) {
212 if ( $this->mParams['async'] && !wfIsWindows() ) {
213 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
214 if ( $progress && $progress['result'] === 'Poll' ) {
215 $this->dieUsage( "Chunk assembly already in progress.", 'stashfailed' );
216 }
217 UploadBase::setSessionStatus(
218 $this->mParams['filekey'],
219 array( 'result' => 'Poll',
220 'stage' => 'queued', 'status' => Status::newGood() )
221 );
222 $retVal = 1;
223 $cmd = wfShellWikiCmd(
224 "$IP/includes/upload/AssembleUploadChunks.php",
225 array(
226 '--wiki', wfWikiID(),
227 '--filename', $this->mParams['filename'],
228 '--filekey', $this->mParams['filekey'],
229 '--userid', $this->getUser()->getId(),
230 '--sessionid', session_id(),
231 '--quiet'
232 )
233 ) . " < " . wfGetNull() . " > " . wfGetNull() . " 2>&1 &";
234 // Start a process in the background. Enforce the time limits via PHP
235 // since ulimit4.sh seems to often not work for this particular usage.
236 wfShellExec( $cmd, $retVal, array(), array( 'time' => 0, 'memory' => 0 ) );
237 if ( $retVal == 0 ) {
238 $result['result'] = 'Poll';
239 } else {
240 UploadBase::setSessionStatus( $this->mParams['filekey'], false );
241 $this->dieUsage(
242 "Failed to start AssembleUploadChunks.php", 'stashfailed' );
243 }
244 } else {
245 $status = $this->mUpload->concatenateChunks();
246 if ( !$status->isGood() ) {
247 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
248 return array();
249 }
250
251 // We have a new filekey for the fully concatenated file.
252 $result['filekey'] = $this->mUpload->getLocalFile()->getFileKey();
253
254 // Remove chunk from stash. (Checks against user ownership of chunks.)
255 $this->mUpload->stash->removeFile( $this->mParams['filekey'] );
256
257 $result['result'] = 'Success';
258 }
259 } else {
260 // Continue passing through the filekey for adding further chunks.
261 $result['filekey'] = $this->mParams['filekey'];
262 }
263 }
264 $result['offset'] = $this->mParams['offset'] + $chunkSize;
265 return $result;
266 }
267
268 /**
269 * Stash the file and return the file key
270 * Also re-raises exceptions with slightly more informative message strings (useful for API)
271 * @throws MWException
272 * @return String file key
273 */
274 private function performStash() {
275 try {
276 $stashFile = $this->mUpload->stashFile();
277
278 if ( !$stashFile ) {
279 throw new MWException( 'Invalid stashed file' );
280 }
281 $fileKey = $stashFile->getFileKey();
282 } catch ( MWException $e ) {
283 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
284 wfDebug( __METHOD__ . ' ' . $message . "\n");
285 throw new MWException( $message );
286 }
287 return $fileKey;
288 }
289
290 /**
291 * Throw an error that the user can recover from by providing a better
292 * value for $parameter
293 *
294 * @param $error array Error array suitable for passing to dieUsageMsg()
295 * @param $parameter string Parameter that needs revising
296 * @param $data array Optional extra data to pass to the user
297 * @throws UsageException
298 */
299 private function dieRecoverableError( $error, $parameter, $data = array() ) {
300 try {
301 $data['filekey'] = $this->performStash();
302 $data['sessionkey'] = $data['filekey'];
303 } catch ( MWException $e ) {
304 $data['stashfailed'] = $e->getMessage();
305 }
306 $data['invalidparameter'] = $parameter;
307
308 $parsed = $this->parseMsg( $error );
309 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
310 }
311
312 /**
313 * Select an upload module and set it to mUpload. Dies on failure. If the
314 * request was a status request and not a true upload, returns false;
315 * otherwise true
316 *
317 * @return bool
318 */
319 protected function selectUploadModule() {
320 $request = $this->getMain()->getRequest();
321
322 // chunk or one and only one of the following parameters is needed
323 if ( !$this->mParams['chunk'] ) {
324 $this->requireOnlyOneParameter( $this->mParams,
325 'filekey', 'file', 'url', 'statuskey' );
326 }
327
328 // Status report for "upload to stash"/"upload from stash"
329 if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
330 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
331 if ( !$progress ) {
332 $this->dieUsage( 'No result in status data', 'missingresult' );
333 } elseif ( !$progress['status']->isGood() ) {
334 $this->dieUsage( $progress['status']->getWikiText(), 'stashfailed' );
335 }
336 if ( isset( $progress['status']->value['verification'] ) ) {
337 $this->checkVerification( $progress['status']->value['verification'] );
338 }
339 unset( $progress['status'] ); // remove Status object
340 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
341 return false;
342 }
343
344 if ( $this->mParams['statuskey'] ) {
345 $this->checkAsyncDownloadEnabled();
346
347 // Status request for an async upload
348 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
349 if ( !isset( $sessionData['result'] ) ) {
350 $this->dieUsage( 'No result in session data', 'missingresult' );
351 }
352 if ( $sessionData['result'] == 'Warning' ) {
353 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
354 $sessionData['sessionkey'] = $this->mParams['statuskey'];
355 }
356 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
357 return false;
358 }
359
360 // The following modules all require the filename parameter to be set
361 if ( is_null( $this->mParams['filename'] ) ) {
362 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
363 }
364
365 if ( $this->mParams['chunk'] ) {
366 // Chunk upload
367 $this->mUpload = new UploadFromChunks();
368 if( isset( $this->mParams['filekey'] ) ){
369 // handle new chunk
370 $this->mUpload->continueChunks(
371 $this->mParams['filename'],
372 $this->mParams['filekey'],
373 $request->getUpload( 'chunk' )
374 );
375 } else {
376 // handle first chunk
377 $this->mUpload->initialize(
378 $this->mParams['filename'],
379 $request->getUpload( 'chunk' )
380 );
381 }
382 } elseif ( isset( $this->mParams['filekey'] ) ) {
383 // Upload stashed in a previous request
384 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
385 $this->dieUsageMsg( 'invalid-file-key' );
386 }
387
388 $this->mUpload = new UploadFromStash( $this->getUser() );
389 // This will not download the temp file in initialize() in async mode.
390 // We still have enough information to call checkWarnings() and such.
391 $this->mUpload->initialize(
392 $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
393 );
394 } elseif ( isset( $this->mParams['file'] ) ) {
395 $this->mUpload = new UploadFromFile();
396 $this->mUpload->initialize(
397 $this->mParams['filename'],
398 $request->getUpload( 'file' )
399 );
400 } elseif ( isset( $this->mParams['url'] ) ) {
401 // Make sure upload by URL is enabled:
402 if ( !UploadFromUrl::isEnabled() ) {
403 $this->dieUsageMsg( 'copyuploaddisabled' );
404 }
405
406 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
407 $this->dieUsageMsg( 'copyuploadbaddomain' );
408 }
409
410 $async = false;
411 if ( $this->mParams['asyncdownload'] ) {
412 $this->checkAsyncDownloadEnabled();
413
414 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
415 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
416 'missing-ignorewarnings' );
417 }
418
419 if ( $this->mParams['leavemessage'] ) {
420 $async = 'async-leavemessage';
421 } else {
422 $async = 'async';
423 }
424 }
425 $this->mUpload = new UploadFromUrl;
426 $this->mUpload->initialize( $this->mParams['filename'],
427 $this->mParams['url'], $async );
428 }
429
430 return true;
431 }
432
433 /**
434 * Checks that the user has permissions to perform this upload.
435 * Dies with usage message on inadequate permissions.
436 * @param $user User The user to check.
437 */
438 protected function checkPermissions( $user ) {
439 // Check whether the user has the appropriate permissions to upload anyway
440 $permission = $this->mUpload->isAllowed( $user );
441
442 if ( $permission !== true ) {
443 if ( !$user->isLoggedIn() ) {
444 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
445 } else {
446 $this->dieUsageMsg( 'badaccess-groups' );
447 }
448 }
449 }
450
451 /**
452 * Performs file verification, dies on error.
453 */
454 protected function verifyUpload( ) {
455 $verification = $this->mUpload->verifyUpload( );
456 if ( $verification['status'] === UploadBase::OK ) {
457 return;
458 } else {
459 return $this->checkVerification( $verification );
460 }
461 }
462
463 /**
464 * Performs file verification, dies on error.
465 */
466 protected function checkVerification( array $verification ) {
467 global $wgFileExtensions;
468
469 // TODO: Move them to ApiBase's message map
470 switch( $verification['status'] ) {
471 // Recoverable errors
472 case UploadBase::MIN_LENGTH_PARTNAME:
473 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
474 break;
475 case UploadBase::ILLEGAL_FILENAME:
476 $this->dieRecoverableError( 'illegal-filename', 'filename',
477 array( 'filename' => $verification['filtered'] ) );
478 break;
479 case UploadBase::FILENAME_TOO_LONG:
480 $this->dieRecoverableError( 'filename-toolong', 'filename' );
481 break;
482 case UploadBase::FILETYPE_MISSING:
483 $this->dieRecoverableError( 'filetype-missing', 'filename' );
484 break;
485 case UploadBase::WINDOWS_NONASCII_FILENAME:
486 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
487 break;
488
489 // Unrecoverable errors
490 case UploadBase::EMPTY_FILE:
491 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
492 break;
493 case UploadBase::FILE_TOO_LARGE:
494 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
495 break;
496
497 case UploadBase::FILETYPE_BADTYPE:
498 $extradata = array(
499 'filetype' => $verification['finalExt'],
500 'allowed' => $wgFileExtensions
501 );
502 $this->getResult()->setIndexedTagName( $extradata['allowed'], 'ext' );
503
504 $msg = "Filetype not permitted: ";
505 if ( isset( $verification['blacklistedExt'] ) ) {
506 $msg .= join( ', ', $verification['blacklistedExt'] );
507 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
508 $this->getResult()->setIndexedTagName( $extradata['blacklisted'], 'ext' );
509 } else {
510 $msg .= $verification['finalExt'];
511 }
512 $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
513 break;
514 case UploadBase::VERIFICATION_ERROR:
515 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
516 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
517 0, array( 'details' => $verification['details'] ) );
518 break;
519 case UploadBase::HOOK_ABORTED:
520 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
521 'hookaborted', 0, array( 'error' => $verification['error'] ) );
522 break;
523 default:
524 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
525 0, array( 'code' => $verification['status'] ) );
526 break;
527 }
528 }
529
530
531 /**
532 * Check warnings.
533 * Returns a suitable array for inclusion into API results if there were warnings
534 * Returns the empty array if there were no warnings
535 *
536 * @return array
537 */
538 protected function getApiWarnings() {
539 $warnings = $this->mUpload->checkWarnings();
540
541 return $this->transformWarnings( $warnings );
542 }
543
544 protected function transformWarnings( $warnings ) {
545 if ( $warnings ) {
546 // Add indices
547 $result = $this->getResult();
548 $result->setIndexedTagName( $warnings, 'warning' );
549
550 if ( isset( $warnings['duplicate'] ) ) {
551 $dupes = array();
552 foreach ( $warnings['duplicate'] as $dupe ) {
553 $dupes[] = $dupe->getName();
554 }
555 $result->setIndexedTagName( $dupes, 'duplicate' );
556 $warnings['duplicate'] = $dupes;
557 }
558
559 if ( isset( $warnings['exists'] ) ) {
560 $warning = $warnings['exists'];
561 unset( $warnings['exists'] );
562 $warnings[$warning['warning']] = $warning['file']->getName();
563 }
564 }
565 return $warnings;
566 }
567
568
569 /**
570 * Perform the actual upload. Returns a suitable result array on success;
571 * dies on failure.
572 *
573 * @param $warnings array Array of Api upload warnings
574 * @return array
575 */
576 protected function performUpload( $warnings ) {
577 global $IP;
578
579 // Use comment as initial page text by default
580 if ( is_null( $this->mParams['text'] ) ) {
581 $this->mParams['text'] = $this->mParams['comment'];
582 }
583
584 $file = $this->mUpload->getLocalFile();
585 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
586
587 // Deprecated parameters
588 if ( $this->mParams['watch'] ) {
589 $watch = true;
590 }
591
592 // No errors, no warnings: do the upload
593 if ( $this->mParams['async'] ) {
594 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
595 if ( $progress && $progress['result'] === 'Poll' ) {
596 $this->dieUsage( "Upload from stash already in progress.", 'publishfailed' );
597 }
598 UploadBase::setSessionStatus(
599 $this->mParams['filekey'],
600 array( 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() )
601 );
602 $retVal = 1;
603 $cmd = wfShellWikiCmd(
604 "$IP/includes/upload/PublishStashedFile.php",
605 array(
606 '--wiki', wfWikiID(),
607 '--filename', $this->mParams['filename'],
608 '--filekey', $this->mParams['filekey'],
609 '--userid', $this->getUser()->getId(),
610 '--comment', $this->mParams['comment'],
611 '--text', $this->mParams['text'],
612 '--watch', $watch,
613 '--sessionid', session_id(),
614 '--quiet'
615 )
616 ) . " < " . wfGetNull() . " > " . wfGetNull() . " 2>&1 &";
617 // Start a process in the background. Enforce the time limits via PHP
618 // since ulimit4.sh seems to often not work for this particular usage.
619 wfShellExec( $cmd, $retVal, array(), array( 'time' => 0, 'memory' => 0 ) );
620 if ( $retVal == 0 ) {
621 $result['result'] = 'Poll';
622 } else {
623 UploadBase::setSessionStatus( $this->mParams['filekey'], false );
624 $this->dieUsage(
625 "Failed to start PublishStashedFile.php", 'publishfailed' );
626 }
627 } else {
628 $status = $this->mUpload->performUpload( $this->mParams['comment'],
629 $this->mParams['text'], $watch, $this->getUser() );
630
631 if ( !$status->isGood() ) {
632 $error = $status->getErrorsArray();
633
634 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
635 // The upload can not be performed right now, because the user
636 // requested so
637 return array(
638 'result' => 'Queued',
639 'statuskey' => $error[0][1],
640 );
641 } else {
642 $this->getResult()->setIndexedTagName( $error, 'error' );
643
644 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
645 }
646 }
647 $result['result'] = 'Success';
648 }
649
650 $result['filename'] = $file->getName();
651 if ( $warnings && count( $warnings ) > 0 ) {
652 $result['warnings'] = $warnings;
653 }
654
655 return $result;
656 }
657
658 /**
659 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
660 */
661 protected function checkAsyncDownloadEnabled() {
662 global $wgAllowAsyncCopyUploads;
663 if ( !$wgAllowAsyncCopyUploads ) {
664 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
665 }
666 }
667
668 public function mustBePosted() {
669 return true;
670 }
671
672 public function isWriteMode() {
673 return true;
674 }
675
676 public function getAllowedParams() {
677 $params = array(
678 'filename' => array(
679 ApiBase::PARAM_TYPE => 'string',
680 ),
681 'comment' => array(
682 ApiBase::PARAM_DFLT => ''
683 ),
684 'text' => null,
685 'token' => array(
686 ApiBase::PARAM_TYPE => 'string',
687 ApiBase::PARAM_REQUIRED => true
688 ),
689 'watch' => array(
690 ApiBase::PARAM_DFLT => false,
691 ApiBase::PARAM_DEPRECATED => true,
692 ),
693 'watchlist' => array(
694 ApiBase::PARAM_DFLT => 'preferences',
695 ApiBase::PARAM_TYPE => array(
696 'watch',
697 'preferences',
698 'nochange'
699 ),
700 ),
701 'ignorewarnings' => false,
702 'file' => null,
703 'url' => null,
704 'filekey' => null,
705 'sessionkey' => array(
706 ApiBase::PARAM_DFLT => null,
707 ApiBase::PARAM_DEPRECATED => true,
708 ),
709 'stash' => false,
710
711 'filesize' => null,
712 'offset' => null,
713 'chunk' => null,
714
715 'async' => false,
716 'asyncdownload' => false,
717 'leavemessage' => false,
718 'statuskey' => null,
719 'checkstatus' => false,
720 );
721
722 return $params;
723 }
724
725 public function getParamDescription() {
726 $params = array(
727 'filename' => 'Target filename',
728 'token' => 'Edit token. You can get one of these through prop=info',
729 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
730 'text' => 'Initial page text for new files',
731 'watch' => 'Watch the page',
732 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
733 'ignorewarnings' => 'Ignore any warnings',
734 'file' => 'File contents',
735 'url' => 'URL to fetch the file from',
736 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
737 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
738 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
739
740 'chunk' => 'Chunk contents',
741 'offset' => 'Offset of chunk in bytes',
742 'filesize' => 'Filesize of entire upload',
743
744 'async' => 'Make potentially large file operations asynchronous when possible',
745 'asyncdownload' => 'Make fetching a URL asynchronous',
746 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
747 'statuskey' => 'Fetch the upload status for this file key (upload by URL)',
748 'checkstatus' => 'Only fetch the upload status for the given file key',
749 );
750
751 return $params;
752
753 }
754
755 public function getResultProperties() {
756 return array(
757 '' => array(
758 'result' => array(
759 ApiBase::PROP_TYPE => array(
760 'Success',
761 'Warning',
762 'Continue',
763 'Queued'
764 ),
765 ),
766 'filekey' => array(
767 ApiBase::PROP_TYPE => 'string',
768 ApiBase::PROP_NULLABLE => true
769 ),
770 'sessionkey' => array(
771 ApiBase::PROP_TYPE => 'string',
772 ApiBase::PROP_NULLABLE => true
773 ),
774 'offset' => array(
775 ApiBase::PROP_TYPE => 'integer',
776 ApiBase::PROP_NULLABLE => true
777 ),
778 'statuskey' => array(
779 ApiBase::PROP_TYPE => 'string',
780 ApiBase::PROP_NULLABLE => true
781 ),
782 'filename' => array(
783 ApiBase::PROP_TYPE => 'string',
784 ApiBase::PROP_NULLABLE => true
785 )
786 )
787 );
788 }
789
790 public function getDescription() {
791 return array(
792 'Upload a file, or get the status of pending uploads. Several methods are available:',
793 ' * Upload file contents directly, using the "file" parameter',
794 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
795 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
796 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
797 'sending the "file". Also you must get and send an edit token before doing any upload stuff'
798 );
799 }
800
801 public function getPossibleErrors() {
802 return array_merge( parent::getPossibleErrors(),
803 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
804 array(
805 array( 'uploaddisabled' ),
806 array( 'invalid-file-key' ),
807 array( 'uploaddisabled' ),
808 array( 'mustbeloggedin', 'upload' ),
809 array( 'badaccess-groups' ),
810 array( 'code' => 'fetchfileerror', 'info' => '' ),
811 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
812 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
813 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
814 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
815 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
816 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
817 array( 'code' => 'publishfailed', 'info' => 'Publishing of stashed file failed' ),
818 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
819 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
820 array( 'fileexists-forbidden' ),
821 array( 'fileexists-shared-forbidden' ),
822 )
823 );
824 }
825
826 public function needsToken() {
827 return true;
828 }
829
830 public function getTokenSalt() {
831 return '';
832 }
833
834 public function getExamples() {
835 return array(
836 'api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png'
837 => 'Upload from a URL',
838 'api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1'
839 => 'Complete an upload that failed due to warnings',
840 );
841 }
842
843 public function getHelpUrls() {
844 return 'https://www.mediawiki.org/wiki/API:Upload';
845 }
846 }