MediaWiki  1.33.0
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'] ) {
239  UploadBase::setSessionStatus(
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() ) {
258  UploadBase::setSessionStatus(
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 {
281  UploadBase::setSessionStatus(
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
574  case UploadBase::MIN_LENGTH_PARTNAME:
575  $this->dieRecoverableError( [ 'filename-tooshort' ], 'filename' );
576  break;
577  case UploadBase::ILLEGAL_FILENAME:
578  $this->dieRecoverableError(
580  'illegal-filename', null, [ 'filename' => $verification['filtered'] ]
581  ) ], 'filename'
582  );
583  break;
584  case UploadBase::FILENAME_TOO_LONG:
585  $this->dieRecoverableError( [ 'filename-toolong' ], 'filename' );
586  break;
587  case UploadBase::FILETYPE_MISSING:
588  $this->dieRecoverableError( [ 'filetype-missing' ], 'filename' );
589  break;
590  case UploadBase::WINDOWS_NONASCII_FILENAME:
591  $this->dieRecoverableError( [ 'windows-nonascii-filename' ], 'filename' );
592  break;
593 
594  // Unrecoverable errors
595  case UploadBase::EMPTY_FILE:
596  $this->dieWithError( 'empty-file' );
597  break;
598  case UploadBase::FILE_TOO_LARGE:
599  $this->dieWithError( 'file-too-large' );
600  break;
601 
602  case UploadBase::FILETYPE_BADTYPE:
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 
630  case UploadBase::VERIFICATION_ERROR:
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 
642  case UploadBase::HOOK_ABORTED:
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 = $warning['normalizedFile'] ?? $warning['file'];
686  $warnings[$warning['warning']] = $localFile->getName();
687  }
688 
689  if ( isset( $warnings['no-change'] ) ) {
691  $file = $warnings['no-change'];
692  unset( $warnings['no-change'] );
693 
694  $warnings['nochange'] = [
695  'timestamp' => wfTimestamp( TS_ISO_8601, $file->getTimestamp() )
696  ];
697  }
698 
699  if ( isset( $warnings['duplicate-version'] ) ) {
700  $dupes = [];
702  foreach ( $warnings['duplicate-version'] as $dupe ) {
703  $dupes[] = [
704  'timestamp' => wfTimestamp( TS_ISO_8601, $dupe->getTimestamp() )
705  ];
706  }
707  unset( $warnings['duplicate-version'] );
708 
709  ApiResult::setIndexedTagName( $dupes, 'ver' );
710  $warnings['duplicateversions'] = $dupes;
711  }
712  }
713 
714  return $warnings;
715  }
716 
723  protected function handleStashException( $e ) {
724  switch ( get_class( $e ) ) {
726  $wrap = 'apierror-stashedfilenotfound';
727  break;
729  $wrap = 'apierror-stashpathinvalid';
730  break;
732  $wrap = 'apierror-stashfilestorage';
733  break;
735  $wrap = 'apierror-stashzerolength';
736  break;
739  [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ], 'stashnotloggedin'
740  ) );
742  $wrap = 'apierror-stashwrongowner';
743  break;
745  $wrap = 'apierror-stashnosuchfilekey';
746  break;
747  default:
748  $wrap = [ 'uploadstash-exception', get_class( $e ) ];
749  break;
750  }
751  return StatusValue::newFatal(
752  $this->getErrorFormatter()->getMessageFromException( $e, [ 'wrap' => $wrap ] )
753  );
754  }
755 
763  protected function performUpload( $warnings ) {
764  // Use comment as initial page text by default
765  if ( is_null( $this->mParams['text'] ) ) {
766  $this->mParams['text'] = $this->mParams['comment'];
767  }
768 
770  $file = $this->mUpload->getLocalFile();
771 
772  // For preferences mode, we want to watch if 'watchdefault' is set,
773  // or if the *file* doesn't exist, and either 'watchuploads' or
774  // 'watchcreations' is set. But getWatchlistValue()'s automatic
775  // handling checks if the *title* exists or not, so we need to check
776  // all three preferences manually.
777  $watch = $this->getWatchlistValue(
778  $this->mParams['watchlist'], $file->getTitle(), 'watchdefault'
779  );
780 
781  if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
782  $watch = (
783  $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchuploads' ) ||
784  $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchcreations' )
785  );
786  }
787 
788  // Deprecated parameters
789  if ( $this->mParams['watch'] ) {
790  $watch = true;
791  }
792 
793  if ( $this->mParams['tags'] ) {
794  $status = ChangeTags::canAddTagsAccompanyingChange( $this->mParams['tags'], $this->getUser() );
795  if ( !$status->isOK() ) {
796  $this->dieStatus( $status );
797  }
798  }
799 
800  // No errors, no warnings: do the upload
801  if ( $this->mParams['async'] ) {
802  $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
803  if ( $progress && $progress['result'] === 'Poll' ) {
804  $this->dieWithError( 'apierror-upload-inprogress', 'publishfailed' );
805  }
806  UploadBase::setSessionStatus(
807  $this->getUser(),
808  $this->mParams['filekey'],
809  [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() ]
810  );
812  Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
813  [
814  'filename' => $this->mParams['filename'],
815  'filekey' => $this->mParams['filekey'],
816  'comment' => $this->mParams['comment'],
817  'tags' => $this->mParams['tags'],
818  'text' => $this->mParams['text'],
819  'watch' => $watch,
820  'session' => $this->getContext()->exportSession()
821  ]
822  ) );
823  $result['result'] = 'Poll';
824  $result['stage'] = 'queued';
825  } else {
827  $status = $this->mUpload->performUpload( $this->mParams['comment'],
828  $this->mParams['text'], $watch, $this->getUser(), $this->mParams['tags'] );
829 
830  if ( !$status->isGood() ) {
831  $this->dieRecoverableError( $status->getErrors() );
832  }
833  $result['result'] = 'Success';
834  }
835 
836  $result['filename'] = $file->getName();
837  if ( $warnings && count( $warnings ) > 0 ) {
838  $result['warnings'] = $warnings;
839  }
840 
841  return $result;
842  }
843 
844  public function mustBePosted() {
845  return true;
846  }
847 
848  public function isWriteMode() {
849  return true;
850  }
851 
852  public function getAllowedParams() {
853  $params = [
854  'filename' => [
855  ApiBase::PARAM_TYPE => 'string',
856  ],
857  'comment' => [
858  ApiBase::PARAM_DFLT => ''
859  ],
860  'tags' => [
861  ApiBase::PARAM_TYPE => 'tags',
862  ApiBase::PARAM_ISMULTI => true,
863  ],
864  'text' => [
865  ApiBase::PARAM_TYPE => 'text',
866  ],
867  'watch' => [
868  ApiBase::PARAM_DFLT => false,
870  ],
871  'watchlist' => [
872  ApiBase::PARAM_DFLT => 'preferences',
874  'watch',
875  'preferences',
876  'nochange'
877  ],
878  ],
879  'ignorewarnings' => false,
880  'file' => [
881  ApiBase::PARAM_TYPE => 'upload',
882  ],
883  'url' => null,
884  'filekey' => null,
885  'sessionkey' => [
887  ],
888  'stash' => false,
889 
890  'filesize' => [
891  ApiBase::PARAM_TYPE => 'integer',
892  ApiBase::PARAM_MIN => 0,
893  ApiBase::PARAM_MAX => UploadBase::getMaxUploadSize(),
894  ],
895  'offset' => [
896  ApiBase::PARAM_TYPE => 'integer',
897  ApiBase::PARAM_MIN => 0,
898  ],
899  'chunk' => [
900  ApiBase::PARAM_TYPE => 'upload',
901  ],
902 
903  'async' => false,
904  'checkstatus' => false,
905  ];
906 
907  return $params;
908  }
909 
910  public function needsToken() {
911  return 'csrf';
912  }
913 
914  protected function getExamplesMessages() {
915  return [
916  'action=upload&filename=Wiki.png' .
917  '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
918  => 'apihelp-upload-example-url',
919  'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
920  => 'apihelp-upload-example-filekey',
921  ];
922  }
923 
924  public function getHelpUrls() {
925  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Upload';
926  }
927 }
ApiUpload\getChunkResult
getChunkResult( $warnings)
Get the result of a chunk upload.
Definition: ApiUpload.php:188
$status
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 '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:1266
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:63
ApiUpload\selectUploadModule
selectUploadModule()
Select an upload module and set it to mUpload.
Definition: ApiUpload.php:407
$user
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1476
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:40
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
ApiUpload\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiUpload.php:848
ApiUpload\getStashResult
getStashResult( $warnings)
Get Stash Result, throws an exception if the file could not be stashed.
Definition: ApiUpload.php:154
User\newFatalPermissionDeniedStatus
static newFatalPermissionDeniedStatus( $permission)
Factory function for fatal permission-denied errors.
Definition: User.php:5688
captcha-old.count
count
Definition: captcha-old.py:249
ApiUpload\verifyUpload
verifyUpload()
Performs file verification, dies on error.
Definition: ApiUpload.php:558
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1990
ContextSource\msg
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:168
$result
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. '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:1983
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1912
ApiBase\PARAM_TYPE
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition: ApiBase.php:87
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:632
ApiUpload\getWarningsResult
getWarningsResult( $warnings)
Get Warnings Result.
Definition: ApiUpload.php:172
MessageSpecifier
Definition: MessageSpecifier.php:21
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
NS_FILE
const NS_FILE
Definition: Defines.php:70
$params
$params
Definition: styleTest.css.php:44
ApiUpload\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiUpload.php:32
ApiUpload\$mUpload
UploadBase UploadFromChunks $mUpload
Definition: ApiUpload.php:28
ApiUpload\getApiWarnings
getApiWarnings()
Check warnings.
Definition: ApiUpload.php:660
ApiUpload\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiUpload.php:852
UploadFromStash
Implements uploading from previously stored file.
Definition: UploadFromStash.php:30
value
if( $inline) $status value
Definition: SyntaxHighlight.php:345
ApiUpload\$mParams
$mParams
Definition: ApiUpload.php:30
ContextSource\getUser
getUser()
Definition: ContextSource.php:120
ApiUpload\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiUpload.php:914
php
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
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:37
ApiMessage
Extension of Message implementing IApiMessage.
Definition: ApiMessage.php:26
ApiBase\dieBlocked
dieBlocked(Block $block)
Throw an ApiUsageException, which will (if uncaught) call the main module's error handler and die wit...
Definition: ApiBase.php:2030
UploadFromUrl\initialize
initialize( $name, $url)
Entry point for API upload.
Definition: UploadFromUrl.php:134
PublishStashedFileJob
Upload a file from the upload stash into the local file repo.
Definition: PublishStashedFileJob.php:32
ApiBase\PARAM_DEPRECATED
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:105
ApiBase\PARAM_MIN
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:99
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
ApiUpload\dieStatusWithCode
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
UploadFromUrl
Implements uploading from a HTTP resource.
Definition: UploadFromUrl.php:31
ApiUpload\performStash
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
UploadFromUrl\isEnabled
static isEnabled()
Checks if the upload from URL feature is enabled.
Definition: UploadFromUrl.php:59
ApiUpload\dieRecoverableError
dieRecoverableError( $errors, $parameter=null)
Throw an error that the user can recover from by providing a better value for $parameter.
Definition: ApiUpload.php:363
ApiBase\PARAM_MAX
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:90
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:743
ApiUpload\getContextResult
getContextResult()
Get an upload result based on upload context.
Definition: ApiUpload.php:125
ApiUpload\handleStashException
handleStashException( $e)
Handles a stash exception, giving a useful error to the user.
Definition: ApiUpload.php:723
ApiUpload
Definition: ApiUpload.php:26
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:576
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:40
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:949
list
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
ApiBase\getWatchlistValue
getWatchlistValue( $watchlist, $titleObj, $userOption=null)
Return true if we're to watch the page, false if not, null if no change.
Definition: ApiBase.php:1081
ApiUpload\needsToken
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiUpload.php:910
$request
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:2636
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:616
UploadFromStash\isValidKey
static isValidKey( $key)
Definition: UploadFromStash.php:74
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2162
UploadFromUrl\isAllowedUrl
static isAllowedUrl( $url)
Checks whether the URL is not allowed.
Definition: UploadFromUrl.php:117
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
AssembleUploadChunksJob
Assemble the segments of a chunked upload.
Definition: AssembleUploadChunksJob.php:30
ApiUpload\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiUpload.php:924
ApiUpload\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiUpload.php:844
ApiUpload\performUpload
performUpload( $warnings)
Perform the actual upload.
Definition: ApiUpload.php:763
ApiBase\requireOnlyOneParameter
requireOnlyOneParameter( $params, $required)
Die if none or more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:875
UploadFromUrl\isAllowedHost
static isAllowedHost( $url)
Checks whether the URL is for an allowed host The domains in the whitelist can include wildcard chara...
Definition: UploadFromUrl.php:73
ChangeTags\canAddTagsAccompanyingChange
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:481
JobQueueGroup\singleton
static singleton( $domain=false)
Definition: JobQueueGroup.php:70
ContextSource\exportSession
exportSession()
Export the resolved user IP, HTTP headers, user ID, and session ID.
Definition: ContextSource.php:181
ApiBase\PARAM_DFLT
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:48
ApiUpload\checkPermissions
checkPermissions( $user)
Checks that the user has permissions to perform this upload.
Definition: ApiUpload.php:532
as
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
ApiBase\dieStatus
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition: ApiBase.php:2061
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:512
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:51
ApiBase\getMain
getMain()
Get the main module.
Definition: ApiBase.php:528
class
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
UploadFromChunks
Implements uploading from chunks.
Definition: UploadFromChunks.php:30
ApiUpload\transformWarnings
transformWarnings( $warnings)
Definition: ApiUpload.php:666
ApiBase\dieDebug
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:2188
UploadFromFile
Implements regular file uploads.
Definition: UploadFromFile.php:30
ApiBase\getErrorFormatter
getErrorFormatter()
Get the error formatter.
Definition: ApiBase.php:646
UploadStashException
Definition: UploadStashException.php:26
ApiUpload\checkVerification
checkVerification(array $verification)
Performs file verification, dies on error.
Definition: ApiUpload.php:571