MediaWiki  master
ApiUpload.php
Go to the documentation of this file.
1 <?php
26 class 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'] ) {
78  $maxSize = UploadBase::getMaxUploadSize();
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( 'apierror-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->isBlockedFromUpload() ) {
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 = UploadBase::makeWarningsSerializable( $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 = [];
673  foreach ( $warnings['duplicate'] as $dupe ) {
674  $dupes[] = $dupe['fileName'];
675  }
676  ApiResult::setIndexedTagName( $dupes, 'duplicate' );
677  $warnings['duplicate'] = $dupes;
678  }
679 
680  if ( isset( $warnings['exists'] ) ) {
681  $warning = $warnings['exists'];
682  unset( $warnings['exists'] );
683  $localFile = $warning['normalizedFile'] ?? $warning['file'];
684  $warnings[$warning['warning']] = $localFile['fileName'];
685  }
686 
687  if ( isset( $warnings['no-change'] ) ) {
688  $file = $warnings['no-change'];
689  unset( $warnings['no-change'] );
690 
691  $warnings['nochange'] = [
692  'timestamp' => wfTimestamp( TS_ISO_8601, $file['timestamp'] )
693  ];
694  }
695 
696  if ( isset( $warnings['duplicate-version'] ) ) {
697  $dupes = [];
698  foreach ( $warnings['duplicate-version'] as $dupe ) {
699  $dupes[] = [
700  'timestamp' => wfTimestamp( TS_ISO_8601, $dupe['timestamp'] )
701  ];
702  }
703  unset( $warnings['duplicate-version'] );
704 
705  ApiResult::setIndexedTagName( $dupes, 'ver' );
706  $warnings['duplicateversions'] = $dupes;
707  }
708  }
709 
710  return $warnings;
711  }
712 
719  protected function handleStashException( $e ) {
720  switch ( get_class( $e ) ) {
722  $wrap = 'apierror-stashedfilenotfound';
723  break;
725  $wrap = 'apierror-stashpathinvalid';
726  break;
728  $wrap = 'apierror-stashfilestorage';
729  break;
731  $wrap = 'apierror-stashzerolength';
732  break;
735  [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ], 'stashnotloggedin'
736  ) );
738  $wrap = 'apierror-stashwrongowner';
739  break;
741  $wrap = 'apierror-stashnosuchfilekey';
742  break;
743  default:
744  $wrap = [ 'uploadstash-exception', get_class( $e ) ];
745  break;
746  }
747  return StatusValue::newFatal(
748  $this->getErrorFormatter()->getMessageFromException( $e, [ 'wrap' => $wrap ] )
749  );
750  }
751 
759  protected function performUpload( $warnings ) {
760  // Use comment as initial page text by default
761  if ( is_null( $this->mParams['text'] ) ) {
762  $this->mParams['text'] = $this->mParams['comment'];
763  }
764 
766  $file = $this->mUpload->getLocalFile();
767 
768  // For preferences mode, we want to watch if 'watchdefault' is set,
769  // or if the *file* doesn't exist, and either 'watchuploads' or
770  // 'watchcreations' is set. But getWatchlistValue()'s automatic
771  // handling checks if the *title* exists or not, so we need to check
772  // all three preferences manually.
773  $watch = $this->getWatchlistValue(
774  $this->mParams['watchlist'], $file->getTitle(), 'watchdefault'
775  );
776 
777  if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
778  $watch = (
779  $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchuploads' ) ||
780  $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchcreations' )
781  );
782  }
783 
784  // Deprecated parameters
785  if ( $this->mParams['watch'] ) {
786  $watch = true;
787  }
788 
789  if ( $this->mParams['tags'] ) {
790  $status = ChangeTags::canAddTagsAccompanyingChange( $this->mParams['tags'], $this->getUser() );
791  if ( !$status->isOK() ) {
792  $this->dieStatus( $status );
793  }
794  }
795 
796  // No errors, no warnings: do the upload
797  if ( $this->mParams['async'] ) {
798  $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
799  if ( $progress && $progress['result'] === 'Poll' ) {
800  $this->dieWithError( 'apierror-upload-inprogress', 'publishfailed' );
801  }
803  $this->getUser(),
804  $this->mParams['filekey'],
805  [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() ]
806  );
808  Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
809  [
810  'filename' => $this->mParams['filename'],
811  'filekey' => $this->mParams['filekey'],
812  'comment' => $this->mParams['comment'],
813  'tags' => $this->mParams['tags'],
814  'text' => $this->mParams['text'],
815  'watch' => $watch,
816  'session' => $this->getContext()->exportSession()
817  ]
818  ) );
819  $result['result'] = 'Poll';
820  $result['stage'] = 'queued';
821  } else {
823  $status = $this->mUpload->performUpload( $this->mParams['comment'],
824  $this->mParams['text'], $watch, $this->getUser(), $this->mParams['tags'] );
825 
826  if ( !$status->isGood() ) {
827  $this->dieRecoverableError( $status->getErrors() );
828  }
829  $result['result'] = 'Success';
830  }
831 
832  $result['filename'] = $file->getName();
833  if ( $warnings && count( $warnings ) > 0 ) {
834  $result['warnings'] = $warnings;
835  }
836 
837  return $result;
838  }
839 
840  public function mustBePosted() {
841  return true;
842  }
843 
844  public function isWriteMode() {
845  return true;
846  }
847 
848  public function getAllowedParams() {
849  $params = [
850  'filename' => [
851  ApiBase::PARAM_TYPE => 'string',
852  ],
853  'comment' => [
854  ApiBase::PARAM_DFLT => ''
855  ],
856  'tags' => [
857  ApiBase::PARAM_TYPE => 'tags',
858  ApiBase::PARAM_ISMULTI => true,
859  ],
860  'text' => [
861  ApiBase::PARAM_TYPE => 'text',
862  ],
863  'watch' => [
864  ApiBase::PARAM_DFLT => false,
866  ],
867  'watchlist' => [
868  ApiBase::PARAM_DFLT => 'preferences',
870  'watch',
871  'preferences',
872  'nochange'
873  ],
874  ],
875  'ignorewarnings' => false,
876  'file' => [
877  ApiBase::PARAM_TYPE => 'upload',
878  ],
879  'url' => null,
880  'filekey' => null,
881  'sessionkey' => [
883  ],
884  'stash' => false,
885 
886  'filesize' => [
887  ApiBase::PARAM_TYPE => 'integer',
888  ApiBase::PARAM_MIN => 0,
890  ],
891  'offset' => [
892  ApiBase::PARAM_TYPE => 'integer',
893  ApiBase::PARAM_MIN => 0,
894  ],
895  'chunk' => [
896  ApiBase::PARAM_TYPE => 'upload',
897  ],
898 
899  'async' => false,
900  'checkstatus' => false,
901  ];
902 
903  return $params;
904  }
905 
906  public function needsToken() {
907  return 'csrf';
908  }
909 
910  protected function getExamplesMessages() {
911  return [
912  'action=upload&filename=Wiki.png' .
913  '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
914  => 'apihelp-upload-example-url',
915  'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
916  => 'apihelp-upload-example-filekey',
917  ];
918  }
919 
920  public function getHelpUrls() {
921  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Upload';
922  }
923 }
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:94
requireOnlyOneParameter( $params, $required)
Die if none or more than one of a certain set of parameters is set and not false. ...
Definition: ApiBase.php:893
getErrorFormatter()
Get the error formatter.
Definition: ApiBase.php:654
getExamplesMessages()
Definition: ApiUpload.php:910
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
handleStashException( $e)
Handles a stash exception, giving a useful error to the user.
Definition: ApiUpload.php:719
const FILENAME_TOO_LONG
Definition: UploadBase.php:104
getResult()
Get the result object.
Definition: ApiBase.php:640
Implements uploading from previously stored file.
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition: ApiBase.php:2080
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2153
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:55
getMain()
Get the main module.
Definition: ApiBase.php:536
dieBlocked(AbstractBlock $block)
Throw an ApiUsageException, which will (if uncaught) call the main module&#39;s error handler and die wit...
Definition: ApiBase.php:2049
static getSessionStatus(User $user, $statusKey)
Get the current status of a chunked upload (used for polling)
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:97
getContextResult()
Get an upload result based on upload context.
Definition: ApiUpload.php:125
transformWarnings( $warnings)
Definition: ApiUpload.php:666
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:2009
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:761
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
verifyUpload()
Performs file verification, dies on error.
Definition: ApiUpload.php:558
const ILLEGAL_FILENAME
Definition: UploadBase.php:96
static getMaxUploadSize( $forType=null)
Get the MediaWiki maximum uploaded file size for given type of upload, based on $wgMaxUploadSize.
static numParam( $num)
Definition: Message.php:1051
static isAllowedHost( $url)
Checks whether the URL is for an allowed host The domains in the whitelist can include wildcard chara...
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:616
Implements uploading from a HTTP resource.
initialize( $name, $url)
Entry point for API upload.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\*-\*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1976
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
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. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header '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 '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:1250
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
performUpload( $warnings)
Perform the actual upload.
Definition: ApiUpload.php:759
static isEnabled()
Checks if the upload from URL feature is enabled.
Implements regular file uploads.
getWatchlistValue( $watchlist, $titleObj, $userOption=null)
Return true if we&#39;re to watch the page, false if not, null if no change.
Definition: ApiBase.php:1099
static isAllowedUrl( $url)
Checks whether the URL is not allowed.
Upload a file from the upload stash into the local file repo.
mustBePosted()
Definition: ApiUpload.php:840
getChunkResult( $warnings)
Get the result of a chunk upload.
Definition: ApiUpload.php:188
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
static isValidKey( $key)
dieStatusWithCode( $status, $overrideCode, $moreExtraData=null)
Like dieStatus(), but always uses $overrideCode for the error code, unless the code comes from IApiMe...
Definition: ApiUpload.php:388
getApiWarnings()
Check warnings.
Definition: ApiUpload.php:660
checkPermissions( $user)
Checks that the user has permissions to perform this upload.
Definition: ApiUpload.php:532
Assemble the segments of a chunked upload.
getContext()
Get the base IContextSource object.
Implements uploading from chunks.
$params
Extension of Message implementing IApiMessage.
Definition: ApiMessage.php:26
static makeWarningsSerializable( $warnings)
Convert the warnings array returned by checkWarnings() to something that can be serialized.
Definition: UploadBase.php:718
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:773
const FILE_TOO_LARGE
Definition: UploadBase.php:102
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:520
const MIN_LENGTH_PARTNAME
Definition: UploadBase.php:95
const NS_FILE
Definition: Defines.php:66
const VERIFICATION_ERROR
Definition: UploadBase.php:100
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
static isEnabled()
Returns true if uploads are enabled.
Definition: UploadBase.php:132
static isThrottled( $user)
Returns true if the user has surpassed the upload rate limit, false otherwise.
Definition: UploadBase.php:167
const FILETYPE_BADTYPE
Definition: UploadBase.php:99
const FILETYPE_MISSING
Definition: UploadBase.php:98
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:592
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
exportSession()
Export the resolved user IP, HTTP headers, user ID, and session ID.
const HOOK_ABORTED
Definition: UploadBase.php:101
selectUploadModule()
Select an upload module and set it to mUpload.
Definition: ApiUpload.php:407
performStash( $failureMode, &$data=null)
Stash the file and add the file key, or error information if it fails, to the data.
Definition: ApiUpload.php:312
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
dieRecoverableError( $errors, $parameter=null)
Throw an error that the user can recover from by providing a better value for $parameter.
Definition: ApiUpload.php:363
static newFatalPermissionDeniedStatus( $permission)
Factory function for fatal permission-denied errors.
Definition: User.php:5350
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:58
const WINDOWS_NONASCII_FILENAME
Definition: UploadBase.php:103
getAllowedParams()
Definition: ApiUpload.php:848
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:2212
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:42
static singleton( $domain=false)
getStashResult( $warnings)
Get Stash Result, throws an exception if the file could not be stashed.
Definition: ApiUpload.php:154
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:112
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...
Definition: ChangeTags.php:521
getWarningsResult( $warnings)
Get Warnings Result.
Definition: ApiUpload.php:172
static setSessionStatus(User $user, $statusKey, $value)
Set the current status of a chunked upload (used for polling)
checkVerification(array $verification)
Performs file verification, dies on error.
Definition: ApiUpload.php:571
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:106
const OK
Definition: UploadBase.php:93
UploadBase UploadFromChunks $mUpload
Definition: ApiUpload.php:28
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:2627
const EMPTY_FILE
Definition: UploadBase.php:94
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1460
static listParam(array $list, $type='text')
Definition: Message.php:1128
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:40