MediaWiki  master
SpecialUpload.php
Go to the documentation of this file.
1 <?php
26 
33 class SpecialUpload extends SpecialPage {
38  public function __construct( $request = null ) {
39  parent::__construct( 'Upload', 'upload' );
40  }
41 
42  public function doesWrites() {
43  return true;
44  }
45 
49  public $mRequest;
50  public $mSourceType;
51 
53  public $mUpload;
54 
56  public $mLocalFile;
58 
63  public $mComment;
64  public $mLicense;
65 
69  public $mWatchthis;
72 
76 
78  public $mForReUpload;
79 
82  public $mTokenOk;
83 
85  public $mUploadSuccessful = false;
86 
90 
94  protected function loadRequest() {
95  $this->mRequest = $request = $this->getRequest();
96  $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
97  $this->mUpload = UploadBase::createFromRequest( $request );
98  $this->mUploadClicked = $request->wasPosted()
99  && ( $request->getCheck( 'wpUpload' )
100  || $request->getCheck( 'wpUploadIgnoreWarning' ) );
101 
102  // Guess the desired name from the filename if not provided
103  $this->mDesiredDestName = $request->getText( 'wpDestFile' );
104  if ( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
105  $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
106  }
107  $this->mLicense = $request->getText( 'wpLicense' );
108 
109  $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
110  $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
111  || $request->getCheck( 'wpUploadIgnoreWarning' );
112  $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
113  $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
114  $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
115 
116  $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
117 
118  $commentDefault = '';
119  $commentMsg = $this->msg( 'upload-default-description' )->inContentLanguage();
120  if ( !$this->mForReUpload && !$commentMsg->isDisabled() ) {
121  $commentDefault = $commentMsg->plain();
122  }
123  $this->mComment = $request->getText( 'wpUploadDescription', $commentDefault );
124 
125  $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
126  || $request->getCheck( 'wpReUpload' ); // b/w compat
127 
128  // If it was posted check for the token (no remote POST'ing with user credentials)
129  $token = $request->getVal( 'wpEditToken' );
130  $this->mTokenOk = $this->getUser()->matchEditToken( $token );
131 
132  $this->uploadFormTextTop = '';
133  $this->uploadFormTextAfterSummary = '';
134  }
135 
144  public function userCanExecute( User $user ) {
145  return UploadBase::isEnabled() && parent::userCanExecute( $user );
146  }
147 
158  public function execute( $par ) {
159  $this->useTransactionalTimeLimit();
160 
161  $this->setHeaders();
162  $this->outputHeader();
163 
164  # Check uploading enabled
165  if ( !UploadBase::isEnabled() ) {
166  throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
167  }
168 
169  $this->addHelpLink( 'Help:Managing files' );
170 
171  # Check permissions
172  $user = $this->getUser();
173  $permissionRequired = UploadBase::isAllowed( $user );
174  if ( $permissionRequired !== true ) {
175  throw new PermissionsError( $permissionRequired );
176  }
177 
178  # Check blocks
179  if ( $user->isBlockedFromUpload() ) {
180  throw new UserBlockedError( $user->getBlock() );
181  }
182 
183  // Global blocks
184  if ( $user->isBlockedGlobally() ) {
185  throw new UserBlockedError( $user->getGlobalBlock() );
186  }
187 
188  # Check whether we actually want to allow changing stuff
189  $this->checkReadOnly();
190 
191  $this->loadRequest();
192 
193  # Unsave the temporary file in case this was a cancelled upload
194  if ( $this->mCancelUpload && !$this->unsaveUploadedFile() ) {
195  # Something went wrong, so unsaveUploadedFile showed a warning
196  return;
197  }
198 
199  # Process upload or show a form
200  if (
201  $this->mTokenOk && !$this->mCancelUpload &&
202  ( $this->mUpload && $this->mUploadClicked )
203  ) {
204  $this->processUpload();
205  } else {
206  # Backwards compatibility hook
207  // Avoid PHP 7.1 warning of passing $this by reference
208  $upload = $this;
209  if ( !Hooks::run( 'UploadForm:initial', [ &$upload ] ) ) {
210  wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
211 
212  return;
213  }
214  $this->showUploadForm( $this->getUploadForm() );
215  }
216 
217  # Cleanup
218  if ( $this->mUpload ) {
219  $this->mUpload->cleanupTempFile();
220  }
221  }
222 
228  protected function showUploadForm( $form ) {
229  # Add links if file was previously deleted
230  if ( $this->mDesiredDestName ) {
231  $this->showViewDeletedLinks();
232  }
233 
234  if ( $form instanceof HTMLForm ) {
235  $form->show();
236  } else {
237  $this->getOutput()->addHTML( $form );
238  }
239  }
240 
249  protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
250  # Initialize form
251  $context = new DerivativeContext( $this->getContext() );
252  $context->setTitle( $this->getPageTitle() ); // Remove subpage
253  $form = new UploadForm( [
254  'watch' => $this->getWatchCheck(),
255  'forreupload' => $this->mForReUpload,
256  'sessionkey' => $sessionKey,
257  'hideignorewarning' => $hideIgnoreWarning,
258  'destwarningack' => (bool)$this->mDestWarningAck,
259 
260  'description' => $this->mComment,
261  'texttop' => $this->uploadFormTextTop,
262  'textaftersummary' => $this->uploadFormTextAfterSummary,
263  'destfile' => $this->mDesiredDestName,
264  ], $context, $this->getLinkRenderer() );
265 
266  # Check the token, but only if necessary
267  if (
268  !$this->mTokenOk && !$this->mCancelUpload &&
269  ( $this->mUpload && $this->mUploadClicked )
270  ) {
271  $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
272  }
273 
274  # Give a notice if the user is uploading a file that has been deleted or moved
275  # Note that this is independent from the message 'filewasdeleted'
276  $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
277  $delNotice = ''; // empty by default
278  if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
279  $dbr = wfGetDB( DB_REPLICA );
280 
281  LogEventsList::showLogExtract( $delNotice, [ 'delete', 'move' ],
282  $desiredTitleObj,
283  '', [ 'lim' => 10,
284  'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
285  'showIfEmpty' => false,
286  'msgKey' => [ 'upload-recreate-warning' ] ]
287  );
288  }
289  $form->addPreText( $delNotice );
290 
291  # Add text to form
292  $form->addPreText( '<div id="uploadtext">' .
293  $this->msg( 'uploadtext', [ $this->mDesiredDestName ] )->parseAsBlock() .
294  '</div>' );
295  # Add upload error message
296  $form->addPreText( $message );
297 
298  # Add footer to form
299  $uploadFooter = $this->msg( 'uploadfooter' );
300  if ( !$uploadFooter->isDisabled() ) {
301  $form->addPostText( '<div id="mw-upload-footer-message">'
302  . $uploadFooter->parseAsBlock() . "</div>\n" );
303  }
304 
305  return $form;
306  }
307 
311  protected function showViewDeletedLinks() {
312  $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
313  $user = $this->getUser();
314  // Show a subtitle link to deleted revisions (to sysops et al only)
315  if ( $title instanceof Title ) {
316  $count = $title->isDeleted();
317  if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
318  $restorelink = $this->getLinkRenderer()->makeKnownLink(
319  SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
320  $this->msg( 'restorelink' )->numParams( $count )->text()
321  );
322  $link = $this->msg( $user->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted' )
323  ->rawParams( $restorelink )->parseAsBlock();
324  $this->getOutput()->addHTML(
326  'div',
327  [ 'id' => 'contentSub2' ],
328  $link
329  )
330  );
331  }
332  }
333  }
334 
346  protected function showRecoverableUploadError( $message ) {
347  $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
348  if ( $stashStatus->isGood() ) {
349  $sessionKey = $stashStatus->getValue()->getFileKey();
350  $uploadWarning = 'upload-tryagain';
351  } else {
352  $sessionKey = null;
353  $uploadWarning = 'upload-tryagain-nostash';
354  }
355  $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
356  '<div class="error">' . $message . "</div>\n";
357 
358  $form = $this->getUploadForm( $message, $sessionKey );
359  $form->setSubmitText( $this->msg( $uploadWarning )->escaped() );
360  $this->showUploadForm( $form );
361  }
362 
371  protected function showUploadWarning( $warnings ) {
372  # If there are no warnings, or warnings we can ignore, return early.
373  # mDestWarningAck is set when some javascript has shown the warning
374  # to the user. mForReUpload is set when the user clicks the "upload a
375  # new version" link.
376  if ( !$warnings || ( count( $warnings ) == 1
377  && isset( $warnings['exists'] )
378  && ( $this->mDestWarningAck || $this->mForReUpload ) )
379  ) {
380  return false;
381  }
382 
383  $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
384  if ( $stashStatus->isGood() ) {
385  $sessionKey = $stashStatus->getValue()->getFileKey();
386  $uploadWarning = 'uploadwarning-text';
387  } else {
388  $sessionKey = null;
389  $uploadWarning = 'uploadwarning-text-nostash';
390  }
391 
392  // Add styles for the warning, reused from the live preview
393  $this->getOutput()->addModuleStyles( 'mediawiki.special' );
394 
395  $linkRenderer = $this->getLinkRenderer();
396  $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
397  . '<div class="mw-destfile-warning"><ul>';
398  foreach ( $warnings as $warning => $args ) {
399  if ( $warning == 'badfilename' ) {
400  $this->mDesiredDestName = Title::makeTitle( NS_FILE, $args )->getText();
401  }
402  if ( $warning == 'exists' ) {
403  $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
404  } elseif ( $warning == 'no-change' ) {
405  $file = $args;
406  $filename = $file->getTitle()->getPrefixedText();
407  $msg = "\t<li>" . $this->msg( 'fileexists-no-change', $filename )->parse() . "</li>\n";
408  } elseif ( $warning == 'duplicate-version' ) {
409  $file = $args[0];
410  $count = count( $args );
411  $filename = $file->getTitle()->getPrefixedText();
412  $message = $this->msg( 'fileexists-duplicate-version' )
413  ->params( $filename )
414  ->numParams( $count );
415  $msg = "\t<li>" . $message->parse() . "</li>\n";
416  } elseif ( $warning == 'was-deleted' ) {
417  # If the file existed before and was deleted, warn the user of this
418  $ltitle = SpecialPage::getTitleFor( 'Log' );
419  $llink = $linkRenderer->makeKnownLink(
420  $ltitle,
421  $this->msg( 'deletionlog' )->text(),
422  [],
423  [
424  'type' => 'delete',
425  'page' => Title::makeTitle( NS_FILE, $args )->getPrefixedText(),
426  ]
427  );
428  $msg = "\t<li>" . $this->msg( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
429  } elseif ( $warning == 'duplicate' ) {
430  $msg = $this->getDupeWarning( $args );
431  } elseif ( $warning == 'duplicate-archive' ) {
432  if ( $args === '' ) {
433  $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
434  . "</li>\n";
435  } else {
436  $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
437  Title::makeTitle( NS_FILE, $args )->getPrefixedText() )->parse()
438  . "</li>\n";
439  }
440  } else {
441  if ( $args === true ) {
442  $args = [];
443  } elseif ( !is_array( $args ) ) {
444  $args = [ $args ];
445  }
446  $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
447  }
448  $warningHtml .= $msg;
449  }
450  $warningHtml .= "</ul></div>\n";
451  $warningHtml .= $this->msg( $uploadWarning )->parseAsBlock();
452 
453  $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
454  $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
455  $form->addButton( [
456  'name' => 'wpUploadIgnoreWarning',
457  'value' => $this->msg( 'ignorewarning' )->text()
458  ] );
459  $form->addButton( [
460  'name' => 'wpCancelUpload',
461  'value' => $this->msg( 'reuploaddesc' )->text()
462  ] );
463 
464  $this->showUploadForm( $form );
465 
466  # Indicate that we showed a form
467  return true;
468  }
469 
475  protected function showUploadError( $message ) {
476  $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
477  '<div class="error">' . $message . "</div>\n";
478  $this->showUploadForm( $this->getUploadForm( $message ) );
479  }
480 
485  protected function processUpload() {
486  // Fetch the file if required
487  $status = $this->mUpload->fetchFile();
488  if ( !$status->isOK() ) {
489  $this->showUploadError( $this->getOutput()->parseAsInterface( $status->getWikiText() ) );
490 
491  return;
492  }
493  // Avoid PHP 7.1 warning of passing $this by reference
494  $upload = $this;
495  if ( !Hooks::run( 'UploadForm:BeforeProcessing', [ &$upload ] ) ) {
496  wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
497  // This code path is deprecated. If you want to break upload processing
498  // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
499  // and UploadBase::verifyFile.
500  // If you use this hook to break uploading, the user will be returned
501  // an empty form with no error message whatsoever.
502  return;
503  }
504 
505  // Upload verification
506  $details = $this->mUpload->verifyUpload();
507  if ( $details['status'] != UploadBase::OK ) {
508  $this->processVerificationError( $details );
509 
510  return;
511  }
512 
513  // Verify permissions for this title
514  $permErrors = $this->mUpload->verifyTitlePermissions( $this->getUser() );
515  if ( $permErrors !== true ) {
516  $code = array_shift( $permErrors[0] );
517  $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
518 
519  return;
520  }
521 
522  $this->mLocalFile = $this->mUpload->getLocalFile();
523 
524  // Check warnings if necessary
525  if ( !$this->mIgnoreWarning ) {
526  $warnings = $this->mUpload->checkWarnings();
527  if ( $this->showUploadWarning( $warnings ) ) {
528  return;
529  }
530  }
531 
532  // This is as late as we can throttle, after expected issues have been handled
533  if ( UploadBase::isThrottled( $this->getUser() ) ) {
535  $this->msg( 'actionthrottledtext' )->escaped()
536  );
537  return;
538  }
539 
540  // Get the page text if this is not a reupload
541  if ( !$this->mForReUpload ) {
542  $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
543  $this->mCopyrightStatus, $this->mCopyrightSource, $this->getConfig() );
544  } else {
545  $pageText = false;
546  }
547 
548  $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
549  if ( is_null( $changeTags ) || $changeTags === '' ) {
550  $changeTags = [];
551  } else {
552  $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
553  }
554 
555  if ( $changeTags ) {
556  $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
557  $changeTags, $this->getUser() );
558  if ( !$changeTagsStatus->isOK() ) {
559  $this->showUploadError( $this->getOutput()->parseAsInterface(
560  $changeTagsStatus->getWikiText()
561  ) );
562 
563  return;
564  }
565  }
566 
567  $status = $this->mUpload->performUpload(
568  $this->mComment,
569  $pageText,
570  $this->mWatchthis,
571  $this->getUser(),
572  $changeTags
573  );
574 
575  if ( !$status->isGood() ) {
577  $this->getOutput()->parseAsInterface( $status->getWikiText() )
578  );
579 
580  return;
581  }
582 
583  // Success, redirect to description page
584  $this->mUploadSuccessful = true;
585  // Avoid PHP 7.1 warning of passing $this by reference
586  $upload = $this;
587  Hooks::run( 'SpecialUploadComplete', [ &$upload ] );
588  $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
589  }
590 
600  public static function getInitialPageText( $comment = '', $license = '',
601  $copyStatus = '', $source = '', Config $config = null
602  ) {
603  if ( $config === null ) {
604  wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
605  $config = MediaWikiServices::getInstance()->getMainConfig();
606  }
607 
608  $msg = [];
609  $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
610  /* These messages are transcluded into the actual text of the description page.
611  * Thus, forcing them as content messages makes the upload to produce an int: template
612  * instead of hardcoding it there in the uploader language.
613  */
614  foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
615  if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
616  $msg[$msgName] = "{{int:$msgName}}";
617  } else {
618  $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
619  }
620  }
621 
622  $licenseText = '';
623  if ( $license !== '' ) {
624  $licenseText = '== ' . $msg['license-header'] . " ==\n{{" . $license . "}}\n";
625  }
626 
627  $pageText = $comment . "\n";
628  $headerText = '== ' . $msg['filedesc'] . ' ==';
629  if ( $comment !== '' && strpos( $comment, $headerText ) === false ) {
630  // prepend header to page text unless it's already there (or there is no content)
631  $pageText = $headerText . "\n" . $pageText;
632  }
633 
634  if ( $config->get( 'UseCopyrightUpload' ) ) {
635  $pageText .= '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n";
636  $pageText .= $licenseText;
637  $pageText .= '== ' . $msg['filesource'] . " ==\n" . $source;
638  } else {
639  $pageText .= $licenseText;
640  }
641 
642  // allow extensions to modify the content
643  Hooks::run( 'UploadForm:getInitialPageText', [ &$pageText, $msg, $config ] );
644 
645  return $pageText;
646  }
647 
660  protected function getWatchCheck() {
661  if ( $this->getUser()->getOption( 'watchdefault' ) ) {
662  // Watch all edits!
663  return true;
664  }
665 
666  $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
667  if ( $desiredTitleObj instanceof Title && $this->getUser()->isWatched( $desiredTitleObj ) ) {
668  // Already watched, don't change that
669  return true;
670  }
671 
672  $local = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()
673  ->newFile( $this->mDesiredDestName );
674  if ( $local && $local->exists() ) {
675  // We're uploading a new version of an existing file.
676  // No creation, so don't watch it if we're not already.
677  return false;
678  } else {
679  // New page should get watched if that's our option.
680  return $this->getUser()->getOption( 'watchcreations' ) ||
681  $this->getUser()->getOption( 'watchuploads' );
682  }
683  }
684 
691  protected function processVerificationError( $details ) {
692  switch ( $details['status'] ) {
695  $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
696  break;
698  $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
699  $details['filtered'] )->parse() );
700  break;
702  $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
703  break;
705  $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
706  break;
708  $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
709  break;
710 
713  $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
714  break;
716  $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
717  break;
719  $msg = $this->msg( 'filetype-banned-type' );
720  if ( isset( $details['blacklistedExt'] ) ) {
721  $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
722  } else {
723  $msg->params( $details['finalExt'] );
724  }
725  $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
726  $msg->params( $this->getLanguage()->commaList( $extensions ),
727  count( $extensions ) );
728 
729  // Add PLURAL support for the first parameter. This results
730  // in a bit unlogical parameter sequence, but does not break
731  // old translations
732  if ( isset( $details['blacklistedExt'] ) ) {
733  $msg->params( count( $details['blacklistedExt'] ) );
734  } else {
735  $msg->params( 1 );
736  }
737 
738  $this->showUploadError( $msg->parse() );
739  break;
741  unset( $details['status'] );
742  $code = array_shift( $details['details'] );
743  $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
744  break;
746  if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
747  $args = $details['error'];
748  $error = array_shift( $args );
749  } else {
750  $error = $details['error'];
751  $args = null;
752  }
753 
754  $this->showUploadError( $this->msg( $error, $args )->parse() );
755  break;
756  default:
757  throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
758  }
759  }
760 
766  protected function unsaveUploadedFile() {
767  if ( !( $this->mUpload instanceof UploadFromStash ) ) {
768  return true;
769  }
770  $success = $this->mUpload->unsaveUploadedFile();
771  if ( !$success ) {
772  $this->getOutput()->showFatalError(
773  $this->msg( 'filedeleteerror' )
774  ->params( $this->mUpload->getTempPath() )
775  ->escaped()
776  );
777 
778  return false;
779  } else {
780  return true;
781  }
782  }
783 
793  public static function getExistsWarning( $exists ) {
794  if ( !$exists ) {
795  return '';
796  }
797 
798  $file = $exists['file'];
799  $filename = $file->getTitle()->getPrefixedText();
800  $warnMsg = null;
801 
802  if ( $exists['warning'] == 'exists' ) {
803  // Exact match
804  $warnMsg = wfMessage( 'fileexists', $filename );
805  } elseif ( $exists['warning'] == 'page-exists' ) {
806  // Page exists but file does not
807  $warnMsg = wfMessage( 'filepageexists', $filename );
808  } elseif ( $exists['warning'] == 'exists-normalized' ) {
809  $warnMsg = wfMessage( 'fileexists-extension', $filename,
810  $exists['normalizedFile']->getTitle()->getPrefixedText() );
811  } elseif ( $exists['warning'] == 'thumb' ) {
812  // Swapped argument order compared with other messages for backwards compatibility
813  $warnMsg = wfMessage( 'fileexists-thumbnail-yes',
814  $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
815  } elseif ( $exists['warning'] == 'thumb-name' ) {
816  // Image w/o '180px-' does not exists, but we do not like these filenames
817  $name = $file->getName();
818  $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
819  $warnMsg = wfMessage( 'file-thumbnail-no', $badPart );
820  } elseif ( $exists['warning'] == 'bad-prefix' ) {
821  $warnMsg = wfMessage( 'filename-bad-prefix', $exists['prefix'] );
822  }
823 
824  return $warnMsg ? $warnMsg->title( $file->getTitle() )->parse() : '';
825  }
826 
832  public function getDupeWarning( $dupes ) {
833  if ( !$dupes ) {
834  return '';
835  }
836 
837  $gallery = ImageGalleryBase::factory( false, $this->getContext() );
838  $gallery->setShowBytes( false );
839  $gallery->setShowDimensions( false );
840  foreach ( $dupes as $file ) {
841  $gallery->add( $file->getTitle() );
842  }
843 
844  return '<li>' .
845  $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
846  $gallery->toHTML() . "</li>\n";
847  }
848 
849  protected function getGroupName() {
850  return 'media';
851  }
852 
861  public static function rotationEnabled() {
862  $bitmapHandler = new BitmapHandler();
863  return $bitmapHandler->autoRotateEnabled();
864  }
865 }
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used $groups Array of ChangesListFilterGroup objects(added in 1.34) 'FileDeleteComplete' null for the local wiki Added in
Definition: hooks.txt:1529
static rotationEnabled()
Should we rotate images in the preview on Special:Upload.
__construct( $request=null)
Get data POSTed through the form and assign them to the object.
const FILENAME_TOO_LONG
Definition: UploadBase.php:104
getUploadForm( $message='', $sessionKey='', $hideIgnoreWarning=false)
Get an UploadForm instance with title and text properly set.
getContext()
Gets the context this SpecialPage is executed in.
static getInitialPageText( $comment='', $license='', $copyStatus='', $source='', Config $config=null)
Get the initial image page text based on a comment and optional file status information.
Implements uploading from previously stored file.
getWatchCheck()
See if we should check the &#39;watch this page&#39; checkbox on the form based on the user&#39;s preferences and...
$success
static createFromRequest(&$request, $type=null)
Create a form of UploadBase depending on wpSourceType and initializes it.
Definition: UploadBase.php:181
showUploadError( $message)
Show the upload form with error message, but do not stash the file.
UploadBase $mUpload
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults error
Definition: hooks.txt:2621
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
An IContextSource implementation which will inherit context from another source but allow individual ...
LocalFile $mLocalFile
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
$source
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
bool $mForReUpload
The user followed an "overwrite this file" link.
static factory( $mode=false, IContextSource $context=null)
Get a new image gallery.
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 MediaWikiServices
Definition: injection.txt:23
showViewDeletedLinks()
Shows the "view X deleted revivions link"".
unsaveUploadedFile()
Remove a temporarily kept file stashed by saveTempUploadedFile().
getOutput()
Get the OutputPage being used for this instance.
const ILLEGAL_FILENAME
Definition: UploadBase.php:96
showUploadWarning( $warnings)
Stashes the upload, shows the main form, but adds a "continue anyway button".
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
bool $mUploadSuccessful
Subclasses can use this to determine whether a file was uploaded.
if( $line===false) $args
Definition: cdb.php:64
userCanExecute(User $user)
This page can be shown if uploading is enabled.
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3039
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1244
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
string $mDesiredDestName
User input variables from the "description" section.
Interface for configuration instances.
Definition: Config.php:28
An error page which can definitely be safely rendered using the OutputPage.
processVerificationError( $details)
Provides output to the user for a result of UploadBase::verifyUpload.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Form for handling uploads and special page.
$uploadFormTextTop
Text injection points for hooks not using HTMLForm.
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes! ...
WebRequest FauxRequest $mRequest
Misc variables.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
const FILE_TOO_LARGE
Definition: UploadBase.php:102
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
Using a hook running we can avoid having all this option specific stuff in our mainline code Using hooks
Definition: hooks.txt:73
const MIN_LENGTH_PARTNAME
Definition: UploadBase.php:95
const NS_FILE
Definition: Defines.php:66
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don&#39;t need a full Title object...
Definition: SpecialPage.php:83
Show an error when the user tries to do something whilst blocked.
const VERIFICATION_ERROR
Definition: UploadBase.php:100
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:767
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
showRecoverableUploadError( $message)
Stashes the upload and shows the main upload form.
static isEnabled()
Returns true if uploads are enabled.
Definition: UploadBase.php:132
static isThrottled( $user)
Returns true if the user has surpassed the upload rate limit, false otherwise.
Definition: UploadBase.php:167
const FILETYPE_BADTYPE
Definition: UploadBase.php:99
const FILETYPE_MISSING
Definition: UploadBase.php:98
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:620
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:592
static getExistsWarning( $exists)
Functions for formatting warnings.
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
showUploadForm( $form)
Show the main upload form.
$mIgnoreWarning
User input variables from the root section.
loadRequest()
Initialize instance variables from request and create an Upload handler.
const HOOK_ABORTED
Definition: UploadBase.php:101
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
getUser()
Shortcut to get the User executing this instance.
getConfig()
Shortcut to get main config object.
Show an error when a user tries to do something they do not have the necessary permissions for...
const WINDOWS_NONASCII_FILENAME
Definition: UploadBase.php:103
getLanguage()
Shortcut to get user&#39;s language.
msg( $key)
Wrapper around wfMessage that sets the current context.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2621
Generic handler for bitmap images.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
bool $mCancelUpload
The user clicked "Cancel and return to upload form" button.
const DB_REPLICA
Definition: defines.php:25
static canAddTagsAccompanyingChange(array $tags, User $user=null)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
Definition: ChangeTags.php:521
processUpload()
Do the upload.
getRequest()
Get the WebRequest being used for this instance.
const OK
Definition: UploadBase.php:93
$mDestWarningAck
Hidden variables.
checkReadOnly()
If the wiki is currently in readonly mode, throws a ReadOnlyError.
getDupeWarning( $dupes)
Construct a warning and a gallery from an array of duplicate files.
Sub class of HTMLForm that provides the form section of SpecialUpload.
Definition: UploadForm.php:27
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2621
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
getPageTitle( $subpage=false)
Get a self-referential title object.
const EMPTY_FILE
Definition: UploadBase.php:94
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1454
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
static isAllowed( $user)
Returns true if the user can use this upload module or else a string identifying the missing permissi...
Definition: UploadBase.php:151
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.
MediaWiki Linker LinkRenderer null $linkRenderer
Definition: SpecialPage.php:67