MediaWiki REL1_31
ApiUpload.php
Go to the documentation of this file.
1<?php
26class ApiUpload extends ApiBase {
28 protected $mUpload = null;
29
30 protected $mParams;
31
32 public function execute() {
33 // Check whether upload is enabled
34 if ( !UploadBase::isEnabled() ) {
35 $this->dieWithError( 'uploaddisabled' );
36 }
37
38 $user = $this->getUser();
39
40 // Parameter handling
41 $this->mParams = $this->extractRequestParams();
42 $request = $this->getMain()->getRequest();
43 // Check if async mode is actually supported (jobs done in cli mode)
44 $this->mParams['async'] = ( $this->mParams['async'] &&
45 $this->getConfig()->get( 'EnableAsyncUploads' ) );
46 // Add the uploaded file to the params array
47 $this->mParams['file'] = $request->getFileName( 'file' );
48 $this->mParams['chunk'] = $request->getFileName( 'chunk' );
49
50 // Copy the session key to the file key, for backward compatibility.
51 if ( !$this->mParams['filekey'] && $this->mParams['sessionkey'] ) {
52 $this->mParams['filekey'] = $this->mParams['sessionkey'];
53 }
54
55 // Select an upload module
56 try {
57 if ( !$this->selectUploadModule() ) {
58 return; // not a true upload, but a status request or similar
59 } elseif ( !isset( $this->mUpload ) ) {
60 $this->dieDebug( __METHOD__, 'No upload module set' );
61 }
62 } catch ( UploadStashException $e ) { // XXX: don't spam exception log
63 $this->dieStatus( $this->handleStashException( $e ) );
64 }
65
66 // First check permission to upload
67 $this->checkPermissions( $user );
68
69 // Fetch the file (usually a no-op)
71 $status = $this->mUpload->fetchFile();
72 if ( !$status->isGood() ) {
73 $this->dieStatus( $status );
74 }
75
76 // Check if the uploaded file is sane
77 if ( $this->mParams['chunk'] ) {
79 if ( $this->mParams['filesize'] > $maxSize ) {
80 $this->dieWithError( 'file-too-large' );
81 }
82 if ( !$this->mUpload->getTitle() ) {
83 $this->dieWithError( 'illegal-filename' );
84 }
85 } elseif ( $this->mParams['async'] && $this->mParams['filekey'] ) {
86 // defer verification to background process
87 } else {
88 wfDebug( __METHOD__ . " about to verify\n" );
89 $this->verifyUpload();
90 }
91
92 // Check if the user has the rights to modify or overwrite the requested title
93 // (This check is irrelevant if stashing is already requested, since the errors
94 // can always be fixed by changing the title)
95 if ( !$this->mParams['stash'] ) {
96 $permErrors = $this->mUpload->verifyTitlePermissions( $user );
97 if ( $permErrors !== true ) {
98 $this->dieRecoverableError( $permErrors, 'filename' );
99 }
100 }
101
102 // Get the result based on the current upload context:
103 try {
104 $result = $this->getContextResult();
105 } catch ( UploadStashException $e ) { // XXX: don't spam exception log
106 $this->dieStatus( $this->handleStashException( $e ) );
107 }
108 $this->getResult()->addValue( null, $this->getModuleName(), $result );
109
110 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
111 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
112 if ( $result['result'] === 'Success' ) {
113 $imageinfo = $this->mUpload->getImageInfo( $this->getResult() );
114 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
115 }
116
117 // Cleanup any temporary mess
118 $this->mUpload->cleanupTempFile();
119 }
120
125 private function getContextResult() {
126 $warnings = $this->getApiWarnings();
127 if ( $warnings && !$this->mParams['ignorewarnings'] ) {
128 // Get warnings formatted 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
138 // Check throttle after we've handled warnings
139 if ( UploadBase::isThrottled( $this->getUser() )
140 ) {
141 $this->dieWithError( 'apierror-ratelimited' );
142 }
143
144 // This is the most common case -- a normal upload with no warnings
145 // performUpload will return a formatted properly for the API with status
146 return $this->performUpload( $warnings );
147 }
148
154 private function getStashResult( $warnings ) {
155 $result = [];
156 $result['result'] = 'Success';
157 if ( $warnings && count( $warnings ) > 0 ) {
158 $result['warnings'] = $warnings;
159 }
160 // Some uploads can request they be stashed, so as not to publish them immediately.
161 // In this case, a failure to stash ought to be fatal
162 $this->performStash( 'critical', $result );
163
164 return $result;
165 }
166
172 private function getWarningsResult( $warnings ) {
173 $result = [];
174 $result['result'] = 'Warning';
175 $result['warnings'] = $warnings;
176 // in case the warnings can be fixed with some further user action, let's stash this upload
177 // and return a key they can use to restart it
178 $this->performStash( 'optional', $result );
179
180 return $result;
181 }
182
188 private function getChunkResult( $warnings ) {
189 $result = [];
190
191 if ( $warnings && count( $warnings ) > 0 ) {
192 $result['warnings'] = $warnings;
193 }
194
195 $request = $this->getMain()->getRequest();
196 $chunkPath = $request->getFileTempname( 'chunk' );
197 $chunkSize = $request->getUpload( 'chunk' )->getSize();
198 $totalSoFar = $this->mParams['offset'] + $chunkSize;
199 $minChunkSize = $this->getConfig()->get( 'MinUploadChunkSize' );
200
201 // Sanity check sizing
202 if ( $totalSoFar > $this->mParams['filesize'] ) {
203 $this->dieWithError( 'apierror-invalid-chunk' );
204 }
205
206 // Enforce minimum chunk size
207 if ( $totalSoFar != $this->mParams['filesize'] && $chunkSize < $minChunkSize ) {
208 $this->dieWithError( [ 'apierror-chunk-too-small', Message::numParam( $minChunkSize ) ] );
209 }
210
211 if ( $this->mParams['offset'] == 0 ) {
212 $filekey = $this->performStash( 'critical' );
213 } else {
214 $filekey = $this->mParams['filekey'];
215
216 // Don't allow further uploads to an already-completed session
217 $progress = UploadBase::getSessionStatus( $this->getUser(), $filekey );
218 if ( !$progress ) {
219 // Probably can't get here, but check anyway just in case
220 $this->dieWithError( 'apierror-stashfailed-nosession', 'stashfailed' );
221 } elseif ( $progress['result'] !== 'Continue' || $progress['stage'] !== 'uploading' ) {
222 $this->dieWithError( 'apierror-stashfailed-complete', 'stashfailed' );
223 }
224
225 $status = $this->mUpload->addChunk(
226 $chunkPath, $chunkSize, $this->mParams['offset'] );
227 if ( !$status->isGood() ) {
228 $extradata = [
229 'offset' => $this->mUpload->getOffset(),
230 ];
231
232 $this->dieStatusWithCode( $status, 'stashfailed', $extradata );
233 }
234 }
235
236 // Check we added the last chunk:
237 if ( $totalSoFar == $this->mParams['filesize'] ) {
238 if ( $this->mParams['async'] ) {
240 $this->getUser(),
241 $filekey,
242 [ 'result' => 'Poll',
243 'stage' => 'queued', 'status' => Status::newGood() ]
244 );
246 Title::makeTitle( NS_FILE, $filekey ),
247 [
248 'filename' => $this->mParams['filename'],
249 'filekey' => $filekey,
250 'session' => $this->getContext()->exportSession()
251 ]
252 ) );
253 $result['result'] = 'Poll';
254 $result['stage'] = 'queued';
255 } else {
256 $status = $this->mUpload->concatenateChunks();
257 if ( !$status->isGood() ) {
259 $this->getUser(),
260 $filekey,
261 [ 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status ]
262 );
263 $this->dieStatusWithCode( $status, 'stashfailed' );
264 }
265
266 // We can only get warnings like 'duplicate' after concatenating the chunks
267 $warnings = $this->getApiWarnings();
268 if ( $warnings ) {
269 $result['warnings'] = $warnings;
270 }
271
272 // The fully concatenated file has a new filekey. So remove
273 // the old filekey and fetch the new one.
274 UploadBase::setSessionStatus( $this->getUser(), $filekey, false );
275 $this->mUpload->stash->removeFile( $filekey );
276 $filekey = $this->mUpload->getStashFile()->getFileKey();
277
278 $result['result'] = 'Success';
279 }
280 } else {
282 $this->getUser(),
283 $filekey,
284 [
285 'result' => 'Continue',
286 'stage' => 'uploading',
287 'offset' => $totalSoFar,
288 'status' => Status::newGood(),
289 ]
290 );
291 $result['result'] = 'Continue';
292 $result['offset'] = $totalSoFar;
293 }
294
295 $result['filekey'] = $filekey;
296
297 return $result;
298 }
299
312 private function performStash( $failureMode, &$data = null ) {
313 $isPartial = (bool)$this->mParams['chunk'];
314 try {
315 $status = $this->mUpload->tryStashFile( $this->getUser(), $isPartial );
316
317 if ( $status->isGood() && !$status->getValue() ) {
318 // Not actually a 'good' status...
319 $status->fatal( new ApiMessage( 'apierror-stashinvalidfile', 'stashfailed' ) );
320 }
321 } catch ( Exception $e ) {
322 $debugMessage = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
323 wfDebug( __METHOD__ . ' ' . $debugMessage . "\n" );
324 $status = Status::newFatal( $this->getErrorFormatter()->getMessageFromException(
325 $e, [ 'wrap' => new ApiMessage( 'apierror-stashexception', 'stashfailed' ) ]
326 ) );
327 }
328
329 if ( $status->isGood() ) {
330 $stashFile = $status->getValue();
331 $data['filekey'] = $stashFile->getFileKey();
332 // Backwards compatibility
333 $data['sessionkey'] = $data['filekey'];
334 return $data['filekey'];
335 }
336
337 if ( $status->getMessage()->getKey() === 'uploadstash-exception' ) {
338 // The exceptions thrown by upload stash code and pretty silly and UploadBase returns poor
339 // Statuses for it. Just extract the exception details and parse them ourselves.
340 list( $exceptionType, $message ) = $status->getMessage()->getParams();
341 $debugMessage = 'Stashing temporary file failed: ' . $exceptionType . ' ' . $message;
342 wfDebug( __METHOD__ . ' ' . $debugMessage . "\n" );
343 }
344
345 // Bad status
346 if ( $failureMode !== 'optional' ) {
347 $this->dieStatus( $status );
348 } else {
349 $data['stasherrors'] = $this->getErrorFormatter()->arrayFromStatus( $status );
350 return null;
351 }
352 }
353
363 private function dieRecoverableError( $errors, $parameter = null ) {
364 $this->performStash( 'optional', $data );
365
366 if ( $parameter ) {
367 $data['invalidparameter'] = $parameter;
368 }
369
370 $sv = StatusValue::newGood();
371 foreach ( $errors as $error ) {
372 $msg = ApiMessage::create( $error );
373 $msg->setApiData( $msg->getApiData() + $data );
374 $sv->fatal( $msg );
375 }
376 $this->dieStatus( $sv );
377 }
378
388 public function dieStatusWithCode( $status, $overrideCode, $moreExtraData = null ) {
389 $sv = StatusValue::newGood();
390 foreach ( $status->getErrors() as $error ) {
391 $msg = ApiMessage::create( $error, $overrideCode );
392 if ( $moreExtraData ) {
393 $msg->setApiData( $msg->getApiData() + $moreExtraData );
394 }
395 $sv->fatal( $msg );
396 }
397 $this->dieStatus( $sv );
398 }
399
407 protected function selectUploadModule() {
408 $request = $this->getMain()->getRequest();
409
410 // chunk or one and only one of the following parameters is needed
411 if ( !$this->mParams['chunk'] ) {
412 $this->requireOnlyOneParameter( $this->mParams,
413 'filekey', 'file', 'url' );
414 }
415
416 // Status report for "upload to stash"/"upload from stash"
417 if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
418 $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
419 if ( !$progress ) {
420 $this->dieWithError( 'api-upload-missingresult', 'missingresult' );
421 } elseif ( !$progress['status']->isGood() ) {
422 $this->dieStatusWithCode( $progress['status'], 'stashfailed' );
423 }
424 if ( isset( $progress['status']->value['verification'] ) ) {
425 $this->checkVerification( $progress['status']->value['verification'] );
426 }
427 if ( isset( $progress['status']->value['warnings'] ) ) {
428 $warnings = $this->transformWarnings( $progress['status']->value['warnings'] );
429 if ( $warnings ) {
430 $progress['warnings'] = $warnings;
431 }
432 }
433 unset( $progress['status'] ); // remove Status object
434 $imageinfo = null;
435 if ( isset( $progress['imageinfo'] ) ) {
436 $imageinfo = $progress['imageinfo'];
437 unset( $progress['imageinfo'] );
438 }
439
440 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
441 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
442 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
443 if ( $imageinfo ) {
444 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
445 }
446
447 return false;
448 }
449
450 // The following modules all require the filename parameter to be set
451 if ( is_null( $this->mParams['filename'] ) ) {
452 $this->dieWithError( [ 'apierror-missingparam', 'filename' ] );
453 }
454
455 if ( $this->mParams['chunk'] ) {
456 // Chunk upload
457 $this->mUpload = new UploadFromChunks( $this->getUser() );
458 if ( isset( $this->mParams['filekey'] ) ) {
459 if ( $this->mParams['offset'] === 0 ) {
460 $this->dieWithError( 'apierror-upload-filekeynotallowed', 'filekeynotallowed' );
461 }
462
463 // handle new chunk
464 $this->mUpload->continueChunks(
465 $this->mParams['filename'],
466 $this->mParams['filekey'],
467 $request->getUpload( 'chunk' )
468 );
469 } else {
470 if ( $this->mParams['offset'] !== 0 ) {
471 $this->dieWithError( 'apierror-upload-filekeyneeded', 'filekeyneeded' );
472 }
473
474 // handle first chunk
475 $this->mUpload->initialize(
476 $this->mParams['filename'],
477 $request->getUpload( 'chunk' )
478 );
479 }
480 } elseif ( isset( $this->mParams['filekey'] ) ) {
481 // Upload stashed in a previous request
482 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
483 $this->dieWithError( 'apierror-invalid-file-key' );
484 }
485
486 $this->mUpload = new UploadFromStash( $this->getUser() );
487 // This will not download the temp file in initialize() in async mode.
488 // We still have enough information to call checkWarnings() and such.
489 $this->mUpload->initialize(
490 $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
491 );
492 } elseif ( isset( $this->mParams['file'] ) ) {
493 // Can't async upload directly from a POSTed file, we'd have to
494 // stash the file and then queue the publish job. The user should
495 // just submit the two API queries to perform those two steps.
496 if ( $this->mParams['async'] ) {
497 $this->dieWithError( 'apierror-cannot-async-upload-file' );
498 }
499
500 $this->mUpload = new UploadFromFile();
501 $this->mUpload->initialize(
502 $this->mParams['filename'],
503 $request->getUpload( 'file' )
504 );
505 } elseif ( isset( $this->mParams['url'] ) ) {
506 // Make sure upload by URL is enabled:
507 if ( !UploadFromUrl::isEnabled() ) {
508 $this->dieWithError( 'copyuploaddisabled' );
509 }
510
511 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
512 $this->dieWithError( 'apierror-copyuploadbaddomain' );
513 }
514
515 if ( !UploadFromUrl::isAllowedUrl( $this->mParams['url'] ) ) {
516 $this->dieWithError( 'apierror-copyuploadbadurl' );
517 }
518
519 $this->mUpload = new UploadFromUrl;
520 $this->mUpload->initialize( $this->mParams['filename'],
521 $this->mParams['url'] );
522 }
523
524 return true;
525 }
526
532 protected function checkPermissions( $user ) {
533 // Check whether the user has the appropriate permissions to upload anyway
534 $permission = $this->mUpload->isAllowed( $user );
535
536 if ( $permission !== true ) {
537 if ( !$user->isLoggedIn() ) {
538 $this->dieWithError( [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ] );
539 }
540
541 $this->dieStatus( User::newFatalPermissionDeniedStatus( $permission ) );
542 }
543
544 // Check blocks
545 if ( $user->isBlocked() ) {
546 $this->dieBlocked( $user->getBlock() );
547 }
548
549 // Global blocks
550 if ( $user->isBlockedGlobally() ) {
551 $this->dieBlocked( $user->getGlobalBlock() );
552 }
553 }
554
558 protected function verifyUpload() {
559 $verification = $this->mUpload->verifyUpload();
560 if ( $verification['status'] === UploadBase::OK ) {
561 return;
562 }
563
564 $this->checkVerification( $verification );
565 }
566
571 protected function checkVerification( array $verification ) {
572 switch ( $verification['status'] ) {
573 // Recoverable errors
575 $this->dieRecoverableError( [ 'filename-tooshort' ], 'filename' );
576 break;
578 $this->dieRecoverableError(
580 'illegal-filename', null, [ 'filename' => $verification['filtered'] ]
581 ) ], 'filename'
582 );
583 break;
585 $this->dieRecoverableError( [ 'filename-toolong' ], 'filename' );
586 break;
588 $this->dieRecoverableError( [ 'filetype-missing' ], 'filename' );
589 break;
591 $this->dieRecoverableError( [ 'windows-nonascii-filename' ], 'filename' );
592 break;
593
594 // Unrecoverable errors
596 $this->dieWithError( 'empty-file' );
597 break;
599 $this->dieWithError( 'file-too-large' );
600 break;
601
603 $extradata = [
604 'filetype' => $verification['finalExt'],
605 'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
606 ];
607 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
608 $msg = [
609 'filetype-banned-type',
610 null, // filled in below
611 Message::listParam( $extensions, 'comma' ),
612 count( $extensions ),
613 null, // filled in below
614 ];
615 ApiResult::setIndexedTagName( $extradata['allowed'], 'ext' );
616
617 if ( isset( $verification['blacklistedExt'] ) ) {
618 $msg[1] = Message::listParam( $verification['blacklistedExt'], 'comma' );
619 $msg[4] = count( $verification['blacklistedExt'] );
620 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
621 ApiResult::setIndexedTagName( $extradata['blacklisted'], 'ext' );
622 } else {
623 $msg[1] = $verification['finalExt'];
624 $msg[4] = 1;
625 }
626
627 $this->dieWithError( $msg, 'filetype-banned', $extradata );
628 break;
629
631 $msg = ApiMessage::create( $verification['details'], 'verification-error' );
632 if ( $verification['details'][0] instanceof MessageSpecifier ) {
633 $details = array_merge( [ $msg->getKey() ], $msg->getParams() );
634 } else {
635 $details = $verification['details'];
636 }
637 ApiResult::setIndexedTagName( $details, 'detail' );
638 $msg->setApiData( $msg->getApiData() + [ 'details' => $details ] );
639 $this->dieWithError( $msg );
640 break;
641
643 $msg = $verification['error'] === '' ? 'hookaborted' : $verification['error'];
644 $this->dieWithError( $msg, 'hookaborted', [ 'details' => $verification['error'] ] );
645 break;
646 default:
647 $this->dieWithError( 'apierror-unknownerror-nocode', 'unknown-error',
648 [ 'details' => [ 'code' => $verification['status'] ] ] );
649 break;
650 }
651 }
652
660 protected function getApiWarnings() {
661 $warnings = $this->mUpload->checkWarnings();
662
663 return $this->transformWarnings( $warnings );
664 }
665
666 protected function transformWarnings( $warnings ) {
667 if ( $warnings ) {
668 // Add indices
669 ApiResult::setIndexedTagName( $warnings, 'warning' );
670
671 if ( isset( $warnings['duplicate'] ) ) {
672 $dupes = [];
674 foreach ( $warnings['duplicate'] as $dupe ) {
675 $dupes[] = $dupe->getName();
676 }
677 ApiResult::setIndexedTagName( $dupes, 'duplicate' );
678 $warnings['duplicate'] = $dupes;
679 }
680
681 if ( isset( $warnings['exists'] ) ) {
682 $warning = $warnings['exists'];
683 unset( $warnings['exists'] );
685 $localFile = isset( $warning['normalizedFile'] )
686 ? $warning['normalizedFile']
687 : $warning['file'];
688 $warnings[$warning['warning']] = $localFile->getName();
689 }
690
691 if ( isset( $warnings['no-change'] ) ) {
693 $file = $warnings['no-change'];
694 unset( $warnings['no-change'] );
695
696 $warnings['nochange'] = [
697 'timestamp' => wfTimestamp( TS_ISO_8601, $file->getTimestamp() )
698 ];
699 }
700
701 if ( isset( $warnings['duplicate-version'] ) ) {
702 $dupes = [];
704 foreach ( $warnings['duplicate-version'] as $dupe ) {
705 $dupes[] = [
706 'timestamp' => wfTimestamp( TS_ISO_8601, $dupe->getTimestamp() )
707 ];
708 }
709 unset( $warnings['duplicate-version'] );
710
711 ApiResult::setIndexedTagName( $dupes, 'ver' );
712 $warnings['duplicateversions'] = $dupes;
713 }
714 }
715
716 return $warnings;
717 }
718
725 protected function handleStashException( $e ) {
726 switch ( get_class( $e ) ) {
727 case UploadStashFileNotFoundException::class:
728 $wrap = 'apierror-stashedfilenotfound';
729 break;
730 case UploadStashBadPathException::class:
731 $wrap = 'apierror-stashpathinvalid';
732 break;
733 case UploadStashFileException::class:
734 $wrap = 'apierror-stashfilestorage';
735 break;
736 case UploadStashZeroLengthFileException::class:
737 $wrap = 'apierror-stashzerolength';
738 break;
739 case UploadStashNotLoggedInException::class:
740 return StatusValue::newFatal( ApiMessage::create(
741 [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ], 'stashnotloggedin'
742 ) );
743 case UploadStashWrongOwnerException::class:
744 $wrap = 'apierror-stashwrongowner';
745 break;
746 case UploadStashNoSuchKeyException::class:
747 $wrap = 'apierror-stashnosuchfilekey';
748 break;
749 default:
750 $wrap = [ 'uploadstash-exception', get_class( $e ) ];
751 break;
752 }
753 return StatusValue::newFatal(
754 $this->getErrorFormatter()->getMessageFromException( $e, [ 'wrap' => $wrap ] )
755 );
756 }
757
765 protected function performUpload( $warnings ) {
766 // Use comment as initial page text by default
767 if ( is_null( $this->mParams['text'] ) ) {
768 $this->mParams['text'] = $this->mParams['comment'];
769 }
770
772 $file = $this->mUpload->getLocalFile();
773
774 // For preferences mode, we want to watch if 'watchdefault' is set,
775 // or if the *file* doesn't exist, and either 'watchuploads' or
776 // 'watchcreations' is set. But getWatchlistValue()'s automatic
777 // handling checks if the *title* exists or not, so we need to check
778 // all three preferences manually.
779 $watch = $this->getWatchlistValue(
780 $this->mParams['watchlist'], $file->getTitle(), 'watchdefault'
781 );
782
783 if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
784 $watch = (
785 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchuploads' ) ||
786 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchcreations' )
787 );
788 }
789
790 // Deprecated parameters
791 if ( $this->mParams['watch'] ) {
792 $watch = true;
793 }
794
795 if ( $this->mParams['tags'] ) {
796 $status = ChangeTags::canAddTagsAccompanyingChange( $this->mParams['tags'], $this->getUser() );
797 if ( !$status->isOK() ) {
798 $this->dieStatus( $status );
799 }
800 }
801
802 // No errors, no warnings: do the upload
803 if ( $this->mParams['async'] ) {
804 $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
805 if ( $progress && $progress['result'] === 'Poll' ) {
806 $this->dieWithError( 'apierror-upload-inprogress', 'publishfailed' );
807 }
809 $this->getUser(),
810 $this->mParams['filekey'],
811 [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() ]
812 );
814 Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
815 [
816 'filename' => $this->mParams['filename'],
817 'filekey' => $this->mParams['filekey'],
818 'comment' => $this->mParams['comment'],
819 'tags' => $this->mParams['tags'],
820 'text' => $this->mParams['text'],
821 'watch' => $watch,
822 'session' => $this->getContext()->exportSession()
823 ]
824 ) );
825 $result['result'] = 'Poll';
826 $result['stage'] = 'queued';
827 } else {
829 $status = $this->mUpload->performUpload( $this->mParams['comment'],
830 $this->mParams['text'], $watch, $this->getUser(), $this->mParams['tags'] );
831
832 if ( !$status->isGood() ) {
833 $this->dieRecoverableError( $status->getErrors() );
834 }
835 $result['result'] = 'Success';
836 }
837
838 $result['filename'] = $file->getName();
839 if ( $warnings && count( $warnings ) > 0 ) {
840 $result['warnings'] = $warnings;
841 }
842
843 return $result;
844 }
845
846 public function mustBePosted() {
847 return true;
848 }
849
850 public function isWriteMode() {
851 return true;
852 }
853
854 public function getAllowedParams() {
855 $params = [
856 'filename' => [
857 ApiBase::PARAM_TYPE => 'string',
858 ],
859 'comment' => [
861 ],
862 'tags' => [
863 ApiBase::PARAM_TYPE => 'tags',
865 ],
866 'text' => [
867 ApiBase::PARAM_TYPE => 'text',
868 ],
869 'watch' => [
870 ApiBase::PARAM_DFLT => false,
872 ],
873 'watchlist' => [
874 ApiBase::PARAM_DFLT => 'preferences',
876 'watch',
877 'preferences',
878 'nochange'
879 ],
880 ],
881 'ignorewarnings' => false,
882 'file' => [
883 ApiBase::PARAM_TYPE => 'upload',
884 ],
885 'url' => null,
886 'filekey' => null,
887 'sessionkey' => [
889 ],
890 'stash' => false,
891
892 'filesize' => [
893 ApiBase::PARAM_TYPE => 'integer',
896 ],
897 'offset' => [
898 ApiBase::PARAM_TYPE => 'integer',
900 ],
901 'chunk' => [
902 ApiBase::PARAM_TYPE => 'upload',
903 ],
904
905 'async' => false,
906 'checkstatus' => false,
907 ];
908
909 return $params;
910 }
911
912 public function needsToken() {
913 return 'csrf';
914 }
915
916 protected function getExamplesMessages() {
917 return [
918 'action=upload&filename=Wiki.png' .
919 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
920 => 'apihelp-upload-example-url',
921 'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
922 => 'apihelp-upload-example-filekey',
923 ];
924 }
925
926 public function getHelpUrls() {
927 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Upload';
928 }
929}
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:37
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition ApiBase.php:105
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition ApiBase.php:90
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition ApiBase.php:1895
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition ApiBase.php:2078
getMain()
Get the main module.
Definition ApiBase.php:537
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition ApiBase.php:87
getErrorFormatter()
Get the error formatter.
Definition ApiBase.php:655
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition ApiBase.php:48
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:749
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition ApiBase.php:99
getResult()
Get the result object.
Definition ApiBase.php:641
getWatchlistValue( $watchlist, $titleObj, $userOption=null)
Return true if we're to watch the page, false if not, null if no change.
Definition ApiBase.php:991
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:521
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition ApiBase.php:1960
dieBlocked(Block $block)
Throw an ApiUsageException, which will (if uncaught) call the main module's error handler and die wit...
Definition ApiBase.php:1935
requireOnlyOneParameter( $params, $required)
Die if none or more than one of a certain set of parameters is set and not false.
Definition ApiBase.php:785
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition ApiBase.php:51
Extension of Message implementing IApiMessage.
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
performStash( $failureMode, &$data=null)
Stash the file and add the file key, or error information if it fails, to the data.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition ApiUpload.php:32
checkPermissions( $user)
Checks that the user has permissions to perform this upload.
dieRecoverableError( $errors, $parameter=null)
Throw an error that the user can recover from by providing a better value for $parameter.
verifyUpload()
Performs file verification, dies on error.
UploadBase UploadFromChunks $mUpload
Definition ApiUpload.php:28
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
transformWarnings( $warnings)
handleStashException( $e)
Handles a stash exception, giving a useful error to the user.
getHelpUrls()
Return links to more detailed help pages about the module.
dieStatusWithCode( $status, $overrideCode, $moreExtraData=null)
Like dieStatus(), but always uses $overrideCode for the error code, unless the code comes from IApiMe...
isWriteMode()
Indicates whether this module requires write mode.
getWarningsResult( $warnings)
Get Warnings Result.
getContextResult()
Get an upload result based on upload context.
getChunkResult( $warnings)
Get the result of a chunk upload.
getExamplesMessages()
Returns usage examples for this module.
selectUploadModule()
Select an upload module and set it to mUpload.
getStashResult( $warnings)
Get Stash Result, throws an exception if the file could not be stashed.
needsToken()
Returns the token type this module requires in order to execute.
performUpload( $warnings)
Perform the actual upload.
checkVerification(array $verification)
Performs file verification, dies on error.
mustBePosted()
Indicates whether this module must be called with a POST request.
getApiWarnings()
Check warnings.
Assemble the segments of a chunked upload.
static canAddTagsAccompanyingChange(array $tags, User $user=null)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
exportSession()
Export the resolved user IP, HTTP headers, user ID, and session ID.
getContext()
Get the base IContextSource object.
static singleton( $domain=false)
Upload a file from the upload stash into the local file repo.
UploadBase and subclasses are the backend of MediaWiki's file uploads.
const EMPTY_FILE
static getSessionStatus(User $user, $statusKey)
Get the current status of a chunked upload (used for polling)
const FILETYPE_MISSING
static isEnabled()
Returns true if uploads are enabled.
const HOOK_ABORTED
const VERIFICATION_ERROR
const WINDOWS_NONASCII_FILENAME
const FILETYPE_BADTYPE
static getMaxUploadSize( $forType=null)
Get the MediaWiki maximum uploaded file size for given type of upload, based on $wgMaxUploadSize.
const FILE_TOO_LARGE
static isThrottled( $user)
Returns true if the user has surpassed the upload rate limit, false otherwise.
const ILLEGAL_FILENAME
const MIN_LENGTH_PARTNAME
const FILENAME_TOO_LONG
static setSessionStatus(User $user, $statusKey, $value)
Set the current status of a chunked upload (used for polling)
Implements uploading from chunks.
Implements regular file uploads.
Implements uploading from previously stored file.
static isValidKey( $key)
Implements uploading from a HTTP resource.
initialize( $name, $url)
Entry point for API upload.
static isAllowedHost( $url)
Checks whether the URL is for an allowed host The domains in the whitelist can include wildcard chara...
static isAllowedUrl( $url)
Checks whether the URL is not allowed.
static isEnabled()
Checks if the upload from URL feature is enabled.
static newFatalPermissionDeniedStatus( $permission)
Factory function for fatal permission-denied errors.
Definition User.php:5710
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
namespace being checked & $result
Definition hooks.txt:2323
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2806
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action or null $user:User who performed the tagging when the tagging is subsequent to the action or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy: boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1051
returning false will NOT prevent logging $e
Definition hooks.txt:2176
const NS_FILE
Definition Defines.php:80
$params