MediaWiki  1.28.0
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->dieUsageMsg( '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->dieUsage( 'No upload module set', 'nomodule' );
65  }
66  } catch ( UploadStashException $e ) { // XXX: don't spam exception log
67  list( $msg, $code ) = $this->handleStashException( get_class( $e ), $e->getMessage() );
68  $this->dieUsage( $msg, $code );
69  }
70 
71  // First check permission to upload
72  $this->checkPermissions( $user );
73 
74  // Fetch the file (usually a no-op)
76  $status = $this->mUpload->fetchFile();
77  if ( !$status->isGood() ) {
78  $errors = $status->getErrorsArray();
79  $error = array_shift( $errors[0] );
80  $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
81  }
82 
83  // Check if the uploaded file is sane
84  if ( $this->mParams['chunk'] ) {
85  $maxSize = UploadBase::getMaxUploadSize();
86  if ( $this->mParams['filesize'] > $maxSize ) {
87  $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
88  }
89  if ( !$this->mUpload->getTitle() ) {
90  $this->dieUsage( 'Invalid file title supplied', 'internal-error' );
91  }
92  } elseif ( $this->mParams['async'] && $this->mParams['filekey'] ) {
93  // defer verification to background process
94  } else {
95  wfDebug( __METHOD__ . " about to verify\n" );
96  $this->verifyUpload();
97  }
98 
99  // Check if the user has the rights to modify or overwrite the requested title
100  // (This check is irrelevant if stashing is already requested, since the errors
101  // can always be fixed by changing the title)
102  if ( !$this->mParams['stash'] ) {
103  $permErrors = $this->mUpload->verifyTitlePermissions( $user );
104  if ( $permErrors !== true ) {
105  $this->dieRecoverableError( $permErrors[0], 'filename' );
106  }
107  }
108 
109  // Get the result based on the current upload context:
110  try {
111  $result = $this->getContextResult();
112  } catch ( UploadStashException $e ) { // XXX: don't spam exception log
113  list( $msg, $code ) = $this->handleStashException( get_class( $e ), $e->getMessage() );
114  $this->dieUsage( $msg, $code );
115  }
116  $this->getResult()->addValue( null, $this->getModuleName(), $result );
117 
118  // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
119  // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
120  if ( $result['result'] === 'Success' ) {
121  $imageinfo = $this->mUpload->getImageInfo( $this->getResult() );
122  $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
123  }
124 
125  // Cleanup any temporary mess
126  $this->mUpload->cleanupTempFile();
127  }
128 
133  private function getContextResult() {
134  $warnings = $this->getApiWarnings();
135  if ( $warnings && !$this->mParams['ignorewarnings'] ) {
136  // Get warnings formatted in result array format
137  return $this->getWarningsResult( $warnings );
138  } elseif ( $this->mParams['chunk'] ) {
139  // Add chunk, and get result
140  return $this->getChunkResult( $warnings );
141  } elseif ( $this->mParams['stash'] ) {
142  // Stash the file and get stash result
143  return $this->getStashResult( $warnings );
144  }
145 
146  // Check throttle after we've handled warnings
147  if ( UploadBase::isThrottled( $this->getUser() )
148  ) {
149  $this->dieUsageMsg( 'actionthrottledtext' );
150  }
151 
152  // This is the most common case -- a normal upload with no warnings
153  // performUpload will return a formatted properly for the API with status
154  return $this->performUpload( $warnings );
155  }
156 
162  private function getStashResult( $warnings ) {
163  $result = [];
164  $result['result'] = 'Success';
165  if ( $warnings && count( $warnings ) > 0 ) {
166  $result['warnings'] = $warnings;
167  }
168  // Some uploads can request they be stashed, so as not to publish them immediately.
169  // In this case, a failure to stash ought to be fatal
170  $this->performStash( 'critical', $result );
171 
172  return $result;
173  }
174 
180  private function getWarningsResult( $warnings ) {
181  $result = [];
182  $result['result'] = 'Warning';
183  $result['warnings'] = $warnings;
184  // in case the warnings can be fixed with some further user action, let's stash this upload
185  // and return a key they can use to restart it
186  $this->performStash( 'optional', $result );
187 
188  return $result;
189  }
190 
196  private function getChunkResult( $warnings ) {
197  $result = [];
198 
199  if ( $warnings && count( $warnings ) > 0 ) {
200  $result['warnings'] = $warnings;
201  }
202 
203  $request = $this->getMain()->getRequest();
204  $chunkPath = $request->getFileTempname( 'chunk' );
205  $chunkSize = $request->getUpload( 'chunk' )->getSize();
206  $totalSoFar = $this->mParams['offset'] + $chunkSize;
207  $minChunkSize = $this->getConfig()->get( 'MinUploadChunkSize' );
208 
209  // Sanity check sizing
210  if ( $totalSoFar > $this->mParams['filesize'] ) {
211  $this->dieUsage(
212  'Offset plus current chunk is greater than claimed file size', 'invalid-chunk'
213  );
214  }
215 
216  // Enforce minimum chunk size
217  if ( $totalSoFar != $this->mParams['filesize'] && $chunkSize < $minChunkSize ) {
218  $this->dieUsage(
219  "Minimum chunk size is $minChunkSize bytes for non-final chunks", 'chunk-too-small'
220  );
221  }
222 
223  if ( $this->mParams['offset'] == 0 ) {
224  $filekey = $this->performStash( 'critical' );
225  } else {
226  $filekey = $this->mParams['filekey'];
227 
228  // Don't allow further uploads to an already-completed session
229  $progress = UploadBase::getSessionStatus( $this->getUser(), $filekey );
230  if ( !$progress ) {
231  // Probably can't get here, but check anyway just in case
232  $this->dieUsage( 'No chunked upload session with this key', 'stashfailed' );
233  } elseif ( $progress['result'] !== 'Continue' || $progress['stage'] !== 'uploading' ) {
234  $this->dieUsage(
235  'Chunked upload is already completed, check status for details', 'stashfailed'
236  );
237  }
238 
239  $status = $this->mUpload->addChunk(
240  $chunkPath, $chunkSize, $this->mParams['offset'] );
241  if ( !$status->isGood() ) {
242  $extradata = [
243  'offset' => $this->mUpload->getOffset(),
244  ];
245 
246  $this->dieStatusWithCode( $status, 'stashfailed', $extradata );
247  }
248  }
249 
250  // Check we added the last chunk:
251  if ( $totalSoFar == $this->mParams['filesize'] ) {
252  if ( $this->mParams['async'] ) {
254  $this->getUser(),
255  $filekey,
256  [ 'result' => 'Poll',
257  'stage' => 'queued', 'status' => Status::newGood() ]
258  );
260  Title::makeTitle( NS_FILE, $filekey ),
261  [
262  'filename' => $this->mParams['filename'],
263  'filekey' => $filekey,
264  'session' => $this->getContext()->exportSession()
265  ]
266  ) );
267  $result['result'] = 'Poll';
268  $result['stage'] = 'queued';
269  } else {
270  $status = $this->mUpload->concatenateChunks();
271  if ( !$status->isGood() ) {
273  $this->getUser(),
274  $filekey,
275  [ 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status ]
276  );
277  $this->dieStatusWithCode( $status, 'stashfailed' );
278  }
279 
280  // We can only get warnings like 'duplicate' after concatenating the chunks
281  $warnings = $this->getApiWarnings();
282  if ( $warnings ) {
283  $result['warnings'] = $warnings;
284  }
285 
286  // The fully concatenated file has a new filekey. So remove
287  // the old filekey and fetch the new one.
288  UploadBase::setSessionStatus( $this->getUser(), $filekey, false );
289  $this->mUpload->stash->removeFile( $filekey );
290  $filekey = $this->mUpload->getStashFile()->getFileKey();
291 
292  $result['result'] = 'Success';
293  }
294  } else {
296  $this->getUser(),
297  $filekey,
298  [
299  'result' => 'Continue',
300  'stage' => 'uploading',
301  'offset' => $totalSoFar,
302  'status' => Status::newGood(),
303  ]
304  );
305  $result['result'] = 'Continue';
306  $result['offset'] = $totalSoFar;
307  }
308 
309  $result['filekey'] = $filekey;
310 
311  return $result;
312  }
313 
326  private function performStash( $failureMode, &$data = null ) {
327  $isPartial = (bool)$this->mParams['chunk'];
328  try {
329  $status = $this->mUpload->tryStashFile( $this->getUser(), $isPartial );
330 
331  if ( $status->isGood() && !$status->getValue() ) {
332  // Not actually a 'good' status...
333  $status->fatal( new ApiRawMessage( 'Invalid stashed file', 'stashfailed' ) );
334  }
335  } catch ( Exception $e ) {
336  $debugMessage = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
337  wfDebug( __METHOD__ . ' ' . $debugMessage . "\n" );
338  $status = Status::newFatal( new ApiRawMessage( $e->getMessage(), 'stashfailed' ) );
339  }
340 
341  if ( $status->isGood() ) {
342  $stashFile = $status->getValue();
343  $data['filekey'] = $stashFile->getFileKey();
344  // Backwards compatibility
345  $data['sessionkey'] = $data['filekey'];
346  return $data['filekey'];
347  }
348 
349  if ( $status->getMessage()->getKey() === 'uploadstash-exception' ) {
350  // The exceptions thrown by upload stash code and pretty silly and UploadBase returns poor
351  // Statuses for it. Just extract the exception details and parse them ourselves.
352  list( $exceptionType, $message ) = $status->getMessage()->getParams();
353  $debugMessage = 'Stashing temporary file failed: ' . $exceptionType . ' ' . $message;
354  wfDebug( __METHOD__ . ' ' . $debugMessage . "\n" );
355  list( $msg, $code ) = $this->handleStashException( $exceptionType, $message );
356  $status = Status::newFatal( new ApiRawMessage( $msg, $code ) );
357  }
358 
359  // Bad status
360  if ( $failureMode !== 'optional' ) {
361  $this->dieStatus( $status );
362  } else {
363  list( $code, $msg ) = $this->getErrorFromStatus( $status );
364  $data['stashfailed'] = $msg;
365  return null;
366  }
367  }
368 
379  private function dieRecoverableError( $error, $parameter, $data = [], $code = 'unknownerror' ) {
380  $this->performStash( 'optional', $data );
381  $data['invalidparameter'] = $parameter;
382 
383  $parsed = $this->parseMsg( $error );
384  if ( isset( $parsed['data'] ) ) {
385  $data = array_merge( $data, $parsed['data'] );
386  }
387  if ( $parsed['code'] === 'unknownerror' ) {
388  $parsed['code'] = $code;
389  }
390 
391  $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
392  }
393 
403  public function dieStatusWithCode( $status, $overrideCode, $moreExtraData = null ) {
404  $extraData = null;
405  list( $code, $msg ) = $this->getErrorFromStatus( $status, $extraData );
406  $errors = $status->getErrorsByType( 'error' ) ?: $status->getErrorsByType( 'warning' );
407  if ( !( $errors[0]['message'] instanceof IApiMessage ) ) {
408  $code = $overrideCode;
409  }
410  if ( $moreExtraData ) {
411  $extraData = $extraData ?: [];
412  $extraData += $moreExtraData;
413  }
414  $this->dieUsage( $msg, $code, 0, $extraData );
415  }
416 
424  protected function selectUploadModule() {
425  $request = $this->getMain()->getRequest();
426 
427  // chunk or one and only one of the following parameters is needed
428  if ( !$this->mParams['chunk'] ) {
429  $this->requireOnlyOneParameter( $this->mParams,
430  'filekey', 'file', 'url' );
431  }
432 
433  // Status report for "upload to stash"/"upload from stash"
434  if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
435  $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
436  if ( !$progress ) {
437  $this->dieUsage( 'No result in status data', 'missingresult' );
438  } elseif ( !$progress['status']->isGood() ) {
439  $this->dieStatusWithCode( $progress['status'], 'stashfailed' );
440  }
441  if ( isset( $progress['status']->value['verification'] ) ) {
442  $this->checkVerification( $progress['status']->value['verification'] );
443  }
444  if ( isset( $progress['status']->value['warnings'] ) ) {
445  $warnings = $this->transformWarnings( $progress['status']->value['warnings'] );
446  if ( $warnings ) {
447  $progress['warnings'] = $warnings;
448  }
449  }
450  unset( $progress['status'] ); // remove Status object
451  $imageinfo = null;
452  if ( isset( $progress['imageinfo'] ) ) {
453  $imageinfo = $progress['imageinfo'];
454  unset( $progress['imageinfo'] );
455  }
456 
457  $this->getResult()->addValue( null, $this->getModuleName(), $progress );
458  // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
459  // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
460  if ( $imageinfo ) {
461  $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
462  }
463 
464  return false;
465  }
466 
467  // The following modules all require the filename parameter to be set
468  if ( is_null( $this->mParams['filename'] ) ) {
469  $this->dieUsageMsg( [ 'missingparam', 'filename' ] );
470  }
471 
472  if ( $this->mParams['chunk'] ) {
473  // Chunk upload
474  $this->mUpload = new UploadFromChunks( $this->getUser() );
475  if ( isset( $this->mParams['filekey'] ) ) {
476  if ( $this->mParams['offset'] === 0 ) {
477  $this->dieUsage( 'Cannot supply a filekey when offset is 0', 'badparams' );
478  }
479 
480  // handle new chunk
481  $this->mUpload->continueChunks(
482  $this->mParams['filename'],
483  $this->mParams['filekey'],
484  $request->getUpload( 'chunk' )
485  );
486  } else {
487  if ( $this->mParams['offset'] !== 0 ) {
488  $this->dieUsage( 'Must supply a filekey when offset is non-zero', 'badparams' );
489  }
490 
491  // handle first chunk
492  $this->mUpload->initialize(
493  $this->mParams['filename'],
494  $request->getUpload( 'chunk' )
495  );
496  }
497  } elseif ( isset( $this->mParams['filekey'] ) ) {
498  // Upload stashed in a previous request
499  if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
500  $this->dieUsageMsg( 'invalid-file-key' );
501  }
502 
503  $this->mUpload = new UploadFromStash( $this->getUser() );
504  // This will not download the temp file in initialize() in async mode.
505  // We still have enough information to call checkWarnings() and such.
506  $this->mUpload->initialize(
507  $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
508  );
509  } elseif ( isset( $this->mParams['file'] ) ) {
510  $this->mUpload = new UploadFromFile();
511  $this->mUpload->initialize(
512  $this->mParams['filename'],
513  $request->getUpload( 'file' )
514  );
515  } elseif ( isset( $this->mParams['url'] ) ) {
516  // Make sure upload by URL is enabled:
517  if ( !UploadFromUrl::isEnabled() ) {
518  $this->dieUsageMsg( 'copyuploaddisabled' );
519  }
520 
521  if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
522  $this->dieUsageMsg( 'copyuploadbaddomain' );
523  }
524 
525  if ( !UploadFromUrl::isAllowedUrl( $this->mParams['url'] ) ) {
526  $this->dieUsageMsg( 'copyuploadbadurl' );
527  }
528 
529  $this->mUpload = new UploadFromUrl;
530  $this->mUpload->initialize( $this->mParams['filename'],
531  $this->mParams['url'] );
532  }
533 
534  return true;
535  }
536 
542  protected function checkPermissions( $user ) {
543  // Check whether the user has the appropriate permissions to upload anyway
544  $permission = $this->mUpload->isAllowed( $user );
545 
546  if ( $permission !== true ) {
547  if ( !$user->isLoggedIn() ) {
548  $this->dieUsageMsg( [ 'mustbeloggedin', 'upload' ] );
549  }
550 
551  $this->dieUsageMsg( 'badaccess-groups' );
552  }
553 
554  // Check blocks
555  if ( $user->isBlocked() ) {
556  $this->dieBlocked( $user->getBlock() );
557  }
558 
559  // Global blocks
560  if ( $user->isBlockedGlobally() ) {
561  $this->dieBlocked( $user->getGlobalBlock() );
562  }
563  }
564 
568  protected function verifyUpload() {
569  $verification = $this->mUpload->verifyUpload();
570  if ( $verification['status'] === UploadBase::OK ) {
571  return;
572  }
573 
574  $this->checkVerification( $verification );
575  }
576 
581  protected function checkVerification( array $verification ) {
582  // @todo Move them to ApiBase's message map
583  switch ( $verification['status'] ) {
584  // Recoverable errors
586  $this->dieRecoverableError( 'filename-tooshort', 'filename' );
587  break;
589  $this->dieRecoverableError( 'illegal-filename', 'filename',
590  [ 'filename' => $verification['filtered'] ] );
591  break;
593  $this->dieRecoverableError( 'filename-toolong', 'filename' );
594  break;
596  $this->dieRecoverableError( 'filetype-missing', 'filename' );
597  break;
599  $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
600  break;
601 
602  // Unrecoverable errors
604  $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
605  break;
607  $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
608  break;
609 
611  $extradata = [
612  'filetype' => $verification['finalExt'],
613  'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
614  ];
615  ApiResult::setIndexedTagName( $extradata['allowed'], 'ext' );
616 
617  $msg = 'Filetype not permitted: ';
618  if ( isset( $verification['blacklistedExt'] ) ) {
619  $msg .= implode( ', ', $verification['blacklistedExt'] );
620  $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
621  ApiResult::setIndexedTagName( $extradata['blacklisted'], 'ext' );
622  } else {
623  $msg .= $verification['finalExt'];
624  }
625  $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
626  break;
628  $parsed = $this->parseMsg( $verification['details'] );
629  $info = "This file did not pass file verification: {$parsed['info']}";
630  if ( $verification['details'][0] instanceof IApiMessage ) {
631  $code = $parsed['code'];
632  } else {
633  // For backwards-compatibility, all of the errors from UploadBase::verifyFile() are
634  // reported as 'verification-error', and the real error code is reported in 'details'.
635  $code = 'verification-error';
636  }
637  if ( $verification['details'][0] instanceof IApiMessage ) {
638  $msg = $verification['details'][0];
639  $details = array_merge( [ $msg->getKey() ], $msg->getParams() );
640  } else {
641  $details = $verification['details'];
642  }
643  ApiResult::setIndexedTagName( $details, 'detail' );
644  $data = [ 'details' => $details ];
645  if ( isset( $parsed['data'] ) ) {
646  $data = array_merge( $data, $parsed['data'] );
647  }
648 
649  $this->dieUsage( $info, $code, 0, $data );
650  break;
652  if ( is_array( $verification['error'] ) ) {
653  $params = $verification['error'];
654  } elseif ( $verification['error'] !== '' ) {
655  $params = [ $verification['error'] ];
656  } else {
657  $params = [ 'hookaborted' ];
658  }
659  $key = array_shift( $params );
660  $msg = $this->msg( $key, $params )->inLanguage( 'en' )->useDatabase( false )->text();
661  $this->dieUsage( $msg, 'hookaborted', 0, [ 'details' => $verification['error'] ] );
662  break;
663  default:
664  $this->dieUsage( 'An unknown error occurred', 'unknown-error',
665  0, [ 'details' => [ 'code' => $verification['status'] ] ] );
666  break;
667  }
668  }
669 
677  protected function getApiWarnings() {
678  $warnings = $this->mUpload->checkWarnings();
679 
680  return $this->transformWarnings( $warnings );
681  }
682 
683  protected function transformWarnings( $warnings ) {
684  if ( $warnings ) {
685  // Add indices
686  ApiResult::setIndexedTagName( $warnings, 'warning' );
687 
688  if ( isset( $warnings['duplicate'] ) ) {
689  $dupes = [];
691  foreach ( $warnings['duplicate'] as $dupe ) {
692  $dupes[] = $dupe->getName();
693  }
694  ApiResult::setIndexedTagName( $dupes, 'duplicate' );
695  $warnings['duplicate'] = $dupes;
696  }
697 
698  if ( isset( $warnings['exists'] ) ) {
699  $warning = $warnings['exists'];
700  unset( $warnings['exists'] );
702  $localFile = isset( $warning['normalizedFile'] )
703  ? $warning['normalizedFile']
704  : $warning['file'];
705  $warnings[$warning['warning']] = $localFile->getName();
706  }
707 
708  if ( isset( $warnings['no-change'] ) ) {
710  $file = $warnings['no-change'];
711  unset( $warnings['no-change'] );
712 
713  $warnings['nochange'] = [
714  'timestamp' => wfTimestamp( TS_ISO_8601, $file->getTimestamp() )
715  ];
716  }
717 
718  if ( isset( $warnings['duplicate-version'] ) ) {
719  $dupes = [];
721  foreach ( $warnings['duplicate-version'] as $dupe ) {
722  $dupes[] = [
723  'timestamp' => wfTimestamp( TS_ISO_8601, $dupe->getTimestamp() )
724  ];
725  }
726  unset( $warnings['duplicate-version'] );
727 
728  ApiResult::setIndexedTagName( $dupes, 'ver' );
729  $warnings['duplicateversions'] = $dupes;
730  }
731  }
732 
733  return $warnings;
734  }
735 
742  protected function handleStashException( $exceptionType, $message ) {
743  switch ( $exceptionType ) {
744  case 'UploadStashFileNotFoundException':
745  return [
746  'Could not find the file in the stash: ' . $message,
747  'stashedfilenotfound'
748  ];
749  case 'UploadStashBadPathException':
750  return [
751  'File key of improper format or otherwise invalid: ' . $message,
752  'stashpathinvalid'
753  ];
754  case 'UploadStashFileException':
755  return [
756  'Could not store upload in the stash: ' . $message,
757  'stashfilestorage'
758  ];
759  case 'UploadStashZeroLengthFileException':
760  return [
761  'File is of zero length, and could not be stored in the stash: ' .
762  $message,
763  'stashzerolength'
764  ];
765  case 'UploadStashNotLoggedInException':
766  return [ 'Not logged in: ' . $message, 'stashnotloggedin' ];
767  case 'UploadStashWrongOwnerException':
768  return [ 'Wrong owner: ' . $message, 'stashwrongowner' ];
769  case 'UploadStashNoSuchKeyException':
770  return [ 'No such filekey: ' . $message, 'stashnosuchfilekey' ];
771  default:
772  return [ $exceptionType . ': ' . $message, 'stasherror' ];
773  }
774  }
775 
783  protected function performUpload( $warnings ) {
784  // Use comment as initial page text by default
785  if ( is_null( $this->mParams['text'] ) ) {
786  $this->mParams['text'] = $this->mParams['comment'];
787  }
788 
790  $file = $this->mUpload->getLocalFile();
791 
792  // For preferences mode, we want to watch if 'watchdefault' is set,
793  // or if the *file* doesn't exist, and either 'watchuploads' or
794  // 'watchcreations' is set. But getWatchlistValue()'s automatic
795  // handling checks if the *title* exists or not, so we need to check
796  // all three preferences manually.
797  $watch = $this->getWatchlistValue(
798  $this->mParams['watchlist'], $file->getTitle(), 'watchdefault'
799  );
800 
801  if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
802  $watch = (
803  $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchuploads' ) ||
804  $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchcreations' )
805  );
806  }
807 
808  // Deprecated parameters
809  if ( $this->mParams['watch'] ) {
810  $watch = true;
811  }
812 
813  if ( $this->mParams['tags'] ) {
814  $status = ChangeTags::canAddTagsAccompanyingChange( $this->mParams['tags'], $this->getUser() );
815  if ( !$status->isOK() ) {
816  $this->dieStatus( $status );
817  }
818  }
819 
820  // No errors, no warnings: do the upload
821  if ( $this->mParams['async'] ) {
822  $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
823  if ( $progress && $progress['result'] === 'Poll' ) {
824  $this->dieUsage( 'Upload from stash already in progress.', 'publishfailed' );
825  }
827  $this->getUser(),
828  $this->mParams['filekey'],
829  [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() ]
830  );
832  Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
833  [
834  'filename' => $this->mParams['filename'],
835  'filekey' => $this->mParams['filekey'],
836  'comment' => $this->mParams['comment'],
837  'tags' => $this->mParams['tags'],
838  'text' => $this->mParams['text'],
839  'watch' => $watch,
840  'session' => $this->getContext()->exportSession()
841  ]
842  ) );
843  $result['result'] = 'Poll';
844  $result['stage'] = 'queued';
845  } else {
847  $status = $this->mUpload->performUpload( $this->mParams['comment'],
848  $this->mParams['text'], $watch, $this->getUser(), $this->mParams['tags'] );
849 
850  if ( !$status->isGood() ) {
851  // Is there really no better way to do this?
852  $errors = $status->getErrorsByType( 'error' );
853  $msg = array_merge( [ $errors[0]['message'] ], $errors[0]['params'] );
854  $data = $status->getErrorsArray();
855  ApiResult::setIndexedTagName( $data, 'error' );
856  // For backwards-compatibility, we use the 'internal-error' fallback key and merge $data
857  // into the root of the response (rather than something sane like [ 'details' => $data ]).
858  $this->dieRecoverableError( $msg, null, $data, 'internal-error' );
859  }
860  $result['result'] = 'Success';
861  }
862 
863  $result['filename'] = $file->getName();
864  if ( $warnings && count( $warnings ) > 0 ) {
865  $result['warnings'] = $warnings;
866  }
867 
868  return $result;
869  }
870 
871  public function mustBePosted() {
872  return true;
873  }
874 
875  public function isWriteMode() {
876  return true;
877  }
878 
879  public function getAllowedParams() {
880  $params = [
881  'filename' => [
882  ApiBase::PARAM_TYPE => 'string',
883  ],
884  'comment' => [
885  ApiBase::PARAM_DFLT => ''
886  ],
887  'tags' => [
888  ApiBase::PARAM_TYPE => 'tags',
889  ApiBase::PARAM_ISMULTI => true,
890  ],
891  'text' => [
892  ApiBase::PARAM_TYPE => 'text',
893  ],
894  'watch' => [
895  ApiBase::PARAM_DFLT => false,
897  ],
898  'watchlist' => [
899  ApiBase::PARAM_DFLT => 'preferences',
901  'watch',
902  'preferences',
903  'nochange'
904  ],
905  ],
906  'ignorewarnings' => false,
907  'file' => [
908  ApiBase::PARAM_TYPE => 'upload',
909  ],
910  'url' => null,
911  'filekey' => null,
912  'sessionkey' => [
914  ],
915  'stash' => false,
916 
917  'filesize' => [
918  ApiBase::PARAM_TYPE => 'integer',
919  ApiBase::PARAM_MIN => 0,
921  ],
922  'offset' => [
923  ApiBase::PARAM_TYPE => 'integer',
924  ApiBase::PARAM_MIN => 0,
925  ],
926  'chunk' => [
927  ApiBase::PARAM_TYPE => 'upload',
928  ],
929 
930  'async' => false,
931  'checkstatus' => false,
932  ];
933 
934  return $params;
935  }
936 
937  public function needsToken() {
938  return 'csrf';
939  }
940 
941  protected function getExamplesMessages() {
942  return [
943  'action=upload&filename=Wiki.png' .
944  '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
945  => 'apihelp-upload-example-url',
946  'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
947  => 'apihelp-upload-example-filekey',
948  ];
949  }
950 
951  public function getHelpUrls() {
952  return 'https://www.mediawiki.org/wiki/API:Upload';
953  }
954 }
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
getExamplesMessages()
Definition: ApiUpload.php:941
initialize($name, $url)
Entry point for API upload.
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
const FILENAME_TOO_LONG
Definition: UploadBase.php:80
the array() calling protocol came about after MediaWiki 1.4rc1.
getResult()
Get the result object.
Definition: ApiBase.php:577
Implements uploading from previously stored file.
checkPermissions($user)
Checks that the user has permissions to perform this upload.
Definition: ApiUpload.php:542
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:2102
static newFatal($message)
Factory function for fatal errors.
Definition: StatusValue.php:63
performStash($failureMode, &$data=null)
Stash the file and add the file key, or error information if it fails, to the data.
Definition: ApiUpload.php:326
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
getMain()
Get the main module.
Definition: ApiBase.php:473
static getSessionStatus(User $user, $statusKey)
Get the current status of a chunked upload (used for polling)
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:91
getContextResult()
Get an upload result based on upload context.
Definition: ApiUpload.php:133
getWatchlistValue($watchlist, $titleObj, $userOption=null)
Return true if we're to watch the page, false if not, null if no change.
Definition: ApiBase.php:870
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:678
requireOnlyOneParameter($params, $required)
Die if none or more than one of a certain set of parameters is set and not false. ...
Definition: ApiBase.php:714
Interface for messages with machine-readable data for use by the API.
Definition: ApiMessage.php:35
verifyUpload()
Performs file verification, dies on error.
Definition: ApiUpload.php:568
const ILLEGAL_FILENAME
Definition: UploadBase.php:72
getChunkResult($warnings)
Get the result of a chunk upload.
Definition: ApiUpload.php:196
const TS_ISO_8601
ISO 8601 format with no timezone: 1986-02-09T20:00:00Z.
Definition: defines.php:28
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:618
performUpload($warnings)
Perform the actual upload.
Definition: ApiUpload.php:783
dieStatusWithCode($status, $overrideCode, $moreExtraData=null)
Like dieStatus(), but always uses $overrideCode for the error code, unless the code comes from IApiMe...
Definition: ApiUpload.php:403
Implements uploading from a HTTP resource.
static isAllowedHost($url)
Checks whether the URL is for an allowed host The domains in the whitelist can include wildcard chara...
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
static getMaxUploadSize($forType=null)
Get the MediaWiki maximum uploaded file size for given type of upload, based on $wgMaxUploadSize.
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:Associative array mapping language codes to prefixed links of the form"language:title".&$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:1934
getWarningsResult($warnings)
Get Warnings Result.
Definition: ApiUpload.php:180
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static isThrottled($user)
Returns true if the user has surpassed the upload rate limit, false otherwise.
Definition: UploadBase.php:147
msg()
Get a Message object with context set Parameters are the same as wfMessage()
static isEnabled()
Checks if the upload from URL feature is enabled.
Implements regular file uploads.
Upload a file from the upload stash into the local file repo.
mustBePosted()
Definition: ApiUpload.php:871
getErrorFromStatus($status, &$extraData=null)
Get error (as code, string) from a Status object.
Definition: ApiBase.php:1619
getStashResult($warnings)
Get Stash Result, throws an exception if the file could not be stashed.
Definition: ApiUpload.php:162
getConfig()
Get the Config object.
getApiWarnings()
Check warnings.
Definition: ApiUpload.php:677
Assemble the segments of a chunked upload.
getContext()
Get the base IContextSource object.
Implements uploading from chunks.
$params
const FILE_TOO_LARGE
Definition: UploadBase.php:78
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:457
static newGood($value=null)
Factory function for good results.
Definition: StatusValue.php:76
const MIN_LENGTH_PARTNAME
Definition: UploadBase.php:71
const NS_FILE
Definition: Defines.php:62
dieRecoverableError($error, $parameter, $data=[], $code= 'unknownerror')
Throw an error that the user can recover from by providing a better value for $parameter.
Definition: ApiUpload.php:379
const VERIFICATION_ERROR
Definition: UploadBase.php:76
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
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:802
static isEnabled()
Returns true if uploads are enabled.
Definition: UploadBase.php:112
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 local account $user
Definition: hooks.txt:242
const FILETYPE_BADTYPE
Definition: UploadBase.php:75
transformWarnings($warnings)
Definition: ApiUpload.php:683
static singleton($wiki=false)
const FILETYPE_MISSING
Definition: UploadBase.php:74
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
exportSession()
Export the resolved user IP, HTTP headers, user ID, and session ID.
const HOOK_ABORTED
Definition: UploadBase.php:77
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2573
selectUploadModule()
Select an upload module and set it to mUpload.
Definition: ApiUpload.php:424
static isAllowedUrl($url)
Checks whether the URL is not allowed.
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:53
const WINDOWS_NONASCII_FILENAME
Definition: UploadBase.php:79
getAllowedParams()
Definition: ApiUpload.php:879
dieUsage($description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1574
dieBlocked(Block $block)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1591
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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:1046
Extension of RawMessage implementing IApiMessage.
Definition: ApiMessage.php:171
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:39
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:106
handleStashException($exceptionType, $message)
Handles a stash exception, giving a useful error to the user.
Definition: ApiUpload.php:742
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:392
static setSessionStatus(User $user, $statusKey, $value)
Set the current status of a chunked upload (used for polling)
parseMsg($error)
Return the error message related to a certain array.
Definition: ApiBase.php:2242
checkVerification(array $verification)
Performs file verification, dies on error.
Definition: ApiUpload.php:581
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:100
const OK
Definition: UploadBase.php:69
dieStatus($status)
Throw a UsageException based on the errors in the Status object.
Definition: ApiBase.php:1663
UploadBase UploadFromChunks $mUpload
Definition: ApiUpload.php:32
static isValidKey($key)
getUser()
Get the User object.
const EMPTY_FILE
Definition: UploadBase.php:70
static makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:511
dieUsageMsg($error)
Output the error message related to a certain array.
Definition: ApiBase.php:2192