MediaWiki  master
EditPage.php
Go to the documentation of this file.
1 <?php
28 
44 class EditPage {
48  const UNICODE_CHECK = 'ℳ𝒲♥𝓊𝓃𝒾𝒸ℴ𝒹ℯ';
49 
53  const AS_SUCCESS_UPDATE = 200;
54 
59 
63  const AS_HOOK_ERROR = 210;
64 
69 
74 
78  const AS_CONTENT_TOO_BIG = 216;
79 
84 
89 
93  const AS_READ_ONLY_PAGE = 220;
94 
98  const AS_RATE_LIMITED = 221;
99 
105 
111 
115  const AS_BLANK_ARTICLE = 224;
116 
120  const AS_CONFLICT_DETECTED = 225;
121 
126  const AS_SUMMARY_NEEDED = 226;
127 
131  const AS_TEXTBOX_EMPTY = 228;
132 
137 
141  const AS_END = 231;
142 
146  const AS_SPAM_ERROR = 232;
147 
152 
157 
163 
168  const AS_SELF_REDIRECT = 236;
169 
174  const AS_CHANGE_TAG_ERROR = 237;
175 
179  const AS_PARSE_ERROR = 240;
180 
186 
191 
195  const EDITFORM_ID = 'editform';
196 
201  const POST_EDIT_COOKIE_KEY_PREFIX = 'PostEditRevision';
202 
217 
222  public $mArticle;
224  private $page;
225 
230  public $mTitle;
231 
233  private $mContextTitle = null;
234 
236  public $action = 'submit';
237 
242  public $isConflict = false;
243 
245  public $isNew = false;
246 
249 
251  public $formtype;
252 
257  public $firsttime;
258 
260  public $lastDelete;
261 
263  public $mTokenOk = false;
264 
266  public $mTokenOkExceptSuffix = false;
267 
269  public $mTriedSave = false;
270 
272  public $incompleteForm = false;
273 
275  public $tooBig = false;
276 
278  public $missingComment = false;
279 
281  public $missingSummary = false;
282 
284  public $allowBlankSummary = false;
285 
287  protected $blankArticle = false;
288 
290  protected $allowBlankArticle = false;
291 
293  protected $selfRedirect = false;
294 
296  protected $allowSelfRedirect = false;
297 
299  public $autoSumm = '';
300 
302  public $hookError = '';
303 
306 
308  public $hasPresetSummary = false;
309 
311  public $mBaseRevision = false;
312 
314  public $mShowSummaryField = true;
315 
316  # Form values
317 
319  public $save = false;
320 
322  public $preview = false;
323 
325  public $diff = false;
326 
328  public $minoredit = false;
329 
331  public $watchthis = false;
332 
334  public $recreate = false;
335 
339  public $textbox1 = '';
340 
342  public $textbox2 = '';
343 
345  public $summary = '';
346 
350  public $nosummary = false;
351 
356  public $edittime = '';
357 
369  private $editRevId = null;
370 
372  public $section = '';
373 
375  public $sectiontitle = '';
376 
380  public $starttime = '';
381 
387  public $oldid = 0;
388 
394  public $parentRevId = 0;
395 
397  public $editintro = '';
398 
400  public $scrolltop = null;
401 
403  public $bot = true;
404 
407 
410 
412  private $changeTags = null;
413 
414  # Placeholders for text injection by hooks (must be HTML)
415  # extensions should take care to _append_ to the present value
416 
418  public $editFormPageTop = '';
419  public $editFormTextTop = '';
423  public $editFormTextBottom = '';
427 
428  /* $didSave should be set to true whenever an article was successfully altered. */
429  public $didSave = false;
430  public $undidRev = 0;
431 
432  public $suppressIntro = false;
433 
435  protected $edit;
436 
438  protected $contentLength = false;
439 
443  private $enableApiEditOverride = false;
444 
448  protected $context;
449 
453  private $isOldRev = false;
454 
458  private $unicodeCheck;
459 
466 
471 
475  public function __construct( Article $article ) {
476  $this->mArticle = $article;
477  $this->page = $article->getPage(); // model object
478  $this->mTitle = $article->getTitle();
479 
480  // Make sure the local context is in sync with other member variables.
481  // Particularly make sure everything is using the same WikiPage instance.
482  // This should probably be the case in Article as well, but it's
483  // particularly important for EditPage, to make use of the in-place caching
484  // facility in WikiPage::prepareContentForEdit.
485  $this->context = new DerivativeContext( $article->getContext() );
486  $this->context->setWikiPage( $this->page );
487  $this->context->setTitle( $this->mTitle );
488 
489  $this->contentModel = $this->mTitle->getContentModel();
490 
491  $handler = ContentHandler::getForModelID( $this->contentModel );
492  $this->contentFormat = $handler->getDefaultFormat();
493  $this->editConflictHelperFactory = [ $this, 'newTextConflictHelper' ];
494  }
495 
499  public function getArticle() {
500  return $this->mArticle;
501  }
502 
507  public function getContext() {
508  return $this->context;
509  }
510 
515  public function getTitle() {
516  return $this->mTitle;
517  }
518 
524  public function setContextTitle( $title ) {
525  $this->mContextTitle = $title;
526  }
527 
536  public function getContextTitle() {
537  if ( is_null( $this->mContextTitle ) ) {
538  wfDeprecated( __METHOD__ . ' called with no title set', '1.32' );
539  global $wgTitle;
540  return $wgTitle;
541  } else {
542  return $this->mContextTitle;
543  }
544  }
545 
553  public function isSupportedContentModel( $modelId ) {
554  return $this->enableApiEditOverride === true ||
555  ContentHandler::getForModelID( $modelId )->supportsDirectEditing();
556  }
557 
564  public function setApiEditOverride( $enableOverride ) {
565  $this->enableApiEditOverride = $enableOverride;
566  }
567 
571  public function submit() {
572  wfDeprecated( __METHOD__, '1.29' );
573  $this->edit();
574  }
575 
587  public function edit() {
588  // Allow extensions to modify/prevent this form or submission
589  if ( !Hooks::run( 'AlternateEdit', [ $this ] ) ) {
590  return;
591  }
592 
593  wfDebug( __METHOD__ . ": enter\n" );
594 
595  $request = $this->context->getRequest();
596  // If they used redlink=1 and the page exists, redirect to the main article
597  if ( $request->getBool( 'redlink' ) && $this->mTitle->exists() ) {
598  $this->context->getOutput()->redirect( $this->mTitle->getFullURL() );
599  return;
600  }
601 
602  $this->importFormData( $request );
603  $this->firsttime = false;
604 
605  if ( wfReadOnly() && $this->save ) {
606  // Force preview
607  $this->save = false;
608  $this->preview = true;
609  }
610 
611  if ( $this->save ) {
612  $this->formtype = 'save';
613  } elseif ( $this->preview ) {
614  $this->formtype = 'preview';
615  } elseif ( $this->diff ) {
616  $this->formtype = 'diff';
617  } else { # First time through
618  $this->firsttime = true;
619  if ( $this->previewOnOpen() ) {
620  $this->formtype = 'preview';
621  } else {
622  $this->formtype = 'initial';
623  }
624  }
625 
626  $permErrors = $this->getEditPermissionErrors( $this->save ? 'secure' : 'full' );
627  if ( $permErrors ) {
628  wfDebug( __METHOD__ . ": User can't edit\n" );
629 
630  if ( $this->context->getUser()->getBlock() ) {
631  // track block with a cookie if it doesn't exists already
632  $this->context->getUser()->trackBlockWithCookie();
633 
634  // Auto-block user's IP if the account was "hard" blocked
635  if ( !wfReadOnly() ) {
637  $this->context->getUser()->spreadAnyEditBlock();
638  } );
639  }
640 
641  $config = $this->context->getConfig();
642  if ( $config->get( 'EnableBlockNoticeStats' ) ) {
643  $wiki = $config->get( 'DBname' );
644  $statsd = MediaWikiServices::getInstance()->getStatsdDataFactory();
645  $statsd->increment( 'BlockNotices.' . $wiki . '.WikitextEditor.shown' );
646  }
647  }
648  $this->displayPermissionsError( $permErrors );
649 
650  return;
651  }
652 
653  $revision = $this->mArticle->getRevisionFetched();
654  // Disallow editing revisions with content models different from the current one
655  // Undo edits being an exception in order to allow reverting content model changes.
656  if ( $revision
657  && $revision->getContentModel() !== $this->contentModel
658  ) {
659  $prevRev = null;
660  if ( $this->undidRev ) {
661  $undidRevObj = Revision::newFromId( $this->undidRev );
662  $prevRev = $undidRevObj ? $undidRevObj->getPrevious() : null;
663  }
664  if ( !$this->undidRev
665  || !$prevRev
666  || $prevRev->getContentModel() !== $this->contentModel
667  ) {
668  $this->displayViewSourcePage(
669  $this->getContentObject(),
670  $this->context->msg(
671  'contentmodelediterror',
672  $revision->getContentModel(),
674  )->plain()
675  );
676  return;
677  }
678  }
679 
680  $this->isConflict = false;
681 
682  # Show applicable editing introductions
683  if ( $this->formtype == 'initial' || $this->firsttime ) {
684  $this->showIntro();
685  }
686 
687  # Attempt submission here. This will check for edit conflicts,
688  # and redundantly check for locked database, blocked IPs, etc.
689  # that edit() already checked just in case someone tries to sneak
690  # in the back door with a hand-edited submission URL.
691 
692  if ( $this->formtype == 'save' ) {
693  $resultDetails = null;
694  $status = $this->attemptSave( $resultDetails );
695  if ( !$this->handleStatus( $status, $resultDetails ) ) {
696  return;
697  }
698  }
699 
700  # First time through: get contents, set time for conflict
701  # checking, etc.
702  if ( $this->formtype == 'initial' || $this->firsttime ) {
703  if ( $this->initialiseForm() === false ) {
704  $out = $this->context->getOutput();
705  if ( $out->getRedirect() === '' ) { // mcrundo hack redirects, don't override it
706  $this->noSuchSectionPage();
707  }
708  return;
709  }
710 
711  if ( !$this->mTitle->getArticleID() ) {
712  Hooks::run( 'EditFormPreloadText', [ &$this->textbox1, &$this->mTitle ] );
713  } else {
714  Hooks::run( 'EditFormInitialText', [ $this ] );
715  }
716 
717  }
718 
719  $this->showEditForm();
720  }
721 
726  protected function getEditPermissionErrors( $rigor = 'secure' ) {
727  $user = $this->context->getUser();
728  $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user, $rigor );
729  # Can this title be created?
730  if ( !$this->mTitle->exists() ) {
731  $permErrors = array_merge(
732  $permErrors,
733  wfArrayDiff2(
734  $this->mTitle->getUserPermissionsErrors( 'create', $user, $rigor ),
735  $permErrors
736  )
737  );
738  }
739  # Ignore some permissions errors when a user is just previewing/viewing diffs
740  $remove = [];
741  foreach ( $permErrors as $error ) {
742  if ( ( $this->preview || $this->diff )
743  && (
744  $error[0] == 'blockedtext' ||
745  $error[0] == 'autoblockedtext' ||
746  $error[0] == 'systemblockedtext'
747  )
748  ) {
749  $remove[] = $error;
750  }
751  }
752  $permErrors = wfArrayDiff2( $permErrors, $remove );
753 
754  return $permErrors;
755  }
756 
770  protected function displayPermissionsError( array $permErrors ) {
771  $out = $this->context->getOutput();
772  if ( $this->context->getRequest()->getBool( 'redlink' ) ) {
773  // The edit page was reached via a red link.
774  // Redirect to the article page and let them click the edit tab if
775  // they really want a permission error.
776  $out->redirect( $this->mTitle->getFullURL() );
777  return;
778  }
779 
780  $content = $this->getContentObject();
781 
782  # Use the normal message if there's nothing to display
783  if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
784  $action = $this->mTitle->exists() ? 'edit' :
785  ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
786  throw new PermissionsError( $action, $permErrors );
787  }
788 
789  $this->displayViewSourcePage(
790  $content,
791  $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
792  );
793  }
794 
800  protected function displayViewSourcePage( Content $content, $errorMessage = '' ) {
801  $out = $this->context->getOutput();
802  Hooks::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
803 
804  $out->setRobotPolicy( 'noindex,nofollow' );
805  $out->setPageTitle( $this->context->msg(
806  'viewsource-title',
807  $this->getContextTitle()->getPrefixedText()
808  ) );
809  $out->addBacklinkSubtitle( $this->getContextTitle() );
810  $out->addHTML( $this->editFormPageTop );
811  $out->addHTML( $this->editFormTextTop );
812 
813  if ( $errorMessage !== '' ) {
814  $out->addWikiTextAsInterface( $errorMessage );
815  $out->addHTML( "<hr />\n" );
816  }
817 
818  # If the user made changes, preserve them when showing the markup
819  # (This happens when a user is blocked during edit, for instance)
820  if ( !$this->firsttime ) {
821  $text = $this->textbox1;
822  $out->addWikiMsg( 'viewyourtext' );
823  } else {
824  try {
825  $text = $this->toEditText( $content );
826  } catch ( MWException $e ) {
827  # Serialize using the default format if the content model is not supported
828  # (e.g. for an old revision with a different model)
829  $text = $content->serialize();
830  }
831  $out->addWikiMsg( 'viewsourcetext' );
832  }
833 
834  $out->addHTML( $this->editFormTextBeforeContent );
835  $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
836  $out->addHTML( $this->editFormTextAfterContent );
837 
838  $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
839 
840  $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
841 
842  $out->addHTML( $this->editFormTextBottom );
843  if ( $this->mTitle->exists() ) {
844  $out->returnToMain( null, $this->mTitle );
845  }
846  }
847 
853  protected function previewOnOpen() {
854  $config = $this->context->getConfig();
855  $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
856  $request = $this->context->getRequest();
857  if ( $config->get( 'RawHtml' ) ) {
858  // If raw HTML is enabled, disable preview on open
859  // since it has to be posted with a token for
860  // security reasons
861  return false;
862  }
863  if ( $request->getVal( 'preview' ) == 'yes' ) {
864  // Explicit override from request
865  return true;
866  } elseif ( $request->getVal( 'preview' ) == 'no' ) {
867  // Explicit override from request
868  return false;
869  } elseif ( $this->section == 'new' ) {
870  // Nothing *to* preview for new sections
871  return false;
872  } elseif ( ( $request->getCheck( 'preload' ) || $this->mTitle->exists() )
873  && $this->context->getUser()->getOption( 'previewonfirst' )
874  ) {
875  // Standard preference behavior
876  return true;
877  } elseif ( !$this->mTitle->exists()
878  && isset( $previewOnOpenNamespaces[$this->mTitle->getNamespace()] )
879  && $previewOnOpenNamespaces[$this->mTitle->getNamespace()]
880  ) {
881  // Categories are special
882  return true;
883  } else {
884  return false;
885  }
886  }
887 
894  protected function isWrongCaseUserConfigPage() {
895  if ( $this->mTitle->isUserConfigPage() ) {
896  $name = $this->mTitle->getSkinFromConfigSubpage();
897  $skins = array_merge(
898  array_keys( Skin::getSkinNames() ),
899  [ 'common' ]
900  );
901  return !in_array( $name, $skins )
902  && in_array( strtolower( $name ), $skins );
903  } else {
904  return false;
905  }
906  }
907 
915  protected function isSectionEditSupported() {
916  $contentHandler = ContentHandler::getForTitle( $this->mTitle );
917  return $contentHandler->supportsSections();
918  }
919 
925  public function importFormData( &$request ) {
926  # Section edit can come from either the form or a link
927  $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
928 
929  if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
930  throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
931  }
932 
933  $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
934 
935  if ( $request->wasPosted() ) {
936  # These fields need to be checked for encoding.
937  # Also remove trailing whitespace, but don't remove _initial_
938  # whitespace from the text boxes. This may be significant formatting.
939  $this->textbox1 = rtrim( $request->getText( 'wpTextbox1' ) );
940  if ( !$request->getCheck( 'wpTextbox2' ) ) {
941  // Skip this if wpTextbox2 has input, it indicates that we came
942  // from a conflict page with raw page text, not a custom form
943  // modified by subclasses
945  if ( $textbox1 !== null ) {
946  $this->textbox1 = $textbox1;
947  }
948  }
949 
950  $this->unicodeCheck = $request->getText( 'wpUnicodeCheck' );
951 
952  $this->summary = $request->getText( 'wpSummary' );
953 
954  # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
955  # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
956  # section titles.
957  $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
958 
959  # Treat sectiontitle the same way as summary.
960  # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
961  # currently doing double duty as both edit summary and section title. Right now this
962  # is just to allow API edits to work around this limitation, but this should be
963  # incorporated into the actual edit form when EditPage is rewritten (T20654, T28312).
964  $this->sectiontitle = $request->getText( 'wpSectionTitle' );
965  $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
966 
967  $this->edittime = $request->getVal( 'wpEdittime' );
968  $this->editRevId = $request->getIntOrNull( 'editRevId' );
969  $this->starttime = $request->getVal( 'wpStarttime' );
970 
971  $undidRev = $request->getInt( 'wpUndidRevision' );
972  if ( $undidRev ) {
973  $this->undidRev = $undidRev;
974  }
975 
976  $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
977 
978  if ( $this->textbox1 === '' && !$request->getCheck( 'wpTextbox1' ) ) {
979  // wpTextbox1 field is missing, possibly due to being "too big"
980  // according to some filter rules such as Suhosin's setting for
981  // suhosin.request.max_value_length (d'oh)
982  $this->incompleteForm = true;
983  } else {
984  // If we receive the last parameter of the request, we can fairly
985  // claim the POST request has not been truncated.
986  $this->incompleteForm = !$request->getVal( 'wpUltimateParam' );
987  }
988  if ( $this->incompleteForm ) {
989  # If the form is incomplete, force to preview.
990  wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
991  wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
992  $this->preview = true;
993  } else {
994  $this->preview = $request->getCheck( 'wpPreview' );
995  $this->diff = $request->getCheck( 'wpDiff' );
996 
997  // Remember whether a save was requested, so we can indicate
998  // if we forced preview due to session failure.
999  $this->mTriedSave = !$this->preview;
1000 
1001  if ( $this->tokenOk( $request ) ) {
1002  # Some browsers will not report any submit button
1003  # if the user hits enter in the comment box.
1004  # The unmarked state will be assumed to be a save,
1005  # if the form seems otherwise complete.
1006  wfDebug( __METHOD__ . ": Passed token check.\n" );
1007  } elseif ( $this->diff ) {
1008  # Failed token check, but only requested "Show Changes".
1009  wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
1010  } else {
1011  # Page might be a hack attempt posted from
1012  # an external site. Preview instead of saving.
1013  wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
1014  $this->preview = true;
1015  }
1016  }
1017  $this->save = !$this->preview && !$this->diff;
1018  if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
1019  $this->edittime = null;
1020  }
1021 
1022  if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
1023  $this->starttime = null;
1024  }
1025 
1026  $this->recreate = $request->getCheck( 'wpRecreate' );
1027 
1028  $this->minoredit = $request->getCheck( 'wpMinoredit' );
1029  $this->watchthis = $request->getCheck( 'wpWatchthis' );
1030 
1031  $user = $this->context->getUser();
1032  # Don't force edit summaries when a user is editing their own user or talk page
1033  if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
1034  && $this->mTitle->getText() == $user->getName()
1035  ) {
1036  $this->allowBlankSummary = true;
1037  } else {
1038  $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
1039  || !$user->getOption( 'forceeditsummary' );
1040  }
1041 
1042  $this->autoSumm = $request->getText( 'wpAutoSummary' );
1043 
1044  $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
1045  $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
1046 
1047  $changeTags = $request->getVal( 'wpChangeTags' );
1048  if ( is_null( $changeTags ) || $changeTags === '' ) {
1049  $this->changeTags = [];
1050  } else {
1051  $this->changeTags = array_filter( array_map( 'trim', explode( ',',
1052  $changeTags ) ) );
1053  }
1054  } else {
1055  # Not a posted form? Start with nothing.
1056  wfDebug( __METHOD__ . ": Not a posted form.\n" );
1057  $this->textbox1 = '';
1058  $this->summary = '';
1059  $this->sectiontitle = '';
1060  $this->edittime = '';
1061  $this->editRevId = null;
1062  $this->starttime = wfTimestampNow();
1063  $this->edit = false;
1064  $this->preview = false;
1065  $this->save = false;
1066  $this->diff = false;
1067  $this->minoredit = false;
1068  // Watch may be overridden by request parameters
1069  $this->watchthis = $request->getBool( 'watchthis', false );
1070  $this->recreate = false;
1071 
1072  // When creating a new section, we can preload a section title by passing it as the
1073  // preloadtitle parameter in the URL (T15100)
1074  if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
1075  $this->sectiontitle = $request->getVal( 'preloadtitle' );
1076  // Once wpSummary isn't being use for setting section titles, we should delete this.
1077  $this->summary = $request->getVal( 'preloadtitle' );
1078  } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) !== '' ) {
1079  $this->summary = $request->getText( 'summary' );
1080  if ( $this->summary !== '' ) {
1081  $this->hasPresetSummary = true;
1082  }
1083  }
1084 
1085  if ( $request->getVal( 'minor' ) ) {
1086  $this->minoredit = true;
1087  }
1088  }
1089 
1090  $this->oldid = $request->getInt( 'oldid' );
1091  $this->parentRevId = $request->getInt( 'parentRevId' );
1092 
1093  $this->bot = $request->getBool( 'bot', true );
1094  $this->nosummary = $request->getBool( 'nosummary' );
1095 
1096  // May be overridden by revision.
1097  $this->contentModel = $request->getText( 'model', $this->contentModel );
1098  // May be overridden by revision.
1099  $this->contentFormat = $request->getText( 'format', $this->contentFormat );
1100 
1101  try {
1102  $handler = ContentHandler::getForModelID( $this->contentModel );
1103  } catch ( MWUnknownContentModelException $e ) {
1104  throw new ErrorPageError(
1105  'editpage-invalidcontentmodel-title',
1106  'editpage-invalidcontentmodel-text',
1107  [ wfEscapeWikiText( $this->contentModel ) ]
1108  );
1109  }
1110 
1111  if ( !$handler->isSupportedFormat( $this->contentFormat ) ) {
1112  throw new ErrorPageError(
1113  'editpage-notsupportedcontentformat-title',
1114  'editpage-notsupportedcontentformat-text',
1115  [
1116  wfEscapeWikiText( $this->contentFormat ),
1117  wfEscapeWikiText( ContentHandler::getLocalizedName( $this->contentModel ) )
1118  ]
1119  );
1120  }
1121 
1128  $this->editintro = $request->getText( 'editintro',
1129  // Custom edit intro for new sections
1130  $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
1131 
1132  // Allow extensions to modify form data
1133  Hooks::run( 'EditPage::importFormData', [ $this, $request ] );
1134  }
1135 
1145  protected function importContentFormData( &$request ) {
1146  return; // Don't do anything, EditPage already extracted wpTextbox1
1147  }
1148 
1154  public function initialiseForm() {
1155  $this->edittime = $this->page->getTimestamp();
1156  $this->editRevId = $this->page->getLatest();
1157 
1158  $content = $this->getContentObject( false ); # TODO: track content object?!
1159  if ( $content === false ) {
1160  return false;
1161  }
1162  $this->textbox1 = $this->toEditText( $content );
1163 
1164  $user = $this->context->getUser();
1165  // activate checkboxes if user wants them to be always active
1166  # Sort out the "watch" checkbox
1167  if ( $user->getOption( 'watchdefault' ) ) {
1168  # Watch all edits
1169  $this->watchthis = true;
1170  } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1171  # Watch creations
1172  $this->watchthis = true;
1173  } elseif ( $user->isWatched( $this->mTitle ) ) {
1174  # Already watched
1175  $this->watchthis = true;
1176  }
1177  if ( $user->getOption( 'minordefault' ) && !$this->isNew ) {
1178  $this->minoredit = true;
1179  }
1180  if ( $this->textbox1 === false ) {
1181  return false;
1182  }
1183  return true;
1184  }
1185 
1193  protected function getContentObject( $def_content = null ) {
1194  $content = false;
1195 
1196  $user = $this->context->getUser();
1197  $request = $this->context->getRequest();
1198  // For message page not locally set, use the i18n message.
1199  // For other non-existent articles, use preload text if any.
1200  if ( !$this->mTitle->exists() || $this->section == 'new' ) {
1201  if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
1202  # If this is a system message, get the default text.
1203  $msg = $this->mTitle->getDefaultMessageText();
1204 
1205  $content = $this->toEditContent( $msg );
1206  }
1207  if ( $content === false ) {
1208  # If requested, preload some text.
1209  $preload = $request->getVal( 'preload',
1210  // Custom preload text for new sections
1211  $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
1212  $params = $request->getArray( 'preloadparams', [] );
1213 
1214  $content = $this->getPreloadedContent( $preload, $params );
1215  }
1216  // For existing pages, get text based on "undo" or section parameters.
1217  } elseif ( $this->section != '' ) {
1218  // Get section edit text (returns $def_text for invalid sections)
1219  $orig = $this->getOriginalContent( $user );
1220  $content = $orig ? $orig->getSection( $this->section ) : null;
1221 
1222  if ( !$content ) {
1223  $content = $def_content;
1224  }
1225  } else {
1226  $undoafter = $request->getInt( 'undoafter' );
1227  $undo = $request->getInt( 'undo' );
1228 
1229  if ( $undo > 0 && $undoafter > 0 ) {
1230  $undorev = Revision::newFromId( $undo );
1231  $oldrev = Revision::newFromId( $undoafter );
1232  $undoMsg = null;
1233 
1234  # Sanity check, make sure it's the right page,
1235  # the revisions exist and they were not deleted.
1236  # Otherwise, $content will be left as-is.
1237  if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1238  !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
1239  !$oldrev->isDeleted( Revision::DELETED_TEXT )
1240  ) {
1241  if ( WikiPage::hasDifferencesOutsideMainSlot( $undorev, $oldrev )
1242  || !$this->isSupportedContentModel( $oldrev->getContentModel() )
1243  ) {
1244  // Hack for undo while EditPage can't handle multi-slot editing
1245  $this->context->getOutput()->redirect( $this->mTitle->getFullURL( [
1246  'action' => 'mcrundo',
1247  'undo' => $undo,
1248  'undoafter' => $undoafter,
1249  ] ) );
1250  return false;
1251  } else {
1252  $content = $this->page->getUndoContent( $undorev, $oldrev );
1253 
1254  if ( $content === false ) {
1255  # Warn the user that something went wrong
1256  $undoMsg = 'failure';
1257  }
1258  }
1259 
1260  if ( $undoMsg === null ) {
1261  $oldContent = $this->page->getContent( Revision::RAW );
1263  $user, MediaWikiServices::getInstance()->getContentLanguage() );
1264  $newContent = $content->preSaveTransform( $this->mTitle, $user, $popts );
1265  if ( $newContent->getModel() !== $oldContent->getModel() ) {
1266  // The undo may change content
1267  // model if its reverting the top
1268  // edit. This can result in
1269  // mismatched content model/format.
1270  $this->contentModel = $newContent->getModel();
1271  $this->contentFormat = $oldrev->getContentFormat();
1272  }
1273 
1274  if ( $newContent->equals( $oldContent ) ) {
1275  # Tell the user that the undo results in no change,
1276  # i.e. the revisions were already undone.
1277  $undoMsg = 'nochange';
1278  $content = false;
1279  } else {
1280  # Inform the user of our success and set an automatic edit summary
1281  $undoMsg = 'success';
1282 
1283  # If we just undid one rev, use an autosummary
1284  $firstrev = $oldrev->getNext();
1285  if ( $firstrev && $firstrev->getId() == $undo ) {
1286  $userText = $undorev->getUserText();
1287  if ( $userText === '' ) {
1288  $undoSummary = $this->context->msg(
1289  'undo-summary-username-hidden',
1290  $undo
1291  )->inContentLanguage()->text();
1292  } else {
1293  $undoSummary = $this->context->msg(
1294  'undo-summary',
1295  $undo,
1296  $userText
1297  )->inContentLanguage()->text();
1298  }
1299  if ( $this->summary === '' ) {
1300  $this->summary = $undoSummary;
1301  } else {
1302  $this->summary = $undoSummary . $this->context->msg( 'colon-separator' )
1303  ->inContentLanguage()->text() . $this->summary;
1304  }
1305  $this->undidRev = $undo;
1306  }
1307  $this->formtype = 'diff';
1308  }
1309  }
1310  } else {
1311  // Failed basic sanity checks.
1312  // Older revisions may have been removed since the link
1313  // was created, or we may simply have got bogus input.
1314  $undoMsg = 'norev';
1315  }
1316 
1317  $out = $this->context->getOutput();
1318  // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1319  // undo-nochange.
1320  $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1321  $this->editFormPageTop .= Html::rawElement(
1322  'div', [ 'class' => $class ],
1323  $out->parseAsInterface(
1324  $this->context->msg( 'undo-' . $undoMsg )->plain()
1325  )
1326  );
1327  }
1328 
1329  if ( $content === false ) {
1330  // Hack for restoring old revisions while EditPage
1331  // can't handle multi-slot editing.
1332 
1333  $curRevision = $this->page->getRevision();
1334  $oldRevision = $this->mArticle->getRevisionFetched();
1335 
1336  if ( $curRevision
1337  && $oldRevision
1338  && $curRevision->getId() !== $oldRevision->getId()
1339  && ( WikiPage::hasDifferencesOutsideMainSlot( $oldRevision, $curRevision )
1340  || !$this->isSupportedContentModel( $oldRevision->getContentModel() ) )
1341  ) {
1342  $this->context->getOutput()->redirect(
1343  $this->mTitle->getFullURL(
1344  [
1345  'action' => 'mcrrestore',
1346  'restore' => $oldRevision->getId(),
1347  ]
1348  )
1349  );
1350 
1351  return false;
1352  }
1353  }
1354 
1355  if ( $content === false ) {
1356  $content = $this->getOriginalContent( $user );
1357  }
1358  }
1359 
1360  return $content;
1361  }
1362 
1378  private function getOriginalContent( User $user ) {
1379  if ( $this->section == 'new' ) {
1380  return $this->getCurrentContent();
1381  }
1382  $revision = $this->mArticle->getRevisionFetched();
1383  if ( $revision === null ) {
1384  $handler = ContentHandler::getForModelID( $this->contentModel );
1385  return $handler->makeEmptyContent();
1386  }
1387  $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
1388  return $content;
1389  }
1390 
1403  public function getParentRevId() {
1404  if ( $this->parentRevId ) {
1405  return $this->parentRevId;
1406  } else {
1407  return $this->mArticle->getRevIdFetched();
1408  }
1409  }
1410 
1419  protected function getCurrentContent() {
1420  $rev = $this->page->getRevision();
1421  $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1422 
1423  if ( $content === false || $content === null ) {
1424  $handler = ContentHandler::getForModelID( $this->contentModel );
1425  return $handler->makeEmptyContent();
1426  } elseif ( !$this->undidRev ) {
1427  // Content models should always be the same since we error
1428  // out if they are different before this point (in ->edit()).
1429  // The exception being, during an undo, the current revision might
1430  // differ from the prior revision.
1431  $logger = LoggerFactory::getInstance( 'editpage' );
1432  if ( $this->contentModel !== $rev->getContentModel() ) {
1433  $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1434  'prev' => $this->contentModel,
1435  'new' => $rev->getContentModel(),
1436  'title' => $this->getTitle()->getPrefixedDBkey(),
1437  'method' => __METHOD__
1438  ] );
1439  $this->contentModel = $rev->getContentModel();
1440  }
1441 
1442  // Given that the content models should match, the current selected
1443  // format should be supported.
1444  if ( !$content->isSupportedFormat( $this->contentFormat ) ) {
1445  $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1446 
1447  'prev' => $this->contentFormat,
1448  'new' => $rev->getContentFormat(),
1449  'title' => $this->getTitle()->getPrefixedDBkey(),
1450  'method' => __METHOD__
1451  ] );
1452  $this->contentFormat = $rev->getContentFormat();
1453  }
1454  }
1455  return $content;
1456  }
1457 
1465  public function setPreloadedContent( Content $content ) {
1466  $this->mPreloadContent = $content;
1467  }
1468 
1480  protected function getPreloadedContent( $preload, $params = [] ) {
1481  if ( !empty( $this->mPreloadContent ) ) {
1482  return $this->mPreloadContent;
1483  }
1484 
1485  $handler = ContentHandler::getForModelID( $this->contentModel );
1486 
1487  if ( $preload === '' ) {
1488  return $handler->makeEmptyContent();
1489  }
1490 
1491  $user = $this->context->getUser();
1492  $title = Title::newFromText( $preload );
1493  # Check for existence to avoid getting MediaWiki:Noarticletext
1494  if ( $title === null || !$title->exists() || !$title->userCan( 'read', $user ) ) {
1495  // TODO: somehow show a warning to the user!
1496  return $handler->makeEmptyContent();
1497  }
1498 
1500  if ( $page->isRedirect() ) {
1502  # Same as before
1503  if ( $title === null || !$title->exists() || !$title->userCan( 'read', $user ) ) {
1504  // TODO: somehow show a warning to the user!
1505  return $handler->makeEmptyContent();
1506  }
1508  }
1509 
1510  $parserOptions = ParserOptions::newFromUser( $user );
1512 
1513  if ( !$content ) {
1514  // TODO: somehow show a warning to the user!
1515  return $handler->makeEmptyContent();
1516  }
1517 
1518  if ( $content->getModel() !== $handler->getModelID() ) {
1519  $converted = $content->convert( $handler->getModelID() );
1520 
1521  if ( !$converted ) {
1522  // TODO: somehow show a warning to the user!
1523  wfDebug( "Attempt to preload incompatible content: " .
1524  "can't convert " . $content->getModel() .
1525  " to " . $handler->getModelID() );
1526 
1527  return $handler->makeEmptyContent();
1528  }
1529 
1530  $content = $converted;
1531  }
1532 
1533  return $content->preloadTransform( $title, $parserOptions, $params );
1534  }
1535 
1543  public function tokenOk( &$request ) {
1544  $token = $request->getVal( 'wpEditToken' );
1545  $user = $this->context->getUser();
1546  $this->mTokenOk = $user->matchEditToken( $token );
1547  $this->mTokenOkExceptSuffix = $user->matchEditTokenNoSuffix( $token );
1548  return $this->mTokenOk;
1549  }
1550 
1565  protected function setPostEditCookie( $statusValue ) {
1566  $revisionId = $this->page->getLatest();
1567  $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1568 
1569  $val = 'saved';
1570  if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1571  $val = 'created';
1572  } elseif ( $this->oldid ) {
1573  $val = 'restored';
1574  }
1575 
1576  $response = $this->context->getRequest()->response();
1577  $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION );
1578  }
1579 
1586  public function attemptSave( &$resultDetails = false ) {
1587  // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1588  // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1589  // This is needed since PageUpdater no longer checks these rights!
1590 
1591  // Allow bots to exempt some edits from bot flagging
1592  $bot = $this->context->getUser()->isAllowed( 'bot' ) && $this->bot;
1593  $status = $this->internalAttemptSave( $resultDetails, $bot );
1594 
1595  Hooks::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1596 
1597  return $status;
1598  }
1599 
1603  private function incrementResolvedConflicts() {
1604  if ( $this->context->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1605  return;
1606  }
1607 
1608  $this->getEditConflictHelper()->incrementResolvedStats();
1609  }
1610 
1620  private function handleStatus( Status $status, $resultDetails ) {
1625  if ( $status->value == self::AS_SUCCESS_UPDATE
1626  || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1627  ) {
1628  $this->incrementResolvedConflicts();
1629 
1630  $this->didSave = true;
1631  if ( !$resultDetails['nullEdit'] ) {
1632  $this->setPostEditCookie( $status->value );
1633  }
1634  }
1635 
1636  $out = $this->context->getOutput();
1637 
1638  // "wpExtraQueryRedirect" is a hidden input to modify
1639  // after save URL and is not used by actual edit form
1640  $request = $this->context->getRequest();
1641  $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1642 
1643  switch ( $status->value ) {
1644  case self::AS_HOOK_ERROR_EXPECTED:
1645  case self::AS_CONTENT_TOO_BIG:
1646  case self::AS_ARTICLE_WAS_DELETED:
1647  case self::AS_CONFLICT_DETECTED:
1648  case self::AS_SUMMARY_NEEDED:
1649  case self::AS_TEXTBOX_EMPTY:
1650  case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1651  case self::AS_END:
1652  case self::AS_BLANK_ARTICLE:
1653  case self::AS_SELF_REDIRECT:
1654  return true;
1655 
1656  case self::AS_HOOK_ERROR:
1657  return false;
1658 
1659  case self::AS_CANNOT_USE_CUSTOM_MODEL:
1660  case self::AS_PARSE_ERROR:
1661  case self::AS_UNICODE_NOT_SUPPORTED:
1662  $out->wrapWikiTextAsInterface( 'error', $status->getWikiText() );
1663  return true;
1664 
1665  case self::AS_SUCCESS_NEW_ARTICLE:
1666  $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1667  if ( $extraQueryRedirect ) {
1668  if ( $query !== '' ) {
1669  $query .= '&';
1670  }
1671  $query .= $extraQueryRedirect;
1672  }
1673  $anchor = $resultDetails['sectionanchor'] ?? '';
1674  $out->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1675  return false;
1676 
1677  case self::AS_SUCCESS_UPDATE:
1678  $extraQuery = '';
1679  $sectionanchor = $resultDetails['sectionanchor'];
1680 
1681  // Give extensions a chance to modify URL query on update
1682  Hooks::run(
1683  'ArticleUpdateBeforeRedirect',
1684  [ $this->mArticle, &$sectionanchor, &$extraQuery ]
1685  );
1686 
1687  if ( $resultDetails['redirect'] ) {
1688  if ( $extraQuery !== '' ) {
1689  $extraQuery = '&' . $extraQuery;
1690  }
1691  $extraQuery = 'redirect=no' . $extraQuery;
1692  }
1693  if ( $extraQueryRedirect ) {
1694  if ( $extraQuery !== '' ) {
1695  $extraQuery .= '&';
1696  }
1697  $extraQuery .= $extraQueryRedirect;
1698  }
1699 
1700  $out->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1701  return false;
1702 
1703  case self::AS_SPAM_ERROR:
1704  $this->spamPageWithContent( $resultDetails['spam'] );
1705  return false;
1706 
1707  case self::AS_BLOCKED_PAGE_FOR_USER:
1708  throw new UserBlockedError( $this->context->getUser()->getBlock() );
1709 
1710  case self::AS_IMAGE_REDIRECT_ANON:
1711  case self::AS_IMAGE_REDIRECT_LOGGED:
1712  throw new PermissionsError( 'upload' );
1713 
1714  case self::AS_READ_ONLY_PAGE_ANON:
1715  case self::AS_READ_ONLY_PAGE_LOGGED:
1716  throw new PermissionsError( 'edit' );
1717 
1718  case self::AS_READ_ONLY_PAGE:
1719  throw new ReadOnlyError;
1720 
1721  case self::AS_RATE_LIMITED:
1722  throw new ThrottledError();
1723 
1724  case self::AS_NO_CREATE_PERMISSION:
1725  $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1726  throw new PermissionsError( $permission );
1727 
1728  case self::AS_NO_CHANGE_CONTENT_MODEL:
1729  throw new PermissionsError( 'editcontentmodel' );
1730 
1731  default:
1732  // We don't recognize $status->value. The only way that can happen
1733  // is if an extension hook aborted from inside ArticleSave.
1734  // Render the status object into $this->hookError
1735  // FIXME this sucks, we should just use the Status object throughout
1736  $this->hookError = '<div class="error">' . "\n" . $status->getWikiText() .
1737  '</div>';
1738  return true;
1739  }
1740  }
1741 
1752  // Run old style post-section-merge edit filter
1753  if ( $this->hookError != '' ) {
1754  # ...or the hook could be expecting us to produce an error
1755  $status->fatal( 'hookaborted' );
1756  $status->value = self::AS_HOOK_ERROR_EXPECTED;
1757  return false;
1758  }
1759 
1760  // Run new style post-section-merge edit filter
1761  if ( !Hooks::run( 'EditFilterMergedContent',
1762  [ $this->context, $content, $status, $this->summary,
1763  $user, $this->minoredit ] )
1764  ) {
1765  # Error messages etc. could be handled within the hook...
1766  if ( $status->isGood() ) {
1767  $status->fatal( 'hookaborted' );
1768  // Not setting $this->hookError here is a hack to allow the hook
1769  // to cause a return to the edit page without $this->hookError
1770  // being set. This is used by ConfirmEdit to display a captcha
1771  // without any error message cruft.
1772  } else {
1773  $this->hookError = $this->formatStatusErrors( $status );
1774  }
1775  // Use the existing $status->value if the hook set it
1776  if ( !$status->value ) {
1777  $status->value = self::AS_HOOK_ERROR;
1778  }
1779  return false;
1780  } elseif ( !$status->isOK() ) {
1781  # ...or the hook could be expecting us to produce an error
1782  // FIXME this sucks, we should just use the Status object throughout
1783  $this->hookError = $this->formatStatusErrors( $status );
1784  $status->fatal( 'hookaborted' );
1785  $status->value = self::AS_HOOK_ERROR_EXPECTED;
1786  return false;
1787  }
1788 
1789  return true;
1790  }
1791 
1798  private function formatStatusErrors( Status $status ) {
1799  $errmsg = $status->getWikiText(
1800  'edit-error-short',
1801  'edit-error-long',
1802  $this->context->getLanguage()
1803  );
1804  return <<<ERROR
1805 <div class="errorbox">
1806 {$errmsg}
1807 </div>
1808 <br clear="all" />
1809 ERROR;
1810  }
1811 
1818  private function newSectionSummary( &$sectionanchor = null ) {
1819  if ( $this->sectiontitle !== '' ) {
1820  $sectionanchor = $this->guessSectionName( $this->sectiontitle );
1821  // If no edit summary was specified, create one automatically from the section
1822  // title and have it link to the new section. Otherwise, respect the summary as
1823  // passed.
1824  if ( $this->summary === '' ) {
1825  $cleanSectionTitle = MediaWikiServices::getInstance()->getParser()
1826  ->stripSectionName( $this->sectiontitle );
1827  return $this->context->msg( 'newsectionsummary' )
1828  ->plaintextParams( $cleanSectionTitle )->inContentLanguage()->text();
1829  }
1830  } elseif ( $this->summary !== '' ) {
1831  $sectionanchor = $this->guessSectionName( $this->summary );
1832  # This is a new section, so create a link to the new section
1833  # in the revision summary.
1834  $cleanSummary = MediaWikiServices::getInstance()->getParser()
1835  ->stripSectionName( $this->summary );
1836  return $this->context->msg( 'newsectionsummary' )
1837  ->plaintextParams( $cleanSummary )->inContentLanguage()->text();
1838  }
1839  return $this->summary;
1840  }
1841 
1866  public function internalAttemptSave( &$result, $bot = false ) {
1868  $user = $this->context->getUser();
1869 
1870  if ( !Hooks::run( 'EditPage::attemptSave', [ $this ] ) ) {
1871  wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1872  $status->fatal( 'hookaborted' );
1873  $status->value = self::AS_HOOK_ERROR;
1874  return $status;
1875  }
1876 
1877  if ( $this->unicodeCheck !== self::UNICODE_CHECK ) {
1878  $status->fatal( 'unicode-support-fail' );
1879  $status->value = self::AS_UNICODE_NOT_SUPPORTED;
1880  return $status;
1881  }
1882 
1883  $request = $this->context->getRequest();
1884  $spam = $request->getText( 'wpAntispam' );
1885  if ( $spam !== '' ) {
1886  wfDebugLog(
1887  'SimpleAntiSpam',
1888  $user->getName() .
1889  ' editing "' .
1890  $this->mTitle->getPrefixedText() .
1891  '" submitted bogus field "' .
1892  $spam .
1893  '"'
1894  );
1895  $status->fatal( 'spamprotectionmatch', false );
1896  $status->value = self::AS_SPAM_ERROR;
1897  return $status;
1898  }
1899 
1900  try {
1901  # Construct Content object
1902  $textbox_content = $this->toEditContent( $this->textbox1 );
1903  } catch ( MWContentSerializationException $ex ) {
1904  $status->fatal(
1905  'content-failed-to-parse',
1906  $this->contentModel,
1907  $this->contentFormat,
1908  $ex->getMessage()
1909  );
1910  $status->value = self::AS_PARSE_ERROR;
1911  return $status;
1912  }
1913 
1914  # Check image redirect
1915  if ( $this->mTitle->getNamespace() == NS_FILE &&
1916  $textbox_content->isRedirect() &&
1917  !$user->isAllowed( 'upload' )
1918  ) {
1919  $code = $user->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1920  $status->setResult( false, $code );
1921 
1922  return $status;
1923  }
1924 
1925  # Check for spam
1926  $match = self::matchSummarySpamRegex( $this->summary );
1927  if ( $match === false && $this->section == 'new' ) {
1928  # $wgSpamRegex is enforced on this new heading/summary because, unlike
1929  # regular summaries, it is added to the actual wikitext.
1930  if ( $this->sectiontitle !== '' ) {
1931  # This branch is taken when the API is used with the 'sectiontitle' parameter.
1932  $match = self::matchSpamRegex( $this->sectiontitle );
1933  } else {
1934  # This branch is taken when the "Add Topic" user interface is used, or the API
1935  # is used with the 'summary' parameter.
1936  $match = self::matchSpamRegex( $this->summary );
1937  }
1938  }
1939  if ( $match === false ) {
1940  $match = self::matchSpamRegex( $this->textbox1 );
1941  }
1942  if ( $match !== false ) {
1943  $result['spam'] = $match;
1944  $ip = $request->getIP();
1945  $pdbk = $this->mTitle->getPrefixedDBkey();
1946  $match = str_replace( "\n", '', $match );
1947  wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1948  $status->fatal( 'spamprotectionmatch', $match );
1949  $status->value = self::AS_SPAM_ERROR;
1950  return $status;
1951  }
1952  if ( !Hooks::run(
1953  'EditFilter',
1954  [ $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ] )
1955  ) {
1956  # Error messages etc. could be handled within the hook...
1957  $status->fatal( 'hookaborted' );
1958  $status->value = self::AS_HOOK_ERROR;
1959  return $status;
1960  } elseif ( $this->hookError != '' ) {
1961  # ...or the hook could be expecting us to produce an error
1962  $status->fatal( 'hookaborted' );
1963  $status->value = self::AS_HOOK_ERROR_EXPECTED;
1964  return $status;
1965  }
1966 
1967  if ( $user->isBlockedFrom( $this->mTitle ) ) {
1968  // Auto-block user's IP if the account was "hard" blocked
1969  if ( !wfReadOnly() ) {
1970  $user->spreadAnyEditBlock();
1971  }
1972  # Check block state against master, thus 'false'.
1973  $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1974  return $status;
1975  }
1976 
1977  $this->contentLength = strlen( $this->textbox1 );
1978  $config = $this->context->getConfig();
1979  $maxArticleSize = $config->get( 'MaxArticleSize' );
1980  if ( $this->contentLength > $maxArticleSize * 1024 ) {
1981  // Error will be displayed by showEditForm()
1982  $this->tooBig = true;
1983  $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1984  return $status;
1985  }
1986 
1987  if ( !$user->isAllowed( 'edit' ) ) {
1988  if ( $user->isAnon() ) {
1989  $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1990  return $status;
1991  } else {
1992  $status->fatal( 'readonlytext' );
1993  $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1994  return $status;
1995  }
1996  }
1997 
1998  $changingContentModel = false;
1999  if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
2000  if ( !$config->get( 'ContentHandlerUseDB' ) ) {
2001  $status->fatal( 'editpage-cannot-use-custom-model' );
2002  $status->value = self::AS_CANNOT_USE_CUSTOM_MODEL;
2003  return $status;
2004  } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
2005  $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
2006  return $status;
2007  }
2008  // Make sure the user can edit the page under the new content model too
2009  $titleWithNewContentModel = clone $this->mTitle;
2010  $titleWithNewContentModel->setContentModel( $this->contentModel );
2011  if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
2012  || !$titleWithNewContentModel->userCan( 'edit', $user )
2013  ) {
2014  $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
2015  return $status;
2016  }
2017 
2018  $changingContentModel = true;
2019  $oldContentModel = $this->mTitle->getContentModel();
2020  }
2021 
2022  if ( $this->changeTags ) {
2023  $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
2024  $this->changeTags, $user );
2025  if ( !$changeTagsStatus->isOK() ) {
2026  $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
2027  return $changeTagsStatus;
2028  }
2029  }
2030 
2031  if ( wfReadOnly() ) {
2032  $status->fatal( 'readonlytext' );
2033  $status->value = self::AS_READ_ONLY_PAGE;
2034  return $status;
2035  }
2036  if ( $user->pingLimiter() || $user->pingLimiter( 'linkpurge', 0 )
2037  || ( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
2038  ) {
2039  $status->fatal( 'actionthrottledtext' );
2040  $status->value = self::AS_RATE_LIMITED;
2041  return $status;
2042  }
2043 
2044  # If the article has been deleted while editing, don't save it without
2045  # confirmation
2046  if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
2047  $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
2048  return $status;
2049  }
2050 
2051  # Load the page data from the master. If anything changes in the meantime,
2052  # we detect it by using page_latest like a token in a 1 try compare-and-swap.
2053  $this->page->loadPageData( 'fromdbmaster' );
2054  $new = !$this->page->exists();
2055 
2056  if ( $new ) {
2057  // Late check for create permission, just in case *PARANOIA*
2058  if ( !$this->mTitle->userCan( 'create', $user ) ) {
2059  $status->fatal( 'nocreatetext' );
2060  $status->value = self::AS_NO_CREATE_PERMISSION;
2061  wfDebug( __METHOD__ . ": no create permission\n" );
2062  return $status;
2063  }
2064 
2065  // Don't save a new page if it's blank or if it's a MediaWiki:
2066  // message with content equivalent to default (allow empty pages
2067  // in this case to disable messages, see T52124)
2068  $defaultMessageText = $this->mTitle->getDefaultMessageText();
2069  if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
2070  $defaultText = $defaultMessageText;
2071  } else {
2072  $defaultText = '';
2073  }
2074 
2075  if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
2076  $this->blankArticle = true;
2077  $status->fatal( 'blankarticle' );
2078  $status->setResult( false, self::AS_BLANK_ARTICLE );
2079  return $status;
2080  }
2081 
2082  if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2083  return $status;
2084  }
2085 
2086  $content = $textbox_content;
2087 
2088  $result['sectionanchor'] = '';
2089  if ( $this->section == 'new' ) {
2090  if ( $this->sectiontitle !== '' ) {
2091  // Insert the section title above the content.
2092  $content = $content->addSectionHeader( $this->sectiontitle );
2093  } elseif ( $this->summary !== '' ) {
2094  // Insert the section title above the content.
2095  $content = $content->addSectionHeader( $this->summary );
2096  }
2097  $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
2098  }
2099 
2100  $status->value = self::AS_SUCCESS_NEW_ARTICLE;
2101 
2102  } else { # not $new
2103 
2104  # Article exists. Check for edit conflict.
2105 
2106  $this->page->clear(); # Force reload of dates, etc.
2107  $timestamp = $this->page->getTimestamp();
2108  $latest = $this->page->getLatest();
2109 
2110  wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2111 
2112  // An edit conflict is detected if the current revision is different from the
2113  // revision that was current when editing was initiated on the client.
2114  // This is checked based on the timestamp and revision ID.
2115  // TODO: the timestamp based check can probably go away now.
2116  if ( $timestamp != $this->edittime
2117  || ( $this->editRevId !== null && $this->editRevId != $latest )
2118  ) {
2119  $this->isConflict = true;
2120  if ( $this->section == 'new' ) {
2121  if ( $this->page->getUserText() == $user->getName() &&
2122  $this->page->getComment() == $this->newSectionSummary()
2123  ) {
2124  // Probably a duplicate submission of a new comment.
2125  // This can happen when CDN resends a request after
2126  // a timeout but the first one actually went through.
2127  wfDebug( __METHOD__
2128  . ": duplicate new section submission; trigger edit conflict!\n" );
2129  } else {
2130  // New comment; suppress conflict.
2131  $this->isConflict = false;
2132  wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
2133  }
2134  } elseif ( $this->section == ''
2136  DB_MASTER, $this->mTitle->getArticleID(),
2137  $user->getId(), $this->edittime
2138  )
2139  ) {
2140  # Suppress edit conflict with self, except for section edits where merging is required.
2141  wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
2142  $this->isConflict = false;
2143  }
2144  }
2145 
2146  // If sectiontitle is set, use it, otherwise use the summary as the section title.
2147  if ( $this->sectiontitle !== '' ) {
2148  $sectionTitle = $this->sectiontitle;
2149  } else {
2150  $sectionTitle = $this->summary;
2151  }
2152 
2153  $content = null;
2154 
2155  if ( $this->isConflict ) {
2156  wfDebug( __METHOD__
2157  . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2158  . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2159  // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2160  // ...or disable section editing for non-current revisions (not exposed anyway).
2161  if ( $this->editRevId !== null ) {
2162  $content = $this->page->replaceSectionAtRev(
2163  $this->section,
2164  $textbox_content,
2165  $sectionTitle,
2166  $this->editRevId
2167  );
2168  } else {
2169  $content = $this->page->replaceSectionContent(
2170  $this->section,
2171  $textbox_content,
2172  $sectionTitle,
2173  $this->edittime
2174  );
2175  }
2176  } else {
2177  wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
2178  $content = $this->page->replaceSectionContent(
2179  $this->section,
2180  $textbox_content,
2181  $sectionTitle
2182  );
2183  }
2184 
2185  if ( is_null( $content ) ) {
2186  wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
2187  $this->isConflict = true;
2188  $content = $textbox_content; // do not try to merge here!
2189  } elseif ( $this->isConflict ) {
2190  # Attempt merge
2191  if ( $this->mergeChangesIntoContent( $content ) ) {
2192  // Successful merge! Maybe we should tell the user the good news?
2193  $this->isConflict = false;
2194  wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
2195  } else {
2196  $this->section = '';
2197  $this->textbox1 = ContentHandler::getContentText( $content );
2198  wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
2199  }
2200  }
2201 
2202  if ( $this->isConflict ) {
2203  $status->setResult( false, self::AS_CONFLICT_DETECTED );
2204  return $status;
2205  }
2206 
2207  if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2208  return $status;
2209  }
2210 
2211  if ( $this->section == 'new' ) {
2212  // Handle the user preference to force summaries here
2213  if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
2214  $this->missingSummary = true;
2215  $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2216  $status->value = self::AS_SUMMARY_NEEDED;
2217  return $status;
2218  }
2219 
2220  // Do not allow the user to post an empty comment
2221  if ( $this->textbox1 == '' ) {
2222  $this->missingComment = true;
2223  $status->fatal( 'missingcommenttext' );
2224  $status->value = self::AS_TEXTBOX_EMPTY;
2225  return $status;
2226  }
2227  } elseif ( !$this->allowBlankSummary
2228  && !$content->equals( $this->getOriginalContent( $user ) )
2229  && !$content->isRedirect()
2230  && md5( $this->summary ) == $this->autoSumm
2231  ) {
2232  $this->missingSummary = true;
2233  $status->fatal( 'missingsummary' );
2234  $status->value = self::AS_SUMMARY_NEEDED;
2235  return $status;
2236  }
2237 
2238  # All's well
2239  $sectionanchor = '';
2240  if ( $this->section == 'new' ) {
2241  $this->summary = $this->newSectionSummary( $sectionanchor );
2242  } elseif ( $this->section != '' ) {
2243  # Try to get a section anchor from the section source, redirect
2244  # to edited section if header found.
2245  # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2246  # for duplicate heading checking and maybe parsing.
2247  $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
2248  # We can't deal with anchors, includes, html etc in the header for now,
2249  # headline would need to be parsed to improve this.
2250  if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2251  $sectionanchor = $this->guessSectionName( $matches[2] );
2252  }
2253  }
2254  $result['sectionanchor'] = $sectionanchor;
2255 
2256  // Save errors may fall down to the edit form, but we've now
2257  // merged the section into full text. Clear the section field
2258  // so that later submission of conflict forms won't try to
2259  // replace that into a duplicated mess.
2260  $this->textbox1 = $this->toEditText( $content );
2261  $this->section = '';
2262 
2263  $status->value = self::AS_SUCCESS_UPDATE;
2264  }
2265 
2266  if ( !$this->allowSelfRedirect
2267  && $content->isRedirect()
2268  && $content->getRedirectTarget()->equals( $this->getTitle() )
2269  ) {
2270  // If the page already redirects to itself, don't warn.
2271  $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2272  if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
2273  $this->selfRedirect = true;
2274  $status->fatal( 'selfredirect' );
2275  $status->value = self::AS_SELF_REDIRECT;
2276  return $status;
2277  }
2278  }
2279 
2280  // Check for length errors again now that the section is merged in
2281  $this->contentLength = strlen( $this->toEditText( $content ) );
2282  if ( $this->contentLength > $maxArticleSize * 1024 ) {
2283  $this->tooBig = true;
2284  $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
2285  return $status;
2286  }
2287 
2288  $flags = EDIT_AUTOSUMMARY |
2289  ( $new ? EDIT_NEW : EDIT_UPDATE ) |
2290  ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
2291  ( $bot ? EDIT_FORCE_BOT : 0 );
2292 
2293  $doEditStatus = $this->page->doEditContent(
2294  $content,
2295  $this->summary,
2296  $flags,
2297  false,
2298  $user,
2299  $content->getDefaultFormat(),
2302  );
2303 
2304  if ( !$doEditStatus->isOK() ) {
2305  // Failure from doEdit()
2306  // Show the edit conflict page for certain recognized errors from doEdit(),
2307  // but don't show it for errors from extension hooks
2308  $errors = $doEditStatus->getErrorsArray();
2309  if ( in_array( $errors[0][0],
2310  [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2311  ) {
2312  $this->isConflict = true;
2313  // Destroys data doEdit() put in $status->value but who cares
2314  $doEditStatus->value = self::AS_END;
2315  }
2316  return $doEditStatus;
2317  }
2318 
2319  $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2320  if ( $result['nullEdit'] ) {
2321  // We don't know if it was a null edit until now, so increment here
2322  $user->pingLimiter( 'linkpurge' );
2323  }
2324  $result['redirect'] = $content->isRedirect();
2325 
2326  $this->updateWatchlist();
2327 
2328  // If the content model changed, add a log entry
2329  if ( $changingContentModel ) {
2331  $user,
2332  $new ? false : $oldContentModel,
2333  $this->contentModel,
2334  $this->summary
2335  );
2336  }
2337 
2338  return $status;
2339  }
2340 
2347  protected function addContentModelChangeLogEntry( User $user, $oldModel, $newModel, $reason ) {
2348  $new = $oldModel === false;
2349  $log = new ManualLogEntry( 'contentmodel', $new ? 'new' : 'change' );
2350  $log->setPerformer( $user );
2351  $log->setTarget( $this->mTitle );
2352  $log->setComment( $reason );
2353  $log->setParameters( [
2354  '4::oldmodel' => $oldModel,
2355  '5::newmodel' => $newModel
2356  ] );
2357  $logid = $log->insert();
2358  $log->publish( $logid );
2359  }
2360 
2364  protected function updateWatchlist() {
2365  $user = $this->context->getUser();
2366  if ( !$user->isLoggedIn() ) {
2367  return;
2368  }
2369 
2371  $watch = $this->watchthis;
2372  // Do this in its own transaction to reduce contention...
2373  DeferredUpdates::addCallableUpdate( function () use ( $user, $title, $watch ) {
2374  if ( $watch == $user->isWatched( $title, User::IGNORE_USER_RIGHTS ) ) {
2375  return; // nothing to change
2376  }
2378  } );
2379  }
2380 
2392  private function mergeChangesIntoContent( &$editContent ) {
2393  $db = wfGetDB( DB_MASTER );
2394 
2395  // This is the revision that was current at the time editing was initiated on the client,
2396  // even if the edit was based on an old revision.
2397  $baseRevision = $this->getBaseRevision();
2398  $baseContent = $baseRevision ? $baseRevision->getContent() : null;
2399 
2400  if ( is_null( $baseContent ) ) {
2401  return false;
2402  }
2403 
2404  // The current state, we want to merge updates into it
2405  $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2406  $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2407 
2408  if ( is_null( $currentContent ) ) {
2409  return false;
2410  }
2411 
2412  $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2413 
2414  $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2415 
2416  if ( $result ) {
2417  $editContent = $result;
2418  // Update parentRevId to what we just merged.
2419  $this->parentRevId = $currentRevision->getId();
2420  return true;
2421  }
2422 
2423  return false;
2424  }
2425 
2438  public function getBaseRevision() {
2439  if ( !$this->mBaseRevision ) {
2440  $db = wfGetDB( DB_MASTER );
2441  $this->mBaseRevision = $this->editRevId
2442  ? Revision::newFromId( $this->editRevId, Revision::READ_LATEST )
2443  : Revision::loadFromTimestamp( $db, $this->mTitle, $this->edittime );
2444  }
2445  return $this->mBaseRevision;
2446  }
2447 
2455  public static function matchSpamRegex( $text ) {
2456  global $wgSpamRegex;
2457  // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2458  $regexes = (array)$wgSpamRegex;
2459  return self::matchSpamRegexInternal( $text, $regexes );
2460  }
2461 
2469  public static function matchSummarySpamRegex( $text ) {
2470  global $wgSummarySpamRegex;
2471  $regexes = (array)$wgSummarySpamRegex;
2472  return self::matchSpamRegexInternal( $text, $regexes );
2473  }
2474 
2480  protected static function matchSpamRegexInternal( $text, $regexes ) {
2481  foreach ( $regexes as $regex ) {
2482  $matches = [];
2483  if ( preg_match( $regex, $text, $matches ) ) {
2484  return $matches[0];
2485  }
2486  }
2487  return false;
2488  }
2489 
2490  public function setHeaders() {
2491  $out = $this->context->getOutput();
2492 
2493  $out->addModules( 'mediawiki.action.edit' );
2494  $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2495  $out->addModuleStyles( 'mediawiki.editfont.styles' );
2496 
2497  $user = $this->context->getUser();
2498 
2499  if ( $user->getOption( 'uselivepreview' ) ) {
2500  $out->addModules( 'mediawiki.action.edit.preview' );
2501  }
2502 
2503  if ( $user->getOption( 'useeditwarning' ) ) {
2504  $out->addModules( 'mediawiki.action.edit.editWarning' );
2505  }
2506 
2507  # Enabled article-related sidebar, toplinks, etc.
2508  $out->setArticleRelated( true );
2509 
2510  $contextTitle = $this->getContextTitle();
2511  if ( $this->isConflict ) {
2512  $msg = 'editconflict';
2513  } elseif ( $contextTitle->exists() && $this->section != '' ) {
2514  $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2515  } else {
2516  $msg = $contextTitle->exists()
2517  || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2518  && $contextTitle->getDefaultMessageText() !== false
2519  )
2520  ? 'editing'
2521  : 'creating';
2522  }
2523 
2524  # Use the title defined by DISPLAYTITLE magic word when present
2525  # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2526  # setPageTitle() treats the input as wikitext, which should be safe in either case.
2527  $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2528  if ( $displayTitle === false ) {
2529  $displayTitle = $contextTitle->getPrefixedText();
2530  } else {
2531  $out->setDisplayTitle( $displayTitle );
2532  }
2533  $out->setPageTitle( $this->context->msg( $msg, $displayTitle ) );
2534 
2535  $config = $this->context->getConfig();
2536 
2537  # Transmit the name of the message to JavaScript for live preview
2538  # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2539  $out->addJsConfigVars( [
2540  'wgEditMessage' => $msg,
2541  'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2542  ] );
2543 
2544  // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2545  // editors, etc.
2546  $out->addJsConfigVars(
2547  'wgEditSubmitButtonLabelPublish',
2548  $config->get( 'EditSubmitButtonLabelPublish' )
2549  );
2550  }
2551 
2555  protected function showIntro() {
2556  if ( $this->suppressIntro ) {
2557  return;
2558  }
2559 
2560  $out = $this->context->getOutput();
2561  $namespace = $this->mTitle->getNamespace();
2562 
2563  if ( $namespace == NS_MEDIAWIKI ) {
2564  # Show a warning if editing an interface message
2565  $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2566  # If this is a default message (but not css, json, or js),
2567  # show a hint that it is translatable on translatewiki.net
2568  if (
2569  !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2570  && !$this->mTitle->hasContentModel( CONTENT_MODEL_JSON )
2571  && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2572  ) {
2573  $defaultMessageText = $this->mTitle->getDefaultMessageText();
2574  if ( $defaultMessageText !== false ) {
2575  $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2576  'translateinterface' );
2577  }
2578  }
2579  } elseif ( $namespace == NS_FILE ) {
2580  # Show a hint to shared repo
2581  $file = wfFindFile( $this->mTitle );
2582  if ( $file && !$file->isLocal() ) {
2583  $descUrl = $file->getDescriptionUrl();
2584  # there must be a description url to show a hint to shared repo
2585  if ( $descUrl ) {
2586  if ( !$this->mTitle->exists() ) {
2587  $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2588  'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2589  ] );
2590  } else {
2591  $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2592  'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2593  ] );
2594  }
2595  }
2596  }
2597  }
2598 
2599  # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2600  # Show log extract when the user is currently blocked
2601  if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2602  $username = explode( '/', $this->mTitle->getText(), 2 )[0];
2603  $user = User::newFromName( $username, false /* allow IP users */ );
2604  $ip = User::isIP( $username );
2605  $block = Block::newFromTarget( $user, $user );
2606  if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2607  $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2608  [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2609  } elseif (
2610  !is_null( $block ) &&
2611  $block->getType() != Block::TYPE_AUTO &&
2612  ( $block->isSitewide() || $user->isBlockedFrom( $this->mTitle ) )
2613  ) {
2614  // Show log extract if the user is sitewide blocked or is partially
2615  // blocked and not allowed to edit their user page or user talk page
2617  $out,
2618  'block',
2619  MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2620  '',
2621  [
2622  'lim' => 1,
2623  'showIfEmpty' => false,
2624  'msgKey' => [
2625  'blocked-notice-logextract',
2626  $user->getName() # Support GENDER in notice
2627  ]
2628  ]
2629  );
2630  }
2631  }
2632  # Try to add a custom edit intro, or use the standard one if this is not possible.
2633  if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2635  $this->context->msg( 'helppage' )->inContentLanguage()->text()
2636  ) );
2637  if ( $this->context->getUser()->isLoggedIn() ) {
2638  $out->wrapWikiMsg(
2639  // Suppress the external link icon, consider the help url an internal one
2640  "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2641  [
2642  'newarticletext',
2643  $helpLink
2644  ]
2645  );
2646  } else {
2647  $out->wrapWikiMsg(
2648  // Suppress the external link icon, consider the help url an internal one
2649  "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2650  [
2651  'newarticletextanon',
2652  $helpLink
2653  ]
2654  );
2655  }
2656  }
2657  # Give a notice if the user is editing a deleted/moved page...
2658  if ( !$this->mTitle->exists() ) {
2659  $dbr = wfGetDB( DB_REPLICA );
2660 
2661  LogEventsList::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle,
2662  '',
2663  [
2664  'lim' => 10,
2665  'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2666  'showIfEmpty' => false,
2667  'msgKey' => [ 'recreate-moveddeleted-warn' ]
2668  ]
2669  );
2670  }
2671  }
2672 
2678  protected function showCustomIntro() {
2679  if ( $this->editintro ) {
2680  $title = Title::newFromText( $this->editintro );
2681  if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2682  // Added using template syntax, to take <noinclude>'s into account.
2683  $this->context->getOutput()->addWikiTextAsContent(
2684  '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2685  /*linestart*/true,
2687  );
2688  return true;
2689  }
2690  }
2691  return false;
2692  }
2693 
2712  protected function toEditText( $content ) {
2713  if ( $content === null || $content === false || is_string( $content ) ) {
2714  return $content;
2715  }
2716 
2717  if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2718  throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2719  }
2720 
2721  return $content->serialize( $this->contentFormat );
2722  }
2723 
2740  protected function toEditContent( $text ) {
2741  if ( $text === false || $text === null ) {
2742  return $text;
2743  }
2744 
2745  $content = ContentHandler::makeContent( $text, $this->getTitle(),
2746  $this->contentModel, $this->contentFormat );
2747 
2748  if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2749  throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2750  }
2751 
2752  return $content;
2753  }
2754 
2763  public function showEditForm( $formCallback = null ) {
2764  # need to parse the preview early so that we know which templates are used,
2765  # otherwise users with "show preview after edit box" will get a blank list
2766  # we parse this near the beginning so that setHeaders can do the title
2767  # setting work instead of leaving it in getPreviewText
2768  $previewOutput = '';
2769  if ( $this->formtype == 'preview' ) {
2770  $previewOutput = $this->getPreviewText();
2771  }
2772 
2773  $out = $this->context->getOutput();
2774 
2775  // Avoid PHP 7.1 warning of passing $this by reference
2776  $editPage = $this;
2777  Hooks::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2778 
2779  $this->setHeaders();
2780 
2781  $this->addTalkPageText();
2782  $this->addEditNotices();
2783 
2784  if ( !$this->isConflict &&
2785  $this->section != '' &&
2786  !$this->isSectionEditSupported() ) {
2787  // We use $this->section to much before this and getVal('wgSection') directly in other places
2788  // at this point we can't reset $this->section to '' to fallback to non-section editing.
2789  // Someone is welcome to try refactoring though
2790  $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2791  return;
2792  }
2793 
2794  $this->showHeader();
2795 
2796  $out->addHTML( $this->editFormPageTop );
2797 
2798  $user = $this->context->getUser();
2799  if ( $user->getOption( 'previewontop' ) ) {
2800  $this->displayPreviewArea( $previewOutput, true );
2801  }
2802 
2803  $out->addHTML( $this->editFormTextTop );
2804 
2805  if ( $this->wasDeletedSinceLastEdit() && $this->formtype !== 'save' ) {
2806  $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2807  'deletedwhileediting' );
2808  }
2809 
2810  // @todo add EditForm plugin interface and use it here!
2811  // search for textarea1 and textarea2, and allow EditForm to override all uses.
2812  $out->addHTML( Html::openElement(
2813  'form',
2814  [
2815  'class' => 'mw-editform',
2816  'id' => self::EDITFORM_ID,
2817  'name' => self::EDITFORM_ID,
2818  'method' => 'post',
2819  'action' => $this->getActionURL( $this->getContextTitle() ),
2820  'enctype' => 'multipart/form-data'
2821  ]
2822  ) );
2823 
2824  if ( is_callable( $formCallback ) ) {
2825  wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2826  call_user_func_array( $formCallback, [ &$out ] );
2827  }
2828 
2829  // Add a check for Unicode support
2830  $out->addHTML( Html::hidden( 'wpUnicodeCheck', self::UNICODE_CHECK ) );
2831 
2832  // Add an empty field to trip up spambots
2833  $out->addHTML(
2834  Xml::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2835  . Html::rawElement(
2836  'label',
2837  [ 'for' => 'wpAntispam' ],
2838  $this->context->msg( 'simpleantispam-label' )->parse()
2839  )
2840  . Xml::element(
2841  'input',
2842  [
2843  'type' => 'text',
2844  'name' => 'wpAntispam',
2845  'id' => 'wpAntispam',
2846  'value' => ''
2847  ]
2848  )
2849  . Xml::closeElement( 'div' )
2850  );
2851 
2852  // Avoid PHP 7.1 warning of passing $this by reference
2853  $editPage = $this;
2854  Hooks::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2855 
2856  // Put these up at the top to ensure they aren't lost on early form submission
2857  $this->showFormBeforeText();
2858 
2859  if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2860  $username = $this->lastDelete->user_name;
2861  $comment = CommentStore::getStore()
2862  ->getComment( 'log_comment', $this->lastDelete )->text;
2863 
2864  // It is better to not parse the comment at all than to have templates expanded in the middle
2865  // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2866  $key = $comment === ''
2867  ? 'confirmrecreate-noreason'
2868  : 'confirmrecreate';
2869  $out->addHTML(
2870  '<div class="mw-confirm-recreate">' .
2871  $this->context->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2872  Xml::checkLabel( $this->context->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2873  [ 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2874  ) .
2875  '</div>'
2876  );
2877  }
2878 
2879  # When the summary is hidden, also hide them on preview/show changes
2880  if ( $this->nosummary ) {
2881  $out->addHTML( Html::hidden( 'nosummary', true ) );
2882  }
2883 
2884  # If a blank edit summary was previously provided, and the appropriate
2885  # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2886  # user being bounced back more than once in the event that a summary
2887  # is not required.
2888  # ####
2889  # For a bit more sophisticated detection of blank summaries, hash the
2890  # automatic one and pass that in the hidden field wpAutoSummary.
2891  if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2892  $out->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2893  }
2894 
2895  if ( $this->undidRev ) {
2896  $out->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2897  }
2898 
2899  if ( $this->selfRedirect ) {
2900  $out->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2901  }
2902 
2903  if ( $this->hasPresetSummary ) {
2904  // If a summary has been preset using &summary= we don't want to prompt for
2905  // a different summary. Only prompt for a summary if the summary is blanked.
2906  // (T19416)
2907  $this->autoSumm = md5( '' );
2908  }
2909 
2910  $autosumm = $this->autoSumm !== '' ? $this->autoSumm : md5( $this->summary );
2911  $out->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2912 
2913  $out->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2914  $out->addHTML( Html::hidden( 'parentRevId', $this->getParentRevId() ) );
2915 
2916  $out->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2917  $out->addHTML( Html::hidden( 'model', $this->contentModel ) );
2918 
2919  $out->enableOOUI();
2920 
2921  if ( $this->section == 'new' ) {
2922  $this->showSummaryInput( true, $this->summary );
2923  $out->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2924  }
2925 
2926  $out->addHTML( $this->editFormTextBeforeContent );
2927  if ( $this->isConflict ) {
2928  // In an edit conflict, we turn textbox2 into the user's text,
2929  // and textbox1 into the stored version
2930  $this->textbox2 = $this->textbox1;
2931 
2932  $content = $this->getCurrentContent();
2933  $this->textbox1 = $this->toEditText( $content );
2934 
2936  $editConflictHelper->setTextboxes( $this->textbox2, $this->textbox1 );
2937  $editConflictHelper->setContentModel( $this->contentModel );
2938  $editConflictHelper->setContentFormat( $this->contentFormat );
2940  }
2941 
2942  if ( !$this->mTitle->isUserConfigPage() ) {
2943  $out->addHTML( self::getEditToolbar( $this->mTitle ) );
2944  }
2945 
2946  if ( $this->blankArticle ) {
2947  $out->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2948  }
2949 
2950  if ( $this->isConflict ) {
2951  // In an edit conflict bypass the overridable content form method
2952  // and fallback to the raw wpTextbox1 since editconflicts can't be
2953  // resolved between page source edits and custom ui edits using the
2954  // custom edit ui.
2955  $conflictTextBoxAttribs = [];
2956  if ( $this->wasDeletedSinceLastEdit() ) {
2957  $conflictTextBoxAttribs['style'] = 'display:none;';
2958  } elseif ( $this->isOldRev ) {
2959  $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2960  }
2961 
2962  $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2964  } else {
2965  $this->showContentForm();
2966  }
2967 
2968  $out->addHTML( $this->editFormTextAfterContent );
2969 
2970  $this->showStandardInputs();
2971 
2972  $this->showFormAfterText();
2973 
2974  $this->showTosSummary();
2975 
2976  $this->showEditTools();
2977 
2978  $out->addHTML( $this->editFormTextAfterTools . "\n" );
2979 
2980  $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2981 
2982  $out->addHTML( Html::rawElement( 'div', [ 'class' => 'hiddencats' ],
2983  Linker::formatHiddenCategories( $this->page->getHiddenCategories() ) ) );
2984 
2985  $out->addHTML( Html::rawElement( 'div', [ 'class' => 'limitreport' ],
2986  self::getPreviewLimitReport( $this->mParserOutput ) ) );
2987 
2988  $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2989 
2990  if ( $this->isConflict ) {
2991  try {
2992  $this->showConflict();
2993  } catch ( MWContentSerializationException $ex ) {
2994  // this can't really happen, but be nice if it does.
2995  $msg = $this->context->msg(
2996  'content-failed-to-parse',
2997  $this->contentModel,
2998  $this->contentFormat,
2999  $ex->getMessage()
3000  );
3001  $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3002  }
3003  }
3004 
3005  // Set a hidden field so JS knows what edit form mode we are in
3006  if ( $this->isConflict ) {
3007  $mode = 'conflict';
3008  } elseif ( $this->preview ) {
3009  $mode = 'preview';
3010  } elseif ( $this->diff ) {
3011  $mode = 'diff';
3012  } else {
3013  $mode = 'text';
3014  }
3015  $out->addHTML( Html::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
3016 
3017  // Marker for detecting truncated form data. This must be the last
3018  // parameter sent in order to be of use, so do not move me.
3019  $out->addHTML( Html::hidden( 'wpUltimateParam', true ) );
3020  $out->addHTML( $this->editFormTextBottom . "\n</form>\n" );
3021 
3022  if ( !$user->getOption( 'previewontop' ) ) {
3023  $this->displayPreviewArea( $previewOutput, false );
3024  }
3025  }
3026 
3034  public function makeTemplatesOnThisPageList( array $templates ) {
3035  $templateListFormatter = new TemplatesOnThisPageFormatter(
3036  $this->context, MediaWikiServices::getInstance()->getLinkRenderer()
3037  );
3038 
3039  // preview if preview, else section if section, else false
3040  $type = false;
3041  if ( $this->preview ) {
3042  $type = 'preview';
3043  } elseif ( $this->section != '' ) {
3044  $type = 'section';
3045  }
3046 
3047  return Html::rawElement( 'div', [ 'class' => 'templatesUsed' ],
3048  $templateListFormatter->format( $templates, $type )
3049  );
3050  }
3051 
3058  public static function extractSectionTitle( $text ) {
3059  preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
3060  if ( !empty( $matches[2] ) ) {
3061  return MediaWikiServices::getInstance()->getParser()
3062  ->stripSectionName( trim( $matches[2] ) );
3063  } else {
3064  return false;
3065  }
3066  }
3067 
3068  protected function showHeader() {
3069  $out = $this->context->getOutput();
3070  $user = $this->context->getUser();
3071  if ( $this->isConflict ) {
3072  $this->addExplainConflictHeader( $out );
3073  $this->editRevId = $this->page->getLatest();
3074  } else {
3075  if ( $this->section != '' && $this->section != 'new' && !$this->summary &&
3076  !$this->preview && !$this->diff
3077  ) {
3078  $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
3079  if ( $sectionTitle !== false ) {
3080  $this->summary = "/* $sectionTitle */ ";
3081  }
3082  }
3083 
3084  $buttonLabel = $this->context->msg( $this->getSubmitButtonLabel() )->text();
3085 
3086  if ( $this->missingComment ) {
3087  $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3088  }
3089 
3090  if ( $this->missingSummary && $this->section != 'new' ) {
3091  $out->wrapWikiMsg(
3092  "<div id='mw-missingsummary'>\n$1\n</div>",
3093  [ 'missingsummary', $buttonLabel ]
3094  );
3095  }
3096 
3097  if ( $this->missingSummary && $this->section == 'new' ) {
3098  $out->wrapWikiMsg(
3099  "<div id='mw-missingcommentheader'>\n$1\n</div>",
3100  [ 'missingcommentheader', $buttonLabel ]
3101  );
3102  }
3103 
3104  if ( $this->blankArticle ) {
3105  $out->wrapWikiMsg(
3106  "<div id='mw-blankarticle'>\n$1\n</div>",
3107  [ 'blankarticle', $buttonLabel ]
3108  );
3109  }
3110 
3111  if ( $this->selfRedirect ) {
3112  $out->wrapWikiMsg(
3113  "<div id='mw-selfredirect'>\n$1\n</div>",
3114  [ 'selfredirect', $buttonLabel ]
3115  );
3116  }
3117 
3118  if ( $this->hookError !== '' ) {
3119  $out->addWikiTextAsInterface( $this->hookError );
3120  }
3121 
3122  if ( $this->section != 'new' ) {
3123  $revision = $this->mArticle->getRevisionFetched();
3124  if ( $revision ) {
3125  // Let sysop know that this will make private content public if saved
3126 
3127  if ( !$revision->userCan( Revision::DELETED_TEXT, $user ) ) {
3128  $out->wrapWikiMsg(
3129  "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3130  'rev-deleted-text-permission'
3131  );
3132  } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
3133  $out->wrapWikiMsg(
3134  "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3135  'rev-deleted-text-view'
3136  );
3137  }
3138 
3139  if ( !$revision->isCurrent() ) {
3140  $this->mArticle->setOldSubtitle( $revision->getId() );
3141  $out->wrapWikiMsg(
3142  Html::warningBox( "\n$1\n" ),
3143  'editingold'
3144  );
3145  $this->isOldRev = true;
3146  }
3147  } elseif ( $this->mTitle->exists() ) {
3148  // Something went wrong
3149 
3150  $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3151  [ 'missing-revision', $this->oldid ] );
3152  }
3153  }
3154  }
3155 
3156  if ( wfReadOnly() ) {
3157  $out->wrapWikiMsg(
3158  "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3159  [ 'readonlywarning', wfReadOnlyReason() ]
3160  );
3161  } elseif ( $user->isAnon() ) {
3162  if ( $this->formtype != 'preview' ) {
3163  $returntoquery = array_diff_key(
3164  $this->context->getRequest()->getValues(),
3165  [ 'title' => true, 'returnto' => true, 'returntoquery' => true ]
3166  );
3167  $out->wrapWikiMsg(
3168  "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3169  [ 'anoneditwarning',
3170  // Log-in link
3171  SpecialPage::getTitleFor( 'Userlogin' )->getFullURL( [
3172  'returnto' => $this->getTitle()->getPrefixedDBkey(),
3173  'returntoquery' => wfArrayToCgi( $returntoquery ),
3174  ] ),
3175  // Sign-up link
3176  SpecialPage::getTitleFor( 'CreateAccount' )->getFullURL( [
3177  'returnto' => $this->getTitle()->getPrefixedDBkey(),
3178  'returntoquery' => wfArrayToCgi( $returntoquery ),
3179  ] )
3180  ]
3181  );
3182  } else {
3183  $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3184  'anonpreviewwarning'
3185  );
3186  }
3187  } elseif ( $this->mTitle->isUserConfigPage() ) {
3188  # Check the skin exists
3189  if ( $this->isWrongCaseUserConfigPage() ) {
3190  $out->wrapWikiMsg(
3191  "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3192  [ 'userinvalidconfigtitle', $this->mTitle->getSkinFromConfigSubpage() ]
3193  );
3194  }
3195  if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3196  $isUserCssConfig = $this->mTitle->isUserCssConfigPage();
3197  $isUserJsonConfig = $this->mTitle->isUserJsonConfigPage();
3198  $isUserJsConfig = $this->mTitle->isUserJsConfigPage();
3199 
3200  $warning = $isUserCssConfig
3201  ? 'usercssispublic'
3202  : ( $isUserJsonConfig ? 'userjsonispublic' : 'userjsispublic' );
3203 
3204  $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3205 
3206  if ( $this->formtype !== 'preview' ) {
3207  $config = $this->context->getConfig();
3208  if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3209  $out->wrapWikiMsg(
3210  "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3211  [ 'usercssyoucanpreview' ]
3212  );
3213  } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3214  $out->wrapWikiMsg(
3215  "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3216  [ 'userjsonyoucanpreview' ]
3217  );
3218  } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3219  $out->wrapWikiMsg(
3220  "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3221  [ 'userjsyoucanpreview' ]
3222  );
3223  }
3224  }
3225  }
3226  }
3227 
3229 
3230  $this->addLongPageWarningHeader();
3231 
3232  # Add header copyright warning
3233  $this->showHeaderCopyrightWarning();
3234  }
3235 
3243  private function getSummaryInputAttributes( array $inputAttrs = null ) {
3244  // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3245  // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3246  // Unicode codepoints.
3247  return ( is_array( $inputAttrs ) ? $inputAttrs : [] ) + [
3248  'id' => 'wpSummary',
3249  'name' => 'wpSummary',
3251  'tabindex' => 1,
3252  'size' => 60,
3253  'spellcheck' => 'true',
3254  ];
3255  }
3256 
3266  function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3267  $inputAttrs = OOUI\Element::configFromHtmlAttributes(
3268  $this->getSummaryInputAttributes( $inputAttrs )
3269  );
3270  $inputAttrs += [
3271  'title' => Linker::titleAttrib( 'summary' ),
3272  'accessKey' => Linker::accesskey( 'summary' ),
3273  ];
3274 
3275  // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3276  $inputAttrs['inputId'] = $inputAttrs['id'];
3277  $inputAttrs['id'] = 'wpSummaryWidget';
3278 
3279  return new OOUI\FieldLayout(
3280  new OOUI\TextInputWidget( [
3281  'value' => $summary,
3282  'infusable' => true,
3283  ] + $inputAttrs ),
3284  [
3285  'label' => new OOUI\HtmlSnippet( $labelText ),
3286  'align' => 'top',
3287  'id' => 'wpSummaryLabel',
3288  'classes' => [ $this->missingSummary ? 'mw-summarymissed' : 'mw-summary' ],
3289  ]
3290  );
3291  }
3292 
3299  protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3300  # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3301  $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
3302  if ( $isSubjectPreview ) {
3303  if ( $this->nosummary ) {
3304  return;
3305  }
3306  } elseif ( !$this->mShowSummaryField ) {
3307  return;
3308  }
3309 
3310  $labelText = $this->context->msg( $isSubjectPreview ? 'subject' : 'summary' )->parse();
3311  $this->context->getOutput()->addHTML( $this->getSummaryInputWidget(
3312  $summary,
3313  $labelText,
3314  [ 'class' => $summaryClass ]
3315  ) );
3316  }
3317 
3325  protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3326  // avoid spaces in preview, gets always trimmed on save
3327  $summary = trim( $summary );
3328  if ( !$summary || ( !$this->preview && !$this->diff ) ) {
3329  return "";
3330  }
3331 
3332  if ( $isSubjectPreview ) {
3333  $summary = $this->context->msg( 'newsectionsummary' )
3334  ->rawParams( MediaWikiServices::getInstance()->getParser()
3335  ->stripSectionName( $summary ) )
3336  ->inContentLanguage()->text();
3337  }
3338 
3339  $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
3340 
3341  $summary = $this->context->msg( $message )->parse()
3342  . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
3343  return Xml::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3344  }
3345 
3346  protected function showFormBeforeText() {
3347  $out = $this->context->getOutput();
3348  $out->addHTML( Html::hidden( 'wpSection', $this->section ) );
3349  $out->addHTML( Html::hidden( 'wpStarttime', $this->starttime ) );
3350  $out->addHTML( Html::hidden( 'wpEdittime', $this->edittime ) );
3351  $out->addHTML( Html::hidden( 'editRevId', $this->editRevId ) );
3352  $out->addHTML( Html::hidden( 'wpScrolltop', $this->scrolltop, [ 'id' => 'wpScrolltop' ] ) );
3353  }
3354 
3355  protected function showFormAfterText() {
3368  $this->context->getOutput()->addHTML(
3369  "\n" .
3370  Html::hidden( "wpEditToken", $this->context->getUser()->getEditToken() ) .
3371  "\n"
3372  );
3373  }
3374 
3383  protected function showContentForm() {
3384  $this->showTextbox1();
3385  }
3386 
3395  protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3396  if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
3397  $attribs = [ 'style' => 'display:none;' ];
3398  } else {
3399  $builder = new TextboxBuilder();
3400  $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3401 
3402  # Is an old revision being edited?
3403  if ( $this->isOldRev ) {
3404  $classes[] = 'mw-textarea-oldrev';
3405  }
3406 
3407  $attribs = [ 'tabindex' => 1 ];
3408 
3409  if ( is_array( $customAttribs ) ) {
3411  }
3412 
3413  $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3414  }
3415 
3416  $this->showTextbox(
3417  $textoverride ?? $this->textbox1,
3418  'wpTextbox1',
3419  $attribs
3420  );
3421  }
3422 
3423  protected function showTextbox2() {
3424  $this->showTextbox( $this->textbox2, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3425  }
3426 
3427  protected function showTextbox( $text, $name, $customAttribs = [] ) {
3428  $builder = new TextboxBuilder();
3429  $attribs = $builder->buildTextboxAttribs(
3430  $name,
3432  $this->context->getUser(),
3434  );
3435 
3436  $this->context->getOutput()->addHTML(
3437  Html::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3438  );
3439  }
3440 
3441  protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3442  $classes = [];
3443  if ( $isOnTop ) {
3444  $classes[] = 'ontop';
3445  }
3446 
3447  $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3448 
3449  if ( $this->formtype != 'preview' ) {
3450  $attribs['style'] = 'display: none;';
3451  }
3452 
3453  $out = $this->context->getOutput();
3454  $out->addHTML( Xml::openElement( 'div', $attribs ) );
3455 
3456  if ( $this->formtype == 'preview' ) {
3457  $this->showPreview( $previewOutput );
3458  } else {
3459  // Empty content container for LivePreview
3460  $pageViewLang = $this->mTitle->getPageViewLanguage();
3461  $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3462  'class' => 'mw-content-' . $pageViewLang->getDir() ];
3463  $out->addHTML( Html::rawElement( 'div', $attribs ) );
3464  }
3465 
3466  $out->addHTML( '</div>' );
3467 
3468  if ( $this->formtype == 'diff' ) {
3469  try {
3470  $this->showDiff();
3471  } catch ( MWContentSerializationException $ex ) {
3472  $msg = $this->context->msg(
3473  'content-failed-to-parse',
3474  $this->contentModel,
3475  $this->contentFormat,
3476  $ex->getMessage()
3477  );
3478  $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3479  }
3480  }
3481  }
3482 
3489  protected function showPreview( $text ) {
3490  if ( $this->mArticle instanceof CategoryPage ) {
3491  $this->mArticle->openShowCategory();
3492  }
3493  # This hook seems slightly odd here, but makes things more
3494  # consistent for extensions.
3495  $out = $this->context->getOutput();
3496  Hooks::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3497  $out->addHTML( $text );
3498  if ( $this->mArticle instanceof CategoryPage ) {
3499  $this->mArticle->closeShowCategory();
3500  }
3501  }
3502 
3510  public function showDiff() {
3511  $oldtitlemsg = 'currentrev';
3512  # if message does not exist, show diff against the preloaded default
3513  if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3514  $oldtext = $this->mTitle->getDefaultMessageText();
3515  if ( $oldtext !== false ) {
3516  $oldtitlemsg = 'defaultmessagetext';
3517  $oldContent = $this->toEditContent( $oldtext );
3518  } else {
3519  $oldContent = null;
3520  }
3521  } else {
3522  $oldContent = $this->getCurrentContent();
3523  }
3524 
3525  $textboxContent = $this->toEditContent( $this->textbox1 );
3526  if ( $this->editRevId !== null ) {
3527  $newContent = $this->page->replaceSectionAtRev(
3528  $this->section, $textboxContent, $this->summary, $this->editRevId
3529  );
3530  } else {
3531  $newContent = $this->page->replaceSectionContent(
3532  $this->section, $textboxContent, $this->summary, $this->edittime
3533  );
3534  }
3535 
3536  if ( $newContent ) {
3537  Hooks::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3538 
3539  $user = $this->context->getUser();
3541  MediaWikiServices::getInstance()->getContentLanguage() );
3542  $newContent = $newContent->preSaveTransform( $this->mTitle, $user, $popts );
3543  }
3544 
3545  if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3546  $oldtitle = $this->context->msg( $oldtitlemsg )->parse();
3547  $newtitle = $this->context->msg( 'yourtext' )->parse();
3548 
3549  if ( !$oldContent ) {
3550  $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3551  }
3552 
3553  if ( !$newContent ) {
3554  $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3555  }
3556 
3557  $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context );
3558  $de->setContent( $oldContent, $newContent );
3559 
3560  $difftext = $de->getDiff( $oldtitle, $newtitle );
3561  $de->showDiffStyle();
3562  } else {
3563  $difftext = '';
3564  }
3565 
3566  $this->context->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3567  }
3568 
3572  protected function showHeaderCopyrightWarning() {
3573  $msg = 'editpage-head-copy-warn';
3574  if ( !$this->context->msg( $msg )->isDisabled() ) {
3575  $this->context->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3576  'editpage-head-copy-warn' );
3577  }
3578  }
3579 
3588  protected function showTosSummary() {
3589  $msg = 'editpage-tos-summary';
3590  Hooks::run( 'EditPageTosSummary', [ $this->mTitle, &$msg ] );
3591  if ( !$this->context->msg( $msg )->isDisabled() ) {
3592  $out = $this->context->getOutput();
3593  $out->addHTML( '<div class="mw-tos-summary">' );
3594  $out->addWikiMsg( $msg );
3595  $out->addHTML( '</div>' );
3596  }
3597  }
3598 
3603  protected function showEditTools() {
3604  $this->context->getOutput()->addHTML( '<div class="mw-editTools">' .
3605  $this->context->msg( 'edittools' )->inContentLanguage()->parse() .
3606  '</div>' );
3607  }
3608 
3615  protected function getCopywarn() {
3616  return self::getCopyrightWarning( $this->mTitle );
3617  }
3618 
3627  public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3628  global $wgRightsText;
3629  if ( $wgRightsText ) {
3630  $copywarnMsg = [ 'copyrightwarning',
3631  '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3632  $wgRightsText ];
3633  } else {
3634  $copywarnMsg = [ 'copyrightwarning2',
3635  '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3636  }
3637  // Allow for site and per-namespace customization of contribution/copyright notice.
3638  Hooks::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3639 
3640  $msg = wfMessage( ...$copywarnMsg )->title( $title );
3641  if ( $langcode ) {
3642  $msg->inLanguage( $langcode );
3643  }
3644  return "<div id=\"editpage-copywarn\">\n" .
3645  $msg->$format() . "\n</div>";
3646  }
3647 
3655  public static function getPreviewLimitReport( ParserOutput $output = null ) {
3656  global $wgLang;
3657 
3658  if ( !$output || !$output->getLimitReportData() ) {
3659  return '';
3660  }
3661 
3662  $limitReport = Html::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3663  wfMessage( 'limitreport-title' )->parseAsBlock()
3664  );
3665 
3666  // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3667  $limitReport .= Html::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3668 
3669  $limitReport .= Html::openElement( 'table', [
3670  'class' => 'preview-limit-report wikitable'
3671  ] ) .
3672  Html::openElement( 'tbody' );
3673 
3674  foreach ( $output->getLimitReportData() as $key => $value ) {
3675  if ( Hooks::run( 'ParserLimitReportFormat',
3676  [ $key, &$value, &$limitReport, true, true ]
3677  ) ) {
3678  $keyMsg = wfMessage( $key );
3679  $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3680  if ( !$valueMsg->exists() ) {
3681  $valueMsg = new RawMessage( '$1' );
3682  }
3683  if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3684  $limitReport .= Html::openElement( 'tr' ) .
3685  Html::rawElement( 'th', null, $keyMsg->parse() ) .
3686  Html::rawElement( 'td', null,
3687  $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3688  ) .
3689  Html::closeElement( 'tr' );
3690  }
3691  }
3692  }
3693 
3694  $limitReport .= Html::closeElement( 'tbody' ) .
3695  Html::closeElement( 'table' ) .
3696  Html::closeElement( 'div' );
3697 
3698  return $limitReport;
3699  }
3700 
3701  protected function showStandardInputs( &$tabindex = 2 ) {
3702  $out = $this->context->getOutput();
3703  $out->addHTML( "<div class='editOptions'>\n" );
3704 
3705  if ( $this->section != 'new' ) {
3706  $this->showSummaryInput( false, $this->summary );
3707  $out->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3708  }
3709 
3710  $checkboxes = $this->getCheckboxesWidget(
3711  $tabindex,
3712  [ 'minor' => $this->minoredit, 'watch' => $this->watchthis ]
3713  );
3714  $checkboxesHTML = new OOUI\HorizontalLayout( [ 'items' => $checkboxes ] );
3715 
3716  $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3717 
3718  // Show copyright warning.
3719  $out->addWikiTextAsInterface( $this->getCopywarn() );
3720  $out->addHTML( $this->editFormTextAfterWarn );
3721 
3722  $out->addHTML( "<div class='editButtons'>\n" );
3723  $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3724 
3725  $cancel = $this->getCancelLink();
3726 
3727  $message = $this->context->msg( 'edithelppage' )->inContentLanguage()->text();
3728  $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3729  $edithelp =
3731  $this->context->msg( 'edithelp' )->text(),
3732  [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3733  [ 'mw-ui-quiet' ]
3734  ) .
3735  $this->context->msg( 'word-separator' )->escaped() .
3736  $this->context->msg( 'newwindow' )->parse();
3737 
3738  $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3739  $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3740  $out->addHTML( "</div><!-- editButtons -->\n" );
3741 
3742  Hooks::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3743 
3744  $out->addHTML( "</div><!-- editOptions -->\n" );
3745  }
3746 
3751  protected function showConflict() {
3752  $out = $this->context->getOutput();
3753  // Avoid PHP 7.1 warning of passing $this by reference
3754  $editPage = $this;
3755  if ( Hooks::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3756  $this->incrementConflictStats();
3757 
3758  $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3759  }
3760  }
3761 
3762  protected function incrementConflictStats() {
3763  $this->getEditConflictHelper()->incrementConflictStats();
3764  }
3765 
3769  public function getCancelLink() {
3770  $cancelParams = [];
3771  if ( !$this->isConflict && $this->oldid > 0 ) {
3772  $cancelParams['oldid'] = $this->oldid;
3773  } elseif ( $this->getContextTitle()->isRedirect() ) {
3774  $cancelParams['redirect'] = 'no';
3775  }
3776 
3777  return new OOUI\ButtonWidget( [
3778  'id' => 'mw-editform-cancel',
3779  'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3780  'label' => new OOUI\HtmlSnippet( $this->context->msg( 'cancel' )->parse() ),
3781  'framed' => false,
3782  'infusable' => true,
3783  'flags' => 'destructive',
3784  ] );
3785  }
3786 
3796  protected function getActionURL( Title $title ) {
3797  return $title->getLocalURL( [ 'action' => $this->action ] );
3798  }
3799 
3807  protected function wasDeletedSinceLastEdit() {
3808  if ( $this->deletedSinceEdit !== null ) {
3809  return $this->deletedSinceEdit;
3810  }
3811 
3812  $this->deletedSinceEdit = false;
3813 
3814  if ( !$this->mTitle->exists() && $this->mTitle->isDeletedQuick() ) {
3815  $this->lastDelete = $this->getLastDelete();
3816  if ( $this->lastDelete ) {
3817  $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3818  if ( $deleteTime > $this->starttime ) {
3819  $this->deletedSinceEdit = true;
3820  }
3821  }
3822  }
3823 
3824  return $this->deletedSinceEdit;
3825  }
3826 
3832  protected function getLastDelete() {
3833  $dbr = wfGetDB( DB_REPLICA );
3834  $commentQuery = CommentStore::getStore()->getJoin( 'log_comment' );
3835  $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
3836  $data = $dbr->selectRow(
3837  array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3838  [
3839  'log_type',
3840  'log_action',
3841  'log_timestamp',
3842  'log_namespace',
3843  'log_title',
3844  'log_params',
3845  'log_deleted',
3846  'user_name'
3847  ] + $commentQuery['fields'] + $actorQuery['fields'],
3848  [
3849  'log_namespace' => $this->mTitle->getNamespace(),
3850  'log_title' => $this->mTitle->getDBkey(),
3851  'log_type' => 'delete',
3852  'log_action' => 'delete',
3853  ],
3854  __METHOD__,
3855  [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3856  [
3857  'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3858  ] + $commentQuery['joins'] + $actorQuery['joins']
3859  );
3860  // Quick paranoid permission checks...
3861  if ( is_object( $data ) ) {
3862  if ( $data->log_deleted & LogPage::DELETED_USER ) {
3863  $data->user_name = $this->context->msg( 'rev-deleted-user' )->escaped();
3864  }
3865 
3866  if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3867  $data->log_comment_text = $this->context->msg( 'rev-deleted-comment' )->escaped();
3868  $data->log_comment_data = null;
3869  }
3870  }
3871 
3872  return $data;
3873  }
3874 
3880  public function getPreviewText() {
3881  $out = $this->context->getOutput();
3882  $config = $this->context->getConfig();
3883 
3884  if ( $config->get( 'RawHtml' ) && !$this->mTokenOk ) {
3885  // Could be an offsite preview attempt. This is very unsafe if
3886  // HTML is enabled, as it could be an attack.
3887  $parsedNote = '';
3888  if ( $this->textbox1 !== '' ) {
3889  // Do not put big scary notice, if previewing the empty
3890  // string, which happens when you initially edit
3891  // a category page, due to automatic preview-on-open.
3892  $parsedNote = Html::rawElement( 'div', [ 'class' => 'previewnote' ],
3893  $out->parseAsInterface(
3894  $this->context->msg( 'session_fail_preview_html' )->plain()
3895  ) );
3896  }
3897  $this->incrementEditFailureStats( 'session_loss' );
3898  return $parsedNote;
3899  }
3900 
3901  $note = '';
3902 
3903  try {
3904  $content = $this->toEditContent( $this->textbox1 );
3905 
3906  $previewHTML = '';
3907  if ( !Hooks::run(
3908  'AlternateEditPreview',
3909  [ $this, &$content, &$previewHTML, &$this->mParserOutput ] )
3910  ) {
3911  return $previewHTML;
3912  }
3913 
3914  # provide a anchor link to the editform
3915  $continueEditing = '<span class="mw-continue-editing">' .
3916  '[[#' . self::EDITFORM_ID . '|' .
3917  $this->context->getLanguage()->getArrow() . ' ' .
3918  $this->context->msg( 'continue-editing' )->text() . ']]</span>';
3919  if ( $this->mTriedSave && !$this->mTokenOk ) {
3920  if ( $this->mTokenOkExceptSuffix ) {
3921  $note = $this->context->msg( 'token_suffix_mismatch' )->plain();
3922  $this->incrementEditFailureStats( 'bad_token' );
3923  } else {
3924  $note = $this->context->msg( 'session_fail_preview' )->plain();
3925  $this->incrementEditFailureStats( 'session_loss' );
3926  }
3927  } elseif ( $this->incompleteForm ) {
3928  $note = $this->context->msg( 'edit_form_incomplete' )->plain();
3929  if ( $this->mTriedSave ) {
3930  $this->incrementEditFailureStats( 'incomplete_form' );
3931  }
3932  } else {
3933  $note = $this->context->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3934  }
3935 
3936  # don't parse non-wikitext pages, show message about preview
3937  if ( $this->mTitle->isUserConfigPage() || $this->mTitle->isSiteConfigPage() ) {
3938  if ( $this->mTitle->isUserConfigPage() ) {
3939  $level = 'user';
3940  } elseif ( $this->mTitle->isSiteConfigPage() ) {
3941  $level = 'site';
3942  } else {
3943  $level = false;
3944  }
3945 
3946  if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3947  $format = 'css';
3948  if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3949  $format = false;
3950  }
3951  } elseif ( $content->getModel() == CONTENT_MODEL_JSON ) {
3952  $format = 'json';
3953  if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3954  $format = false;
3955  }
3956  } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3957  $format = 'js';
3958  if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3959  $format = false;
3960  }
3961  } else {
3962  $format = false;
3963  }
3964 
3965  # Used messages to make sure grep find them:
3966  # Messages: usercsspreview, userjsonpreview, userjspreview,
3967  # sitecsspreview, sitejsonpreview, sitejspreview
3968  if ( $level && $format ) {
3969  $note = "<div id='mw-{$level}{$format}preview'>" .
3970  $this->context->msg( "{$level}{$format}preview" )->plain() .
3971  ' ' . $continueEditing . "</div>";
3972  }
3973  }
3974 
3975  # If we're adding a comment, we need to show the
3976  # summary as the headline
3977  if ( $this->section === "new" && $this->summary !== "" ) {
3978  $content = $content->addSectionHeader( $this->summary );
3979  }
3980 
3981  $hook_args = [ $this, &$content ];
3982  Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3983 
3984  $parserResult = $this->doPreviewParse( $content );
3985  $parserOutput = $parserResult['parserOutput'];
3986  $previewHTML = $parserResult['html'];
3987  $this->mParserOutput = $parserOutput;
3988  $out->addParserOutputMetadata( $parserOutput );
3989  if ( $out->userCanPreview() ) {
3990  $out->addContentOverride( $this->getTitle(), $content );
3991  }
3992 
3993  if ( count( $parserOutput->getWarnings() ) ) {
3994  $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3995  }
3996 
3997  } catch ( MWContentSerializationException $ex ) {
3998  $m = $this->context->msg(
3999  'content-failed-to-parse',
4000  $this->contentModel,
4001  $this->contentFormat,
4002  $ex->getMessage()
4003  );
4004  $note .= "\n\n" . $m->plain(); # gets parsed down below
4005  $previewHTML = '';
4006  }
4007 
4008  if ( $this->isConflict ) {
4009  $conflict = Html::rawElement(
4010  'h2', [ 'id' => 'mw-previewconflict' ],
4011  $this->context->msg( 'previewconflict' )->escaped()
4012  );
4013  } else {
4014  $conflict = '<hr />';
4015  }
4016 
4017  $previewhead = Html::rawElement(
4018  'div', [ 'class' => 'previewnote' ],
4020  'h2', [ 'id' => 'mw-previewheader' ],
4021  $this->context->msg( 'preview' )->escaped()
4022  ) .
4023  $out->parseAsInterface( $note ) . $conflict
4024  );
4025 
4026  $pageViewLang = $this->mTitle->getPageViewLanguage();
4027  $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
4028  'class' => 'mw-content-' . $pageViewLang->getDir() ];
4029  $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
4030 
4031  return $previewhead . $previewHTML . $this->previewTextAfterContent;
4032  }
4033 
4034  private function incrementEditFailureStats( $failureType ) {
4035  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
4036  $stats->increment( 'edit.failures.' . $failureType );
4037  }
4038 
4043  protected function getPreviewParserOptions() {
4044  $parserOptions = $this->page->makeParserOptions( $this->context );
4045  $parserOptions->setIsPreview( true );
4046  $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
4047  $parserOptions->enableLimitReport();
4048 
4049  // XXX: we could call $parserOptions->setCurrentRevisionCallback here to force the
4050  // current revision to be null during PST, until setupFakeRevision is called on
4051  // the ParserOptions. Currently, we rely on Parser::getRevisionObject() to ignore
4052  // existing revisions in preview mode.
4053 
4054  return $parserOptions;
4055  }
4056 
4066  protected function doPreviewParse( Content $content ) {
4067  $user = $this->context->getUser();
4068  $parserOptions = $this->getPreviewParserOptions();
4069 
4070  // NOTE: preSaveTransform doesn't have a fake revision to operate on.
4071  // Parser::getRevisionObject() will return null in preview mode,
4072  // causing the context user to be used for {{subst:REVISIONUSER}}.
4073  // XXX: Alternatively, we could also call setupFakeRevision() a second time:
4074  // once before PST with $content, and then after PST with $pstContent.
4075  $pstContent = $content->preSaveTransform( $this->mTitle, $user, $parserOptions );
4076  $scopedCallback = $parserOptions->setupFakeRevision( $this->mTitle, $pstContent, $user );
4077  $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
4078  ScopedCallback::consume( $scopedCallback );
4079  return [
4080  'parserOutput' => $parserOutput,
4081  'html' => $parserOutput->getText( [
4082  'enableSectionEditLinks' => false
4083  ] )
4084  ];
4085  }
4086 
4090  public function getTemplates() {
4091  if ( $this->preview || $this->section != '' ) {
4092  $templates = [];
4093  if ( !isset( $this->mParserOutput ) ) {
4094  return $templates;
4095  }
4096  foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
4097  foreach ( array_keys( $template ) as $dbk ) {
4098  $templates[] = Title::makeTitle( $ns, $dbk );
4099  }
4100  }
4101  return $templates;
4102  } else {
4103  return $this->mTitle->getTemplateLinksFrom();
4104  }
4105  }
4106 
4113  public static function getEditToolbar( $title = null ) {
4114  $startingToolbar = '<div id="toolbar"></div>';
4115  $toolbar = $startingToolbar;
4116 
4117  if ( !Hooks::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4118  return null;
4119  };
4120  // Don't add a pointless `<div>` to the page unless a hook caller populated it
4121  return ( $toolbar === $startingToolbar ) ? null : $toolbar;
4122  }
4123 
4142  public function getCheckboxesDefinition( $checked ) {
4143  $checkboxes = [];
4144 
4145  $user = $this->context->getUser();
4146  // don't show the minor edit checkbox if it's a new page or section
4147  if ( !$this->isNew && $user->isAllowed( 'minoredit' ) ) {
4148  $checkboxes['wpMinoredit'] = [
4149  'id' => 'wpMinoredit',
4150  'label-message' => 'minoredit',
4151  // Uses messages: tooltip-minoredit, accesskey-minoredit
4152  'tooltip' => 'minoredit',
4153  'label-id' => 'mw-editpage-minoredit',
4154  'legacy-name' => 'minor',
4155  'default' => $checked['minor'],
4156  ];
4157  }
4158 
4159  if ( $user->isLoggedIn() ) {
4160  $checkboxes['wpWatchthis'] = [
4161  'id' => 'wpWatchthis',
4162  'label-message' => 'watchthis',
4163  // Uses messages: tooltip-watch, accesskey-watch
4164  'tooltip' => 'watch',
4165  'label-id' => 'mw-editpage-watch',
4166  'legacy-name' => 'watch',
4167  'default' => $checked['watch'],
4168  ];
4169  }
4170 
4171  $editPage = $this;
4172  Hooks::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4173 
4174  return $checkboxes;
4175  }
4176 
4187  public function getCheckboxesWidget( &$tabindex, $checked ) {
4188  $checkboxes = [];
4189  $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4190 
4191  foreach ( $checkboxesDef as $name => $options ) {
4192  $legacyName = $options['legacy-name'] ?? $name;
4193 
4194  $title = null;
4195  $accesskey = null;
4196  if ( isset( $options['tooltip'] ) ) {
4197  $accesskey = $this->context->msg( "accesskey-{$options['tooltip']}" )->text();
4198  $title = Linker::titleAttrib( $options['tooltip'] );
4199  }
4200  if ( isset( $options['title-message'] ) ) {
4201  $title = $this->context->msg( $options['title-message'] )->text();
4202  }
4203 
4204  $checkboxes[ $legacyName ] = new OOUI\FieldLayout(
4205  new OOUI\CheckboxInputWidget( [
4206  'tabIndex' => ++$tabindex,
4207  'accessKey' => $accesskey,
4208  'id' => $options['id'] . 'Widget',
4209  'inputId' => $options['id'],
4210  'name' => $name,
4211  'selected' => $options['default'],
4212  'infusable' => true,
4213  ] ),
4214  [
4215  'align' => 'inline',
4216  'label' => new OOUI\HtmlSnippet( $this->context->msg( $options['label-message'] )->parse() ),
4217  'title' => $title,
4218  'id' => $options['label-id'] ?? null,
4219  ]
4220  );
4221  }
4222 
4223  return $checkboxes;
4224  }
4225 
4232  protected function getSubmitButtonLabel() {
4233  $labelAsPublish =
4234  $this->context->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4235 
4236  // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4237  $newPage = !$this->mTitle->exists();
4238 
4239  if ( $labelAsPublish ) {
4240  $buttonLabelKey = $newPage ? 'publishpage' : 'publishchanges';
4241  } else {
4242  $buttonLabelKey = $newPage ? 'savearticle' : 'savechanges';
4243  }
4244 
4245  return $buttonLabelKey;
4246  }
4247 
4256  public function getEditButtons( &$tabindex ) {
4257  $buttons = [];
4258 
4259  $labelAsPublish =
4260  $this->context->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4261 
4262  $buttonLabel = $this->context->msg( $this->getSubmitButtonLabel() )->text();
4263  $buttonTooltip = $labelAsPublish ? 'publish' : 'save';
4264 
4265  $buttons['save'] = new OOUI\ButtonInputWidget( [
4266  'name' => 'wpSave',
4267  'tabIndex' => ++$tabindex,
4268  'id' => 'wpSaveWidget',
4269  'inputId' => 'wpSave',
4270  // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4271  'useInputTag' => true,
4272  'flags' => [ 'progressive', 'primary' ],
4273  'label' => $buttonLabel,
4274  'infusable' => true,
4275  'type' => 'submit',
4276  // Messages used: tooltip-save, tooltip-publish
4277  'title' => Linker::titleAttrib( $buttonTooltip ),
4278  // Messages used: accesskey-save, accesskey-publish
4279  'accessKey' => Linker::accesskey( $buttonTooltip ),
4280  ] );
4281 
4282  $buttons['preview'] = new OOUI\ButtonInputWidget( [
4283  'name' => 'wpPreview',
4284  'tabIndex' => ++$tabindex,
4285  'id' => 'wpPreviewWidget',
4286  'inputId' => 'wpPreview',
4287  // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4288  'useInputTag' => true,
4289  'label' => $this->context->msg( 'showpreview' )->text(),
4290  'infusable' => true,
4291  'type' => 'submit',
4292  // Message used: tooltip-preview
4293  'title' => Linker::titleAttrib( 'preview' ),
4294  // Message used: accesskey-preview
4295  'accessKey' => Linker::accesskey( 'preview' ),
4296  ] );
4297 
4298  $buttons['diff'] = new OOUI\ButtonInputWidget( [
4299  'name' => 'wpDiff',
4300  'tabIndex' => ++$tabindex,
4301  'id' => 'wpDiffWidget',
4302  'inputId' => 'wpDiff',
4303  // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4304  'useInputTag' => true,
4305  'label' => $this->context->msg( 'showdiff' )->text(),
4306  'infusable' => true,
4307  'type' => 'submit',
4308  // Message used: tooltip-diff
4309  'title' => Linker::titleAttrib( 'diff' ),
4310  // Message used: accesskey-diff
4311  'accessKey' => Linker::accesskey( 'diff' ),
4312  ] );
4313 
4314  // Avoid PHP 7.1 warning of passing $this by reference
4315  $editPage = $this;
4316  Hooks::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4317 
4318  return $buttons;
4319  }
4320 
4325  public function noSuchSectionPage() {
4326  $out = $this->context->getOutput();
4327  $out->prepareErrorPage( $this->context->msg( 'nosuchsectiontitle' ) );
4328 
4329  $res = $this->context->msg( 'nosuchsectiontext', $this->section )->parseAsBlock();
4330 
4331  // Avoid PHP 7.1 warning of passing $this by reference
4332  $editPage = $this;
4333  Hooks::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4334  $out->addHTML( $res );
4335 
4336  $out->returnToMain( false, $this->mTitle );
4337  }
4338 
4344  public function spamPageWithContent( $match = false ) {
4345  $this->textbox2 = $this->textbox1;
4346 
4347  if ( is_array( $match ) ) {
4348  $match = $this->context->getLanguage()->listToText( $match );
4349  }
4350  $out = $this->context->getOutput();
4351  $out->prepareErrorPage( $this->context->msg( 'spamprotectiontitle' ) );
4352 
4353  $out->addHTML( '<div id="spamprotected">' );
4354  $out->addWikiMsg( 'spamprotectiontext' );
4355  if ( $match ) {
4356  $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4357  }
4358  $out->addHTML( '</div>' );
4359 
4360  $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4361  $this->showDiff();
4362 
4363  $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4364  $this->showTextbox2();
4365 
4366  $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4367  }
4368 
4379  protected function safeUnicodeInput( $request, $field ) {
4380  return rtrim( $request->getText( $field ) );
4381  }
4382 
4392  protected function safeUnicodeOutput( $text ) {
4393  return $text;
4394  }
4395 
4399  protected function addEditNotices() {
4400  $out = $this->context->getOutput();
4401  $editNotices = $this->mTitle->getEditNotices( $this->oldid );
4402  if ( count( $editNotices ) ) {
4403  $out->addHTML( implode( "\n", $editNotices ) );
4404  } else {
4405  $msg = $this->context->msg( 'editnotice-notext' );
4406  if ( !$msg->isDisabled() ) {
4407  $out->addHTML(
4408  '<div class="mw-editnotice-notext">'
4409  . $msg->parseAsBlock()
4410  . '</div>'
4411  );
4412  }
4413  }
4414  }
4415 
4419  protected function addTalkPageText() {
4420  if ( $this->mTitle->isTalkPage() ) {
4421  $this->context->getOutput()->addWikiMsg( 'talkpagetext' );
4422  }
4423  }
4424 
4428  protected function addLongPageWarningHeader() {
4429  if ( $this->contentLength === false ) {
4430  $this->contentLength = strlen( $this->textbox1 );
4431  }
4432 
4433  $out = $this->context->getOutput();
4434  $lang = $this->context->getLanguage();
4435  $maxArticleSize = $this->context->getConfig()->get( 'MaxArticleSize' );
4436  if ( $this->tooBig || $this->contentLength > $maxArticleSize * 1024 ) {
4437  $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4438  [
4439  'longpageerror',
4440  $lang->formatNum( round( $this->contentLength / 1024, 3 ) ),
4441  $lang->formatNum( $maxArticleSize )
4442  ]
4443  );
4444  } elseif ( !$this->context->msg( 'longpage-hint' )->isDisabled() ) {
4445  $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4446  [
4447  'longpage-hint',
4448  $lang->formatSize( strlen( $this->textbox1 ) ),
4449  strlen( $this->textbox1 )
4450  ]
4451  );
4452  }
4453  }
4454 
4458  protected function addPageProtectionWarningHeaders() {
4459  $out = $this->context->getOutput();
4460  if ( $this->mTitle->isProtected( 'edit' ) &&
4461  MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== [ '' ]
4462  ) {
4463  # Is the title semi-protected?
4464  if ( $this->mTitle->isSemiProtected() ) {
4465  $noticeMsg = 'semiprotectedpagewarning';
4466  } else {
4467  # Then it must be protected based on static groups (regular)
4468  $noticeMsg = 'protectedpagewarning';
4469  }
4470  LogEventsList::showLogExtract( $out, 'protect', $this->mTitle, '',
4471  [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4472  }
4473  if ( $this->mTitle->isCascadeProtected() ) {
4474  # Is this page under cascading protection from some source pages?
4475 
4476  list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
4477  $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4478  $cascadeSourcesCount = count( $cascadeSources );
4479  if ( $cascadeSourcesCount > 0 ) {
4480  # Explain, and list the titles responsible
4481  foreach ( $cascadeSources as $page ) {
4482  $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4483  }
4484  }
4485  $notice .= '</div>';
4486  $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4487  }
4488  if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
4489  LogEventsList::showLogExtract( $out, 'protect', $this->mTitle, '',
4490  [ 'lim' => 1,
4491  'showIfEmpty' => false,
4492  'msgKey' => [ 'titleprotectedwarning' ],
4493  'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4494  }
4495  }
4496 
4501  protected function addExplainConflictHeader( OutputPage $out ) {
4502  $out->addHTML(
4503  $this->getEditConflictHelper()->getExplainHeader()
4504  );
4505  }
4506 
4515  return ( new TextboxBuilder() )->buildTextboxAttribs(
4516  $name, $customAttribs, $user, $this->mTitle
4517  );
4518  }
4519 
4525  protected function addNewLineAtEnd( $wikitext ) {
4526  return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4527  }
4528 
4539  private function guessSectionName( $text ) {
4540  // Detect Microsoft browsers
4541  $userAgent = $this->context->getRequest()->getHeader( 'User-Agent' );
4542  $parser = MediaWikiServices::getInstance()->getParser();
4543  if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4544  // ...and redirect them to legacy encoding, if available
4545  return $parser->guessLegacySectionNameFromWikiText( $text );
4546  }
4547  // Meanwhile, real browsers get real anchors
4548  $name = $parser->guessSectionNameFromWikiText( $text );
4549  // With one little caveat: per T216029, fragments in HTTP redirects need to be urlencoded,
4550  // otherwise Chrome double-escapes the rest of the URL.
4551  return '#' . urlencode( mb_substr( $name, 1 ) );
4552  }
4553 
4560  public function setEditConflictHelperFactory( callable $factory ) {
4561  $this->editConflictHelperFactory = $factory;
4562  $this->editConflictHelper = null;
4563  }
4564 
4568  private function getEditConflictHelper() {
4569  if ( !$this->editConflictHelper ) {
4570  $this->editConflictHelper = call_user_func(
4571  $this->editConflictHelperFactory,
4572  $this->getSubmitButtonLabel()
4573  );
4574  }
4575 
4577  }
4578 
4583  private function newTextConflictHelper( $submitButtonLabel ) {
4584  return new TextConflictHelper(
4585  $this->getTitle(),
4586  $this->getContext()->getOutput(),
4587  MediaWikiServices::getInstance()->getStatsdDataFactory(),
4588  $submitButtonLabel
4589  );
4590  }
4591 }
string $autoSumm
Definition: EditPage.php:299
getContent( $audience=Revision::FOR_PUBLIC, User $user=null)
Get the content of the current revision.
Definition: WikiPage.php:816
Helps EditPage build textboxes.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:138
displayPermissionsError(array $permErrors)
Display a permissions error page, like OutputPage::showPermissionsErrorPage(), but with the following...
Definition: EditPage.php:770
safeUnicodeInput( $request, $field)
Filter an input field through a Unicode de-armoring process if it came from an old browser with known...
Definition: EditPage.php:4379
incrementConflictStats()
Definition: EditPage.php:3762
const FOR_THIS_USER
Definition: Revision.php:55
bool $nosummary
If true, hide the summary field.
Definition: EditPage.php:350
getPreloadedContent( $preload, $params=[])
Get the contents to be preloaded into the box, either set by an earlier setPreloadText() or by loadin...
Definition: EditPage.php:1480
$editFormTextBottom
Definition: EditPage.php:423
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
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
spamPageWithContent( $match=false)
Show "your edit contains spam" page with your diff and text.
Definition: EditPage.php:4344
const AS_READ_ONLY_PAGE_ANON
Status: this anonymous user is not allowed to edit this page.
Definition: EditPage.php:83
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
bool $missingSummary
Definition: EditPage.php:281
bool $bot
Definition: EditPage.php:403
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1585
string $textbox2
Definition: EditPage.php:342
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
either a plain
Definition: hooks.txt:2043
bool $mTokenOk
Definition: EditPage.php:263
$editFormTextAfterContent
Definition: EditPage.php:424
showContentForm()
Subpage overridable method for printing the form for page content editing By default this simply outp...
Definition: EditPage.php:3383
bool $allowBlankSummary
Definition: EditPage.php:284
getPreviewText()
Get the rendered text for previewing.
Definition: EditPage.php:3880
bool $isConflict
Whether an edit conflict needs to be resolved.
Definition: EditPage.php:242
int $oldid
Revision ID the edit is based on, or 0 if it&#39;s the current revision.
Definition: EditPage.php:387
getContentObject( $def_content=null)
Definition: EditPage.php:1193
handleStatus(Status $status, $resultDetails)
Handle status, such as after attempt save.
Definition: EditPage.php:1620
string $summary
Definition: EditPage.php:345
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
setHeaders()
Definition: EditPage.php:2490
WikiPage $page
Definition: EditPage.php:224
per default it will return the text for text based content
static matchSpamRegexInternal( $text, $regexes)
Definition: EditPage.php:2480
Show an error when the wiki is locked/read-only and the user tries to do something that requires writ...
static isIP( $name)
Does the string match an anonymous IP address?
Definition: User.php:969
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
const AS_ARTICLE_WAS_DELETED
Status: article was deleted while editing and param wpRecreate == false or form was not posted...
Definition: EditPage.php:104
Handles formatting for the "templates used on this page" lists.
const AS_HOOK_ERROR
Status: Article update aborted by a hook function.
Definition: EditPage.php:63
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
showTextbox2()
Definition: EditPage.php:3423
bool $tooBig
Definition: EditPage.php:275
showHeaderCopyrightWarning()
Show the header copyright warning.
Definition: EditPage.php:3572
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
getPage()
Get the WikiPage object of this instance.
Definition: Article.php:230
globals txt Globals are evil The original MediaWiki code relied on globals for processing context far too often MediaWiki development since then has been a story of slowly moving context out of global variables and into objects Storing processing context in object member variables allows those objects to be reused in a much more flexible way Consider the elegance of
database rows
Definition: globals.txt:10
if(!isset( $args[0])) $lang
static getCopyrightWarning( $title, $format='plain', $langcode=null)
Get the copyright warning, by default returns wikitext.
Definition: EditPage.php:3627
static newFromTarget( $specificTarget, $vagueTarget=null, $fromMaster=false)
Given a target and the target&#39;s type, get an existing Block object if possible.
Definition: Block.php:1397
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing &#39;/&#39;...
Definition: Html.php:252
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:210
showTosSummary()
Give a chance for site and per-namespace customizations of terms of service summary link that might e...
Definition: EditPage.php:3588
Special handling for category description pages, showing pages, subcategories and file that belong to...
An IContextSource implementation which will inherit context from another source but allow individual ...
static warningBox( $html)
Return a warning box.
Definition: Html.php:725
The edit page/HTML interface (split from Article) The actual database and text munging is still in Ar...
Definition: EditPage.php:44
Title $mTitle
Definition: EditPage.php:230
const AS_SUMMARY_NEEDED
Status: no edit summary given and the user has forceeditsummary set and the user is not editing in hi...
Definition: EditPage.php:126
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
const AS_HOOK_ERROR_EXPECTED
Status: A hook function returned an error.
Definition: EditPage.php:68
getLocalURL( $query='', $query2=false)
Get a URL with no fragment or server name (relative URL) from a Title object.
Definition: Title.php:1979
static accesskey( $name)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition: Linker.php:2025
static loadFromTimestamp( $db, $title, $timestamp)
Load the revision for the given title with the given timestamp.
Definition: Revision.php:295
getSummaryInputAttributes(array $inputAttrs=null)
Helper function for summary input functions, which returns the necessary attributes for the input...
Definition: EditPage.php:3243
getEditButtons(&$tabindex)
Returns an array of html code of the following buttons: save, diff and preview.
Definition: EditPage.php:4256
static newFromUserAndLang(User $user, Language $lang)
Get a ParserOptions object from a given user and language.
also included in $newHeader if any indicating whether we should show just the diff
Definition: hooks.txt:1266
string $editintro
Definition: EditPage.php:397
Class for viewing MediaWiki article and history.
Definition: Article.php:37
null for the local wiki Added in
Definition: hooks.txt:1585
static getSkinNames()
Fetch the set of available skins.
Definition: Skin.php:57
bool $allowBlankArticle
Definition: EditPage.php:290
toEditText( $content)
Gets an editable textual representation of $content.
Definition: EditPage.php:2712
IContextSource $context
Definition: EditPage.php:448
$value
Article $mArticle
Definition: EditPage.php:222
null string $contentFormat
Definition: EditPage.php:409
const AS_BLOCKED_PAGE_FOR_USER
Status: User is blocked from editing this page.
Definition: EditPage.php:73
getWikiText( $shortContext=false, $longContext=false, $lang=null)
Get the error list as a wikitext formatted list.
Definition: Status.php:175
static linkButton( $contents, array $attrs, array $modifiers=[])
Returns an HTML link element in a string styled as a button (when $wgUseMediaWikiUIEverywhere is enab...
Definition: Html.php:166
bool $blankArticle
Definition: EditPage.php:287
buildTextboxAttribs( $name, array $customAttribs, User $user)
Definition: EditPage.php:4514
Helper for displaying edit conflicts in text content models to users.
isGood()
Returns whether the operation completed and didn&#39;t have any error or warnings.
const AS_NO_CREATE_PERMISSION
Status: user tried to create this page, but is not allowed to do that ( Title->userCan(&#39;create&#39;) == f...
Definition: EditPage.php:110
The First
Definition: primes.txt:1
getEditConflictMainTextBox(array $customAttribs=[])
HTML to build the textbox1 on edit conflicts.
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
bool $missingComment
Definition: EditPage.php:278
const EDIT_MINOR
Definition: Defines.php:154
getEditPermissionErrors( $rigor='secure')
Definition: EditPage.php:726
const COMMENT_CHARACTER_LIMIT
Maximum length of a comment in UTF-8 characters.
const POST_EDIT_COOKIE_DURATION
Duration of PostEdit cookie, in seconds.
Definition: EditPage.php:216
const EDIT_UPDATE
Definition: Defines.php:153
static userWasLastToEdit( $db, $pageId, $userId, $since)
Check if no edits were made by other users since the time a user started editing the page...
Definition: Revision.php:1306
this hook is for auditing only $response
Definition: hooks.txt:780
showFormBeforeText()
Definition: EditPage.php:3346
null means default & $customAttribs
Definition: hooks.txt:1982
internalAttemptSave(&$result, $bot=false)
Attempt submission (no UI)
Definition: EditPage.php:1866
bool stdClass $lastDelete
Definition: EditPage.php:260
const AS_UNICODE_NOT_SUPPORTED
Status: edit rejected because browser doesn&#39;t support Unicode.
Definition: EditPage.php:190
target page
addPageProtectionWarningHeaders()
Definition: EditPage.php:4458
static getLocalizedName( $name, Language $lang=null)
Returns the localized name for a given content model.
getCheckboxesWidget(&$tabindex, $checked)
Returns an array of checkboxes for the edit form, including &#39;minor&#39; and &#39;watch&#39; checkboxes and any ot...
Definition: EditPage.php:4187
const CONTENT_MODEL_JSON
Definition: Defines.php:239
edit()
This is the function that gets called for "action=edit".
Definition: EditPage.php:587
getContextTitle()
Get the context title object.
Definition: EditPage.php:536
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition: hooks.txt:1799
mergeChangesIntoContent(&$editContent)
Attempts to do 3-way merge of edit content with a base revision and current content, in case of edit conflict, in whichever way appropriate for the content type.
Definition: EditPage.php:2392
const DB_MASTER
Definition: defines.php:26
displayPreviewArea( $previewOutput, $isOnTop=false)
Definition: EditPage.php:3441
addEditNotices()
Definition: EditPage.php:4399
static formatHiddenCategories( $hiddencats)
Returns HTML for the "hidden categories on this page" list.
Definition: Linker.php:1942
isRedirect()
Tests if the article content represents a redirect.
Definition: WikiPage.php:630
null Title $mContextTitle
Definition: EditPage.php:233
static textarea( $name, $value='', array $attribs=[])
Convenience function to produce a <textarea> element.
Definition: Html.php:813
getEditFormHtmlBeforeContent()
Content to go in the edit form before textbox1.
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition: hooks.txt:2217
int $editRevId
Revision ID of the latest revision of the page when editing was initiated on the client.
Definition: EditPage.php:369
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
const AS_CONTENT_TOO_BIG
Status: Content too big (> $wgMaxArticleSize)
Definition: EditPage.php:78
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:48
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 modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:780
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 $out
Definition: hooks.txt:780
getContext()
Gets the context this Article is executed in.
Definition: Article.php:2233
addExplainConflictHeader(OutputPage $out)
Definition: EditPage.php:4501
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e.g.
attemptSave(&$resultDetails=false)
Attempt submission.
Definition: EditPage.php:1586
showIntro()
Show all applicable editing introductions.
Definition: EditPage.php:2555
setWikiPage(WikiPage $wikiPage)
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1982
getArticle()
Definition: EditPage.php:499
$wgSpamRegex
Edits matching these regular expressions in body text will be recognised as spam and rejected automat...
bool $watchthis
Definition: EditPage.php:331
$previewTextAfterContent
Definition: EditPage.php:425
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:1263
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
const DELETED_COMMENT
Definition: LogPage.php:35
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add a callable update.
getParentRevId()
Get the edit&#39;s parent revision ID.
Definition: EditPage.php:1403
addLongPageWarningHeader()
Definition: EditPage.php:4428
getTemplates()
Definition: EditPage.php:4090
bool $save
Definition: EditPage.php:319
wfReadOnly()
Check whether the wiki is in read-only mode.
$wgLang
Definition: Setup.php:875
static newMigration()
Static constructor.
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
setContextTitle( $title)
Set the context Title object.
Definition: EditPage.php:524
static openElement( $element, $attribs=null)
This opens an XML element.
Definition: Xml.php:108
TextConflictHelper null $editConflictHelper
Definition: EditPage.php:470
toEditContent( $text)
Turns the given text into a Content object by unserializing it.
Definition: EditPage.php:2740
static getForModelID( $modelId)
Returns the ContentHandler singleton for the given model ID.
See &</td >< td > &Fill in a specific reason below(for example, citing particular pages that were vandalized).</td >< td >
const AS_SPAM_ERROR
Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex.
Definition: EditPage.php:146
const EDIT_FORCE_BOT
Definition: Defines.php:156
An error page which can definitely be safely rendered using the OutputPage.
static titleAttrib( $name, $options=null, array $msgParams=[])
Given the id of an interface element, constructs the appropriate title attribute from the system mess...
Definition: Linker.php:1977
static getPreviewLimitReport(ParserOutput $output=null)
Get the Limit report for page previews.
Definition: EditPage.php:3655
callable $editConflictHelperFactory
Factory function to create an edit conflict helper.
Definition: EditPage.php:465
getLastDelete()
Get the last log record of this page being deleted, if ever.
Definition: EditPage.php:3832
in this case you re responsible for computing and outputting the entire conflict i the difference between revisions and your text headers and sections and Diff & $tabindex
Definition: hooks.txt:1420
getActionURL(Title $title)
Returns the URL to use in the form&#39;s action attribute.
Definition: EditPage.php:3796
static doWatchOrUnwatch( $watch, Title $title, User $user)
Watch or unwatch a page.
Definition: WatchAction.php:89
$editFormTextAfterTools
Definition: EditPage.php:422
const AS_CANNOT_USE_CUSTOM_MODEL
Status: when changing the content model is disallowed due to $wgContentHandlerUseDB being false...
Definition: EditPage.php:185
wfFindFile( $title, $options=[])
Find a file.
$editFormTextAfterWarn
Definition: EditPage.php:421
$res
Definition: database.txt:21
bool $recreate
Definition: EditPage.php:334
setPreloadedContent(Content $content)
Use this method before edit() to preload some content into the edit box.
Definition: EditPage.php:1465
static getContentText(Content $content=null)
Convenience function for getting flat text from a Content object.
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
const AS_SUCCESS_UPDATE
Status: Article successfully updated.
Definition: EditPage.php:53
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing etc
Definition: hooks.txt:91
const AS_READ_ONLY_PAGE
Status: wiki is in readonly mode (wfReadOnly() == true)
Definition: EditPage.php:93
static extractSectionTitle( $text)
Extract the section title from current section text, if any.
Definition: EditPage.php:3058
bool $isOldRev
Whether an old revision is edited.
Definition: EditPage.php:453
showHeader()
Definition: EditPage.php:3068
const EDIT_AUTOSUMMARY
Definition: Defines.php:158
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
const UNICODE_CHECK
Used for Unicode support checks.
Definition: EditPage.php:48
const AS_NO_CHANGE_CONTENT_MODEL
Status: user tried to modify the content model, but is not allowed to do that ( User::isAllowed(&#39;edit...
Definition: EditPage.php:162
addContentModelChangeLogEntry(User $user, $oldModel, $newModel, $reason)
Definition: EditPage.php:2347
getTitle()
Get the title object of the article.
Definition: Article.php:220
const IGNORE_USER_RIGHTS
Definition: User.php:80
$params
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1982
static tags( $element, $attribs, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:130
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:316
string $edittime
Timestamp of the latest revision of the page when editing was initiated on the client.
Definition: EditPage.php:356
showSummaryInput( $isSubjectPreview, $summary="")
Definition: EditPage.php:3299
showEditForm( $formCallback=null)
Send the edit form and related headers to OutputPage.
Definition: EditPage.php:2763
static loadFromTitle( $db, $title, $id=0)
Load either the current, or a specified, revision that&#39;s attached to a given page.
Definition: Revision.php:277
initialiseForm()
Initialise form fields in the object Called on the first invocation, e.g.
Definition: EditPage.php:1154
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
Definition: hooks.txt:1982
wasDeletedSinceLastEdit()
Check if a page was deleted while the user was editing it, before submit.
Definition: EditPage.php:3807
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 save
Definition: deferred.txt:4
isSectionEditSupported()
Returns whether section editing is supported for the current page.
Definition: EditPage.php:915
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:780
getEditFormHtmlAfterContent()
Content to go in the edit form after textbox1.
bool $firsttime
True the first time the edit form is rendered, false after re-rendering with diff, save prompts, etc.
Definition: EditPage.php:257
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
showFormAfterText()
Definition: EditPage.php:3355
showDiff()
Get a diff between the current contents of the edit box and the version of the page we&#39;re editing fro...
Definition: EditPage.php:3510
bool $isNew
New page or new section.
Definition: EditPage.php:245
$wgRightsText
If either $wgRightsUrl or $wgRightsPage is specified then this variable gives the text for the link...
previewOnOpen()
Should we show a preview when the edit form is first shown?
Definition: EditPage.php:853
const EDITFORM_ID
HTML id and name for the beginning of the edit form.
Definition: EditPage.php:195
const NS_FILE
Definition: Defines.php:70
getCopywarn()
Get the copyright warning.
Definition: EditPage.php:3615
bool $allowSelfRedirect
Definition: EditPage.php:296
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:82
const TYPE_AUTO
Definition: Block.php:99
const AS_SUCCESS_NEW_ARTICLE
Status: Article successfully created.
Definition: EditPage.php:58
Show an error when the user tries to do something whilst blocked.
safeUnicodeOutput( $text)
Filter an output field through a Unicode armoring process if it is going to an old browser with known...
Definition: EditPage.php:4392
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1766
isOK()
Returns whether the operation completed.
const AS_IMAGE_REDIRECT_LOGGED
Status: logged in user is not allowed to upload (User::isAllowed(&#39;upload&#39;) == false) ...
Definition: EditPage.php:156
const RAW
Definition: Revision.php:56
static getForTitle(Title $title)
Returns the appropriate ContentHandler singleton for the given title.
getPreviewParserOptions()
Get parser options for a preview.
Definition: EditPage.php:4043
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:780
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
getCancelLink()
Definition: EditPage.php:3769
bool int $contentLength
Definition: EditPage.php:438
const NS_MEDIAWIKI
Definition: Defines.php:72
showTextbox1( $customAttribs=null, $textoverride=null)
Method to output wpTextbox1 The $textoverride method can be used by subclasses overriding showContent...
Definition: EditPage.php:3395
incrementEditFailureStats( $failureType)
Definition: EditPage.php:4034
const AS_END
Status: WikiPage::doEdit() was unsuccessful.
Definition: EditPage.php:141
getSummaryPreview( $isSubjectPreview, $summary="")
Definition: EditPage.php:3325
makeTemplatesOnThisPageList(array $templates)
Wrapper around TemplatesOnThisPageFormatter to make a "templates on this page" list.
Definition: EditPage.php:3034
showPreview( $text)
Append preview output to OutputPage.
Definition: EditPage.php:3489
string $textbox1
Page content input field.
Definition: EditPage.php:339
CONTENT_MODEL_JAVASCRIPT
Allow users to upload files.
const DELETED_USER
Definition: LogPage.php:36
const DELETED_TEXT
Definition: Revision.php:46
importFormData(&$request)
This function collects the form data and uses it to populate various member variables.
Definition: EditPage.php:925
noSuchSectionPage()
Creates a basic error page which informs the user that they have attempted to edit a nonexistent sect...
Definition: EditPage.php:4325
$wgSummarySpamRegex
Same as the above except for edit summaries.
displayViewSourcePage(Content $content, $errorMessage='')
Display a read-only View Source page.
Definition: EditPage.php:800
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:589
static getEditToolbar( $title=null)
Allow extensions to provide a toolbar.
Definition: EditPage.php:4113
ParserOutput $mParserOutput
Definition: EditPage.php:305
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
bool $mShowSummaryField
Definition: EditPage.php:314
string $sectiontitle
Definition: EditPage.php:375
string null $unicodeCheck
What the user submitted in the &#39;wpUnicodeCheck&#39; field.
Definition: EditPage.php:458
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 $template
Definition: hooks.txt:780
bool $minoredit
Definition: EditPage.php:328
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:780
bool $enableApiEditOverride
Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing.
Definition: EditPage.php:443
static getCanonicalName( $index)
Returns the canonical (English) name for a given index.
static closeElement( $element)
Shortcut to close an XML element.
Definition: Xml.php:117
int $parentRevId
Revision ID the edit is based on, adjusted when an edit conflict is resolved.
Definition: EditPage.php:394
doPreviewParse(Content $content)
Parse the page for a preview.
Definition: EditPage.php:4066
static matchSpamRegex( $text)
Check given input text against $wgSpamRegex, and return the text of the first match.
Definition: EditPage.php:2455
string $action
Definition: EditPage.php:236
newTextConflictHelper( $submitButtonLabel)
Definition: EditPage.php:4583
bool $deletedSinceEdit
Definition: EditPage.php:248
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
static getStore()
showCustomIntro()
Attempt to show a custom editing introduction, if supplied.
Definition: EditPage.php:2678
static matchSummarySpamRegex( $text)
Check given input text against $wgSummarySpamRegex, and return the text of the first match...
Definition: EditPage.php:2469
importContentFormData(&$request)
Subpage overridable method for extracting the page content data from the posted form to be placed in ...
Definition: EditPage.php:1145
const EDIT_NEW
Definition: Defines.php:152
Revision bool null $mBaseRevision
A revision object corresponding to $this->editRevId.
Definition: EditPage.php:311
newSectionSummary(&$sectionanchor=null)
Return the summary to be used for a new section.
Definition: EditPage.php:1818
const AS_RATE_LIMITED
Status: rate limiter for action &#39;edit&#39; was tripped.
Definition: EditPage.php:98
getBaseRevision()
Returns the revision that was current at the time editing was initiated on the client, even if the edit was based on an old revision.
Definition: EditPage.php:2438
static hasDifferencesOutsideMainSlot(Revision $a, Revision $b)
Helper method for checking whether two revisions have differences that go beyond the main slot...
Definition: WikiPage.php:1526
addNewLineAtEnd( $wikitext)
Definition: EditPage.php:4525
Variant of the Message class.
Definition: RawMessage.php:34
runPostMergeFilters(Content $content, Status $status, User $user)
Run hooks that can filter edits just before they get saved.
Definition: EditPage.php:1751
const AS_MAX_ARTICLE_SIZE_EXCEEDED
Status: article is too big (> $wgMaxArticleSize), after merging in the new section.
Definition: EditPage.php:136
static newFromUser( $user)
Get a ParserOptions object from a given user.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
incrementResolvedConflicts()
Log when a page was successfully saved after the edit conflict view.
Definition: EditPage.php:1603
getCurrentContent()
Get the current content of the page.
Definition: EditPage.php:1419
updateWatchlist()
Register the change of watch status.
Definition: EditPage.php:2364
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:797
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
string $hookError
Definition: EditPage.php:302
showEditTools()
Inserts optional text shown below edit and upload forms.
Definition: EditPage.php:3603
bool $preview
Definition: EditPage.php:322
const AS_IMAGE_REDIRECT_ANON
Status: anonymous user is not allowed to upload (User::isAllowed(&#39;upload&#39;) == false) ...
Definition: EditPage.php:151
getCheckboxesDefinition( $checked)
Return an array of checkbox definitions.
Definition: EditPage.php:4142
showStandardInputs(&$tabindex=2)
Definition: EditPage.php:3701
preSaveTransform(Title $title, User $user, ParserOptions $parserOptions)
Returns a Content object with pre-save transformations applied (or this object if no transformations ...
const AS_TEXTBOX_EMPTY
Status: user tried to create a new section without content.
Definition: EditPage.php:131
Show an error when a user tries to do something they do not have the necessary permissions for...
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:41
setPostEditCookie( $statusValue)
Sets post-edit cookie indicating the user just saved a particular revision.
Definition: EditPage.php:1565
static getRestrictionLevels( $index, User $user=null)
Determine which restriction levels it makes sense to use in a namespace, optionally filtered by a use...
getRedirectTarget()
If this page is a redirect, get its target.
Definition: WikiPage.php:995
bool $mTriedSave
Definition: EditPage.php:269
const CONTENT_MODEL_CSS
Definition: Defines.php:237
$mPreloadContent
Definition: EditPage.php:426
getContext()
Definition: EditPage.php:507
showConflict()
Show an edit conflict.
Definition: EditPage.php:3751
addTalkPageText()
Definition: EditPage.php:4419
bool $hasPresetSummary
Has a summary been preset using GET parameter &summary= ?
Definition: EditPage.php:308
getEditConflictHelper()
Definition: EditPage.php:4568
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
const POST_EDIT_COOKIE_KEY_PREFIX
Prefix of key for cookie used to pass post-edit state.
Definition: EditPage.php:201
bool $diff
Definition: EditPage.php:325
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
const AS_BLANK_ARTICLE
Status: user tried to create a blank page and wpIgnoreBlankArticle == false.
Definition: EditPage.php:115
addHTML( $text)
Append $text to the body HTML.
setEditConflictHelperFactory(callable $factory)
Set a factory function to create an EditConflictHelper.
Definition: EditPage.php:4560
string $starttime
Timestamp from the first time the edit form was rendered.
Definition: EditPage.php:380
string $formtype
Definition: EditPage.php:251
string $section
Definition: EditPage.php:372
getSummaryInputWidget( $summary="", $labelText=null, $inputAttrs=null)
Builds a standard summary input with a label.
Definition: EditPage.php:3266
const DB_REPLICA
Definition: defines.php:25
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 the name of the old file & $article
Definition: hooks.txt:1473
static makeInternalOrExternalUrl( $name)
If url string starts with http, consider as external URL, else internal.
Definition: Skin.php:1192
formatStatusErrors(Status $status)
Wrap status errors in an errorbox for increased visibility.
Definition: EditPage.php:1798
static canAddTagsAccompanyingChange(array $tags, User $user=null)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
Definition: ChangeTags.php:481
getTitle()
Definition: EditPage.php:515
bool $mTokenOkExceptSuffix
Definition: EditPage.php:266
if(! $wgRequest->checkUrlExtension()) if(isset( $_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !='') $wgTitle
Definition: api.php:57
static checkLabel( $label, $name, $id, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox with a label.
Definition: Xml.php:419
wfArrayDiff2( $a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
const AS_CONFLICT_DETECTED
Status: (non-resolvable) edit conflict.
Definition: EditPage.php:120
isSupportedContentModel( $modelId)
Returns if the given content model is editable.
Definition: EditPage.php:553
setApiEditOverride( $enableOverride)
Allow editing of content that supports API direct editing, but not general direct editing...
Definition: EditPage.php:564
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:587
$suppressIntro
Definition: EditPage.php:432
getOriginalContent(User $user)
Get the content of the wanted revision, without section extraction.
Definition: EditPage.php:1378
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
Definition: Revision.php:118
bool $selfRedirect
Definition: EditPage.php:293
bool $incompleteForm
Definition: EditPage.php:272
bool $edit
Definition: EditPage.php:435
const AS_READ_ONLY_PAGE_LOGGED
Status: this logged in user is not allowed to edit this page.
Definition: EditPage.php:88
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
fatal( $message)
Add an error and set OK to false, indicating that the operation as a whole was fatal.
$content
Definition: pageupdater.txt:72
const AS_PARSE_ERROR
Status: can&#39;t parse content.
Definition: EditPage.php:179
const NS_USER_TALK
Definition: Defines.php:67
getSubmitButtonLabel()
Get the message key of the label for the button to save the page.
Definition: EditPage.php:4232
showTextbox( $text, $name, $customAttribs=[])
Definition: EditPage.php:3427
const AS_SELF_REDIRECT
Status: user tried to create self-redirect (redirect to the same article) and wpIgnoreSelfRedirect ==...
Definition: EditPage.php:168
setContentModel( $model)
Set a proposed content model for the page for permissions checking.
Definition: Title.php:1075
$editFormTextBeforeContent
Definition: EditPage.php:420
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:2633
null array $changeTags
Definition: EditPage.php:412
setTextboxes( $yourtext, $storedversion)
isWrongCaseUserConfigPage()
Checks whether the user entered a skin name in uppercase, e.g.
Definition: EditPage.php:894
Show an error when the user hits a rate limit.
static commentBlock( $comment, $title=null, $local=false, $wikiId=null, $useParentheses=true)
Wrap a comment in standard punctuation and formatting if it&#39;s non-empty, otherwise return empty strin...
Definition: Linker.php:1492
string $contentModel
Definition: EditPage.php:406
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
Exception representing a failure to serialize or unserialize a content object.
tokenOk(&$request)
Make sure the form isn&#39;t faking a user&#39;s credentials.
Definition: EditPage.php:1543
string $editFormPageTop
Before even the preview.
Definition: EditPage.php:418
const AS_CHANGE_TAG_ERROR
Status: an error relating to change tagging.
Definition: EditPage.php:174
guessSectionName( $text)
Turns section name wikitext into anchors for use in HTTP redirects.
Definition: EditPage.php:4539
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
serialize( $format=null)
Convenience method for serializing this Content object.
__construct(Article $article)
Definition: EditPage.php:475
$editFormTextTop
Definition: EditPage.php:419
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.
$matches
null $scrolltop
Definition: EditPage.php:400
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:319