MediaWiki REL1_32
EditPage.php
Go to the documentation of this file.
1<?php
27use Wikimedia\ScopedCallback;
28
44class EditPage {
48 const UNICODE_CHECK = 'ℳ𝒲β™₯π“Šπ“ƒπ’Ύπ’Έβ„΄π’Ήβ„―';
49
53 const AS_SUCCESS_UPDATE = 200;
54
59
63 const AS_HOOK_ERROR = 210;
64
69
74
78 const AS_CONTENT_TOO_BIG = 216;
79
84
89
93 const AS_READ_ONLY_PAGE = 220;
94
98 const AS_RATE_LIMITED = 221;
99
105
111
115 const AS_BLANK_ARTICLE = 224;
116
121
126 const AS_SUMMARY_NEEDED = 226;
127
131 const AS_TEXTBOX_EMPTY = 228;
132
137
141 const AS_END = 231;
142
146 const AS_SPAM_ERROR = 232;
147
152
157
163
168 const AS_SELF_REDIRECT = 236;
169
175
179 const AS_PARSE_ERROR = 240;
180
186
191
195 const EDITFORM_ID = 'editform';
196
201 const POST_EDIT_COOKIE_KEY_PREFIX = 'PostEditRevision';
202
217
222 public $mArticle;
224 private $page;
225
230 public $mTitle;
231
233 private $mContextTitle = null;
234
236 public $action = 'submit';
237
242 public $isConflict = false;
243
245 public $isNew = false;
246
249
251 public $formtype;
252
258
261
263 public $mTokenOk = false;
264
266 public $mTokenOkExceptSuffix = false;
267
269 public $mTriedSave = false;
270
272 public $incompleteForm = false;
273
275 public $tooBig = false;
276
278 public $missingComment = false;
279
281 public $missingSummary = false;
282
284 public $allowBlankSummary = false;
285
287 protected $blankArticle = false;
288
290 protected $allowBlankArticle = false;
291
293 protected $selfRedirect = false;
294
296 protected $allowSelfRedirect = false;
297
299 public $autoSumm = '';
300
302 public $hookError = '';
303
306
308 public $hasPresetSummary = false;
309
311 public $mBaseRevision = false;
312
314 public $mShowSummaryField = true;
315
316 # Form values
317
319 public $save = false;
320
322 public $preview = false;
323
325 public $diff = false;
326
328 public $minoredit = false;
329
331 public $watchthis = false;
332
334 public $recreate = false;
335
339 public $textbox1 = '';
340
342 public $textbox2 = '';
343
345 public $summary = '';
346
350 public $nosummary = false;
351
356 public $edittime = '';
357
369 private $editRevId = null;
370
372 public $section = '';
373
375 public $sectiontitle = '';
376
380 public $starttime = '';
381
387 public $oldid = 0;
388
394 public $parentRevId = 0;
395
397 public $editintro = '';
398
400 public $scrolltop = null;
401
403 public $bot = true;
404
407
409 public $contentFormat = null;
410
412 private $changeTags = null;
413
414 # Placeholders for text injection by hooks (must be HTML)
415 # extensions should take care to _append_ to the present value
416
418 public $editFormPageTop = '';
419 public $editFormTextTop = '';
426 public $mPreloadContent = null;
427
428 /* $didSave should be set to true whenever an article was successfully altered. */
429 public $didSave = false;
430 public $undidRev = 0;
431
432 public $suppressIntro = false;
433
435 protected $edit;
436
438 protected $contentLength = false;
439
443 private $enableApiEditOverride = false;
444
448 protected $context;
449
453 private $isOldRev = false;
454
459
466
471
475 public function __construct( Article $article ) {
476 $this->mArticle = $article;
477 $this->page = $article->getPage(); // model object
478 $this->mTitle = $article->getTitle();
479 $this->context = $article->getContext();
480
481 $this->contentModel = $this->mTitle->getContentModel();
482
483 $handler = ContentHandler::getForModelID( $this->contentModel );
484 $this->contentFormat = $handler->getDefaultFormat();
485 $this->editConflictHelperFactory = [ $this, 'newTextConflictHelper' ];
486 }
487
491 public function getArticle() {
492 return $this->mArticle;
493 }
494
499 public function getContext() {
500 return $this->context;
501 }
502
507 public function getTitle() {
508 return $this->mTitle;
509 }
510
516 public function setContextTitle( $title ) {
517 $this->mContextTitle = $title;
518 }
519
528 public function getContextTitle() {
529 if ( is_null( $this->mContextTitle ) ) {
530 wfDeprecated( __METHOD__ . ' called with no title set', '1.32' );
531 global $wgTitle;
532 return $wgTitle;
533 } else {
535 }
536 }
537
545 public function isSupportedContentModel( $modelId ) {
546 return $this->enableApiEditOverride === true ||
547 ContentHandler::getForModelID( $modelId )->supportsDirectEditing();
548 }
549
556 public function setApiEditOverride( $enableOverride ) {
557 $this->enableApiEditOverride = $enableOverride;
558 }
559
563 public function submit() {
564 wfDeprecated( __METHOD__, '1.29' );
565 $this->edit();
566 }
567
579 public function edit() {
580 // Allow extensions to modify/prevent this form or submission
581 if ( !Hooks::run( 'AlternateEdit', [ $this ] ) ) {
582 return;
583 }
584
585 wfDebug( __METHOD__ . ": enter\n" );
586
587 $request = $this->context->getRequest();
588 // If they used redlink=1 and the page exists, redirect to the main article
589 if ( $request->getBool( 'redlink' ) && $this->mTitle->exists() ) {
590 $this->context->getOutput()->redirect( $this->mTitle->getFullURL() );
591 return;
592 }
593
594 $this->importFormData( $request );
595 $this->firsttime = false;
596
597 if ( wfReadOnly() && $this->save ) {
598 // Force preview
599 $this->save = false;
600 $this->preview = true;
601 }
602
603 if ( $this->save ) {
604 $this->formtype = 'save';
605 } elseif ( $this->preview ) {
606 $this->formtype = 'preview';
607 } elseif ( $this->diff ) {
608 $this->formtype = 'diff';
609 } else { # First time through
610 $this->firsttime = true;
611 if ( $this->previewOnOpen() ) {
612 $this->formtype = 'preview';
613 } else {
614 $this->formtype = 'initial';
615 }
616 }
617
618 $permErrors = $this->getEditPermissionErrors( $this->save ? 'secure' : 'full' );
619 if ( $permErrors ) {
620 wfDebug( __METHOD__ . ": User can't edit\n" );
621
622 // track block with a cookie if it doesn't exists already
623 $this->context->getUser()->trackBlockWithCookie();
624
625 // Auto-block user's IP if the account was "hard" blocked
626 if ( !wfReadOnly() ) {
627 DeferredUpdates::addCallableUpdate( function () {
628 $this->context->getUser()->spreadAnyEditBlock();
629 } );
630 }
631 $this->displayPermissionsError( $permErrors );
632
633 return;
634 }
635
636 $revision = $this->mArticle->getRevisionFetched();
637 // Disallow editing revisions with content models different from the current one
638 // Undo edits being an exception in order to allow reverting content model changes.
639 if ( $revision
640 && $revision->getContentModel() !== $this->contentModel
641 ) {
642 $prevRev = null;
643 if ( $this->undidRev ) {
644 $undidRevObj = Revision::newFromId( $this->undidRev );
645 $prevRev = $undidRevObj ? $undidRevObj->getPrevious() : null;
646 }
647 if ( !$this->undidRev
648 || !$prevRev
649 || $prevRev->getContentModel() !== $this->contentModel
650 ) {
652 $this->getContentObject(),
653 $this->context->msg(
654 'contentmodelediterror',
655 $revision->getContentModel(),
656 $this->contentModel
657 )->plain()
658 );
659 return;
660 }
661 }
662
663 $this->isConflict = false;
664
665 # Show applicable editing introductions
666 if ( $this->formtype == 'initial' || $this->firsttime ) {
667 $this->showIntro();
668 }
669
670 # Attempt submission here. This will check for edit conflicts,
671 # and redundantly check for locked database, blocked IPs, etc.
672 # that edit() already checked just in case someone tries to sneak
673 # in the back door with a hand-edited submission URL.
674
675 if ( 'save' == $this->formtype ) {
676 $resultDetails = null;
677 $status = $this->attemptSave( $resultDetails );
678 if ( !$this->handleStatus( $status, $resultDetails ) ) {
679 return;
680 }
681 }
682
683 # First time through: get contents, set time for conflict
684 # checking, etc.
685 if ( 'initial' == $this->formtype || $this->firsttime ) {
686 if ( $this->initialiseForm() === false ) {
687 $out = $this->context->getOutput();
688 if ( $out->getRedirect() === '' ) { // mcrundo hack redirects, don't override it
689 $this->noSuchSectionPage();
690 }
691 return;
692 }
693
694 if ( !$this->mTitle->getArticleID() ) {
695 Hooks::run( 'EditFormPreloadText', [ &$this->textbox1, &$this->mTitle ] );
696 } else {
697 Hooks::run( 'EditFormInitialText', [ $this ] );
698 }
699
700 }
701
702 $this->showEditForm();
703 }
704
709 protected function getEditPermissionErrors( $rigor = 'secure' ) {
710 $user = $this->context->getUser();
711 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user, $rigor );
712 # Can this title be created?
713 if ( !$this->mTitle->exists() ) {
714 $permErrors = array_merge(
715 $permErrors,
717 $this->mTitle->getUserPermissionsErrors( 'create', $user, $rigor ),
718 $permErrors
719 )
720 );
721 }
722 # Ignore some permissions errors when a user is just previewing/viewing diffs
723 $remove = [];
724 foreach ( $permErrors as $error ) {
725 if ( ( $this->preview || $this->diff )
726 && (
727 $error[0] == 'blockedtext' ||
728 $error[0] == 'autoblockedtext' ||
729 $error[0] == 'systemblockedtext'
730 )
731 ) {
732 $remove[] = $error;
733 }
734 }
735 $permErrors = wfArrayDiff2( $permErrors, $remove );
736
737 return $permErrors;
738 }
739
753 protected function displayPermissionsError( array $permErrors ) {
754 $out = $this->context->getOutput();
755 if ( $this->context->getRequest()->getBool( 'redlink' ) ) {
756 // The edit page was reached via a red link.
757 // Redirect to the article page and let them click the edit tab if
758 // they really want a permission error.
759 $out->redirect( $this->mTitle->getFullURL() );
760 return;
761 }
762
763 $content = $this->getContentObject();
764
765 # Use the normal message if there's nothing to display
766 if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
767 $action = $this->mTitle->exists() ? 'edit' :
768 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
769 throw new PermissionsError( $action, $permErrors );
770 }
771
773 $content,
774 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
775 );
776 }
777
783 protected function displayViewSourcePage( Content $content, $errorMessage = '' ) {
784 $out = $this->context->getOutput();
785 Hooks::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
786
787 $out->setRobotPolicy( 'noindex,nofollow' );
788 $out->setPageTitle( $this->context->msg(
789 'viewsource-title',
790 $this->getContextTitle()->getPrefixedText()
791 ) );
792 $out->addBacklinkSubtitle( $this->getContextTitle() );
793 $out->addHTML( $this->editFormPageTop );
794 $out->addHTML( $this->editFormTextTop );
795
796 if ( $errorMessage !== '' ) {
797 $out->addWikiText( $errorMessage );
798 $out->addHTML( "<hr />\n" );
799 }
800
801 # If the user made changes, preserve them when showing the markup
802 # (This happens when a user is blocked during edit, for instance)
803 if ( !$this->firsttime ) {
804 $text = $this->textbox1;
805 $out->addWikiMsg( 'viewyourtext' );
806 } else {
807 try {
808 $text = $this->toEditText( $content );
809 } catch ( MWException $e ) {
810 # Serialize using the default format if the content model is not supported
811 # (e.g. for an old revision with a different model)
812 $text = $content->serialize();
813 }
814 $out->addWikiMsg( 'viewsourcetext' );
815 }
816
817 $out->addHTML( $this->editFormTextBeforeContent );
818 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
819 $out->addHTML( $this->editFormTextAfterContent );
820
821 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
822
823 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
824
825 $out->addHTML( $this->editFormTextBottom );
826 if ( $this->mTitle->exists() ) {
827 $out->returnToMain( null, $this->mTitle );
828 }
829 }
830
836 protected function previewOnOpen() {
837 $config = $this->context->getConfig();
838 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
839 $request = $this->context->getRequest();
840 if ( $config->get( 'RawHtml' ) ) {
841 // If raw HTML is enabled, disable preview on open
842 // since it has to be posted with a token for
843 // security reasons
844 return false;
845 }
846 if ( $request->getVal( 'preview' ) == 'yes' ) {
847 // Explicit override from request
848 return true;
849 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
850 // Explicit override from request
851 return false;
852 } elseif ( $this->section == 'new' ) {
853 // Nothing *to* preview for new sections
854 return false;
855 } elseif ( ( $request->getVal( 'preload' ) !== null || $this->mTitle->exists() )
856 && $this->context->getUser()->getOption( 'previewonfirst' )
857 ) {
858 // Standard preference behavior
859 return true;
860 } elseif ( !$this->mTitle->exists()
861 && isset( $previewOnOpenNamespaces[$this->mTitle->getNamespace()] )
862 && $previewOnOpenNamespaces[$this->mTitle->getNamespace()]
863 ) {
864 // Categories are special
865 return true;
866 } else {
867 return false;
868 }
869 }
870
877 protected function isWrongCaseUserConfigPage() {
878 if ( $this->mTitle->isUserConfigPage() ) {
879 $name = $this->mTitle->getSkinFromConfigSubpage();
880 $skins = array_merge(
881 array_keys( Skin::getSkinNames() ),
882 [ 'common' ]
883 );
884 return !in_array( $name, $skins )
885 && in_array( strtolower( $name ), $skins );
886 } else {
887 return false;
888 }
889 }
890
898 protected function isSectionEditSupported() {
899 $contentHandler = ContentHandler::getForTitle( $this->mTitle );
900 return $contentHandler->supportsSections();
901 }
902
908 public function importFormData( &$request ) {
909 # Section edit can come from either the form or a link
910 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
911
912 if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
913 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
914 }
915
916 $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
917
918 if ( $request->wasPosted() ) {
919 # These fields need to be checked for encoding.
920 # Also remove trailing whitespace, but don't remove _initial_
921 # whitespace from the text boxes. This may be significant formatting.
922 $this->textbox1 = rtrim( $request->getText( 'wpTextbox1' ) );
923 if ( !$request->getCheck( 'wpTextbox2' ) ) {
924 // Skip this if wpTextbox2 has input, it indicates that we came
925 // from a conflict page with raw page text, not a custom form
926 // modified by subclasses
928 if ( $textbox1 !== null ) {
929 $this->textbox1 = $textbox1;
930 }
931 }
932
933 $this->unicodeCheck = $request->getText( 'wpUnicodeCheck' );
934
935 $this->summary = $request->getText( 'wpSummary' );
936
937 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
938 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
939 # section titles.
940 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
941
942 # Treat sectiontitle the same way as summary.
943 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
944 # currently doing double duty as both edit summary and section title. Right now this
945 # is just to allow API edits to work around this limitation, but this should be
946 # incorporated into the actual edit form when EditPage is rewritten (T20654, T28312).
947 $this->sectiontitle = $request->getText( 'wpSectionTitle' );
948 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
949
950 $this->edittime = $request->getVal( 'wpEdittime' );
951 $this->editRevId = $request->getIntOrNull( 'editRevId' );
952 $this->starttime = $request->getVal( 'wpStarttime' );
953
954 $undidRev = $request->getInt( 'wpUndidRevision' );
955 if ( $undidRev ) {
956 $this->undidRev = $undidRev;
957 }
958
959 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
960
961 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
962 // wpTextbox1 field is missing, possibly due to being "too big"
963 // according to some filter rules such as Suhosin's setting for
964 // suhosin.request.max_value_length (d'oh)
965 $this->incompleteForm = true;
966 } else {
967 // If we receive the last parameter of the request, we can fairly
968 // claim the POST request has not been truncated.
969 $this->incompleteForm = !$request->getVal( 'wpUltimateParam' );
970 }
971 if ( $this->incompleteForm ) {
972 # If the form is incomplete, force to preview.
973 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
974 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
975 $this->preview = true;
976 } else {
977 $this->preview = $request->getCheck( 'wpPreview' );
978 $this->diff = $request->getCheck( 'wpDiff' );
979
980 // Remember whether a save was requested, so we can indicate
981 // if we forced preview due to session failure.
982 $this->mTriedSave = !$this->preview;
983
984 if ( $this->tokenOk( $request ) ) {
985 # Some browsers will not report any submit button
986 # if the user hits enter in the comment box.
987 # The unmarked state will be assumed to be a save,
988 # if the form seems otherwise complete.
989 wfDebug( __METHOD__ . ": Passed token check.\n" );
990 } elseif ( $this->diff ) {
991 # Failed token check, but only requested "Show Changes".
992 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
993 } else {
994 # Page might be a hack attempt posted from
995 # an external site. Preview instead of saving.
996 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
997 $this->preview = true;
998 }
999 }
1000 $this->save = !$this->preview && !$this->diff;
1001 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
1002 $this->edittime = null;
1003 }
1004
1005 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
1006 $this->starttime = null;
1007 }
1008
1009 $this->recreate = $request->getCheck( 'wpRecreate' );
1010
1011 $this->minoredit = $request->getCheck( 'wpMinoredit' );
1012 $this->watchthis = $request->getCheck( 'wpWatchthis' );
1013
1014 $user = $this->context->getUser();
1015 # Don't force edit summaries when a user is editing their own user or talk page
1016 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
1017 && $this->mTitle->getText() == $user->getName()
1018 ) {
1019 $this->allowBlankSummary = true;
1020 } else {
1021 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
1022 || !$user->getOption( 'forceeditsummary' );
1023 }
1024
1025 $this->autoSumm = $request->getText( 'wpAutoSummary' );
1026
1027 $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
1028 $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
1029
1030 $changeTags = $request->getVal( 'wpChangeTags' );
1031 if ( is_null( $changeTags ) || $changeTags === '' ) {
1032 $this->changeTags = [];
1033 } else {
1034 $this->changeTags = array_filter( array_map( 'trim', explode( ',',
1035 $changeTags ) ) );
1036 }
1037 } else {
1038 # Not a posted form? Start with nothing.
1039 wfDebug( __METHOD__ . ": Not a posted form.\n" );
1040 $this->textbox1 = '';
1041 $this->summary = '';
1042 $this->sectiontitle = '';
1043 $this->edittime = '';
1044 $this->editRevId = null;
1045 $this->starttime = wfTimestampNow();
1046 $this->edit = false;
1047 $this->preview = false;
1048 $this->save = false;
1049 $this->diff = false;
1050 $this->minoredit = false;
1051 // Watch may be overridden by request parameters
1052 $this->watchthis = $request->getBool( 'watchthis', false );
1053 $this->recreate = false;
1054
1055 // When creating a new section, we can preload a section title by passing it as the
1056 // preloadtitle parameter in the URL (T15100)
1057 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
1058 $this->sectiontitle = $request->getVal( 'preloadtitle' );
1059 // Once wpSummary isn't being use for setting section titles, we should delete this.
1060 $this->summary = $request->getVal( 'preloadtitle' );
1061 } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) !== '' ) {
1062 $this->summary = $request->getText( 'summary' );
1063 if ( $this->summary !== '' ) {
1064 $this->hasPresetSummary = true;
1065 }
1066 }
1067
1068 if ( $request->getVal( 'minor' ) ) {
1069 $this->minoredit = true;
1070 }
1071 }
1072
1073 $this->oldid = $request->getInt( 'oldid' );
1074 $this->parentRevId = $request->getInt( 'parentRevId' );
1075
1076 $this->bot = $request->getBool( 'bot', true );
1077 $this->nosummary = $request->getBool( 'nosummary' );
1078
1079 // May be overridden by revision.
1080 $this->contentModel = $request->getText( 'model', $this->contentModel );
1081 // May be overridden by revision.
1082 $this->contentFormat = $request->getText( 'format', $this->contentFormat );
1083
1084 try {
1085 $handler = ContentHandler::getForModelID( $this->contentModel );
1087 throw new ErrorPageError(
1088 'editpage-invalidcontentmodel-title',
1089 'editpage-invalidcontentmodel-text',
1090 [ wfEscapeWikiText( $this->contentModel ) ]
1091 );
1092 }
1093
1094 if ( !$handler->isSupportedFormat( $this->contentFormat ) ) {
1095 throw new ErrorPageError(
1096 'editpage-notsupportedcontentformat-title',
1097 'editpage-notsupportedcontentformat-text',
1098 [
1099 wfEscapeWikiText( $this->contentFormat ),
1100 wfEscapeWikiText( ContentHandler::getLocalizedName( $this->contentModel ) )
1101 ]
1102 );
1103 }
1104
1111 $this->editintro = $request->getText( 'editintro',
1112 // Custom edit intro for new sections
1113 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
1114
1115 // Allow extensions to modify form data
1116 Hooks::run( 'EditPage::importFormData', [ $this, $request ] );
1117 }
1118
1128 protected function importContentFormData( &$request ) {
1129 return; // Don't do anything, EditPage already extracted wpTextbox1
1130 }
1131
1137 public function initialiseForm() {
1138 $this->edittime = $this->page->getTimestamp();
1139 $this->editRevId = $this->page->getLatest();
1140
1141 $content = $this->getContentObject( false ); # TODO: track content object?!
1142 if ( $content === false ) {
1143 return false;
1144 }
1145 $this->textbox1 = $this->toEditText( $content );
1146
1147 $user = $this->context->getUser();
1148 // activate checkboxes if user wants them to be always active
1149 # Sort out the "watch" checkbox
1150 if ( $user->getOption( 'watchdefault' ) ) {
1151 # Watch all edits
1152 $this->watchthis = true;
1153 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1154 # Watch creations
1155 $this->watchthis = true;
1156 } elseif ( $user->isWatched( $this->mTitle ) ) {
1157 # Already watched
1158 $this->watchthis = true;
1159 }
1160 if ( $user->getOption( 'minordefault' ) && !$this->isNew ) {
1161 $this->minoredit = true;
1162 }
1163 if ( $this->textbox1 === false ) {
1164 return false;
1165 }
1166 return true;
1167 }
1168
1176 protected function getContentObject( $def_content = null ) {
1177 $content = false;
1178
1179 $user = $this->context->getUser();
1180 $request = $this->context->getRequest();
1181 // For message page not locally set, use the i18n message.
1182 // For other non-existent articles, use preload text if any.
1183 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
1184 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
1185 # If this is a system message, get the default text.
1186 $msg = $this->mTitle->getDefaultMessageText();
1187
1188 $content = $this->toEditContent( $msg );
1189 }
1190 if ( $content === false ) {
1191 # If requested, preload some text.
1192 $preload = $request->getVal( 'preload',
1193 // Custom preload text for new sections
1194 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
1195 $params = $request->getArray( 'preloadparams', [] );
1196
1197 $content = $this->getPreloadedContent( $preload, $params );
1198 }
1199 // For existing pages, get text based on "undo" or section parameters.
1200 } else {
1201 if ( $this->section != '' ) {
1202 // Get section edit text (returns $def_text for invalid sections)
1203 $orig = $this->getOriginalContent( $user );
1204 $content = $orig ? $orig->getSection( $this->section ) : null;
1205
1206 if ( !$content ) {
1207 $content = $def_content;
1208 }
1209 } else {
1210 $undoafter = $request->getInt( 'undoafter' );
1211 $undo = $request->getInt( 'undo' );
1212
1213 if ( $undo > 0 && $undoafter > 0 ) {
1214 $undorev = Revision::newFromId( $undo );
1215 $oldrev = Revision::newFromId( $undoafter );
1216 $undoMsg = null;
1217
1218 # Sanity check, make sure it's the right page,
1219 # the revisions exist and they were not deleted.
1220 # Otherwise, $content will be left as-is.
1221 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1222 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
1223 !$oldrev->isDeleted( Revision::DELETED_TEXT )
1224 ) {
1225 if ( WikiPage::hasDifferencesOutsideMainSlot( $undorev, $oldrev )
1226 || !$this->isSupportedContentModel( $oldrev->getContentModel() )
1227 ) {
1228 // Hack for undo while EditPage can't handle multi-slot editing
1229 $this->context->getOutput()->redirect( $this->mTitle->getFullURL( [
1230 'action' => 'mcrundo',
1231 'undo' => $undo,
1232 'undoafter' => $undoafter,
1233 ] ) );
1234 return false;
1235 } else {
1236 $content = $this->page->getUndoContent( $undorev, $oldrev );
1237
1238 if ( $content === false ) {
1239 # Warn the user that something went wrong
1240 $undoMsg = 'failure';
1241 }
1242 }
1243
1244 if ( $undoMsg === null ) {
1245 $oldContent = $this->page->getContent( Revision::RAW );
1246 $popts = ParserOptions::newFromUserAndLang(
1247 $user, MediaWikiServices::getInstance()->getContentLanguage() );
1248 $newContent = $content->preSaveTransform( $this->mTitle, $user, $popts );
1249 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1250 // The undo may change content
1251 // model if its reverting the top
1252 // edit. This can result in
1253 // mismatched content model/format.
1254 $this->contentModel = $newContent->getModel();
1255 $this->contentFormat = $oldrev->getContentFormat();
1256 }
1257
1258 if ( $newContent->equals( $oldContent ) ) {
1259 # Tell the user that the undo results in no change,
1260 # i.e. the revisions were already undone.
1261 $undoMsg = 'nochange';
1262 $content = false;
1263 } else {
1264 # Inform the user of our success and set an automatic edit summary
1265 $undoMsg = 'success';
1266
1267 # If we just undid one rev, use an autosummary
1268 $firstrev = $oldrev->getNext();
1269 if ( $firstrev && $firstrev->getId() == $undo ) {
1270 $userText = $undorev->getUserText();
1271 if ( $userText === '' ) {
1272 $undoSummary = $this->context->msg(
1273 'undo-summary-username-hidden',
1274 $undo
1275 )->inContentLanguage()->text();
1276 } else {
1277 $undoSummary = $this->context->msg(
1278 'undo-summary',
1279 $undo,
1280 $userText
1281 )->inContentLanguage()->text();
1282 }
1283 if ( $this->summary === '' ) {
1284 $this->summary = $undoSummary;
1285 } else {
1286 $this->summary = $undoSummary . $this->context->msg( 'colon-separator' )
1287 ->inContentLanguage()->text() . $this->summary;
1288 }
1289 $this->undidRev = $undo;
1290 }
1291 $this->formtype = 'diff';
1292 }
1293 }
1294 } else {
1295 // Failed basic sanity checks.
1296 // Older revisions may have been removed since the link
1297 // was created, or we may simply have got bogus input.
1298 $undoMsg = 'norev';
1299 }
1300
1301 $out = $this->context->getOutput();
1302 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1303 // undo-nochange.
1304 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1305 $this->editFormPageTop .= $out->parse( "<div class=\"{$class}\">" .
1306 $this->context->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1307 }
1308
1309 if ( $content === false ) {
1310 // Hack for restoring old revisions while EditPage
1311 // can't handle multi-slot editing.
1312
1313 $curRevision = $this->page->getRevision();
1314 $oldRevision = $this->mArticle->getRevisionFetched();
1315
1316 if ( $curRevision
1317 && $oldRevision
1318 && $curRevision->getId() !== $oldRevision->getId()
1319 && ( WikiPage::hasDifferencesOutsideMainSlot( $oldRevision, $curRevision )
1320 || !$this->isSupportedContentModel( $oldRevision->getContentModel() ) )
1321 ) {
1322 $this->context->getOutput()->redirect(
1323 $this->mTitle->getFullURL(
1324 [
1325 'action' => 'mcrrestore',
1326 'restore' => $oldRevision->getId(),
1327 ]
1328 )
1329 );
1330
1331 return false;
1332 }
1333 }
1334
1335 if ( $content === false ) {
1336 $content = $this->getOriginalContent( $user );
1337 }
1338 }
1339 }
1340
1341 return $content;
1342 }
1343
1359 private function getOriginalContent( User $user ) {
1360 if ( $this->section == 'new' ) {
1361 return $this->getCurrentContent();
1362 }
1363 $revision = $this->mArticle->getRevisionFetched();
1364 if ( $revision === null ) {
1365 $handler = ContentHandler::getForModelID( $this->contentModel );
1366 return $handler->makeEmptyContent();
1367 }
1368 $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
1369 return $content;
1370 }
1371
1384 public function getParentRevId() {
1385 if ( $this->parentRevId ) {
1386 return $this->parentRevId;
1387 } else {
1388 return $this->mArticle->getRevIdFetched();
1389 }
1390 }
1391
1400 protected function getCurrentContent() {
1401 $rev = $this->page->getRevision();
1402 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1403
1404 if ( $content === false || $content === null ) {
1405 $handler = ContentHandler::getForModelID( $this->contentModel );
1406 return $handler->makeEmptyContent();
1407 } elseif ( !$this->undidRev ) {
1408 // Content models should always be the same since we error
1409 // out if they are different before this point (in ->edit()).
1410 // The exception being, during an undo, the current revision might
1411 // differ from the prior revision.
1412 $logger = LoggerFactory::getInstance( 'editpage' );
1413 if ( $this->contentModel !== $rev->getContentModel() ) {
1414 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1415 'prev' => $this->contentModel,
1416 'new' => $rev->getContentModel(),
1417 'title' => $this->getTitle()->getPrefixedDBkey(),
1418 'method' => __METHOD__
1419 ] );
1420 $this->contentModel = $rev->getContentModel();
1421 }
1422
1423 // Given that the content models should match, the current selected
1424 // format should be supported.
1425 if ( !$content->isSupportedFormat( $this->contentFormat ) ) {
1426 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1427
1428 'prev' => $this->contentFormat,
1429 'new' => $rev->getContentFormat(),
1430 'title' => $this->getTitle()->getPrefixedDBkey(),
1431 'method' => __METHOD__
1432 ] );
1433 $this->contentFormat = $rev->getContentFormat();
1434 }
1435 }
1436 return $content;
1437 }
1438
1447 $this->mPreloadContent = $content;
1448 }
1449
1461 protected function getPreloadedContent( $preload, $params = [] ) {
1462 if ( !empty( $this->mPreloadContent ) ) {
1464 }
1465
1466 $handler = ContentHandler::getForModelID( $this->contentModel );
1467
1468 if ( $preload === '' ) {
1469 return $handler->makeEmptyContent();
1470 }
1471
1472 $user = $this->context->getUser();
1473 $title = Title::newFromText( $preload );
1474 # Check for existence to avoid getting MediaWiki:Noarticletext
1475 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $user ) ) {
1476 // TODO: somehow show a warning to the user!
1477 return $handler->makeEmptyContent();
1478 }
1479
1480 $page = WikiPage::factory( $title );
1481 if ( $page->isRedirect() ) {
1483 # Same as before
1484 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $user ) ) {
1485 // TODO: somehow show a warning to the user!
1486 return $handler->makeEmptyContent();
1487 }
1488 $page = WikiPage::factory( $title );
1489 }
1490
1491 $parserOptions = ParserOptions::newFromUser( $user );
1493
1494 if ( !$content ) {
1495 // TODO: somehow show a warning to the user!
1496 return $handler->makeEmptyContent();
1497 }
1498
1499 if ( $content->getModel() !== $handler->getModelID() ) {
1500 $converted = $content->convert( $handler->getModelID() );
1501
1502 if ( !$converted ) {
1503 // TODO: somehow show a warning to the user!
1504 wfDebug( "Attempt to preload incompatible content: " .
1505 "can't convert " . $content->getModel() .
1506 " to " . $handler->getModelID() );
1507
1508 return $handler->makeEmptyContent();
1509 }
1510
1511 $content = $converted;
1512 }
1513
1514 return $content->preloadTransform( $title, $parserOptions, $params );
1515 }
1516
1524 public function tokenOk( &$request ) {
1525 $token = $request->getVal( 'wpEditToken' );
1526 $user = $this->context->getUser();
1527 $this->mTokenOk = $user->matchEditToken( $token );
1528 $this->mTokenOkExceptSuffix = $user->matchEditTokenNoSuffix( $token );
1529 return $this->mTokenOk;
1530 }
1531
1546 protected function setPostEditCookie( $statusValue ) {
1547 $revisionId = $this->page->getLatest();
1548 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1549
1550 $val = 'saved';
1551 if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1552 $val = 'created';
1553 } elseif ( $this->oldid ) {
1554 $val = 'restored';
1555 }
1556
1557 $response = $this->context->getRequest()->response();
1558 $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION );
1559 }
1560
1567 public function attemptSave( &$resultDetails = false ) {
1568 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1569 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1570 // This is needed since PageUpdater no longer checks these rights!
1571
1572 // Allow bots to exempt some edits from bot flagging
1573 $bot = $this->context->getUser()->isAllowed( 'bot' ) && $this->bot;
1574 $status = $this->internalAttemptSave( $resultDetails, $bot );
1575
1576 Hooks::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1577
1578 return $status;
1579 }
1580
1584 private function incrementResolvedConflicts() {
1585 if ( $this->context->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1586 return;
1587 }
1588
1589 $this->getEditConflictHelper()->incrementResolvedStats();
1590 }
1591
1601 private function handleStatus( Status $status, $resultDetails ) {
1606 if ( $status->value == self::AS_SUCCESS_UPDATE
1607 || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1608 ) {
1610
1611 $this->didSave = true;
1612 if ( !$resultDetails['nullEdit'] ) {
1613 $this->setPostEditCookie( $status->value );
1614 }
1615 }
1616
1617 $out = $this->context->getOutput();
1618
1619 // "wpExtraQueryRedirect" is a hidden input to modify
1620 // after save URL and is not used by actual edit form
1621 $request = $this->context->getRequest();
1622 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1623
1624 switch ( $status->value ) {
1632 case self::AS_END:
1635 return true;
1636
1638 return false;
1639
1643 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1644 return true;
1645
1647 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1648 if ( $extraQueryRedirect ) {
1649 if ( $query === '' ) {
1650 $query = $extraQueryRedirect;
1651 } else {
1652 $query = $query . '&' . $extraQueryRedirect;
1653 }
1654 }
1655 $anchor = $resultDetails['sectionanchor'] ?? '';
1656 $out->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1657 return false;
1658
1660 $extraQuery = '';
1661 $sectionanchor = $resultDetails['sectionanchor'];
1662
1663 // Give extensions a chance to modify URL query on update
1664 Hooks::run(
1665 'ArticleUpdateBeforeRedirect',
1666 [ $this->mArticle, &$sectionanchor, &$extraQuery ]
1667 );
1668
1669 if ( $resultDetails['redirect'] ) {
1670 if ( $extraQuery == '' ) {
1671 $extraQuery = 'redirect=no';
1672 } else {
1673 $extraQuery = 'redirect=no&' . $extraQuery;
1674 }
1675 }
1676 if ( $extraQueryRedirect ) {
1677 if ( $extraQuery === '' ) {
1678 $extraQuery = $extraQueryRedirect;
1679 } else {
1680 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1681 }
1682 }
1683
1684 $out->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1685 return false;
1686
1688 $this->spamPageWithContent( $resultDetails['spam'] );
1689 return false;
1690
1692 throw new UserBlockedError( $this->context->getUser()->getBlock() );
1693
1696 throw new PermissionsError( 'upload' );
1697
1700 throw new PermissionsError( 'edit' );
1701
1703 throw new ReadOnlyError;
1704
1706 throw new ThrottledError();
1707
1709 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1710 throw new PermissionsError( $permission );
1711
1713 throw new PermissionsError( 'editcontentmodel' );
1714
1715 default:
1716 // We don't recognize $status->value. The only way that can happen
1717 // is if an extension hook aborted from inside ArticleSave.
1718 // Render the status object into $this->hookError
1719 // FIXME this sucks, we should just use the Status object throughout
1720 $this->hookError = '<div class="error">' . "\n" . $status->getWikiText() .
1721 '</div>';
1722 return true;
1723 }
1724 }
1725
1735 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1736 // Run old style post-section-merge edit filter
1737 if ( $this->hookError != '' ) {
1738 # ...or the hook could be expecting us to produce an error
1739 $status->fatal( 'hookaborted' );
1741 return false;
1742 }
1743
1744 // Run new style post-section-merge edit filter
1745 if ( !Hooks::run( 'EditFilterMergedContent',
1746 [ $this->context, $content, $status, $this->summary,
1747 $user, $this->minoredit ] )
1748 ) {
1749 # Error messages etc. could be handled within the hook...
1750 if ( $status->isGood() ) {
1751 $status->fatal( 'hookaborted' );
1752 // Not setting $this->hookError here is a hack to allow the hook
1753 // to cause a return to the edit page without $this->hookError
1754 // being set. This is used by ConfirmEdit to display a captcha
1755 // without any error message cruft.
1756 } else {
1757 $this->hookError = $this->formatStatusErrors( $status );
1758 }
1759 // Use the existing $status->value if the hook set it
1760 if ( !$status->value ) {
1762 }
1763 return false;
1764 } elseif ( !$status->isOK() ) {
1765 # ...or the hook could be expecting us to produce an error
1766 // FIXME this sucks, we should just use the Status object throughout
1767 $this->hookError = $this->formatStatusErrors( $status );
1768 $status->fatal( 'hookaborted' );
1770 return false;
1771 }
1772
1773 return true;
1774 }
1775
1782 private function formatStatusErrors( Status $status ) {
1783 $errmsg = $status->getWikiText(
1784 'edit-error-short',
1785 'edit-error-long',
1786 $this->context->getLanguage()
1787 );
1788 return <<<ERROR
1789<div class="errorbox">
1790{$errmsg}
1791</div>
1792<br clear="all" />
1793ERROR;
1794 }
1795
1802 private function newSectionSummary( &$sectionanchor = null ) {
1803 global $wgParser;
1804
1805 if ( $this->sectiontitle !== '' ) {
1806 $sectionanchor = $this->guessSectionName( $this->sectiontitle );
1807 // If no edit summary was specified, create one automatically from the section
1808 // title and have it link to the new section. Otherwise, respect the summary as
1809 // passed.
1810 if ( $this->summary === '' ) {
1811 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1812 return $this->context->msg( 'newsectionsummary' )
1813 ->plaintextParams( $cleanSectionTitle )->inContentLanguage()->text();
1814 }
1815 } elseif ( $this->summary !== '' ) {
1816 $sectionanchor = $this->guessSectionName( $this->summary );
1817 # This is a new section, so create a link to the new section
1818 # in the revision summary.
1819 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1820 return $this->context->msg( 'newsectionsummary' )
1821 ->plaintextParams( $cleanSummary )->inContentLanguage()->text();
1822 }
1823 return $this->summary;
1824 }
1825
1850 public function internalAttemptSave( &$result, $bot = false ) {
1851 $status = Status::newGood();
1852 $user = $this->context->getUser();
1853
1854 if ( !Hooks::run( 'EditPage::attemptSave', [ $this ] ) ) {
1855 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1856 $status->fatal( 'hookaborted' );
1858 return $status;
1859 }
1860
1861 if ( $this->unicodeCheck !== self::UNICODE_CHECK ) {
1862 $status->fatal( 'unicode-support-fail' );
1864 return $status;
1865 }
1866
1867 $request = $this->context->getRequest();
1868 $spam = $request->getText( 'wpAntispam' );
1869 if ( $spam !== '' ) {
1870 wfDebugLog(
1871 'SimpleAntiSpam',
1872 $user->getName() .
1873 ' editing "' .
1874 $this->mTitle->getPrefixedText() .
1875 '" submitted bogus field "' .
1876 $spam .
1877 '"'
1878 );
1879 $status->fatal( 'spamprotectionmatch', false );
1881 return $status;
1882 }
1883
1884 try {
1885 # Construct Content object
1886 $textbox_content = $this->toEditContent( $this->textbox1 );
1887 } catch ( MWContentSerializationException $ex ) {
1888 $status->fatal(
1889 'content-failed-to-parse',
1890 $this->contentModel,
1891 $this->contentFormat,
1892 $ex->getMessage()
1893 );
1895 return $status;
1896 }
1897
1898 # Check image redirect
1899 if ( $this->mTitle->getNamespace() == NS_FILE &&
1900 $textbox_content->isRedirect() &&
1901 !$user->isAllowed( 'upload' )
1902 ) {
1904 $status->setResult( false, $code );
1905
1906 return $status;
1907 }
1908
1909 # Check for spam
1910 $match = self::matchSummarySpamRegex( $this->summary );
1911 if ( $match === false && $this->section == 'new' ) {
1912 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1913 # regular summaries, it is added to the actual wikitext.
1914 if ( $this->sectiontitle !== '' ) {
1915 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1916 $match = self::matchSpamRegex( $this->sectiontitle );
1917 } else {
1918 # This branch is taken when the "Add Topic" user interface is used, or the API
1919 # is used with the 'summary' parameter.
1920 $match = self::matchSpamRegex( $this->summary );
1921 }
1922 }
1923 if ( $match === false ) {
1924 $match = self::matchSpamRegex( $this->textbox1 );
1925 }
1926 if ( $match !== false ) {
1927 $result['spam'] = $match;
1928 $ip = $request->getIP();
1929 $pdbk = $this->mTitle->getPrefixedDBkey();
1930 $match = str_replace( "\n", '', $match );
1931 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1932 $status->fatal( 'spamprotectionmatch', $match );
1934 return $status;
1935 }
1936 if ( !Hooks::run(
1937 'EditFilter',
1938 [ $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ] )
1939 ) {
1940 # Error messages etc. could be handled within the hook...
1941 $status->fatal( 'hookaborted' );
1943 return $status;
1944 } elseif ( $this->hookError != '' ) {
1945 # ...or the hook could be expecting us to produce an error
1946 $status->fatal( 'hookaborted' );
1948 return $status;
1949 }
1950
1951 if ( $user->isBlockedFrom( $this->mTitle, false ) ) {
1952 // Auto-block user's IP if the account was "hard" blocked
1953 if ( !wfReadOnly() ) {
1954 $user->spreadAnyEditBlock();
1955 }
1956 # Check block state against master, thus 'false'.
1957 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1958 return $status;
1959 }
1960
1961 $this->contentLength = strlen( $this->textbox1 );
1962 $config = $this->context->getConfig();
1963 $maxArticleSize = $config->get( 'MaxArticleSize' );
1964 if ( $this->contentLength > $maxArticleSize * 1024 ) {
1965 // Error will be displayed by showEditForm()
1966 $this->tooBig = true;
1967 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1968 return $status;
1969 }
1970
1971 if ( !$user->isAllowed( 'edit' ) ) {
1972 if ( $user->isAnon() ) {
1973 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1974 return $status;
1975 } else {
1976 $status->fatal( 'readonlytext' );
1978 return $status;
1979 }
1980 }
1981
1982 $changingContentModel = false;
1983 if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
1984 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1985 $status->fatal( 'editpage-cannot-use-custom-model' );
1987 return $status;
1988 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1989 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1990 return $status;
1991 }
1992 // Make sure the user can edit the page under the new content model too
1993 $titleWithNewContentModel = clone $this->mTitle;
1994 $titleWithNewContentModel->setContentModel( $this->contentModel );
1995 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1996 || !$titleWithNewContentModel->userCan( 'edit', $user )
1997 ) {
1998 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1999 return $status;
2000 }
2001
2002 $changingContentModel = true;
2003 $oldContentModel = $this->mTitle->getContentModel();
2004 }
2005
2006 if ( $this->changeTags ) {
2007 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
2008 $this->changeTags, $user );
2009 if ( !$changeTagsStatus->isOK() ) {
2010 $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
2011 return $changeTagsStatus;
2012 }
2013 }
2014
2015 if ( wfReadOnly() ) {
2016 $status->fatal( 'readonlytext' );
2018 return $status;
2019 }
2020 if ( $user->pingLimiter() || $user->pingLimiter( 'linkpurge', 0 )
2021 || ( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
2022 ) {
2023 $status->fatal( 'actionthrottledtext' );
2025 return $status;
2026 }
2027
2028 # If the article has been deleted while editing, don't save it without
2029 # confirmation
2030 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
2031 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
2032 return $status;
2033 }
2034
2035 # Load the page data from the master. If anything changes in the meantime,
2036 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
2037 $this->page->loadPageData( 'fromdbmaster' );
2038 $new = !$this->page->exists();
2039
2040 if ( $new ) {
2041 // Late check for create permission, just in case *PARANOIA*
2042 if ( !$this->mTitle->userCan( 'create', $user ) ) {
2043 $status->fatal( 'nocreatetext' );
2045 wfDebug( __METHOD__ . ": no create permission\n" );
2046 return $status;
2047 }
2048
2049 // Don't save a new page if it's blank or if it's a MediaWiki:
2050 // message with content equivalent to default (allow empty pages
2051 // in this case to disable messages, see T52124)
2052 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2053 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
2054 $defaultText = $defaultMessageText;
2055 } else {
2056 $defaultText = '';
2057 }
2058
2059 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
2060 $this->blankArticle = true;
2061 $status->fatal( 'blankarticle' );
2062 $status->setResult( false, self::AS_BLANK_ARTICLE );
2063 return $status;
2064 }
2065
2066 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2067 return $status;
2068 }
2069
2070 $content = $textbox_content;
2071
2072 $result['sectionanchor'] = '';
2073 if ( $this->section == 'new' ) {
2074 if ( $this->sectiontitle !== '' ) {
2075 // Insert the section title above the content.
2076 $content = $content->addSectionHeader( $this->sectiontitle );
2077 } elseif ( $this->summary !== '' ) {
2078 // Insert the section title above the content.
2079 $content = $content->addSectionHeader( $this->summary );
2080 }
2081 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
2082 }
2083
2085
2086 } else { # not $new
2087
2088 # Article exists. Check for edit conflict.
2089
2090 $this->page->clear(); # Force reload of dates, etc.
2091 $timestamp = $this->page->getTimestamp();
2092 $latest = $this->page->getLatest();
2093
2094 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2095
2096 // An edit conflict is detected if the current revision is different from the
2097 // revision that was current when editing was initiated on the client.
2098 // This is checked based on the timestamp and revision ID.
2099 // TODO: the timestamp based check can probably go away now.
2100 if ( $timestamp != $this->edittime
2101 || ( $this->editRevId !== null && $this->editRevId != $latest )
2102 ) {
2103 $this->isConflict = true;
2104 if ( $this->section == 'new' ) {
2105 if ( $this->page->getUserText() == $user->getName() &&
2106 $this->page->getComment() == $this->newSectionSummary()
2107 ) {
2108 // Probably a duplicate submission of a new comment.
2109 // This can happen when CDN resends a request after
2110 // a timeout but the first one actually went through.
2111 wfDebug( __METHOD__
2112 . ": duplicate new section submission; trigger edit conflict!\n" );
2113 } else {
2114 // New comment; suppress conflict.
2115 $this->isConflict = false;
2116 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
2117 }
2118 } elseif ( $this->section == ''
2120 DB_MASTER, $this->mTitle->getArticleID(),
2121 $user->getId(), $this->edittime
2122 )
2123 ) {
2124 # Suppress edit conflict with self, except for section edits where merging is required.
2125 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
2126 $this->isConflict = false;
2127 }
2128 }
2129
2130 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2131 if ( $this->sectiontitle !== '' ) {
2132 $sectionTitle = $this->sectiontitle;
2133 } else {
2134 $sectionTitle = $this->summary;
2135 }
2136
2137 $content = null;
2138
2139 if ( $this->isConflict ) {
2140 wfDebug( __METHOD__
2141 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2142 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2143 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2144 // ...or disable section editing for non-current revisions (not exposed anyway).
2145 if ( $this->editRevId !== null ) {
2146 $content = $this->page->replaceSectionAtRev(
2147 $this->section,
2148 $textbox_content,
2149 $sectionTitle,
2150 $this->editRevId
2151 );
2152 } else {
2153 $content = $this->page->replaceSectionContent(
2154 $this->section,
2155 $textbox_content,
2156 $sectionTitle,
2157 $this->edittime
2158 );
2159 }
2160 } else {
2161 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
2162 $content = $this->page->replaceSectionContent(
2163 $this->section,
2164 $textbox_content,
2165 $sectionTitle
2166 );
2167 }
2168
2169 if ( is_null( $content ) ) {
2170 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
2171 $this->isConflict = true;
2172 $content = $textbox_content; // do not try to merge here!
2173 } elseif ( $this->isConflict ) {
2174 # Attempt merge
2175 if ( $this->mergeChangesIntoContent( $content ) ) {
2176 // Successful merge! Maybe we should tell the user the good news?
2177 $this->isConflict = false;
2178 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
2179 } else {
2180 $this->section = '';
2181 $this->textbox1 = ContentHandler::getContentText( $content );
2182 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
2183 }
2184 }
2185
2186 if ( $this->isConflict ) {
2187 $status->setResult( false, self::AS_CONFLICT_DETECTED );
2188 return $status;
2189 }
2190
2191 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2192 return $status;
2193 }
2194
2195 if ( $this->section == 'new' ) {
2196 // Handle the user preference to force summaries here
2197 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
2198 $this->missingSummary = true;
2199 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2201 return $status;
2202 }
2203
2204 // Do not allow the user to post an empty comment
2205 if ( $this->textbox1 == '' ) {
2206 $this->missingComment = true;
2207 $status->fatal( 'missingcommenttext' );
2209 return $status;
2210 }
2211 } elseif ( !$this->allowBlankSummary
2212 && !$content->equals( $this->getOriginalContent( $user ) )
2213 && !$content->isRedirect()
2214 && md5( $this->summary ) == $this->autoSumm
2215 ) {
2216 $this->missingSummary = true;
2217 $status->fatal( 'missingsummary' );
2219 return $status;
2220 }
2221
2222 # All's well
2223 $sectionanchor = '';
2224 if ( $this->section == 'new' ) {
2225 $this->summary = $this->newSectionSummary( $sectionanchor );
2226 } elseif ( $this->section != '' ) {
2227 # Try to get a section anchor from the section source, redirect
2228 # to edited section if header found.
2229 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2230 # for duplicate heading checking and maybe parsing.
2231 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
2232 # We can't deal with anchors, includes, html etc in the header for now,
2233 # headline would need to be parsed to improve this.
2234 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2235 $sectionanchor = $this->guessSectionName( $matches[2] );
2236 }
2237 }
2238 $result['sectionanchor'] = $sectionanchor;
2239
2240 // Save errors may fall down to the edit form, but we've now
2241 // merged the section into full text. Clear the section field
2242 // so that later submission of conflict forms won't try to
2243 // replace that into a duplicated mess.
2244 $this->textbox1 = $this->toEditText( $content );
2245 $this->section = '';
2246
2248 }
2249
2250 if ( !$this->allowSelfRedirect
2251 && $content->isRedirect()
2252 && $content->getRedirectTarget()->equals( $this->getTitle() )
2253 ) {
2254 // If the page already redirects to itself, don't warn.
2255 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2256 if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
2257 $this->selfRedirect = true;
2258 $status->fatal( 'selfredirect' );
2260 return $status;
2261 }
2262 }
2263
2264 // Check for length errors again now that the section is merged in
2265 $this->contentLength = strlen( $this->toEditText( $content ) );
2266 if ( $this->contentLength > $maxArticleSize * 1024 ) {
2267 $this->tooBig = true;
2268 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
2269 return $status;
2270 }
2271
2272 $flags = EDIT_AUTOSUMMARY |
2273 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
2274 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
2275 ( $bot ? EDIT_FORCE_BOT : 0 );
2276
2277 $doEditStatus = $this->page->doEditContent(
2278 $content,
2279 $this->summary,
2280 $flags,
2281 false,
2282 $user,
2283 $content->getDefaultFormat(),
2286 );
2287
2288 if ( !$doEditStatus->isOK() ) {
2289 // Failure from doEdit()
2290 // Show the edit conflict page for certain recognized errors from doEdit(),
2291 // but don't show it for errors from extension hooks
2292 $errors = $doEditStatus->getErrorsArray();
2293 if ( in_array( $errors[0][0],
2294 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2295 ) {
2296 $this->isConflict = true;
2297 // Destroys data doEdit() put in $status->value but who cares
2298 $doEditStatus->value = self::AS_END;
2299 }
2300 return $doEditStatus;
2301 }
2302
2303 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2304 if ( $result['nullEdit'] ) {
2305 // We don't know if it was a null edit until now, so increment here
2306 $user->pingLimiter( 'linkpurge' );
2307 }
2308 $result['redirect'] = $content->isRedirect();
2309
2310 $this->updateWatchlist();
2311
2312 // If the content model changed, add a log entry
2313 if ( $changingContentModel ) {
2315 $user,
2316 $new ? false : $oldContentModel,
2319 );
2320 }
2321
2322 return $status;
2323 }
2324
2331 protected function addContentModelChangeLogEntry( User $user, $oldModel, $newModel, $reason ) {
2332 $new = $oldModel === false;
2333 $log = new ManualLogEntry( 'contentmodel', $new ? 'new' : 'change' );
2334 $log->setPerformer( $user );
2335 $log->setTarget( $this->mTitle );
2336 $log->setComment( $reason );
2337 $log->setParameters( [
2338 '4::oldmodel' => $oldModel,
2339 '5::newmodel' => $newModel
2340 ] );
2341 $logid = $log->insert();
2342 $log->publish( $logid );
2343 }
2344
2348 protected function updateWatchlist() {
2349 $user = $this->context->getUser();
2350 if ( !$user->isLoggedIn() ) {
2351 return;
2352 }
2353
2355 $watch = $this->watchthis;
2356 // Do this in its own transaction to reduce contention...
2357 DeferredUpdates::addCallableUpdate( function () use ( $user, $title, $watch ) {
2358 if ( $watch == $user->isWatched( $title, User::IGNORE_USER_RIGHTS ) ) {
2359 return; // nothing to change
2360 }
2362 } );
2363 }
2364
2376 private function mergeChangesIntoContent( &$editContent ) {
2377 $db = wfGetDB( DB_MASTER );
2378
2379 // This is the revision that was current at the time editing was initiated on the client,
2380 // even if the edit was based on an old revision.
2381 $baseRevision = $this->getBaseRevision();
2382 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
2383
2384 if ( is_null( $baseContent ) ) {
2385 return false;
2386 }
2387
2388 // The current state, we want to merge updates into it
2389 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2390 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2391
2392 if ( is_null( $currentContent ) ) {
2393 return false;
2394 }
2395
2396 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2397
2398 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2399
2400 if ( $result ) {
2401 $editContent = $result;
2402 // Update parentRevId to what we just merged.
2403 $this->parentRevId = $currentRevision->getId();
2404 return true;
2405 }
2406
2407 return false;
2408 }
2409
2422 public function getBaseRevision() {
2423 if ( !$this->mBaseRevision ) {
2424 $db = wfGetDB( DB_MASTER );
2425 $this->mBaseRevision = $this->editRevId
2426 ? Revision::newFromId( $this->editRevId, Revision::READ_LATEST )
2427 : Revision::loadFromTimestamp( $db, $this->mTitle, $this->edittime );
2428 }
2429 return $this->mBaseRevision;
2430 }
2431
2439 public static function matchSpamRegex( $text ) {
2440 global $wgSpamRegex;
2441 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2442 $regexes = (array)$wgSpamRegex;
2443 return self::matchSpamRegexInternal( $text, $regexes );
2444 }
2445
2453 public static function matchSummarySpamRegex( $text ) {
2454 global $wgSummarySpamRegex;
2455 $regexes = (array)$wgSummarySpamRegex;
2456 return self::matchSpamRegexInternal( $text, $regexes );
2457 }
2458
2464 protected static function matchSpamRegexInternal( $text, $regexes ) {
2465 foreach ( $regexes as $regex ) {
2466 $matches = [];
2467 if ( preg_match( $regex, $text, $matches ) ) {
2468 return $matches[0];
2469 }
2470 }
2471 return false;
2472 }
2473
2474 public function setHeaders() {
2475 $out = $this->context->getOutput();
2476
2477 $out->addModules( 'mediawiki.action.edit' );
2478 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2479 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2480
2481 $user = $this->context->getUser();
2482
2483 if ( $user->getOption( 'uselivepreview' ) ) {
2484 $out->addModules( 'mediawiki.action.edit.preview' );
2485 }
2486
2487 if ( $user->getOption( 'useeditwarning' ) ) {
2488 $out->addModules( 'mediawiki.action.edit.editWarning' );
2489 }
2490
2491 # Enabled article-related sidebar, toplinks, etc.
2492 $out->setArticleRelated( true );
2493
2494 $contextTitle = $this->getContextTitle();
2495 if ( $this->isConflict ) {
2496 $msg = 'editconflict';
2497 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2498 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2499 } else {
2500 $msg = $contextTitle->exists()
2501 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2502 && $contextTitle->getDefaultMessageText() !== false
2503 )
2504 ? 'editing'
2505 : 'creating';
2506 }
2507
2508 # Use the title defined by DISPLAYTITLE magic word when present
2509 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2510 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2511 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2512 if ( $displayTitle === false ) {
2513 $displayTitle = $contextTitle->getPrefixedText();
2514 } else {
2515 $out->setDisplayTitle( $displayTitle );
2516 }
2517 $out->setPageTitle( $this->context->msg( $msg, $displayTitle ) );
2518
2519 $config = $this->context->getConfig();
2520
2521 # Transmit the name of the message to JavaScript for live preview
2522 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2523 $out->addJsConfigVars( [
2524 'wgEditMessage' => $msg,
2525 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2526 ] );
2527
2528 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2529 // editors, etc.
2530 $out->addJsConfigVars(
2531 'wgEditSubmitButtonLabelPublish',
2532 $config->get( 'EditSubmitButtonLabelPublish' )
2533 );
2534 }
2535
2539 protected function showIntro() {
2540 if ( $this->suppressIntro ) {
2541 return;
2542 }
2543
2544 $out = $this->context->getOutput();
2545 $namespace = $this->mTitle->getNamespace();
2546
2547 if ( $namespace == NS_MEDIAWIKI ) {
2548 # Show a warning if editing an interface message
2549 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2550 # If this is a default message (but not css, json, or js),
2551 # show a hint that it is translatable on translatewiki.net
2552 if (
2553 !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2554 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JSON )
2555 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2556 ) {
2557 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2558 if ( $defaultMessageText !== false ) {
2559 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2560 'translateinterface' );
2561 }
2562 }
2563 } elseif ( $namespace == NS_FILE ) {
2564 # Show a hint to shared repo
2565 $file = wfFindFile( $this->mTitle );
2566 if ( $file && !$file->isLocal() ) {
2567 $descUrl = $file->getDescriptionUrl();
2568 # there must be a description url to show a hint to shared repo
2569 if ( $descUrl ) {
2570 if ( !$this->mTitle->exists() ) {
2571 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2572 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2573 ] );
2574 } else {
2575 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2576 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2577 ] );
2578 }
2579 }
2580 }
2581 }
2582
2583 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2584 # Show log extract when the user is currently blocked
2585 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2586 $username = explode( '/', $this->mTitle->getText(), 2 )[0];
2587 $user = User::newFromName( $username, false /* allow IP users */ );
2588 $ip = User::isIP( $username );
2589 $block = Block::newFromTarget( $user, $user );
2590 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2591 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2592 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2593 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2594 # Show log extract if the user is currently blocked
2596 $out,
2597 'block',
2598 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2599 '',
2600 [
2601 'lim' => 1,
2602 'showIfEmpty' => false,
2603 'msgKey' => [
2604 'blocked-notice-logextract',
2605 $user->getName() # Support GENDER in notice
2606 ]
2607 ]
2608 );
2609 }
2610 }
2611 # Try to add a custom edit intro, or use the standard one if this is not possible.
2612 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2613 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2614 $this->context->msg( 'helppage' )->inContentLanguage()->text()
2615 ) );
2616 if ( $this->context->getUser()->isLoggedIn() ) {
2617 $out->wrapWikiMsg(
2618 // Suppress the external link icon, consider the help url an internal one
2619 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2620 [
2621 'newarticletext',
2622 $helpLink
2623 ]
2624 );
2625 } else {
2626 $out->wrapWikiMsg(
2627 // Suppress the external link icon, consider the help url an internal one
2628 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2629 [
2630 'newarticletextanon',
2631 $helpLink
2632 ]
2633 );
2634 }
2635 }
2636 # Give a notice if the user is editing a deleted/moved page...
2637 if ( !$this->mTitle->exists() ) {
2638 $dbr = wfGetDB( DB_REPLICA );
2639
2640 LogEventsList::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle,
2641 '',
2642 [
2643 'lim' => 10,
2644 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2645 'showIfEmpty' => false,
2646 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2647 ]
2648 );
2649 }
2650 }
2651
2657 protected function showCustomIntro() {
2658 if ( $this->editintro ) {
2659 $title = Title::newFromText( $this->editintro );
2660 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2661 // Added using template syntax, to take <noinclude>'s into account.
2662 $this->context->getOutput()->addWikiTextAsContent(
2663 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2664 /*linestart*/true,
2665 $this->mTitle
2666 );
2667 return true;
2668 }
2669 }
2670 return false;
2671 }
2672
2691 protected function toEditText( $content ) {
2692 if ( $content === null || $content === false || is_string( $content ) ) {
2693 return $content;
2694 }
2695
2696 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2697 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2698 }
2699
2700 return $content->serialize( $this->contentFormat );
2701 }
2702
2719 protected function toEditContent( $text ) {
2720 if ( $text === false || $text === null ) {
2721 return $text;
2722 }
2723
2724 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2725 $this->contentModel, $this->contentFormat );
2726
2727 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2728 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2729 }
2730
2731 return $content;
2732 }
2733
2742 public function showEditForm( $formCallback = null ) {
2743 # need to parse the preview early so that we know which templates are used,
2744 # otherwise users with "show preview after edit box" will get a blank list
2745 # we parse this near the beginning so that setHeaders can do the title
2746 # setting work instead of leaving it in getPreviewText
2747 $previewOutput = '';
2748 if ( $this->formtype == 'preview' ) {
2749 $previewOutput = $this->getPreviewText();
2750 }
2751
2752 $out = $this->context->getOutput();
2753
2754 // Avoid PHP 7.1 warning of passing $this by reference
2755 $editPage = $this;
2756 Hooks::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2757
2758 $this->setHeaders();
2759
2760 $this->addTalkPageText();
2761 $this->addEditNotices();
2762
2763 if ( !$this->isConflict &&
2764 $this->section != '' &&
2765 !$this->isSectionEditSupported() ) {
2766 // We use $this->section to much before this and getVal('wgSection') directly in other places
2767 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2768 // Someone is welcome to try refactoring though
2769 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2770 return;
2771 }
2772
2773 $this->showHeader();
2774
2775 $out->addHTML( $this->editFormPageTop );
2776
2777 $user = $this->context->getUser();
2778 if ( $user->getOption( 'previewontop' ) ) {
2779 $this->displayPreviewArea( $previewOutput, true );
2780 }
2781
2782 $out->addHTML( $this->editFormTextTop );
2783
2784 if ( $this->wasDeletedSinceLastEdit() ) {
2785 if ( $this->formtype !== 'save' ) {
2786 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2787 'deletedwhileediting' );
2788 }
2789 }
2790
2791 // @todo add EditForm plugin interface and use it here!
2792 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2793 $out->addHTML( Html::openElement(
2794 'form',
2795 [
2796 'class' => 'mw-editform',
2797 'id' => self::EDITFORM_ID,
2798 'name' => self::EDITFORM_ID,
2799 'method' => 'post',
2800 'action' => $this->getActionURL( $this->getContextTitle() ),
2801 'enctype' => 'multipart/form-data'
2802 ]
2803 ) );
2804
2805 if ( is_callable( $formCallback ) ) {
2806 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2807 call_user_func_array( $formCallback, [ &$out ] );
2808 }
2809
2810 // Add a check for Unicode support
2811 $out->addHTML( Html::hidden( 'wpUnicodeCheck', self::UNICODE_CHECK ) );
2812
2813 // Add an empty field to trip up spambots
2814 $out->addHTML(
2815 Xml::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2816 . Html::rawElement(
2817 'label',
2818 [ 'for' => 'wpAntispam' ],
2819 $this->context->msg( 'simpleantispam-label' )->parse()
2820 )
2821 . Xml::element(
2822 'input',
2823 [
2824 'type' => 'text',
2825 'name' => 'wpAntispam',
2826 'id' => 'wpAntispam',
2827 'value' => ''
2828 ]
2829 )
2830 . Xml::closeElement( 'div' )
2831 );
2832
2833 // Avoid PHP 7.1 warning of passing $this by reference
2834 $editPage = $this;
2835 Hooks::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2836
2837 // Put these up at the top to ensure they aren't lost on early form submission
2838 $this->showFormBeforeText();
2839
2840 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2841 $username = $this->lastDelete->user_name;
2842 $comment = CommentStore::getStore()
2843 ->getComment( 'log_comment', $this->lastDelete )->text;
2844
2845 // It is better to not parse the comment at all than to have templates expanded in the middle
2846 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2847 $key = $comment === ''
2848 ? 'confirmrecreate-noreason'
2849 : 'confirmrecreate';
2850 $out->addHTML(
2851 '<div class="mw-confirm-recreate">' .
2852 $this->context->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2853 Xml::checkLabel( $this->context->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2854 [ 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2855 ) .
2856 '</div>'
2857 );
2858 }
2859
2860 # When the summary is hidden, also hide them on preview/show changes
2861 if ( $this->nosummary ) {
2862 $out->addHTML( Html::hidden( 'nosummary', true ) );
2863 }
2864
2865 # If a blank edit summary was previously provided, and the appropriate
2866 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2867 # user being bounced back more than once in the event that a summary
2868 # is not required.
2869 # ####
2870 # For a bit more sophisticated detection of blank summaries, hash the
2871 # automatic one and pass that in the hidden field wpAutoSummary.
2872 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2873 $out->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2874 }
2875
2876 if ( $this->undidRev ) {
2877 $out->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2878 }
2879
2880 if ( $this->selfRedirect ) {
2881 $out->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2882 }
2883
2884 if ( $this->hasPresetSummary ) {
2885 // If a summary has been preset using &summary= we don't want to prompt for
2886 // a different summary. Only prompt for a summary if the summary is blanked.
2887 // (T19416)
2888 $this->autoSumm = md5( '' );
2889 }
2890
2891 $autosumm = $this->autoSumm !== '' ? $this->autoSumm : md5( $this->summary );
2892 $out->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2893
2894 $out->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2895 $out->addHTML( Html::hidden( 'parentRevId', $this->getParentRevId() ) );
2896
2897 $out->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2898 $out->addHTML( Html::hidden( 'model', $this->contentModel ) );
2899
2900 $out->enableOOUI();
2901
2902 if ( $this->section == 'new' ) {
2903 $this->showSummaryInput( true, $this->summary );
2904 $out->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2905 }
2906
2907 $out->addHTML( $this->editFormTextBeforeContent );
2908 if ( $this->isConflict ) {
2909 // In an edit conflict, we turn textbox2 into the user's text,
2910 // and textbox1 into the stored version
2911 $this->textbox2 = $this->textbox1;
2912
2913 $content = $this->getCurrentContent();
2914 $this->textbox1 = $this->toEditText( $content );
2915
2917 $editConflictHelper->setTextboxes( $this->textbox2, $this->textbox1 );
2918 $editConflictHelper->setContentModel( $this->contentModel );
2919 $editConflictHelper->setContentFormat( $this->contentFormat );
2921 }
2922
2923 if ( !$this->mTitle->isUserConfigPage() ) {
2924 $out->addHTML( self::getEditToolbar( $this->mTitle ) );
2925 }
2926
2927 if ( $this->blankArticle ) {
2928 $out->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2929 }
2930
2931 if ( $this->isConflict ) {
2932 // In an edit conflict bypass the overridable content form method
2933 // and fallback to the raw wpTextbox1 since editconflicts can't be
2934 // resolved between page source edits and custom ui edits using the
2935 // custom edit ui.
2936 $conflictTextBoxAttribs = [];
2937 if ( $this->wasDeletedSinceLastEdit() ) {
2938 $conflictTextBoxAttribs['style'] = 'display:none;';
2939 } elseif ( $this->isOldRev ) {
2940 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2941 }
2942
2943 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2945 } else {
2946 $this->showContentForm();
2947 }
2948
2949 $out->addHTML( $this->editFormTextAfterContent );
2950
2951 $this->showStandardInputs();
2952
2953 $this->showFormAfterText();
2954
2955 $this->showTosSummary();
2956
2957 $this->showEditTools();
2958
2959 $out->addHTML( $this->editFormTextAfterTools . "\n" );
2960
2961 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2962
2963 $out->addHTML( Html::rawElement( 'div', [ 'class' => 'hiddencats' ],
2964 Linker::formatHiddenCategories( $this->page->getHiddenCategories() ) ) );
2965
2966 $out->addHTML( Html::rawElement( 'div', [ 'class' => 'limitreport' ],
2967 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2968
2969 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2970
2971 if ( $this->isConflict ) {
2972 try {
2973 $this->showConflict();
2974 } catch ( MWContentSerializationException $ex ) {
2975 // this can't really happen, but be nice if it does.
2976 $msg = $this->context->msg(
2977 'content-failed-to-parse',
2978 $this->contentModel,
2979 $this->contentFormat,
2980 $ex->getMessage()
2981 );
2982 $out->addWikiText( '<div class="error">' . $msg->plain() . '</div>' );
2983 }
2984 }
2985
2986 // Set a hidden field so JS knows what edit form mode we are in
2987 if ( $this->isConflict ) {
2988 $mode = 'conflict';
2989 } elseif ( $this->preview ) {
2990 $mode = 'preview';
2991 } elseif ( $this->diff ) {
2992 $mode = 'diff';
2993 } else {
2994 $mode = 'text';
2995 }
2996 $out->addHTML( Html::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2997
2998 // Marker for detecting truncated form data. This must be the last
2999 // parameter sent in order to be of use, so do not move me.
3000 $out->addHTML( Html::hidden( 'wpUltimateParam', true ) );
3001 $out->addHTML( $this->editFormTextBottom . "\n</form>\n" );
3002
3003 if ( !$user->getOption( 'previewontop' ) ) {
3004 $this->displayPreviewArea( $previewOutput, false );
3005 }
3006 }
3007
3015 public function makeTemplatesOnThisPageList( array $templates ) {
3016 $templateListFormatter = new TemplatesOnThisPageFormatter(
3017 $this->context, MediaWikiServices::getInstance()->getLinkRenderer()
3018 );
3019
3020 // preview if preview, else section if section, else false
3021 $type = false;
3022 if ( $this->preview ) {
3023 $type = 'preview';
3024 } elseif ( $this->section != '' ) {
3025 $type = 'section';
3026 }
3027
3028 return Html::rawElement( 'div', [ 'class' => 'templatesUsed' ],
3029 $templateListFormatter->format( $templates, $type )
3030 );
3031 }
3032
3039 public static function extractSectionTitle( $text ) {
3040 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
3041 if ( !empty( $matches[2] ) ) {
3042 global $wgParser;
3043 return $wgParser->stripSectionName( trim( $matches[2] ) );
3044 } else {
3045 return false;
3046 }
3047 }
3048
3049 protected function showHeader() {
3050 $out = $this->context->getOutput();
3051 $user = $this->context->getUser();
3052 if ( $this->isConflict ) {
3054 $this->editRevId = $this->page->getLatest();
3055 } else {
3056 if ( $this->section != '' && $this->section != 'new' ) {
3057 if ( !$this->summary && !$this->preview && !$this->diff ) {
3058 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
3059 if ( $sectionTitle !== false ) {
3060 $this->summary = "/* $sectionTitle */ ";
3061 }
3062 }
3063 }
3064
3065 $buttonLabel = $this->context->msg( $this->getSubmitButtonLabel() )->text();
3066
3067 if ( $this->missingComment ) {
3068 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3069 }
3070
3071 if ( $this->missingSummary && $this->section != 'new' ) {
3072 $out->wrapWikiMsg(
3073 "<div id='mw-missingsummary'>\n$1\n</div>",
3074 [ 'missingsummary', $buttonLabel ]
3075 );
3076 }
3077
3078 if ( $this->missingSummary && $this->section == 'new' ) {
3079 $out->wrapWikiMsg(
3080 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3081 [ 'missingcommentheader', $buttonLabel ]
3082 );
3083 }
3084
3085 if ( $this->blankArticle ) {
3086 $out->wrapWikiMsg(
3087 "<div id='mw-blankarticle'>\n$1\n</div>",
3088 [ 'blankarticle', $buttonLabel ]
3089 );
3090 }
3091
3092 if ( $this->selfRedirect ) {
3093 $out->wrapWikiMsg(
3094 "<div id='mw-selfredirect'>\n$1\n</div>",
3095 [ 'selfredirect', $buttonLabel ]
3096 );
3097 }
3098
3099 if ( $this->hookError !== '' ) {
3100 $out->addWikiText( $this->hookError );
3101 }
3102
3103 if ( $this->section != 'new' ) {
3104 $revision = $this->mArticle->getRevisionFetched();
3105 if ( $revision ) {
3106 // Let sysop know that this will make private content public if saved
3107
3108 if ( !$revision->userCan( Revision::DELETED_TEXT, $user ) ) {
3109 $out->wrapWikiMsg(
3110 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3111 'rev-deleted-text-permission'
3112 );
3113 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
3114 $out->wrapWikiMsg(
3115 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3116 'rev-deleted-text-view'
3117 );
3118 }
3119
3120 if ( !$revision->isCurrent() ) {
3121 $this->mArticle->setOldSubtitle( $revision->getId() );
3122 $out->addWikiMsg( 'editingold' );
3123 $this->isOldRev = true;
3124 }
3125 } elseif ( $this->mTitle->exists() ) {
3126 // Something went wrong
3127
3128 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3129 [ 'missing-revision', $this->oldid ] );
3130 }
3131 }
3132 }
3133
3134 if ( wfReadOnly() ) {
3135 $out->wrapWikiMsg(
3136 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3137 [ 'readonlywarning', wfReadOnlyReason() ]
3138 );
3139 } elseif ( $user->isAnon() ) {
3140 if ( $this->formtype != 'preview' ) {
3141 $out->wrapWikiMsg(
3142 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3143 [ 'anoneditwarning',
3144 // Log-in link
3145 SpecialPage::getTitleFor( 'Userlogin' )->getFullURL( [
3146 'returnto' => $this->getTitle()->getPrefixedDBkey()
3147 ] ),
3148 // Sign-up link
3149 SpecialPage::getTitleFor( 'CreateAccount' )->getFullURL( [
3150 'returnto' => $this->getTitle()->getPrefixedDBkey()
3151 ] )
3152 ]
3153 );
3154 } else {
3155 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3156 'anonpreviewwarning'
3157 );
3158 }
3159 } else {
3160 if ( $this->mTitle->isUserConfigPage() ) {
3161 # Check the skin exists
3162 if ( $this->isWrongCaseUserConfigPage() ) {
3163 $out->wrapWikiMsg(
3164 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3165 [ 'userinvalidconfigtitle', $this->mTitle->getSkinFromConfigSubpage() ]
3166 );
3167 }
3168 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3169 $isUserCssConfig = $this->mTitle->isUserCssConfigPage();
3170 $isUserJsonConfig = $this->mTitle->isUserJsonConfigPage();
3171 $isUserJsConfig = $this->mTitle->isUserJsConfigPage();
3172
3173 $warning = $isUserCssConfig
3174 ? 'usercssispublic'
3175 : ( $isUserJsonConfig ? 'userjsonispublic' : 'userjsispublic' );
3176
3177 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3178
3179 if ( $this->formtype !== 'preview' ) {
3180 $config = $this->context->getConfig();
3181 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3182 $out->wrapWikiMsg(
3183 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3184 [ 'usercssyoucanpreview' ]
3185 );
3186 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3187 $out->wrapWikiMsg(
3188 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3189 [ 'userjsonyoucanpreview' ]
3190 );
3191 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3192 $out->wrapWikiMsg(
3193 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3194 [ 'userjsyoucanpreview' ]
3195 );
3196 }
3197 }
3198 }
3199 }
3200 }
3201
3203
3204 $this->addLongPageWarningHeader();
3205
3206 # Add header copyright warning
3208 }
3209
3217 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3218 $conf = $this->context->getConfig();
3219 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD;
3220 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3221 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3222 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
3223 return ( is_array( $inputAttrs ) ? $inputAttrs : [] ) + [
3224 'id' => 'wpSummary',
3225 'name' => 'wpSummary',
3226 'maxlength' => $oldCommentSchema ? 200 : CommentStore::COMMENT_CHARACTER_LIMIT,
3227 'tabindex' => 1,
3228 'size' => 60,
3229 'spellcheck' => 'true',
3230 ];
3231 }
3232
3242 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3243 $inputAttrs = OOUI\Element::configFromHtmlAttributes(
3244 $this->getSummaryInputAttributes( $inputAttrs )
3245 );
3246 $inputAttrs += [
3247 'title' => Linker::titleAttrib( 'summary' ),
3248 'accessKey' => Linker::accesskey( 'summary' ),
3249 ];
3250
3251 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3252 $inputAttrs['inputId'] = $inputAttrs['id'];
3253 $inputAttrs['id'] = 'wpSummaryWidget';
3254
3255 return new OOUI\FieldLayout(
3256 new OOUI\TextInputWidget( [
3257 'value' => $summary,
3258 'infusable' => true,
3259 ] + $inputAttrs ),
3260 [
3261 'label' => new OOUI\HtmlSnippet( $labelText ),
3262 'align' => 'top',
3263 'id' => 'wpSummaryLabel',
3264 'classes' => [ $this->missingSummary ? 'mw-summarymissed' : 'mw-summary' ],
3265 ]
3266 );
3267 }
3268
3275 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3276 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3277 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
3278 if ( $isSubjectPreview ) {
3279 if ( $this->nosummary ) {
3280 return;
3281 }
3282 } else {
3283 if ( !$this->mShowSummaryField ) {
3284 return;
3285 }
3286 }
3287
3288 $labelText = $this->context->msg( $isSubjectPreview ? 'subject' : 'summary' )->parse();
3289 $this->context->getOutput()->addHTML( $this->getSummaryInputWidget(
3290 $summary,
3291 $labelText,
3292 [ 'class' => $summaryClass ]
3293 ) );
3294 }
3295
3303 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3304 // avoid spaces in preview, gets always trimmed on save
3305 $summary = trim( $summary );
3306 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
3307 return "";
3308 }
3309
3310 global $wgParser;
3311
3312 if ( $isSubjectPreview ) {
3313 $summary = $this->context->msg( 'newsectionsummary' )
3314 ->rawParams( $wgParser->stripSectionName( $summary ) )
3315 ->inContentLanguage()->text();
3316 }
3317
3318 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
3319
3320 $summary = $this->context->msg( $message )->parse()
3321 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
3322 return Xml::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3323 }
3324
3325 protected function showFormBeforeText() {
3326 $out = $this->context->getOutput();
3327 $out->addHTML( Html::hidden( 'wpSection', $this->section ) );
3328 $out->addHTML( Html::hidden( 'wpStarttime', $this->starttime ) );
3329 $out->addHTML( Html::hidden( 'wpEdittime', $this->edittime ) );
3330 $out->addHTML( Html::hidden( 'editRevId', $this->editRevId ) );
3331 $out->addHTML( Html::hidden( 'wpScrolltop', $this->scrolltop, [ 'id' => 'wpScrolltop' ] ) );
3332 }
3333
3334 protected function showFormAfterText() {
3347 $this->context->getOutput()->addHTML(
3348 "\n" .
3349 Html::hidden( "wpEditToken", $this->context->getUser()->getEditToken() ) .
3350 "\n"
3351 );
3352 }
3353
3362 protected function showContentForm() {
3363 $this->showTextbox1();
3364 }
3365
3374 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3375 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
3376 $attribs = [ 'style' => 'display:none;' ];
3377 } else {
3378 $builder = new TextboxBuilder();
3379 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3380
3381 # Is an old revision being edited?
3382 if ( $this->isOldRev ) {
3383 $classes[] = 'mw-textarea-oldrev';
3384 }
3385
3386 $attribs = [ 'tabindex' => 1 ];
3387
3388 if ( is_array( $customAttribs ) ) {
3390 }
3391
3392 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3393 }
3394
3395 $this->showTextbox(
3396 $textoverride ?? $this->textbox1,
3397 'wpTextbox1',
3398 $attribs
3399 );
3400 }
3401
3402 protected function showTextbox2() {
3403 $this->showTextbox( $this->textbox2, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3404 }
3405
3406 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3407 $builder = new TextboxBuilder();
3408 $attribs = $builder->buildTextboxAttribs(
3409 $name,
3411 $this->context->getUser(),
3412 $this->mTitle
3413 );
3414
3415 $this->context->getOutput()->addHTML(
3416 Html::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3417 );
3418 }
3419
3420 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3421 $classes = [];
3422 if ( $isOnTop ) {
3423 $classes[] = 'ontop';
3424 }
3425
3426 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3427
3428 if ( $this->formtype != 'preview' ) {
3429 $attribs['style'] = 'display: none;';
3430 }
3431
3432 $out = $this->context->getOutput();
3433 $out->addHTML( Xml::openElement( 'div', $attribs ) );
3434
3435 if ( $this->formtype == 'preview' ) {
3436 $this->showPreview( $previewOutput );
3437 } else {
3438 // Empty content container for LivePreview
3439 $pageViewLang = $this->mTitle->getPageViewLanguage();
3440 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3441 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3442 $out->addHTML( Html::rawElement( 'div', $attribs ) );
3443 }
3444
3445 $out->addHTML( '</div>' );
3446
3447 if ( $this->formtype == 'diff' ) {
3448 try {
3449 $this->showDiff();
3450 } catch ( MWContentSerializationException $ex ) {
3451 $msg = $this->context->msg(
3452 'content-failed-to-parse',
3453 $this->contentModel,
3454 $this->contentFormat,
3455 $ex->getMessage()
3456 );
3457 $out->addWikiText( '<div class="error">' . $msg->plain() . '</div>' );
3458 }
3459 }
3460 }
3461
3468 protected function showPreview( $text ) {
3469 if ( $this->mArticle instanceof CategoryPage ) {
3470 $this->mArticle->openShowCategory();
3471 }
3472 # This hook seems slightly odd here, but makes things more
3473 # consistent for extensions.
3474 $out = $this->context->getOutput();
3475 Hooks::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3476 $out->addHTML( $text );
3477 if ( $this->mArticle instanceof CategoryPage ) {
3478 $this->mArticle->closeShowCategory();
3479 }
3480 }
3481
3489 public function showDiff() {
3490 $oldtitlemsg = 'currentrev';
3491 # if message does not exist, show diff against the preloaded default
3492 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3493 $oldtext = $this->mTitle->getDefaultMessageText();
3494 if ( $oldtext !== false ) {
3495 $oldtitlemsg = 'defaultmessagetext';
3496 $oldContent = $this->toEditContent( $oldtext );
3497 } else {
3498 $oldContent = null;
3499 }
3500 } else {
3501 $oldContent = $this->getCurrentContent();
3502 }
3503
3504 $textboxContent = $this->toEditContent( $this->textbox1 );
3505 if ( $this->editRevId !== null ) {
3506 $newContent = $this->page->replaceSectionAtRev(
3507 $this->section, $textboxContent, $this->summary, $this->editRevId
3508 );
3509 } else {
3510 $newContent = $this->page->replaceSectionContent(
3511 $this->section, $textboxContent, $this->summary, $this->edittime
3512 );
3513 }
3514
3515 if ( $newContent ) {
3516 Hooks::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3517
3518 $user = $this->context->getUser();
3519 $popts = ParserOptions::newFromUserAndLang( $user,
3520 MediaWikiServices::getInstance()->getContentLanguage() );
3521 $newContent = $newContent->preSaveTransform( $this->mTitle, $user, $popts );
3522 }
3523
3524 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3525 $oldtitle = $this->context->msg( $oldtitlemsg )->parse();
3526 $newtitle = $this->context->msg( 'yourtext' )->parse();
3527
3528 if ( !$oldContent ) {
3529 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3530 }
3531
3532 if ( !$newContent ) {
3533 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3534 }
3535
3536 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context );
3537 $de->setContent( $oldContent, $newContent );
3538
3539 $difftext = $de->getDiff( $oldtitle, $newtitle );
3540 $de->showDiffStyle();
3541 } else {
3542 $difftext = '';
3543 }
3544
3545 $this->context->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3546 }
3547
3551 protected function showHeaderCopyrightWarning() {
3552 $msg = 'editpage-head-copy-warn';
3553 if ( !$this->context->msg( $msg )->isDisabled() ) {
3554 $this->context->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3555 'editpage-head-copy-warn' );
3556 }
3557 }
3558
3567 protected function showTosSummary() {
3568 $msg = 'editpage-tos-summary';
3569 Hooks::run( 'EditPageTosSummary', [ $this->mTitle, &$msg ] );
3570 if ( !$this->context->msg( $msg )->isDisabled() ) {
3571 $out = $this->context->getOutput();
3572 $out->addHTML( '<div class="mw-tos-summary">' );
3573 $out->addWikiMsg( $msg );
3574 $out->addHTML( '</div>' );
3575 }
3576 }
3577
3582 protected function showEditTools() {
3583 $this->context->getOutput()->addHTML( '<div class="mw-editTools">' .
3584 $this->context->msg( 'edittools' )->inContentLanguage()->parse() .
3585 '</div>' );
3586 }
3587
3594 protected function getCopywarn() {
3595 return self::getCopyrightWarning( $this->mTitle );
3596 }
3597
3606 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3607 global $wgRightsText;
3608 if ( $wgRightsText ) {
3609 $copywarnMsg = [ 'copyrightwarning',
3610 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3611 $wgRightsText ];
3612 } else {
3613 $copywarnMsg = [ 'copyrightwarning2',
3614 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3615 }
3616 // Allow for site and per-namespace customization of contribution/copyright notice.
3617 Hooks::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3618
3619 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3620 if ( $langcode ) {
3621 $msg->inLanguage( $langcode );
3622 }
3623 return "<div id=\"editpage-copywarn\">\n" .
3624 $msg->$format() . "\n</div>";
3625 }
3626
3634 public static function getPreviewLimitReport( ParserOutput $output = null ) {
3635 global $wgLang;
3636
3637 if ( !$output || !$output->getLimitReportData() ) {
3638 return '';
3639 }
3640
3641 $limitReport = Html::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3642 wfMessage( 'limitreport-title' )->parseAsBlock()
3643 );
3644
3645 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3646 $limitReport .= Html::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3647
3648 $limitReport .= Html::openElement( 'table', [
3649 'class' => 'preview-limit-report wikitable'
3650 ] ) .
3651 Html::openElement( 'tbody' );
3652
3653 foreach ( $output->getLimitReportData() as $key => $value ) {
3654 if ( Hooks::run( 'ParserLimitReportFormat',
3655 [ $key, &$value, &$limitReport, true, true ]
3656 ) ) {
3657 $keyMsg = wfMessage( $key );
3658 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3659 if ( !$valueMsg->exists() ) {
3660 $valueMsg = new RawMessage( '$1' );
3661 }
3662 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3663 $limitReport .= Html::openElement( 'tr' ) .
3664 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3665 Html::rawElement( 'td', null,
3666 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3667 ) .
3668 Html::closeElement( 'tr' );
3669 }
3670 }
3671 }
3672
3673 $limitReport .= Html::closeElement( 'tbody' ) .
3674 Html::closeElement( 'table' ) .
3675 Html::closeElement( 'div' );
3676
3677 return $limitReport;
3678 }
3679
3680 protected function showStandardInputs( &$tabindex = 2 ) {
3681 $out = $this->context->getOutput();
3682 $out->addHTML( "<div class='editOptions'>\n" );
3683
3684 if ( $this->section != 'new' ) {
3685 $this->showSummaryInput( false, $this->summary );
3686 $out->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3687 }
3688
3689 $checkboxes = $this->getCheckboxesWidget(
3690 $tabindex,
3691 [ 'minor' => $this->minoredit, 'watch' => $this->watchthis ]
3692 );
3693 $checkboxesHTML = new OOUI\HorizontalLayout( [ 'items' => $checkboxes ] );
3694
3695 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3696
3697 // Show copyright warning.
3698 $out->addWikiText( $this->getCopywarn() );
3699 $out->addHTML( $this->editFormTextAfterWarn );
3700
3701 $out->addHTML( "<div class='editButtons'>\n" );
3702 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3703
3704 $cancel = $this->getCancelLink();
3705
3706 $message = $this->context->msg( 'edithelppage' )->inContentLanguage()->text();
3707 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3708 $edithelp =
3709 Html::linkButton(
3710 $this->context->msg( 'edithelp' )->text(),
3711 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3712 [ 'mw-ui-quiet' ]
3713 ) .
3714 $this->context->msg( 'word-separator' )->escaped() .
3715 $this->context->msg( 'newwindow' )->parse();
3716
3717 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3718 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3719 $out->addHTML( "</div><!-- editButtons -->\n" );
3720
3721 Hooks::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3722
3723 $out->addHTML( "</div><!-- editOptions -->\n" );
3724 }
3725
3730 protected function showConflict() {
3731 $out = $this->context->getOutput();
3732 // Avoid PHP 7.1 warning of passing $this by reference
3733 $editPage = $this;
3734 if ( Hooks::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3735 $this->incrementConflictStats();
3736
3737 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3738 }
3739 }
3740
3741 protected function incrementConflictStats() {
3742 $this->getEditConflictHelper()->incrementConflictStats();
3743 }
3744
3748 public function getCancelLink() {
3749 $cancelParams = [];
3750 if ( !$this->isConflict && $this->oldid > 0 ) {
3751 $cancelParams['oldid'] = $this->oldid;
3752 } elseif ( $this->getContextTitle()->isRedirect() ) {
3753 $cancelParams['redirect'] = 'no';
3754 }
3755
3756 return new OOUI\ButtonWidget( [
3757 'id' => 'mw-editform-cancel',
3758 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3759 'label' => new OOUI\HtmlSnippet( $this->context->msg( 'cancel' )->parse() ),
3760 'framed' => false,
3761 'infusable' => true,
3762 'flags' => 'destructive',
3763 ] );
3764 }
3765
3775 protected function getActionURL( Title $title ) {
3776 return $title->getLocalURL( [ 'action' => $this->action ] );
3777 }
3778
3786 protected function wasDeletedSinceLastEdit() {
3787 if ( $this->deletedSinceEdit !== null ) {
3789 }
3790
3791 $this->deletedSinceEdit = false;
3792
3793 if ( !$this->mTitle->exists() && $this->mTitle->isDeletedQuick() ) {
3794 $this->lastDelete = $this->getLastDelete();
3795 if ( $this->lastDelete ) {
3796 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3797 if ( $deleteTime > $this->starttime ) {
3798 $this->deletedSinceEdit = true;
3799 }
3800 }
3801 }
3802
3804 }
3805
3811 protected function getLastDelete() {
3812 $dbr = wfGetDB( DB_REPLICA );
3813 $commentQuery = CommentStore::getStore()->getJoin( 'log_comment' );
3814 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
3815 $data = $dbr->selectRow(
3816 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3817 [
3818 'log_type',
3819 'log_action',
3820 'log_timestamp',
3821 'log_namespace',
3822 'log_title',
3823 'log_params',
3824 'log_deleted',
3825 'user_name'
3826 ] + $commentQuery['fields'] + $actorQuery['fields'],
3827 [
3828 'log_namespace' => $this->mTitle->getNamespace(),
3829 'log_title' => $this->mTitle->getDBkey(),
3830 'log_type' => 'delete',
3831 'log_action' => 'delete',
3832 ],
3833 __METHOD__,
3834 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3835 [
3836 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3837 ] + $commentQuery['joins'] + $actorQuery['joins']
3838 );
3839 // Quick paranoid permission checks...
3840 if ( is_object( $data ) ) {
3841 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3842 $data->user_name = $this->context->msg( 'rev-deleted-user' )->escaped();
3843 }
3844
3845 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3846 $data->log_comment_text = $this->context->msg( 'rev-deleted-comment' )->escaped();
3847 $data->log_comment_data = null;
3848 }
3849 }
3850
3851 return $data;
3852 }
3853
3859 public function getPreviewText() {
3860 $out = $this->context->getOutput();
3861 $config = $this->context->getConfig();
3862
3863 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk ) {
3864 // Could be an offsite preview attempt. This is very unsafe if
3865 // HTML is enabled, as it could be an attack.
3866 $parsedNote = '';
3867 if ( $this->textbox1 !== '' ) {
3868 // Do not put big scary notice, if previewing the empty
3869 // string, which happens when you initially edit
3870 // a category page, due to automatic preview-on-open.
3871 $parsedNote = $out->parse( "<div class='previewnote'>" .
3872 $this->context->msg( 'session_fail_preview_html' )->text() . "</div>",
3873 true, /* interface */true );
3874 }
3875 $this->incrementEditFailureStats( 'session_loss' );
3876 return $parsedNote;
3877 }
3878
3879 $note = '';
3880
3881 try {
3882 $content = $this->toEditContent( $this->textbox1 );
3883
3884 $previewHTML = '';
3885 if ( !Hooks::run(
3886 'AlternateEditPreview',
3887 [ $this, &$content, &$previewHTML, &$this->mParserOutput ] )
3888 ) {
3889 return $previewHTML;
3890 }
3891
3892 # provide a anchor link to the editform
3893 $continueEditing = '<span class="mw-continue-editing">' .
3894 '[[#' . self::EDITFORM_ID . '|' .
3895 $this->context->getLanguage()->getArrow() . ' ' .
3896 $this->context->msg( 'continue-editing' )->text() . ']]</span>';
3897 if ( $this->mTriedSave && !$this->mTokenOk ) {
3898 if ( $this->mTokenOkExceptSuffix ) {
3899 $note = $this->context->msg( 'token_suffix_mismatch' )->plain();
3900 $this->incrementEditFailureStats( 'bad_token' );
3901 } else {
3902 $note = $this->context->msg( 'session_fail_preview' )->plain();
3903 $this->incrementEditFailureStats( 'session_loss' );
3904 }
3905 } elseif ( $this->incompleteForm ) {
3906 $note = $this->context->msg( 'edit_form_incomplete' )->plain();
3907 if ( $this->mTriedSave ) {
3908 $this->incrementEditFailureStats( 'incomplete_form' );
3909 }
3910 } else {
3911 $note = $this->context->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3912 }
3913
3914 # don't parse non-wikitext pages, show message about preview
3915 if ( $this->mTitle->isUserConfigPage() || $this->mTitle->isSiteConfigPage() ) {
3916 if ( $this->mTitle->isUserConfigPage() ) {
3917 $level = 'user';
3918 } elseif ( $this->mTitle->isSiteConfigPage() ) {
3919 $level = 'site';
3920 } else {
3921 $level = false;
3922 }
3923
3924 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3925 $format = 'css';
3926 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3927 $format = false;
3928 }
3929 } elseif ( $content->getModel() == CONTENT_MODEL_JSON ) {
3930 $format = 'json';
3931 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3932 $format = false;
3933 }
3934 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3935 $format = 'js';
3936 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3937 $format = false;
3938 }
3939 } else {
3940 $format = false;
3941 }
3942
3943 # Used messages to make sure grep find them:
3944 # Messages: usercsspreview, userjsonpreview, userjspreview,
3945 # sitecsspreview, sitejsonpreview, sitejspreview
3946 if ( $level && $format ) {
3947 $note = "<div id='mw-{$level}{$format}preview'>" .
3948 $this->context->msg( "{$level}{$format}preview" )->text() .
3949 ' ' . $continueEditing . "</div>";
3950 }
3951 }
3952
3953 # If we're adding a comment, we need to show the
3954 # summary as the headline
3955 if ( $this->section === "new" && $this->summary !== "" ) {
3956 $content = $content->addSectionHeader( $this->summary );
3957 }
3958
3959 $hook_args = [ $this, &$content ];
3960 Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3961
3962 $parserResult = $this->doPreviewParse( $content );
3963 $parserOutput = $parserResult['parserOutput'];
3964 $previewHTML = $parserResult['html'];
3965 $this->mParserOutput = $parserOutput;
3966 $out->addParserOutputMetadata( $parserOutput );
3967 if ( $out->userCanPreview() ) {
3968 $out->addContentOverride( $this->getTitle(), $content );
3969 }
3970
3971 if ( count( $parserOutput->getWarnings() ) ) {
3972 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3973 }
3974
3975 } catch ( MWContentSerializationException $ex ) {
3976 $m = $this->context->msg(
3977 'content-failed-to-parse',
3978 $this->contentModel,
3979 $this->contentFormat,
3980 $ex->getMessage()
3981 );
3982 $note .= "\n\n" . $m->parse();
3983 $previewHTML = '';
3984 }
3985
3986 if ( $this->isConflict ) {
3987 $conflict = '<h2 id="mw-previewconflict">'
3988 . $this->context->msg( 'previewconflict' )->escaped() . "</h2>\n";
3989 } else {
3990 $conflict = '<hr />';
3991 }
3992
3993 $previewhead = "<div class='previewnote'>\n" .
3994 '<h2 id="mw-previewheader">' . $this->context->msg( 'preview' )->escaped() . "</h2>" .
3995 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3996
3997 $pageViewLang = $this->mTitle->getPageViewLanguage();
3998 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3999 'class' => 'mw-content-' . $pageViewLang->getDir() ];
4000 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
4001
4002 return $previewhead . $previewHTML . $this->previewTextAfterContent;
4003 }
4004
4005 private function incrementEditFailureStats( $failureType ) {
4006 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
4007 $stats->increment( 'edit.failures.' . $failureType );
4008 }
4009
4014 protected function getPreviewParserOptions() {
4015 $parserOptions = $this->page->makeParserOptions( $this->context );
4016 $parserOptions->setIsPreview( true );
4017 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
4018 $parserOptions->enableLimitReport();
4019
4020 // XXX: we could call $parserOptions->setCurrentRevisionCallback here to force the
4021 // current revision to be null during PST, until setupFakeRevision is called on
4022 // the ParserOptions. Currently, we rely on Parser::getRevisionObject() to ignore
4023 // existing revisions in preview mode.
4024
4025 return $parserOptions;
4026 }
4027
4037 protected function doPreviewParse( Content $content ) {
4038 $user = $this->context->getUser();
4039 $parserOptions = $this->getPreviewParserOptions();
4040
4041 // NOTE: preSaveTransform doesn't have a fake revision to operate on.
4042 // Parser::getRevisionObject() will return null in preview mode,
4043 // causing the context user to be used for {{subst:REVISIONUSER}}.
4044 // XXX: Alternatively, we could also call setupFakeRevision() a second time:
4045 // once before PST with $content, and then after PST with $pstContent.
4046 $pstContent = $content->preSaveTransform( $this->mTitle, $user, $parserOptions );
4047 $scopedCallback = $parserOptions->setupFakeRevision( $this->mTitle, $pstContent, $user );
4048 $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
4049 ScopedCallback::consume( $scopedCallback );
4050 return [
4051 'parserOutput' => $parserOutput,
4052 'html' => $parserOutput->getText( [
4053 'enableSectionEditLinks' => false
4054 ] )
4055 ];
4056 }
4057
4061 public function getTemplates() {
4062 if ( $this->preview || $this->section != '' ) {
4063 $templates = [];
4064 if ( !isset( $this->mParserOutput ) ) {
4065 return $templates;
4066 }
4067 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
4068 foreach ( array_keys( $template ) as $dbk ) {
4069 $templates[] = Title::makeTitle( $ns, $dbk );
4070 }
4071 }
4072 return $templates;
4073 } else {
4074 return $this->mTitle->getTemplateLinksFrom();
4075 }
4076 }
4077
4084 public static function getEditToolbar( $title = null ) {
4085 $startingToolbar = '<div id="toolbar"></div>';
4086 $toolbar = $startingToolbar;
4087
4088 if ( !Hooks::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4089 return null;
4090 };
4091 // Don't add a pointless `<div>` to the page unless a hook caller populated it
4092 return ( $toolbar === $startingToolbar ) ? null : $toolbar;
4093 }
4094
4113 public function getCheckboxesDefinition( $checked ) {
4114 $checkboxes = [];
4115
4116 $user = $this->context->getUser();
4117 // don't show the minor edit checkbox if it's a new page or section
4118 if ( !$this->isNew && $user->isAllowed( 'minoredit' ) ) {
4119 $checkboxes['wpMinoredit'] = [
4120 'id' => 'wpMinoredit',
4121 'label-message' => 'minoredit',
4122 // Uses messages: tooltip-minoredit, accesskey-minoredit
4123 'tooltip' => 'minoredit',
4124 'label-id' => 'mw-editpage-minoredit',
4125 'legacy-name' => 'minor',
4126 'default' => $checked['minor'],
4127 ];
4128 }
4129
4130 if ( $user->isLoggedIn() ) {
4131 $checkboxes['wpWatchthis'] = [
4132 'id' => 'wpWatchthis',
4133 'label-message' => 'watchthis',
4134 // Uses messages: tooltip-watch, accesskey-watch
4135 'tooltip' => 'watch',
4136 'label-id' => 'mw-editpage-watch',
4137 'legacy-name' => 'watch',
4138 'default' => $checked['watch'],
4139 ];
4140 }
4141
4142 $editPage = $this;
4143 Hooks::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4144
4145 return $checkboxes;
4146 }
4147
4158 public function getCheckboxesWidget( &$tabindex, $checked ) {
4159 $checkboxes = [];
4160 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4161
4162 foreach ( $checkboxesDef as $name => $options ) {
4163 $legacyName = $options['legacy-name'] ?? $name;
4164
4165 $title = null;
4166 $accesskey = null;
4167 if ( isset( $options['tooltip'] ) ) {
4168 $accesskey = $this->context->msg( "accesskey-{$options['tooltip']}" )->text();
4169 $title = Linker::titleAttrib( $options['tooltip'] );
4170 }
4171 if ( isset( $options['title-message'] ) ) {
4172 $title = $this->context->msg( $options['title-message'] )->text();
4173 }
4174
4175 $checkboxes[ $legacyName ] = new OOUI\FieldLayout(
4176 new OOUI\CheckboxInputWidget( [
4177 'tabIndex' => ++$tabindex,
4178 'accessKey' => $accesskey,
4179 'id' => $options['id'] . 'Widget',
4180 'inputId' => $options['id'],
4181 'name' => $name,
4182 'selected' => $options['default'],
4183 'infusable' => true,
4184 ] ),
4185 [
4186 'align' => 'inline',
4187 'label' => new OOUI\HtmlSnippet( $this->context->msg( $options['label-message'] )->parse() ),
4188 'title' => $title,
4189 'id' => $options['label-id'] ?? null,
4190 ]
4191 );
4192 }
4193
4194 return $checkboxes;
4195 }
4196
4203 protected function getSubmitButtonLabel() {
4204 $labelAsPublish =
4205 $this->context->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4206
4207 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4208 $newPage = !$this->mTitle->exists();
4209
4210 if ( $labelAsPublish ) {
4211 $buttonLabelKey = $newPage ? 'publishpage' : 'publishchanges';
4212 } else {
4213 $buttonLabelKey = $newPage ? 'savearticle' : 'savechanges';
4214 }
4215
4216 return $buttonLabelKey;
4217 }
4218
4227 public function getEditButtons( &$tabindex ) {
4228 $buttons = [];
4229
4230 $labelAsPublish =
4231 $this->context->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4232
4233 $buttonLabel = $this->context->msg( $this->getSubmitButtonLabel() )->text();
4234 $buttonTooltip = $labelAsPublish ? 'publish' : 'save';
4235
4236 $buttons['save'] = new OOUI\ButtonInputWidget( [
4237 'name' => 'wpSave',
4238 'tabIndex' => ++$tabindex,
4239 'id' => 'wpSaveWidget',
4240 'inputId' => 'wpSave',
4241 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4242 'useInputTag' => true,
4243 'flags' => [ 'progressive', 'primary' ],
4244 'label' => $buttonLabel,
4245 'infusable' => true,
4246 'type' => 'submit',
4247 // Messages used: tooltip-save, tooltip-publish
4248 'title' => Linker::titleAttrib( $buttonTooltip ),
4249 // Messages used: accesskey-save, accesskey-publish
4250 'accessKey' => Linker::accesskey( $buttonTooltip ),
4251 ] );
4252
4253 $buttons['preview'] = new OOUI\ButtonInputWidget( [
4254 'name' => 'wpPreview',
4255 'tabIndex' => ++$tabindex,
4256 'id' => 'wpPreviewWidget',
4257 'inputId' => 'wpPreview',
4258 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4259 'useInputTag' => true,
4260 'label' => $this->context->msg( 'showpreview' )->text(),
4261 'infusable' => true,
4262 'type' => 'submit',
4263 // Message used: tooltip-preview
4264 'title' => Linker::titleAttrib( 'preview' ),
4265 // Message used: accesskey-preview
4266 'accessKey' => Linker::accesskey( 'preview' ),
4267 ] );
4268
4269 $buttons['diff'] = new OOUI\ButtonInputWidget( [
4270 'name' => 'wpDiff',
4271 'tabIndex' => ++$tabindex,
4272 'id' => 'wpDiffWidget',
4273 'inputId' => 'wpDiff',
4274 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4275 'useInputTag' => true,
4276 'label' => $this->context->msg( 'showdiff' )->text(),
4277 'infusable' => true,
4278 'type' => 'submit',
4279 // Message used: tooltip-diff
4280 'title' => Linker::titleAttrib( 'diff' ),
4281 // Message used: accesskey-diff
4282 'accessKey' => Linker::accesskey( 'diff' ),
4283 ] );
4284
4285 // Avoid PHP 7.1 warning of passing $this by reference
4286 $editPage = $this;
4287 Hooks::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4288
4289 return $buttons;
4290 }
4291
4296 public function noSuchSectionPage() {
4297 $out = $this->context->getOutput();
4298 $out->prepareErrorPage( $this->context->msg( 'nosuchsectiontitle' ) );
4299
4300 $res = $this->context->msg( 'nosuchsectiontext', $this->section )->parseAsBlock();
4301
4302 // Avoid PHP 7.1 warning of passing $this by reference
4303 $editPage = $this;
4304 Hooks::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4305 $out->addHTML( $res );
4306
4307 $out->returnToMain( false, $this->mTitle );
4308 }
4309
4315 public function spamPageWithContent( $match = false ) {
4316 $this->textbox2 = $this->textbox1;
4317
4318 if ( is_array( $match ) ) {
4319 $match = $this->context->getLanguage()->listToText( $match );
4320 }
4321 $out = $this->context->getOutput();
4322 $out->prepareErrorPage( $this->context->msg( 'spamprotectiontitle' ) );
4323
4324 $out->addHTML( '<div id="spamprotected">' );
4325 $out->addWikiMsg( 'spamprotectiontext' );
4326 if ( $match ) {
4327 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4328 }
4329 $out->addHTML( '</div>' );
4330
4331 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4332 $this->showDiff();
4333
4334 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4335 $this->showTextbox2();
4336
4337 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4338 }
4339
4350 protected function safeUnicodeInput( $request, $field ) {
4351 return rtrim( $request->getText( $field ) );
4352 }
4353
4363 protected function safeUnicodeOutput( $text ) {
4364 return $text;
4365 }
4366
4370 protected function addEditNotices() {
4371 $out = $this->context->getOutput();
4372 $editNotices = $this->mTitle->getEditNotices( $this->oldid );
4373 if ( count( $editNotices ) ) {
4374 $out->addHTML( implode( "\n", $editNotices ) );
4375 } else {
4376 $msg = $this->context->msg( 'editnotice-notext' );
4377 if ( !$msg->isDisabled() ) {
4378 $out->addHTML(
4379 '<div class="mw-editnotice-notext">'
4380 . $msg->parseAsBlock()
4381 . '</div>'
4382 );
4383 }
4384 }
4385 }
4386
4390 protected function addTalkPageText() {
4391 if ( $this->mTitle->isTalkPage() ) {
4392 $this->context->getOutput()->addWikiMsg( 'talkpagetext' );
4393 }
4394 }
4395
4399 protected function addLongPageWarningHeader() {
4400 if ( $this->contentLength === false ) {
4401 $this->contentLength = strlen( $this->textbox1 );
4402 }
4403
4404 $out = $this->context->getOutput();
4405 $lang = $this->context->getLanguage();
4406 $maxArticleSize = $this->context->getConfig()->get( 'MaxArticleSize' );
4407 if ( $this->tooBig || $this->contentLength > $maxArticleSize * 1024 ) {
4408 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4409 [
4410 'longpageerror',
4411 $lang->formatNum( round( $this->contentLength / 1024, 3 ) ),
4412 $lang->formatNum( $maxArticleSize )
4413 ]
4414 );
4415 } else {
4416 if ( !$this->context->msg( 'longpage-hint' )->isDisabled() ) {
4417 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4418 [
4419 'longpage-hint',
4420 $lang->formatSize( strlen( $this->textbox1 ) ),
4421 strlen( $this->textbox1 )
4422 ]
4423 );
4424 }
4425 }
4426 }
4427
4431 protected function addPageProtectionWarningHeaders() {
4432 $out = $this->context->getOutput();
4433 if ( $this->mTitle->isProtected( 'edit' ) &&
4434 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== [ '' ]
4435 ) {
4436 # Is the title semi-protected?
4437 if ( $this->mTitle->isSemiProtected() ) {
4438 $noticeMsg = 'semiprotectedpagewarning';
4439 } else {
4440 # Then it must be protected based on static groups (regular)
4441 $noticeMsg = 'protectedpagewarning';
4442 }
4443 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle, '',
4444 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4445 }
4446 if ( $this->mTitle->isCascadeProtected() ) {
4447 # Is this page under cascading protection from some source pages?
4449 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
4450 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4451 $cascadeSourcesCount = count( $cascadeSources );
4452 if ( $cascadeSourcesCount > 0 ) {
4453 # Explain, and list the titles responsible
4454 foreach ( $cascadeSources as $page ) {
4455 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4456 }
4457 }
4458 $notice .= '</div>';
4459 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4460 }
4461 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
4462 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle, '',
4463 [ 'lim' => 1,
4464 'showIfEmpty' => false,
4465 'msgKey' => [ 'titleprotectedwarning' ],
4466 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4467 }
4468 }
4469
4475 $out->addHTML(
4476 $this->getEditConflictHelper()->getExplainHeader()
4477 );
4478 }
4479
4487 protected function buildTextboxAttribs( $name, array $customAttribs, User $user ) {
4488 return ( new TextboxBuilder() )->buildTextboxAttribs(
4489 $name, $customAttribs, $user, $this->mTitle
4490 );
4491 }
4492
4498 protected function addNewLineAtEnd( $wikitext ) {
4499 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4500 }
4501
4512 private function guessSectionName( $text ) {
4513 global $wgParser;
4514
4515 // Detect Microsoft browsers
4516 $userAgent = $this->context->getRequest()->getHeader( 'User-Agent' );
4517 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4518 // ...and redirect them to legacy encoding, if available
4519 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4520 }
4521 // Meanwhile, real browsers get real anchors
4522 $name = $wgParser->guessSectionNameFromWikiText( $text );
4523 // With one little caveat: per T216029, fragments in HTTP redirects need to be urlencoded,
4524 // otherwise Chrome double-escapes the rest of the URL.
4525 return '#' . urlencode( mb_substr( $name, 1 ) );
4526 }
4527
4534 public function setEditConflictHelperFactory( callable $factory ) {
4535 $this->editConflictHelperFactory = $factory;
4536 $this->editConflictHelper = null;
4537 }
4538
4542 private function getEditConflictHelper() {
4543 if ( !$this->editConflictHelper ) {
4544 $this->editConflictHelper = call_user_func(
4545 $this->editConflictHelperFactory,
4546 $this->getSubmitButtonLabel()
4547 );
4548 }
4549
4551 }
4552
4557 private function newTextConflictHelper( $submitButtonLabel ) {
4558 return new TextConflictHelper(
4559 $this->getTitle(),
4560 $this->getContext()->getOutput(),
4561 MediaWikiServices::getInstance()->getStatsdDataFactory(),
4562 $submitButtonLabel
4563 );
4564 }
4565}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
target page
$wgSummarySpamRegex
Same as the above except for edit summaries.
$wgRightsText
If either $wgRightsUrl or $wgRightsPage is specified then this variable gives the text for the link.
$wgSpamRegex
Edits matching these regular expressions in body text will be recognised as spam and rejected automat...
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfReadOnly()
Check whether the wiki is in read-only mode.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfFindFile( $title, $options=[])
Find a file.
wfArrayDiff2( $a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$wgParser
Definition Setup.php:921
$wgLang
Definition Setup.php:910
if(! $wgRequest->checkUrlExtension()) if(isset( $_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !='') $wgTitle
Definition api.php:57
Class for viewing MediaWiki article and history.
Definition Article.php:38
const TYPE_AUTO
Definition Block.php:86
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:1174
Special handling for category description pages, showing pages, subcategories and file that belong to...
getContext()
Get the base IContextSource object.
The edit page/HTML interface (split from Article) The actual database and text munging is still in Ar...
Definition EditPage.php:44
getPreviewParserOptions()
Get parser options for a preview.
string $sectiontitle
Definition EditPage.php:375
getActionURL(Title $title)
Returns the URL to use in the form's action attribute.
getEditConflictHelper()
safeUnicodeInput( $request, $field)
Filter an input field through a Unicode de-armoring process if it came from an old browser with known...
bool stdClass $lastDelete
Definition EditPage.php:260
showTextbox( $text, $name, $customAttribs=[])
string $hookError
Definition EditPage.php:302
attemptSave(&$resultDetails=false)
Attempt submission.
$editFormTextAfterTools
Definition EditPage.php:422
isSectionEditSupported()
Returns whether section editing is supported for the current page.
Definition EditPage.php:898
getCheckboxesWidget(&$tabindex, $checked)
Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and any ot...
WikiPage $page
Definition EditPage.php:224
updateWatchlist()
Register the change of watch status.
const AS_SELF_REDIRECT
Status: user tried to create self-redirect (redirect to the same article) and wpIgnoreSelfRedirect ==...
Definition EditPage.php:168
getOriginalContent(User $user)
Get the content of the wanted revision, without section extraction.
getCancelLink()
null string $contentFormat
Definition EditPage.php:409
bool $allowBlankSummary
Definition EditPage.php:284
showCustomIntro()
Attempt to show a custom editing introduction, if supplied.
displayPermissionsError(array $permErrors)
Display a permissions error page, like OutputPage::showPermissionsErrorPage(), but with the following...
Definition EditPage.php:753
bool $firsttime
True the first time the edit form is rendered, false after re-rendering with diff,...
Definition EditPage.php:257
const AS_CANNOT_USE_CUSTOM_MODEL
Status: when changing the content model is disallowed due to $wgContentHandlerUseDB being false.
Definition EditPage.php:185
runPostMergeFilters(Content $content, Status $status, User $user)
Run hooks that can filter edits just before they get saved.
bool $bot
Definition EditPage.php:403
showPreview( $text)
Append preview output to OutputPage.
const AS_UNICODE_NOT_SUPPORTED
Status: edit rejected because browser doesn't support Unicode.
Definition EditPage.php:190
const AS_HOOK_ERROR_EXPECTED
Status: A hook function returned an error.
Definition EditPage.php:68
addTalkPageText()
const AS_READ_ONLY_PAGE_ANON
Status: this anonymous user is not allowed to edit this page.
Definition EditPage.php:83
string $textbox2
Definition EditPage.php:342
bool $tooBig
Definition EditPage.php:275
safeUnicodeOutput( $text)
Filter an output field through a Unicode armoring process if it is going to an old browser with known...
getCheckboxesDefinition( $checked)
Return an array of checkbox definitions.
showEditTools()
Inserts optional text shown below edit and upload forms.
isSupportedContentModel( $modelId)
Returns if the given content model is editable.
Definition EditPage.php:545
$editFormTextAfterContent
Definition EditPage.php:424
$editFormTextBottom
Definition EditPage.php:423
int $editRevId
Revision ID of the latest revision of the page when editing was initiated on the client.
Definition EditPage.php:369
$editFormTextBeforeContent
Definition EditPage.php:420
string $contentModel
Definition EditPage.php:406
bool $deletedSinceEdit
Definition EditPage.php:248
__construct(Article $article)
Definition EditPage.php:475
getEditPermissionErrors( $rigor='secure')
Definition EditPage.php:709
toEditContent( $text)
Turns the given text into a Content object by unserializing it.
int $oldid
Revision ID the edit is based on, or 0 if it's the current revision.
Definition EditPage.php:387
const POST_EDIT_COOKIE_KEY_PREFIX
Prefix of key for cookie used to pass post-edit state.
Definition EditPage.php:201
const AS_MAX_ARTICLE_SIZE_EXCEEDED
Status: article is too big (> $wgMaxArticleSize), after merging in the new section.
Definition EditPage.php:136
const AS_CONFLICT_DETECTED
Status: (non-resolvable) edit conflict.
Definition EditPage.php:120
addExplainConflictHeader(OutputPage $out)
$editFormTextAfterWarn
Definition EditPage.php:421
bool $mTokenOk
Definition EditPage.php:263
getSummaryInputAttributes(array $inputAttrs=null)
Helper function for summary input functions, which returns the necessary attributes for the input.
incrementEditFailureStats( $failureType)
setPostEditCookie( $statusValue)
Sets post-edit cookie indicating the user just saved a particular revision.
showFormBeforeText()
const AS_SPAM_ERROR
Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex.
Definition EditPage.php:146
wasDeletedSinceLastEdit()
Check if a page was deleted while the user was editing it, before submit.
setEditConflictHelperFactory(callable $factory)
Set a factory function to create an EditConflictHelper.
string null $unicodeCheck
What the user submitted in the 'wpUnicodeCheck' field.
Definition EditPage.php:458
const AS_READ_ONLY_PAGE_LOGGED
Status: this logged in user is not allowed to edit this page.
Definition EditPage.php:88
bool $mShowSummaryField
Definition EditPage.php:314
showFormAfterText()
bool $recreate
Definition EditPage.php:334
callable $editConflictHelperFactory
Factory function to create an edit conflict helper.
Definition EditPage.php:465
int $parentRevId
Revision ID the edit is based on, adjusted when an edit conflict is resolved.
Definition EditPage.php:394
isWrongCaseUserConfigPage()
Checks whether the user entered a skin name in uppercase, e.g.
Definition EditPage.php:877
initialiseForm()
Initialise form fields in the object Called on the first invocation, e.g.
static getPreviewLimitReport(ParserOutput $output=null)
Get the Limit report for page previews.
bool $hasPresetSummary
Has a summary been preset using GET parameter &summary= ?
Definition EditPage.php:308
const AS_BLANK_ARTICLE
Status: user tried to create a blank page and wpIgnoreBlankArticle == false.
Definition EditPage.php:115
static matchSummarySpamRegex( $text)
Check given input text against $wgSummarySpamRegex, and return the text of the first match.
handleStatus(Status $status, $resultDetails)
Handle status, such as after attempt save.
importFormData(&$request)
This function collects the form data and uses it to populate various member variables.
Definition EditPage.php:908
static extractSectionTitle( $text)
Extract the section title from current section text, if any.
bool $missingSummary
Definition EditPage.php:281
showTextbox1( $customAttribs=null, $textoverride=null)
Method to output wpTextbox1 The $textoverride method can be used by subclasses overriding showContent...
buildTextboxAttribs( $name, array $customAttribs, User $user)
showDiff()
Get a diff between the current contents of the edit box and the version of the page we're editing fro...
addEditNotices()
Title $mTitle
Definition EditPage.php:230
Revision bool null $mBaseRevision
A revision object corresponding to $this->editRevId.
Definition EditPage.php:311
bool int $contentLength
Definition EditPage.php:438
const AS_PARSE_ERROR
Status: can't parse content.
Definition EditPage.php:179
bool $blankArticle
Definition EditPage.php:287
noSuchSectionPage()
Creates a basic error page which informs the user that they have attempted to edit a nonexistent sect...
bool $mTriedSave
Definition EditPage.php:269
incrementResolvedConflicts()
Log when a page was successfully saved after the edit conflict view.
showConflict()
Show an edit conflict.
guessSectionName( $text)
Turns section name wikitext into anchors for use in HTTP redirects.
const AS_READ_ONLY_PAGE
Status: wiki is in readonly mode (wfReadOnly() == true)
Definition EditPage.php:93
setPreloadedContent(Content $content)
Use this method before edit() to preload some content into the edit box.
static getCopyrightWarning( $title, $format='plain', $langcode=null)
Get the copyright warning, by default returns wikitext.
getParentRevId()
Get the edit's parent revision ID.
tokenOk(&$request)
Make sure the form isn't faking a user's credentials.
makeTemplatesOnThisPageList(array $templates)
Wrapper around TemplatesOnThisPageFormatter to make a "templates on this page" list.
string $section
Definition EditPage.php:372
ParserOutput $mParserOutput
Definition EditPage.php:305
previewOnOpen()
Should we show a preview when the edit form is first shown?
Definition EditPage.php:836
displayPreviewArea( $previewOutput, $isOnTop=false)
doPreviewParse(Content $content)
Parse the page for a preview.
string $formtype
Definition EditPage.php:251
bool $allowBlankArticle
Definition EditPage.php:290
setApiEditOverride( $enableOverride)
Allow editing of content that supports API direct editing, but not general direct editing.
Definition EditPage.php:556
internalAttemptSave(&$result, $bot=false)
Attempt submission (no UI)
string $summary
Definition EditPage.php:345
getSubmitButtonLabel()
Get the message key of the label for the button to save the page.
getSummaryInputWidget( $summary="", $labelText=null, $inputAttrs=null)
Builds a standard summary input with a label.
bool $save
Definition EditPage.php:319
const AS_CONTENT_TOO_BIG
Status: Content too big (> $wgMaxArticleSize)
Definition EditPage.php:78
bool $diff
Definition EditPage.php:325
showStandardInputs(&$tabindex=2)
getCurrentContent()
Get the current content of the page.
bool $selfRedirect
Definition EditPage.php:293
string $textbox1
Page content input field.
Definition EditPage.php:339
addContentModelChangeLogEntry(User $user, $oldModel, $newModel, $reason)
const EDITFORM_ID
HTML id and name for the beginning of the edit form.
Definition EditPage.php:195
const AS_CHANGE_TAG_ERROR
Status: an error relating to change tagging.
Definition EditPage.php:174
string $editFormPageTop
Before even the preview.
Definition EditPage.php:418
const AS_BLOCKED_PAGE_FOR_USER
Status: User is blocked from editing this page.
Definition EditPage.php:73
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:162
getCopywarn()
Get the copyright warning.
const POST_EDIT_COOKIE_DURATION
Duration of PostEdit cookie, in seconds.
Definition EditPage.php:216
static matchSpamRegex( $text)
Check given input text against $wgSpamRegex, and return the text of the first match.
getContextTitle()
Get the context title object.
Definition EditPage.php:528
toEditText( $content)
Gets an editable textual representation of $content.
null Title $mContextTitle
Definition EditPage.php:233
string $autoSumm
Definition EditPage.php:299
bool $isOldRev
Whether an old revision is edited.
Definition EditPage.php:453
const AS_IMAGE_REDIRECT_LOGGED
Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
Definition EditPage.php:156
const AS_END
Status: WikiPage::doEdit() was unsuccessful.
Definition EditPage.php:141
const AS_ARTICLE_WAS_DELETED
Status: article was deleted while editing and param wpRecreate == false or form was not posted.
Definition EditPage.php:104
const AS_TEXTBOX_EMPTY
Status: user tried to create a new section without content.
Definition EditPage.php:131
bool $mTokenOkExceptSuffix
Definition EditPage.php:266
newSectionSummary(&$sectionanchor=null)
Return the summary to be used for a new section.
const AS_SUCCESS_UPDATE
Status: Article successfully updated.
Definition EditPage.php:53
getBaseRevision()
Returns the revision that was current at the time editing was initiated on the client,...
string $starttime
Timestamp from the first time the edit form was rendered.
Definition EditPage.php:380
bool $isNew
New page or new section.
Definition EditPage.php:245
showIntro()
Show all applicable editing introductions.
static getEditToolbar( $title=null)
Allow extensions to provide a toolbar.
Article $mArticle
Definition EditPage.php:222
bool $allowSelfRedirect
Definition EditPage.php:296
const AS_IMAGE_REDIRECT_ANON
Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
Definition EditPage.php:151
getContentObject( $def_content=null)
bool $isConflict
Whether an edit conflict needs to be resolved.
Definition EditPage.php:242
null $scrolltop
Definition EditPage.php:400
getLastDelete()
Get the last log record of this page being deleted, if ever.
string $action
Definition EditPage.php:236
getEditButtons(&$tabindex)
Returns an array of html code of the following buttons: save, diff and preview.
edit()
This is the function that gets called for "action=edit".
Definition EditPage.php:579
string $editintro
Definition EditPage.php:397
newTextConflictHelper( $submitButtonLabel)
bool $enableApiEditOverride
Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing.
Definition EditPage.php:443
displayViewSourcePage(Content $content, $errorMessage='')
Display a read-only View Source page.
Definition EditPage.php:783
bool $watchthis
Definition EditPage.php:331
addPageProtectionWarningHeaders()
addLongPageWarningHeader()
const AS_NO_CREATE_PERMISSION
Status: user tried to create this page, but is not allowed to do that ( Title->userCan('create') == f...
Definition EditPage.php:110
addNewLineAtEnd( $wikitext)
importContentFormData(&$request)
Subpage overridable method for extracting the page content data from the posted form to be placed in ...
showHeaderCopyrightWarning()
Show the header copyright warning.
bool $minoredit
Definition EditPage.php:328
$previewTextAfterContent
Definition EditPage.php:425
getSummaryPreview( $isSubjectPreview, $summary="")
bool $nosummary
If true, hide the summary field.
Definition EditPage.php:350
bool $incompleteForm
Definition EditPage.php:272
const AS_SUCCESS_NEW_ARTICLE
Status: Article successfully created.
Definition EditPage.php:58
showSummaryInput( $isSubjectPreview, $summary="")
mergeChangesIntoContent(&$editContent)
Attempts to do 3-way merge of edit content with a base revision and current content,...
bool $missingComment
Definition EditPage.php:278
string $edittime
Timestamp of the latest revision of the page when editing was initiated on the client.
Definition EditPage.php:356
showTosSummary()
Give a chance for site and per-namespace customizations of terms of service summary link that might e...
const UNICODE_CHECK
Used for Unicode support checks.
Definition EditPage.php:48
getPreviewText()
Get the rendered text for previewing.
formatStatusErrors(Status $status)
Wrap status errors in an errorbox for increased visibility.
showContentForm()
Subpage overridable method for printing the form for page content editing By default this simply outp...
bool $edit
Definition EditPage.php:435
incrementConflictStats()
IContextSource $context
Definition EditPage.php:448
bool $preview
Definition EditPage.php:322
getPreloadedContent( $preload, $params=[])
Get the contents to be preloaded into the box, either set by an earlier setPreloadText() or by loadin...
static matchSpamRegexInternal( $text, $regexes)
TextConflictHelper null $editConflictHelper
Definition EditPage.php:470
showEditForm( $formCallback=null)
Send the edit form and related headers to OutputPage.
null array $changeTags
Definition EditPage.php:412
const AS_RATE_LIMITED
Status: rate limiter for action 'edit' was tripped.
Definition EditPage.php:98
const AS_HOOK_ERROR
Status: Article update aborted by a hook function.
Definition EditPage.php:63
setContextTitle( $title)
Set the context Title object.
Definition EditPage.php:516
spamPageWithContent( $match=false)
Show "your edit contains spam" page with your diff and text.
const AS_SUMMARY_NEEDED
Status: no edit summary given and the user has forceeditsummary set and the user is not editing in hi...
Definition EditPage.php:126
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:1967
static accesskey( $name)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition Linker.php:2015
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:1441
static formatHiddenCategories( $hiddencats)
Returns HTML for the "hidden categories on this page" list.
Definition Linker.php:1915
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.
const DELETED_USER
Definition LogPage.php:36
const DELETED_COMMENT
Definition LogPage.php:35
Exception representing a failure to serialize or unserialize a content object.
MediaWiki exception.
Exception thrown when an unregistered content model is requested.
Class for creating new log entries and inserting them into the database.
Definition LogEntry.php:437
setPerformer(User $performer)
Set the user that performed the action being logged.
Definition LogEntry.php:532
Helper for displaying edit conflicts in text content models to users.
getEditFormHtmlAfterContent()
Content to go in the edit form after textbox1.
getEditConflictMainTextBox(array $customAttribs=[])
HTML to build the textbox1 on edit conflicts.
setTextboxes( $yourtext, $storedversion)
getEditFormHtmlBeforeContent()
Content to go in the edit form before textbox1.
Helps EditPage build textboxes.
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
This class should be covered by a general architecture document which does not exist as of January 20...
Show an error when a user tries to do something they do not have the necessary permissions for.
Variant of the Message class.
Show an error when the wiki is locked/read-only and the user tries to do something that requires writ...
static loadFromTitle( $db, $title, $id=0)
Load either the current, or a specified, revision that's attached to a given page.
Definition Revision.php:273
static loadFromTimestamp( $db, $title, $timestamp)
Load the revision for the given title with the given timestamp.
Definition Revision.php:291
const DELETED_TEXT
Definition Revision.php:47
static userWasLastToEdit( $db, $pageId, $userId, $since)
Check if no edits were made by other users since the time a user started editing the page.
const RAW
Definition Revision.php:57
const FOR_THIS_USER
Definition Revision.php:56
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
Definition Revision.php:114
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:40
Handles formatting for the "templates used on this page" lists.
Show an error when the user hits a rate limit.
Represents a title within MediaWiki.
Definition Title.php:39
setContentModel( $model)
Set a proposed content model for the page for permissions checking.
Definition Title.php:1022
Show an error when the user tries to do something whilst blocked.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:47
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition User.php:592
const IGNORE_USER_RIGHTS
Definition User.php:84
static isIP( $name)
Does the string match an anonymous IP address?
Definition User.php:971
static doWatchOrUnwatch( $watch, Title $title, User $user)
Watch or unwatch a page.
Class representing a MediaWiki article and history.
Definition WikiPage.php:44
getRedirectTarget()
If this page is a redirect, get its target.
Definition WikiPage.php:971
getContent( $audience=Revision::FOR_PUBLIC, User $user=null)
Get the content of the current revision.
Definition WikiPage.php:798
isRedirect()
Tests if the article content represents a redirect.
Definition WikiPage.php:612
per default it will return the text for text based content
$res
Definition database.txt:21
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:5
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
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
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
const EDIT_FORCE_BOT
Definition Defines.php:156
const EDIT_UPDATE
Definition Defines.php:153
const NS_USER
Definition Defines.php:66
const CONTENT_MODEL_CSS
Definition Defines.php:237
const NS_FILE
Definition Defines.php:70
const NS_MEDIAWIKI
Definition Defines.php:72
const CONTENT_MODEL_JSON
Definition Defines.php:239
const NS_USER_TALK
Definition Defines.php:67
const MIGRATION_OLD
Definition Defines.php:315
const EDIT_MINOR
Definition Defines.php:154
const CONTENT_MODEL_JAVASCRIPT
Definition Defines.php:236
const EDIT_AUTOSUMMARY
Definition Defines.php:158
const EDIT_NEW
Definition Defines.php:152
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2880
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED since 1.16! 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:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:2042
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:861
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1305
also included in $newHeader if any indicating whether we should show just the diff
Definition hooks.txt:1311
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2050
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing etc
Definition hooks.txt:91
null means default & $customAttribs
Definition hooks.txt:2044
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:994
null for the local wiki Added in
Definition hooks.txt:1627
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:895
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:2055
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:1475
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
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 $out
Definition hooks.txt:894
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:815
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used the name of the old file & $article
Definition hooks.txt:1619
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:2063
this hook is for auditing only $response
Definition hooks.txt:813
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:933
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:1656
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition hooks.txt:2317
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:1818
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
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:247
returning false will NOT prevent logging $e
Definition hooks.txt:2226
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:37
Base interface for content objects.
Definition Content.php:34
Interface for objects which can provide a MediaWiki context on request.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$content
The First
Definition primes.txt:1
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:26
$params
if(!isset( $args[0])) $lang