MediaWiki  master
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  $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  $errors = $status->getErrorsArray();
78  $error = array_shift( $errors[0] );
79  $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
80  }
81 
82  // Check if the uploaded file is sane
83  if ( $this->mParams['chunk'] ) {
84  $maxSize = UploadBase::getMaxUploadSize();
85  if ( $this->mParams['filesize'] > $maxSize ) {
86  $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
87  }
88  if ( !$this->mUpload->getTitle() ) {
89  $this->dieUsage( 'Invalid file title supplied', 'internal-error' );
90  }
91  } elseif ( $this->mParams['async'] && $this->mParams['filekey'] ) {
92  // defer verification to background process
93  } else {
94  wfDebug( __METHOD__ . " about to verify\n" );
95  $this->verifyUpload();
96  }
97 
98  // Check if the user has the rights to modify or overwrite the requested title
99  // (This check is irrelevant if stashing is already requested, since the errors
100  // can always be fixed by changing the title)
101  if ( !$this->mParams['stash'] ) {
102  $permErrors = $this->mUpload->verifyTitlePermissions( $user );
103  if ( $permErrors !== true ) {
104  $this->dieRecoverableError( $permErrors[0], 'filename' );
105  }
106  }
107 
108  // Get the result based on the current upload context:
109  try {
110  $result = $this->getContextResult();
111  if ( $result['result'] === 'Success' ) {
112  $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
113  }
114  } catch ( UploadStashException $e ) { // XXX: don't spam exception log
115  $this->handleStashException( $e );
116  }
117 
118  $this->getResult()->addValue( null, $this->getModuleName(), $result );
119 
120  // Cleanup any temporary mess
121  $this->mUpload->cleanupTempFile();
122  }
123 
128  private function getContextResult() {
129  $warnings = $this->getApiWarnings();
130  if ( $warnings && !$this->mParams['ignorewarnings'] ) {
131  // Get warnings formatted in result array format
132  return $this->getWarningsResult( $warnings );
133  } elseif ( $this->mParams['chunk'] ) {
134  // Add chunk, and get result
135  return $this->getChunkResult( $warnings );
136  } elseif ( $this->mParams['stash'] ) {
137  // Stash the file and get stash result
138  return $this->getStashResult( $warnings );
139  }
140 
141  // Check throttle after we've handled warnings
142  if ( UploadBase::isThrottled( $this->getUser() )
143  ) {
144  $this->dieUsageMsg( 'actionthrottledtext' );
145  }
146 
147  // This is the most common case -- a normal upload with no warnings
148  // performUpload will return a formatted properly for the API with status
149  return $this->performUpload( $warnings );
150  }
151 
157  private function getStashResult( $warnings ) {
158  $result = [];
159  // Some uploads can request they be stashed, so as not to publish them immediately.
160  // In this case, a failure to stash ought to be fatal
161  try {
162  $result['result'] = 'Success';
163  $result['filekey'] = $this->performStash();
164  $result['sessionkey'] = $result['filekey']; // backwards compatibility
165  if ( $warnings && count( $warnings ) > 0 ) {
166  $result['warnings'] = $warnings;
167  }
168  } catch ( UploadStashException $e ) {
169  $this->handleStashException( $e );
170  } catch ( Exception $e ) {
171  $this->dieUsage( $e->getMessage(), 'stashfailed' );
172  }
173 
174  return $result;
175  }
176 
182  private function getWarningsResult( $warnings ) {
183  $result = [];
184  $result['result'] = 'Warning';
185  $result['warnings'] = $warnings;
186  // in case the warnings can be fixed with some further user action, let's stash this upload
187  // and return a key they can use to restart it
188  try {
189  $result['filekey'] = $this->performStash();
190  $result['sessionkey'] = $result['filekey']; // backwards compatibility
191  } catch ( Exception $e ) {
192  $result['warnings']['stashfailed'] = $e->getMessage();
193  }
194 
195  return $result;
196  }
197 
203  private function getChunkResult( $warnings ) {
204  $result = [];
205 
206  if ( $warnings && count( $warnings ) > 0 ) {
207  $result['warnings'] = $warnings;
208  }
209 
210  $request = $this->getMain()->getRequest();
211  $chunkPath = $request->getFileTempname( 'chunk' );
212  $chunkSize = $request->getUpload( 'chunk' )->getSize();
213  $totalSoFar = $this->mParams['offset'] + $chunkSize;
214  $minChunkSize = $this->getConfig()->get( 'MinUploadChunkSize' );
215 
216  // Sanity check sizing
217  if ( $totalSoFar > $this->mParams['filesize'] ) {
218  $this->dieUsage(
219  'Offset plus current chunk is greater than claimed file size', 'invalid-chunk'
220  );
221  }
222 
223  // Enforce minimum chunk size
224  if ( $totalSoFar != $this->mParams['filesize'] && $chunkSize < $minChunkSize ) {
225  $this->dieUsage(
226  "Minimum chunk size is $minChunkSize bytes for non-final chunks", 'chunk-too-small'
227  );
228  }
229 
230  if ( $this->mParams['offset'] == 0 ) {
231  try {
232  $filekey = $this->performStash();
233  } catch ( UploadStashException $e ) {
234  $this->handleStashException( $e );
235  } catch ( Exception $e ) {
236  // FIXME: Error handling here is wrong/different from rest of this
237  $this->dieUsage( $e->getMessage(), 'stashfailed' );
238  }
239  } else {
240  $filekey = $this->mParams['filekey'];
241 
242  // Don't allow further uploads to an already-completed session
243  $progress = UploadBase::getSessionStatus( $this->getUser(), $filekey );
244  if ( !$progress ) {
245  // Probably can't get here, but check anyway just in case
246  $this->dieUsage( 'No chunked upload session with this key', 'stashfailed' );
247  } elseif ( $progress['result'] !== 'Continue' || $progress['stage'] !== 'uploading' ) {
248  $this->dieUsage(
249  'Chunked upload is already completed, check status for details', 'stashfailed'
250  );
251  }
252 
253  $status = $this->mUpload->addChunk(
254  $chunkPath, $chunkSize, $this->mParams['offset'] );
255  if ( !$status->isGood() ) {
256  $extradata = [
257  'offset' => $this->mUpload->getOffset(),
258  ];
259 
260  $this->dieUsage( $status->getWikiText( false, false, 'en' ), 'stashfailed', 0, $extradata );
261  }
262  }
263 
264  // Check we added the last chunk:
265  if ( $totalSoFar == $this->mParams['filesize'] ) {
266  if ( $this->mParams['async'] ) {
268  $this->getUser(),
269  $filekey,
270  [ 'result' => 'Poll',
271  'stage' => 'queued', 'status' => Status::newGood() ]
272  );
274  Title::makeTitle( NS_FILE, $filekey ),
275  [
276  'filename' => $this->mParams['filename'],
277  'filekey' => $filekey,
278  'session' => $this->getContext()->exportSession()
279  ]
280  ) );
281  $result['result'] = 'Poll';
282  $result['stage'] = 'queued';
283  } else {
284  $status = $this->mUpload->concatenateChunks();
285  if ( !$status->isGood() ) {
287  $this->getUser(),
288  $filekey,
289  [ 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status ]
290  );
291  $this->dieUsage( $status->getWikiText( false, false, 'en' ), 'stashfailed' );
292  }
293 
294  // The fully concatenated file has a new filekey. So remove
295  // the old filekey and fetch the new one.
296  UploadBase::setSessionStatus( $this->getUser(), $filekey, false );
297  $this->mUpload->stash->removeFile( $filekey );
298  $filekey = $this->mUpload->getLocalFile()->getFileKey();
299 
300  $result['result'] = 'Success';
301  }
302  } else {
304  $this->getUser(),
305  $filekey,
306  [
307  'result' => 'Continue',
308  'stage' => 'uploading',
309  'offset' => $totalSoFar,
310  'status' => Status::newGood(),
311  ]
312  );
313  $result['result'] = 'Continue';
314  $result['offset'] = $totalSoFar;
315  }
316 
317  $result['filekey'] = $filekey;
318 
319  return $result;
320  }
321 
328  private function performStash() {
329  try {
330  $stashFile = $this->mUpload->stashFile( $this->getUser() );
331 
332  if ( !$stashFile ) {
333  throw new MWException( 'Invalid stashed file' );
334  }
335  $fileKey = $stashFile->getFileKey();
336  } catch ( Exception $e ) {
337  $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
338  wfDebug( __METHOD__ . ' ' . $message . "\n" );
339  $className = get_class( $e );
340  throw new $className( $message );
341  }
342 
343  return $fileKey;
344  }
345 
356  private function dieRecoverableError( $error, $parameter, $data = [], $code = 'unknownerror' ) {
357  try {
358  $data['filekey'] = $this->performStash();
359  $data['sessionkey'] = $data['filekey'];
360  } catch ( Exception $e ) {
361  $data['stashfailed'] = $e->getMessage();
362  }
363  $data['invalidparameter'] = $parameter;
364 
365  $parsed = $this->parseMsg( $error );
366  if ( isset( $parsed['data'] ) ) {
367  $data = array_merge( $data, $parsed['data'] );
368  }
369  if ( $parsed['code'] === 'unknownerror' ) {
370  $parsed['code'] = $code;
371  }
372 
373  $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
374  }
375 
383  protected function selectUploadModule() {
384  $request = $this->getMain()->getRequest();
385 
386  // chunk or one and only one of the following parameters is needed
387  if ( !$this->mParams['chunk'] ) {
388  $this->requireOnlyOneParameter( $this->mParams,
389  'filekey', 'file', 'url' );
390  }
391 
392  // Status report for "upload to stash"/"upload from stash"
393  if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
394  $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
395  if ( !$progress ) {
396  $this->dieUsage( 'No result in status data', 'missingresult' );
397  } elseif ( !$progress['status']->isGood() ) {
398  $this->dieUsage( $progress['status']->getWikiText( false, false, 'en' ), 'stashfailed' );
399  }
400  if ( isset( $progress['status']->value['verification'] ) ) {
401  $this->checkVerification( $progress['status']->value['verification'] );
402  }
403  unset( $progress['status'] ); // remove Status object
404  $this->getResult()->addValue( null, $this->getModuleName(), $progress );
405 
406  return false;
407  }
408 
409  // The following modules all require the filename parameter to be set
410  if ( is_null( $this->mParams['filename'] ) ) {
411  $this->dieUsageMsg( [ 'missingparam', 'filename' ] );
412  }
413 
414  if ( $this->mParams['chunk'] ) {
415  // Chunk upload
416  $this->mUpload = new UploadFromChunks();
417  if ( isset( $this->mParams['filekey'] ) ) {
418  if ( $this->mParams['offset'] === 0 ) {
419  $this->dieUsage( 'Cannot supply a filekey when offset is 0', 'badparams' );
420  }
421 
422  // handle new chunk
423  $this->mUpload->continueChunks(
424  $this->mParams['filename'],
425  $this->mParams['filekey'],
426  $request->getUpload( 'chunk' )
427  );
428  } else {
429  if ( $this->mParams['offset'] !== 0 ) {
430  $this->dieUsage( 'Must supply a filekey when offset is non-zero', 'badparams' );
431  }
432 
433  // handle first chunk
434  $this->mUpload->initialize(
435  $this->mParams['filename'],
436  $request->getUpload( 'chunk' )
437  );
438  }
439  } elseif ( isset( $this->mParams['filekey'] ) ) {
440  // Upload stashed in a previous request
441  if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
442  $this->dieUsageMsg( 'invalid-file-key' );
443  }
444 
445  $this->mUpload = new UploadFromStash( $this->getUser() );
446  // This will not download the temp file in initialize() in async mode.
447  // We still have enough information to call checkWarnings() and such.
448  $this->mUpload->initialize(
449  $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
450  );
451  } elseif ( isset( $this->mParams['file'] ) ) {
452  $this->mUpload = new UploadFromFile();
453  $this->mUpload->initialize(
454  $this->mParams['filename'],
455  $request->getUpload( 'file' )
456  );
457  } elseif ( isset( $this->mParams['url'] ) ) {
458  // Make sure upload by URL is enabled:
459  if ( !UploadFromUrl::isEnabled() ) {
460  $this->dieUsageMsg( 'copyuploaddisabled' );
461  }
462 
463  if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
464  $this->dieUsageMsg( 'copyuploadbaddomain' );
465  }
466 
467  if ( !UploadFromUrl::isAllowedUrl( $this->mParams['url'] ) ) {
468  $this->dieUsageMsg( 'copyuploadbadurl' );
469  }
470 
471  $this->mUpload = new UploadFromUrl;
472  $this->mUpload->initialize( $this->mParams['filename'],
473  $this->mParams['url'] );
474  }
475 
476  return true;
477  }
478 
484  protected function checkPermissions( $user ) {
485  // Check whether the user has the appropriate permissions to upload anyway
486  $permission = $this->mUpload->isAllowed( $user );
487 
488  if ( $permission !== true ) {
489  if ( !$user->isLoggedIn() ) {
490  $this->dieUsageMsg( [ 'mustbeloggedin', 'upload' ] );
491  }
492 
493  $this->dieUsageMsg( 'badaccess-groups' );
494  }
495 
496  // Check blocks
497  if ( $user->isBlocked() ) {
498  $this->dieBlocked( $user->getBlock() );
499  }
500 
501  // Global blocks
502  if ( $user->isBlockedGlobally() ) {
503  $this->dieBlocked( $user->getGlobalBlock() );
504  }
505  }
506 
510  protected function verifyUpload() {
511  $verification = $this->mUpload->verifyUpload();
512  if ( $verification['status'] === UploadBase::OK ) {
513  return;
514  }
515 
516  $this->checkVerification( $verification );
517  }
518 
523  protected function checkVerification( array $verification ) {
524  // @todo Move them to ApiBase's message map
525  switch ( $verification['status'] ) {
526  // Recoverable errors
528  $this->dieRecoverableError( 'filename-tooshort', 'filename' );
529  break;
531  $this->dieRecoverableError( 'illegal-filename', 'filename',
532  [ 'filename' => $verification['filtered'] ] );
533  break;
535  $this->dieRecoverableError( 'filename-toolong', 'filename' );
536  break;
538  $this->dieRecoverableError( 'filetype-missing', 'filename' );
539  break;
541  $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
542  break;
543 
544  // Unrecoverable errors
546  $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
547  break;
549  $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
550  break;
551 
553  $extradata = [
554  'filetype' => $verification['finalExt'],
555  'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
556  ];
557  ApiResult::setIndexedTagName( $extradata['allowed'], 'ext' );
558 
559  $msg = 'Filetype not permitted: ';
560  if ( isset( $verification['blacklistedExt'] ) ) {
561  $msg .= implode( ', ', $verification['blacklistedExt'] );
562  $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
563  ApiResult::setIndexedTagName( $extradata['blacklisted'], 'ext' );
564  } else {
565  $msg .= $verification['finalExt'];
566  }
567  $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
568  break;
570  $parsed = $this->parseMsg( $verification['details'] );
571  $info = "This file did not pass file verification: {$parsed['info']}";
572  if ( $verification['details'][0] instanceof IApiMessage ) {
573  $code = $parsed['code'];
574  } else {
575  // For backwards-compatibility, all of the errors from UploadBase::verifyFile() are
576  // reported as 'verification-error', and the real error code is reported in 'details'.
577  $code = 'verification-error';
578  }
579  if ( $verification['details'][0] instanceof IApiMessage ) {
580  $msg = $verification['details'][0];
581  $details = array_merge( [ $msg->getKey() ], $msg->getParams() );
582  } else {
583  $details = $verification['details'];
584  }
585  ApiResult::setIndexedTagName( $details, 'detail' );
586  $data = [ 'details' => $details ];
587  if ( isset( $parsed['data'] ) ) {
588  $data = array_merge( $data, $parsed['data'] );
589  }
590 
591  $this->dieUsage( $info, $code, 0, $data );
592  break;
594  if ( is_array( $verification['error'] ) ) {
595  $params = $verification['error'];
596  } elseif ( $verification['error'] !== '' ) {
597  $params = [ $verification['error'] ];
598  } else {
599  $params = [ 'hookaborted' ];
600  }
601  $key = array_shift( $params );
602  $msg = $this->msg( $key, $params )->inLanguage( 'en' )->useDatabase( false )->text();
603  $this->dieUsage( $msg, 'hookaborted', 0, [ 'details' => $verification['error'] ] );
604  break;
605  default:
606  $this->dieUsage( 'An unknown error occurred', 'unknown-error',
607  0, [ 'details' => [ 'code' => $verification['status'] ] ] );
608  break;
609  }
610  }
611 
619  protected function getApiWarnings() {
620  $warnings = $this->mUpload->checkWarnings();
621 
622  return $this->transformWarnings( $warnings );
623  }
624 
625  protected function transformWarnings( $warnings ) {
626  if ( $warnings ) {
627  // Add indices
628  ApiResult::setIndexedTagName( $warnings, 'warning' );
629 
630  if ( isset( $warnings['duplicate'] ) ) {
631  $dupes = [];
633  foreach ( $warnings['duplicate'] as $dupe ) {
634  $dupes[] = $dupe->getName();
635  }
636  ApiResult::setIndexedTagName( $dupes, 'duplicate' );
637  $warnings['duplicate'] = $dupes;
638  }
639 
640  if ( isset( $warnings['exists'] ) ) {
641  $warning = $warnings['exists'];
642  unset( $warnings['exists'] );
644  $localFile = isset( $warning['normalizedFile'] )
645  ? $warning['normalizedFile']
646  : $warning['file'];
647  $warnings[$warning['warning']] = $localFile->getName();
648  }
649  }
650 
651  return $warnings;
652  }
653 
658  protected function handleStashException( $e ) {
659  $exceptionType = get_class( $e );
660 
661  switch ( $exceptionType ) {
662  case 'UploadStashFileNotFoundException':
663  $this->dieUsage(
664  'Could not find the file in the stash: ' . $e->getMessage(),
665  'stashedfilenotfound'
666  );
667  break;
668  case 'UploadStashBadPathException':
669  $this->dieUsage(
670  'File key of improper format or otherwise invalid: ' . $e->getMessage(),
671  'stashpathinvalid'
672  );
673  break;
674  case 'UploadStashFileException':
675  $this->dieUsage(
676  'Could not store upload in the stash: ' . $e->getMessage(),
677  'stashfilestorage'
678  );
679  break;
680  case 'UploadStashZeroLengthFileException':
681  $this->dieUsage(
682  'File is of zero length, and could not be stored in the stash: ' .
683  $e->getMessage(),
684  'stashzerolength'
685  );
686  break;
687  case 'UploadStashNotLoggedInException':
688  $this->dieUsage( 'Not logged in: ' . $e->getMessage(), 'stashnotloggedin' );
689  break;
690  case 'UploadStashWrongOwnerException':
691  $this->dieUsage( 'Wrong owner: ' . $e->getMessage(), 'stashwrongowner' );
692  break;
693  case 'UploadStashNoSuchKeyException':
694  $this->dieUsage( 'No such filekey: ' . $e->getMessage(), 'stashnosuchfilekey' );
695  break;
696  default:
697  $this->dieUsage( $exceptionType . ': ' . $e->getMessage(), 'stasherror' );
698  break;
699  }
700  }
701 
709  protected function performUpload( $warnings ) {
710  // Use comment as initial page text by default
711  if ( is_null( $this->mParams['text'] ) ) {
712  $this->mParams['text'] = $this->mParams['comment'];
713  }
714 
716  $file = $this->mUpload->getLocalFile();
717 
718  // For preferences mode, we want to watch if 'watchdefault' is set,
719  // or if the *file* doesn't exist, and either 'watchuploads' or
720  // 'watchcreations' is set. But getWatchlistValue()'s automatic
721  // handling checks if the *title* exists or not, so we need to check
722  // all three preferences manually.
723  $watch = $this->getWatchlistValue(
724  $this->mParams['watchlist'], $file->getTitle(), 'watchdefault'
725  );
726 
727  if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
728  $watch = (
729  $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchuploads' ) ||
730  $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchcreations' )
731  );
732  }
733 
734  // Deprecated parameters
735  if ( $this->mParams['watch'] ) {
736  $watch = true;
737  }
738 
739  if ( $this->mParams['tags'] ) {
740  $status = ChangeTags::canAddTagsAccompanyingChange( $this->mParams['tags'], $this->getUser() );
741  if ( !$status->isOK() ) {
742  $this->dieStatus( $status );
743  }
744  }
745 
746  // No errors, no warnings: do the upload
747  if ( $this->mParams['async'] ) {
748  $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
749  if ( $progress && $progress['result'] === 'Poll' ) {
750  $this->dieUsage( 'Upload from stash already in progress.', 'publishfailed' );
751  }
753  $this->getUser(),
754  $this->mParams['filekey'],
755  [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() ]
756  );
758  Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
759  [
760  'filename' => $this->mParams['filename'],
761  'filekey' => $this->mParams['filekey'],
762  'comment' => $this->mParams['comment'],
763  'tags' => $this->mParams['tags'],
764  'text' => $this->mParams['text'],
765  'watch' => $watch,
766  'session' => $this->getContext()->exportSession()
767  ]
768  ) );
769  $result['result'] = 'Poll';
770  $result['stage'] = 'queued';
771  } else {
773  $status = $this->mUpload->performUpload( $this->mParams['comment'],
774  $this->mParams['text'], $watch, $this->getUser(), $this->mParams['tags'] );
775 
776  if ( !$status->isGood() ) {
777  // Is there really no better way to do this?
778  $errors = $status->getErrorsByType( 'error' );
779  $msg = array_merge( [ $errors[0]['message'] ], $errors[0]['params'] );
780  $data = $status->getErrorsArray();
781  ApiResult::setIndexedTagName( $data, 'error' );
782  // For backwards-compatibility, we use the 'internal-error' fallback key and merge $data
783  // into the root of the response (rather than something sane like [ 'details' => $data ]).
784  $this->dieRecoverableError( $msg, null, $data, 'internal-error' );
785  }
786  $result['result'] = 'Success';
787  }
788 
789  $result['filename'] = $file->getName();
790  if ( $warnings && count( $warnings ) > 0 ) {
791  $result['warnings'] = $warnings;
792  }
793 
794  return $result;
795  }
796 
797  public function mustBePosted() {
798  return true;
799  }
800 
801  public function isWriteMode() {
802  return true;
803  }
804 
805  public function getAllowedParams() {
806  $params = [
807  'filename' => [
808  ApiBase::PARAM_TYPE => 'string',
809  ],
810  'comment' => [
811  ApiBase::PARAM_DFLT => ''
812  ],
813  'tags' => [
814  ApiBase::PARAM_TYPE => 'tags',
815  ApiBase::PARAM_ISMULTI => true,
816  ],
817  'text' => [
818  ApiBase::PARAM_TYPE => 'text',
819  ],
820  'watch' => [
821  ApiBase::PARAM_DFLT => false,
823  ],
824  'watchlist' => [
825  ApiBase::PARAM_DFLT => 'preferences',
827  'watch',
828  'preferences',
829  'nochange'
830  ],
831  ],
832  'ignorewarnings' => false,
833  'file' => [
834  ApiBase::PARAM_TYPE => 'upload',
835  ],
836  'url' => null,
837  'filekey' => null,
838  'sessionkey' => [
840  ],
841  'stash' => false,
842 
843  'filesize' => [
844  ApiBase::PARAM_TYPE => 'integer',
845  ApiBase::PARAM_MIN => 0,
847  ],
848  'offset' => [
849  ApiBase::PARAM_TYPE => 'integer',
850  ApiBase::PARAM_MIN => 0,
851  ],
852  'chunk' => [
853  ApiBase::PARAM_TYPE => 'upload',
854  ],
855 
856  'async' => false,
857  'checkstatus' => false,
858  ];
859 
860  return $params;
861  }
862 
863  public function needsToken() {
864  return 'csrf';
865  }
866 
867  protected function getExamplesMessages() {
868  return [
869  'action=upload&filename=Wiki.png' .
870  '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
871  => 'apihelp-upload-example-url',
872  'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
873  => 'apihelp-upload-example-filekey',
874  ];
875  }
876 
877  public function getHelpUrls() {
878  return 'https://www.mediawiki.org/wiki/API:Upload';
879  }
880 }
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:867
initialize($name, $url)
Entry point for API upload.
const FILENAME_TOO_LONG
Definition: UploadBase.php:71
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:484
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1980
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:128
getWatchlistValue($watchlist, $titleObj, $userOption=null)
Return true if we're to watch the page, false if not, null if no change.
Definition: ApiBase.php:837
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:510
const ILLEGAL_FILENAME
Definition: UploadBase.php:63
getChunkResult($warnings)
Get the result of a chunk upload.
Definition: ApiUpload.php:203
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:709
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:1814
getWarningsResult($warnings)
Get Warnings Result.
Definition: ApiUpload.php:182
performStash()
Stash the file and return the file key Also re-raises exceptions with slightly more informative messa...
Definition: ApiUpload.php:328
static isThrottled($user)
Returns true if the user has surpassed the upload rate limit, false otherwise.
Definition: UploadBase.php:138
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:797
getStashResult($warnings)
Get Stash Result, throws an exception if the file could not be stashed.
Definition: ApiUpload.php:157
getConfig()
Get the Config object.
MediaWiki exception.
Definition: MWException.php:26
getApiWarnings()
Check warnings.
Definition: ApiUpload.php:619
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:69
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:457
const MIN_LENGTH_PARTNAME
Definition: UploadBase.php:62
const NS_FILE
Definition: Defines.php:75
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:356
const VERIFICATION_ERROR
Definition: UploadBase.php:67
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:776
static isEnabled()
Returns true if uploads are enabled.
Definition: UploadBase.php:103
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:66
transformWarnings($warnings)
Definition: ApiUpload.php:625
static singleton($wiki=false)
const FILETYPE_MISSING
Definition: UploadBase.php:65
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:68
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2458
selectUploadModule()
Select an upload module and set it to mUpload.
Definition: ApiUpload.php:383
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:70
getAllowedParams()
Definition: ApiUpload.php:805
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:1481
dieBlocked(Block $block)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1498
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:1020
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
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:378
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:2149
checkVerification(array $verification)
Performs file verification, dies on error.
Definition: ApiUpload.php:523
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:60
dieStatus($status)
Throw a UsageException based on the errors in the Status object.
Definition: ApiBase.php:1570
UploadBase UploadFromChunks $mUpload
Definition: ApiUpload.php:32
static isValidKey($key)
getUser()
Get the User object.
const EMPTY_FILE
Definition: UploadBase.php:61
static makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:503
dieUsageMsg($error)
Output the error message related to a certain array.
Definition: ApiBase.php:2099
static newGood($value=null)
Factory function for good results.
Definition: Status.php:101
handleStashException($e)
Handles a stash exception, giving a useful error to the user.
Definition: ApiUpload.php:658