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