MediaWiki  master
EditPage.php
Go to the documentation of this file.
1 <?php
24 
40 class EditPage {
44  const AS_SUCCESS_UPDATE = 200;
45 
50 
54  const AS_HOOK_ERROR = 210;
55 
60 
65 
69  const AS_CONTENT_TOO_BIG = 216;
70 
75 
80 
84  const AS_READ_ONLY_PAGE = 220;
85 
89  const AS_RATE_LIMITED = 221;
90 
96 
102 
106  const AS_BLANK_ARTICLE = 224;
107 
111  const AS_CONFLICT_DETECTED = 225;
112 
117  const AS_SUMMARY_NEEDED = 226;
118 
122  const AS_TEXTBOX_EMPTY = 228;
123 
128 
132  const AS_END = 231;
133 
137  const AS_SPAM_ERROR = 232;
138 
143 
148 
154 
159  const AS_SELF_REDIRECT = 236;
160 
165  const AS_CHANGE_TAG_ERROR = 237;
166 
170  const AS_PARSE_ERROR = 240;
171 
177 
181  const EDITFORM_ID = 'editform';
182 
187  const POST_EDIT_COOKIE_KEY_PREFIX = 'PostEditRevision';
188 
203 
205  public $mArticle;
207  private $page;
208 
210  public $mTitle;
211 
213  private $mContextTitle = null;
214 
216  public $action = 'submit';
217 
219  public $isConflict = false;
220 
222  public $isCssJsSubpage = false;
223 
225  public $isCssSubpage = false;
226 
228  public $isJsSubpage = false;
229 
231  public $isWrongCaseCssJsPage = false;
232 
234  public $isNew = false;
235 
238 
240  public $formtype;
241 
243  public $firsttime;
244 
246  public $lastDelete;
247 
249  public $mTokenOk = false;
250 
252  public $mTokenOkExceptSuffix = false;
253 
255  public $mTriedSave = false;
256 
258  public $incompleteForm = false;
259 
261  public $tooBig = false;
262 
264  public $missingComment = false;
265 
267  public $missingSummary = false;
268 
270  public $allowBlankSummary = false;
271 
273  protected $blankArticle = false;
274 
276  protected $allowBlankArticle = false;
277 
279  protected $selfRedirect = false;
280 
282  protected $allowSelfRedirect = false;
283 
285  public $autoSumm = '';
286 
288  public $hookError = '';
289 
292 
294  public $hasPresetSummary = false;
295 
297  public $mBaseRevision = false;
298 
300  public $mShowSummaryField = true;
301 
302  # Form values
303 
305  public $save = false;
306 
308  public $preview = false;
309 
311  public $diff = false;
312 
314  public $minoredit = false;
315 
317  public $watchthis = false;
318 
320  public $recreate = false;
321 
323  public $textbox1 = '';
324 
326  public $textbox2 = '';
327 
329  public $summary = '';
330 
332  public $nosummary = false;
333 
335  public $edittime = '';
336 
338  private $editRevId = null;
339 
341  public $section = '';
342 
344  public $sectiontitle = '';
345 
347  public $starttime = '';
348 
350  public $oldid = 0;
351 
353  public $parentRevId = 0;
354 
356  public $editintro = '';
357 
359  public $scrolltop = null;
360 
362  public $bot = true;
363 
365  public $contentModel = null;
366 
368  public $contentFormat = null;
369 
371  private $changeTags = null;
372 
373  # Placeholders for text injection by hooks (must be HTML)
374  # extensions should take care to _append_ to the present value
375 
377  public $editFormPageTop = '';
378  public $editFormTextTop = '';
382  public $editFormTextBottom = '';
385  public $mPreloadContent = null;
386 
387  /* $didSave should be set to true whenever an article was successfully altered. */
388  public $didSave = false;
389  public $undidRev = 0;
390 
391  public $suppressIntro = false;
392 
394  protected $edit;
395 
397  protected $contentLength = false;
398 
402  private $enableApiEditOverride = false;
403 
407  public function __construct( Article $article ) {
408  $this->mArticle = $article;
409  $this->page = $article->getPage(); // model object
410  $this->mTitle = $article->getTitle();
411 
412  $this->contentModel = $this->mTitle->getContentModel();
413 
414  $handler = ContentHandler::getForModelID( $this->contentModel );
415  $this->contentFormat = $handler->getDefaultFormat();
416  }
417 
421  public function getArticle() {
422  return $this->mArticle;
423  }
424 
429  public function getTitle() {
430  return $this->mTitle;
431  }
432 
438  public function setContextTitle( $title ) {
439  $this->mContextTitle = $title;
440  }
441 
449  public function getContextTitle() {
450  if ( is_null( $this->mContextTitle ) ) {
452  return $wgTitle;
453  } else {
454  return $this->mContextTitle;
455  }
456  }
457 
465  public function isSupportedContentModel( $modelId ) {
466  return $this->enableApiEditOverride === true ||
467  ContentHandler::getForModelID( $modelId )->supportsDirectEditing();
468  }
469 
476  public function setApiEditOverride( $enableOverride ) {
477  $this->enableApiEditOverride = $enableOverride;
478  }
479 
480  function submit() {
481  $this->edit();
482  }
483 
495  function edit() {
497  // Allow extensions to modify/prevent this form or submission
498  if ( !Hooks::run( 'AlternateEdit', [ $this ] ) ) {
499  return;
500  }
501 
502  wfDebug( __METHOD__ . ": enter\n" );
503 
504  // If they used redlink=1 and the page exists, redirect to the main article
505  if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
506  $wgOut->redirect( $this->mTitle->getFullURL() );
507  return;
508  }
509 
510  $this->importFormData( $wgRequest );
511  $this->firsttime = false;
512 
513  if ( wfReadOnly() && $this->save ) {
514  // Force preview
515  $this->save = false;
516  $this->preview = true;
517  }
518 
519  if ( $this->save ) {
520  $this->formtype = 'save';
521  } elseif ( $this->preview ) {
522  $this->formtype = 'preview';
523  } elseif ( $this->diff ) {
524  $this->formtype = 'diff';
525  } else { # First time through
526  $this->firsttime = true;
527  if ( $this->previewOnOpen() ) {
528  $this->formtype = 'preview';
529  } else {
530  $this->formtype = 'initial';
531  }
532  }
533 
534  $permErrors = $this->getEditPermissionErrors( $this->save ? 'secure' : 'full' );
535  if ( $permErrors ) {
536  wfDebug( __METHOD__ . ": User can't edit\n" );
537  // Auto-block user's IP if the account was "hard" blocked
538  if ( !wfReadOnly() ) {
539  $user = $wgUser;
540  DeferredUpdates::addCallableUpdate( function () use ( $user ) {
541  $user->spreadAnyEditBlock();
542  } );
543  }
544  $this->displayPermissionsError( $permErrors );
545 
546  return;
547  }
548 
549  $revision = $this->mArticle->getRevisionFetched();
550  // Disallow editing revisions with content models different from the current one
551  if ( $revision && $revision->getContentModel() !== $this->contentModel ) {
552  $this->displayViewSourcePage(
553  $this->getContentObject(),
554  wfMessage(
555  'contentmodelediterror',
556  $revision->getContentModel(),
558  )->plain()
559  );
560  return;
561  }
562 
563  $this->isConflict = false;
564  // css / js subpages of user pages get a special treatment
565  $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
566  $this->isCssSubpage = $this->mTitle->isCssSubpage();
567  $this->isJsSubpage = $this->mTitle->isJsSubpage();
568  // @todo FIXME: Silly assignment.
569  $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
570 
571  # Show applicable editing introductions
572  if ( $this->formtype == 'initial' || $this->firsttime ) {
573  $this->showIntro();
574  }
575 
576  # Attempt submission here. This will check for edit conflicts,
577  # and redundantly check for locked database, blocked IPs, etc.
578  # that edit() already checked just in case someone tries to sneak
579  # in the back door with a hand-edited submission URL.
580 
581  if ( 'save' == $this->formtype ) {
582  $resultDetails = null;
583  $status = $this->attemptSave( $resultDetails );
584  if ( !$this->handleStatus( $status, $resultDetails ) ) {
585  return;
586  }
587  }
588 
589  # First time through: get contents, set time for conflict
590  # checking, etc.
591  if ( 'initial' == $this->formtype || $this->firsttime ) {
592  if ( $this->initialiseForm() === false ) {
593  $this->noSuchSectionPage();
594  return;
595  }
596 
597  if ( !$this->mTitle->getArticleID() ) {
598  Hooks::run( 'EditFormPreloadText', [ &$this->textbox1, &$this->mTitle ] );
599  } else {
600  Hooks::run( 'EditFormInitialText', [ $this ] );
601  }
602 
603  }
604 
605  $this->showEditForm();
606  }
607 
612  protected function getEditPermissionErrors( $rigor = 'secure' ) {
613  global $wgUser;
614 
615  $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
616  # Can this title be created?
617  if ( !$this->mTitle->exists() ) {
618  $permErrors = array_merge(
619  $permErrors,
620  wfArrayDiff2(
621  $this->mTitle->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
622  $permErrors
623  )
624  );
625  }
626  # Ignore some permissions errors when a user is just previewing/viewing diffs
627  $remove = [];
628  foreach ( $permErrors as $error ) {
629  if ( ( $this->preview || $this->diff )
630  && ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' )
631  ) {
632  $remove[] = $error;
633  }
634  }
635  $permErrors = wfArrayDiff2( $permErrors, $remove );
636 
637  return $permErrors;
638  }
639 
653  protected function displayPermissionsError( array $permErrors ) {
655 
656  if ( $wgRequest->getBool( 'redlink' ) ) {
657  // The edit page was reached via a red link.
658  // Redirect to the article page and let them click the edit tab if
659  // they really want a permission error.
660  $wgOut->redirect( $this->mTitle->getFullURL() );
661  return;
662  }
663 
664  $content = $this->getContentObject();
665 
666  # Use the normal message if there's nothing to display
667  if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
668  $action = $this->mTitle->exists() ? 'edit' :
669  ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
670  throw new PermissionsError( $action, $permErrors );
671  }
672 
673  $this->displayViewSourcePage(
674  $content,
675  $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' )
676  );
677  }
678 
684  protected function displayViewSourcePage( Content $content, $errorMessage = '' ) {
685  global $wgOut;
686 
687  Hooks::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$wgOut ] );
688 
689  $wgOut->setRobotPolicy( 'noindex,nofollow' );
690  $wgOut->setPageTitle( wfMessage(
691  'viewsource-title',
692  $this->getContextTitle()->getPrefixedText()
693  ) );
694  $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
695  $wgOut->addHTML( $this->editFormPageTop );
696  $wgOut->addHTML( $this->editFormTextTop );
697 
698  if ( $errorMessage !== '' ) {
699  $wgOut->addWikiText( $errorMessage );
700  $wgOut->addHTML( "<hr />\n" );
701  }
702 
703  # If the user made changes, preserve them when showing the markup
704  # (This happens when a user is blocked during edit, for instance)
705  if ( !$this->firsttime ) {
706  $text = $this->textbox1;
707  $wgOut->addWikiMsg( 'viewyourtext' );
708  } else {
709  try {
710  $text = $this->toEditText( $content );
711  } catch ( MWException $e ) {
712  # Serialize using the default format if the content model is not supported
713  # (e.g. for an old revision with a different model)
714  $text = $content->serialize();
715  }
716  $wgOut->addWikiMsg( 'viewsourcetext' );
717  }
718 
719  $wgOut->addHTML( $this->editFormTextBeforeContent );
720  $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
721  $wgOut->addHTML( $this->editFormTextAfterContent );
722 
723  $wgOut->addHTML( Html::rawElement( 'div', [ 'class' => 'templatesUsed' ],
724  Linker::formatTemplates( $this->getTemplates() ) ) );
725 
726  $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
727 
728  $wgOut->addHTML( $this->editFormTextBottom );
729  if ( $this->mTitle->exists() ) {
730  $wgOut->returnToMain( null, $this->mTitle );
731  }
732  }
733 
739  protected function previewOnOpen() {
741  if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
742  // Explicit override from request
743  return true;
744  } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
745  // Explicit override from request
746  return false;
747  } elseif ( $this->section == 'new' ) {
748  // Nothing *to* preview for new sections
749  return false;
750  } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() )
751  && $wgUser->getOption( 'previewonfirst' )
752  ) {
753  // Standard preference behavior
754  return true;
755  } elseif ( !$this->mTitle->exists()
756  && isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
757  && $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]
758  ) {
759  // Categories are special
760  return true;
761  } else {
762  return false;
763  }
764  }
765 
772  protected function isWrongCaseCssJsPage() {
773  if ( $this->mTitle->isCssJsSubpage() ) {
774  $name = $this->mTitle->getSkinFromCssJsSubpage();
775  $skins = array_merge(
776  array_keys( Skin::getSkinNames() ),
777  [ 'common' ]
778  );
779  return !in_array( $name, $skins )
780  && in_array( strtolower( $name ), $skins );
781  } else {
782  return false;
783  }
784  }
785 
793  protected function isSectionEditSupported() {
794  $contentHandler = ContentHandler::getForTitle( $this->mTitle );
795  return $contentHandler->supportsSections();
796  }
797 
803  function importFormData( &$request ) {
805 
806  # Section edit can come from either the form or a link
807  $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
808 
809  if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
810  throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
811  }
812 
813  $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
814 
815  if ( $request->wasPosted() ) {
816  # These fields need to be checked for encoding.
817  # Also remove trailing whitespace, but don't remove _initial_
818  # whitespace from the text boxes. This may be significant formatting.
819  $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
820  if ( !$request->getCheck( 'wpTextbox2' ) ) {
821  // Skip this if wpTextbox2 has input, it indicates that we came
822  // from a conflict page with raw page text, not a custom form
823  // modified by subclasses
825  if ( $textbox1 !== null ) {
826  $this->textbox1 = $textbox1;
827  }
828  }
829 
830  # Truncate for whole multibyte characters
831  $this->summary = $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
832 
833  # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
834  # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
835  # section titles.
836  $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
837 
838  # Treat sectiontitle the same way as summary.
839  # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
840  # currently doing double duty as both edit summary and section title. Right now this
841  # is just to allow API edits to work around this limitation, but this should be
842  # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
843  $this->sectiontitle = $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
844  $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
845 
846  $this->edittime = $request->getVal( 'wpEdittime' );
847  $this->editRevId = $request->getIntOrNull( 'editRevId' );
848  $this->starttime = $request->getVal( 'wpStarttime' );
849 
850  $undidRev = $request->getInt( 'wpUndidRevision' );
851  if ( $undidRev ) {
852  $this->undidRev = $undidRev;
853  }
854 
855  $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
856 
857  if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
858  // wpTextbox1 field is missing, possibly due to being "too big"
859  // according to some filter rules such as Suhosin's setting for
860  // suhosin.request.max_value_length (d'oh)
861  $this->incompleteForm = true;
862  } else {
863  // If we receive the last parameter of the request, we can fairly
864  // claim the POST request has not been truncated.
865 
866  // TODO: softened the check for cutover. Once we determine
867  // that it is safe, we should complete the transition by
868  // removing the "edittime" clause.
869  $this->incompleteForm = ( !$request->getVal( 'wpUltimateParam' )
870  && is_null( $this->edittime ) );
871  }
872  if ( $this->incompleteForm ) {
873  # If the form is incomplete, force to preview.
874  wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
875  wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
876  $this->preview = true;
877  } else {
878  $this->preview = $request->getCheck( 'wpPreview' );
879  $this->diff = $request->getCheck( 'wpDiff' );
880 
881  // Remember whether a save was requested, so we can indicate
882  // if we forced preview due to session failure.
883  $this->mTriedSave = !$this->preview;
884 
885  if ( $this->tokenOk( $request ) ) {
886  # Some browsers will not report any submit button
887  # if the user hits enter in the comment box.
888  # The unmarked state will be assumed to be a save,
889  # if the form seems otherwise complete.
890  wfDebug( __METHOD__ . ": Passed token check.\n" );
891  } elseif ( $this->diff ) {
892  # Failed token check, but only requested "Show Changes".
893  wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
894  } else {
895  # Page might be a hack attempt posted from
896  # an external site. Preview instead of saving.
897  wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
898  $this->preview = true;
899  }
900  }
901  $this->save = !$this->preview && !$this->diff;
902  if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
903  $this->edittime = null;
904  }
905 
906  if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
907  $this->starttime = null;
908  }
909 
910  $this->recreate = $request->getCheck( 'wpRecreate' );
911 
912  $this->minoredit = $request->getCheck( 'wpMinoredit' );
913  $this->watchthis = $request->getCheck( 'wpWatchthis' );
914 
915  # Don't force edit summaries when a user is editing their own user or talk page
916  if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
917  && $this->mTitle->getText() == $wgUser->getName()
918  ) {
919  $this->allowBlankSummary = true;
920  } else {
921  $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
922  || !$wgUser->getOption( 'forceeditsummary' );
923  }
924 
925  $this->autoSumm = $request->getText( 'wpAutoSummary' );
926 
927  $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
928  $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
929 
930  $changeTags = $request->getVal( 'wpChangeTags' );
931  if ( is_null( $changeTags ) || $changeTags === '' ) {
932  $this->changeTags = [];
933  } else {
934  $this->changeTags = array_filter( array_map( 'trim', explode( ',',
935  $changeTags ) ) );
936  }
937  } else {
938  # Not a posted form? Start with nothing.
939  wfDebug( __METHOD__ . ": Not a posted form.\n" );
940  $this->textbox1 = '';
941  $this->summary = '';
942  $this->sectiontitle = '';
943  $this->edittime = '';
944  $this->editRevId = null;
945  $this->starttime = wfTimestampNow();
946  $this->edit = false;
947  $this->preview = false;
948  $this->save = false;
949  $this->diff = false;
950  $this->minoredit = false;
951  // Watch may be overridden by request parameters
952  $this->watchthis = $request->getBool( 'watchthis', false );
953  $this->recreate = false;
954 
955  // When creating a new section, we can preload a section title by passing it as the
956  // preloadtitle parameter in the URL (Bug 13100)
957  if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
958  $this->sectiontitle = $request->getVal( 'preloadtitle' );
959  // Once wpSummary isn't being use for setting section titles, we should delete this.
960  $this->summary = $request->getVal( 'preloadtitle' );
961  } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
962  $this->summary = $request->getText( 'summary' );
963  if ( $this->summary !== '' ) {
964  $this->hasPresetSummary = true;
965  }
966  }
967 
968  if ( $request->getVal( 'minor' ) ) {
969  $this->minoredit = true;
970  }
971  }
972 
973  $this->oldid = $request->getInt( 'oldid' );
974  $this->parentRevId = $request->getInt( 'parentRevId' );
975 
976  $this->bot = $request->getBool( 'bot', true );
977  $this->nosummary = $request->getBool( 'nosummary' );
978 
979  // May be overridden by revision.
980  $this->contentModel = $request->getText( 'model', $this->contentModel );
981  // May be overridden by revision.
982  $this->contentFormat = $request->getText( 'format', $this->contentFormat );
983 
984  if ( !ContentHandler::getForModelID( $this->contentModel )
985  ->isSupportedFormat( $this->contentFormat )
986  ) {
987  throw new ErrorPageError(
988  'editpage-notsupportedcontentformat-title',
989  'editpage-notsupportedcontentformat-text',
990  [ $this->contentFormat, ContentHandler::getLocalizedName( $this->contentModel ) ]
991  );
992  }
993 
1000  $this->editintro = $request->getText( 'editintro',
1001  // Custom edit intro for new sections
1002  $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
1003 
1004  // Allow extensions to modify form data
1005  Hooks::run( 'EditPage::importFormData', [ $this, $request ] );
1006 
1007  }
1008 
1018  protected function importContentFormData( &$request ) {
1019  return; // Don't do anything, EditPage already extracted wpTextbox1
1020  }
1021 
1027  function initialiseForm() {
1028  global $wgUser;
1029  $this->edittime = $this->page->getTimestamp();
1030  $this->editRevId = $this->page->getLatest();
1031 
1032  $content = $this->getContentObject( false ); # TODO: track content object?!
1033  if ( $content === false ) {
1034  return false;
1035  }
1036  $this->textbox1 = $this->toEditText( $content );
1037 
1038  // activate checkboxes if user wants them to be always active
1039  # Sort out the "watch" checkbox
1040  if ( $wgUser->getOption( 'watchdefault' ) ) {
1041  # Watch all edits
1042  $this->watchthis = true;
1043  } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1044  # Watch creations
1045  $this->watchthis = true;
1046  } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
1047  # Already watched
1048  $this->watchthis = true;
1049  }
1050  if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
1051  $this->minoredit = true;
1052  }
1053  if ( $this->textbox1 === false ) {
1054  return false;
1055  }
1056  return true;
1057  }
1058 
1066  protected function getContentObject( $def_content = null ) {
1068 
1069  $content = false;
1070 
1071  // For message page not locally set, use the i18n message.
1072  // For other non-existent articles, use preload text if any.
1073  if ( !$this->mTitle->exists() || $this->section == 'new' ) {
1074  if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
1075  # If this is a system message, get the default text.
1076  $msg = $this->mTitle->getDefaultMessageText();
1077 
1078  $content = $this->toEditContent( $msg );
1079  }
1080  if ( $content === false ) {
1081  # If requested, preload some text.
1082  $preload = $wgRequest->getVal( 'preload',
1083  // Custom preload text for new sections
1084  $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
1085  $params = $wgRequest->getArray( 'preloadparams', [] );
1086 
1087  $content = $this->getPreloadedContent( $preload, $params );
1088  }
1089  // For existing pages, get text based on "undo" or section parameters.
1090  } else {
1091  if ( $this->section != '' ) {
1092  // Get section edit text (returns $def_text for invalid sections)
1093  $orig = $this->getOriginalContent( $wgUser );
1094  $content = $orig ? $orig->getSection( $this->section ) : null;
1095 
1096  if ( !$content ) {
1097  $content = $def_content;
1098  }
1099  } else {
1100  $undoafter = $wgRequest->getInt( 'undoafter' );
1101  $undo = $wgRequest->getInt( 'undo' );
1102 
1103  if ( $undo > 0 && $undoafter > 0 ) {
1104  $undorev = Revision::newFromId( $undo );
1105  $oldrev = Revision::newFromId( $undoafter );
1106 
1107  # Sanity check, make sure it's the right page,
1108  # the revisions exist and they were not deleted.
1109  # Otherwise, $content will be left as-is.
1110  if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1111  !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
1112  !$oldrev->isDeleted( Revision::DELETED_TEXT )
1113  ) {
1114  $content = $this->page->getUndoContent( $undorev, $oldrev );
1115 
1116  if ( $content === false ) {
1117  # Warn the user that something went wrong
1118  $undoMsg = 'failure';
1119  } else {
1120  $oldContent = $this->page->getContent( Revision::RAW );
1121  $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
1122  $newContent = $content->preSaveTransform( $this->mTitle, $wgUser, $popts );
1123 
1124  if ( $newContent->equals( $oldContent ) ) {
1125  # Tell the user that the undo results in no change,
1126  # i.e. the revisions were already undone.
1127  $undoMsg = 'nochange';
1128  $content = false;
1129  } else {
1130  # Inform the user of our success and set an automatic edit summary
1131  $undoMsg = 'success';
1132 
1133  # If we just undid one rev, use an autosummary
1134  $firstrev = $oldrev->getNext();
1135  if ( $firstrev && $firstrev->getId() == $undo ) {
1136  $userText = $undorev->getUserText();
1137  if ( $userText === '' ) {
1138  $undoSummary = wfMessage(
1139  'undo-summary-username-hidden',
1140  $undo
1141  )->inContentLanguage()->text();
1142  } else {
1143  $undoSummary = wfMessage(
1144  'undo-summary',
1145  $undo,
1146  $userText
1147  )->inContentLanguage()->text();
1148  }
1149  if ( $this->summary === '' ) {
1150  $this->summary = $undoSummary;
1151  } else {
1152  $this->summary = $undoSummary . wfMessage( 'colon-separator' )
1153  ->inContentLanguage()->text() . $this->summary;
1154  }
1155  $this->undidRev = $undo;
1156  }
1157  $this->formtype = 'diff';
1158  }
1159  }
1160  } else {
1161  // Failed basic sanity checks.
1162  // Older revisions may have been removed since the link
1163  // was created, or we may simply have got bogus input.
1164  $undoMsg = 'norev';
1165  }
1166 
1167  // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1168  $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1169  $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
1170  wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1171  }
1172 
1173  if ( $content === false ) {
1174  $content = $this->getOriginalContent( $wgUser );
1175  }
1176  }
1177  }
1178 
1179  return $content;
1180  }
1181 
1197  private function getOriginalContent( User $user ) {
1198  if ( $this->section == 'new' ) {
1199  return $this->getCurrentContent();
1200  }
1201  $revision = $this->mArticle->getRevisionFetched();
1202  if ( $revision === null ) {
1203  if ( !$this->contentModel ) {
1204  $this->contentModel = $this->getTitle()->getContentModel();
1205  }
1206  $handler = ContentHandler::getForModelID( $this->contentModel );
1207 
1208  return $handler->makeEmptyContent();
1209  }
1210  $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
1211  return $content;
1212  }
1213 
1226  public function getParentRevId() {
1227  if ( $this->parentRevId ) {
1228  return $this->parentRevId;
1229  } else {
1230  return $this->mArticle->getRevIdFetched();
1231  }
1232  }
1233 
1242  protected function getCurrentContent() {
1243  $rev = $this->page->getRevision();
1244  $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1245 
1246  if ( $content === false || $content === null ) {
1247  if ( !$this->contentModel ) {
1248  $this->contentModel = $this->getTitle()->getContentModel();
1249  }
1250  $handler = ContentHandler::getForModelID( $this->contentModel );
1251 
1252  return $handler->makeEmptyContent();
1253  } else {
1254  // Content models should always be the same since we error
1255  // out if they are different before this point.
1256  $logger = LoggerFactory::getInstance( 'editpage' );
1257  if ( $this->contentModel !== $rev->getContentModel() ) {
1258  $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1259  'prev' => $this->contentModel,
1260  'new' => $rev->getContentModel(),
1261  'title' => $this->getTitle()->getPrefixedDBkey(),
1262  'method' => __METHOD__
1263  ] );
1264  $this->contentModel = $rev->getContentModel();
1265  }
1266 
1267  // Given that the content models should match, the current selected
1268  // format should be supported.
1269  if ( !$content->isSupportedFormat( $this->contentFormat ) ) {
1270  $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1271 
1272  'prev' => $this->contentFormat,
1273  'new' => $rev->getContentFormat(),
1274  'title' => $this->getTitle()->getPrefixedDBkey(),
1275  'method' => __METHOD__
1276  ] );
1277  $this->contentFormat = $rev->getContentFormat();
1278  }
1279 
1280  return $content;
1281  }
1282  }
1283 
1291  public function setPreloadedContent( Content $content ) {
1292  $this->mPreloadContent = $content;
1293  }
1294 
1306  protected function getPreloadedContent( $preload, $params = [] ) {
1307  global $wgUser;
1308 
1309  if ( !empty( $this->mPreloadContent ) ) {
1310  return $this->mPreloadContent;
1311  }
1312 
1313  $handler = ContentHandler::getForModelID( $this->contentModel );
1314 
1315  if ( $preload === '' ) {
1316  return $handler->makeEmptyContent();
1317  }
1318 
1319  $title = Title::newFromText( $preload );
1320  # Check for existence to avoid getting MediaWiki:Noarticletext
1321  if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1322  // TODO: somehow show a warning to the user!
1323  return $handler->makeEmptyContent();
1324  }
1325 
1327  if ( $page->isRedirect() ) {
1329  # Same as before
1330  if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1331  // TODO: somehow show a warning to the user!
1332  return $handler->makeEmptyContent();
1333  }
1335  }
1336 
1337  $parserOptions = ParserOptions::newFromUser( $wgUser );
1339 
1340  if ( !$content ) {
1341  // TODO: somehow show a warning to the user!
1342  return $handler->makeEmptyContent();
1343  }
1344 
1345  if ( $content->getModel() !== $handler->getModelID() ) {
1346  $converted = $content->convert( $handler->getModelID() );
1347 
1348  if ( !$converted ) {
1349  // TODO: somehow show a warning to the user!
1350  wfDebug( "Attempt to preload incompatible content: " .
1351  "can't convert " . $content->getModel() .
1352  " to " . $handler->getModelID() );
1353 
1354  return $handler->makeEmptyContent();
1355  }
1356 
1357  $content = $converted;
1358  }
1359 
1360  return $content->preloadTransform( $title, $parserOptions, $params );
1361  }
1362 
1370  function tokenOk( &$request ) {
1371  global $wgUser;
1372  $token = $request->getVal( 'wpEditToken' );
1373  $this->mTokenOk = $wgUser->matchEditToken( $token );
1374  $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1375  return $this->mTokenOk;
1376  }
1377 
1394  protected function setPostEditCookie( $statusValue ) {
1395  $revisionId = $this->page->getLatest();
1396  $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1397 
1398  $val = 'saved';
1399  if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1400  $val = 'created';
1401  } elseif ( $this->oldid ) {
1402  $val = 'restored';
1403  }
1404 
1405  $response = RequestContext::getMain()->getRequest()->response();
1406  $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION, [
1407  'httpOnly' => false,
1408  ] );
1409  }
1410 
1417  public function attemptSave( &$resultDetails = false ) {
1418  global $wgUser;
1419 
1420  # Allow bots to exempt some edits from bot flagging
1421  $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1422  $status = $this->internalAttemptSave( $resultDetails, $bot );
1423 
1424  Hooks::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1425 
1426  return $status;
1427  }
1428 
1438  private function handleStatus( Status $status, $resultDetails ) {
1440 
1445  if ( $status->value == self::AS_SUCCESS_UPDATE
1446  || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1447  ) {
1448  $this->didSave = true;
1449  if ( !$resultDetails['nullEdit'] ) {
1450  $this->setPostEditCookie( $status->value );
1451  }
1452  }
1453 
1454  // "wpExtraQueryRedirect" is a hidden input to modify
1455  // after save URL and is not used by actual edit form
1456  $request = RequestContext::getMain()->getRequest();
1457  $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1458 
1459  switch ( $status->value ) {
1460  case self::AS_HOOK_ERROR_EXPECTED:
1461  case self::AS_CONTENT_TOO_BIG:
1462  case self::AS_ARTICLE_WAS_DELETED:
1463  case self::AS_CONFLICT_DETECTED:
1464  case self::AS_SUMMARY_NEEDED:
1465  case self::AS_TEXTBOX_EMPTY:
1466  case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1467  case self::AS_END:
1468  case self::AS_BLANK_ARTICLE:
1469  case self::AS_SELF_REDIRECT:
1470  return true;
1471 
1472  case self::AS_HOOK_ERROR:
1473  return false;
1474 
1475  case self::AS_CANNOT_USE_CUSTOM_MODEL:
1476  case self::AS_PARSE_ERROR:
1477  $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1478  return true;
1479 
1480  case self::AS_SUCCESS_NEW_ARTICLE:
1481  $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1482  if ( $extraQueryRedirect ) {
1483  if ( $query === '' ) {
1484  $query = $extraQueryRedirect;
1485  } else {
1486  $query = $query . '&' . $extraQueryRedirect;
1487  }
1488  }
1489  $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1490  $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1491  return false;
1492 
1493  case self::AS_SUCCESS_UPDATE:
1494  $extraQuery = '';
1495  $sectionanchor = $resultDetails['sectionanchor'];
1496 
1497  // Give extensions a chance to modify URL query on update
1498  Hooks::run(
1499  'ArticleUpdateBeforeRedirect',
1500  [ $this->mArticle, &$sectionanchor, &$extraQuery ]
1501  );
1502 
1503  if ( $resultDetails['redirect'] ) {
1504  if ( $extraQuery == '' ) {
1505  $extraQuery = 'redirect=no';
1506  } else {
1507  $extraQuery = 'redirect=no&' . $extraQuery;
1508  }
1509  }
1510  if ( $extraQueryRedirect ) {
1511  if ( $extraQuery === '' ) {
1512  $extraQuery = $extraQueryRedirect;
1513  } else {
1514  $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1515  }
1516  }
1517 
1518  $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1519  return false;
1520 
1521  case self::AS_SPAM_ERROR:
1522  $this->spamPageWithContent( $resultDetails['spam'] );
1523  return false;
1524 
1525  case self::AS_BLOCKED_PAGE_FOR_USER:
1526  throw new UserBlockedError( $wgUser->getBlock() );
1527 
1528  case self::AS_IMAGE_REDIRECT_ANON:
1529  case self::AS_IMAGE_REDIRECT_LOGGED:
1530  throw new PermissionsError( 'upload' );
1531 
1532  case self::AS_READ_ONLY_PAGE_ANON:
1533  case self::AS_READ_ONLY_PAGE_LOGGED:
1534  throw new PermissionsError( 'edit' );
1535 
1536  case self::AS_READ_ONLY_PAGE:
1537  throw new ReadOnlyError;
1538 
1539  case self::AS_RATE_LIMITED:
1540  throw new ThrottledError();
1541 
1542  case self::AS_NO_CREATE_PERMISSION:
1543  $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1544  throw new PermissionsError( $permission );
1545 
1546  case self::AS_NO_CHANGE_CONTENT_MODEL:
1547  throw new PermissionsError( 'editcontentmodel' );
1548 
1549  default:
1550  // We don't recognize $status->value. The only way that can happen
1551  // is if an extension hook aborted from inside ArticleSave.
1552  // Render the status object into $this->hookError
1553  // FIXME this sucks, we should just use the Status object throughout
1554  $this->hookError = '<div class="error">' . $status->getWikiText() .
1555  '</div>';
1556  return true;
1557  }
1558  }
1559 
1570  // Run old style post-section-merge edit filter
1571  if ( !ContentHandler::runLegacyHooks( 'EditFilterMerged',
1572  [ $this, $content, &$this->hookError, $this->summary ] )
1573  ) {
1574  # Error messages etc. could be handled within the hook...
1575  $status->fatal( 'hookaborted' );
1576  $status->value = self::AS_HOOK_ERROR;
1577  return false;
1578  } elseif ( $this->hookError != '' ) {
1579  # ...or the hook could be expecting us to produce an error
1580  $status->fatal( 'hookaborted' );
1581  $status->value = self::AS_HOOK_ERROR_EXPECTED;
1582  return false;
1583  }
1584 
1585  // Run new style post-section-merge edit filter
1586  if ( !Hooks::run( 'EditFilterMergedContent',
1587  [ $this->mArticle->getContext(), $content, $status, $this->summary,
1588  $user, $this->minoredit ] )
1589  ) {
1590  # Error messages etc. could be handled within the hook...
1591  if ( $status->isGood() ) {
1592  $status->fatal( 'hookaborted' );
1593  // Not setting $this->hookError here is a hack to allow the hook
1594  // to cause a return to the edit page without $this->hookError
1595  // being set. This is used by ConfirmEdit to display a captcha
1596  // without any error message cruft.
1597  } else {
1598  $this->hookError = $status->getWikiText();
1599  }
1600  // Use the existing $status->value if the hook set it
1601  if ( !$status->value ) {
1602  $status->value = self::AS_HOOK_ERROR;
1603  }
1604  return false;
1605  } elseif ( !$status->isOK() ) {
1606  # ...or the hook could be expecting us to produce an error
1607  // FIXME this sucks, we should just use the Status object throughout
1608  $this->hookError = $status->getWikiText();
1609  $status->fatal( 'hookaborted' );
1610  $status->value = self::AS_HOOK_ERROR_EXPECTED;
1611  return false;
1612  }
1613 
1614  return true;
1615  }
1616 
1623  private function newSectionSummary( &$sectionanchor = null ) {
1624  global $wgParser;
1625 
1626  if ( $this->sectiontitle !== '' ) {
1627  $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1628  // If no edit summary was specified, create one automatically from the section
1629  // title and have it link to the new section. Otherwise, respect the summary as
1630  // passed.
1631  if ( $this->summary === '' ) {
1632  $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1633  return wfMessage( 'newsectionsummary' )
1634  ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1635  }
1636  } elseif ( $this->summary !== '' ) {
1637  $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1638  # This is a new section, so create a link to the new section
1639  # in the revision summary.
1640  $cleanSummary = $wgParser->stripSectionName( $this->summary );
1641  return wfMessage( 'newsectionsummary' )
1642  ->rawParams( $cleanSummary )->inContentLanguage()->text();
1643  }
1644  return $this->summary;
1645  }
1646 
1671  function internalAttemptSave( &$result, $bot = false ) {
1674 
1676 
1677  if ( !Hooks::run( 'EditPage::attemptSave', [ $this ] ) ) {
1678  wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1679  $status->fatal( 'hookaborted' );
1680  $status->value = self::AS_HOOK_ERROR;
1681  return $status;
1682  }
1683 
1684  $spam = $wgRequest->getText( 'wpAntispam' );
1685  if ( $spam !== '' ) {
1686  wfDebugLog(
1687  'SimpleAntiSpam',
1688  $wgUser->getName() .
1689  ' editing "' .
1690  $this->mTitle->getPrefixedText() .
1691  '" submitted bogus field "' .
1692  $spam .
1693  '"'
1694  );
1695  $status->fatal( 'spamprotectionmatch', false );
1696  $status->value = self::AS_SPAM_ERROR;
1697  return $status;
1698  }
1699 
1700  try {
1701  # Construct Content object
1702  $textbox_content = $this->toEditContent( $this->textbox1 );
1703  } catch ( MWContentSerializationException $ex ) {
1704  $status->fatal(
1705  'content-failed-to-parse',
1706  $this->contentModel,
1707  $this->contentFormat,
1708  $ex->getMessage()
1709  );
1710  $status->value = self::AS_PARSE_ERROR;
1711  return $status;
1712  }
1713 
1714  # Check image redirect
1715  if ( $this->mTitle->getNamespace() == NS_FILE &&
1716  $textbox_content->isRedirect() &&
1717  !$wgUser->isAllowed( 'upload' )
1718  ) {
1719  $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1720  $status->setResult( false, $code );
1721 
1722  return $status;
1723  }
1724 
1725  # Check for spam
1726  $match = self::matchSummarySpamRegex( $this->summary );
1727  if ( $match === false && $this->section == 'new' ) {
1728  # $wgSpamRegex is enforced on this new heading/summary because, unlike
1729  # regular summaries, it is added to the actual wikitext.
1730  if ( $this->sectiontitle !== '' ) {
1731  # This branch is taken when the API is used with the 'sectiontitle' parameter.
1732  $match = self::matchSpamRegex( $this->sectiontitle );
1733  } else {
1734  # This branch is taken when the "Add Topic" user interface is used, or the API
1735  # is used with the 'summary' parameter.
1736  $match = self::matchSpamRegex( $this->summary );
1737  }
1738  }
1739  if ( $match === false ) {
1740  $match = self::matchSpamRegex( $this->textbox1 );
1741  }
1742  if ( $match !== false ) {
1743  $result['spam'] = $match;
1744  $ip = $wgRequest->getIP();
1745  $pdbk = $this->mTitle->getPrefixedDBkey();
1746  $match = str_replace( "\n", '', $match );
1747  wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1748  $status->fatal( 'spamprotectionmatch', $match );
1749  $status->value = self::AS_SPAM_ERROR;
1750  return $status;
1751  }
1752  if ( !Hooks::run(
1753  'EditFilter',
1754  [ $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ] )
1755  ) {
1756  # Error messages etc. could be handled within the hook...
1757  $status->fatal( 'hookaborted' );
1758  $status->value = self::AS_HOOK_ERROR;
1759  return $status;
1760  } elseif ( $this->hookError != '' ) {
1761  # ...or the hook could be expecting us to produce an error
1762  $status->fatal( 'hookaborted' );
1763  $status->value = self::AS_HOOK_ERROR_EXPECTED;
1764  return $status;
1765  }
1766 
1767  if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1768  // Auto-block user's IP if the account was "hard" blocked
1769  if ( !wfReadOnly() ) {
1770  $wgUser->spreadAnyEditBlock();
1771  }
1772  # Check block state against master, thus 'false'.
1773  $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1774  return $status;
1775  }
1776 
1777  $this->contentLength = strlen( $this->textbox1 );
1778  if ( $this->contentLength > $wgMaxArticleSize * 1024 ) {
1779  // Error will be displayed by showEditForm()
1780  $this->tooBig = true;
1781  $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1782  return $status;
1783  }
1784 
1785  if ( !$wgUser->isAllowed( 'edit' ) ) {
1786  if ( $wgUser->isAnon() ) {
1787  $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1788  return $status;
1789  } else {
1790  $status->fatal( 'readonlytext' );
1791  $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1792  return $status;
1793  }
1794  }
1795 
1796  $changingContentModel = false;
1797  if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
1798  if ( !$wgContentHandlerUseDB ) {
1799  $status->fatal( 'editpage-cannot-use-custom-model' );
1800  $status->value = self::AS_CANNOT_USE_CUSTOM_MODEL;
1801  return $status;
1802  } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1803  $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1804  return $status;
1805 
1806  }
1807  $changingContentModel = true;
1808  $oldContentModel = $this->mTitle->getContentModel();
1809  }
1810 
1811  if ( $this->changeTags ) {
1812  $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
1813  $this->changeTags, $wgUser );
1814  if ( !$changeTagsStatus->isOK() ) {
1815  $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
1816  return $changeTagsStatus;
1817  }
1818  }
1819 
1820  if ( wfReadOnly() ) {
1821  $status->fatal( 'readonlytext' );
1822  $status->value = self::AS_READ_ONLY_PAGE;
1823  return $status;
1824  }
1825  if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1826  $status->fatal( 'actionthrottledtext' );
1827  $status->value = self::AS_RATE_LIMITED;
1828  return $status;
1829  }
1830 
1831  # If the article has been deleted while editing, don't save it without
1832  # confirmation
1833  if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1834  $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1835  return $status;
1836  }
1837 
1838  # Load the page data from the master. If anything changes in the meantime,
1839  # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1840  $this->page->loadPageData( 'fromdbmaster' );
1841  $new = !$this->page->exists();
1842 
1843  if ( $new ) {
1844  // Late check for create permission, just in case *PARANOIA*
1845  if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1846  $status->fatal( 'nocreatetext' );
1847  $status->value = self::AS_NO_CREATE_PERMISSION;
1848  wfDebug( __METHOD__ . ": no create permission\n" );
1849  return $status;
1850  }
1851 
1852  // Don't save a new page if it's blank or if it's a MediaWiki:
1853  // message with content equivalent to default (allow empty pages
1854  // in this case to disable messages, see bug 50124)
1855  $defaultMessageText = $this->mTitle->getDefaultMessageText();
1856  if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1857  $defaultText = $defaultMessageText;
1858  } else {
1859  $defaultText = '';
1860  }
1861 
1862  if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
1863  $this->blankArticle = true;
1864  $status->fatal( 'blankarticle' );
1865  $status->setResult( false, self::AS_BLANK_ARTICLE );
1866  return $status;
1867  }
1868 
1869  if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1870  return $status;
1871  }
1872 
1873  $content = $textbox_content;
1874 
1875  $result['sectionanchor'] = '';
1876  if ( $this->section == 'new' ) {
1877  if ( $this->sectiontitle !== '' ) {
1878  // Insert the section title above the content.
1879  $content = $content->addSectionHeader( $this->sectiontitle );
1880  } elseif ( $this->summary !== '' ) {
1881  // Insert the section title above the content.
1882  $content = $content->addSectionHeader( $this->summary );
1883  }
1884  $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
1885  }
1886 
1887  $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1888 
1889  } else { # not $new
1890 
1891  # Article exists. Check for edit conflict.
1892 
1893  $this->page->clear(); # Force reload of dates, etc.
1894  $timestamp = $this->page->getTimestamp();
1895  $latest = $this->page->getLatest();
1896 
1897  wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1898 
1899  // Check editRevId if set, which handles same-second timestamp collisions
1900  if ( $timestamp != $this->edittime
1901  || ( $this->editRevId !== null && $this->editRevId != $latest )
1902  ) {
1903  $this->isConflict = true;
1904  if ( $this->section == 'new' ) {
1905  if ( $this->page->getUserText() == $wgUser->getName() &&
1906  $this->page->getComment() == $this->newSectionSummary()
1907  ) {
1908  // Probably a duplicate submission of a new comment.
1909  // This can happen when CDN resends a request after
1910  // a timeout but the first one actually went through.
1911  wfDebug( __METHOD__
1912  . ": duplicate new section submission; trigger edit conflict!\n" );
1913  } else {
1914  // New comment; suppress conflict.
1915  $this->isConflict = false;
1916  wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1917  }
1918  } elseif ( $this->section == ''
1920  DB_MASTER, $this->mTitle->getArticleID(),
1921  $wgUser->getId(), $this->edittime
1922  )
1923  ) {
1924  # Suppress edit conflict with self, except for section edits where merging is required.
1925  wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1926  $this->isConflict = false;
1927  }
1928  }
1929 
1930  // If sectiontitle is set, use it, otherwise use the summary as the section title.
1931  if ( $this->sectiontitle !== '' ) {
1932  $sectionTitle = $this->sectiontitle;
1933  } else {
1934  $sectionTitle = $this->summary;
1935  }
1936 
1937  $content = null;
1938 
1939  if ( $this->isConflict ) {
1940  wfDebug( __METHOD__
1941  . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1942  . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
1943  // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
1944  // ...or disable section editing for non-current revisions (not exposed anyway).
1945  if ( $this->editRevId !== null ) {
1946  $content = $this->page->replaceSectionAtRev(
1947  $this->section,
1948  $textbox_content,
1949  $sectionTitle,
1950  $this->editRevId
1951  );
1952  } else {
1953  $content = $this->page->replaceSectionContent(
1954  $this->section,
1955  $textbox_content,
1956  $sectionTitle,
1957  $this->edittime
1958  );
1959  }
1960  } else {
1961  wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
1962  $content = $this->page->replaceSectionContent(
1963  $this->section,
1964  $textbox_content,
1965  $sectionTitle
1966  );
1967  }
1968 
1969  if ( is_null( $content ) ) {
1970  wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1971  $this->isConflict = true;
1972  $content = $textbox_content; // do not try to merge here!
1973  } elseif ( $this->isConflict ) {
1974  # Attempt merge
1975  if ( $this->mergeChangesIntoContent( $content ) ) {
1976  // Successful merge! Maybe we should tell the user the good news?
1977  $this->isConflict = false;
1978  wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1979  } else {
1980  $this->section = '';
1981  $this->textbox1 = ContentHandler::getContentText( $content );
1982  wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1983  }
1984  }
1985 
1986  if ( $this->isConflict ) {
1987  $status->setResult( false, self::AS_CONFLICT_DETECTED );
1988  return $status;
1989  }
1990 
1991  if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1992  return $status;
1993  }
1994 
1995  if ( $this->section == 'new' ) {
1996  // Handle the user preference to force summaries here
1997  if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
1998  $this->missingSummary = true;
1999  $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2000  $status->value = self::AS_SUMMARY_NEEDED;
2001  return $status;
2002  }
2003 
2004  // Do not allow the user to post an empty comment
2005  if ( $this->textbox1 == '' ) {
2006  $this->missingComment = true;
2007  $status->fatal( 'missingcommenttext' );
2008  $status->value = self::AS_TEXTBOX_EMPTY;
2009  return $status;
2010  }
2011  } elseif ( !$this->allowBlankSummary
2012  && !$content->equals( $this->getOriginalContent( $wgUser ) )
2013  && !$content->isRedirect()
2014  && md5( $this->summary ) == $this->autoSumm
2015  ) {
2016  $this->missingSummary = true;
2017  $status->fatal( 'missingsummary' );
2018  $status->value = self::AS_SUMMARY_NEEDED;
2019  return $status;
2020  }
2021 
2022  # All's well
2023  $sectionanchor = '';
2024  if ( $this->section == 'new' ) {
2025  $this->summary = $this->newSectionSummary( $sectionanchor );
2026  } elseif ( $this->section != '' ) {
2027  # Try to get a section anchor from the section source, redirect
2028  # to edited section if header found.
2029  # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2030  # for duplicate heading checking and maybe parsing.
2031  $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
2032  # We can't deal with anchors, includes, html etc in the header for now,
2033  # headline would need to be parsed to improve this.
2034  if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2035  $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
2036  }
2037  }
2038  $result['sectionanchor'] = $sectionanchor;
2039 
2040  // Save errors may fall down to the edit form, but we've now
2041  // merged the section into full text. Clear the section field
2042  // so that later submission of conflict forms won't try to
2043  // replace that into a duplicated mess.
2044  $this->textbox1 = $this->toEditText( $content );
2045  $this->section = '';
2046 
2047  $status->value = self::AS_SUCCESS_UPDATE;
2048  }
2049 
2050  if ( !$this->allowSelfRedirect
2051  && $content->isRedirect()
2052  && $content->getRedirectTarget()->equals( $this->getTitle() )
2053  ) {
2054  // If the page already redirects to itself, don't warn.
2055  $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2056  if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
2057  $this->selfRedirect = true;
2058  $status->fatal( 'selfredirect' );
2059  $status->value = self::AS_SELF_REDIRECT;
2060  return $status;
2061  }
2062  }
2063 
2064  // Check for length errors again now that the section is merged in
2065  $this->contentLength = strlen( $this->toEditText( $content ) );
2066  if ( $this->contentLength > $wgMaxArticleSize * 1024 ) {
2067  $this->tooBig = true;
2068  $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
2069  return $status;
2070  }
2071 
2073  ( $new ? EDIT_NEW : EDIT_UPDATE ) |
2074  ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
2075  ( $bot ? EDIT_FORCE_BOT : 0 );
2076 
2077  $doEditStatus = $this->page->doEditContent(
2078  $content,
2079  $this->summary,
2080  $flags,
2081  false,
2082  $wgUser,
2083  $content->getDefaultFormat(),
2085  );
2086 
2087  if ( !$doEditStatus->isOK() ) {
2088  // Failure from doEdit()
2089  // Show the edit conflict page for certain recognized errors from doEdit(),
2090  // but don't show it for errors from extension hooks
2091  $errors = $doEditStatus->getErrorsArray();
2092  if ( in_array( $errors[0][0],
2093  [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2094  ) {
2095  $this->isConflict = true;
2096  // Destroys data doEdit() put in $status->value but who cares
2097  $doEditStatus->value = self::AS_END;
2098  }
2099  return $doEditStatus;
2100  }
2101 
2102  $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2103  if ( $result['nullEdit'] ) {
2104  // We don't know if it was a null edit until now, so increment here
2105  $wgUser->pingLimiter( 'linkpurge' );
2106  }
2107  $result['redirect'] = $content->isRedirect();
2108 
2109  $this->updateWatchlist();
2110 
2111  // If the content model changed, add a log entry
2112  if ( $changingContentModel ) {
2114  $wgUser,
2115  $new ? false : $oldContentModel,
2116  $this->contentModel,
2117  $this->summary
2118  );
2119  }
2120 
2121  return $status;
2122  }
2123 
2130  protected function addContentModelChangeLogEntry( User $user, $oldModel, $newModel, $reason ) {
2131  $new = $oldModel === false;
2132  $log = new ManualLogEntry( 'contentmodel', $new ? 'new' : 'change' );
2133  $log->setPerformer( $user );
2134  $log->setTarget( $this->mTitle );
2135  $log->setComment( $reason );
2136  $log->setParameters( [
2137  '4::oldmodel' => $oldModel,
2138  '5::newmodel' => $newModel
2139  ] );
2140  $logid = $log->insert();
2141  $log->publish( $logid );
2142  }
2143 
2147  protected function updateWatchlist() {
2148  global $wgUser;
2149 
2150  if ( !$wgUser->isLoggedIn() ) {
2151  return;
2152  }
2153 
2154  $user = $wgUser;
2156  $watch = $this->watchthis;
2157  // Do this in its own transaction to reduce contention...
2158  DeferredUpdates::addCallableUpdate( function () use ( $user, $title, $watch ) {
2159  if ( $watch == $user->isWatched( $title, User::IGNORE_USER_RIGHTS ) ) {
2160  return; // nothing to change
2161  }
2163  } );
2164  }
2165 
2177  private function mergeChangesIntoContent( &$editContent ) {
2178 
2179  $db = wfGetDB( DB_MASTER );
2180 
2181  // This is the revision the editor started from
2182  $baseRevision = $this->getBaseRevision();
2183  $baseContent = $baseRevision ? $baseRevision->getContent() : null;
2184 
2185  if ( is_null( $baseContent ) ) {
2186  return false;
2187  }
2188 
2189  // The current state, we want to merge updates into it
2190  $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2191  $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2192 
2193  if ( is_null( $currentContent ) ) {
2194  return false;
2195  }
2196 
2197  $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2198 
2199  $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2200 
2201  if ( $result ) {
2202  $editContent = $result;
2203  // Update parentRevId to what we just merged.
2204  $this->parentRevId = $currentRevision->getId();
2205  return true;
2206  }
2207 
2208  return false;
2209  }
2210 
2216  function getBaseRevision() {
2217  if ( !$this->mBaseRevision ) {
2218  $db = wfGetDB( DB_MASTER );
2219  $this->mBaseRevision = $this->editRevId
2220  ? Revision::newFromId( $this->editRevId, Revision::READ_LATEST )
2221  : Revision::loadFromTimestamp( $db, $this->mTitle, $this->edittime );
2222  }
2223  return $this->mBaseRevision;
2224  }
2225 
2233  public static function matchSpamRegex( $text ) {
2235  // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2236  $regexes = (array)$wgSpamRegex;
2237  return self::matchSpamRegexInternal( $text, $regexes );
2238  }
2239 
2247  public static function matchSummarySpamRegex( $text ) {
2249  $regexes = (array)$wgSummarySpamRegex;
2250  return self::matchSpamRegexInternal( $text, $regexes );
2251  }
2252 
2258  protected static function matchSpamRegexInternal( $text, $regexes ) {
2259  foreach ( $regexes as $regex ) {
2260  $matches = [];
2261  if ( preg_match( $regex, $text, $matches ) ) {
2262  return $matches[0];
2263  }
2264  }
2265  return false;
2266  }
2267 
2268  function setHeaders() {
2270 
2271  $wgOut->addModules( 'mediawiki.action.edit' );
2272  $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2273 
2274  if ( $wgUser->getOption( 'showtoolbar' ) ) {
2275  // The addition of default buttons is handled by getEditToolbar() which
2276  // has its own dependency on this module. The call here ensures the module
2277  // is loaded in time (it has position "top") for other modules to register
2278  // buttons (e.g. extensions, gadgets, user scripts).
2279  $wgOut->addModules( 'mediawiki.toolbar' );
2280  }
2281 
2282  if ( $wgUser->getOption( 'uselivepreview' ) ) {
2283  $wgOut->addModules( 'mediawiki.action.edit.preview' );
2284  }
2285 
2286  if ( $wgUser->getOption( 'useeditwarning' ) ) {
2287  $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2288  }
2289 
2290  # Enabled article-related sidebar, toplinks, etc.
2291  $wgOut->setArticleRelated( true );
2292 
2293  $contextTitle = $this->getContextTitle();
2294  if ( $this->isConflict ) {
2295  $msg = 'editconflict';
2296  } elseif ( $contextTitle->exists() && $this->section != '' ) {
2297  $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2298  } else {
2299  $msg = $contextTitle->exists()
2300  || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2301  && $contextTitle->getDefaultMessageText() !== false
2302  )
2303  ? 'editing'
2304  : 'creating';
2305  }
2306 
2307  # Use the title defined by DISPLAYTITLE magic word when present
2308  # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2309  # setPageTitle() treats the input as wikitext, which should be safe in either case.
2310  $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2311  if ( $displayTitle === false ) {
2312  $displayTitle = $contextTitle->getPrefixedText();
2313  }
2314  $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2315  # Transmit the name of the message to JavaScript for live preview
2316  # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2317  $wgOut->addJsConfigVars( [
2318  'wgEditMessage' => $msg,
2319  'wgAjaxEditStash' => $wgAjaxEditStash,
2320  ] );
2321  }
2322 
2326  protected function showIntro() {
2328  if ( $this->suppressIntro ) {
2329  return;
2330  }
2331 
2332  $namespace = $this->mTitle->getNamespace();
2333 
2334  if ( $namespace == NS_MEDIAWIKI ) {
2335  # Show a warning if editing an interface message
2336  $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2337  # If this is a default message (but not css or js),
2338  # show a hint that it is translatable on translatewiki.net
2339  if ( !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2340  && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2341  ) {
2342  $defaultMessageText = $this->mTitle->getDefaultMessageText();
2343  if ( $defaultMessageText !== false ) {
2344  $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2345  'translateinterface' );
2346  }
2347  }
2348  } elseif ( $namespace == NS_FILE ) {
2349  # Show a hint to shared repo
2350  $file = wfFindFile( $this->mTitle );
2351  if ( $file && !$file->isLocal() ) {
2352  $descUrl = $file->getDescriptionUrl();
2353  # there must be a description url to show a hint to shared repo
2354  if ( $descUrl ) {
2355  if ( !$this->mTitle->exists() ) {
2356  $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2357  'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2358  ] );
2359  } else {
2360  $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2361  'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2362  ] );
2363  }
2364  }
2365  }
2366  }
2367 
2368  # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2369  # Show log extract when the user is currently blocked
2370  if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2371  $username = explode( '/', $this->mTitle->getText(), 2 )[0];
2372  $user = User::newFromName( $username, false /* allow IP users*/ );
2373  $ip = User::isIP( $username );
2374  $block = Block::newFromTarget( $user, $user );
2375  if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2376  $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2377  [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2378  } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2379  # Show log extract if the user is currently blocked
2381  $wgOut,
2382  'block',
2383  MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2384  '',
2385  [
2386  'lim' => 1,
2387  'showIfEmpty' => false,
2388  'msgKey' => [
2389  'blocked-notice-logextract',
2390  $user->getName() # Support GENDER in notice
2391  ]
2392  ]
2393  );
2394  }
2395  }
2396  # Try to add a custom edit intro, or use the standard one if this is not possible.
2397  if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2399  wfMessage( 'helppage' )->inContentLanguage()->text()
2400  ) );
2401  if ( $wgUser->isLoggedIn() ) {
2402  $wgOut->wrapWikiMsg(
2403  // Suppress the external link icon, consider the help url an internal one
2404  "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2405  [
2406  'newarticletext',
2407  $helpLink
2408  ]
2409  );
2410  } else {
2411  $wgOut->wrapWikiMsg(
2412  // Suppress the external link icon, consider the help url an internal one
2413  "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2414  [
2415  'newarticletextanon',
2416  $helpLink
2417  ]
2418  );
2419  }
2420  }
2421  # Give a notice if the user is editing a deleted/moved page...
2422  if ( !$this->mTitle->exists() ) {
2423  LogEventsList::showLogExtract( $wgOut, [ 'delete', 'move' ], $this->mTitle,
2424  '',
2425  [
2426  'lim' => 10,
2427  'conds' => [ "log_action != 'revision'" ],
2428  'showIfEmpty' => false,
2429  'msgKey' => [ 'recreate-moveddeleted-warn' ]
2430  ]
2431  );
2432  }
2433  }
2434 
2440  protected function showCustomIntro() {
2441  if ( $this->editintro ) {
2442  $title = Title::newFromText( $this->editintro );
2443  if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2444  global $wgOut;
2445  // Added using template syntax, to take <noinclude>'s into account.
2446  $wgOut->addWikiTextTitleTidy(
2447  '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2449  );
2450  return true;
2451  }
2452  }
2453  return false;
2454  }
2455 
2474  protected function toEditText( $content ) {
2475  if ( $content === null || $content === false || is_string( $content ) ) {
2476  return $content;
2477  }
2478 
2479  if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2480  throw new MWException( 'This content model is not supported: '
2481  . ContentHandler::getLocalizedName( $content->getModel() ) );
2482  }
2483 
2484  return $content->serialize( $this->contentFormat );
2485  }
2486 
2503  protected function toEditContent( $text ) {
2504  if ( $text === false || $text === null ) {
2505  return $text;
2506  }
2507 
2508  $content = ContentHandler::makeContent( $text, $this->getTitle(),
2509  $this->contentModel, $this->contentFormat );
2510 
2511  if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2512  throw new MWException( 'This content model is not supported: '
2513  . ContentHandler::getLocalizedName( $content->getModel() ) );
2514  }
2515 
2516  return $content;
2517  }
2518 
2527  function showEditForm( $formCallback = null ) {
2529 
2530  # need to parse the preview early so that we know which templates are used,
2531  # otherwise users with "show preview after edit box" will get a blank list
2532  # we parse this near the beginning so that setHeaders can do the title
2533  # setting work instead of leaving it in getPreviewText
2534  $previewOutput = '';
2535  if ( $this->formtype == 'preview' ) {
2536  $previewOutput = $this->getPreviewText();
2537  }
2538 
2539  Hooks::run( 'EditPage::showEditForm:initial', [ &$this, &$wgOut ] );
2540 
2541  $this->setHeaders();
2542 
2543  if ( $this->showHeader() === false ) {
2544  return;
2545  }
2546 
2547  $wgOut->addHTML( $this->editFormPageTop );
2548 
2549  if ( $wgUser->getOption( 'previewontop' ) ) {
2550  $this->displayPreviewArea( $previewOutput, true );
2551  }
2552 
2553  $wgOut->addHTML( $this->editFormTextTop );
2554 
2555  $showToolbar = true;
2556  if ( $this->wasDeletedSinceLastEdit() ) {
2557  if ( $this->formtype == 'save' ) {
2558  // Hide the toolbar and edit area, user can click preview to get it back
2559  // Add an confirmation checkbox and explanation.
2560  $showToolbar = false;
2561  } else {
2562  $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2563  'deletedwhileediting' );
2564  }
2565  }
2566 
2567  // @todo add EditForm plugin interface and use it here!
2568  // search for textarea1 and textares2, and allow EditForm to override all uses.
2569  $wgOut->addHTML( Html::openElement(
2570  'form',
2571  [
2572  'id' => self::EDITFORM_ID,
2573  'name' => self::EDITFORM_ID,
2574  'method' => 'post',
2575  'action' => $this->getActionURL( $this->getContextTitle() ),
2576  'enctype' => 'multipart/form-data'
2577  ]
2578  ) );
2579 
2580  if ( is_callable( $formCallback ) ) {
2581  wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2582  call_user_func_array( $formCallback, [ &$wgOut ] );
2583  }
2584 
2585  // Add an empty field to trip up spambots
2586  $wgOut->addHTML(
2587  Xml::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2588  . Html::rawElement(
2589  'label',
2590  [ 'for' => 'wpAntispam' ],
2591  wfMessage( 'simpleantispam-label' )->parse()
2592  )
2593  . Xml::element(
2594  'input',
2595  [
2596  'type' => 'text',
2597  'name' => 'wpAntispam',
2598  'id' => 'wpAntispam',
2599  'value' => ''
2600  ]
2601  )
2602  . Xml::closeElement( 'div' )
2603  );
2604 
2605  Hooks::run( 'EditPage::showEditForm:fields', [ &$this, &$wgOut ] );
2606 
2607  // Put these up at the top to ensure they aren't lost on early form submission
2608  $this->showFormBeforeText();
2609 
2610  if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2611  $username = $this->lastDelete->user_name;
2612  $comment = $this->lastDelete->log_comment;
2613 
2614  // It is better to not parse the comment at all than to have templates expanded in the middle
2615  // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2616  $key = $comment === ''
2617  ? 'confirmrecreate-noreason'
2618  : 'confirmrecreate';
2619  $wgOut->addHTML(
2620  '<div class="mw-confirm-recreate">' .
2621  wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2622  Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2623  [ 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2624  ) .
2625  '</div>'
2626  );
2627  }
2628 
2629  # When the summary is hidden, also hide them on preview/show changes
2630  if ( $this->nosummary ) {
2631  $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2632  }
2633 
2634  # If a blank edit summary was previously provided, and the appropriate
2635  # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2636  # user being bounced back more than once in the event that a summary
2637  # is not required.
2638  # ####
2639  # For a bit more sophisticated detection of blank summaries, hash the
2640  # automatic one and pass that in the hidden field wpAutoSummary.
2641  if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2642  $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2643  }
2644 
2645  if ( $this->undidRev ) {
2646  $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2647  }
2648 
2649  if ( $this->selfRedirect ) {
2650  $wgOut->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2651  }
2652 
2653  if ( $this->hasPresetSummary ) {
2654  // If a summary has been preset using &summary= we don't want to prompt for
2655  // a different summary. Only prompt for a summary if the summary is blanked.
2656  // (Bug 17416)
2657  $this->autoSumm = md5( '' );
2658  }
2659 
2660  $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2661  $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2662 
2663  $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2664  $wgOut->addHTML( Html::hidden( 'parentRevId', $this->getParentRevId() ) );
2665 
2666  $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2667  $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2668 
2669  if ( $this->section == 'new' ) {
2670  $this->showSummaryInput( true, $this->summary );
2671  $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2672  }
2673 
2674  $wgOut->addHTML( $this->editFormTextBeforeContent );
2675 
2676  if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2677  $wgOut->addHTML( EditPage::getEditToolbar( $this->mTitle ) );
2678  }
2679 
2680  if ( $this->blankArticle ) {
2681  $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2682  }
2683 
2684  if ( $this->isConflict ) {
2685  // In an edit conflict bypass the overridable content form method
2686  // and fallback to the raw wpTextbox1 since editconflicts can't be
2687  // resolved between page source edits and custom ui edits using the
2688  // custom edit ui.
2689  $this->textbox2 = $this->textbox1;
2690 
2691  $content = $this->getCurrentContent();
2692  $this->textbox1 = $this->toEditText( $content );
2693 
2694  $this->showTextbox1();
2695  } else {
2696  $this->showContentForm();
2697  }
2698 
2699  $wgOut->addHTML( $this->editFormTextAfterContent );
2700 
2701  $this->showStandardInputs();
2702 
2703  $this->showFormAfterText();
2704 
2705  $this->showTosSummary();
2706 
2707  $this->showEditTools();
2708 
2709  $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2710 
2711  $wgOut->addHTML( Html::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2712  Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2713 
2714  $wgOut->addHTML( Html::rawElement( 'div', [ 'class' => 'hiddencats' ],
2715  Linker::formatHiddenCategories( $this->page->getHiddenCategories() ) ) );
2716 
2717  $wgOut->addHTML( Html::rawElement( 'div', [ 'class' => 'limitreport' ],
2718  self::getPreviewLimitReport( $this->mParserOutput ) ) );
2719 
2720  $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2721 
2722  if ( $this->isConflict ) {
2723  try {
2724  $this->showConflict();
2725  } catch ( MWContentSerializationException $ex ) {
2726  // this can't really happen, but be nice if it does.
2727  $msg = wfMessage(
2728  'content-failed-to-parse',
2729  $this->contentModel,
2730  $this->contentFormat,
2731  $ex->getMessage()
2732  );
2733  $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2734  }
2735  }
2736 
2737  // Set a hidden field so JS knows what edit form mode we are in
2738  if ( $this->isConflict ) {
2739  $mode = 'conflict';
2740  } elseif ( $this->preview ) {
2741  $mode = 'preview';
2742  } elseif ( $this->diff ) {
2743  $mode = 'diff';
2744  } else {
2745  $mode = 'text';
2746  }
2747  $wgOut->addHTML( Html::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2748 
2749  // Marker for detecting truncated form data. This must be the last
2750  // parameter sent in order to be of use, so do not move me.
2751  $wgOut->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2752  $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2753 
2754  if ( !$wgUser->getOption( 'previewontop' ) ) {
2755  $this->displayPreviewArea( $previewOutput, false );
2756  }
2757 
2758  }
2759 
2766  public static function extractSectionTitle( $text ) {
2767  preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2768  if ( !empty( $matches[2] ) ) {
2769  global $wgParser;
2770  return $wgParser->stripSectionName( trim( $matches[2] ) );
2771  } else {
2772  return false;
2773  }
2774  }
2775 
2779  protected function showHeader() {
2782 
2783  if ( $this->mTitle->isTalkPage() ) {
2784  $wgOut->addWikiMsg( 'talkpagetext' );
2785  }
2786 
2787  // Add edit notices
2788  $editNotices = $this->mTitle->getEditNotices( $this->oldid );
2789  if ( count( $editNotices ) ) {
2790  $wgOut->addHTML( implode( "\n", $editNotices ) );
2791  } else {
2792  $msg = wfMessage( 'editnotice-notext' );
2793  if ( !$msg->isDisabled() ) {
2794  $wgOut->addHTML(
2795  '<div class="mw-editnotice-notext">'
2796  . $msg->parseAsBlock()
2797  . '</div>'
2798  );
2799  }
2800  }
2801 
2802  if ( $this->isConflict ) {
2803  $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2804  $this->editRevId = $this->page->getLatest();
2805  } else {
2806  if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2807  // We use $this->section to much before this and getVal('wgSection') directly in other places
2808  // at this point we can't reset $this->section to '' to fallback to non-section editing.
2809  // Someone is welcome to try refactoring though
2810  $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2811  return false;
2812  }
2813 
2814  if ( $this->section != '' && $this->section != 'new' ) {
2815  if ( !$this->summary && !$this->preview && !$this->diff ) {
2816  $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
2817  if ( $sectionTitle !== false ) {
2818  $this->summary = "/* $sectionTitle */ ";
2819  }
2820  }
2821  }
2822 
2823  if ( $this->missingComment ) {
2824  $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2825  }
2826 
2827  if ( $this->missingSummary && $this->section != 'new' ) {
2828  $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2829  }
2830 
2831  if ( $this->missingSummary && $this->section == 'new' ) {
2832  $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2833  }
2834 
2835  if ( $this->blankArticle ) {
2836  $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2837  }
2838 
2839  if ( $this->selfRedirect ) {
2840  $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2841  }
2842 
2843  if ( $this->hookError !== '' ) {
2844  $wgOut->addWikiText( $this->hookError );
2845  }
2846 
2847  if ( !$this->checkUnicodeCompliantBrowser() ) {
2848  $wgOut->addWikiMsg( 'nonunicodebrowser' );
2849  }
2850 
2851  if ( $this->section != 'new' ) {
2852  $revision = $this->mArticle->getRevisionFetched();
2853  if ( $revision ) {
2854  // Let sysop know that this will make private content public if saved
2855 
2856  if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2857  $wgOut->wrapWikiMsg(
2858  "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2859  'rev-deleted-text-permission'
2860  );
2861  } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2862  $wgOut->wrapWikiMsg(
2863  "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2864  'rev-deleted-text-view'
2865  );
2866  }
2867 
2868  if ( !$revision->isCurrent() ) {
2869  $this->mArticle->setOldSubtitle( $revision->getId() );
2870  $wgOut->addWikiMsg( 'editingold' );
2871  }
2872  } elseif ( $this->mTitle->exists() ) {
2873  // Something went wrong
2874 
2875  $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2876  [ 'missing-revision', $this->oldid ] );
2877  }
2878  }
2879  }
2880 
2881  if ( wfReadOnly() ) {
2882  $wgOut->wrapWikiMsg(
2883  "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2884  [ 'readonlywarning', wfReadOnlyReason() ]
2885  );
2886  } elseif ( $wgUser->isAnon() ) {
2887  if ( $this->formtype != 'preview' ) {
2888  $wgOut->wrapWikiMsg(
2889  "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
2890  [ 'anoneditwarning',
2891  // Log-in link
2892  SpecialPage::getTitleFor( 'Userlogin' )->getFullURL( [
2893  'returnto' => $this->getTitle()->getPrefixedDBkey()
2894  ] ),
2895  // Sign-up link
2896  SpecialPage::getTitleFor( 'CreateAccount' )->getFullURL( [
2897  'returnto' => $this->getTitle()->getPrefixedDBkey()
2898  ] )
2899  ]
2900  );
2901  } else {
2902  $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
2903  'anonpreviewwarning'
2904  );
2905  }
2906  } else {
2907  if ( $this->isCssJsSubpage ) {
2908  # Check the skin exists
2909  if ( $this->isWrongCaseCssJsPage ) {
2910  $wgOut->wrapWikiMsg(
2911  "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2912  [ 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ]
2913  );
2914  }
2915  if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
2916  if ( $this->formtype !== 'preview' ) {
2917  if ( $this->isCssSubpage && $wgAllowUserCss ) {
2918  $wgOut->wrapWikiMsg(
2919  "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2920  [ 'usercssyoucanpreview' ]
2921  );
2922  }
2923 
2924  if ( $this->isJsSubpage && $wgAllowUserJs ) {
2925  $wgOut->wrapWikiMsg(
2926  "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2927  [ 'userjsyoucanpreview' ]
2928  );
2929  }
2930  }
2931  }
2932  }
2933  }
2934 
2935  if ( $this->mTitle->isProtected( 'edit' ) &&
2936  MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== [ '' ]
2937  ) {
2938  # Is the title semi-protected?
2939  if ( $this->mTitle->isSemiProtected() ) {
2940  $noticeMsg = 'semiprotectedpagewarning';
2941  } else {
2942  # Then it must be protected based on static groups (regular)
2943  $noticeMsg = 'protectedpagewarning';
2944  }
2945  LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2946  [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
2947  }
2948  if ( $this->mTitle->isCascadeProtected() ) {
2949  # Is this page under cascading protection from some source pages?
2950 
2951  list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2952  $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2953  $cascadeSourcesCount = count( $cascadeSources );
2954  if ( $cascadeSourcesCount > 0 ) {
2955  # Explain, and list the titles responsible
2956  foreach ( $cascadeSources as $page ) {
2957  $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2958  }
2959  }
2960  $notice .= '</div>';
2961  $wgOut->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
2962  }
2963  if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2964  LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2965  [ 'lim' => 1,
2966  'showIfEmpty' => false,
2967  'msgKey' => [ 'titleprotectedwarning' ],
2968  'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
2969  }
2970 
2971  if ( $this->contentLength === false ) {
2972  $this->contentLength = strlen( $this->textbox1 );
2973  }
2974 
2975  if ( $this->tooBig || $this->contentLength > $wgMaxArticleSize * 1024 ) {
2976  $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2977  [
2978  'longpageerror',
2979  $wgLang->formatNum( round( $this->contentLength / 1024, 3 ) ),
2980  $wgLang->formatNum( $wgMaxArticleSize )
2981  ]
2982  );
2983  } else {
2984  if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2985  $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2986  [
2987  'longpage-hint',
2988  $wgLang->formatSize( strlen( $this->textbox1 ) ),
2989  strlen( $this->textbox1 )
2990  ]
2991  );
2992  }
2993  }
2994  # Add header copyright warning
2995  $this->showHeaderCopyrightWarning();
2996 
2997  return true;
2998  }
2999 
3014  function getSummaryInput( $summary = "", $labelText = null,
3015  $inputAttrs = null, $spanLabelAttrs = null
3016  ) {
3017  // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
3018  $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : [] ) + [
3019  'id' => 'wpSummary',
3020  'maxlength' => '200',
3021  'tabindex' => '1',
3022  'size' => 60,
3023  'spellcheck' => 'true',
3024  ] + Linker::tooltipAndAccesskeyAttribs( 'summary' );
3025 
3026  $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : [] ) + [
3027  'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
3028  'id' => "wpSummaryLabel"
3029  ];
3030 
3031  $label = null;
3032  if ( $labelText ) {
3033  $label = Xml::tags(
3034  'label',
3035  $inputAttrs['id'] ? [ 'for' => $inputAttrs['id'] ] : null,
3036  $labelText
3037  );
3038  $label = Xml::tags( 'span', $spanLabelAttrs, $label );
3039  }
3040 
3041  $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
3042 
3043  return [ $label, $input ];
3044  }
3045 
3052  protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3053  global $wgOut;
3054  # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3055  $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
3056  if ( $isSubjectPreview ) {
3057  if ( $this->nosummary ) {
3058  return;
3059  }
3060  } else {
3061  if ( !$this->mShowSummaryField ) {
3062  return;
3063  }
3064  }
3065  $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
3066  list( $label, $input ) = $this->getSummaryInput(
3067  $summary,
3068  $labelText,
3069  [ 'class' => $summaryClass ],
3070  []
3071  );
3072  $wgOut->addHTML( "{$label} {$input}" );
3073  }
3074 
3082  protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3083  // avoid spaces in preview, gets always trimmed on save
3084  $summary = trim( $summary );
3085  if ( !$summary || ( !$this->preview && !$this->diff ) ) {
3086  return "";
3087  }
3088 
3089  global $wgParser;
3090 
3091  if ( $isSubjectPreview ) {
3092  $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
3093  ->inContentLanguage()->text();
3094  }
3095 
3096  $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
3097 
3098  $summary = wfMessage( $message )->parse()
3099  . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
3100  return Xml::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3101  }
3102 
3103  protected function showFormBeforeText() {
3104  global $wgOut;
3105  $section = htmlspecialchars( $this->section );
3106  $wgOut->addHTML( <<<HTML
3107 <input type='hidden' value="{$section}" name="wpSection"/>
3108 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
3109 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
3110 <input type='hidden' value="{$this->editRevId}" name="editRevId" />
3111 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
3112 
3113 HTML
3114  );
3115  if ( !$this->checkUnicodeCompliantBrowser() ) {
3116  $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
3117  }
3118  }
3119 
3120  protected function showFormAfterText() {
3134  $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
3135  }
3136 
3145  protected function showContentForm() {
3146  $this->showTextbox1();
3147  }
3148 
3157  protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3158  if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
3159  $attribs = [ 'style' => 'display:none;' ];
3160  } else {
3161  $classes = []; // Textarea CSS
3162  if ( $this->mTitle->isProtected( 'edit' ) &&
3163  MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== [ '' ]
3164  ) {
3165  # Is the title semi-protected?
3166  if ( $this->mTitle->isSemiProtected() ) {
3167  $classes[] = 'mw-textarea-sprotected';
3168  } else {
3169  # Then it must be protected based on static groups (regular)
3170  $classes[] = 'mw-textarea-protected';
3171  }
3172  # Is the title cascade-protected?
3173  if ( $this->mTitle->isCascadeProtected() ) {
3174  $classes[] = 'mw-textarea-cprotected';
3175  }
3176  }
3177 
3178  $attribs = [ 'tabindex' => 1 ];
3179 
3180  if ( is_array( $customAttribs ) ) {
3182  }
3183 
3184  if ( count( $classes ) ) {
3185  if ( isset( $attribs['class'] ) ) {
3186  $classes[] = $attribs['class'];
3187  }
3188  $attribs['class'] = implode( ' ', $classes );
3189  }
3190  }
3191 
3192  $this->showTextbox(
3193  $textoverride !== null ? $textoverride : $this->textbox1,
3194  'wpTextbox1',
3195  $attribs
3196  );
3197  }
3198 
3199  protected function showTextbox2() {
3200  $this->showTextbox( $this->textbox2, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3201  }
3202 
3203  protected function showTextbox( $text, $name, $customAttribs = [] ) {
3205 
3206  $wikitext = $this->safeUnicodeOutput( $text );
3207  if ( strval( $wikitext ) !== '' ) {
3208  // Ensure there's a newline at the end, otherwise adding lines
3209  // is awkward.
3210  // But don't add a newline if the ext is empty, or Firefox in XHTML
3211  // mode will show an extra newline. A bit annoying.
3212  $wikitext .= "\n";
3213  }
3214 
3215  $attribs = $customAttribs + [
3216  'accesskey' => ',',
3217  'id' => $name,
3218  'cols' => $wgUser->getIntOption( 'cols' ),
3219  'rows' => $wgUser->getIntOption( 'rows' ),
3220  // Avoid PHP notices when appending preferences
3221  // (appending allows customAttribs['style'] to still work).
3222  'style' => ''
3223  ];
3224 
3225  $pageLang = $this->mTitle->getPageLanguage();
3226  $attribs['lang'] = $pageLang->getHtmlCode();
3227  $attribs['dir'] = $pageLang->getDir();
3228 
3229  $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
3230  }
3231 
3232  protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3233  global $wgOut;
3234  $classes = [];
3235  if ( $isOnTop ) {
3236  $classes[] = 'ontop';
3237  }
3238 
3239  $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3240 
3241  if ( $this->formtype != 'preview' ) {
3242  $attribs['style'] = 'display: none;';
3243  }
3244 
3245  $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
3246 
3247  if ( $this->formtype == 'preview' ) {
3248  $this->showPreview( $previewOutput );
3249  } else {
3250  // Empty content container for LivePreview
3251  $pageViewLang = $this->mTitle->getPageViewLanguage();
3252  $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3253  'class' => 'mw-content-' . $pageViewLang->getDir() ];
3254  $wgOut->addHTML( Html::rawElement( 'div', $attribs ) );
3255  }
3256 
3257  $wgOut->addHTML( '</div>' );
3258 
3259  if ( $this->formtype == 'diff' ) {
3260  try {
3261  $this->showDiff();
3262  } catch ( MWContentSerializationException $ex ) {
3263  $msg = wfMessage(
3264  'content-failed-to-parse',
3265  $this->contentModel,
3266  $this->contentFormat,
3267  $ex->getMessage()
3268  );
3269  $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3270  }
3271  }
3272  }
3273 
3280  protected function showPreview( $text ) {
3281  global $wgOut;
3282  if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3283  $this->mArticle->openShowCategory();
3284  }
3285  # This hook seems slightly odd here, but makes things more
3286  # consistent for extensions.
3287  Hooks::run( 'OutputPageBeforeHTML', [ &$wgOut, &$text ] );
3288  $wgOut->addHTML( $text );
3289  if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3290  $this->mArticle->closeShowCategory();
3291  }
3292  }
3293 
3301  function showDiff() {
3303 
3304  $oldtitlemsg = 'currentrev';
3305  # if message does not exist, show diff against the preloaded default
3306  if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3307  $oldtext = $this->mTitle->getDefaultMessageText();
3308  if ( $oldtext !== false ) {
3309  $oldtitlemsg = 'defaultmessagetext';
3310  $oldContent = $this->toEditContent( $oldtext );
3311  } else {
3312  $oldContent = null;
3313  }
3314  } else {
3315  $oldContent = $this->getCurrentContent();
3316  }
3317 
3318  $textboxContent = $this->toEditContent( $this->textbox1 );
3319  if ( $this->editRevId !== null ) {
3320  $newContent = $this->page->replaceSectionAtRev(
3321  $this->section, $textboxContent, $this->summary, $this->editRevId
3322  );
3323  } else {
3324  $newContent = $this->page->replaceSectionContent(
3325  $this->section, $textboxContent, $this->summary, $this->edittime
3326  );
3327  }
3328 
3329  if ( $newContent ) {
3330  ContentHandler::runLegacyHooks( 'EditPageGetDiffText', [ $this, &$newContent ] );
3331  Hooks::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3332 
3333  $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
3334  $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
3335  }
3336 
3337  if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3338  $oldtitle = wfMessage( $oldtitlemsg )->parse();
3339  $newtitle = wfMessage( 'yourtext' )->parse();
3340 
3341  if ( !$oldContent ) {
3342  $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3343  }
3344 
3345  if ( !$newContent ) {
3346  $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3347  }
3348 
3349  $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
3350  $de->setContent( $oldContent, $newContent );
3351 
3352  $difftext = $de->getDiff( $oldtitle, $newtitle );
3353  $de->showDiffStyle();
3354  } else {
3355  $difftext = '';
3356  }
3357 
3358  $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3359  }
3360 
3364  protected function showHeaderCopyrightWarning() {
3365  $msg = 'editpage-head-copy-warn';
3366  if ( !wfMessage( $msg )->isDisabled() ) {
3367  global $wgOut;
3368  $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3369  'editpage-head-copy-warn' );
3370  }
3371  }
3372 
3381  protected function showTosSummary() {
3382  $msg = 'editpage-tos-summary';
3383  Hooks::run( 'EditPageTosSummary', [ $this->mTitle, &$msg ] );
3384  if ( !wfMessage( $msg )->isDisabled() ) {
3385  global $wgOut;
3386  $wgOut->addHTML( '<div class="mw-tos-summary">' );
3387  $wgOut->addWikiMsg( $msg );
3388  $wgOut->addHTML( '</div>' );
3389  }
3390  }
3391 
3392  protected function showEditTools() {
3393  global $wgOut;
3394  $wgOut->addHTML( '<div class="mw-editTools">' .
3395  wfMessage( 'edittools' )->inContentLanguage()->parse() .
3396  '</div>' );
3397  }
3398 
3405  protected function getCopywarn() {
3406  return self::getCopyrightWarning( $this->mTitle );
3407  }
3408 
3416  public static function getCopyrightWarning( $title, $format = 'plain' ) {
3418  if ( $wgRightsText ) {
3419  $copywarnMsg = [ 'copyrightwarning',
3420  '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3421  $wgRightsText ];
3422  } else {
3423  $copywarnMsg = [ 'copyrightwarning2',
3424  '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3425  }
3426  // Allow for site and per-namespace customization of contribution/copyright notice.
3427  Hooks::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3428 
3429  return "<div id=\"editpage-copywarn\">\n" .
3430  call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3431  }
3432 
3440  public static function getPreviewLimitReport( $output ) {
3441  if ( !$output || !$output->getLimitReportData() ) {
3442  return '';
3443  }
3444 
3445  $limitReport = Html::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3446  wfMessage( 'limitreport-title' )->parseAsBlock()
3447  );
3448 
3449  // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3450  $limitReport .= Html::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3451 
3452  $limitReport .= Html::openElement( 'table', [
3453  'class' => 'preview-limit-report wikitable'
3454  ] ) .
3455  Html::openElement( 'tbody' );
3456 
3457  foreach ( $output->getLimitReportData() as $key => $value ) {
3458  if ( Hooks::run( 'ParserLimitReportFormat',
3459  [ $key, &$value, &$limitReport, true, true ]
3460  ) ) {
3461  $keyMsg = wfMessage( $key );
3462  $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3463  if ( !$valueMsg->exists() ) {
3464  $valueMsg = new RawMessage( '$1' );
3465  }
3466  if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3467  $limitReport .= Html::openElement( 'tr' ) .
3468  Html::rawElement( 'th', null, $keyMsg->parse() ) .
3469  Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3470  Html::closeElement( 'tr' );
3471  }
3472  }
3473  }
3474 
3475  $limitReport .= Html::closeElement( 'tbody' ) .
3476  Html::closeElement( 'table' ) .
3477  Html::closeElement( 'div' );
3478 
3479  return $limitReport;
3480  }
3481 
3482  protected function showStandardInputs( &$tabindex = 2 ) {
3483  global $wgOut;
3484  $wgOut->addHTML( "<div class='editOptions'>\n" );
3485 
3486  if ( $this->section != 'new' ) {
3487  $this->showSummaryInput( false, $this->summary );
3488  $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3489  }
3490 
3491  $checkboxes = $this->getCheckboxes( $tabindex,
3492  [ 'minor' => $this->minoredit, 'watch' => $this->watchthis ] );
3493  $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3494 
3495  // Show copyright warning.
3496  $wgOut->addWikiText( $this->getCopywarn() );
3497  $wgOut->addHTML( $this->editFormTextAfterWarn );
3498 
3499  $wgOut->addHTML( "<div class='editButtons'>\n" );
3500  $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3501 
3502  $cancel = $this->getCancelLink();
3503  if ( $cancel !== '' ) {
3504  $cancel .= Html::element( 'span',
3505  [ 'class' => 'mw-editButtons-pipe-separator' ],
3506  wfMessage( 'pipe-separator' )->text() );
3507  }
3508 
3509  $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3510  $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3511  $attrs = [
3512  'target' => 'helpwindow',
3513  'href' => $edithelpurl,
3514  ];
3515  $edithelp = Html::linkButton( wfMessage( 'edithelp' )->text(),
3516  $attrs, [ 'mw-ui-quiet' ] ) .
3517  wfMessage( 'word-separator' )->escaped() .
3518  wfMessage( 'newwindow' )->parse();
3519 
3520  $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3521  $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3522  $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3523 
3524  Hooks::run( 'EditPage::showStandardInputs:options', [ $this, $wgOut, &$tabindex ] );
3525 
3526  $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3527  }
3528 
3533  protected function showConflict() {
3534  global $wgOut;
3535 
3536  if ( Hooks::run( 'EditPageBeforeConflictDiff', [ &$this, &$wgOut ] ) ) {
3537  $stats = $wgOut->getContext()->getStats();
3538  $stats->increment( 'edit.failures.conflict' );
3539  // Only include 'standard' namespaces to avoid creating unknown numbers of statsd metrics
3540  if (
3541  $this->mTitle->getNamespace() >= NS_MAIN &&
3542  $this->mTitle->getNamespace() <= NS_CATEGORY_TALK
3543  ) {
3544  $stats->increment( 'edit.failures.conflict.byNamespaceId.' . $this->mTitle->getNamespace() );
3545  }
3546 
3547  $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3548 
3549  $content1 = $this->toEditContent( $this->textbox1 );
3550  $content2 = $this->toEditContent( $this->textbox2 );
3551 
3552  $handler = ContentHandler::getForModelID( $this->contentModel );
3553  $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3554  $de->setContent( $content2, $content1 );
3555  $de->showDiff(
3556  wfMessage( 'yourtext' )->parse(),
3557  wfMessage( 'storedversion' )->text()
3558  );
3559 
3560  $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3561  $this->showTextbox2();
3562  }
3563  }
3564 
3568  public function getCancelLink() {
3569  $cancelParams = [];
3570  if ( !$this->isConflict && $this->oldid > 0 ) {
3571  $cancelParams['oldid'] = $this->oldid;
3572  } elseif ( $this->getContextTitle()->isRedirect() ) {
3573  $cancelParams['redirect'] = 'no';
3574  }
3575  $attrs = [ 'id' => 'mw-editform-cancel' ];
3576 
3577  return Linker::linkKnown(
3578  $this->getContextTitle(),
3579  wfMessage( 'cancel' )->parse(),
3580  Html::buttonAttributes( $attrs, [ 'mw-ui-quiet' ] ),
3581  $cancelParams
3582  );
3583  }
3584 
3594  protected function getActionURL( Title $title ) {
3595  return $title->getLocalURL( [ 'action' => $this->action ] );
3596  }
3597 
3605  protected function wasDeletedSinceLastEdit() {
3606  if ( $this->deletedSinceEdit !== null ) {
3607  return $this->deletedSinceEdit;
3608  }
3609 
3610  $this->deletedSinceEdit = false;
3611 
3612  if ( !$this->mTitle->exists() && $this->mTitle->isDeletedQuick() ) {
3613  $this->lastDelete = $this->getLastDelete();
3614  if ( $this->lastDelete ) {
3615  $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3616  if ( $deleteTime > $this->starttime ) {
3617  $this->deletedSinceEdit = true;
3618  }
3619  }
3620  }
3621 
3622  return $this->deletedSinceEdit;
3623  }
3624 
3628  protected function getLastDelete() {
3629  $dbr = wfGetDB( DB_SLAVE );
3630  $data = $dbr->selectRow(
3631  [ 'logging', 'user' ],
3632  [
3633  'log_type',
3634  'log_action',
3635  'log_timestamp',
3636  'log_user',
3637  'log_namespace',
3638  'log_title',
3639  'log_comment',
3640  'log_params',
3641  'log_deleted',
3642  'user_name'
3643  ], [
3644  'log_namespace' => $this->mTitle->getNamespace(),
3645  'log_title' => $this->mTitle->getDBkey(),
3646  'log_type' => 'delete',
3647  'log_action' => 'delete',
3648  'user_id=log_user'
3649  ],
3650  __METHOD__,
3651  [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ]
3652  );
3653  // Quick paranoid permission checks...
3654  if ( is_object( $data ) ) {
3655  if ( $data->log_deleted & LogPage::DELETED_USER ) {
3656  $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
3657  }
3658 
3659  if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3660  $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
3661  }
3662  }
3663 
3664  return $data;
3665  }
3666 
3672  function getPreviewText() {
3675 
3676  $stats = $wgOut->getContext()->getStats();
3677 
3678  if ( $wgRawHtml && !$this->mTokenOk ) {
3679  // Could be an offsite preview attempt. This is very unsafe if
3680  // HTML is enabled, as it could be an attack.
3681  $parsedNote = '';
3682  if ( $this->textbox1 !== '' ) {
3683  // Do not put big scary notice, if previewing the empty
3684  // string, which happens when you initially edit
3685  // a category page, due to automatic preview-on-open.
3686  $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3687  wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3688  }
3689  $stats->increment( 'edit.failures.session_loss' );
3690  return $parsedNote;
3691  }
3692 
3693  $note = '';
3694 
3695  try {
3696  $content = $this->toEditContent( $this->textbox1 );
3697 
3698  $previewHTML = '';
3699  if ( !Hooks::run(
3700  'AlternateEditPreview',
3701  [ $this, &$content, &$previewHTML, &$this->mParserOutput ] )
3702  ) {
3703  return $previewHTML;
3704  }
3705 
3706  # provide a anchor link to the editform
3707  $continueEditing = '<span class="mw-continue-editing">' .
3708  '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3709  wfMessage( 'continue-editing' )->text() . ']]</span>';
3710  if ( $this->mTriedSave && !$this->mTokenOk ) {
3711  if ( $this->mTokenOkExceptSuffix ) {
3712  $note = wfMessage( 'token_suffix_mismatch' )->plain();
3713  $stats->increment( 'edit.failures.bad_token' );
3714  } else {
3715  $note = wfMessage( 'session_fail_preview' )->plain();
3716  $stats->increment( 'edit.failures.session_loss' );
3717  }
3718  } elseif ( $this->incompleteForm ) {
3719  $note = wfMessage( 'edit_form_incomplete' )->plain();
3720  if ( $this->mTriedSave ) {
3721  $stats->increment( 'edit.failures.incomplete_form' );
3722  }
3723  } else {
3724  $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3725  }
3726 
3727  # don't parse non-wikitext pages, show message about preview
3728  if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3729  if ( $this->mTitle->isCssJsSubpage() ) {
3730  $level = 'user';
3731  } elseif ( $this->mTitle->isCssOrJsPage() ) {
3732  $level = 'site';
3733  } else {
3734  $level = false;
3735  }
3736 
3737  if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3738  $format = 'css';
3739  if ( $level === 'user' && !$wgAllowUserCss ) {
3740  $format = false;
3741  }
3742  } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3743  $format = 'js';
3744  if ( $level === 'user' && !$wgAllowUserJs ) {
3745  $format = false;
3746  }
3747  } else {
3748  $format = false;
3749  }
3750 
3751  # Used messages to make sure grep find them:
3752  # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3753  if ( $level && $format ) {
3754  $note = "<div id='mw-{$level}{$format}preview'>" .
3755  wfMessage( "{$level}{$format}preview" )->text() .
3756  ' ' . $continueEditing . "</div>";
3757  }
3758  }
3759 
3760  # If we're adding a comment, we need to show the
3761  # summary as the headline
3762  if ( $this->section === "new" && $this->summary !== "" ) {
3763  $content = $content->addSectionHeader( $this->summary );
3764  }
3765 
3766  $hook_args = [ $this, &$content ];
3767  ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3768  Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3769 
3770  $parserResult = $this->doPreviewParse( $content );
3771  $parserOutput = $parserResult['parserOutput'];
3772  $previewHTML = $parserResult['html'];
3773  $this->mParserOutput = $parserOutput;
3774  $wgOut->addParserOutputMetadata( $parserOutput );
3775 
3776  if ( count( $parserOutput->getWarnings() ) ) {
3777  $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3778  }
3779 
3780  } catch ( MWContentSerializationException $ex ) {
3781  $m = wfMessage(
3782  'content-failed-to-parse',
3783  $this->contentModel,
3784  $this->contentFormat,
3785  $ex->getMessage()
3786  );
3787  $note .= "\n\n" . $m->parse();
3788  $previewHTML = '';
3789  }
3790 
3791  if ( $this->isConflict ) {
3792  $conflict = '<h2 id="mw-previewconflict">'
3793  . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3794  } else {
3795  $conflict = '<hr />';
3796  }
3797 
3798  $previewhead = "<div class='previewnote'>\n" .
3799  '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3800  $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3801 
3802  $pageViewLang = $this->mTitle->getPageViewLanguage();
3803  $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3804  'class' => 'mw-content-' . $pageViewLang->getDir() ];
3805  $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3806 
3807  return $previewhead . $previewHTML . $this->previewTextAfterContent;
3808  }
3809 
3814  protected function getPreviewParserOptions() {
3815  $parserOptions = $this->page->makeParserOptions( $this->mArticle->getContext() );
3816  $parserOptions->setIsPreview( true );
3817  $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3818  $parserOptions->enableLimitReport();
3819  return $parserOptions;
3820  }
3821 
3831  protected function doPreviewParse( Content $content ) {
3832  global $wgUser;
3833  $parserOptions = $this->getPreviewParserOptions();
3834  $pstContent = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3835  $scopedCallback = $parserOptions->setupFakeRevision(
3836  $this->mTitle, $pstContent, $wgUser );
3837  $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
3838  ScopedCallback::consume( $scopedCallback );
3839  $parserOutput->setEditSectionTokens( false ); // no section edit links
3840  return [
3841  'parserOutput' => $parserOutput,
3842  'html' => $parserOutput->getText() ];
3843  }
3844 
3848  function getTemplates() {
3849  if ( $this->preview || $this->section != '' ) {
3850  $templates = [];
3851  if ( !isset( $this->mParserOutput ) ) {
3852  return $templates;
3853  }
3854  foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3855  foreach ( array_keys( $template ) as $dbk ) {
3856  $templates[] = Title::makeTitle( $ns, $dbk );
3857  }
3858  }
3859  return $templates;
3860  } else {
3861  return $this->mTitle->getTemplateLinksFrom();
3862  }
3863  }
3864 
3872  static function getEditToolbar( $title = null ) {
3875 
3876  $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3877  $showSignature = true;
3878  if ( $title ) {
3879  $showSignature = MWNamespace::wantSignatures( $title->getNamespace() );
3880  }
3881 
3891  $toolarray = [
3892  [
3893  'id' => 'mw-editbutton-bold',
3894  'open' => '\'\'\'',
3895  'close' => '\'\'\'',
3896  'sample' => wfMessage( 'bold_sample' )->text(),
3897  'tip' => wfMessage( 'bold_tip' )->text(),
3898  ],
3899  [
3900  'id' => 'mw-editbutton-italic',
3901  'open' => '\'\'',
3902  'close' => '\'\'',
3903  'sample' => wfMessage( 'italic_sample' )->text(),
3904  'tip' => wfMessage( 'italic_tip' )->text(),
3905  ],
3906  [
3907  'id' => 'mw-editbutton-link',
3908  'open' => '[[',
3909  'close' => ']]',
3910  'sample' => wfMessage( 'link_sample' )->text(),
3911  'tip' => wfMessage( 'link_tip' )->text(),
3912  ],
3913  [
3914  'id' => 'mw-editbutton-extlink',
3915  'open' => '[',
3916  'close' => ']',
3917  'sample' => wfMessage( 'extlink_sample' )->text(),
3918  'tip' => wfMessage( 'extlink_tip' )->text(),
3919  ],
3920  [
3921  'id' => 'mw-editbutton-headline',
3922  'open' => "\n== ",
3923  'close' => " ==\n",
3924  'sample' => wfMessage( 'headline_sample' )->text(),
3925  'tip' => wfMessage( 'headline_tip' )->text(),
3926  ],
3927  $imagesAvailable ? [
3928  'id' => 'mw-editbutton-image',
3929  'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3930  'close' => ']]',
3931  'sample' => wfMessage( 'image_sample' )->text(),
3932  'tip' => wfMessage( 'image_tip' )->text(),
3933  ] : false,
3934  $imagesAvailable ? [
3935  'id' => 'mw-editbutton-media',
3936  'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3937  'close' => ']]',
3938  'sample' => wfMessage( 'media_sample' )->text(),
3939  'tip' => wfMessage( 'media_tip' )->text(),
3940  ] : false,
3941  [
3942  'id' => 'mw-editbutton-nowiki',
3943  'open' => "<nowiki>",
3944  'close' => "</nowiki>",
3945  'sample' => wfMessage( 'nowiki_sample' )->text(),
3946  'tip' => wfMessage( 'nowiki_tip' )->text(),
3947  ],
3948  $showSignature ? [
3949  'id' => 'mw-editbutton-signature',
3950  'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
3951  'close' => '',
3952  'sample' => '',
3953  'tip' => wfMessage( 'sig_tip' )->text(),
3954  ] : false,
3955  [
3956  'id' => 'mw-editbutton-hr',
3957  'open' => "\n----\n",
3958  'close' => '',
3959  'sample' => '',
3960  'tip' => wfMessage( 'hr_tip' )->text(),
3961  ]
3962  ];
3963 
3964  $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3965  foreach ( $toolarray as $tool ) {
3966  if ( !$tool ) {
3967  continue;
3968  }
3969 
3970  $params = [
3971  // Images are defined in ResourceLoaderEditToolbarModule
3972  false,
3973  // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3974  // Older browsers show a "speedtip" type message only for ALT.
3975  // Ideally these should be different, realistically they
3976  // probably don't need to be.
3977  $tool['tip'],
3978  $tool['open'],
3979  $tool['close'],
3980  $tool['sample'],
3981  $tool['id'],
3982  ];
3983 
3984  $script .= Xml::encodeJsCall(
3985  'mw.toolbar.addButton',
3986  $params,
3988  );
3989  }
3990 
3991  $script .= '});';
3992  $wgOut->addScript( ResourceLoader::makeInlineScript( $script ) );
3993 
3994  $toolbar = '<div id="toolbar"></div>';
3995 
3996  Hooks::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] );
3997 
3998  return $toolbar;
3999  }
4000 
4011  public function getCheckboxes( &$tabindex, $checked ) {
4013 
4014  $checkboxes = [];
4015 
4016  // don't show the minor edit checkbox if it's a new page or section
4017  if ( !$this->isNew ) {
4018  $checkboxes['minor'] = '';
4019  $minorLabel = wfMessage( 'minoredit' )->parse();
4020  if ( $wgUser->isAllowed( 'minoredit' ) ) {
4021  $attribs = [
4022  'tabindex' => ++$tabindex,
4023  'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
4024  'id' => 'wpMinoredit',
4025  ];
4026  $minorEditHtml =
4027  Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
4028  "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
4029  Xml::expandAttributes( [ 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ] ) .
4030  ">{$minorLabel}</label>";
4031 
4032  if ( $wgUseMediaWikiUIEverywhere ) {
4033  $checkboxes['minor'] = Html::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
4034  $minorEditHtml .
4035  Html::closeElement( 'div' );
4036  } else {
4037  $checkboxes['minor'] = $minorEditHtml;
4038  }
4039  }
4040  }
4041 
4042  $watchLabel = wfMessage( 'watchthis' )->parse();
4043  $checkboxes['watch'] = '';
4044  if ( $wgUser->isLoggedIn() ) {
4045  $attribs = [
4046  'tabindex' => ++$tabindex,
4047  'accesskey' => wfMessage( 'accesskey-watch' )->text(),
4048  'id' => 'wpWatchthis',
4049  ];
4050  $watchThisHtml =
4051  Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
4052  "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
4053  Xml::expandAttributes( [ 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ] ) .
4054  ">{$watchLabel}</label>";
4055  if ( $wgUseMediaWikiUIEverywhere ) {
4056  $checkboxes['watch'] = Html::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
4057  $watchThisHtml .
4058  Html::closeElement( 'div' );
4059  } else {
4060  $checkboxes['watch'] = $watchThisHtml;
4061  }
4062  }
4063  Hooks::run( 'EditPageBeforeEditChecks', [ &$this, &$checkboxes, &$tabindex ] );
4064  return $checkboxes;
4065  }
4066 
4075  public function getEditButtons( &$tabindex ) {
4076  $buttons = [];
4077 
4078  $attribs = [
4079  'id' => 'wpSave',
4080  'name' => 'wpSave',
4081  'tabindex' => ++$tabindex,
4082  ] + Linker::tooltipAndAccesskeyAttribs( 'save' );
4083  $buttons['save'] = Html::submitButton( wfMessage( 'savearticle' )->text(),
4084  $attribs, [ 'mw-ui-constructive' ] );
4085 
4086  ++$tabindex; // use the same for preview and live preview
4087  $attribs = [
4088  'id' => 'wpPreview',
4089  'name' => 'wpPreview',
4090  'tabindex' => $tabindex,
4091  ] + Linker::tooltipAndAccesskeyAttribs( 'preview' );
4092  $buttons['preview'] = Html::submitButton( wfMessage( 'showpreview' )->text(),
4093  $attribs );
4094  $buttons['live'] = '';
4095 
4096  $attribs = [
4097  'id' => 'wpDiff',
4098  'name' => 'wpDiff',
4099  'tabindex' => ++$tabindex,
4100  ] + Linker::tooltipAndAccesskeyAttribs( 'diff' );
4101  $buttons['diff'] = Html::submitButton( wfMessage( 'showdiff' )->text(),
4102  $attribs );
4103 
4104  Hooks::run( 'EditPageBeforeEditButtons', [ &$this, &$buttons, &$tabindex ] );
4105  return $buttons;
4106  }
4107 
4112  function noSuchSectionPage() {
4113  global $wgOut;
4114 
4115  $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
4116 
4117  $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
4118  Hooks::run( 'EditPageNoSuchSection', [ &$this, &$res ] );
4119  $wgOut->addHTML( $res );
4120 
4121  $wgOut->returnToMain( false, $this->mTitle );
4122  }
4123 
4129  public function spamPageWithContent( $match = false ) {
4131  $this->textbox2 = $this->textbox1;
4132 
4133  if ( is_array( $match ) ) {
4134  $match = $wgLang->listToText( $match );
4135  }
4136  $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
4137 
4138  $wgOut->addHTML( '<div id="spamprotected">' );
4139  $wgOut->addWikiMsg( 'spamprotectiontext' );
4140  if ( $match ) {
4141  $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4142  }
4143  $wgOut->addHTML( '</div>' );
4144 
4145  $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4146  $this->showDiff();
4147 
4148  $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4149  $this->showTextbox2();
4150 
4151  $wgOut->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4152  }
4153 
4160  private function checkUnicodeCompliantBrowser() {
4162 
4163  $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
4164  if ( $currentbrowser === false ) {
4165  // No User-Agent header sent? Trust it by default...
4166  return true;
4167  }
4168 
4169  foreach ( $wgBrowserBlackList as $browser ) {
4170  if ( preg_match( $browser, $currentbrowser ) ) {
4171  return false;
4172  }
4173  }
4174  return true;
4175  }
4176 
4185  protected function safeUnicodeInput( $request, $field ) {
4186  $text = rtrim( $request->getText( $field ) );
4187  return $request->getBool( 'safemode' )
4188  ? $this->unmakeSafe( $text )
4189  : $text;
4190  }
4191 
4199  protected function safeUnicodeOutput( $text ) {
4200  return $this->checkUnicodeCompliantBrowser()
4201  ? $text
4202  : $this->makesafe( $text );
4203  }
4204 
4217  private function makeSafe( $invalue ) {
4218  // Armor existing references for reversibility.
4219  $invalue = strtr( $invalue, [ "&#x" => "&#x0" ] );
4220 
4221  $bytesleft = 0;
4222  $result = "";
4223  $working = 0;
4224  $valueLength = strlen( $invalue );
4225  for ( $i = 0; $i < $valueLength; $i++ ) {
4226  $bytevalue = ord( $invalue[$i] );
4227  if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4228  $result .= chr( $bytevalue );
4229  $bytesleft = 0;
4230  } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4231  $working = $working << 6;
4232  $working += ( $bytevalue & 0x3F );
4233  $bytesleft--;
4234  if ( $bytesleft <= 0 ) {
4235  $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4236  }
4237  } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4238  $working = $bytevalue & 0x1F;
4239  $bytesleft = 1;
4240  } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4241  $working = $bytevalue & 0x0F;
4242  $bytesleft = 2;
4243  } else { // 1111 0xxx
4244  $working = $bytevalue & 0x07;
4245  $bytesleft = 3;
4246  }
4247  }
4248  return $result;
4249  }
4250 
4259  private function unmakeSafe( $invalue ) {
4260  $result = "";
4261  $valueLength = strlen( $invalue );
4262  for ( $i = 0; $i < $valueLength; $i++ ) {
4263  if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
4264  $i += 3;
4265  $hexstring = "";
4266  do {
4267  $hexstring .= $invalue[$i];
4268  $i++;
4269  } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4270 
4271  // Do some sanity checks. These aren't needed for reversibility,
4272  // but should help keep the breakage down if the editor
4273  // breaks one of the entities whilst editing.
4274  if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4275  $codepoint = hexdec( $hexstring );
4276  $result .= UtfNormal\Utils::codepointToUtf8( $codepoint );
4277  } else {
4278  $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4279  }
4280  } else {
4281  $result .= substr( $invalue, $i, 1 );
4282  }
4283  }
4284  // reverse the transform that we made for reversibility reasons.
4285  return strtr( $result, [ "&#x0" => "&#x" ] );
4286  }
4287 }
string $autoSumm
Definition: EditPage.php:285
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:522
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:101
displayPermissionsError(array $permErrors)
Display a permissions error page, like OutputPage::showPermissionsErrorPage(), but with the following...
Definition: EditPage.php:653
$wgForeignFileRepos
makeSafe($invalue)
A number of web browsers are known to corrupt non-ASCII characters in a UTF-8 text editing environmen...
Definition: EditPage.php:4217
const FOR_THIS_USER
Definition: Revision.php:84
bool $nosummary
Definition: EditPage.php:332
static closeElement($element)
Returns "</$element>".
Definition: Html.php:306
$editFormTextBottom
Definition: EditPage.php:382
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
const AS_READ_ONLY_PAGE_ANON
Status: this anonymous user is not allowed to edit this page.
Definition: EditPage.php:74
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
$wgMaxArticleSize
Maximum article size in kilobytes.
bool $missingSummary
Definition: EditPage.php:267
the array() calling protocol came about after MediaWiki 1.4rc1.
bool $bot
Definition: EditPage.php:362
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:1435
string $textbox2
Definition: EditPage.php:326
bool $mTokenOk
Definition: EditPage.php:249
$editFormTextAfterContent
Definition: EditPage.php:383
showContentForm()
Subpage overridable method for printing the form for page content editing By default this simply outp...
Definition: EditPage.php:3145
bool $allowBlankSummary
Definition: EditPage.php:270
getPreviewText()
Get the rendered text for previewing.
Definition: EditPage.php:3672
serialize($format=null)
Convenience method for serializing this Content object.
bool $isConflict
Definition: EditPage.php:219
int $oldid
Definition: EditPage.php:350
const NS_MAIN
Definition: Defines.php:69
static element($element, $attribs=null, $contents= '', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:39
handleStatus(Status $status, $resultDetails)
Handle status, such as after attempt save.
Definition: EditPage.php:1438
string $summary
Definition: EditPage.php:329
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
setHeaders()
Definition: EditPage.php:2268
WikiPage $page
Definition: EditPage.php:207
per default it will return the text for text based content
Show an error when the wiki is locked/read-only and the user tries to do something that requires writ...
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:95
static getTitleFor($name, $subpage=false, $fragment= '')
Get a localised Title object for a specified special page name.
Definition: SpecialPage.php:80
const AS_HOOK_ERROR
Status: Article update aborted by a hook function.
Definition: EditPage.php:54
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1980
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:4185
showTextbox2()
Definition: EditPage.php:3199
bool $tooBig
Definition: EditPage.php:261
$wgParser
Definition: Setup.php:816
static rawElement($element, $attribs=[], $contents= '')
Returns an HTML element in a string.
Definition: Html.php:210
showHeaderCopyrightWarning()
Show the header copyright warning.
Definition: EditPage.php:3364
getPage()
Get the WikiPage object of this instance.
Definition: Article.php:176
getWikiText($shortContext=false, $longContext=false, $lang=null)
Get the error list as a wikitext formatted list.
Definition: Status.php:217
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
static expandAttributes($attribs)
Given an array of ('attributename' => 'value'), it generates the code to set the XML attributes : attr...
Definition: Xml.php:67
showTosSummary()
Give a chance for site and per-namespace customizations of terms of service summary link that might e...
Definition: EditPage.php:3381
The edit page/HTML interface (split from Article) The actual database and text munging is still in Ar...
Definition: EditPage.php:40
Title $mTitle
Definition: EditPage.php:210
static hidden($name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:749
setContextTitle($title)
Set the context Title object.
Definition: EditPage.php:438
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:117
const AS_HOOK_ERROR_EXPECTED
Status: A hook function returned an error.
Definition: EditPage.php:59
Generic operation result class Has warning/error list, boolean status and arbitrary value...
Definition: Status.php:40
getEditButtons(&$tabindex)
Returns an array of html code of the following buttons: save, diff, preview and live.
Definition: EditPage.php:4075
$comment
$wgAllowUserCss
Allow user Cascading Style Sheets (CSS)? This enables a lot of neat customizations, but may increase security risk to users and server load.
static newFromUserAndLang(User $user, Language $lang)
Get a ParserOptions object from a given user and language.
string $editintro
Definition: EditPage.php:356
Class for viewing MediaWiki article and history.
Definition: Article.php:34
null for the local wiki Added in
Definition: hooks.txt:1435
static getSkinNames()
Fetch the set of available skins.
Definition: Skin.php:49
bool $allowBlankArticle
Definition: EditPage.php:276
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function array $article
Definition: hooks.txt:78
$value
Article $mArticle
Definition: EditPage.php:205
null string $contentFormat
Definition: EditPage.php:368
const AS_BLOCKED_PAGE_FOR_USER
Status: User is blocked from editing this page.
Definition: EditPage.php:64
bool $blankArticle
Definition: EditPage.php:273
setPostEditCookie($statusValue)
Sets post-edit cookie indicating the user just saved a particular revision.
Definition: EditPage.php:1394
const AS_NO_CREATE_PERMISSION
Status: user tried to create this page, but is not allowed to do that ( Title->userCan('create') == fa...
Definition: EditPage.php:101
The First
Definition: primes.txt:1
static getPreviewLimitReport($output)
Get the Limit report for page previews.
Definition: EditPage.php:3440
spamPageWithContent($match=false)
Show "your edit contains spam" page with your diff and text.
Definition: EditPage.php:4129
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2588
static getCopyrightWarning($title, $format= 'plain')
Get the copyright warning, by default returns wikitext.
Definition: EditPage.php:3416
bool $missingComment
Definition: EditPage.php:264
const EDIT_MINOR
Definition: Defines.php:181
static check($name, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox.
Definition: Xml.php:324
const POST_EDIT_COOKIE_DURATION
Duration of PostEdit cookie, in seconds.
Definition: EditPage.php:202
const EDIT_UPDATE
Definition: Defines.php:180
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:256
this hook is for auditing only $response
Definition: hooks.txt:776
showFormBeforeText()
Definition: EditPage.php:3103
null means default & $customAttribs
Definition: hooks.txt:1816
internalAttemptSave(&$result, $bot=false)
Attempt submission (no UI)
Definition: EditPage.php:1671
bool stdClass $lastDelete
Definition: EditPage.php:246
Represents a title within MediaWiki.
Definition: Title.php:36
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
wfExpandUrl($url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
$wgRawHtml
Allow raw, unchecked HTML in "<html>...</html>" sections.
static newFromUser($user)
Get a ParserOptions object from a given user.
edit()
This is the function that gets called for "action=edit".
Definition: EditPage.php:495
getContextTitle()
Get the context title object.
Definition: EditPage.php:449
bool $mBaseRevision
Definition: EditPage.php:297
getContentObject($def_content=null)
Definition: EditPage.php:1066
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:2177
static getRestrictionLevels($index, User $user=null)
Determine which restriction levels it makes sense to use in a namespace, optionally filtered by a use...
static tooltipAndAccesskeyAttribs($name, array $msgParams=[])
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2240
null string $contentModel
Definition: EditPage.php:365
getEditPermissionErrors($rigor= 'secure')
Definition: EditPage.php:612
isRedirect()
Tests if the article content represents a redirect.
Definition: WikiPage.php:462
null Title $mContextTitle
Definition: EditPage.php:213
wfArrayDiff2($a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
static formatTemplates($templates, $preview=false, $section=false, $more=null)
Returns HTML for the "templates used on this page" list.
Definition: Linker.php:1938
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
static showLogExtract(&$out, $types=[], $page= '', $user= '', $param=[])
Show log extract.
static matchSummarySpamRegex($text)
Check given input text against $wgSummarySpamRegex, and return the text of the first match...
Definition: EditPage.php:2247
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
Definition: design.txt:56
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1814
const AS_CONTENT_TOO_BIG
Status: Content too big (> $wgMaxArticleSize)
Definition: EditPage.php:69
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping $template
Definition: hooks.txt:776
safeUnicodeOutput($text)
Filter an output field through a Unicode armoring process if it is going to an old browser with known...
Definition: EditPage.php:4199
static addCallableUpdate($callable, $type=self::POSTSEND)
Add a callable update.
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:47
$wgContentHandlerUseDB
Set to false to disable use of the database fields introduced by the ContentHandler facility...
$wgEnableUploads
Uploads have to be specially set up to be secure.
bool $isWrongCaseCssJsPage
Definition: EditPage.php:231
attemptSave(&$resultDetails=false)
Attempt submission.
Definition: EditPage.php:1417
showIntro()
Show all applicable editing introductions.
Definition: EditPage.php:2326
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getArticle()
Definition: EditPage.php:421
bool $isCssSubpage
Definition: EditPage.php:225
$wgSpamRegex
Edits matching these regular expressions in body text will be recognised as spam and rejected automat...
bool $watchthis
Definition: EditPage.php:317
$previewTextAfterContent
Definition: EditPage.php:384
static closeElement($element)
Shortcut to close an XML element.
Definition: Xml.php:118
const DELETED_COMMENT
Definition: LogPage.php:34
wfDebugLog($logGroup, $text, $dest= 'all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
getContent($audience=Revision::FOR_PUBLIC, User $user=null)
Get the content of the current revision.
Definition: WikiPage.php:650
static openElement($element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:248
getParentRevId()
Get the edit's parent revision ID.
Definition: EditPage.php:1226
isWrongCaseCssJsPage()
Checks whether the user entered a skin name in uppercase, e.g.
Definition: EditPage.php:772
getTemplates()
Definition: EditPage.php:3848
wfEscapeWikiText($text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
bool $save
Definition: EditPage.php:305
wfReadOnly()
Check whether the wiki is in read-only mode.
static getMain()
Static methods.
integer $editRevId
Definition: EditPage.php:338
static textarea($name, $value= '', array $attribs=[])
Convenience function to produce a <textarea> element.
Definition: Html.php:765
static getCanonicalName($index)
Returns the canonical (English) name for a given index.
const AS_SPAM_ERROR
Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex.
Definition: EditPage.php:137
const EDIT_FORCE_BOT
Definition: Defines.php:183
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:2080
getLastDelete()
Definition: EditPage.php:3628
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add etc
Definition: design.txt:12
wfWarn($msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
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:1256
$wgAjaxEditStash
Have clients send edits to be prepared when filling in edit summaries.
getActionURL(Title $title)
Returns the URL to use in the form's action attribute.
Definition: EditPage.php:3594
if($limit) $timestamp
static newFromTarget($specificTarget, $vagueTarget=null, $fromMaster=false)
Given a target and the target's type, get an existing Block object if possible.
Definition: Block.php:1057
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context $parserOutput
Definition: hooks.txt:1020
$editFormTextAfterTools
Definition: EditPage.php:381
displayViewSourcePage(Content $content, $errorMessage= '')
Display a read-only View Source page.
Definition: EditPage.php:684
const AS_CANNOT_USE_CUSTOM_MODEL
Status: when changing the content model is disallowed due to $wgContentHandlerUseDB being false...
Definition: EditPage.php:176
$editFormTextAfterWarn
Definition: EditPage.php:380
const NS_MEDIA
Definition: Defines.php:57
getLocalURL($query= '', $query2=false)
Get a URL with no fragment or server name (relative URL) from a Title object.
Definition: Title.php:1688
$res
Definition: database.txt:21
bool $recreate
Definition: EditPage.php:320
static loadFromTimestamp($db, $title, $timestamp)
Load the revision for the given title with the given timestamp.
Definition: Revision.php:290
setPreloadedContent(Content $content)
Use this method before edit() to preload some content into the edit box.
Definition: EditPage.php:1291
const AS_SUCCESS_UPDATE
Status: Article successfully updated.
Definition: EditPage.php:44
$wgAllowUserJs
Allow user Javascript page? This enables a lot of neat customizations, but may increase security risk...
const AS_READ_ONLY_PAGE
Status: wiki is in readonly mode (wfReadOnly() == true)
Definition: EditPage.php:84
MediaWiki exception.
Definition: MWException.php:26
static openElement($element, $attribs=null)
This opens an XML element.
Definition: Xml.php:109
showHeader()
Definition: EditPage.php:2779
const EDIT_AUTOSUMMARY
Definition: Defines.php:185
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Base interface for content objects.
Definition: Content.php:34
const AS_NO_CHANGE_CONTENT_MODEL
Status: user tried to modify the content model, but is not allowed to do that ( User::isAllowed('edit...
Definition: EditPage.php:153
addContentModelChangeLogEntry(User $user, $oldModel, $newModel, $reason)
Definition: EditPage.php:2130
getTitle()
Get the title object of the article.
Definition: Article.php:166
const IGNORE_USER_RIGHTS
Definition: User.php:84
$params
const NS_CATEGORY
Definition: Defines.php:83
string $edittime
Definition: EditPage.php:335
initialiseForm()
Initialise form fields in the object Called on the first invocation, e.g.
Definition: EditPage.php:1027
wasDeletedSinceLastEdit()
Check if a page was deleted while the user was editing it, before submit.
Definition: EditPage.php:3605
toEditText($content)
Gets an editable textual representation of $content.
Definition: EditPage.php:2474
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
fatal($message)
Add an error and set OK to false, indicating that the operation as a whole was fatal.
Definition: Status.php:171
isSectionEditSupported()
Returns whether section editing is supported for the current page.
Definition: EditPage.php:793
static isIP($name)
Does the string match an anonymous IP address?
Definition: User.php:824
getSummaryInput($summary="", $labelText=null, $inputAttrs=null, $spanLabelAttrs=null)
Standard summary input and label (wgSummary), abstracted so EditPage subclasses may reorganize the fo...
Definition: EditPage.php:3014
showTextbox($text, $name, $customAttribs=[])
Definition: EditPage.php:3203
const DB_SLAVE
Definition: Defines.php:46
getPreloadedContent($preload, $params=[])
Get the contents to be preloaded into the box, either set by an earlier setPreloadText() or by loadin...
Definition: EditPage.php:1306
$wgUseMediaWikiUIEverywhere
Temporary variable that applies MediaWiki UI wherever it can be supported.
static makeInlineScript($script)
Construct an inline script tag with given JS code.
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 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 after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation 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 unsetoffset-wrap String Wrap the message in html(usually something like"&lt
bool $firsttime
Definition: EditPage.php:243
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead.&$feedLinks conditions will AND in the final query as a Content object as a Content object $title
Definition: hooks.txt:312
static linkKnown($target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition: Linker.php:255
showFormAfterText()
Definition: EditPage.php:3120
showDiff()
Get a diff between the current contents of the edit box and the version of the page we're editing fro...
Definition: EditPage.php:3301
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
bool $isNew
New page or new section.
Definition: EditPage.php:234
$wgRightsText
If either $wgRightsUrl or $wgRightsPage is specified then this variable gives the text for the link...
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
unmakeSafe($invalue)
Reverse the previously applied transliteration of non-ASCII characters back to UTF-8.
Definition: EditPage.php:4259
previewOnOpen()
Should we show a preview when the edit form is first shown?
Definition: EditPage.php:739
static loadFromTitle($db, $title, $id=0)
Load either the current, or a specified, revision that's attached to a given page.
Definition: Revision.php:265
const EDITFORM_ID
HTML id and name for the beginning of the edit form.
Definition: EditPage.php:181
const NS_FILE
Definition: Defines.php:75
getCopywarn()
Get the copyright warning.
Definition: EditPage.php:3405
bool $allowSelfRedirect
Definition: EditPage.php:282
showTextbox1($customAttribs=null, $textoverride=null)
Method to output wpTextbox1 The $textoverride method can be used by subclasses overriding showContent...
Definition: EditPage.php:3157
const TYPE_AUTO
Definition: Block.php:78
const AS_SUCCESS_NEW_ARTICLE
Status: Article successfully created.
Definition: EditPage.php:49
Show an error when the user tries to do something whilst blocked.
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:1601
const AS_IMAGE_REDIRECT_LOGGED
Status: logged in user is not allowed to upload (User::isAllowed('upload') == false) ...
Definition: EditPage.php:147
const RAW
Definition: Revision.php:85
static matchSpamRegexInternal($text, $regexes)
Definition: EditPage.php:2258
getPreviewParserOptions()
Get parser options for a preview.
Definition: EditPage.php:3814
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
static extractSectionTitle($text)
Extract the section title from current section text, if any.
Definition: EditPage.php:2766
getCancelLink()
Definition: EditPage.php:3568
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:776
bool int $contentLength
Definition: EditPage.php:397
bool $isCssJsSubpage
Definition: EditPage.php:222
const NS_MEDIAWIKI
Definition: Defines.php:77
const AS_END
Status: WikiPage::doEdit() was unsuccessful.
Definition: EditPage.php:132
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
string $textbox1
Definition: EditPage.php:323
CONTENT_MODEL_JAVASCRIPT
Uploads have to be specially set up to be secure.
const DELETED_USER
Definition: LogPage.php:35
const DELETED_TEXT
Definition: Revision.php:76
importFormData(&$request)
This function collects the form data and uses it to populate various member variables.
Definition: EditPage.php:803
noSuchSectionPage()
Creates a basic error page which informs the user that they have attempted to edit a nonexistent sect...
Definition: EditPage.php:4112
$wgSummarySpamRegex
Same as the above except for edit summaries.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:1020
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
static newFromId($id, $flags=0)
Load a page revision from a given revision ID number.
Definition: Revision.php:99
ParserOutput $mParserOutput
Definition: EditPage.php:291
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:300
string $sectiontitle
Definition: EditPage.php:344
bool $minoredit
Definition: EditPage.php:314
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:776
static inDebugMode()
Determine whether debug mode was requested Order of priority is 1) request param, 2) cookie...
bool $enableApiEditOverride
Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing.
Definition: EditPage.php:402
This document describes the state of Postgres support in and is fairly well maintained The main code is very well while extensions are very hit and miss it is probably the most supported database after MySQL Much of the work in making MediaWiki database agnostic came about through the work of creating Postgres as and are nearing end of but without copying over all the usage comments General notes on the but these can almost always be programmed around *Although Postgres has a true BOOLEAN type
Definition: postgres.txt:22
static tags($element, $attribs=null, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:131
const NS_CATEGORY_TALK
Definition: Defines.php:84
getCheckboxes(&$tabindex, $checked)
Returns an array of html code of the following checkboxes: minor and watch.
Definition: EditPage.php:4011
int $parentRevId
Definition: EditPage.php:353
doPreviewParse(Content $content)
Parse the page for a preview.
Definition: EditPage.php:3831
string $action
Definition: EditPage.php:216
static submitButton($contents, array $attrs, array $modifiers=[])
Returns an HTML link element in a string styled as a button (when $wgUseMediaWikiUIEverywhere is enab...
Definition: Html.php:186
bool $deletedSinceEdit
Definition: EditPage.php:237
Class for creating log entries manually, to inject them into the database.
Definition: LogEntry.php:394
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2458
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
showCustomIntro()
Attempt to show a custom editing introduction, if supplied.
Definition: EditPage.php:2440
static matchSpamRegex($text)
Check given input text against $wgSpamRegex, and return the text of the first match.
Definition: EditPage.php:2233
static input($name, $value= '', $type= 'text', array $attribs=[])
Convenience function to produce an "<input>" element.
Definition: Html.php:666
bool $isJsSubpage
Definition: EditPage.php:228
importContentFormData(&$request)
Subpage overridable method for extracting the page content data from the posted form to be placed in ...
Definition: EditPage.php:1018
displayPreviewArea($previewOutput, $isOnTop=false)
Definition: EditPage.php:3232
const EDIT_NEW
Definition: Defines.php:179
newSectionSummary(&$sectionanchor=null)
Return the summary to be used for a new section.
Definition: EditPage.php:1623
const AS_RATE_LIMITED
Status: rate limiter for action 'edit' was tripped.
Definition: EditPage.php:89
getBaseRevision()
Definition: EditPage.php:2216
static formatHiddenCategories($hiddencats)
Returns HTML for the "hidden categories on this page" list.
Definition: Linker.php:2032
Variant of the Message class.
Definition: Message.php:1236
runPostMergeFilters(Content $content, Status $status, User $user)
Run hooks that can filter edits just before they get saved.
Definition: EditPage.php:1569
const AS_MAX_ARTICLE_SIZE_EXCEEDED
Status: article is too big (> $wgMaxArticleSize), after merging in the new section.
Definition: EditPage.php:127
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition: hooks.txt:1020
getCurrentContent()
Get the current content of the page.
Definition: EditPage.php:1242
$wgPreviewOnOpenNamespaces
Which namespaces have special treatment where they should be preview-on-open Internally only Category...
updateWatchlist()
Register the change of watch status.
Definition: EditPage.php:2147
static buttonAttributes(array $attrs, array $modifiers=[])
Modifies a set of attributes meant for button elements and apply a set of default attributes when $wg...
Definition: Html.php:110
string $hookError
Definition: EditPage.php:288
showEditTools()
Definition: EditPage.php:3392
bool $preview
Definition: EditPage.php:308
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at name
Definition: design.txt:12
const AS_IMAGE_REDIRECT_ANON
Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false) ...
Definition: EditPage.php:142
showStandardInputs(&$tabindex=2)
Definition: EditPage.php:3482
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:122
Show an error when a user tries to do something they do not have the necessary permissions for...
getRedirectTarget()
If this page is a redirect, get its target.
Definition: WikiPage.php:841
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
bool $mTriedSave
Definition: EditPage.php:255
const CONTENT_MODEL_CSS
Definition: Defines.php:280
checkUnicodeCompliantBrowser()
Check if the browser is on a blacklist of user-agents known to mangle UTF-8 data on form submission...
Definition: EditPage.php:4160
$mPreloadContent
Definition: EditPage.php:385
showConflict()
Show an edit conflict.
Definition: EditPage.php:3533
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1020
bool $hasPresetSummary
Has a summary been preset using GET parameter &summary= ?
Definition: EditPage.php:294
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
static consume(ScopedCallback &$sc=null)
Trigger a scoped callback and destroy it.
setApiEditOverride($enableOverride)
Allow editing of content that supports API direct editing, but not general direct editing...
Definition: EditPage.php:476
static makeInternalOrExternalUrl($name)
If url string starts with http, consider as external URL, else internal.
Definition: Skin.php:1098
const POST_EDIT_COOKIE_KEY_PREFIX
Prefix of key for cookie used to pass post-edit state.
Definition: EditPage.php:187
bool $diff
Definition: EditPage.php:311
static checkLabel($label, $name, $id, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox with a label.
Definition: Xml.php:420
const AS_BLANK_ARTICLE
Status: user tried to create a blank page and wpIgnoreBlankArticle == false.
Definition: EditPage.php:106
codepointToUtf8($codepoint)
Return UTF-8 sequence for a given Unicode code point.
const DB_MASTER
Definition: Defines.php:47
string $starttime
Definition: EditPage.php:347
string $formtype
Definition: EditPage.php:240
string $section
Definition: EditPage.php:341
$wgOut
Definition: Setup.php:811
static canAddTagsAccompanyingChange(array $tags, User $user=null)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
Definition: ChangeTags.php:378
getTitle()
Definition: EditPage.php:429
bool $mTokenOkExceptSuffix
Definition: EditPage.php:252
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:1816
if(!$wgRequest->checkUrlExtension()) if(!$wgEnableAPI) $wgTitle
Definition: api.php:57
const AS_CONFLICT_DETECTED
Status: (non-resolvable) edit conflict.
Definition: EditPage.php:111
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
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable 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:776
$suppressIntro
Definition: EditPage.php:391
static commentBlock($comment, $title=null, $local=false, $wikiId=null)
Wrap a comment in standard punctuation and formatting if it's non-empty, otherwise return empty strin...
Definition: Linker.php:1526
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:1829
getOriginalContent(User $user)
Get the content of the wanted revision, without section extraction.
Definition: EditPage.php:1197
static encodeJsCall($name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition: Xml.php:682
static doWatchOrUnwatch($watch, Title $title, User $user)
Watch or unwatch a page.
Definition: WatchAction.php:83
bool $selfRedirect
Definition: EditPage.php:279
bool $incompleteForm
Definition: EditPage.php:258
bool $edit
Definition: EditPage.php:394
const AS_READ_ONLY_PAGE_LOGGED
Status: this logged in user is not allowed to edit this page.
Definition: EditPage.php:79
const AS_PARSE_ERROR
Status: can't parse content.
Definition: EditPage.php:170
const NS_USER_TALK
Definition: Defines.php:72
const AS_SELF_REDIRECT
Status: user tried to create self-redirect (redirect to the same article) and wpIgnoreSelfRedirect ==...
Definition: EditPage.php:159
isSupportedContentModel($modelId)
Returns if the given content model is editable.
Definition: EditPage.php:465
static element($element, $attribs=[], $contents= '')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:230
$editFormTextBeforeContent
Definition: EditPage.php:379
showPreview($text)
Append preview output to $wgOut.
Definition: EditPage.php:3280
null array $changeTags
Definition: EditPage.php:371
wfFindFile($title, $options=[])
Find a file.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk page
Definition: hooks.txt:2376
if(is_null($wgLocalTZoffset)) if(!$wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:663
Show an error when the user hits a rate limit.
static getEditToolbar($title=null)
Shows a bulletin board style toolbar for common editing functions.
Definition: EditPage.php:3872
static makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:503
showSummaryInput($isSubjectPreview, $summary="")
Definition: EditPage.php:3052
toEditContent($text)
Turns the given text into a Content object by unserializing it.
Definition: EditPage.php:2503
showEditForm($formCallback=null)
Send the edit form and related headers to $wgOut.
Definition: EditPage.php:2527
static newGood($value=null)
Factory function for good results.
Definition: Status.php:101
Exception representing a failure to serialize or unserialize a content object.
tokenOk(&$request)
Make sure the form isn't faking a user's credentials.
Definition: EditPage.php:1370
string $editFormPageTop
Before even the preview.
Definition: EditPage.php:377
getSummaryPreview($isSubjectPreview, $summary="")
Definition: EditPage.php:3082
const AS_CHANGE_TAG_ERROR
Status: an error relating to change tagging.
Definition: EditPage.php:165
$wgBrowserBlackList
Browser Blacklist for unicode non compliant browsers.
static wantSignatures($index)
Might pages in this namespace require the use of the Signature button on the edit toolbar...
__construct(Article $article)
Definition: EditPage.php:407
$editFormTextTop
Definition: EditPage.php:378
$wgUser
Definition: Setup.php:801
$matches
null $scrolltop
Definition: EditPage.php:359
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310