3 * User interface for page editing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\EditPage\TextboxBuilder
;
24 use MediaWiki\EditPage\TextConflictHelper
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\ScopedCallback
;
30 * The edit page/HTML interface (split from Article)
31 * The actual database and text munging is still in Article,
32 * but it should get easier to call those from alternate
35 * EditPage cares about two distinct titles:
36 * $this->mContextTitle is the page that forms submit to, links point to,
37 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
38 * page in the database that is actually being edited. These are
39 * usually the same, but they are now allowed to be different.
41 * Surgeon General's Warning: prolonged exposure to this class is known to cause
42 * headaches, which may be fatal.
46 * Used for Unicode support checks
48 const UNICODE_CHECK
= 'β³π²β₯πππΎπΈβ΄πΉβ―';
51 * Status: Article successfully updated
53 const AS_SUCCESS_UPDATE
= 200;
56 * Status: Article successfully created
58 const AS_SUCCESS_NEW_ARTICLE
= 201;
61 * Status: Article update aborted by a hook function
63 const AS_HOOK_ERROR
= 210;
66 * Status: A hook function returned an error
68 const AS_HOOK_ERROR_EXPECTED
= 212;
71 * Status: User is blocked from editing this page
73 const AS_BLOCKED_PAGE_FOR_USER
= 215;
76 * Status: Content too big (> $wgMaxArticleSize)
78 const AS_CONTENT_TOO_BIG
= 216;
81 * Status: this anonymous user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_ANON
= 218;
86 * Status: this logged in user is not allowed to edit this page
88 const AS_READ_ONLY_PAGE_LOGGED
= 219;
91 * Status: wiki is in readonly mode (wfReadOnly() == true)
93 const AS_READ_ONLY_PAGE
= 220;
96 * Status: rate limiter for action 'edit' was tripped
98 const AS_RATE_LIMITED
= 221;
101 * Status: article was deleted while editing and param wpRecreate == false or form
104 const AS_ARTICLE_WAS_DELETED
= 222;
107 * Status: user tried to create this page, but is not allowed to do that
108 * ( Title->userCan('create') == false )
110 const AS_NO_CREATE_PERMISSION
= 223;
113 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
115 const AS_BLANK_ARTICLE
= 224;
118 * Status: (non-resolvable) edit conflict
120 const AS_CONFLICT_DETECTED
= 225;
123 * Status: no edit summary given and the user has forceeditsummary set and the user is not
124 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
126 const AS_SUMMARY_NEEDED
= 226;
129 * Status: user tried to create a new section without content
131 const AS_TEXTBOX_EMPTY
= 228;
134 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
136 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
139 * Status: WikiPage::doEdit() was unsuccessful
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
146 const AS_SPAM_ERROR
= 232;
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
151 const AS_IMAGE_REDIRECT_ANON
= 233;
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
156 const AS_IMAGE_REDIRECT_LOGGED
= 234;
159 * Status: user tried to modify the content model, but is not allowed to do that
160 * ( User::isAllowed('editcontentmodel') == false )
162 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
165 * Status: user tried to create self-redirect (redirect to the same article) and
166 * wpIgnoreSelfRedirect == false
168 const AS_SELF_REDIRECT
= 236;
171 * Status: an error relating to change tagging. Look at the message key for
174 const AS_CHANGE_TAG_ERROR
= 237;
177 * Status: can't parse content
179 const AS_PARSE_ERROR
= 240;
182 * Status: when changing the content model is disallowed due to
183 * $wgContentHandlerUseDB being false
185 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
188 * Status: edit rejected because browser doesn't support Unicode.
190 const AS_UNICODE_NOT_SUPPORTED
= 242;
193 * HTML id and name for the beginning of the edit form.
195 const EDITFORM_ID
= 'editform';
198 * Prefix of key for cookie used to pass post-edit state.
199 * The revision id edited is added after this
201 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
204 * Duration of PostEdit cookie, in seconds.
205 * The cookie will be removed instantly if the JavaScript runs.
207 * Otherwise, though, we don't want the cookies to accumulate.
208 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
209 * limit of only 20 cookies per domain. This still applies at least to some
210 * versions of IE without full updates:
211 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
213 * A value of 20 minutes should be enough to take into account slow loads and minor
214 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
216 const POST_EDIT_COOKIE_DURATION
= 1200;
219 * @deprecated for public usage since 1.30 use EditPage::getArticle()
227 * @deprecated for public usage since 1.30 use EditPage::getTitle()
232 /** @var null|Title */
233 private $mContextTitle = null;
236 public $action = 'submit';
239 public $isConflict = false;
241 /** @var bool New page or new section */
242 public $isNew = false;
245 public $deletedSinceEdit;
253 /** @var bool|stdClass */
257 public $mTokenOk = false;
260 public $mTokenOkExceptSuffix = false;
263 public $mTriedSave = false;
266 public $incompleteForm = false;
269 public $tooBig = false;
272 public $missingComment = false;
275 public $missingSummary = false;
278 public $allowBlankSummary = false;
281 protected $blankArticle = false;
284 protected $allowBlankArticle = false;
287 protected $selfRedirect = false;
290 protected $allowSelfRedirect = false;
293 public $autoSumm = '';
296 public $hookError = '';
298 /** @var ParserOutput */
299 public $mParserOutput;
301 /** @var bool Has a summary been preset using GET parameter &summary= ? */
302 public $hasPresetSummary = false;
304 /** @var Revision|bool|null */
305 public $mBaseRevision = false;
308 public $mShowSummaryField = true;
313 public $save = false;
316 public $preview = false;
319 public $diff = false;
322 public $minoredit = false;
325 public $watchthis = false;
328 public $recreate = false;
331 public $textbox1 = '';
334 public $textbox2 = '';
337 public $summary = '';
340 public $nosummary = false;
343 public $edittime = '';
346 private $editRevId = null;
349 public $section = '';
352 public $sectiontitle = '';
355 public $starttime = '';
361 public $parentRevId = 0;
364 public $editintro = '';
367 public $scrolltop = null;
373 public $contentModel;
375 /** @var null|string */
376 public $contentFormat = null;
378 /** @var null|array */
379 private $changeTags = null;
381 # Placeholders for text injection by hooks (must be HTML)
382 # extensions should take care to _append_ to the present value
384 /** @var string Before even the preview */
385 public $editFormPageTop = '';
386 public $editFormTextTop = '';
387 public $editFormTextBeforeContent = '';
388 public $editFormTextAfterWarn = '';
389 public $editFormTextAfterTools = '';
390 public $editFormTextBottom = '';
391 public $editFormTextAfterContent = '';
392 public $previewTextAfterContent = '';
393 public $mPreloadContent = null;
395 /* $didSave should be set to true whenever an article was successfully altered. */
396 public $didSave = false;
397 public $undidRev = 0;
399 public $suppressIntro = false;
405 protected $contentLength = false;
408 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
410 private $enableApiEditOverride = false;
413 * @var IContextSource
418 * @var bool Whether an old revision is edited
420 private $isOldRev = false;
423 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
425 private $unicodeCheck;
428 * Factory function to create an edit conflict helper
432 private $editConflictHelperFactory;
435 * @var TextConflictHelper|null
437 private $editConflictHelper;
440 * @param Article $article
442 public function __construct( Article
$article ) {
443 $this->mArticle
= $article;
444 $this->page
= $article->getPage(); // model object
445 $this->mTitle
= $article->getTitle();
446 $this->context
= $article->getContext();
448 $this->contentModel
= $this->mTitle
->getContentModel();
450 $handler = ContentHandler
::getForModelID( $this->contentModel
);
451 $this->contentFormat
= $handler->getDefaultFormat();
452 $this->editConflictHelperFactory
= [ $this, 'newTextConflictHelper' ];
458 public function getArticle() {
459 return $this->mArticle
;
464 * @return IContextSource
466 public function getContext() {
467 return $this->context
;
474 public function getTitle() {
475 return $this->mTitle
;
479 * Set the context Title object
481 * @param Title|null $title Title object or null
483 public function setContextTitle( $title ) {
484 $this->mContextTitle
= $title;
488 * Get the context title object.
490 * If not set, $wgTitle will be returned, but this is deprecated. This will
491 * throw an exception.
495 public function getContextTitle() {
496 if ( is_null( $this->mContextTitle
) ) {
497 wfDeprecated( __METHOD__
. ' called with no title set', '1.32' );
501 return $this->mContextTitle
;
506 * Returns if the given content model is editable.
508 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
510 * @throws MWException If $modelId has no known handler
512 public function isSupportedContentModel( $modelId ) {
513 return $this->enableApiEditOverride
=== true ||
514 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
518 * Allow editing of content that supports API direct editing, but not general
519 * direct editing. Set to false by default.
521 * @param bool $enableOverride
523 public function setApiEditOverride( $enableOverride ) {
524 $this->enableApiEditOverride
= $enableOverride;
528 * @deprecated since 1.29, call edit directly
530 public function submit() {
531 wfDeprecated( __METHOD__
, '1.29' );
536 * This is the function that gets called for "action=edit". It
537 * sets up various member variables, then passes execution to
538 * another function, usually showEditForm()
540 * The edit form is self-submitting, so that when things like
541 * preview and edit conflicts occur, we get the same form back
542 * with the extra stuff added. Only when the final submission
543 * is made and all is well do we actually save and redirect to
544 * the newly-edited page.
546 public function edit() {
547 // Allow extensions to modify/prevent this form or submission
548 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
552 wfDebug( __METHOD__
. ": enter\n" );
554 $request = $this->context
->getRequest();
555 // If they used redlink=1 and the page exists, redirect to the main article
556 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
557 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
561 $this->importFormData( $request );
562 $this->firsttime
= false;
564 if ( wfReadOnly() && $this->save
) {
567 $this->preview
= true;
571 $this->formtype
= 'save';
572 } elseif ( $this->preview
) {
573 $this->formtype
= 'preview';
574 } elseif ( $this->diff
) {
575 $this->formtype
= 'diff';
576 } else { # First time through
577 $this->firsttime
= true;
578 if ( $this->previewOnOpen() ) {
579 $this->formtype
= 'preview';
581 $this->formtype
= 'initial';
585 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
587 wfDebug( __METHOD__
. ": User can't edit\n" );
589 // track block with a cookie if it doesn't exists already
590 $this->context
->getUser()->trackBlockWithCookie();
592 // Auto-block user's IP if the account was "hard" blocked
593 if ( !wfReadOnly() ) {
594 DeferredUpdates
::addCallableUpdate( function () {
595 $this->context
->getUser()->spreadAnyEditBlock();
598 $this->displayPermissionsError( $permErrors );
603 $revision = $this->mArticle
->getRevisionFetched();
604 // Disallow editing revisions with content models different from the current one
605 // Undo edits being an exception in order to allow reverting content model changes.
607 && $revision->getContentModel() !== $this->contentModel
610 if ( $this->undidRev
) {
611 $undidRevObj = Revision
::newFromId( $this->undidRev
);
612 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
614 if ( !$this->undidRev
616 ||
$prevRev->getContentModel() !== $this->contentModel
618 $this->displayViewSourcePage(
619 $this->getContentObject(),
621 'contentmodelediterror',
622 $revision->getContentModel(),
630 $this->isConflict
= false;
632 # Show applicable editing introductions
633 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
637 # Attempt submission here. This will check for edit conflicts,
638 # and redundantly check for locked database, blocked IPs, etc.
639 # that edit() already checked just in case someone tries to sneak
640 # in the back door with a hand-edited submission URL.
642 if ( 'save' == $this->formtype
) {
643 $resultDetails = null;
644 $status = $this->attemptSave( $resultDetails );
645 if ( !$this->handleStatus( $status, $resultDetails ) ) {
650 # First time through: get contents, set time for conflict
652 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
653 if ( $this->initialiseForm() === false ) {
654 $this->noSuchSectionPage();
658 if ( !$this->mTitle
->getArticleID() ) {
659 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
661 Hooks
::run( 'EditFormInitialText', [ $this ] );
666 $this->showEditForm();
670 * @param string $rigor Same format as Title::getUserPermissionErrors()
673 protected function getEditPermissionErrors( $rigor = 'secure' ) {
674 $user = $this->context
->getUser();
675 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
676 # Can this title be created?
677 if ( !$this->mTitle
->exists() ) {
678 $permErrors = array_merge(
681 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
686 # Ignore some permissions errors when a user is just previewing/viewing diffs
688 foreach ( $permErrors as $error ) {
689 if ( ( $this->preview ||
$this->diff
)
691 $error[0] == 'blockedtext' ||
692 $error[0] == 'autoblockedtext' ||
693 $error[0] == 'systemblockedtext'
699 $permErrors = wfArrayDiff2( $permErrors, $remove );
705 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
706 * but with the following differences:
707 * - If redlink=1, the user will be redirected to the page
708 * - If there is content to display or the error occurs while either saving,
709 * previewing or showing the difference, it will be a
710 * "View source for ..." page displaying the source code after the error message.
713 * @param array $permErrors Array of permissions errors, as returned by
714 * Title::getUserPermissionsErrors().
715 * @throws PermissionsError
717 protected function displayPermissionsError( array $permErrors ) {
718 $out = $this->context
->getOutput();
719 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
720 // The edit page was reached via a red link.
721 // Redirect to the article page and let them click the edit tab if
722 // they really want a permission error.
723 $out->redirect( $this->mTitle
->getFullURL() );
727 $content = $this->getContentObject();
729 # Use the normal message if there's nothing to display
730 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
731 $action = $this->mTitle
->exists() ?
'edit' :
732 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
733 throw new PermissionsError( $action, $permErrors );
736 $this->displayViewSourcePage(
738 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
743 * Display a read-only View Source page
744 * @param Content $content
745 * @param string $errorMessage additional wikitext error message to display
747 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
748 $out = $this->context
->getOutput();
749 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
751 $out->setRobotPolicy( 'noindex,nofollow' );
752 $out->setPageTitle( $this->context
->msg(
754 $this->getContextTitle()->getPrefixedText()
756 $out->addBacklinkSubtitle( $this->getContextTitle() );
757 $out->addHTML( $this->editFormPageTop
);
758 $out->addHTML( $this->editFormTextTop
);
760 if ( $errorMessage !== '' ) {
761 $out->addWikiText( $errorMessage );
762 $out->addHTML( "<hr />\n" );
765 # If the user made changes, preserve them when showing the markup
766 # (This happens when a user is blocked during edit, for instance)
767 if ( !$this->firsttime
) {
768 $text = $this->textbox1
;
769 $out->addWikiMsg( 'viewyourtext' );
772 $text = $this->toEditText( $content );
773 } catch ( MWException
$e ) {
774 # Serialize using the default format if the content model is not supported
775 # (e.g. for an old revision with a different model)
776 $text = $content->serialize();
778 $out->addWikiMsg( 'viewsourcetext' );
781 $out->addHTML( $this->editFormTextBeforeContent
);
782 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
783 $out->addHTML( $this->editFormTextAfterContent
);
785 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
787 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
789 $out->addHTML( $this->editFormTextBottom
);
790 if ( $this->mTitle
->exists() ) {
791 $out->returnToMain( null, $this->mTitle
);
796 * Should we show a preview when the edit form is first shown?
800 protected function previewOnOpen() {
801 $config = $this->context
->getConfig();
802 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
803 $request = $this->context
->getRequest();
804 if ( $config->get( 'RawHtml' ) ) {
805 // If raw HTML is enabled, disable preview on open
806 // since it has to be posted with a token for
810 if ( $request->getVal( 'preview' ) == 'yes' ) {
811 // Explicit override from request
813 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
814 // Explicit override from request
816 } elseif ( $this->section
== 'new' ) {
817 // Nothing *to* preview for new sections
819 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
820 && $this->context
->getUser()->getOption( 'previewonfirst' )
822 // Standard preference behavior
824 } elseif ( !$this->mTitle
->exists()
825 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
826 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
828 // Categories are special
836 * Checks whether the user entered a skin name in uppercase,
837 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
841 protected function isWrongCaseUserConfigPage() {
842 if ( $this->mTitle
->isUserConfigPage() ) {
843 $name = $this->mTitle
->getSkinFromConfigSubpage();
844 $skins = array_merge(
845 array_keys( Skin
::getSkinNames() ),
848 return !in_array( $name, $skins )
849 && in_array( strtolower( $name ), $skins );
856 * Returns whether section editing is supported for the current page.
857 * Subclasses may override this to replace the default behavior, which is
858 * to check ContentHandler::supportsSections.
860 * @return bool True if this edit page supports sections, false otherwise.
862 protected function isSectionEditSupported() {
863 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
864 return $contentHandler->supportsSections();
868 * This function collects the form data and uses it to populate various member variables.
869 * @param WebRequest &$request
870 * @throws ErrorPageError
872 public function importFormData( &$request ) {
873 # Section edit can come from either the form or a link
874 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
876 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
877 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
880 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
882 if ( $request->wasPosted() ) {
883 # These fields need to be checked for encoding.
884 # Also remove trailing whitespace, but don't remove _initial_
885 # whitespace from the text boxes. This may be significant formatting.
886 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
887 if ( !$request->getCheck( 'wpTextbox2' ) ) {
888 // Skip this if wpTextbox2 has input, it indicates that we came
889 // from a conflict page with raw page text, not a custom form
890 // modified by subclasses
891 $textbox1 = $this->importContentFormData( $request );
892 if ( $textbox1 !== null ) {
893 $this->textbox1
= $textbox1;
897 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
899 $this->summary
= $request->getText( 'wpSummary' );
901 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
902 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
904 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
906 # Treat sectiontitle the same way as summary.
907 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
908 # currently doing double duty as both edit summary and section title. Right now this
909 # is just to allow API edits to work around this limitation, but this should be
910 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
911 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
912 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
914 $this->edittime
= $request->getVal( 'wpEdittime' );
915 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
916 $this->starttime
= $request->getVal( 'wpStarttime' );
918 $undidRev = $request->getInt( 'wpUndidRevision' );
920 $this->undidRev
= $undidRev;
923 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
925 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
926 // wpTextbox1 field is missing, possibly due to being "too big"
927 // according to some filter rules such as Suhosin's setting for
928 // suhosin.request.max_value_length (d'oh)
929 $this->incompleteForm
= true;
931 // If we receive the last parameter of the request, we can fairly
932 // claim the POST request has not been truncated.
934 // TODO: softened the check for cutover. Once we determine
935 // that it is safe, we should complete the transition by
936 // removing the "edittime" clause.
937 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
938 && is_null( $this->edittime
) );
940 if ( $this->incompleteForm
) {
941 # If the form is incomplete, force to preview.
942 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
943 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
944 $this->preview
= true;
946 $this->preview
= $request->getCheck( 'wpPreview' );
947 $this->diff
= $request->getCheck( 'wpDiff' );
949 // Remember whether a save was requested, so we can indicate
950 // if we forced preview due to session failure.
951 $this->mTriedSave
= !$this->preview
;
953 if ( $this->tokenOk( $request ) ) {
954 # Some browsers will not report any submit button
955 # if the user hits enter in the comment box.
956 # The unmarked state will be assumed to be a save,
957 # if the form seems otherwise complete.
958 wfDebug( __METHOD__
. ": Passed token check.\n" );
959 } elseif ( $this->diff
) {
960 # Failed token check, but only requested "Show Changes".
961 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
963 # Page might be a hack attempt posted from
964 # an external site. Preview instead of saving.
965 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
966 $this->preview
= true;
969 $this->save
= !$this->preview
&& !$this->diff
;
970 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
971 $this->edittime
= null;
974 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
975 $this->starttime
= null;
978 $this->recreate
= $request->getCheck( 'wpRecreate' );
980 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
981 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
983 $user = $this->context
->getUser();
984 # Don't force edit summaries when a user is editing their own user or talk page
985 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
986 && $this->mTitle
->getText() == $user->getName()
988 $this->allowBlankSummary
= true;
990 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
991 ||
!$user->getOption( 'forceeditsummary' );
994 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
996 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
997 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
999 $changeTags = $request->getVal( 'wpChangeTags' );
1000 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1001 $this->changeTags
= [];
1003 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1007 # Not a posted form? Start with nothing.
1008 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1009 $this->textbox1
= '';
1010 $this->summary
= '';
1011 $this->sectiontitle
= '';
1012 $this->edittime
= '';
1013 $this->editRevId
= null;
1014 $this->starttime
= wfTimestampNow();
1015 $this->edit
= false;
1016 $this->preview
= false;
1017 $this->save
= false;
1018 $this->diff
= false;
1019 $this->minoredit
= false;
1020 // Watch may be overridden by request parameters
1021 $this->watchthis
= $request->getBool( 'watchthis', false );
1022 $this->recreate
= false;
1024 // When creating a new section, we can preload a section title by passing it as the
1025 // preloadtitle parameter in the URL (T15100)
1026 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1027 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1028 // Once wpSummary isn't being use for setting section titles, we should delete this.
1029 $this->summary
= $request->getVal( 'preloadtitle' );
1030 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1031 $this->summary
= $request->getText( 'summary' );
1032 if ( $this->summary
!== '' ) {
1033 $this->hasPresetSummary
= true;
1037 if ( $request->getVal( 'minor' ) ) {
1038 $this->minoredit
= true;
1042 $this->oldid
= $request->getInt( 'oldid' );
1043 $this->parentRevId
= $request->getInt( 'parentRevId' );
1045 $this->bot
= $request->getBool( 'bot', true );
1046 $this->nosummary
= $request->getBool( 'nosummary' );
1048 // May be overridden by revision.
1049 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1050 // May be overridden by revision.
1051 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1054 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1055 } catch ( MWUnknownContentModelException
$e ) {
1056 throw new ErrorPageError(
1057 'editpage-invalidcontentmodel-title',
1058 'editpage-invalidcontentmodel-text',
1059 [ wfEscapeWikiText( $this->contentModel
) ]
1063 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1064 throw new ErrorPageError(
1065 'editpage-notsupportedcontentformat-title',
1066 'editpage-notsupportedcontentformat-text',
1068 wfEscapeWikiText( $this->contentFormat
),
1069 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1075 * @todo Check if the desired model is allowed in this namespace, and if
1076 * a transition from the page's current model to the new model is
1080 $this->editintro
= $request->getText( 'editintro',
1081 // Custom edit intro for new sections
1082 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1084 // Allow extensions to modify form data
1085 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1089 * Subpage overridable method for extracting the page content data from the
1090 * posted form to be placed in $this->textbox1, if using customized input
1091 * this method should be overridden and return the page text that will be used
1092 * for saving, preview parsing and so on...
1094 * @param WebRequest &$request
1095 * @return string|null
1097 protected function importContentFormData( &$request ) {
1098 return; // Don't do anything, EditPage already extracted wpTextbox1
1102 * Initialise form fields in the object
1103 * Called on the first invocation, e.g. when a user clicks an edit link
1104 * @return bool If the requested section is valid
1106 public function initialiseForm() {
1107 $this->edittime
= $this->page
->getTimestamp();
1108 $this->editRevId
= $this->page
->getLatest();
1110 $content = $this->getContentObject( false ); # TODO: track content object?!
1111 if ( $content === false ) {
1114 $this->textbox1
= $this->toEditText( $content );
1116 $user = $this->context
->getUser();
1117 // activate checkboxes if user wants them to be always active
1118 # Sort out the "watch" checkbox
1119 if ( $user->getOption( 'watchdefault' ) ) {
1121 $this->watchthis
= true;
1122 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1124 $this->watchthis
= true;
1125 } elseif ( $user->isWatched( $this->mTitle
) ) {
1127 $this->watchthis
= true;
1129 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1130 $this->minoredit
= true;
1132 if ( $this->textbox1
=== false ) {
1139 * @param Content|null $def_content The default value to return
1141 * @return Content|null Content on success, $def_content for invalid sections
1145 protected function getContentObject( $def_content = null ) {
1150 $user = $this->context
->getUser();
1151 $request = $this->context
->getRequest();
1152 // For message page not locally set, use the i18n message.
1153 // For other non-existent articles, use preload text if any.
1154 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1155 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1156 # If this is a system message, get the default text.
1157 $msg = $this->mTitle
->getDefaultMessageText();
1159 $content = $this->toEditContent( $msg );
1161 if ( $content === false ) {
1162 # If requested, preload some text.
1163 $preload = $request->getVal( 'preload',
1164 // Custom preload text for new sections
1165 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1166 $params = $request->getArray( 'preloadparams', [] );
1168 $content = $this->getPreloadedContent( $preload, $params );
1170 // For existing pages, get text based on "undo" or section parameters.
1172 if ( $this->section
!= '' ) {
1173 // Get section edit text (returns $def_text for invalid sections)
1174 $orig = $this->getOriginalContent( $user );
1175 $content = $orig ?
$orig->getSection( $this->section
) : null;
1178 $content = $def_content;
1181 $undoafter = $request->getInt( 'undoafter' );
1182 $undo = $request->getInt( 'undo' );
1184 if ( $undo > 0 && $undoafter > 0 ) {
1185 $undorev = Revision
::newFromId( $undo );
1186 $oldrev = Revision
::newFromId( $undoafter );
1188 # Sanity check, make sure it's the right page,
1189 # the revisions exist and they were not deleted.
1190 # Otherwise, $content will be left as-is.
1191 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1192 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1193 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1195 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1197 if ( $content === false ) {
1198 # Warn the user that something went wrong
1199 $undoMsg = 'failure';
1201 $oldContent = $this->page
->getContent( Revision
::RAW
);
1202 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1203 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1204 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1205 // The undo may change content
1206 // model if its reverting the top
1207 // edit. This can result in
1208 // mismatched content model/format.
1209 $this->contentModel
= $newContent->getModel();
1210 $this->contentFormat
= $oldrev->getContentFormat();
1213 if ( $newContent->equals( $oldContent ) ) {
1214 # Tell the user that the undo results in no change,
1215 # i.e. the revisions were already undone.
1216 $undoMsg = 'nochange';
1219 # Inform the user of our success and set an automatic edit summary
1220 $undoMsg = 'success';
1222 # If we just undid one rev, use an autosummary
1223 $firstrev = $oldrev->getNext();
1224 if ( $firstrev && $firstrev->getId() == $undo ) {
1225 $userText = $undorev->getUserText();
1226 if ( $userText === '' ) {
1227 $undoSummary = $this->context
->msg(
1228 'undo-summary-username-hidden',
1230 )->inContentLanguage()->text();
1232 $undoSummary = $this->context
->msg(
1236 )->inContentLanguage()->text();
1238 if ( $this->summary
=== '' ) {
1239 $this->summary
= $undoSummary;
1241 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1242 ->inContentLanguage()->text() . $this->summary
;
1244 $this->undidRev
= $undo;
1246 $this->formtype
= 'diff';
1250 // Failed basic sanity checks.
1251 // Older revisions may have been removed since the link
1252 // was created, or we may simply have got bogus input.
1256 $out = $this->context
->getOutput();
1257 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1258 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1259 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1260 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1263 if ( $content === false ) {
1264 $content = $this->getOriginalContent( $user );
1273 * Get the content of the wanted revision, without section extraction.
1275 * The result of this function can be used to compare user's input with
1276 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1277 * to the original text of the edit.
1279 * This differs from Article::getContent() that when a missing revision is
1280 * encountered the result will be null and not the
1281 * 'missing-revision' message.
1284 * @param User $user The user to get the revision for
1285 * @return Content|null
1287 private function getOriginalContent( User
$user ) {
1288 if ( $this->section
== 'new' ) {
1289 return $this->getCurrentContent();
1291 $revision = $this->mArticle
->getRevisionFetched();
1292 if ( $revision === null ) {
1293 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1294 return $handler->makeEmptyContent();
1296 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1301 * Get the edit's parent revision ID
1303 * The "parent" revision is the ancestor that should be recorded in this
1304 * page's revision history. It is either the revision ID of the in-memory
1305 * article content, or in the case of a 3-way merge in order to rebase
1306 * across a recoverable edit conflict, the ID of the newer revision to
1307 * which we have rebased this page.
1310 * @return int Revision ID
1312 public function getParentRevId() {
1313 if ( $this->parentRevId
) {
1314 return $this->parentRevId
;
1316 return $this->mArticle
->getRevIdFetched();
1321 * Get the current content of the page. This is basically similar to
1322 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1323 * content object is returned instead of null.
1328 protected function getCurrentContent() {
1329 $rev = $this->page
->getRevision();
1330 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1332 if ( $content === false ||
$content === null ) {
1333 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1334 return $handler->makeEmptyContent();
1335 } elseif ( !$this->undidRev
) {
1336 // Content models should always be the same since we error
1337 // out if they are different before this point (in ->edit()).
1338 // The exception being, during an undo, the current revision might
1339 // differ from the prior revision.
1340 $logger = LoggerFactory
::getInstance( 'editpage' );
1341 if ( $this->contentModel
!== $rev->getContentModel() ) {
1342 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1343 'prev' => $this->contentModel
,
1344 'new' => $rev->getContentModel(),
1345 'title' => $this->getTitle()->getPrefixedDBkey(),
1346 'method' => __METHOD__
1348 $this->contentModel
= $rev->getContentModel();
1351 // Given that the content models should match, the current selected
1352 // format should be supported.
1353 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1354 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1356 'prev' => $this->contentFormat
,
1357 'new' => $rev->getContentFormat(),
1358 'title' => $this->getTitle()->getPrefixedDBkey(),
1359 'method' => __METHOD__
1361 $this->contentFormat
= $rev->getContentFormat();
1368 * Use this method before edit() to preload some content into the edit box
1370 * @param Content $content
1374 public function setPreloadedContent( Content
$content ) {
1375 $this->mPreloadContent
= $content;
1379 * Get the contents to be preloaded into the box, either set by
1380 * an earlier setPreloadText() or by loading the given page.
1382 * @param string $preload Representing the title to preload from.
1383 * @param array $params Parameters to use (interface-message style) in the preloaded text
1389 protected function getPreloadedContent( $preload, $params = [] ) {
1390 if ( !empty( $this->mPreloadContent
) ) {
1391 return $this->mPreloadContent
;
1394 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1396 if ( $preload === '' ) {
1397 return $handler->makeEmptyContent();
1400 $user = $this->context
->getUser();
1401 $title = Title
::newFromText( $preload );
1402 # Check for existence to avoid getting MediaWiki:Noarticletext
1403 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1404 // TODO: somehow show a warning to the user!
1405 return $handler->makeEmptyContent();
1408 $page = WikiPage
::factory( $title );
1409 if ( $page->isRedirect() ) {
1410 $title = $page->getRedirectTarget();
1412 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1413 // TODO: somehow show a warning to the user!
1414 return $handler->makeEmptyContent();
1416 $page = WikiPage
::factory( $title );
1419 $parserOptions = ParserOptions
::newFromUser( $user );
1420 $content = $page->getContent( Revision
::RAW
);
1423 // TODO: somehow show a warning to the user!
1424 return $handler->makeEmptyContent();
1427 if ( $content->getModel() !== $handler->getModelID() ) {
1428 $converted = $content->convert( $handler->getModelID() );
1430 if ( !$converted ) {
1431 // TODO: somehow show a warning to the user!
1432 wfDebug( "Attempt to preload incompatible content: " .
1433 "can't convert " . $content->getModel() .
1434 " to " . $handler->getModelID() );
1436 return $handler->makeEmptyContent();
1439 $content = $converted;
1442 return $content->preloadTransform( $title, $parserOptions, $params );
1446 * Make sure the form isn't faking a user's credentials.
1448 * @param WebRequest &$request
1452 public function tokenOk( &$request ) {
1453 $token = $request->getVal( 'wpEditToken' );
1454 $user = $this->context
->getUser();
1455 $this->mTokenOk
= $user->matchEditToken( $token );
1456 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1457 return $this->mTokenOk
;
1461 * Sets post-edit cookie indicating the user just saved a particular revision.
1463 * This uses a temporary cookie for each revision ID so separate saves will never
1464 * interfere with each other.
1466 * Article::view deletes the cookie on server-side after the redirect and
1467 * converts the value to the global JavaScript variable wgPostEdit.
1469 * If the variable were set on the server, it would be cached, which is unwanted
1470 * since the post-edit state should only apply to the load right after the save.
1472 * @param int $statusValue The status value (to check for new article status)
1474 protected function setPostEditCookie( $statusValue ) {
1475 $revisionId = $this->page
->getLatest();
1476 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1479 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1481 } elseif ( $this->oldid
) {
1485 $response = $this->context
->getRequest()->response();
1486 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1490 * Attempt submission
1491 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1492 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1493 * @return Status The resulting status object.
1495 public function attemptSave( &$resultDetails = false ) {
1496 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1497 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1498 // This is needed since PageUpdater no longer checks these rights!
1500 // Allow bots to exempt some edits from bot flagging
1501 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1502 $status = $this->internalAttemptSave( $resultDetails, $bot );
1504 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1510 * Log when a page was successfully saved after the edit conflict view
1512 private function incrementResolvedConflicts() {
1513 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1517 $this->getEditConflictHelper()->incrementResolvedStats();
1521 * Handle status, such as after attempt save
1523 * @param Status $status
1524 * @param array|bool $resultDetails
1526 * @throws ErrorPageError
1527 * @return bool False, if output is done, true if rest of the form should be displayed
1529 private function handleStatus( Status
$status, $resultDetails ) {
1531 * @todo FIXME: once the interface for internalAttemptSave() is made
1532 * nicer, this should use the message in $status
1534 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1535 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1537 $this->incrementResolvedConflicts();
1539 $this->didSave
= true;
1540 if ( !$resultDetails['nullEdit'] ) {
1541 $this->setPostEditCookie( $status->value
);
1545 $out = $this->context
->getOutput();
1547 // "wpExtraQueryRedirect" is a hidden input to modify
1548 // after save URL and is not used by actual edit form
1549 $request = $this->context
->getRequest();
1550 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1552 switch ( $status->value
) {
1553 case self
::AS_HOOK_ERROR_EXPECTED
:
1554 case self
::AS_CONTENT_TOO_BIG
:
1555 case self
::AS_ARTICLE_WAS_DELETED
:
1556 case self
::AS_CONFLICT_DETECTED
:
1557 case self
::AS_SUMMARY_NEEDED
:
1558 case self
::AS_TEXTBOX_EMPTY
:
1559 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1561 case self
::AS_BLANK_ARTICLE
:
1562 case self
::AS_SELF_REDIRECT
:
1565 case self
::AS_HOOK_ERROR
:
1568 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1569 case self
::AS_PARSE_ERROR
:
1570 case self
::AS_UNICODE_NOT_SUPPORTED
:
1571 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1574 case self
::AS_SUCCESS_NEW_ARTICLE
:
1575 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1576 if ( $extraQueryRedirect ) {
1577 if ( $query === '' ) {
1578 $query = $extraQueryRedirect;
1580 $query = $query . '&' . $extraQueryRedirect;
1583 $anchor = $resultDetails['sectionanchor'] ??
'';
1584 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1587 case self
::AS_SUCCESS_UPDATE
:
1589 $sectionanchor = $resultDetails['sectionanchor'];
1591 // Give extensions a chance to modify URL query on update
1593 'ArticleUpdateBeforeRedirect',
1594 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1597 if ( $resultDetails['redirect'] ) {
1598 if ( $extraQuery == '' ) {
1599 $extraQuery = 'redirect=no';
1601 $extraQuery = 'redirect=no&' . $extraQuery;
1604 if ( $extraQueryRedirect ) {
1605 if ( $extraQuery === '' ) {
1606 $extraQuery = $extraQueryRedirect;
1608 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1612 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1615 case self
::AS_SPAM_ERROR
:
1616 $this->spamPageWithContent( $resultDetails['spam'] );
1619 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1620 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1622 case self
::AS_IMAGE_REDIRECT_ANON
:
1623 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1624 throw new PermissionsError( 'upload' );
1626 case self
::AS_READ_ONLY_PAGE_ANON
:
1627 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1628 throw new PermissionsError( 'edit' );
1630 case self
::AS_READ_ONLY_PAGE
:
1631 throw new ReadOnlyError
;
1633 case self
::AS_RATE_LIMITED
:
1634 throw new ThrottledError();
1636 case self
::AS_NO_CREATE_PERMISSION
:
1637 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1638 throw new PermissionsError( $permission );
1640 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1641 throw new PermissionsError( 'editcontentmodel' );
1644 // We don't recognize $status->value. The only way that can happen
1645 // is if an extension hook aborted from inside ArticleSave.
1646 // Render the status object into $this->hookError
1647 // FIXME this sucks, we should just use the Status object throughout
1648 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1655 * Run hooks that can filter edits just before they get saved.
1657 * @param Content $content The Content to filter.
1658 * @param Status $status For reporting the outcome to the caller
1659 * @param User $user The user performing the edit
1663 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1664 // Run old style post-section-merge edit filter
1665 if ( $this->hookError
!= '' ) {
1666 # ...or the hook could be expecting us to produce an error
1667 $status->fatal( 'hookaborted' );
1668 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1672 // Run new style post-section-merge edit filter
1673 if ( !Hooks
::run( 'EditFilterMergedContent',
1674 [ $this->context
, $content, $status, $this->summary
,
1675 $user, $this->minoredit
] )
1677 # Error messages etc. could be handled within the hook...
1678 if ( $status->isGood() ) {
1679 $status->fatal( 'hookaborted' );
1680 // Not setting $this->hookError here is a hack to allow the hook
1681 // to cause a return to the edit page without $this->hookError
1682 // being set. This is used by ConfirmEdit to display a captcha
1683 // without any error message cruft.
1685 $this->hookError
= $this->formatStatusErrors( $status );
1687 // Use the existing $status->value if the hook set it
1688 if ( !$status->value
) {
1689 $status->value
= self
::AS_HOOK_ERROR
;
1692 } elseif ( !$status->isOK() ) {
1693 # ...or the hook could be expecting us to produce an error
1694 // FIXME this sucks, we should just use the Status object throughout
1695 $this->hookError
= $this->formatStatusErrors( $status );
1696 $status->fatal( 'hookaborted' );
1697 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1705 * Wrap status errors in an errorbox for increased visibility
1707 * @param Status $status
1708 * @return string Wikitext
1710 private function formatStatusErrors( Status
$status ) {
1711 $errmsg = $status->getWikiText(
1714 $this->context
->getLanguage()
1717 <div class="errorbox">
1725 * Return the summary to be used for a new section.
1727 * @param string $sectionanchor Set to the section anchor text
1730 private function newSectionSummary( &$sectionanchor = null ) {
1733 if ( $this->sectiontitle
!== '' ) {
1734 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1735 // If no edit summary was specified, create one automatically from the section
1736 // title and have it link to the new section. Otherwise, respect the summary as
1738 if ( $this->summary
=== '' ) {
1739 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1740 return $this->context
->msg( 'newsectionsummary' )
1741 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1743 } elseif ( $this->summary
!== '' ) {
1744 $sectionanchor = $this->guessSectionName( $this->summary
);
1745 # This is a new section, so create a link to the new section
1746 # in the revision summary.
1747 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1748 return $this->context
->msg( 'newsectionsummary' )
1749 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1751 return $this->summary
;
1755 * Attempt submission (no UI)
1757 * @param array &$result Array to add statuses to, currently with the
1759 * - spam (string): Spam string from content if any spam is detected by
1761 * - sectionanchor (string): Section anchor for a section save.
1762 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1764 * - redirect (bool): Set if doEditContent is OK. True if resulting
1765 * revision is a redirect.
1766 * @param bool $bot True if edit is being made under the bot right.
1768 * @return Status Status object, possibly with a message, but always with
1769 * one of the AS_* constants in $status->value,
1771 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1772 * various error display idiosyncrasies. There are also lots of cases
1773 * where error metadata is set in the object and retrieved later instead
1774 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1775 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1778 public function internalAttemptSave( &$result, $bot = false ) {
1779 $status = Status
::newGood();
1780 $user = $this->context
->getUser();
1782 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1783 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1784 $status->fatal( 'hookaborted' );
1785 $status->value
= self
::AS_HOOK_ERROR
;
1789 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1790 $status->fatal( 'unicode-support-fail' );
1791 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1795 $request = $this->context
->getRequest();
1796 $spam = $request->getText( 'wpAntispam' );
1797 if ( $spam !== '' ) {
1802 $this->mTitle
->getPrefixedText() .
1803 '" submitted bogus field "' .
1807 $status->fatal( 'spamprotectionmatch', false );
1808 $status->value
= self
::AS_SPAM_ERROR
;
1813 # Construct Content object
1814 $textbox_content = $this->toEditContent( $this->textbox1
);
1815 } catch ( MWContentSerializationException
$ex ) {
1817 'content-failed-to-parse',
1818 $this->contentModel
,
1819 $this->contentFormat
,
1822 $status->value
= self
::AS_PARSE_ERROR
;
1826 # Check image redirect
1827 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1828 $textbox_content->isRedirect() &&
1829 !$user->isAllowed( 'upload' )
1831 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1832 $status->setResult( false, $code );
1838 $match = self
::matchSummarySpamRegex( $this->summary
);
1839 if ( $match === false && $this->section
== 'new' ) {
1840 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1841 # regular summaries, it is added to the actual wikitext.
1842 if ( $this->sectiontitle
!== '' ) {
1843 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1844 $match = self
::matchSpamRegex( $this->sectiontitle
);
1846 # This branch is taken when the "Add Topic" user interface is used, or the API
1847 # is used with the 'summary' parameter.
1848 $match = self
::matchSpamRegex( $this->summary
);
1851 if ( $match === false ) {
1852 $match = self
::matchSpamRegex( $this->textbox1
);
1854 if ( $match !== false ) {
1855 $result['spam'] = $match;
1856 $ip = $request->getIP();
1857 $pdbk = $this->mTitle
->getPrefixedDBkey();
1858 $match = str_replace( "\n", '', $match );
1859 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1860 $status->fatal( 'spamprotectionmatch', $match );
1861 $status->value
= self
::AS_SPAM_ERROR
;
1866 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1868 # Error messages etc. could be handled within the hook...
1869 $status->fatal( 'hookaborted' );
1870 $status->value
= self
::AS_HOOK_ERROR
;
1872 } elseif ( $this->hookError
!= '' ) {
1873 # ...or the hook could be expecting us to produce an error
1874 $status->fatal( 'hookaborted' );
1875 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1879 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1880 // Auto-block user's IP if the account was "hard" blocked
1881 if ( !wfReadOnly() ) {
1882 $user->spreadAnyEditBlock();
1884 # Check block state against master, thus 'false'.
1885 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1889 $this->contentLength
= strlen( $this->textbox1
);
1890 $config = $this->context
->getConfig();
1891 $maxArticleSize = $config->get( 'MaxArticleSize' );
1892 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1893 // Error will be displayed by showEditForm()
1894 $this->tooBig
= true;
1895 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1899 if ( !$user->isAllowed( 'edit' ) ) {
1900 if ( $user->isAnon() ) {
1901 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1904 $status->fatal( 'readonlytext' );
1905 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1910 $changingContentModel = false;
1911 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1912 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1913 $status->fatal( 'editpage-cannot-use-custom-model' );
1914 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1916 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1917 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1920 // Make sure the user can edit the page under the new content model too
1921 $titleWithNewContentModel = clone $this->mTitle
;
1922 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1923 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1924 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1926 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1930 $changingContentModel = true;
1931 $oldContentModel = $this->mTitle
->getContentModel();
1934 if ( $this->changeTags
) {
1935 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1936 $this->changeTags
, $user );
1937 if ( !$changeTagsStatus->isOK() ) {
1938 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1939 return $changeTagsStatus;
1943 if ( wfReadOnly() ) {
1944 $status->fatal( 'readonlytext' );
1945 $status->value
= self
::AS_READ_ONLY_PAGE
;
1948 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1949 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1951 $status->fatal( 'actionthrottledtext' );
1952 $status->value
= self
::AS_RATE_LIMITED
;
1956 # If the article has been deleted while editing, don't save it without
1958 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1959 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1963 # Load the page data from the master. If anything changes in the meantime,
1964 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1965 $this->page
->loadPageData( 'fromdbmaster' );
1966 $new = !$this->page
->exists();
1969 // Late check for create permission, just in case *PARANOIA*
1970 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1971 $status->fatal( 'nocreatetext' );
1972 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1973 wfDebug( __METHOD__
. ": no create permission\n" );
1977 // Don't save a new page if it's blank or if it's a MediaWiki:
1978 // message with content equivalent to default (allow empty pages
1979 // in this case to disable messages, see T52124)
1980 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1981 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1982 $defaultText = $defaultMessageText;
1987 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1988 $this->blankArticle
= true;
1989 $status->fatal( 'blankarticle' );
1990 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1994 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
1998 $content = $textbox_content;
2000 $result['sectionanchor'] = '';
2001 if ( $this->section
== 'new' ) {
2002 if ( $this->sectiontitle
!== '' ) {
2003 // Insert the section title above the content.
2004 $content = $content->addSectionHeader( $this->sectiontitle
);
2005 } elseif ( $this->summary
!== '' ) {
2006 // Insert the section title above the content.
2007 $content = $content->addSectionHeader( $this->summary
);
2009 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2012 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2016 # Article exists. Check for edit conflict.
2018 $this->page
->clear(); # Force reload of dates, etc.
2019 $timestamp = $this->page
->getTimestamp();
2020 $latest = $this->page
->getLatest();
2022 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2024 // Check editRevId if set, which handles same-second timestamp collisions
2025 if ( $timestamp != $this->edittime
2026 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2028 $this->isConflict
= true;
2029 if ( $this->section
== 'new' ) {
2030 if ( $this->page
->getUserText() == $user->getName() &&
2031 $this->page
->getComment() == $this->newSectionSummary()
2033 // Probably a duplicate submission of a new comment.
2034 // This can happen when CDN resends a request after
2035 // a timeout but the first one actually went through.
2037 . ": duplicate new section submission; trigger edit conflict!\n" );
2039 // New comment; suppress conflict.
2040 $this->isConflict
= false;
2041 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2043 } elseif ( $this->section
== ''
2044 && Revision
::userWasLastToEdit(
2045 DB_MASTER
, $this->mTitle
->getArticleID(),
2046 $user->getId(), $this->edittime
2049 # Suppress edit conflict with self, except for section edits where merging is required.
2050 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2051 $this->isConflict
= false;
2055 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2056 if ( $this->sectiontitle
!== '' ) {
2057 $sectionTitle = $this->sectiontitle
;
2059 $sectionTitle = $this->summary
;
2064 if ( $this->isConflict
) {
2066 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2067 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2068 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2069 // ...or disable section editing for non-current revisions (not exposed anyway).
2070 if ( $this->editRevId
!== null ) {
2071 $content = $this->page
->replaceSectionAtRev(
2078 $content = $this->page
->replaceSectionContent(
2086 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2087 $content = $this->page
->replaceSectionContent(
2094 if ( is_null( $content ) ) {
2095 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2096 $this->isConflict
= true;
2097 $content = $textbox_content; // do not try to merge here!
2098 } elseif ( $this->isConflict
) {
2100 if ( $this->mergeChangesIntoContent( $content ) ) {
2101 // Successful merge! Maybe we should tell the user the good news?
2102 $this->isConflict
= false;
2103 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2105 $this->section
= '';
2106 $this->textbox1
= ContentHandler
::getContentText( $content );
2107 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2111 if ( $this->isConflict
) {
2112 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2116 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2120 if ( $this->section
== 'new' ) {
2121 // Handle the user preference to force summaries here
2122 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2123 $this->missingSummary
= true;
2124 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2125 $status->value
= self
::AS_SUMMARY_NEEDED
;
2129 // Do not allow the user to post an empty comment
2130 if ( $this->textbox1
== '' ) {
2131 $this->missingComment
= true;
2132 $status->fatal( 'missingcommenttext' );
2133 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2136 } elseif ( !$this->allowBlankSummary
2137 && !$content->equals( $this->getOriginalContent( $user ) )
2138 && !$content->isRedirect()
2139 && md5( $this->summary
) == $this->autoSumm
2141 $this->missingSummary
= true;
2142 $status->fatal( 'missingsummary' );
2143 $status->value
= self
::AS_SUMMARY_NEEDED
;
2148 $sectionanchor = '';
2149 if ( $this->section
== 'new' ) {
2150 $this->summary
= $this->newSectionSummary( $sectionanchor );
2151 } elseif ( $this->section
!= '' ) {
2152 # Try to get a section anchor from the section source, redirect
2153 # to edited section if header found.
2154 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2155 # for duplicate heading checking and maybe parsing.
2156 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2157 # We can't deal with anchors, includes, html etc in the header for now,
2158 # headline would need to be parsed to improve this.
2159 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2160 $sectionanchor = $this->guessSectionName( $matches[2] );
2163 $result['sectionanchor'] = $sectionanchor;
2165 // Save errors may fall down to the edit form, but we've now
2166 // merged the section into full text. Clear the section field
2167 // so that later submission of conflict forms won't try to
2168 // replace that into a duplicated mess.
2169 $this->textbox1
= $this->toEditText( $content );
2170 $this->section
= '';
2172 $status->value
= self
::AS_SUCCESS_UPDATE
;
2175 if ( !$this->allowSelfRedirect
2176 && $content->isRedirect()
2177 && $content->getRedirectTarget()->equals( $this->getTitle() )
2179 // If the page already redirects to itself, don't warn.
2180 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2181 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2182 $this->selfRedirect
= true;
2183 $status->fatal( 'selfredirect' );
2184 $status->value
= self
::AS_SELF_REDIRECT
;
2189 // Check for length errors again now that the section is merged in
2190 $this->contentLength
= strlen( $this->toEditText( $content ) );
2191 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2192 $this->tooBig
= true;
2193 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2197 $flags = EDIT_AUTOSUMMARY |
2198 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2199 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2200 ( $bot ? EDIT_FORCE_BOT
: 0 );
2202 $doEditStatus = $this->page
->doEditContent(
2208 $content->getDefaultFormat(),
2213 if ( !$doEditStatus->isOK() ) {
2214 // Failure from doEdit()
2215 // Show the edit conflict page for certain recognized errors from doEdit(),
2216 // but don't show it for errors from extension hooks
2217 $errors = $doEditStatus->getErrorsArray();
2218 if ( in_array( $errors[0][0],
2219 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2221 $this->isConflict
= true;
2222 // Destroys data doEdit() put in $status->value but who cares
2223 $doEditStatus->value
= self
::AS_END
;
2225 return $doEditStatus;
2228 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2229 if ( $result['nullEdit'] ) {
2230 // We don't know if it was a null edit until now, so increment here
2231 $user->pingLimiter( 'linkpurge' );
2233 $result['redirect'] = $content->isRedirect();
2235 $this->updateWatchlist();
2237 // If the content model changed, add a log entry
2238 if ( $changingContentModel ) {
2239 $this->addContentModelChangeLogEntry(
2241 $new ?
false : $oldContentModel,
2242 $this->contentModel
,
2252 * @param string|false $oldModel false if the page is being newly created
2253 * @param string $newModel
2254 * @param string $reason
2256 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2257 $new = $oldModel === false;
2258 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2259 $log->setPerformer( $user );
2260 $log->setTarget( $this->mTitle
);
2261 $log->setComment( $reason );
2262 $log->setParameters( [
2263 '4::oldmodel' => $oldModel,
2264 '5::newmodel' => $newModel
2266 $logid = $log->insert();
2267 $log->publish( $logid );
2271 * Register the change of watch status
2273 protected function updateWatchlist() {
2274 $user = $this->context
->getUser();
2275 if ( !$user->isLoggedIn() ) {
2279 $title = $this->mTitle
;
2280 $watch = $this->watchthis
;
2281 // Do this in its own transaction to reduce contention...
2282 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2283 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2284 return; // nothing to change
2286 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2291 * Attempts to do 3-way merge of edit content with a base revision
2292 * and current content, in case of edit conflict, in whichever way appropriate
2293 * for the content type.
2297 * @param Content $editContent
2301 private function mergeChangesIntoContent( &$editContent ) {
2302 $db = wfGetDB( DB_MASTER
);
2304 // This is the revision the editor started from
2305 $baseRevision = $this->getBaseRevision();
2306 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2308 if ( is_null( $baseContent ) ) {
2312 // The current state, we want to merge updates into it
2313 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2314 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2316 if ( is_null( $currentContent ) ) {
2320 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2322 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2325 $editContent = $result;
2326 // Update parentRevId to what we just merged.
2327 $this->parentRevId
= $currentRevision->getId();
2335 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2336 * one might think of X as the "base revision", which is NOT what this returns.
2337 * @return Revision|null Current version when the edit was started
2339 public function getBaseRevision() {
2340 if ( !$this->mBaseRevision
) {
2341 $db = wfGetDB( DB_MASTER
);
2342 $this->mBaseRevision
= $this->editRevId
2343 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2344 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2346 return $this->mBaseRevision
;
2350 * Check given input text against $wgSpamRegex, and return the text of the first match.
2352 * @param string $text
2354 * @return string|bool Matching string or false
2356 public static function matchSpamRegex( $text ) {
2357 global $wgSpamRegex;
2358 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2359 $regexes = (array)$wgSpamRegex;
2360 return self
::matchSpamRegexInternal( $text, $regexes );
2364 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2366 * @param string $text
2368 * @return string|bool Matching string or false
2370 public static function matchSummarySpamRegex( $text ) {
2371 global $wgSummarySpamRegex;
2372 $regexes = (array)$wgSummarySpamRegex;
2373 return self
::matchSpamRegexInternal( $text, $regexes );
2377 * @param string $text
2378 * @param array $regexes
2379 * @return bool|string
2381 protected static function matchSpamRegexInternal( $text, $regexes ) {
2382 foreach ( $regexes as $regex ) {
2384 if ( preg_match( $regex, $text, $matches ) ) {
2391 public function setHeaders() {
2392 $out = $this->context
->getOutput();
2394 $out->addModules( 'mediawiki.action.edit' );
2395 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2396 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2398 $user = $this->context
->getUser();
2399 if ( $user->getOption( 'showtoolbar' ) ) {
2400 // The addition of default buttons is handled by getEditToolbar() which
2401 // has its own dependency on this module. The call here ensures the module
2402 // is loaded in time (it has position "top") for other modules to register
2403 // buttons (e.g. extensions, gadgets, user scripts).
2404 $out->addModules( 'mediawiki.toolbar' );
2407 if ( $user->getOption( 'uselivepreview' ) ) {
2408 $out->addModules( 'mediawiki.action.edit.preview' );
2411 if ( $user->getOption( 'useeditwarning' ) ) {
2412 $out->addModules( 'mediawiki.action.edit.editWarning' );
2415 # Enabled article-related sidebar, toplinks, etc.
2416 $out->setArticleRelated( true );
2418 $contextTitle = $this->getContextTitle();
2419 if ( $this->isConflict
) {
2420 $msg = 'editconflict';
2421 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2422 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2424 $msg = $contextTitle->exists()
2425 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2426 && $contextTitle->getDefaultMessageText() !== false
2432 # Use the title defined by DISPLAYTITLE magic word when present
2433 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2434 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2435 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2436 if ( $displayTitle === false ) {
2437 $displayTitle = $contextTitle->getPrefixedText();
2439 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2441 $config = $this->context
->getConfig();
2443 # Transmit the name of the message to JavaScript for live preview
2444 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2445 $out->addJsConfigVars( [
2446 'wgEditMessage' => $msg,
2447 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2450 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2452 $out->addJsConfigVars(
2453 'wgEditSubmitButtonLabelPublish',
2454 $config->get( 'EditSubmitButtonLabelPublish' )
2459 * Show all applicable editing introductions
2461 protected function showIntro() {
2462 if ( $this->suppressIntro
) {
2466 $out = $this->context
->getOutput();
2467 $namespace = $this->mTitle
->getNamespace();
2469 if ( $namespace == NS_MEDIAWIKI
) {
2470 # Show a warning if editing an interface message
2471 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2472 # If this is a default message (but not css, json, or js),
2473 # show a hint that it is translatable on translatewiki.net
2475 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2476 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2477 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2479 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2480 if ( $defaultMessageText !== false ) {
2481 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2482 'translateinterface' );
2485 } elseif ( $namespace == NS_FILE
) {
2486 # Show a hint to shared repo
2487 $file = wfFindFile( $this->mTitle
);
2488 if ( $file && !$file->isLocal() ) {
2489 $descUrl = $file->getDescriptionUrl();
2490 # there must be a description url to show a hint to shared repo
2492 if ( !$this->mTitle
->exists() ) {
2493 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2494 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2497 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2498 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2505 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2506 # Show log extract when the user is currently blocked
2507 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2508 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2509 $user = User
::newFromName( $username, false /* allow IP users */ );
2510 $ip = User
::isIP( $username );
2511 $block = Block
::newFromTarget( $user, $user );
2512 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2513 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2514 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2515 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2516 # Show log extract if the user is currently blocked
2517 LogEventsList
::showLogExtract(
2520 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2524 'showIfEmpty' => false,
2526 'blocked-notice-logextract',
2527 $user->getName() # Support GENDER in notice
2533 # Try to add a custom edit intro, or use the standard one if this is not possible.
2534 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2535 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2536 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2538 if ( $this->context
->getUser()->isLoggedIn() ) {
2540 // Suppress the external link icon, consider the help url an internal one
2541 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2549 // Suppress the external link icon, consider the help url an internal one
2550 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2552 'newarticletextanon',
2558 # Give a notice if the user is editing a deleted/moved page...
2559 if ( !$this->mTitle
->exists() ) {
2560 $dbr = wfGetDB( DB_REPLICA
);
2562 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2566 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2567 'showIfEmpty' => false,
2568 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2575 * Attempt to show a custom editing introduction, if supplied
2579 protected function showCustomIntro() {
2580 if ( $this->editintro
) {
2581 $title = Title
::newFromText( $this->editintro
);
2582 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2583 // Added using template syntax, to take <noinclude>'s into account.
2584 $this->context
->getOutput()->addWikiTextTitleTidy(
2585 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2595 * Gets an editable textual representation of $content.
2596 * The textual representation can be turned by into a Content object by the
2597 * toEditContent() method.
2599 * If $content is null or false or a string, $content is returned unchanged.
2601 * If the given Content object is not of a type that can be edited using
2602 * the text base EditPage, an exception will be raised. Set
2603 * $this->allowNonTextContent to true to allow editing of non-textual
2606 * @param Content|null|bool|string $content
2607 * @return string The editable text form of the content.
2609 * @throws MWException If $content is not an instance of TextContent and
2610 * $this->allowNonTextContent is not true.
2612 protected function toEditText( $content ) {
2613 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2617 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2618 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2621 return $content->serialize( $this->contentFormat
);
2625 * Turns the given text into a Content object by unserializing it.
2627 * If the resulting Content object is not of a type that can be edited using
2628 * the text base EditPage, an exception will be raised. Set
2629 * $this->allowNonTextContent to true to allow editing of non-textual
2632 * @param string|null|bool $text Text to unserialize
2633 * @return Content|bool|null The content object created from $text. If $text was false
2634 * or null, false resp. null will be returned instead.
2636 * @throws MWException If unserializing the text results in a Content
2637 * object that is not an instance of TextContent and
2638 * $this->allowNonTextContent is not true.
2640 protected function toEditContent( $text ) {
2641 if ( $text === false ||
$text === null ) {
2645 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2646 $this->contentModel
, $this->contentFormat
);
2648 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2649 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2656 * Send the edit form and related headers to OutputPage
2657 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2658 * during form output near the top, for captchas and the like.
2660 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2661 * use the EditPage::showEditForm:fields hook instead.
2663 public function showEditForm( $formCallback = null ) {
2664 # need to parse the preview early so that we know which templates are used,
2665 # otherwise users with "show preview after edit box" will get a blank list
2666 # we parse this near the beginning so that setHeaders can do the title
2667 # setting work instead of leaving it in getPreviewText
2668 $previewOutput = '';
2669 if ( $this->formtype
== 'preview' ) {
2670 $previewOutput = $this->getPreviewText();
2673 $out = $this->context
->getOutput();
2675 // Avoid PHP 7.1 warning of passing $this by reference
2677 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2679 $this->setHeaders();
2681 $this->addTalkPageText();
2682 $this->addEditNotices();
2684 if ( !$this->isConflict
&&
2685 $this->section
!= '' &&
2686 !$this->isSectionEditSupported() ) {
2687 // We use $this->section to much before this and getVal('wgSection') directly in other places
2688 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2689 // Someone is welcome to try refactoring though
2690 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2694 $this->showHeader();
2696 $out->addHTML( $this->editFormPageTop
);
2698 $user = $this->context
->getUser();
2699 if ( $user->getOption( 'previewontop' ) ) {
2700 $this->displayPreviewArea( $previewOutput, true );
2703 $out->addHTML( $this->editFormTextTop
);
2705 $showToolbar = true;
2706 if ( $this->wasDeletedSinceLastEdit() ) {
2707 if ( $this->formtype
== 'save' ) {
2708 // Hide the toolbar and edit area, user can click preview to get it back
2709 // Add an confirmation checkbox and explanation.
2710 $showToolbar = false;
2712 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2713 'deletedwhileediting' );
2717 // @todo add EditForm plugin interface and use it here!
2718 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2719 $out->addHTML( Html
::openElement(
2722 'class' => 'mw-editform',
2723 'id' => self
::EDITFORM_ID
,
2724 'name' => self
::EDITFORM_ID
,
2726 'action' => $this->getActionURL( $this->getContextTitle() ),
2727 'enctype' => 'multipart/form-data'
2731 if ( is_callable( $formCallback ) ) {
2732 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2733 call_user_func_array( $formCallback, [ &$out ] );
2736 // Add a check for Unicode support
2737 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2739 // Add an empty field to trip up spambots
2741 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2744 [ 'for' => 'wpAntispam' ],
2745 $this->context
->msg( 'simpleantispam-label' )->parse()
2751 'name' => 'wpAntispam',
2752 'id' => 'wpAntispam',
2756 . Xml
::closeElement( 'div' )
2759 // Avoid PHP 7.1 warning of passing $this by reference
2761 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2763 // Put these up at the top to ensure they aren't lost on early form submission
2764 $this->showFormBeforeText();
2766 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2767 $username = $this->lastDelete
->user_name
;
2768 $comment = CommentStore
::getStore()
2769 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2771 // It is better to not parse the comment at all than to have templates expanded in the middle
2772 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2773 $key = $comment === ''
2774 ?
'confirmrecreate-noreason'
2775 : 'confirmrecreate';
2777 '<div class="mw-confirm-recreate">' .
2778 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2779 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2780 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2786 # When the summary is hidden, also hide them on preview/show changes
2787 if ( $this->nosummary
) {
2788 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2791 # If a blank edit summary was previously provided, and the appropriate
2792 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2793 # user being bounced back more than once in the event that a summary
2796 # For a bit more sophisticated detection of blank summaries, hash the
2797 # automatic one and pass that in the hidden field wpAutoSummary.
2798 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2799 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2802 if ( $this->undidRev
) {
2803 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2806 if ( $this->selfRedirect
) {
2807 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2810 if ( $this->hasPresetSummary
) {
2811 // If a summary has been preset using &summary= we don't want to prompt for
2812 // a different summary. Only prompt for a summary if the summary is blanked.
2814 $this->autoSumm
= md5( '' );
2817 $autosumm = $this->autoSumm ?
: md5( $this->summary
);
2818 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2820 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2821 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2823 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2824 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2828 if ( $this->section
== 'new' ) {
2829 $this->showSummaryInput( true, $this->summary
);
2830 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2833 $out->addHTML( $this->editFormTextBeforeContent
);
2834 if ( $this->isConflict
) {
2835 // In an edit conflict, we turn textbox2 into the user's text,
2836 // and textbox1 into the stored version
2837 $this->textbox2
= $this->textbox1
;
2839 $content = $this->getCurrentContent();
2840 $this->textbox1
= $this->toEditText( $content );
2842 $editConflictHelper = $this->getEditConflictHelper();
2843 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2844 $editConflictHelper->setContentModel( $this->contentModel
);
2845 $editConflictHelper->setContentFormat( $this->contentFormat
);
2846 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2849 if ( !$this->mTitle
->isUserConfigPage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2850 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2853 if ( $this->blankArticle
) {
2854 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2857 if ( $this->isConflict
) {
2858 // In an edit conflict bypass the overridable content form method
2859 // and fallback to the raw wpTextbox1 since editconflicts can't be
2860 // resolved between page source edits and custom ui edits using the
2862 $conflictTextBoxAttribs = [];
2863 if ( $this->wasDeletedSinceLastEdit() ) {
2864 $conflictTextBoxAttribs['style'] = 'display:none;';
2865 } elseif ( $this->isOldRev
) {
2866 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2869 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2870 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2872 $this->showContentForm();
2875 $out->addHTML( $this->editFormTextAfterContent
);
2877 $this->showStandardInputs();
2879 $this->showFormAfterText();
2881 $this->showTosSummary();
2883 $this->showEditTools();
2885 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2887 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2889 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2890 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2892 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2893 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2895 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2897 if ( $this->isConflict
) {
2899 $this->showConflict();
2900 } catch ( MWContentSerializationException
$ex ) {
2901 // this can't really happen, but be nice if it does.
2902 $msg = $this->context
->msg(
2903 'content-failed-to-parse',
2904 $this->contentModel
,
2905 $this->contentFormat
,
2908 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2912 // Set a hidden field so JS knows what edit form mode we are in
2913 if ( $this->isConflict
) {
2915 } elseif ( $this->preview
) {
2917 } elseif ( $this->diff
) {
2922 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2924 // Marker for detecting truncated form data. This must be the last
2925 // parameter sent in order to be of use, so do not move me.
2926 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2927 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2929 if ( !$user->getOption( 'previewontop' ) ) {
2930 $this->displayPreviewArea( $previewOutput, false );
2935 * Wrapper around TemplatesOnThisPageFormatter to make
2936 * a "templates on this page" list.
2938 * @param Title[] $templates
2939 * @return string HTML
2941 public function makeTemplatesOnThisPageList( array $templates ) {
2942 $templateListFormatter = new TemplatesOnThisPageFormatter(
2943 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2946 // preview if preview, else section if section, else false
2948 if ( $this->preview
) {
2950 } elseif ( $this->section
!= '' ) {
2954 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2955 $templateListFormatter->format( $templates, $type )
2960 * Extract the section title from current section text, if any.
2962 * @param string $text
2963 * @return string|bool String or false
2965 public static function extractSectionTitle( $text ) {
2966 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2967 if ( !empty( $matches[2] ) ) {
2969 return $wgParser->stripSectionName( trim( $matches[2] ) );
2975 protected function showHeader() {
2976 $out = $this->context
->getOutput();
2977 $user = $this->context
->getUser();
2978 if ( $this->isConflict
) {
2979 $this->addExplainConflictHeader( $out );
2980 $this->editRevId
= $this->page
->getLatest();
2982 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2983 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2984 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2985 if ( $sectionTitle !== false ) {
2986 $this->summary
= "/* $sectionTitle */ ";
2991 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
2993 if ( $this->missingComment
) {
2994 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2997 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2999 "<div id='mw-missingsummary'>\n$1\n</div>",
3000 [ 'missingsummary', $buttonLabel ]
3004 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3006 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3007 [ 'missingcommentheader', $buttonLabel ]
3011 if ( $this->blankArticle
) {
3013 "<div id='mw-blankarticle'>\n$1\n</div>",
3014 [ 'blankarticle', $buttonLabel ]
3018 if ( $this->selfRedirect
) {
3020 "<div id='mw-selfredirect'>\n$1\n</div>",
3021 [ 'selfredirect', $buttonLabel ]
3025 if ( $this->hookError
!== '' ) {
3026 $out->addWikiText( $this->hookError
);
3029 if ( $this->section
!= 'new' ) {
3030 $revision = $this->mArticle
->getRevisionFetched();
3032 // Let sysop know that this will make private content public if saved
3034 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3036 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3037 'rev-deleted-text-permission'
3039 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3041 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3042 'rev-deleted-text-view'
3046 if ( !$revision->isCurrent() ) {
3047 $this->mArticle
->setOldSubtitle( $revision->getId() );
3048 $out->addWikiMsg( 'editingold' );
3049 $this->isOldRev
= true;
3051 } elseif ( $this->mTitle
->exists() ) {
3052 // Something went wrong
3054 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3055 [ 'missing-revision', $this->oldid
] );
3060 if ( wfReadOnly() ) {
3062 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3063 [ 'readonlywarning', wfReadOnlyReason() ]
3065 } elseif ( $user->isAnon() ) {
3066 if ( $this->formtype
!= 'preview' ) {
3068 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3069 [ 'anoneditwarning',
3071 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3072 'returnto' => $this->getTitle()->getPrefixedDBkey()
3075 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3076 'returnto' => $this->getTitle()->getPrefixedDBkey()
3081 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3082 'anonpreviewwarning'
3086 if ( $this->mTitle
->isUserConfigPage() ) {
3087 # Check the skin exists
3088 if ( $this->isWrongCaseUserConfigPage() ) {
3090 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3091 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3094 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3095 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3096 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3097 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3099 $warning = $isUserCssConfig
3101 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3103 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3105 if ( $this->formtype
!== 'preview' ) {
3106 $config = $this->context
->getConfig();
3107 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3109 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3110 [ 'usercssyoucanpreview' ]
3112 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3114 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3115 [ 'userjsonyoucanpreview' ]
3117 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3119 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3120 [ 'userjsyoucanpreview' ]
3128 $this->addPageProtectionWarningHeaders();
3130 $this->addLongPageWarningHeader();
3132 # Add header copyright warning
3133 $this->showHeaderCopyrightWarning();
3137 * Helper function for summary input functions, which returns the neccessary
3138 * attributes for the input.
3140 * @param array|null $inputAttrs Array of attrs to use on the input
3143 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3144 $conf = $this->context
->getConfig();
3145 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
3146 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3147 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3148 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
3149 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3150 'id' => 'wpSummary',
3151 'name' => 'wpSummary',
3152 'maxlength' => $oldCommentSchema ?
200 : CommentStore
::COMMENT_CHARACTER_LIMIT
,
3155 'spellcheck' => 'true',
3160 * Builds a standard summary input with a label.
3162 * @param string $summary The value of the summary input
3163 * @param string $labelText The html to place inside the label
3164 * @param array $inputAttrs Array of attrs to use on the input
3166 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3168 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3169 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3170 $this->getSummaryInputAttributes( $inputAttrs )
3173 'title' => Linker
::titleAttrib( 'summary' ),
3174 'accessKey' => Linker
::accesskey( 'summary' ),
3177 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3178 $inputAttrs['inputId'] = $inputAttrs['id'];
3179 $inputAttrs['id'] = 'wpSummaryWidget';
3181 return new OOUI\
FieldLayout(
3182 new OOUI\
TextInputWidget( [
3183 'value' => $summary,
3184 'infusable' => true,
3187 'label' => new OOUI\
HtmlSnippet( $labelText ),
3189 'id' => 'wpSummaryLabel',
3190 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3196 * @param bool $isSubjectPreview True if this is the section subject/title
3197 * up top, or false if this is the comment summary
3198 * down below the textarea
3199 * @param string $summary The text of the summary to display
3201 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3202 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3203 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3204 if ( $isSubjectPreview ) {
3205 if ( $this->nosummary
) {
3209 if ( !$this->mShowSummaryField
) {
3214 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3215 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3218 [ 'class' => $summaryClass ]
3223 * @param bool $isSubjectPreview True if this is the section subject/title
3224 * up top, or false if this is the comment summary
3225 * down below the textarea
3226 * @param string $summary The text of the summary to display
3229 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3230 // avoid spaces in preview, gets always trimmed on save
3231 $summary = trim( $summary );
3232 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3238 if ( $isSubjectPreview ) {
3239 $summary = $this->context
->msg( 'newsectionsummary' )
3240 ->rawParams( $wgParser->stripSectionName( $summary ) )
3241 ->inContentLanguage()->text();
3244 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3246 $summary = $this->context
->msg( $message )->parse()
3247 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3248 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3251 protected function showFormBeforeText() {
3252 $out = $this->context
->getOutput();
3253 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3254 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3255 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3256 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3257 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3260 protected function showFormAfterText() {
3262 * To make it harder for someone to slip a user a page
3263 * which submits an edit form to the wiki without their
3264 * knowledge, a random token is associated with the login
3265 * session. If it's not passed back with the submission,
3266 * we won't save the page, or render user JavaScript and
3269 * For anon editors, who may not have a session, we just
3270 * include the constant suffix to prevent editing from
3271 * broken text-mangling proxies.
3273 $this->context
->getOutput()->addHTML(
3275 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3281 * Subpage overridable method for printing the form for page content editing
3282 * By default this simply outputs wpTextbox1
3283 * Subclasses can override this to provide a custom UI for editing;
3284 * be it a form, or simply wpTextbox1 with a modified content that will be
3285 * reverse modified when extracted from the post data.
3286 * Note that this is basically the inverse for importContentFormData
3288 protected function showContentForm() {
3289 $this->showTextbox1();
3293 * Method to output wpTextbox1
3294 * The $textoverride method can be used by subclasses overriding showContentForm
3295 * to pass back to this method.
3297 * @param array $customAttribs Array of html attributes to use in the textarea
3298 * @param string $textoverride Optional text to override $this->textarea1 with
3300 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3301 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3302 $attribs = [ 'style' => 'display:none;' ];
3304 $builder = new TextboxBuilder();
3305 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3307 # Is an old revision being edited?
3308 if ( $this->isOldRev
) {
3309 $classes[] = 'mw-textarea-oldrev';
3312 $attribs = [ 'tabindex' => 1 ];
3314 if ( is_array( $customAttribs ) ) {
3315 $attribs +
= $customAttribs;
3318 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3322 $textoverride !== null ?
$textoverride : $this->textbox1
,
3328 protected function showTextbox2() {
3329 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3332 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3333 $builder = new TextboxBuilder();
3334 $attribs = $builder->buildTextboxAttribs(
3337 $this->context
->getUser(),
3341 $this->context
->getOutput()->addHTML(
3342 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3346 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3349 $classes[] = 'ontop';
3352 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3354 if ( $this->formtype
!= 'preview' ) {
3355 $attribs['style'] = 'display: none;';
3358 $out = $this->context
->getOutput();
3359 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3361 if ( $this->formtype
== 'preview' ) {
3362 $this->showPreview( $previewOutput );
3364 // Empty content container for LivePreview
3365 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3366 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3367 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3368 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3371 $out->addHTML( '</div>' );
3373 if ( $this->formtype
== 'diff' ) {
3376 } catch ( MWContentSerializationException
$ex ) {
3377 $msg = $this->context
->msg(
3378 'content-failed-to-parse',
3379 $this->contentModel
,
3380 $this->contentFormat
,
3383 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3389 * Append preview output to OutputPage.
3390 * Includes category rendering if this is a category page.
3392 * @param string $text The HTML to be output for the preview.
3394 protected function showPreview( $text ) {
3395 if ( $this->mArticle
instanceof CategoryPage
) {
3396 $this->mArticle
->openShowCategory();
3398 # This hook seems slightly odd here, but makes things more
3399 # consistent for extensions.
3400 $out = $this->context
->getOutput();
3401 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3402 $out->addHTML( $text );
3403 if ( $this->mArticle
instanceof CategoryPage
) {
3404 $this->mArticle
->closeShowCategory();
3409 * Get a diff between the current contents of the edit box and the
3410 * version of the page we're editing from.
3412 * If this is a section edit, we'll replace the section as for final
3413 * save and then make a comparison.
3415 public function showDiff() {
3418 $oldtitlemsg = 'currentrev';
3419 # if message does not exist, show diff against the preloaded default
3420 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3421 $oldtext = $this->mTitle
->getDefaultMessageText();
3422 if ( $oldtext !== false ) {
3423 $oldtitlemsg = 'defaultmessagetext';
3424 $oldContent = $this->toEditContent( $oldtext );
3429 $oldContent = $this->getCurrentContent();
3432 $textboxContent = $this->toEditContent( $this->textbox1
);
3433 if ( $this->editRevId
!== null ) {
3434 $newContent = $this->page
->replaceSectionAtRev(
3435 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3438 $newContent = $this->page
->replaceSectionContent(
3439 $this->section
, $textboxContent, $this->summary
, $this->edittime
3443 if ( $newContent ) {
3444 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3446 $user = $this->context
->getUser();
3447 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
3448 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3451 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3452 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3453 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3455 if ( !$oldContent ) {
3456 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3459 if ( !$newContent ) {
3460 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3463 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3464 $de->setContent( $oldContent, $newContent );
3466 $difftext = $de->getDiff( $oldtitle, $newtitle );
3467 $de->showDiffStyle();
3472 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3476 * Show the header copyright warning.
3478 protected function showHeaderCopyrightWarning() {
3479 $msg = 'editpage-head-copy-warn';
3480 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3481 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3482 'editpage-head-copy-warn' );
3487 * Give a chance for site and per-namespace customizations of
3488 * terms of service summary link that might exist separately
3489 * from the copyright notice.
3491 * This will display between the save button and the edit tools,
3492 * so should remain short!
3494 protected function showTosSummary() {
3495 $msg = 'editpage-tos-summary';
3496 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3497 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3498 $out = $this->context
->getOutput();
3499 $out->addHTML( '<div class="mw-tos-summary">' );
3500 $out->addWikiMsg( $msg );
3501 $out->addHTML( '</div>' );
3506 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3507 * characters not present on most keyboards for copying/pasting.
3509 protected function showEditTools() {
3510 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3511 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3516 * Get the copyright warning
3518 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3521 protected function getCopywarn() {
3522 return self
::getCopyrightWarning( $this->mTitle
);
3526 * Get the copyright warning, by default returns wikitext
3528 * @param Title $title
3529 * @param string $format Output format, valid values are any function of a Message object
3530 * @param Language|string|null $langcode Language code or Language object.
3533 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3534 global $wgRightsText;
3535 if ( $wgRightsText ) {
3536 $copywarnMsg = [ 'copyrightwarning',
3537 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3540 $copywarnMsg = [ 'copyrightwarning2',
3541 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3543 // Allow for site and per-namespace customization of contribution/copyright notice.
3544 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3546 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3548 $msg->inLanguage( $langcode );
3550 return "<div id=\"editpage-copywarn\">\n" .
3551 $msg->$format() . "\n</div>";
3555 * Get the Limit report for page previews
3558 * @param ParserOutput $output ParserOutput object from the parse
3559 * @return string HTML
3561 public static function getPreviewLimitReport( $output ) {
3564 if ( !$output ||
!$output->getLimitReportData() ) {
3568 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3569 wfMessage( 'limitreport-title' )->parseAsBlock()
3572 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3573 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3575 $limitReport .= Html
::openElement( 'table', [
3576 'class' => 'preview-limit-report wikitable'
3578 Html
::openElement( 'tbody' );
3580 foreach ( $output->getLimitReportData() as $key => $value ) {
3581 if ( Hooks
::run( 'ParserLimitReportFormat',
3582 [ $key, &$value, &$limitReport, true, true ]
3584 $keyMsg = wfMessage( $key );
3585 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3586 if ( !$valueMsg->exists() ) {
3587 $valueMsg = new RawMessage( '$1' );
3589 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3590 $limitReport .= Html
::openElement( 'tr' ) .
3591 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3592 Html
::rawElement( 'td', null,
3593 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3595 Html
::closeElement( 'tr' );
3600 $limitReport .= Html
::closeElement( 'tbody' ) .
3601 Html
::closeElement( 'table' ) .
3602 Html
::closeElement( 'div' );
3604 return $limitReport;
3607 protected function showStandardInputs( &$tabindex = 2 ) {
3608 $out = $this->context
->getOutput();
3609 $out->addHTML( "<div class='editOptions'>\n" );
3611 if ( $this->section
!= 'new' ) {
3612 $this->showSummaryInput( false, $this->summary
);
3613 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3616 $checkboxes = $this->getCheckboxesWidget(
3618 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3620 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3622 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3624 // Show copyright warning.
3625 $out->addWikiText( $this->getCopywarn() );
3626 $out->addHTML( $this->editFormTextAfterWarn
);
3628 $out->addHTML( "<div class='editButtons'>\n" );
3629 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3631 $cancel = $this->getCancelLink();
3633 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3634 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3637 $this->context
->msg( 'edithelp' )->text(),
3638 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3641 $this->context
->msg( 'word-separator' )->escaped() .
3642 $this->context
->msg( 'newwindow' )->parse();
3644 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3645 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3646 $out->addHTML( "</div><!-- editButtons -->\n" );
3648 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3650 $out->addHTML( "</div><!-- editOptions -->\n" );
3654 * Show an edit conflict. textbox1 is already shown in showEditForm().
3655 * If you want to use another entry point to this function, be careful.
3657 protected function showConflict() {
3658 $out = $this->context
->getOutput();
3659 // Avoid PHP 7.1 warning of passing $this by reference
3661 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3662 $this->incrementConflictStats();
3664 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3668 protected function incrementConflictStats() {
3669 $this->getEditConflictHelper()->incrementConflictStats();
3675 public function getCancelLink() {
3677 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3678 $cancelParams['oldid'] = $this->oldid
;
3679 } elseif ( $this->getContextTitle()->isRedirect() ) {
3680 $cancelParams['redirect'] = 'no';
3683 return new OOUI\
ButtonWidget( [
3684 'id' => 'mw-editform-cancel',
3685 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3686 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3688 'infusable' => true,
3689 'flags' => 'destructive',
3694 * Returns the URL to use in the form's action attribute.
3695 * This is used by EditPage subclasses when simply customizing the action
3696 * variable in the constructor is not enough. This can be used when the
3697 * EditPage lives inside of a Special page rather than a custom page action.
3699 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3702 protected function getActionURL( Title
$title ) {
3703 return $title->getLocalURL( [ 'action' => $this->action
] );
3707 * Check if a page was deleted while the user was editing it, before submit.
3708 * Note that we rely on the logging table, which hasn't been always there,
3709 * but that doesn't matter, because this only applies to brand new
3713 protected function wasDeletedSinceLastEdit() {
3714 if ( $this->deletedSinceEdit
!== null ) {
3715 return $this->deletedSinceEdit
;
3718 $this->deletedSinceEdit
= false;
3720 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3721 $this->lastDelete
= $this->getLastDelete();
3722 if ( $this->lastDelete
) {
3723 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3724 if ( $deleteTime > $this->starttime
) {
3725 $this->deletedSinceEdit
= true;
3730 return $this->deletedSinceEdit
;
3734 * @return bool|stdClass
3736 protected function getLastDelete() {
3737 $dbr = wfGetDB( DB_REPLICA
);
3738 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3739 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3740 $data = $dbr->selectRow(
3741 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3751 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3753 'log_namespace' => $this->mTitle
->getNamespace(),
3754 'log_title' => $this->mTitle
->getDBkey(),
3755 'log_type' => 'delete',
3756 'log_action' => 'delete',
3759 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3761 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3762 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3764 // Quick paranoid permission checks...
3765 if ( is_object( $data ) ) {
3766 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3767 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3770 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3771 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3772 $data->log_comment_data
= null;
3780 * Get the rendered text for previewing.
3781 * @throws MWException
3784 public function getPreviewText() {
3785 $out = $this->context
->getOutput();
3786 $config = $this->context
->getConfig();
3788 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3789 // Could be an offsite preview attempt. This is very unsafe if
3790 // HTML is enabled, as it could be an attack.
3792 if ( $this->textbox1
!== '' ) {
3793 // Do not put big scary notice, if previewing the empty
3794 // string, which happens when you initially edit
3795 // a category page, due to automatic preview-on-open.
3796 $parsedNote = $out->parse( "<div class='previewnote'>" .
3797 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3798 true, /* interface */true );
3800 $this->incrementEditFailureStats( 'session_loss' );
3807 $content = $this->toEditContent( $this->textbox1
);
3811 'AlternateEditPreview',
3812 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3814 return $previewHTML;
3817 # provide a anchor link to the editform
3818 $continueEditing = '<span class="mw-continue-editing">' .
3819 '[[#' . self
::EDITFORM_ID
. '|' .
3820 $this->context
->getLanguage()->getArrow() . ' ' .
3821 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3822 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3823 if ( $this->mTokenOkExceptSuffix
) {
3824 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3825 $this->incrementEditFailureStats( 'bad_token' );
3827 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3828 $this->incrementEditFailureStats( 'session_loss' );
3830 } elseif ( $this->incompleteForm
) {
3831 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3832 if ( $this->mTriedSave
) {
3833 $this->incrementEditFailureStats( 'incomplete_form' );
3836 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3839 # don't parse non-wikitext pages, show message about preview
3840 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3841 if ( $this->mTitle
->isUserConfigPage() ) {
3843 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3849 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3851 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3854 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3856 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3859 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3861 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3868 # Used messages to make sure grep find them:
3869 # Messages: usercsspreview, userjsonpreview, userjspreview,
3870 # sitecsspreview, sitejsonpreview, sitejspreview
3871 if ( $level && $format ) {
3872 $note = "<div id='mw-{$level}{$format}preview'>" .
3873 $this->context
->msg( "{$level}{$format}preview" )->text() .
3874 ' ' . $continueEditing . "</div>";
3878 # If we're adding a comment, we need to show the
3879 # summary as the headline
3880 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3881 $content = $content->addSectionHeader( $this->summary
);
3884 $hook_args = [ $this, &$content ];
3885 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3887 $parserResult = $this->doPreviewParse( $content );
3888 $parserOutput = $parserResult['parserOutput'];
3889 $previewHTML = $parserResult['html'];
3890 $this->mParserOutput
= $parserOutput;
3891 $out->addParserOutputMetadata( $parserOutput );
3892 if ( $out->userCanPreview() ) {
3893 $out->addContentOverride( $this->getTitle(), $content );
3896 if ( count( $parserOutput->getWarnings() ) ) {
3897 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3900 } catch ( MWContentSerializationException
$ex ) {
3901 $m = $this->context
->msg(
3902 'content-failed-to-parse',
3903 $this->contentModel
,
3904 $this->contentFormat
,
3907 $note .= "\n\n" . $m->parse();
3911 if ( $this->isConflict
) {
3912 $conflict = '<h2 id="mw-previewconflict">'
3913 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3915 $conflict = '<hr />';
3918 $previewhead = "<div class='previewnote'>\n" .
3919 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3920 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3922 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3923 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3924 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3925 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3927 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3930 private function incrementEditFailureStats( $failureType ) {
3931 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3932 $stats->increment( 'edit.failures.' . $failureType );
3936 * Get parser options for a preview
3937 * @return ParserOptions
3939 protected function getPreviewParserOptions() {
3940 $parserOptions = $this->page
->makeParserOptions( $this->context
);
3941 $parserOptions->setIsPreview( true );
3942 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3943 $parserOptions->enableLimitReport();
3944 return $parserOptions;
3948 * Parse the page for a preview. Subclasses may override this class, in order
3949 * to parse with different options, or to otherwise modify the preview HTML.
3951 * @param Content $content The page content
3952 * @return array with keys:
3953 * - parserOutput: The ParserOutput object
3954 * - html: The HTML to be displayed
3956 protected function doPreviewParse( Content
$content ) {
3957 $user = $this->context
->getUser();
3958 $parserOptions = $this->getPreviewParserOptions();
3959 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
3960 $scopedCallback = $parserOptions->setupFakeRevision(
3961 $this->mTitle
, $pstContent, $user );
3962 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3963 ScopedCallback
::consume( $scopedCallback );
3965 'parserOutput' => $parserOutput,
3966 'html' => $parserOutput->getText( [
3967 'enableSectionEditLinks' => false
3975 public function getTemplates() {
3976 if ( $this->preview ||
$this->section
!= '' ) {
3978 if ( !isset( $this->mParserOutput
) ) {
3981 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3982 foreach ( array_keys( $template ) as $dbk ) {
3983 $templates[] = Title
::makeTitle( $ns, $dbk );
3988 return $this->mTitle
->getTemplateLinksFrom();
3993 * Shows a bulletin board style toolbar for common editing functions.
3994 * It can be disabled in the user preferences.
3996 * @param Title $title Title object for the page being edited (optional)
3999 public static function getEditToolbar( $title = null ) {
4000 global $wgContLang, $wgOut;
4001 global $wgEnableUploads, $wgForeignFileRepos;
4003 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
4004 $showSignature = true;
4006 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4010 * $toolarray is an array of arrays each of which includes the
4011 * opening tag, the closing tag, optionally a sample text that is
4012 * inserted between the two when no selection is highlighted
4013 * and. The tip text is shown when the user moves the mouse
4016 * Images are defined in ResourceLoaderEditToolbarModule.
4020 'id' => 'mw-editbutton-bold',
4022 'close' => '\'\'\'',
4023 'sample' => wfMessage( 'bold_sample' )->text(),
4024 'tip' => wfMessage( 'bold_tip' )->text(),
4027 'id' => 'mw-editbutton-italic',
4030 'sample' => wfMessage( 'italic_sample' )->text(),
4031 'tip' => wfMessage( 'italic_tip' )->text(),
4034 'id' => 'mw-editbutton-link',
4037 'sample' => wfMessage( 'link_sample' )->text(),
4038 'tip' => wfMessage( 'link_tip' )->text(),
4041 'id' => 'mw-editbutton-extlink',
4044 'sample' => wfMessage( 'extlink_sample' )->text(),
4045 'tip' => wfMessage( 'extlink_tip' )->text(),
4048 'id' => 'mw-editbutton-headline',
4051 'sample' => wfMessage( 'headline_sample' )->text(),
4052 'tip' => wfMessage( 'headline_tip' )->text(),
4054 $imagesAvailable ?
[
4055 'id' => 'mw-editbutton-image',
4056 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4058 'sample' => wfMessage( 'image_sample' )->text(),
4059 'tip' => wfMessage( 'image_tip' )->text(),
4061 $imagesAvailable ?
[
4062 'id' => 'mw-editbutton-media',
4063 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4065 'sample' => wfMessage( 'media_sample' )->text(),
4066 'tip' => wfMessage( 'media_tip' )->text(),
4069 'id' => 'mw-editbutton-nowiki',
4070 'open' => "<nowiki>",
4071 'close' => "</nowiki>",
4072 'sample' => wfMessage( 'nowiki_sample' )->text(),
4073 'tip' => wfMessage( 'nowiki_tip' )->text(),
4076 'id' => 'mw-editbutton-signature',
4077 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4080 'tip' => wfMessage( 'sig_tip' )->text(),
4083 'id' => 'mw-editbutton-hr',
4084 'open' => "\n----\n",
4087 'tip' => wfMessage( 'hr_tip' )->text(),
4091 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4092 foreach ( $toolarray as $tool ) {
4098 // Images are defined in ResourceLoaderEditToolbarModule
4100 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4101 // Older browsers show a "speedtip" type message only for ALT.
4102 // Ideally these should be different, realistically they
4103 // probably don't need to be.
4111 $script .= Xml
::encodeJsCall(
4112 'mw.toolbar.addButton',
4114 ResourceLoader
::inDebugMode()
4120 $toolbar = '<div id="toolbar"></div>';
4122 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4123 // Only add the old toolbar cruft to the page payload if the toolbar has not
4124 // been over-written by a hook caller
4125 $nonce = $wgOut->getCSPNonce();
4126 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script, $nonce ) );
4133 * Return an array of checkbox definitions.
4135 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4137 * Array values are associative arrays with the following keys:
4138 * - 'label-message' (required): message for label text
4139 * - 'id' (required): 'id' attribute for the `<input>`
4140 * - 'default' (required): default checkedness (true or false)
4141 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4142 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4143 * from messages like 'tooltip-foo', 'accesskey-foo'
4144 * - 'label-id' (optional): 'id' attribute for the `<label>`
4145 * - 'legacy-name' (optional): short name for backwards-compatibility
4146 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4147 * where bool indicates the checked status of the checkbox
4150 public function getCheckboxesDefinition( $checked ) {
4153 $user = $this->context
->getUser();
4154 // don't show the minor edit checkbox if it's a new page or section
4155 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4156 $checkboxes['wpMinoredit'] = [
4157 'id' => 'wpMinoredit',
4158 'label-message' => 'minoredit',
4159 // Uses messages: tooltip-minoredit, accesskey-minoredit
4160 'tooltip' => 'minoredit',
4161 'label-id' => 'mw-editpage-minoredit',
4162 'legacy-name' => 'minor',
4163 'default' => $checked['minor'],
4167 if ( $user->isLoggedIn() ) {
4168 $checkboxes['wpWatchthis'] = [
4169 'id' => 'wpWatchthis',
4170 'label-message' => 'watchthis',
4171 // Uses messages: tooltip-watch, accesskey-watch
4172 'tooltip' => 'watch',
4173 'label-id' => 'mw-editpage-watch',
4174 'legacy-name' => 'watch',
4175 'default' => $checked['watch'],
4180 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4186 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4187 * any other added by extensions.
4189 * @param int &$tabindex Current tabindex
4190 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4191 * status of the checkbox
4193 * @return array Associative array of string keys to OOUI\FieldLayout instances
4195 public function getCheckboxesWidget( &$tabindex, $checked ) {
4197 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4199 foreach ( $checkboxesDef as $name => $options ) {
4200 $legacyName = $options['legacy-name'] ??
$name;
4204 if ( isset( $options['tooltip'] ) ) {
4205 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4206 $title = Linker
::titleAttrib( $options['tooltip'] );
4208 if ( isset( $options['title-message'] ) ) {
4209 $title = $this->context
->msg( $options['title-message'] )->text();
4212 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4213 new OOUI\
CheckboxInputWidget( [
4214 'tabIndex' => ++
$tabindex,
4215 'accessKey' => $accesskey,
4216 'id' => $options['id'] . 'Widget',
4217 'inputId' => $options['id'],
4219 'selected' => $options['default'],
4220 'infusable' => true,
4223 'align' => 'inline',
4224 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4226 'id' => $options['label-id'] ??
null,
4235 * Get the message key of the label for the button to save the page
4240 protected function getSubmitButtonLabel() {
4242 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4244 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4245 $newPage = !$this->mTitle
->exists();
4247 if ( $labelAsPublish ) {
4248 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4250 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4253 return $buttonLabelKey;
4257 * Returns an array of html code of the following buttons:
4258 * save, diff and preview
4260 * @param int &$tabindex Current tabindex
4264 public function getEditButtons( &$tabindex ) {
4268 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4270 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4271 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4273 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4275 'tabIndex' => ++
$tabindex,
4276 'id' => 'wpSaveWidget',
4277 'inputId' => 'wpSave',
4278 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4279 'useInputTag' => true,
4280 'flags' => [ 'progressive', 'primary' ],
4281 'label' => $buttonLabel,
4282 'infusable' => true,
4284 // Messages used: tooltip-save, tooltip-publish
4285 'title' => Linker
::titleAttrib( $buttonTooltip ),
4286 // Messages used: accesskey-save, accesskey-publish
4287 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4290 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4291 'name' => 'wpPreview',
4292 'tabIndex' => ++
$tabindex,
4293 'id' => 'wpPreviewWidget',
4294 'inputId' => 'wpPreview',
4295 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4296 'useInputTag' => true,
4297 'label' => $this->context
->msg( 'showpreview' )->text(),
4298 'infusable' => true,
4300 // Message used: tooltip-preview
4301 'title' => Linker
::titleAttrib( 'preview' ),
4302 // Message used: accesskey-preview
4303 'accessKey' => Linker
::accesskey( 'preview' ),
4306 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4308 'tabIndex' => ++
$tabindex,
4309 'id' => 'wpDiffWidget',
4310 'inputId' => 'wpDiff',
4311 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4312 'useInputTag' => true,
4313 'label' => $this->context
->msg( 'showdiff' )->text(),
4314 'infusable' => true,
4316 // Message used: tooltip-diff
4317 'title' => Linker
::titleAttrib( 'diff' ),
4318 // Message used: accesskey-diff
4319 'accessKey' => Linker
::accesskey( 'diff' ),
4322 // Avoid PHP 7.1 warning of passing $this by reference
4324 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4330 * Creates a basic error page which informs the user that
4331 * they have attempted to edit a nonexistent section.
4333 public function noSuchSectionPage() {
4334 $out = $this->context
->getOutput();
4335 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4337 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4339 // Avoid PHP 7.1 warning of passing $this by reference
4341 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4342 $out->addHTML( $res );
4344 $out->returnToMain( false, $this->mTitle
);
4348 * Show "your edit contains spam" page with your diff and text
4350 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4352 public function spamPageWithContent( $match = false ) {
4353 $this->textbox2
= $this->textbox1
;
4355 if ( is_array( $match ) ) {
4356 $match = $this->context
->getLanguage()->listToText( $match );
4358 $out = $this->context
->getOutput();
4359 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4361 $out->addHTML( '<div id="spamprotected">' );
4362 $out->addWikiMsg( 'spamprotectiontext' );
4364 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4366 $out->addHTML( '</div>' );
4368 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4371 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4372 $this->showTextbox2();
4374 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4378 * Filter an input field through a Unicode de-armoring process if it
4379 * came from an old browser with known broken Unicode editing issues.
4381 * @deprecated since 1.30, does nothing
4383 * @param WebRequest $request
4384 * @param string $field
4387 protected function safeUnicodeInput( $request, $field ) {
4388 return rtrim( $request->getText( $field ) );
4392 * Filter an output field through a Unicode armoring process if it is
4393 * going to an old browser with known broken Unicode editing issues.
4395 * @deprecated since 1.30, does nothing
4397 * @param string $text
4400 protected function safeUnicodeOutput( $text ) {
4407 protected function addEditNotices() {
4408 $out = $this->context
->getOutput();
4409 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4410 if ( count( $editNotices ) ) {
4411 $out->addHTML( implode( "\n", $editNotices ) );
4413 $msg = $this->context
->msg( 'editnotice-notext' );
4414 if ( !$msg->isDisabled() ) {
4416 '<div class="mw-editnotice-notext">'
4417 . $msg->parseAsBlock()
4427 protected function addTalkPageText() {
4428 if ( $this->mTitle
->isTalkPage() ) {
4429 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4436 protected function addLongPageWarningHeader() {
4437 if ( $this->contentLength
=== false ) {
4438 $this->contentLength
= strlen( $this->textbox1
);
4441 $out = $this->context
->getOutput();
4442 $lang = $this->context
->getLanguage();
4443 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4444 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4445 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4448 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4449 $lang->formatNum( $maxArticleSize )
4453 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4454 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4457 $lang->formatSize( strlen( $this->textbox1
) ),
4458 strlen( $this->textbox1
)
4468 protected function addPageProtectionWarningHeaders() {
4469 $out = $this->context
->getOutput();
4470 if ( $this->mTitle
->isProtected( 'edit' ) &&
4471 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4473 # Is the title semi-protected?
4474 if ( $this->mTitle
->isSemiProtected() ) {
4475 $noticeMsg = 'semiprotectedpagewarning';
4477 # Then it must be protected based on static groups (regular)
4478 $noticeMsg = 'protectedpagewarning';
4480 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4481 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4483 if ( $this->mTitle
->isCascadeProtected() ) {
4484 # Is this page under cascading protection from some source pages?
4485 /** @var Title[] $cascadeSources */
4486 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4487 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4488 $cascadeSourcesCount = count( $cascadeSources );
4489 if ( $cascadeSourcesCount > 0 ) {
4490 # Explain, and list the titles responsible
4491 foreach ( $cascadeSources as $page ) {
4492 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4495 $notice .= '</div>';
4496 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4498 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4499 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4501 'showIfEmpty' => false,
4502 'msgKey' => [ 'titleprotectedwarning' ],
4503 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4508 * @param OutputPage $out
4511 protected function addExplainConflictHeader( OutputPage
$out ) {
4513 $this->getEditConflictHelper()->getExplainHeader()
4518 * @param string $name
4519 * @param mixed[] $customAttribs
4524 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4525 return ( new TextboxBuilder() )->buildTextboxAttribs(
4526 $name, $customAttribs, $user, $this->mTitle
4531 * @param string $wikitext
4535 protected function addNewLineAtEnd( $wikitext ) {
4536 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4540 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4541 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4542 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4543 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4544 * spread the new style links more efficiently.
4546 * @param string $text
4549 private function guessSectionName( $text ) {
4552 // Detect Microsoft browsers
4553 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4554 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4555 // ...and redirect them to legacy encoding, if available
4556 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4558 // Meanwhile, real browsers get real anchors
4559 return $wgParser->guessSectionNameFromWikiText( $text );
4563 * Set a factory function to create an EditConflictHelper
4565 * @param callable $factory Factory function
4568 public function setEditConflictHelperFactory( callable
$factory ) {
4569 $this->editConflictHelperFactory
= $factory;
4570 $this->editConflictHelper
= null;
4574 * @return TextConflictHelper
4576 private function getEditConflictHelper() {
4577 if ( !$this->editConflictHelper
) {
4578 $this->editConflictHelper
= call_user_func(
4579 $this->editConflictHelperFactory
,
4580 $this->getSubmitButtonLabel()
4584 return $this->editConflictHelper
;
4588 * @param string $submitButtonLabel
4589 * @return TextConflictHelper
4591 private function newTextConflictHelper( $submitButtonLabel ) {
4592 return new TextConflictHelper(
4594 $this->getContext()->getOutput(),
4595 MediaWikiServices
::getInstance()->getStatsdDataFactory(),