MediaWiki  1.29.1
ApiUpload.php
Go to the documentation of this file.
1 <?php
30 class ApiUpload extends ApiBase {
32  protected $mUpload = null;
33 
34  protected $mParams;
35 
36  public function execute() {
37  // Check whether upload is enabled
38  if ( !UploadBase::isEnabled() ) {
39  $this->dieWithError( 'uploaddisabled' );
40  }
41 
42  $user = $this->getUser();
43 
44  // Parameter handling
45  $this->mParams = $this->extractRequestParams();
46  $request = $this->getMain()->getRequest();
47  // Check if async mode is actually supported (jobs done in cli mode)
48  $this->mParams['async'] = ( $this->mParams['async'] &&
49  $this->getConfig()->get( 'EnableAsyncUploads' ) );
50  // Add the uploaded file to the params array
51  $this->mParams['file'] = $request->getFileName( 'file' );
52  $this->mParams['chunk'] = $request->getFileName( 'chunk' );
53 
54  // Copy the session key to the file key, for backward compatibility.
55  if ( !$this->mParams['filekey'] && $this->mParams['sessionkey'] ) {
56  $this->mParams['filekey'] = $this->mParams['sessionkey'];
57  }
58 
59  // Select an upload module
60  try {
61  if ( !$this->selectUploadModule() ) {
62  return; // not a true upload, but a status request or similar
63  } elseif ( !isset( $this->mUpload ) ) {
64  $this->dieDebug( __METHOD__, 'No upload module set' );
65  }
66  } catch ( UploadStashException $e ) { // XXX: don't spam exception log
67  $this->dieStatus( $this->handleStashException( $e ) );
68  }
69 
70  // First check permission to upload
71  $this->checkPermissions( $user );
72 
73  // Fetch the file (usually a no-op)
75  $status = $this->mUpload->fetchFile();
76  if ( !$status->isGood() ) {
77  $this->dieStatus( $status );
78  }
79 
80  // Check if the uploaded file is sane
81  if ( $this->mParams['chunk'] ) {
82  $maxSize = UploadBase::getMaxUploadSize();
83  if ( $this->mParams['filesize'] > $maxSize ) {
84  $this->dieWithError( 'file-too-large' );
85  }
86  if ( !$this->mUpload->getTitle() ) {
87  $this->dieWithError( 'illegal-filename' );
88  }
89  } elseif ( $this->mParams['async'] && $this->mParams['filekey'] ) {
90  // defer verification to background process
91  } else {
92  wfDebug( __METHOD__ . " about to verify\n" );
93  $this->verifyUpload();
94  }
95 
96  // Check if the user has the rights to modify or overwrite the requested title
97  // (This check is irrelevant if stashing is already requested, since the errors
98  // can always be fixed by changing the title)
99  if ( !$this->mParams['stash'] ) {
100  $permErrors = $this->mUpload->verifyTitlePermissions( $user );
101  if ( $permErrors !== true ) {
102  $this->dieRecoverableError( $permErrors, 'filename' );
103  }
104  }
105 
106  // Get the result based on the current upload context:
107  try {
108  $result = $this->getContextResult();
109  } catch ( UploadStashException $e ) { // XXX: don't spam exception log
110  $this->dieStatus( $this->handleStashException( $e ) );
111  }
112  $this->getResult()->addValue( null, $this->getModuleName(), $result );
113 
114  // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
115  // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
116  if ( $result['result'] === 'Success' ) {
117  $imageinfo = $this->mUpload->getImageInfo( $this->getResult() );
118  $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
119  }
120 
121  // Cleanup any temporary mess
122  $this->mUpload->cleanupTempFile();
123  }
124 
129  private function getContextResult() {
130  $warnings = $this->getApiWarnings();
131  if ( $warnings && !$this->mParams['ignorewarnings'] ) {
132  // Get warnings formatted in result array format
133  return $this->getWarningsResult( $warnings );
134  } elseif ( $this->mParams['chunk'] ) {
135  // Add chunk, and get result
136  return $this->getChunkResult( $warnings );
137  } elseif ( $this->mParams['stash'] ) {
138  // Stash the file and get stash result
139  return $this->getStashResult( $warnings );
140  }
141 
142  // Check throttle after we've handled warnings
143  if ( UploadBase::isThrottled( $this->getUser() )
144  ) {
145  $this->dieWithError( 'apierror-ratelimited' );
146  }
147 
148  // This is the most common case -- a normal upload with no warnings
149  // performUpload will return a formatted properly for the API with status
150  return $this->performUpload( $warnings );
151  }
152 
158  private function getStashResult( $warnings ) {
159  $result = [];
160  $result['result'] = 'Success';
161  if ( $warnings && count( $warnings ) > 0 ) {
162  $result['warnings'] = $warnings;
163  }
164  // Some uploads can request they be stashed, so as not to publish them immediately.
165  // In this case, a failure to stash ought to be fatal
166  $this->performStash( 'critical', $result );
167 
168  return $result;
169  }
170 
176  private function getWarningsResult( $warnings ) {
177  $result = [];
178  $result['result'] = 'Warning';
179  $result['warnings'] = $warnings;
180  // in case the warnings can be fixed with some further user action, let's stash this upload
181  // and return a key they can use to restart it
182  $this->performStash( 'optional', $result );
183 
184  return $result;
185  }
186 
192  private function getChunkResult( $warnings ) {
193  $result = [];
194 
195  if ( $warnings && count( $warnings ) > 0 ) {
196  $result['warnings'] = $warnings;
197  }
198 
199  $request = $this->getMain()->getRequest();
200  $chunkPath = $request->getFileTempname( 'chunk' );
201  $chunkSize = $request->getUpload( 'chunk' )->getSize();
202  $totalSoFar = $this->mParams['offset'] + $chunkSize;
203  $minChunkSize = $this->getConfig()->get( 'MinUploadChunkSize' );
204 
205  // Sanity check sizing
206  if ( $totalSoFar > $this->mParams['filesize'] ) {
207  $this->dieWithError( 'apierror-invalid-chunk' );
208  }
209 
210  // Enforce minimum chunk size
211  if ( $totalSoFar != $this->mParams['filesize'] && $chunkSize < $minChunkSize ) {
212  $this->dieWithError( [ 'apierror-chunk-too-small', Message::numParam( $minChunkSize ) ] );
213  }
214 
215  if ( $this->mParams['offset'] == 0 ) {
216  $filekey = $this->performStash( 'critical' );
217  } else {
218  $filekey = $this->mParams['filekey'];
219 
220  // Don't allow further uploads to an already-completed session
221  $progress = UploadBase::getSessionStatus( $this->getUser(), $filekey );
222  if ( !$progress ) {
223  // Probably can't get here, but check anyway just in case
224  $this->dieWithError( 'apierror-stashfailed-nosession', 'stashfailed' );
225  } elseif ( $progress['result'] !== 'Continue' || $progress['stage'] !== 'uploading' ) {
226  $this->dieWithError( 'apierror-stashfailed-complete', 'stashfailed' );
227  }
228 
229  $status = $this->mUpload->addChunk(
230  $chunkPath, $chunkSize, $this->mParams['offset'] );
231  if ( !$status->isGood() ) {
232  $extradata = [
233  'offset' => $this->mUpload->getOffset(),
234  ];
235 
236  $this->dieStatusWithCode( $status, 'stashfailed', $extradata );
237  }
238  }
239 
240  // Check we added the last chunk:
241  if ( $totalSoFar == $this->mParams['filesize'] ) {
242  if ( $this->mParams['async'] ) {
243  UploadBase::setSessionStatus(
244  $this->getUser(),
245  $filekey,
246  [ 'result' => 'Poll',
247  'stage' => 'queued', 'status' => Status::newGood() ]
248  );
250  Title::makeTitle( NS_FILE, $filekey ),
251  [
252  'filename' => $this->mParams['filename'],
253  'filekey' => $filekey,
254  'session' => $this->getContext()->exportSession()
255  ]
256  ) );
257  $result['result'] = 'Poll';
258  $result['stage'] = 'queued';
259  } else {
260  $status = $this->mUpload->concatenateChunks();
261  if ( !$status->isGood() ) {
262  UploadBase::setSessionStatus(
263  $this->getUser(),
264  $filekey,
265  [ 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status ]
266  );
267  $this->dieStatusWithCode( $status, 'stashfailed' );
268  }
269 
270  // We can only get warnings like 'duplicate' after concatenating the chunks
271  $warnings = $this->getApiWarnings();
272  if ( $warnings ) {
273  $result['warnings'] = $warnings;
274  }
275 
276  // The fully concatenated file has a new filekey. So remove
277  // the old filekey and fetch the new one.
278  UploadBase::setSessionStatus( $this->getUser(), $filekey, false );
279  $this->mUpload->stash->removeFile( $filekey );
280  $filekey = $this->mUpload->getStashFile()->getFileKey();
281 
282  $result['result'] = 'Success';
283  }
284  } else {
285  UploadBase::setSessionStatus(
286  $this->getUser(),
287  $filekey,
288  [
289  'result' => 'Continue',
290  'stage' => 'uploading',
291  'offset' => $totalSoFar,
292  'status' => Status::newGood(),
293  ]
294  );
295  $result['result'] = 'Continue';
296  $result['offset'] = $totalSoFar;
297  }
298 
299  $result['filekey'] = $filekey;
300 
301  return $result;
302  }
303 
316  private function performStash( $failureMode, &$data = null ) {
317  $isPartial = (bool)$this->mParams['chunk'];
318  try {
319  $status = $this->mUpload->tryStashFile( $this->getUser(), $isPartial );
320 
321  if ( $status->isGood() && !$status->getValue() ) {
322  // Not actually a 'good' status...
323  $status->fatal( new ApiMessage( 'apierror-stashinvalidfile', 'stashfailed' ) );
324  }
325  } catch ( Exception $e ) {
326  $debugMessage = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
327  wfDebug( __METHOD__ . ' ' . $debugMessage . "\n" );
328  $status = Status::newFatal( $this->getErrorFormatter()->getMessageFromException(
329  $e, [ 'wrap' => new ApiMessage( 'apierror-stashexception', 'stashfailed' ) ]
330  ) );
331  }
332 
333  if ( $status->isGood() ) {
334  $stashFile = $status->getValue();
335  $data['filekey'] = $stashFile->getFileKey();
336  // Backwards compatibility
337  $data['sessionkey'] = $data['filekey'];
338  return $data['filekey'];
339  }
340 
341  if ( $status->getMessage()->getKey() === 'uploadstash-exception' ) {
342  // The exceptions thrown by upload stash code and pretty silly and UploadBase returns poor
343  // Statuses for it. Just extract the exception details and parse them ourselves.
344  list( $exceptionType, $message ) = $status->getMessage()->getParams();
345  $debugMessage = 'Stashing temporary file failed: ' . $exceptionType . ' ' . $message;
346  wfDebug( __METHOD__ . ' ' . $debugMessage . "\n" );
347  }
348 
349  // Bad status
350  if ( $failureMode !== 'optional' ) {
351  $this->dieStatus( $status );
352  } else {
353  $data['stasherrors'] = $this->getErrorFormatter()->arrayFromStatus( $status );
354  return null;
355  }
356  }
357 
367  private function dieRecoverableError( $errors, $parameter = null ) {
368  $this->performStash( 'optional', $data );
369 
370  if ( $parameter ) {
371  $data['invalidparameter'] = $parameter;
372  }
373 
374  $sv = StatusValue::newGood();
375  foreach ( $errors as $error ) {
376  $msg = ApiMessage::create( $error );
377  $msg->setApiData( $msg->getApiData() + $data );
378  $sv->fatal( $msg );
379  }
380  $this->dieStatus( $sv );
381  }
382 
392  public function dieStatusWithCode( $status, $overrideCode, $moreExtraData = null ) {
393  $sv = StatusValue::newGood();
394  foreach ( $status->getErrors() as $error ) {
395  $msg = ApiMessage::create( $error, $overrideCode );
396  if ( $moreExtraData ) {
397  $msg->setApiData( $msg->getApiData() + $moreExtraData );
398  }
399  $sv->fatal( $msg );
400  }
401  $this->dieStatus( $sv );
402  }
403 
411  protected function selectUploadModule() {
412  $request = $this->getMain()->getRequest();
413 
414  // chunk or one and only one of the following parameters is needed
415  if ( !$this->mParams['chunk'] ) {
416  $this->requireOnlyOneParameter( $this->mParams,
417  'filekey', 'file', 'url' );
418  }
419 
420  // Status report for "upload to stash"/"upload from stash"
421  if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
422  $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
423  if ( !$progress ) {
424  $this->dieWithError( 'api-upload-missingresult', 'missingresult' );
425  } elseif ( !$progress['status']->isGood() ) {
426  $this->dieStatusWithCode( $progress['status'], 'stashfailed' );
427  }
428  if ( isset( $progress['status']->value['verification'] ) ) {
429  $this->checkVerification( $progress['status']->value['verification'] );
430  }
431  if ( isset( $progress['status']->value['warnings'] ) ) {
432  $warnings = $this->transformWarnings( $progress['status']->value['warnings'] );
433  if ( $warnings ) {
434  $progress['warnings'] = $warnings;
435  }
436  }
437  unset( $progress['status'] ); // remove Status object
438  $imageinfo = null;
439  if ( isset( $progress['imageinfo'] ) ) {
440  $imageinfo = $progress['imageinfo'];
441  unset( $progress['imageinfo'] );
442  }
443 
444  $this->getResult()->addValue( null, $this->getModuleName(), $progress );
445  // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
446  // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
447  if ( $imageinfo ) {
448  $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
449  }
450 
451  return false;
452  }
453 
454  // The following modules all require the filename parameter to be set
455  if ( is_null( $this->mParams['filename'] ) ) {
456  $this->dieWithError( [ 'apierror-missingparam', 'filename' ] );
457  }
458 
459  if ( $this->mParams['chunk'] ) {
460  // Chunk upload
461  $this->mUpload = new UploadFromChunks( $this->getUser() );
462  if ( isset( $this->mParams['filekey'] ) ) {
463  if ( $this->mParams['offset'] === 0 ) {
464  $this->dieWithError( 'apierror-upload-filekeynotallowed', 'filekeynotallowed' );
465  }
466 
467  // handle new chunk
468  $this->mUpload->continueChunks(
469  $this->mParams['filename'],
470  $this->mParams['filekey'],
471  $request->getUpload( 'chunk' )
472  );
473  } else {
474  if ( $this->mParams['offset'] !== 0 ) {
475  $this->dieWithError( 'apierror-upload-filekeyneeded', 'filekeyneeded' );
476  }
477 
478  // handle first chunk
479  $this->mUpload->initialize(
480  $this->mParams['filename'],
481  $request->getUpload( 'chunk' )
482  );
483  }
484  } elseif ( isset( $this->mParams['filekey'] ) ) {
485  // Upload stashed in a previous request
486  if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
487  $this->dieWithError( 'apierror-invalid-file-key' );
488  }
489 
490  $this->mUpload = new UploadFromStash( $this->getUser() );
491  // This will not download the temp file in initialize() in async mode.
492  // We still have enough information to call checkWarnings() and such.
493  $this->mUpload->initialize(
494  $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
495  );
496  } elseif ( isset( $this->mParams['file'] ) ) {
497  // Can't async upload directly from a POSTed file, we'd have to
498  // stash the file and then queue the publish job. The user should
499  // just submit the two API queries to perform those two steps.
500  if ( $this->mParams['async'] ) {
501  $this->dieWithError( 'apierror-cannot-async-upload-file' );
502  }
503 
504  $this->mUpload = new UploadFromFile();
505  $this->mUpload->initialize(
506  $this->mParams['filename'],
507  $request->getUpload( 'file' )
508  );
509  } elseif ( isset( $this->mParams['url'] ) ) {
510  // Make sure upload by URL is enabled:
511  if ( !UploadFromUrl::isEnabled() ) {
512  $this->dieWithError( 'copyuploaddisabled' );
513  }
514 
515  if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
516  $this->dieWithError( 'apierror-copyuploadbaddomain' );
517  }
518 
519  if ( !UploadFromUrl::isAllowedUrl( $this->mParams['url'] ) ) {
520  $this->dieWithError( 'apierror-copyuploadbadurl' );
521  }
522 
523  $this->mUpload = new UploadFromUrl;
524  $this->mUpload->initialize( $this->mParams['filename'],
525  $this->mParams['url'] );
526  }
527 
528  return true;
529  }
530 
536  protected function checkPermissions( $user ) {
537  // Check whether the user has the appropriate permissions to upload anyway
538  $permission = $this->mUpload->isAllowed( $user );
539 
540  if ( $permission !== true ) {
541  if ( !$user->isLoggedIn() ) {
542  $this->dieWithError( [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ] );
543  }
544 
545  $this->dieStatus( User::newFatalPermissionDeniedStatus( $permission ) );
546  }
547 
548  // Check blocks
549  if ( $user->isBlocked() ) {
550  $this->dieBlocked( $user->getBlock() );
551  }
552 
553  // Global blocks
554  if ( $user->isBlockedGlobally() ) {
555  $this->dieBlocked( $user->getGlobalBlock() );
556  }
557  }
558 
562  protected function verifyUpload() {
563  $verification = $this->mUpload->verifyUpload();
564  if ( $verification['status'] === UploadBase::OK ) {
565  return;
566  }
567 
568  $this->checkVerification( $verification );
569  }
570 
575  protected function checkVerification( array $verification ) {
576  switch ( $verification['status'] ) {
577  // Recoverable errors
578  case UploadBase::MIN_LENGTH_PARTNAME:
579  $this->dieRecoverableError( [ 'filename-tooshort' ], 'filename' );
580  break;
581  case UploadBase::ILLEGAL_FILENAME:
582  $this->dieRecoverableError(
584  'illegal-filename', null, [ 'filename' => $verification['filtered'] ]
585  ) ], 'filename'
586  );
587  break;
588  case UploadBase::FILENAME_TOO_LONG:
589  $this->dieRecoverableError( [ 'filename-toolong' ], 'filename' );
590  break;
591  case UploadBase::FILETYPE_MISSING:
592  $this->dieRecoverableError( [ 'filetype-missing' ], 'filename' );
593  break;
594  case UploadBase::WINDOWS_NONASCII_FILENAME:
595  $this->dieRecoverableError( [ 'windows-nonascii-filename' ], 'filename' );
596  break;
597 
598  // Unrecoverable errors
599  case UploadBase::EMPTY_FILE:
600  $this->dieWithError( 'empty-file' );
601  break;
602  case UploadBase::FILE_TOO_LARGE:
603  $this->dieWithError( 'file-too-large' );
604  break;
605 
606  case UploadBase::FILETYPE_BADTYPE:
607  $extradata = [
608  'filetype' => $verification['finalExt'],
609  'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
610  ];
611  $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
612  $msg = [
613  'filetype-banned-type',
614  null, // filled in below
615  Message::listParam( $extensions, 'comma' ),
616  count( $extensions ),
617  null, // filled in below
618  ];
619  ApiResult::setIndexedTagName( $extradata['allowed'], 'ext' );
620 
621  if ( isset( $verification['blacklistedExt'] ) ) {
622  $msg[1] = Message::listParam( $verification['blacklistedExt'], 'comma' );
623  $msg[4] = count( $verification['blacklistedExt'] );
624  $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
625  ApiResult::setIndexedTagName( $extradata['blacklisted'], 'ext' );
626  } else {
627  $msg[1] = $verification['finalExt'];
628  $msg[4] = 1;
629  }
630 
631  $this->dieWithError( $msg, 'filetype-banned', $extradata );
632  break;
633 
634  case UploadBase::VERIFICATION_ERROR:
635  $msg = ApiMessage::create( $verification['details'], 'verification-error' );
636  if ( $verification['details'][0] instanceof MessageSpecifier ) {
637  $details = array_merge( [ $msg->getKey() ], $msg->getParams() );
638  } else {
639  $details = $verification['details'];
640  }
641  ApiResult::setIndexedTagName( $details, 'detail' );
642  $msg->setApiData( $msg->getApiData() + [ 'details' => $details ] );
643  $this->dieWithError( $msg );
644  break;
645 
646  case UploadBase::HOOK_ABORTED:
647  $msg = $verification['error'] === '' ? 'hookaborted' : $verification['error'];
648  $this->dieWithError( $msg, 'hookaborted', [ 'details' => $verification['error'] ] );
649  break;
650  default:
651  $this->dieWithError( 'apierror-unknownerror-nocode', 'unknown-error',
652  [ 'details' => [ 'code' => $verification['status'] ] ] );
653  break;
654  }
655  }
656 
664  protected function getApiWarnings() {
665  $warnings = $this->mUpload->checkWarnings();
666 
667  return $this->transformWarnings( $warnings );
668  }
669 
670  protected function transformWarnings( $warnings ) {
671  if ( $warnings ) {
672  // Add indices
673  ApiResult::setIndexedTagName( $warnings, 'warning' );
674 
675  if ( isset( $warnings['duplicate'] ) ) {
676  $dupes = [];
678  foreach ( $warnings['duplicate'] as $dupe ) {
679  $dupes[] = $dupe->getName();
680  }
681  ApiResult::setIndexedTagName( $dupes, 'duplicate' );
682  $warnings['duplicate'] = $dupes;
683  }
684 
685  if ( isset( $warnings['exists'] ) ) {
686  $warning = $warnings['exists'];
687  unset( $warnings['exists'] );
689  $localFile = isset( $warning['normalizedFile'] )
690  ? $warning['normalizedFile']
691  : $warning['file'];
692  $warnings[$warning['warning']] = $localFile->getName();
693  }
694 
695  if ( isset( $warnings['no-change'] ) ) {
697  $file = $warnings['no-change'];
698  unset( $warnings['no-change'] );
699 
700  $warnings['nochange'] = [
701  'timestamp' => wfTimestamp( TS_ISO_8601, $file->getTimestamp() )
702  ];
703  }
704 
705  if ( isset( $warnings['duplicate-version'] ) ) {
706  $dupes = [];
708  foreach ( $warnings['duplicate-version'] as $dupe ) {
709  $dupes[] = [
710  'timestamp' => wfTimestamp( TS_ISO_8601, $dupe->getTimestamp() )
711  ];
712  }
713  unset( $warnings['duplicate-version'] );
714 
715  ApiResult::setIndexedTagName( $dupes, 'ver' );
716  $warnings['duplicateversions'] = $dupes;
717  }
718  }
719 
720  return $warnings;
721  }
722 
729  protected function handleStashException( $e ) {
730  switch ( get_class( $e ) ) {
731  case 'UploadStashFileNotFoundException':
732  $wrap = 'apierror-stashedfilenotfound';
733  break;
734  case 'UploadStashBadPathException':
735  $wrap = 'apierror-stashpathinvalid';
736  break;
737  case 'UploadStashFileException':
738  $wrap = 'apierror-stashfilestorage';
739  break;
740  case 'UploadStashZeroLengthFileException':
741  $wrap = 'apierror-stashzerolength';
742  break;
743  case 'UploadStashNotLoggedInException':
745  [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ], 'stashnotloggedin'
746  ) );
747  case 'UploadStashWrongOwnerException':
748  $wrap = 'apierror-stashwrongowner';
749  break;
750  case 'UploadStashNoSuchKeyException':
751  $wrap = 'apierror-stashnosuchfilekey';
752  break;
753  default:
754  $wrap = [ 'uploadstash-exception', get_class( $e ) ];
755  break;
756  }
757  return StatusValue::newFatal(
758  $this->getErrorFormatter()->getMessageFromException( $e, [ 'wrap' => $wrap ] )
759  );
760  }
761 
769  protected function performUpload( $warnings ) {
770  // Use comment as initial page text by default
771  if ( is_null( $this->mParams['text'] ) ) {
772  $this->mParams['text'] = $this->mParams['comment'];
773  }
774 
776  $file = $this->mUpload->getLocalFile();
777 
778  // For preferences mode, we want to watch if 'watchdefault' is set,
779  // or if the *file* doesn't exist, and either 'watchuploads' or
780  // 'watchcreations' is set. But getWatchlistValue()'s automatic
781  // handling checks if the *title* exists or not, so we need to check
782  // all three preferences manually.
783  $watch = $this->getWatchlistValue(
784  $this->mParams['watchlist'], $file->getTitle(), 'watchdefault'
785  );
786 
787  if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
788  $watch = (
789  $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchuploads' ) ||
790  $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchcreations' )
791  );
792  }
793 
794  // Deprecated parameters
795  if ( $this->mParams['watch'] ) {
796  $watch = true;
797  }
798 
799  if ( $this->mParams['tags'] ) {
800  $status = ChangeTags::canAddTagsAccompanyingChange( $this->mParams['tags'], $this->getUser() );
801  if ( !$status->isOK() ) {
802  $this->dieStatus( $status );
803  }
804  }
805 
806  // No errors, no warnings: do the upload
807  if ( $this->mParams['async'] ) {
808  $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
809  if ( $progress && $progress['result'] === 'Poll' ) {
810  $this->dieWithError( 'apierror-upload-inprogress', 'publishfailed' );
811  }
812  UploadBase::setSessionStatus(
813  $this->getUser(),
814  $this->mParams['filekey'],
815  [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() ]
816  );
818  Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
819  [
820  'filename' => $this->mParams['filename'],
821  'filekey' => $this->mParams['filekey'],
822  'comment' => $this->mParams['comment'],
823  'tags' => $this->mParams['tags'],
824  'text' => $this->mParams['text'],
825  'watch' => $watch,
826  'session' => $this->getContext()->exportSession()
827  ]
828  ) );
829  $result['result'] = 'Poll';
830  $result['stage'] = 'queued';
831  } else {
833  $status = $this->mUpload->performUpload( $this->mParams['comment'],
834  $this->mParams['text'], $watch, $this->getUser(), $this->mParams['tags'] );
835 
836  if ( !$status->isGood() ) {
837  $this->dieRecoverableError( $status->getErrors() );
838  }
839  $result['result'] = 'Success';
840  }
841 
842  $result['filename'] = $file->getName();
843  if ( $warnings && count( $warnings ) > 0 ) {
844  $result['warnings'] = $warnings;
845  }
846 
847  return $result;
848  }
849 
850  public function mustBePosted() {
851  return true;
852  }
853 
854  public function isWriteMode() {
855  return true;
856  }
857 
858  public function getAllowedParams() {
859  $params = [
860  'filename' => [
861  ApiBase::PARAM_TYPE => 'string',
862  ],
863  'comment' => [
864  ApiBase::PARAM_DFLT => ''
865  ],
866  'tags' => [
867  ApiBase::PARAM_TYPE => 'tags',
868  ApiBase::PARAM_ISMULTI => true,
869  ],
870  'text' => [
871  ApiBase::PARAM_TYPE => 'text',
872  ],
873  'watch' => [
874  ApiBase::PARAM_DFLT => false,
876  ],
877  'watchlist' => [
878  ApiBase::PARAM_DFLT => 'preferences',
880  'watch',
881  'preferences',
882  'nochange'
883  ],
884  ],
885  'ignorewarnings' => false,
886  'file' => [
887  ApiBase::PARAM_TYPE => 'upload',
888  ],
889  'url' => null,
890  'filekey' => null,
891  'sessionkey' => [
893  ],
894  'stash' => false,
895 
896  'filesize' => [
897  ApiBase::PARAM_TYPE => 'integer',
898  ApiBase::PARAM_MIN => 0,
899  ApiBase::PARAM_MAX => UploadBase::getMaxUploadSize(),
900  ],
901  'offset' => [
902  ApiBase::PARAM_TYPE => 'integer',
903  ApiBase::PARAM_MIN => 0,
904  ],
905  'chunk' => [
906  ApiBase::PARAM_TYPE => 'upload',
907  ],
908 
909  'async' => false,
910  'checkstatus' => false,
911  ];
912 
913  return $params;
914  }
915 
916  public function needsToken() {
917  return 'csrf';
918  }
919 
920  protected function getExamplesMessages() {
921  return [
922  'action=upload&filename=Wiki.png' .
923  '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
924  => 'apihelp-upload-example-url',
925  'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
926  => 'apihelp-upload-example-filekey',
927  ];
928  }
929 
930  public function getHelpUrls() {
931  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Upload';
932  }
933 }
ApiUpload\getChunkResult
getChunkResult( $warnings)
Get the result of a chunk upload.
Definition: ApiUpload.php:192
ContextSource\getConfig
getConfig()
Get the Config object.
Definition: ContextSource.php:68
ApiUpload\selectUploadModule
selectUploadModule()
Select an upload module and set it to mUpload.
Definition: ApiUpload.php:411
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:41
$request
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2612
ApiUpload\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiUpload.php:854
ApiUpload\getStashResult
getStashResult( $warnings)
Get Stash Result, throws an exception if the file could not be stashed.
Definition: ApiUpload.php:158
ContextSource\msg
msg()
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:187
User\newFatalPermissionDeniedStatus
static newFatalPermissionDeniedStatus( $permission)
Factory function for fatal permission-denied errors.
Definition: User.php:5467
captcha-old.count
count
Definition: captcha-old.py:225
ApiUpload\verifyUpload
verifyUpload()
Performs file verification, dies on error.
Definition: ApiUpload.php:562
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1796
$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 '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. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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! 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:1954
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1994
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:91
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:610
ApiUpload\getWarningsResult
getWarningsResult( $warnings)
Get Warnings Result.
Definition: ApiUpload.php:176
MessageSpecifier
Definition: MessageSpecifier.php:21
$status
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1049
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:246
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:63
NS_FILE
const NS_FILE
Definition: Defines.php:68
$params
$params
Definition: styleTest.css.php:40
ApiUpload\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiUpload.php:36
ApiUpload\$mUpload
UploadBase UploadFromChunks $mUpload
Definition: ApiUpload.php:32
ApiUpload\getApiWarnings
getApiWarnings()
Check warnings.
Definition: ApiUpload.php:664
ApiUpload\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiUpload.php:858
UploadFromStash
Implements uploading from previously stored file.
Definition: UploadFromStash.php:30
ApiUpload\$mParams
$mParams
Definition: ApiUpload.php:34
ContextSource\getUser
getUser()
Get the User object.
Definition: ContextSource.php:133
ApiUpload\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiUpload.php:920
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:41
ApiMessage
Extension of Message implementing IApiMessage.
Definition: ApiMessage.php:198
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:1836
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:109
ApiBase\PARAM_MIN
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:103
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:392
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:316
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:367
ApiBase\PARAM_MAX
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:94
ApiUpload\getContextResult
getContextResult()
Get an upload result based on upload context.
Definition: ApiUpload.php:129
ApiUpload\handleStashException
handleStashException( $e)
Handles a stash exception, giving a useful error to the user.
Definition: ApiUpload.php:729
ApiUpload
Definition: ApiUpload.php:30
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:514
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:212
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:999
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:960
ApiUpload\needsToken
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiUpload.php:916
ApiBase\extractRequestParams
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:718
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:2122
value
$status value
Definition: SyntaxHighlight_GeSHi.class.php:309
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:76
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:930
ApiUpload\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiUpload.php:850
ApiUpload\performUpload
performUpload( $warnings)
Perform the actual upload.
Definition: ApiUpload.php:769
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:754
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:395
ContextSource\exportSession
exportSession()
Export the resolved user IP, HTTP headers, user ID, and session ID.
Definition: ContextSource.php:200
JobQueueGroup\singleton
static singleton( $wiki=false)
Definition: JobQueueGroup.php:71
ApiBase\PARAM_DFLT
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:52
ApiUpload\checkPermissions
checkPermissions( $user)
Checks that the user has permissions to perform this upload.
Definition: ApiUpload.php:536
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:1861
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:490
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:55
ApiBase\getMain
getMain()
Get the main module.
Definition: ApiBase.php:506
UploadFromChunks
Implements uploading from chunks.
Definition: UploadFromChunks.php:30
ApiUpload\transformWarnings
transformWarnings( $warnings)
Definition: ApiUpload.php:670
ApiBase\dieDebug
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:1962
UploadFromFile
Implements regular file uploads.
Definition: UploadFromFile.php:30
ApiBase\getErrorFormatter
getErrorFormatter()
Get the error formatter.
Definition: ApiBase.php:624
array
the array() calling protocol came about after MediaWiki 1.4rc1.
UploadStashException
Definition: UploadStash.php:738
ApiUpload\checkVerification
checkVerification(array $verification)
Performs file verification, dies on error.
Definition: ApiUpload.php:575