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';
238 /** @var bool Whether an edit conflict needs to be resolved. Detected based on whether
239 * $editRevId is different than the latest revision. When a conflict has successfully
240 * been resolved by a 3-way-merge, this field is set to false.
242 public $isConflict = false;
244 /** @var bool New page or new section */
245 public $isNew = false;
248 public $deletedSinceEdit;
254 * True the first time the edit form is rendered, false after re-rendering
255 * with diff, save prompts, etc.
259 /** @var bool|stdClass */
263 public $mTokenOk = false;
266 public $mTokenOkExceptSuffix = false;
269 public $mTriedSave = false;
272 public $incompleteForm = false;
275 public $tooBig = false;
278 public $missingComment = false;
281 public $missingSummary = false;
284 public $allowBlankSummary = false;
287 protected $blankArticle = false;
290 protected $allowBlankArticle = false;
293 protected $selfRedirect = false;
296 protected $allowSelfRedirect = false;
299 public $autoSumm = '';
302 public $hookError = '';
304 /** @var ParserOutput */
305 public $mParserOutput;
307 /** @var bool Has a summary been preset using GET parameter &summary= ? */
308 public $hasPresetSummary = false;
310 /** @var Revision|bool|null A revision object corresponding to $this->editRevId. */
311 public $mBaseRevision = false;
314 public $mShowSummaryField = true;
319 public $save = false;
322 public $preview = false;
325 public $diff = false;
328 public $minoredit = false;
331 public $watchthis = false;
334 public $recreate = false;
337 * Page content input field.
339 public $textbox1 = '';
342 public $textbox2 = '';
345 public $summary = '';
348 * If true, hide the summary field.
350 public $nosummary = false;
353 * Timestamp of the latest revision of the page when editing was initiated
356 public $edittime = '';
358 /** @var int Revision ID of the latest revision of the page when editing
359 * was initiated on the client. This is used to detect and resolve edit
362 * @note 0 if the page did not exist at that time.
363 * @note When starting an edit from an old revision, this still records the current
364 * revision at the time, not the one the edit is based on.
367 * @see getBaseRevision()
369 private $editRevId = null;
372 public $section = '';
375 public $sectiontitle = '';
378 * Timestamp from the first time the edit form was rendered.
380 public $starttime = '';
382 /** @var int Revision ID the edit is based on, or 0 if it's the current revision.
383 * FIXME: This isn't used in conflict resolution--provide a better
384 * justification or merge with parentRevId.
389 /** @var int Revision ID the edit is based on, adjusted when an edit conflict is resolved.
392 * @see getparentRevId()
394 public $parentRevId = 0;
397 public $editintro = '';
400 public $scrolltop = null;
406 public $contentModel;
408 /** @var null|string */
409 public $contentFormat = null;
411 /** @var null|array */
412 private $changeTags = null;
414 # Placeholders for text injection by hooks (must be HTML)
415 # extensions should take care to _append_ to the present value
417 /** @var string Before even the preview */
418 public $editFormPageTop = '';
419 public $editFormTextTop = '';
420 public $editFormTextBeforeContent = '';
421 public $editFormTextAfterWarn = '';
422 public $editFormTextAfterTools = '';
423 public $editFormTextBottom = '';
424 public $editFormTextAfterContent = '';
425 public $previewTextAfterContent = '';
426 public $mPreloadContent = null;
428 /* $didSave should be set to true whenever an article was successfully altered. */
429 public $didSave = false;
430 public $undidRev = 0;
432 public $suppressIntro = false;
438 protected $contentLength = false;
441 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
443 private $enableApiEditOverride = false;
446 * @var IContextSource
451 * @var bool Whether an old revision is edited
453 private $isOldRev = false;
456 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
458 private $unicodeCheck;
461 * Factory function to create an edit conflict helper
465 private $editConflictHelperFactory;
468 * @var TextConflictHelper|null
470 private $editConflictHelper;
473 * @param Article $article
475 public function __construct( Article
$article ) {
476 $this->mArticle
= $article;
477 $this->page
= $article->getPage(); // model object
478 $this->mTitle
= $article->getTitle();
480 // Make sure the local context is in sync with other member variables.
481 // Particularly make sure everything is using the same WikiPage instance.
482 // This should probably be the case in Article as well, but it's
483 // particularly important for EditPage, to make use of the in-place caching
484 // facility in WikiPage::prepareContentForEdit.
485 $this->context
= new DerivativeContext( $article->getContext() );
486 $this->context
->setWikiPage( $this->page
);
487 $this->context
->setTitle( $this->mTitle
);
489 $this->contentModel
= $this->mTitle
->getContentModel();
491 $handler = ContentHandler
::getForModelID( $this->contentModel
);
492 $this->contentFormat
= $handler->getDefaultFormat();
493 $this->editConflictHelperFactory
= [ $this, 'newTextConflictHelper' ];
499 public function getArticle() {
500 return $this->mArticle
;
505 * @return IContextSource
507 public function getContext() {
508 return $this->context
;
515 public function getTitle() {
516 return $this->mTitle
;
520 * Set the context Title object
522 * @param Title|null $title Title object or null
524 public function setContextTitle( $title ) {
525 $this->mContextTitle
= $title;
529 * Get the context title object.
531 * If not set, $wgTitle will be returned, but this is deprecated. This will
532 * throw an exception.
536 public function getContextTitle() {
537 if ( is_null( $this->mContextTitle
) ) {
538 wfDeprecated( __METHOD__
. ' called with no title set', '1.32' );
542 return $this->mContextTitle
;
547 * Returns if the given content model is editable.
549 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
551 * @throws MWException If $modelId has no known handler
553 public function isSupportedContentModel( $modelId ) {
554 return $this->enableApiEditOverride
=== true ||
555 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
559 * Allow editing of content that supports API direct editing, but not general
560 * direct editing. Set to false by default.
562 * @param bool $enableOverride
564 public function setApiEditOverride( $enableOverride ) {
565 $this->enableApiEditOverride
= $enableOverride;
569 * @deprecated since 1.29, call edit directly
571 public function submit() {
572 wfDeprecated( __METHOD__
, '1.29' );
577 * This is the function that gets called for "action=edit". It
578 * sets up various member variables, then passes execution to
579 * another function, usually showEditForm()
581 * The edit form is self-submitting, so that when things like
582 * preview and edit conflicts occur, we get the same form back
583 * with the extra stuff added. Only when the final submission
584 * is made and all is well do we actually save and redirect to
585 * the newly-edited page.
587 public function edit() {
588 // Allow extensions to modify/prevent this form or submission
589 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
593 wfDebug( __METHOD__
. ": enter\n" );
595 $request = $this->context
->getRequest();
596 // If they used redlink=1 and the page exists, redirect to the main article
597 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
598 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
602 $this->importFormData( $request );
603 $this->firsttime
= false;
605 if ( wfReadOnly() && $this->save
) {
608 $this->preview
= true;
612 $this->formtype
= 'save';
613 } elseif ( $this->preview
) {
614 $this->formtype
= 'preview';
615 } elseif ( $this->diff
) {
616 $this->formtype
= 'diff';
617 } else { # First time through
618 $this->firsttime
= true;
619 if ( $this->previewOnOpen() ) {
620 $this->formtype
= 'preview';
622 $this->formtype
= 'initial';
626 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
628 wfDebug( __METHOD__
. ": User can't edit\n" );
630 if ( $this->context
->getUser()->getBlock() ) {
631 // track block with a cookie if it doesn't exists already
632 $this->context
->getUser()->trackBlockWithCookie();
634 // Auto-block user's IP if the account was "hard" blocked
635 if ( !wfReadOnly() ) {
636 DeferredUpdates
::addCallableUpdate( function () {
637 $this->context
->getUser()->spreadAnyEditBlock();
641 $this->displayPermissionsError( $permErrors );
646 $revision = $this->mArticle
->getRevisionFetched();
647 // Disallow editing revisions with content models different from the current one
648 // Undo edits being an exception in order to allow reverting content model changes.
650 && $revision->getContentModel() !== $this->contentModel
653 if ( $this->undidRev
) {
654 $undidRevObj = Revision
::newFromId( $this->undidRev
);
655 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
657 if ( !$this->undidRev
659 ||
$prevRev->getContentModel() !== $this->contentModel
661 $this->displayViewSourcePage(
662 $this->getContentObject(),
664 'contentmodelediterror',
665 $revision->getContentModel(),
673 $this->isConflict
= false;
675 # Show applicable editing introductions
676 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
680 # Attempt submission here. This will check for edit conflicts,
681 # and redundantly check for locked database, blocked IPs, etc.
682 # that edit() already checked just in case someone tries to sneak
683 # in the back door with a hand-edited submission URL.
685 if ( $this->formtype
== 'save' ) {
686 $resultDetails = null;
687 $status = $this->attemptSave( $resultDetails );
688 if ( !$this->handleStatus( $status, $resultDetails ) ) {
693 # First time through: get contents, set time for conflict
695 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
696 if ( $this->initialiseForm() === false ) {
697 $out = $this->context
->getOutput();
698 if ( $out->getRedirect() === '' ) { // mcrundo hack redirects, don't override it
699 $this->noSuchSectionPage();
704 if ( !$this->mTitle
->getArticleID() ) {
705 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
707 Hooks
::run( 'EditFormInitialText', [ $this ] );
712 $this->showEditForm();
716 * @param string $rigor Same format as Title::getUserPermissionErrors()
719 protected function getEditPermissionErrors( $rigor = 'secure' ) {
720 $user = $this->context
->getUser();
721 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
722 # Can this title be created?
723 if ( !$this->mTitle
->exists() ) {
724 $permErrors = array_merge(
727 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
732 # Ignore some permissions errors when a user is just previewing/viewing diffs
734 foreach ( $permErrors as $error ) {
735 if ( ( $this->preview ||
$this->diff
)
737 $error[0] == 'blockedtext' ||
738 $error[0] == 'autoblockedtext' ||
739 $error[0] == 'systemblockedtext'
745 $permErrors = wfArrayDiff2( $permErrors, $remove );
751 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
752 * but with the following differences:
753 * - If redlink=1, the user will be redirected to the page
754 * - If there is content to display or the error occurs while either saving,
755 * previewing or showing the difference, it will be a
756 * "View source for ..." page displaying the source code after the error message.
759 * @param array $permErrors Array of permissions errors, as returned by
760 * Title::getUserPermissionsErrors().
761 * @throws PermissionsError
763 protected function displayPermissionsError( array $permErrors ) {
764 $out = $this->context
->getOutput();
765 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
766 // The edit page was reached via a red link.
767 // Redirect to the article page and let them click the edit tab if
768 // they really want a permission error.
769 $out->redirect( $this->mTitle
->getFullURL() );
773 $content = $this->getContentObject();
775 # Use the normal message if there's nothing to display
776 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
777 $action = $this->mTitle
->exists() ?
'edit' :
778 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
779 throw new PermissionsError( $action, $permErrors );
782 $this->displayViewSourcePage(
784 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
789 * Display a read-only View Source page
790 * @param Content $content
791 * @param string $errorMessage additional wikitext error message to display
793 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
794 $out = $this->context
->getOutput();
795 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
797 $out->setRobotPolicy( 'noindex,nofollow' );
798 $out->setPageTitle( $this->context
->msg(
800 $this->getContextTitle()->getPrefixedText()
802 $out->addBacklinkSubtitle( $this->getContextTitle() );
803 $out->addHTML( $this->editFormPageTop
);
804 $out->addHTML( $this->editFormTextTop
);
806 if ( $errorMessage !== '' ) {
807 $out->addWikiTextAsInterface( $errorMessage );
808 $out->addHTML( "<hr />\n" );
811 # If the user made changes, preserve them when showing the markup
812 # (This happens when a user is blocked during edit, for instance)
813 if ( !$this->firsttime
) {
814 $text = $this->textbox1
;
815 $out->addWikiMsg( 'viewyourtext' );
818 $text = $this->toEditText( $content );
819 } catch ( MWException
$e ) {
820 # Serialize using the default format if the content model is not supported
821 # (e.g. for an old revision with a different model)
822 $text = $content->serialize();
824 $out->addWikiMsg( 'viewsourcetext' );
827 $out->addHTML( $this->editFormTextBeforeContent
);
828 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
829 $out->addHTML( $this->editFormTextAfterContent
);
831 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
833 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
835 $out->addHTML( $this->editFormTextBottom
);
836 if ( $this->mTitle
->exists() ) {
837 $out->returnToMain( null, $this->mTitle
);
842 * Should we show a preview when the edit form is first shown?
846 protected function previewOnOpen() {
847 $config = $this->context
->getConfig();
848 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
849 $request = $this->context
->getRequest();
850 if ( $config->get( 'RawHtml' ) ) {
851 // If raw HTML is enabled, disable preview on open
852 // since it has to be posted with a token for
856 if ( $request->getVal( 'preview' ) == 'yes' ) {
857 // Explicit override from request
859 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
860 // Explicit override from request
862 } elseif ( $this->section
== 'new' ) {
863 // Nothing *to* preview for new sections
865 } elseif ( ( $request->getCheck( 'preload' ) ||
$this->mTitle
->exists() )
866 && $this->context
->getUser()->getOption( 'previewonfirst' )
868 // Standard preference behavior
870 } elseif ( !$this->mTitle
->exists()
871 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
872 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
874 // Categories are special
882 * Checks whether the user entered a skin name in uppercase,
883 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
887 protected function isWrongCaseUserConfigPage() {
888 if ( $this->mTitle
->isUserConfigPage() ) {
889 $name = $this->mTitle
->getSkinFromConfigSubpage();
890 $skins = array_merge(
891 array_keys( Skin
::getSkinNames() ),
894 return !in_array( $name, $skins )
895 && in_array( strtolower( $name ), $skins );
902 * Returns whether section editing is supported for the current page.
903 * Subclasses may override this to replace the default behavior, which is
904 * to check ContentHandler::supportsSections.
906 * @return bool True if this edit page supports sections, false otherwise.
908 protected function isSectionEditSupported() {
909 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
910 return $contentHandler->supportsSections();
914 * This function collects the form data and uses it to populate various member variables.
915 * @param WebRequest &$request
916 * @throws ErrorPageError
918 public function importFormData( &$request ) {
919 # Section edit can come from either the form or a link
920 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
922 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
923 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
926 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
928 if ( $request->wasPosted() ) {
929 # These fields need to be checked for encoding.
930 # Also remove trailing whitespace, but don't remove _initial_
931 # whitespace from the text boxes. This may be significant formatting.
932 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
933 if ( !$request->getCheck( 'wpTextbox2' ) ) {
934 // Skip this if wpTextbox2 has input, it indicates that we came
935 // from a conflict page with raw page text, not a custom form
936 // modified by subclasses
937 $textbox1 = $this->importContentFormData( $request );
938 if ( $textbox1 !== null ) {
939 $this->textbox1
= $textbox1;
943 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
945 $this->summary
= $request->getText( 'wpSummary' );
947 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
948 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
950 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
952 # Treat sectiontitle the same way as summary.
953 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
954 # currently doing double duty as both edit summary and section title. Right now this
955 # is just to allow API edits to work around this limitation, but this should be
956 # incorporated into the actual edit form when EditPage is rewritten (T20654, T28312).
957 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
958 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
960 $this->edittime
= $request->getVal( 'wpEdittime' );
961 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
962 $this->starttime
= $request->getVal( 'wpStarttime' );
964 $undidRev = $request->getInt( 'wpUndidRevision' );
966 $this->undidRev
= $undidRev;
969 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
971 if ( $this->textbox1
=== '' && !$request->getCheck( 'wpTextbox1' ) ) {
972 // wpTextbox1 field is missing, possibly due to being "too big"
973 // according to some filter rules such as Suhosin's setting for
974 // suhosin.request.max_value_length (d'oh)
975 $this->incompleteForm
= true;
977 // If we receive the last parameter of the request, we can fairly
978 // claim the POST request has not been truncated.
979 $this->incompleteForm
= !$request->getVal( 'wpUltimateParam' );
981 if ( $this->incompleteForm
) {
982 # If the form is incomplete, force to preview.
983 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
984 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
985 $this->preview
= true;
987 $this->preview
= $request->getCheck( 'wpPreview' );
988 $this->diff
= $request->getCheck( 'wpDiff' );
990 // Remember whether a save was requested, so we can indicate
991 // if we forced preview due to session failure.
992 $this->mTriedSave
= !$this->preview
;
994 if ( $this->tokenOk( $request ) ) {
995 # Some browsers will not report any submit button
996 # if the user hits enter in the comment box.
997 # The unmarked state will be assumed to be a save,
998 # if the form seems otherwise complete.
999 wfDebug( __METHOD__
. ": Passed token check.\n" );
1000 } elseif ( $this->diff
) {
1001 # Failed token check, but only requested "Show Changes".
1002 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
1004 # Page might be a hack attempt posted from
1005 # an external site. Preview instead of saving.
1006 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
1007 $this->preview
= true;
1010 $this->save
= !$this->preview
&& !$this->diff
;
1011 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
1012 $this->edittime
= null;
1015 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
1016 $this->starttime
= null;
1019 $this->recreate
= $request->getCheck( 'wpRecreate' );
1021 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
1022 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
1024 $user = $this->context
->getUser();
1025 # Don't force edit summaries when a user is editing their own user or talk page
1026 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
1027 && $this->mTitle
->getText() == $user->getName()
1029 $this->allowBlankSummary
= true;
1031 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1032 ||
!$user->getOption( 'forceeditsummary' );
1035 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1037 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1038 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1040 $changeTags = $request->getVal( 'wpChangeTags' );
1041 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1042 $this->changeTags
= [];
1044 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1048 # Not a posted form? Start with nothing.
1049 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1050 $this->textbox1
= '';
1051 $this->summary
= '';
1052 $this->sectiontitle
= '';
1053 $this->edittime
= '';
1054 $this->editRevId
= null;
1055 $this->starttime
= wfTimestampNow();
1056 $this->edit
= false;
1057 $this->preview
= false;
1058 $this->save
= false;
1059 $this->diff
= false;
1060 $this->minoredit
= false;
1061 // Watch may be overridden by request parameters
1062 $this->watchthis
= $request->getBool( 'watchthis', false );
1063 $this->recreate
= false;
1065 // When creating a new section, we can preload a section title by passing it as the
1066 // preloadtitle parameter in the URL (T15100)
1067 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1068 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1069 // Once wpSummary isn't being use for setting section titles, we should delete this.
1070 $this->summary
= $request->getVal( 'preloadtitle' );
1071 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) !== '' ) {
1072 $this->summary
= $request->getText( 'summary' );
1073 if ( $this->summary
!== '' ) {
1074 $this->hasPresetSummary
= true;
1078 if ( $request->getVal( 'minor' ) ) {
1079 $this->minoredit
= true;
1083 $this->oldid
= $request->getInt( 'oldid' );
1084 $this->parentRevId
= $request->getInt( 'parentRevId' );
1086 $this->bot
= $request->getBool( 'bot', true );
1087 $this->nosummary
= $request->getBool( 'nosummary' );
1089 // May be overridden by revision.
1090 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1091 // May be overridden by revision.
1092 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1095 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1096 } catch ( MWUnknownContentModelException
$e ) {
1097 throw new ErrorPageError(
1098 'editpage-invalidcontentmodel-title',
1099 'editpage-invalidcontentmodel-text',
1100 [ wfEscapeWikiText( $this->contentModel
) ]
1104 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1105 throw new ErrorPageError(
1106 'editpage-notsupportedcontentformat-title',
1107 'editpage-notsupportedcontentformat-text',
1109 wfEscapeWikiText( $this->contentFormat
),
1110 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1116 * @todo Check if the desired model is allowed in this namespace, and if
1117 * a transition from the page's current model to the new model is
1121 $this->editintro
= $request->getText( 'editintro',
1122 // Custom edit intro for new sections
1123 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1125 // Allow extensions to modify form data
1126 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1130 * Subpage overridable method for extracting the page content data from the
1131 * posted form to be placed in $this->textbox1, if using customized input
1132 * this method should be overridden and return the page text that will be used
1133 * for saving, preview parsing and so on...
1135 * @param WebRequest &$request
1136 * @return string|null
1138 protected function importContentFormData( &$request ) {
1139 return; // Don't do anything, EditPage already extracted wpTextbox1
1143 * Initialise form fields in the object
1144 * Called on the first invocation, e.g. when a user clicks an edit link
1145 * @return bool If the requested section is valid
1147 public function initialiseForm() {
1148 $this->edittime
= $this->page
->getTimestamp();
1149 $this->editRevId
= $this->page
->getLatest();
1151 $content = $this->getContentObject( false ); # TODO: track content object?!
1152 if ( $content === false ) {
1155 $this->textbox1
= $this->toEditText( $content );
1157 $user = $this->context
->getUser();
1158 // activate checkboxes if user wants them to be always active
1159 # Sort out the "watch" checkbox
1160 if ( $user->getOption( 'watchdefault' ) ) {
1162 $this->watchthis
= true;
1163 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1165 $this->watchthis
= true;
1166 } elseif ( $user->isWatched( $this->mTitle
) ) {
1168 $this->watchthis
= true;
1170 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1171 $this->minoredit
= true;
1173 if ( $this->textbox1
=== false ) {
1180 * @param Content|null $def_content The default value to return
1182 * @return Content|null Content on success, $def_content for invalid sections
1186 protected function getContentObject( $def_content = null ) {
1189 $user = $this->context
->getUser();
1190 $request = $this->context
->getRequest();
1191 // For message page not locally set, use the i18n message.
1192 // For other non-existent articles, use preload text if any.
1193 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1194 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1195 # If this is a system message, get the default text.
1196 $msg = $this->mTitle
->getDefaultMessageText();
1198 $content = $this->toEditContent( $msg );
1200 if ( $content === false ) {
1201 # If requested, preload some text.
1202 $preload = $request->getVal( 'preload',
1203 // Custom preload text for new sections
1204 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1205 $params = $request->getArray( 'preloadparams', [] );
1207 $content = $this->getPreloadedContent( $preload, $params );
1209 // For existing pages, get text based on "undo" or section parameters.
1210 } elseif ( $this->section
!= '' ) {
1211 // Get section edit text (returns $def_text for invalid sections)
1212 $orig = $this->getOriginalContent( $user );
1213 $content = $orig ?
$orig->getSection( $this->section
) : null;
1216 $content = $def_content;
1219 $undoafter = $request->getInt( 'undoafter' );
1220 $undo = $request->getInt( 'undo' );
1222 if ( $undo > 0 && $undoafter > 0 ) {
1223 $undorev = Revision
::newFromId( $undo );
1224 $oldrev = Revision
::newFromId( $undoafter );
1227 # Sanity check, make sure it's the right page,
1228 # the revisions exist and they were not deleted.
1229 # Otherwise, $content will be left as-is.
1230 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1231 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1232 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1234 if ( WikiPage
::hasDifferencesOutsideMainSlot( $undorev, $oldrev )
1235 ||
!$this->isSupportedContentModel( $oldrev->getContentModel() )
1237 // Hack for undo while EditPage can't handle multi-slot editing
1238 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL( [
1239 'action' => 'mcrundo',
1241 'undoafter' => $undoafter,
1245 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1247 if ( $content === false ) {
1248 # Warn the user that something went wrong
1249 $undoMsg = 'failure';
1253 if ( $undoMsg === null ) {
1254 $oldContent = $this->page
->getContent( Revision
::RAW
);
1255 $popts = ParserOptions
::newFromUserAndLang(
1256 $user, MediaWikiServices
::getInstance()->getContentLanguage() );
1257 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1258 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1259 // The undo may change content
1260 // model if its reverting the top
1261 // edit. This can result in
1262 // mismatched content model/format.
1263 $this->contentModel
= $newContent->getModel();
1264 $this->contentFormat
= $oldrev->getContentFormat();
1267 if ( $newContent->equals( $oldContent ) ) {
1268 # Tell the user that the undo results in no change,
1269 # i.e. the revisions were already undone.
1270 $undoMsg = 'nochange';
1273 # Inform the user of our success and set an automatic edit summary
1274 $undoMsg = 'success';
1276 # If we just undid one rev, use an autosummary
1277 $firstrev = $oldrev->getNext();
1278 if ( $firstrev && $firstrev->getId() == $undo ) {
1279 $userText = $undorev->getUserText();
1280 if ( $userText === '' ) {
1281 $undoSummary = $this->context
->msg(
1282 'undo-summary-username-hidden',
1284 )->inContentLanguage()->text();
1286 $undoSummary = $this->context
->msg(
1290 )->inContentLanguage()->text();
1292 if ( $this->summary
=== '' ) {
1293 $this->summary
= $undoSummary;
1295 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1296 ->inContentLanguage()->text() . $this->summary
;
1298 $this->undidRev
= $undo;
1300 $this->formtype
= 'diff';
1304 // Failed basic sanity checks.
1305 // Older revisions may have been removed since the link
1306 // was created, or we may simply have got bogus input.
1310 $out = $this->context
->getOutput();
1311 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1313 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1314 $this->editFormPageTop
.= Html
::rawElement(
1315 'div', [ 'class' => $class ],
1316 $out->parseAsInterface(
1317 $this->context
->msg( 'undo-' . $undoMsg )->plain()
1322 if ( $content === false ) {
1323 // Hack for restoring old revisions while EditPage
1324 // can't handle multi-slot editing.
1326 $curRevision = $this->page
->getRevision();
1327 $oldRevision = $this->mArticle
->getRevisionFetched();
1331 && $curRevision->getId() !== $oldRevision->getId()
1332 && ( WikiPage
::hasDifferencesOutsideMainSlot( $oldRevision, $curRevision )
1333 ||
!$this->isSupportedContentModel( $oldRevision->getContentModel() ) )
1335 $this->context
->getOutput()->redirect(
1336 $this->mTitle
->getFullURL(
1338 'action' => 'mcrrestore',
1339 'restore' => $oldRevision->getId(),
1348 if ( $content === false ) {
1349 $content = $this->getOriginalContent( $user );
1357 * Get the content of the wanted revision, without section extraction.
1359 * The result of this function can be used to compare user's input with
1360 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1361 * to the original text of the edit.
1363 * This differs from Article::getContent() that when a missing revision is
1364 * encountered the result will be null and not the
1365 * 'missing-revision' message.
1368 * @param User $user The user to get the revision for
1369 * @return Content|null
1371 private function getOriginalContent( User
$user ) {
1372 if ( $this->section
== 'new' ) {
1373 return $this->getCurrentContent();
1375 $revision = $this->mArticle
->getRevisionFetched();
1376 if ( $revision === null ) {
1377 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1378 return $handler->makeEmptyContent();
1380 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1385 * Get the edit's parent revision ID
1387 * The "parent" revision is the ancestor that should be recorded in this
1388 * page's revision history. It is either the revision ID of the in-memory
1389 * article content, or in the case of a 3-way merge in order to rebase
1390 * across a recoverable edit conflict, the ID of the newer revision to
1391 * which we have rebased this page.
1394 * @return int Revision ID
1396 public function getParentRevId() {
1397 if ( $this->parentRevId
) {
1398 return $this->parentRevId
;
1400 return $this->mArticle
->getRevIdFetched();
1405 * Get the current content of the page. This is basically similar to
1406 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1407 * content object is returned instead of null.
1412 protected function getCurrentContent() {
1413 $rev = $this->page
->getRevision();
1414 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1416 if ( $content === false ||
$content === null ) {
1417 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1418 return $handler->makeEmptyContent();
1419 } elseif ( !$this->undidRev
) {
1420 // Content models should always be the same since we error
1421 // out if they are different before this point (in ->edit()).
1422 // The exception being, during an undo, the current revision might
1423 // differ from the prior revision.
1424 $logger = LoggerFactory
::getInstance( 'editpage' );
1425 if ( $this->contentModel
!== $rev->getContentModel() ) {
1426 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1427 'prev' => $this->contentModel
,
1428 'new' => $rev->getContentModel(),
1429 'title' => $this->getTitle()->getPrefixedDBkey(),
1430 'method' => __METHOD__
1432 $this->contentModel
= $rev->getContentModel();
1435 // Given that the content models should match, the current selected
1436 // format should be supported.
1437 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1438 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1440 'prev' => $this->contentFormat
,
1441 'new' => $rev->getContentFormat(),
1442 'title' => $this->getTitle()->getPrefixedDBkey(),
1443 'method' => __METHOD__
1445 $this->contentFormat
= $rev->getContentFormat();
1452 * Use this method before edit() to preload some content into the edit box
1454 * @param Content $content
1458 public function setPreloadedContent( Content
$content ) {
1459 $this->mPreloadContent
= $content;
1463 * Get the contents to be preloaded into the box, either set by
1464 * an earlier setPreloadText() or by loading the given page.
1466 * @param string $preload Representing the title to preload from.
1467 * @param array $params Parameters to use (interface-message style) in the preloaded text
1473 protected function getPreloadedContent( $preload, $params = [] ) {
1474 if ( !empty( $this->mPreloadContent
) ) {
1475 return $this->mPreloadContent
;
1478 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1480 if ( $preload === '' ) {
1481 return $handler->makeEmptyContent();
1484 $user = $this->context
->getUser();
1485 $title = Title
::newFromText( $preload );
1486 # Check for existence to avoid getting MediaWiki:Noarticletext
1487 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1488 // TODO: somehow show a warning to the user!
1489 return $handler->makeEmptyContent();
1492 $page = WikiPage
::factory( $title );
1493 if ( $page->isRedirect() ) {
1494 $title = $page->getRedirectTarget();
1496 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1497 // TODO: somehow show a warning to the user!
1498 return $handler->makeEmptyContent();
1500 $page = WikiPage
::factory( $title );
1503 $parserOptions = ParserOptions
::newFromUser( $user );
1504 $content = $page->getContent( Revision
::RAW
);
1507 // TODO: somehow show a warning to the user!
1508 return $handler->makeEmptyContent();
1511 if ( $content->getModel() !== $handler->getModelID() ) {
1512 $converted = $content->convert( $handler->getModelID() );
1514 if ( !$converted ) {
1515 // TODO: somehow show a warning to the user!
1516 wfDebug( "Attempt to preload incompatible content: " .
1517 "can't convert " . $content->getModel() .
1518 " to " . $handler->getModelID() );
1520 return $handler->makeEmptyContent();
1523 $content = $converted;
1526 return $content->preloadTransform( $title, $parserOptions, $params );
1530 * Make sure the form isn't faking a user's credentials.
1532 * @param WebRequest &$request
1536 public function tokenOk( &$request ) {
1537 $token = $request->getVal( 'wpEditToken' );
1538 $user = $this->context
->getUser();
1539 $this->mTokenOk
= $user->matchEditToken( $token );
1540 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1541 return $this->mTokenOk
;
1545 * Sets post-edit cookie indicating the user just saved a particular revision.
1547 * This uses a temporary cookie for each revision ID so separate saves will never
1548 * interfere with each other.
1550 * Article::view deletes the cookie on server-side after the redirect and
1551 * converts the value to the global JavaScript variable wgPostEdit.
1553 * If the variable were set on the server, it would be cached, which is unwanted
1554 * since the post-edit state should only apply to the load right after the save.
1556 * @param int $statusValue The status value (to check for new article status)
1558 protected function setPostEditCookie( $statusValue ) {
1559 $revisionId = $this->page
->getLatest();
1560 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1563 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1565 } elseif ( $this->oldid
) {
1569 $response = $this->context
->getRequest()->response();
1570 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1574 * Attempt submission
1575 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1576 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1577 * @return Status The resulting status object.
1579 public function attemptSave( &$resultDetails = false ) {
1580 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1581 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1582 // This is needed since PageUpdater no longer checks these rights!
1584 // Allow bots to exempt some edits from bot flagging
1585 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1586 $status = $this->internalAttemptSave( $resultDetails, $bot );
1588 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1594 * Log when a page was successfully saved after the edit conflict view
1596 private function incrementResolvedConflicts() {
1597 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1601 $this->getEditConflictHelper()->incrementResolvedStats();
1605 * Handle status, such as after attempt save
1607 * @param Status $status
1608 * @param array|bool $resultDetails
1610 * @throws ErrorPageError
1611 * @return bool False, if output is done, true if rest of the form should be displayed
1613 private function handleStatus( Status
$status, $resultDetails ) {
1615 * @todo FIXME: once the interface for internalAttemptSave() is made
1616 * nicer, this should use the message in $status
1618 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1619 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1621 $this->incrementResolvedConflicts();
1623 $this->didSave
= true;
1624 if ( !$resultDetails['nullEdit'] ) {
1625 $this->setPostEditCookie( $status->value
);
1629 $out = $this->context
->getOutput();
1631 // "wpExtraQueryRedirect" is a hidden input to modify
1632 // after save URL and is not used by actual edit form
1633 $request = $this->context
->getRequest();
1634 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1636 switch ( $status->value
) {
1637 case self
::AS_HOOK_ERROR_EXPECTED
:
1638 case self
::AS_CONTENT_TOO_BIG
:
1639 case self
::AS_ARTICLE_WAS_DELETED
:
1640 case self
::AS_CONFLICT_DETECTED
:
1641 case self
::AS_SUMMARY_NEEDED
:
1642 case self
::AS_TEXTBOX_EMPTY
:
1643 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1645 case self
::AS_BLANK_ARTICLE
:
1646 case self
::AS_SELF_REDIRECT
:
1649 case self
::AS_HOOK_ERROR
:
1652 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1653 case self
::AS_PARSE_ERROR
:
1654 case self
::AS_UNICODE_NOT_SUPPORTED
:
1655 $out->wrapWikiTextAsInterface( 'error', $status->getWikiText() );
1658 case self
::AS_SUCCESS_NEW_ARTICLE
:
1659 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1660 if ( $extraQueryRedirect ) {
1661 if ( $query !== '' ) {
1664 $query .= $extraQueryRedirect;
1666 $anchor = $resultDetails['sectionanchor'] ??
'';
1667 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1670 case self
::AS_SUCCESS_UPDATE
:
1672 $sectionanchor = $resultDetails['sectionanchor'];
1674 // Give extensions a chance to modify URL query on update
1676 'ArticleUpdateBeforeRedirect',
1677 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1680 if ( $resultDetails['redirect'] ) {
1681 if ( $extraQuery !== '' ) {
1682 $extraQuery = '&' . $extraQuery;
1684 $extraQuery = 'redirect=no' . $extraQuery;
1686 if ( $extraQueryRedirect ) {
1687 if ( $extraQuery !== '' ) {
1690 $extraQuery .= $extraQueryRedirect;
1693 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1696 case self
::AS_SPAM_ERROR
:
1697 $this->spamPageWithContent( $resultDetails['spam'] );
1700 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1701 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1703 case self
::AS_IMAGE_REDIRECT_ANON
:
1704 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1705 throw new PermissionsError( 'upload' );
1707 case self
::AS_READ_ONLY_PAGE_ANON
:
1708 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1709 throw new PermissionsError( 'edit' );
1711 case self
::AS_READ_ONLY_PAGE
:
1712 throw new ReadOnlyError
;
1714 case self
::AS_RATE_LIMITED
:
1715 throw new ThrottledError();
1717 case self
::AS_NO_CREATE_PERMISSION
:
1718 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1719 throw new PermissionsError( $permission );
1721 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1722 throw new PermissionsError( 'editcontentmodel' );
1725 // We don't recognize $status->value. The only way that can happen
1726 // is if an extension hook aborted from inside ArticleSave.
1727 // Render the status object into $this->hookError
1728 // FIXME this sucks, we should just use the Status object throughout
1729 $this->hookError
= '<div class="error">' . "\n" . $status->getWikiText() .
1736 * Run hooks that can filter edits just before they get saved.
1738 * @param Content $content The Content to filter.
1739 * @param Status $status For reporting the outcome to the caller
1740 * @param User $user The user performing the edit
1744 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1745 // Run old style post-section-merge edit filter
1746 if ( $this->hookError
!= '' ) {
1747 # ...or the hook could be expecting us to produce an error
1748 $status->fatal( 'hookaborted' );
1749 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1753 // Run new style post-section-merge edit filter
1754 if ( !Hooks
::run( 'EditFilterMergedContent',
1755 [ $this->context
, $content, $status, $this->summary
,
1756 $user, $this->minoredit
] )
1758 # Error messages etc. could be handled within the hook...
1759 if ( $status->isGood() ) {
1760 $status->fatal( 'hookaborted' );
1761 // Not setting $this->hookError here is a hack to allow the hook
1762 // to cause a return to the edit page without $this->hookError
1763 // being set. This is used by ConfirmEdit to display a captcha
1764 // without any error message cruft.
1766 $this->hookError
= $this->formatStatusErrors( $status );
1768 // Use the existing $status->value if the hook set it
1769 if ( !$status->value
) {
1770 $status->value
= self
::AS_HOOK_ERROR
;
1773 } elseif ( !$status->isOK() ) {
1774 # ...or the hook could be expecting us to produce an error
1775 // FIXME this sucks, we should just use the Status object throughout
1776 $this->hookError
= $this->formatStatusErrors( $status );
1777 $status->fatal( 'hookaborted' );
1778 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1786 * Wrap status errors in an errorbox for increased visibility
1788 * @param Status $status
1789 * @return string Wikitext
1791 private function formatStatusErrors( Status
$status ) {
1792 $errmsg = $status->getWikiText(
1795 $this->context
->getLanguage()
1798 <div class="errorbox">
1806 * Return the summary to be used for a new section.
1808 * @param string $sectionanchor Set to the section anchor text
1811 private function newSectionSummary( &$sectionanchor = null ) {
1812 if ( $this->sectiontitle
!== '' ) {
1813 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1814 // If no edit summary was specified, create one automatically from the section
1815 // title and have it link to the new section. Otherwise, respect the summary as
1817 if ( $this->summary
=== '' ) {
1818 $cleanSectionTitle = MediaWikiServices
::getInstance()->getParser()
1819 ->stripSectionName( $this->sectiontitle
);
1820 return $this->context
->msg( 'newsectionsummary' )
1821 ->plaintextParams( $cleanSectionTitle )->inContentLanguage()->text();
1823 } elseif ( $this->summary
!== '' ) {
1824 $sectionanchor = $this->guessSectionName( $this->summary
);
1825 # This is a new section, so create a link to the new section
1826 # in the revision summary.
1827 $cleanSummary = MediaWikiServices
::getInstance()->getParser()
1828 ->stripSectionName( $this->summary
);
1829 return $this->context
->msg( 'newsectionsummary' )
1830 ->plaintextParams( $cleanSummary )->inContentLanguage()->text();
1832 return $this->summary
;
1836 * Attempt submission (no UI)
1838 * @param array &$result Array to add statuses to, currently with the
1840 * - spam (string): Spam string from content if any spam is detected by
1842 * - sectionanchor (string): Section anchor for a section save.
1843 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1845 * - redirect (bool): Set if doEditContent is OK. True if resulting
1846 * revision is a redirect.
1847 * @param bool $bot True if edit is being made under the bot right.
1849 * @return Status Status object, possibly with a message, but always with
1850 * one of the AS_* constants in $status->value,
1852 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1853 * various error display idiosyncrasies. There are also lots of cases
1854 * where error metadata is set in the object and retrieved later instead
1855 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1856 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1859 public function internalAttemptSave( &$result, $bot = false ) {
1860 $status = Status
::newGood();
1861 $user = $this->context
->getUser();
1863 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1864 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1865 $status->fatal( 'hookaborted' );
1866 $status->value
= self
::AS_HOOK_ERROR
;
1870 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1871 $status->fatal( 'unicode-support-fail' );
1872 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1876 $request = $this->context
->getRequest();
1877 $spam = $request->getText( 'wpAntispam' );
1878 if ( $spam !== '' ) {
1883 $this->mTitle
->getPrefixedText() .
1884 '" submitted bogus field "' .
1888 $status->fatal( 'spamprotectionmatch', false );
1889 $status->value
= self
::AS_SPAM_ERROR
;
1894 # Construct Content object
1895 $textbox_content = $this->toEditContent( $this->textbox1
);
1896 } catch ( MWContentSerializationException
$ex ) {
1898 'content-failed-to-parse',
1899 $this->contentModel
,
1900 $this->contentFormat
,
1903 $status->value
= self
::AS_PARSE_ERROR
;
1907 # Check image redirect
1908 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1909 $textbox_content->isRedirect() &&
1910 !$user->isAllowed( 'upload' )
1912 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1913 $status->setResult( false, $code );
1919 $match = self
::matchSummarySpamRegex( $this->summary
);
1920 if ( $match === false && $this->section
== 'new' ) {
1921 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1922 # regular summaries, it is added to the actual wikitext.
1923 if ( $this->sectiontitle
!== '' ) {
1924 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1925 $match = self
::matchSpamRegex( $this->sectiontitle
);
1927 # This branch is taken when the "Add Topic" user interface is used, or the API
1928 # is used with the 'summary' parameter.
1929 $match = self
::matchSpamRegex( $this->summary
);
1932 if ( $match === false ) {
1933 $match = self
::matchSpamRegex( $this->textbox1
);
1935 if ( $match !== false ) {
1936 $result['spam'] = $match;
1937 $ip = $request->getIP();
1938 $pdbk = $this->mTitle
->getPrefixedDBkey();
1939 $match = str_replace( "\n", '', $match );
1940 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1941 $status->fatal( 'spamprotectionmatch', $match );
1942 $status->value
= self
::AS_SPAM_ERROR
;
1947 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1949 # Error messages etc. could be handled within the hook...
1950 $status->fatal( 'hookaborted' );
1951 $status->value
= self
::AS_HOOK_ERROR
;
1953 } elseif ( $this->hookError
!= '' ) {
1954 # ...or the hook could be expecting us to produce an error
1955 $status->fatal( 'hookaborted' );
1956 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1960 if ( $user->isBlockedFrom( $this->mTitle
) ) {
1961 // Auto-block user's IP if the account was "hard" blocked
1962 if ( !wfReadOnly() ) {
1963 $user->spreadAnyEditBlock();
1965 # Check block state against master, thus 'false'.
1966 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1970 $this->contentLength
= strlen( $this->textbox1
);
1971 $config = $this->context
->getConfig();
1972 $maxArticleSize = $config->get( 'MaxArticleSize' );
1973 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1974 // Error will be displayed by showEditForm()
1975 $this->tooBig
= true;
1976 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1980 if ( !$user->isAllowed( 'edit' ) ) {
1981 if ( $user->isAnon() ) {
1982 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1985 $status->fatal( 'readonlytext' );
1986 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1991 $changingContentModel = false;
1992 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1993 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1994 $status->fatal( 'editpage-cannot-use-custom-model' );
1995 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1997 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1998 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2001 // Make sure the user can edit the page under the new content model too
2002 $titleWithNewContentModel = clone $this->mTitle
;
2003 $titleWithNewContentModel->setContentModel( $this->contentModel
);
2004 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
2005 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
2007 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2011 $changingContentModel = true;
2012 $oldContentModel = $this->mTitle
->getContentModel();
2015 if ( $this->changeTags
) {
2016 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
2017 $this->changeTags
, $user );
2018 if ( !$changeTagsStatus->isOK() ) {
2019 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
2020 return $changeTagsStatus;
2024 if ( wfReadOnly() ) {
2025 $status->fatal( 'readonlytext' );
2026 $status->value
= self
::AS_READ_ONLY_PAGE
;
2029 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
2030 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
2032 $status->fatal( 'actionthrottledtext' );
2033 $status->value
= self
::AS_RATE_LIMITED
;
2037 # If the article has been deleted while editing, don't save it without
2039 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
2040 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
2044 # Load the page data from the master. If anything changes in the meantime,
2045 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
2046 $this->page
->loadPageData( 'fromdbmaster' );
2047 $new = !$this->page
->exists();
2050 // Late check for create permission, just in case *PARANOIA*
2051 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
2052 $status->fatal( 'nocreatetext' );
2053 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
2054 wfDebug( __METHOD__
. ": no create permission\n" );
2058 // Don't save a new page if it's blank or if it's a MediaWiki:
2059 // message with content equivalent to default (allow empty pages
2060 // in this case to disable messages, see T52124)
2061 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2062 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
2063 $defaultText = $defaultMessageText;
2068 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
2069 $this->blankArticle
= true;
2070 $status->fatal( 'blankarticle' );
2071 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
2075 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2079 $content = $textbox_content;
2081 $result['sectionanchor'] = '';
2082 if ( $this->section
== 'new' ) {
2083 if ( $this->sectiontitle
!== '' ) {
2084 // Insert the section title above the content.
2085 $content = $content->addSectionHeader( $this->sectiontitle
);
2086 } elseif ( $this->summary
!== '' ) {
2087 // Insert the section title above the content.
2088 $content = $content->addSectionHeader( $this->summary
);
2090 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2093 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2097 # Article exists. Check for edit conflict.
2099 $this->page
->clear(); # Force reload of dates, etc.
2100 $timestamp = $this->page
->getTimestamp();
2101 $latest = $this->page
->getLatest();
2103 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2105 // An edit conflict is detected if the current revision is different from the
2106 // revision that was current when editing was initiated on the client.
2107 // This is checked based on the timestamp and revision ID.
2108 // TODO: the timestamp based check can probably go away now.
2109 if ( $timestamp != $this->edittime
2110 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2112 $this->isConflict
= true;
2113 if ( $this->section
== 'new' ) {
2114 if ( $this->page
->getUserText() == $user->getName() &&
2115 $this->page
->getComment() == $this->newSectionSummary()
2117 // Probably a duplicate submission of a new comment.
2118 // This can happen when CDN resends a request after
2119 // a timeout but the first one actually went through.
2121 . ": duplicate new section submission; trigger edit conflict!\n" );
2123 // New comment; suppress conflict.
2124 $this->isConflict
= false;
2125 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2127 } elseif ( $this->section
== ''
2128 && Revision
::userWasLastToEdit(
2129 DB_MASTER
, $this->mTitle
->getArticleID(),
2130 $user->getId(), $this->edittime
2133 # Suppress edit conflict with self, except for section edits where merging is required.
2134 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2135 $this->isConflict
= false;
2139 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2140 if ( $this->sectiontitle
!== '' ) {
2141 $sectionTitle = $this->sectiontitle
;
2143 $sectionTitle = $this->summary
;
2148 if ( $this->isConflict
) {
2150 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2151 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2152 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2153 // ...or disable section editing for non-current revisions (not exposed anyway).
2154 if ( $this->editRevId
!== null ) {
2155 $content = $this->page
->replaceSectionAtRev(
2162 $content = $this->page
->replaceSectionContent(
2170 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2171 $content = $this->page
->replaceSectionContent(
2178 if ( is_null( $content ) ) {
2179 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2180 $this->isConflict
= true;
2181 $content = $textbox_content; // do not try to merge here!
2182 } elseif ( $this->isConflict
) {
2184 if ( $this->mergeChangesIntoContent( $content ) ) {
2185 // Successful merge! Maybe we should tell the user the good news?
2186 $this->isConflict
= false;
2187 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2189 $this->section
= '';
2190 $this->textbox1
= ContentHandler
::getContentText( $content );
2191 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2195 if ( $this->isConflict
) {
2196 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2200 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2204 if ( $this->section
== 'new' ) {
2205 // Handle the user preference to force summaries here
2206 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2207 $this->missingSummary
= true;
2208 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2209 $status->value
= self
::AS_SUMMARY_NEEDED
;
2213 // Do not allow the user to post an empty comment
2214 if ( $this->textbox1
== '' ) {
2215 $this->missingComment
= true;
2216 $status->fatal( 'missingcommenttext' );
2217 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2220 } elseif ( !$this->allowBlankSummary
2221 && !$content->equals( $this->getOriginalContent( $user ) )
2222 && !$content->isRedirect()
2223 && md5( $this->summary
) == $this->autoSumm
2225 $this->missingSummary
= true;
2226 $status->fatal( 'missingsummary' );
2227 $status->value
= self
::AS_SUMMARY_NEEDED
;
2232 $sectionanchor = '';
2233 if ( $this->section
== 'new' ) {
2234 $this->summary
= $this->newSectionSummary( $sectionanchor );
2235 } elseif ( $this->section
!= '' ) {
2236 # Try to get a section anchor from the section source, redirect
2237 # to edited section if header found.
2238 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2239 # for duplicate heading checking and maybe parsing.
2240 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2241 # We can't deal with anchors, includes, html etc in the header for now,
2242 # headline would need to be parsed to improve this.
2243 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2244 $sectionanchor = $this->guessSectionName( $matches[2] );
2247 $result['sectionanchor'] = $sectionanchor;
2249 // Save errors may fall down to the edit form, but we've now
2250 // merged the section into full text. Clear the section field
2251 // so that later submission of conflict forms won't try to
2252 // replace that into a duplicated mess.
2253 $this->textbox1
= $this->toEditText( $content );
2254 $this->section
= '';
2256 $status->value
= self
::AS_SUCCESS_UPDATE
;
2259 if ( !$this->allowSelfRedirect
2260 && $content->isRedirect()
2261 && $content->getRedirectTarget()->equals( $this->getTitle() )
2263 // If the page already redirects to itself, don't warn.
2264 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2265 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2266 $this->selfRedirect
= true;
2267 $status->fatal( 'selfredirect' );
2268 $status->value
= self
::AS_SELF_REDIRECT
;
2273 // Check for length errors again now that the section is merged in
2274 $this->contentLength
= strlen( $this->toEditText( $content ) );
2275 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2276 $this->tooBig
= true;
2277 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2281 $flags = EDIT_AUTOSUMMARY |
2282 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2283 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2284 ( $bot ? EDIT_FORCE_BOT
: 0 );
2286 $doEditStatus = $this->page
->doEditContent(
2292 $content->getDefaultFormat(),
2297 if ( !$doEditStatus->isOK() ) {
2298 // Failure from doEdit()
2299 // Show the edit conflict page for certain recognized errors from doEdit(),
2300 // but don't show it for errors from extension hooks
2301 $errors = $doEditStatus->getErrorsArray();
2302 if ( in_array( $errors[0][0],
2303 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2305 $this->isConflict
= true;
2306 // Destroys data doEdit() put in $status->value but who cares
2307 $doEditStatus->value
= self
::AS_END
;
2309 return $doEditStatus;
2312 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2313 if ( $result['nullEdit'] ) {
2314 // We don't know if it was a null edit until now, so increment here
2315 $user->pingLimiter( 'linkpurge' );
2317 $result['redirect'] = $content->isRedirect();
2319 $this->updateWatchlist();
2321 // If the content model changed, add a log entry
2322 if ( $changingContentModel ) {
2323 $this->addContentModelChangeLogEntry(
2325 $new ?
false : $oldContentModel,
2326 $this->contentModel
,
2336 * @param string|false $oldModel false if the page is being newly created
2337 * @param string $newModel
2338 * @param string $reason
2340 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2341 $new = $oldModel === false;
2342 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2343 $log->setPerformer( $user );
2344 $log->setTarget( $this->mTitle
);
2345 $log->setComment( $reason );
2346 $log->setParameters( [
2347 '4::oldmodel' => $oldModel,
2348 '5::newmodel' => $newModel
2350 $logid = $log->insert();
2351 $log->publish( $logid );
2355 * Register the change of watch status
2357 protected function updateWatchlist() {
2358 $user = $this->context
->getUser();
2359 if ( !$user->isLoggedIn() ) {
2363 $title = $this->mTitle
;
2364 $watch = $this->watchthis
;
2365 // Do this in its own transaction to reduce contention...
2366 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2367 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2368 return; // nothing to change
2370 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2375 * Attempts to do 3-way merge of edit content with a base revision
2376 * and current content, in case of edit conflict, in whichever way appropriate
2377 * for the content type.
2381 * @param Content $editContent
2385 private function mergeChangesIntoContent( &$editContent ) {
2386 $db = wfGetDB( DB_MASTER
);
2388 // This is the revision that was current at the time editing was initiated on the client,
2389 // even if the edit was based on an old revision.
2390 $baseRevision = $this->getBaseRevision();
2391 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2393 if ( is_null( $baseContent ) ) {
2397 // The current state, we want to merge updates into it
2398 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2399 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2401 if ( is_null( $currentContent ) ) {
2405 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2407 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2410 $editContent = $result;
2411 // Update parentRevId to what we just merged.
2412 $this->parentRevId
= $currentRevision->getId();
2420 * Returns the revision that was current at the time editing was initiated on the client,
2421 * even if the edit was based on an old revision.
2423 * @warning this method is very poorly named. If the user opened the form with ?oldid=X,
2424 * one might think of X as the "base revision", which is NOT what this returns,
2425 * see oldid for that. One might further assume that this corresponds to the $baseRevId
2426 * parameter of WikiPage::doEditContent, which is not the case either.
2427 * getExpectedParentRevision() would perhaps be a better name.
2429 * @return Revision|null Current version when editing was initiated on the client
2431 public function getBaseRevision() {
2432 if ( !$this->mBaseRevision
) {
2433 $db = wfGetDB( DB_MASTER
);
2434 $this->mBaseRevision
= $this->editRevId
2435 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2436 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2438 return $this->mBaseRevision
;
2442 * Check given input text against $wgSpamRegex, and return the text of the first match.
2444 * @param string $text
2446 * @return string|bool Matching string or false
2448 public static function matchSpamRegex( $text ) {
2449 global $wgSpamRegex;
2450 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2451 $regexes = (array)$wgSpamRegex;
2452 return self
::matchSpamRegexInternal( $text, $regexes );
2456 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2458 * @param string $text
2460 * @return string|bool Matching string or false
2462 public static function matchSummarySpamRegex( $text ) {
2463 global $wgSummarySpamRegex;
2464 $regexes = (array)$wgSummarySpamRegex;
2465 return self
::matchSpamRegexInternal( $text, $regexes );
2469 * @param string $text
2470 * @param array $regexes
2471 * @return bool|string
2473 protected static function matchSpamRegexInternal( $text, $regexes ) {
2474 foreach ( $regexes as $regex ) {
2476 if ( preg_match( $regex, $text, $matches ) ) {
2483 public function setHeaders() {
2484 $out = $this->context
->getOutput();
2486 $out->addModules( 'mediawiki.action.edit' );
2487 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2488 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2490 $user = $this->context
->getUser();
2492 if ( $user->getOption( 'uselivepreview' ) ) {
2493 $out->addModules( 'mediawiki.action.edit.preview' );
2496 if ( $user->getOption( 'useeditwarning' ) ) {
2497 $out->addModules( 'mediawiki.action.edit.editWarning' );
2500 # Enabled article-related sidebar, toplinks, etc.
2501 $out->setArticleRelated( true );
2503 $contextTitle = $this->getContextTitle();
2504 if ( $this->isConflict
) {
2505 $msg = 'editconflict';
2506 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2507 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2509 $msg = $contextTitle->exists()
2510 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2511 && $contextTitle->getDefaultMessageText() !== false
2517 # Use the title defined by DISPLAYTITLE magic word when present
2518 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2519 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2520 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2521 if ( $displayTitle === false ) {
2522 $displayTitle = $contextTitle->getPrefixedText();
2524 $out->setDisplayTitle( $displayTitle );
2526 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2528 $config = $this->context
->getConfig();
2530 # Transmit the name of the message to JavaScript for live preview
2531 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2532 $out->addJsConfigVars( [
2533 'wgEditMessage' => $msg,
2534 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2537 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2539 $out->addJsConfigVars(
2540 'wgEditSubmitButtonLabelPublish',
2541 $config->get( 'EditSubmitButtonLabelPublish' )
2546 * Show all applicable editing introductions
2548 protected function showIntro() {
2549 if ( $this->suppressIntro
) {
2553 $out = $this->context
->getOutput();
2554 $namespace = $this->mTitle
->getNamespace();
2556 if ( $namespace == NS_MEDIAWIKI
) {
2557 # Show a warning if editing an interface message
2558 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2559 # If this is a default message (but not css, json, or js),
2560 # show a hint that it is translatable on translatewiki.net
2562 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2563 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2564 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2566 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2567 if ( $defaultMessageText !== false ) {
2568 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2569 'translateinterface' );
2572 } elseif ( $namespace == NS_FILE
) {
2573 # Show a hint to shared repo
2574 $file = wfFindFile( $this->mTitle
);
2575 if ( $file && !$file->isLocal() ) {
2576 $descUrl = $file->getDescriptionUrl();
2577 # there must be a description url to show a hint to shared repo
2579 if ( !$this->mTitle
->exists() ) {
2580 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2581 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2584 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2585 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2592 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2593 # Show log extract when the user is currently blocked
2594 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2595 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2596 $user = User
::newFromName( $username, false /* allow IP users */ );
2597 $ip = User
::isIP( $username );
2598 $block = Block
::newFromTarget( $user, $user );
2599 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2600 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2601 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2603 !is_null( $block ) &&
2604 $block->getType() != Block
::TYPE_AUTO
&&
2605 ( $block->isSitewide() ||
$user->isBlockedFrom( $this->mTitle
) )
2607 // Show log extract if the user is sitewide blocked or is partially
2608 // blocked and not allowed to edit their user page or user talk page
2609 LogEventsList
::showLogExtract(
2612 MediaWikiServices
::getInstance()->getNamespaceInfo()->
2613 getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2617 'showIfEmpty' => false,
2619 'blocked-notice-logextract',
2620 $user->getName() # Support GENDER in notice
2626 # Try to add a custom edit intro, or use the standard one if this is not possible.
2627 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2628 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2629 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2631 if ( $this->context
->getUser()->isLoggedIn() ) {
2633 // Suppress the external link icon, consider the help url an internal one
2634 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2642 // Suppress the external link icon, consider the help url an internal one
2643 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2645 'newarticletextanon',
2651 # Give a notice if the user is editing a deleted/moved page...
2652 if ( !$this->mTitle
->exists() ) {
2653 $dbr = wfGetDB( DB_REPLICA
);
2655 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2659 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2660 'showIfEmpty' => false,
2661 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2668 * Attempt to show a custom editing introduction, if supplied
2672 protected function showCustomIntro() {
2673 if ( $this->editintro
) {
2674 $title = Title
::newFromText( $this->editintro
);
2675 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2676 // Added using template syntax, to take <noinclude>'s into account.
2677 $this->context
->getOutput()->addWikiTextAsContent(
2678 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2689 * Gets an editable textual representation of $content.
2690 * The textual representation can be turned by into a Content object by the
2691 * toEditContent() method.
2693 * If $content is null or false or a string, $content is returned unchanged.
2695 * If the given Content object is not of a type that can be edited using
2696 * the text base EditPage, an exception will be raised. Set
2697 * $this->allowNonTextContent to true to allow editing of non-textual
2700 * @param Content|null|bool|string $content
2701 * @return string The editable text form of the content.
2703 * @throws MWException If $content is not an instance of TextContent and
2704 * $this->allowNonTextContent is not true.
2706 protected function toEditText( $content ) {
2707 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2711 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2712 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2715 return $content->serialize( $this->contentFormat
);
2719 * Turns the given text into a Content object by unserializing it.
2721 * If the resulting Content object is not of a type that can be edited using
2722 * the text base EditPage, an exception will be raised. Set
2723 * $this->allowNonTextContent to true to allow editing of non-textual
2726 * @param string|null|bool $text Text to unserialize
2727 * @return Content|bool|null The content object created from $text. If $text was false
2728 * or null, then false or null will be returned instead.
2730 * @throws MWException If unserializing the text results in a Content
2731 * object that is not an instance of TextContent and
2732 * $this->allowNonTextContent is not true.
2734 protected function toEditContent( $text ) {
2735 if ( $text === false ||
$text === null ) {
2739 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2740 $this->contentModel
, $this->contentFormat
);
2742 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2743 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2750 * Send the edit form and related headers to OutputPage
2751 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2752 * during form output near the top, for captchas and the like.
2754 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2755 * use the EditPage::showEditForm:fields hook instead.
2757 public function showEditForm( $formCallback = null ) {
2758 # need to parse the preview early so that we know which templates are used,
2759 # otherwise users with "show preview after edit box" will get a blank list
2760 # we parse this near the beginning so that setHeaders can do the title
2761 # setting work instead of leaving it in getPreviewText
2762 $previewOutput = '';
2763 if ( $this->formtype
== 'preview' ) {
2764 $previewOutput = $this->getPreviewText();
2767 $out = $this->context
->getOutput();
2769 // Avoid PHP 7.1 warning of passing $this by reference
2771 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2773 $this->setHeaders();
2775 $this->addTalkPageText();
2776 $this->addEditNotices();
2778 if ( !$this->isConflict
&&
2779 $this->section
!= '' &&
2780 !$this->isSectionEditSupported() ) {
2781 // We use $this->section to much before this and getVal('wgSection') directly in other places
2782 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2783 // Someone is welcome to try refactoring though
2784 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2788 $this->showHeader();
2790 $out->addHTML( $this->editFormPageTop
);
2792 $user = $this->context
->getUser();
2793 if ( $user->getOption( 'previewontop' ) ) {
2794 $this->displayPreviewArea( $previewOutput, true );
2797 $out->addHTML( $this->editFormTextTop
);
2799 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
!== 'save' ) {
2800 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2801 'deletedwhileediting' );
2804 // @todo add EditForm plugin interface and use it here!
2805 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2806 $out->addHTML( Html
::openElement(
2809 'class' => 'mw-editform',
2810 'id' => self
::EDITFORM_ID
,
2811 'name' => self
::EDITFORM_ID
,
2813 'action' => $this->getActionURL( $this->getContextTitle() ),
2814 'enctype' => 'multipart/form-data'
2818 if ( is_callable( $formCallback ) ) {
2819 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2820 call_user_func_array( $formCallback, [ &$out ] );
2823 // Add a check for Unicode support
2824 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2826 // Add an empty field to trip up spambots
2828 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2831 [ 'for' => 'wpAntispam' ],
2832 $this->context
->msg( 'simpleantispam-label' )->parse()
2838 'name' => 'wpAntispam',
2839 'id' => 'wpAntispam',
2843 . Xml
::closeElement( 'div' )
2846 // Avoid PHP 7.1 warning of passing $this by reference
2848 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2850 // Put these up at the top to ensure they aren't lost on early form submission
2851 $this->showFormBeforeText();
2853 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2854 $username = $this->lastDelete
->user_name
;
2855 $comment = CommentStore
::getStore()
2856 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2858 // It is better to not parse the comment at all than to have templates expanded in the middle
2859 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2860 $key = $comment === ''
2861 ?
'confirmrecreate-noreason'
2862 : 'confirmrecreate';
2864 '<div class="mw-confirm-recreate">' .
2865 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2866 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2867 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2873 # When the summary is hidden, also hide them on preview/show changes
2874 if ( $this->nosummary
) {
2875 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2878 # If a blank edit summary was previously provided, and the appropriate
2879 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2880 # user being bounced back more than once in the event that a summary
2883 # For a bit more sophisticated detection of blank summaries, hash the
2884 # automatic one and pass that in the hidden field wpAutoSummary.
2885 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2886 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2889 if ( $this->undidRev
) {
2890 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2893 if ( $this->selfRedirect
) {
2894 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2897 if ( $this->hasPresetSummary
) {
2898 // If a summary has been preset using &summary= we don't want to prompt for
2899 // a different summary. Only prompt for a summary if the summary is blanked.
2901 $this->autoSumm
= md5( '' );
2904 $autosumm = $this->autoSumm
!== '' ?
$this->autoSumm
: md5( $this->summary
);
2905 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2907 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2908 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2910 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2911 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2915 if ( $this->section
== 'new' ) {
2916 $this->showSummaryInput( true, $this->summary
);
2917 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2920 $out->addHTML( $this->editFormTextBeforeContent
);
2921 if ( $this->isConflict
) {
2922 // In an edit conflict, we turn textbox2 into the user's text,
2923 // and textbox1 into the stored version
2924 $this->textbox2
= $this->textbox1
;
2926 $content = $this->getCurrentContent();
2927 $this->textbox1
= $this->toEditText( $content );
2929 $editConflictHelper = $this->getEditConflictHelper();
2930 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2931 $editConflictHelper->setContentModel( $this->contentModel
);
2932 $editConflictHelper->setContentFormat( $this->contentFormat
);
2933 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2936 if ( !$this->mTitle
->isUserConfigPage() ) {
2937 $out->addHTML( self
::getEditToolbar() );
2940 if ( $this->blankArticle
) {
2941 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2944 if ( $this->isConflict
) {
2945 // In an edit conflict bypass the overridable content form method
2946 // and fallback to the raw wpTextbox1 since editconflicts can't be
2947 // resolved between page source edits and custom ui edits using the
2949 $conflictTextBoxAttribs = [];
2950 if ( $this->wasDeletedSinceLastEdit() ) {
2951 $conflictTextBoxAttribs['style'] = 'display:none;';
2952 } elseif ( $this->isOldRev
) {
2953 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2956 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2957 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2959 $this->showContentForm();
2962 $out->addHTML( $this->editFormTextAfterContent
);
2964 $this->showStandardInputs();
2966 $this->showFormAfterText();
2968 $this->showTosSummary();
2970 $this->showEditTools();
2972 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2974 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2976 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2977 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2979 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2980 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2982 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2984 if ( $this->isConflict
) {
2986 $this->showConflict();
2987 } catch ( MWContentSerializationException
$ex ) {
2988 // this can't really happen, but be nice if it does.
2989 $msg = $this->context
->msg(
2990 'content-failed-to-parse',
2991 $this->contentModel
,
2992 $this->contentFormat
,
2995 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
2999 // Set a hidden field so JS knows what edit form mode we are in
3000 if ( $this->isConflict
) {
3002 } elseif ( $this->preview
) {
3004 } elseif ( $this->diff
) {
3009 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
3011 // Marker for detecting truncated form data. This must be the last
3012 // parameter sent in order to be of use, so do not move me.
3013 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
3014 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
3016 if ( !$user->getOption( 'previewontop' ) ) {
3017 $this->displayPreviewArea( $previewOutput, false );
3022 * Wrapper around TemplatesOnThisPageFormatter to make
3023 * a "templates on this page" list.
3025 * @param Title[] $templates
3026 * @return string HTML
3028 public function makeTemplatesOnThisPageList( array $templates ) {
3029 $templateListFormatter = new TemplatesOnThisPageFormatter(
3030 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
3033 // preview if preview, else section if section, else false
3035 if ( $this->preview
) {
3037 } elseif ( $this->section
!= '' ) {
3041 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
3042 $templateListFormatter->format( $templates, $type )
3047 * Extract the section title from current section text, if any.
3049 * @param string $text
3050 * @return string|bool String or false
3052 public static function extractSectionTitle( $text ) {
3053 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
3054 if ( !empty( $matches[2] ) ) {
3055 return MediaWikiServices
::getInstance()->getParser()
3056 ->stripSectionName( trim( $matches[2] ) );
3062 protected function showHeader() {
3063 $out = $this->context
->getOutput();
3064 $user = $this->context
->getUser();
3065 if ( $this->isConflict
) {
3066 $this->addExplainConflictHeader( $out );
3067 $this->editRevId
= $this->page
->getLatest();
3069 if ( $this->section
!= '' && $this->section
!= 'new' && !$this->summary
&&
3070 !$this->preview
&& !$this->diff
3072 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
3073 if ( $sectionTitle !== false ) {
3074 $this->summary
= "/* $sectionTitle */ ";
3078 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
3080 if ( $this->missingComment
) {
3081 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3084 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
3086 "<div id='mw-missingsummary'>\n$1\n</div>",
3087 [ 'missingsummary', $buttonLabel ]
3091 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3093 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3094 [ 'missingcommentheader', $buttonLabel ]
3098 if ( $this->blankArticle
) {
3100 "<div id='mw-blankarticle'>\n$1\n</div>",
3101 [ 'blankarticle', $buttonLabel ]
3105 if ( $this->selfRedirect
) {
3107 "<div id='mw-selfredirect'>\n$1\n</div>",
3108 [ 'selfredirect', $buttonLabel ]
3112 if ( $this->hookError
!== '' ) {
3113 $out->addWikiTextAsInterface( $this->hookError
);
3116 if ( $this->section
!= 'new' ) {
3117 $revision = $this->mArticle
->getRevisionFetched();
3119 // Let sysop know that this will make private content public if saved
3121 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3123 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3124 'rev-deleted-text-permission'
3126 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3128 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3129 'rev-deleted-text-view'
3133 if ( !$revision->isCurrent() ) {
3134 $this->mArticle
->setOldSubtitle( $revision->getId() );
3136 Html
::warningBox( "\n$1\n" ),
3139 $this->isOldRev
= true;
3141 } elseif ( $this->mTitle
->exists() ) {
3142 // Something went wrong
3144 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3145 [ 'missing-revision', $this->oldid
] );
3150 if ( wfReadOnly() ) {
3152 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3153 [ 'readonlywarning', wfReadOnlyReason() ]
3155 } elseif ( $user->isAnon() ) {
3156 if ( $this->formtype
!= 'preview' ) {
3157 $returntoquery = array_diff_key(
3158 $this->context
->getRequest()->getValues(),
3159 [ 'title' => true, 'returnto' => true, 'returntoquery' => true ]
3162 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3163 [ 'anoneditwarning',
3165 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3166 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3167 'returntoquery' => wfArrayToCgi( $returntoquery ),
3170 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3171 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3172 'returntoquery' => wfArrayToCgi( $returntoquery ),
3177 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3178 'anonpreviewwarning'
3181 } elseif ( $this->mTitle
->isUserConfigPage() ) {
3182 # Check the skin exists
3183 if ( $this->isWrongCaseUserConfigPage() ) {
3185 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3186 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3189 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3190 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3191 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3192 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3194 $warning = $isUserCssConfig
3196 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3198 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3200 if ( $this->formtype
!== 'preview' ) {
3201 $config = $this->context
->getConfig();
3202 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3204 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3205 [ 'usercssyoucanpreview' ]
3207 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3209 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3210 [ 'userjsonyoucanpreview' ]
3212 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3214 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3215 [ 'userjsyoucanpreview' ]
3222 $this->addPageProtectionWarningHeaders();
3224 $this->addLongPageWarningHeader();
3226 # Add header copyright warning
3227 $this->showHeaderCopyrightWarning();
3231 * Helper function for summary input functions, which returns the necessary
3232 * attributes for the input.
3234 * @param array|null $inputAttrs Array of attrs to use on the input
3237 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3238 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3239 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3240 // Unicode codepoints.
3241 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3242 'id' => 'wpSummary',
3243 'name' => 'wpSummary',
3244 'maxlength' => CommentStore
::COMMENT_CHARACTER_LIMIT
,
3247 'spellcheck' => 'true',
3252 * Builds a standard summary input with a label.
3254 * @param string $summary The value of the summary input
3255 * @param string|null $labelText The html to place inside the label
3256 * @param array|null $inputAttrs Array of attrs to use on the input
3258 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3260 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3261 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3262 $this->getSummaryInputAttributes( $inputAttrs )
3265 'title' => Linker
::titleAttrib( 'summary' ),
3266 'accessKey' => Linker
::accesskey( 'summary' ),
3269 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3270 $inputAttrs['inputId'] = $inputAttrs['id'];
3271 $inputAttrs['id'] = 'wpSummaryWidget';
3273 return new OOUI\
FieldLayout(
3274 new OOUI\
TextInputWidget( [
3275 'value' => $summary,
3276 'infusable' => true,
3279 'label' => new OOUI\
HtmlSnippet( $labelText ),
3281 'id' => 'wpSummaryLabel',
3282 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3288 * @param bool $isSubjectPreview True if this is the section subject/title
3289 * up top, or false if this is the comment summary
3290 * down below the textarea
3291 * @param string $summary The text of the summary to display
3293 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3294 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3295 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3296 if ( $isSubjectPreview ) {
3297 if ( $this->nosummary
) {
3300 } elseif ( !$this->mShowSummaryField
) {
3304 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3305 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3308 [ 'class' => $summaryClass ]
3313 * @param bool $isSubjectPreview True if this is the section subject/title
3314 * up top, or false if this is the comment summary
3315 * down below the textarea
3316 * @param string $summary The text of the summary to display
3319 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3320 // avoid spaces in preview, gets always trimmed on save
3321 $summary = trim( $summary );
3322 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3326 if ( $isSubjectPreview ) {
3327 $summary = $this->context
->msg( 'newsectionsummary' )
3328 ->rawParams( MediaWikiServices
::getInstance()->getParser()
3329 ->stripSectionName( $summary ) )
3330 ->inContentLanguage()->text();
3333 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3335 $summary = $this->context
->msg( $message )->parse()
3336 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3337 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3340 protected function showFormBeforeText() {
3341 $out = $this->context
->getOutput();
3342 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3343 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3344 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3345 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3346 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3349 protected function showFormAfterText() {
3351 * To make it harder for someone to slip a user a page
3352 * which submits an edit form to the wiki without their
3353 * knowledge, a random token is associated with the login
3354 * session. If it's not passed back with the submission,
3355 * we won't save the page, or render user JavaScript and
3358 * For anon editors, who may not have a session, we just
3359 * include the constant suffix to prevent editing from
3360 * broken text-mangling proxies.
3362 $this->context
->getOutput()->addHTML(
3364 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3370 * Subpage overridable method for printing the form for page content editing
3371 * By default this simply outputs wpTextbox1
3372 * Subclasses can override this to provide a custom UI for editing;
3373 * be it a form, or simply wpTextbox1 with a modified content that will be
3374 * reverse modified when extracted from the post data.
3375 * Note that this is basically the inverse for importContentFormData
3377 protected function showContentForm() {
3378 $this->showTextbox1();
3382 * Method to output wpTextbox1
3383 * The $textoverride method can be used by subclasses overriding showContentForm
3384 * to pass back to this method.
3386 * @param array|null $customAttribs Array of html attributes to use in the textarea
3387 * @param string|null $textoverride Optional text to override $this->textarea1 with
3389 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3390 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3391 $attribs = [ 'style' => 'display:none;' ];
3393 $builder = new TextboxBuilder();
3394 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3396 # Is an old revision being edited?
3397 if ( $this->isOldRev
) {
3398 $classes[] = 'mw-textarea-oldrev';
3401 $attribs = [ 'tabindex' => 1 ];
3403 if ( is_array( $customAttribs ) ) {
3404 $attribs +
= $customAttribs;
3407 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3411 $textoverride ??
$this->textbox1
,
3417 protected function showTextbox2() {
3418 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3421 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3422 $builder = new TextboxBuilder();
3423 $attribs = $builder->buildTextboxAttribs(
3426 $this->context
->getUser(),
3430 $this->context
->getOutput()->addHTML(
3431 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3435 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3438 $classes[] = 'ontop';
3441 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3443 if ( $this->formtype
!= 'preview' ) {
3444 $attribs['style'] = 'display: none;';
3447 $out = $this->context
->getOutput();
3448 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3450 if ( $this->formtype
== 'preview' ) {
3451 $this->showPreview( $previewOutput );
3453 // Empty content container for LivePreview
3454 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3455 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3456 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3457 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3460 $out->addHTML( '</div>' );
3462 if ( $this->formtype
== 'diff' ) {
3465 } catch ( MWContentSerializationException
$ex ) {
3466 $msg = $this->context
->msg(
3467 'content-failed-to-parse',
3468 $this->contentModel
,
3469 $this->contentFormat
,
3472 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3478 * Append preview output to OutputPage.
3479 * Includes category rendering if this is a category page.
3481 * @param string $text The HTML to be output for the preview.
3483 protected function showPreview( $text ) {
3484 if ( $this->mArticle
instanceof CategoryPage
) {
3485 $this->mArticle
->openShowCategory();
3487 # This hook seems slightly odd here, but makes things more
3488 # consistent for extensions.
3489 $out = $this->context
->getOutput();
3490 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3491 $out->addHTML( $text );
3492 if ( $this->mArticle
instanceof CategoryPage
) {
3493 $this->mArticle
->closeShowCategory();
3498 * Get a diff between the current contents of the edit box and the
3499 * version of the page we're editing from.
3501 * If this is a section edit, we'll replace the section as for final
3502 * save and then make a comparison.
3504 public function showDiff() {
3505 $oldtitlemsg = 'currentrev';
3506 # if message does not exist, show diff against the preloaded default
3507 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3508 $oldtext = $this->mTitle
->getDefaultMessageText();
3509 if ( $oldtext !== false ) {
3510 $oldtitlemsg = 'defaultmessagetext';
3511 $oldContent = $this->toEditContent( $oldtext );
3516 $oldContent = $this->getCurrentContent();
3519 $textboxContent = $this->toEditContent( $this->textbox1
);
3520 if ( $this->editRevId
!== null ) {
3521 $newContent = $this->page
->replaceSectionAtRev(
3522 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3525 $newContent = $this->page
->replaceSectionContent(
3526 $this->section
, $textboxContent, $this->summary
, $this->edittime
3530 if ( $newContent ) {
3531 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3533 $user = $this->context
->getUser();
3534 $popts = ParserOptions
::newFromUserAndLang( $user,
3535 MediaWikiServices
::getInstance()->getContentLanguage() );
3536 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3539 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3540 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3541 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3543 if ( !$oldContent ) {
3544 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3547 if ( !$newContent ) {
3548 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3551 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3552 $de->setContent( $oldContent, $newContent );
3554 $difftext = $de->getDiff( $oldtitle, $newtitle );
3555 $de->showDiffStyle();
3560 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3564 * Show the header copyright warning.
3566 protected function showHeaderCopyrightWarning() {
3567 $msg = 'editpage-head-copy-warn';
3568 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3569 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3570 'editpage-head-copy-warn' );
3575 * Give a chance for site and per-namespace customizations of
3576 * terms of service summary link that might exist separately
3577 * from the copyright notice.
3579 * This will display between the save button and the edit tools,
3580 * so should remain short!
3582 protected function showTosSummary() {
3583 $msg = 'editpage-tos-summary';
3584 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3585 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3586 $out = $this->context
->getOutput();
3587 $out->addHTML( '<div class="mw-tos-summary">' );
3588 $out->addWikiMsg( $msg );
3589 $out->addHTML( '</div>' );
3594 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3595 * characters not present on most keyboards for copying/pasting.
3597 protected function showEditTools() {
3598 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3599 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3604 * Get the copyright warning
3606 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3609 protected function getCopywarn() {
3610 return self
::getCopyrightWarning( $this->mTitle
);
3614 * Get the copyright warning, by default returns wikitext
3616 * @param Title $title
3617 * @param string $format Output format, valid values are any function of a Message object
3618 * @param Language|string|null $langcode Language code or Language object.
3621 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3622 global $wgRightsText;
3623 if ( $wgRightsText ) {
3624 $copywarnMsg = [ 'copyrightwarning',
3625 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3628 $copywarnMsg = [ 'copyrightwarning2',
3629 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3631 // Allow for site and per-namespace customization of contribution/copyright notice.
3632 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3634 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3636 $msg->inLanguage( $langcode );
3638 return "<div id=\"editpage-copywarn\">\n" .
3639 $msg->$format() . "\n</div>";
3643 * Get the Limit report for page previews
3646 * @param ParserOutput|null $output ParserOutput object from the parse
3647 * @return string HTML
3649 public static function getPreviewLimitReport( ParserOutput
$output = null ) {
3652 if ( !$output ||
!$output->getLimitReportData() ) {
3656 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3657 wfMessage( 'limitreport-title' )->parseAsBlock()
3660 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3661 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3663 $limitReport .= Html
::openElement( 'table', [
3664 'class' => 'preview-limit-report wikitable'
3666 Html
::openElement( 'tbody' );
3668 foreach ( $output->getLimitReportData() as $key => $value ) {
3669 if ( Hooks
::run( 'ParserLimitReportFormat',
3670 [ $key, &$value, &$limitReport, true, true ]
3672 $keyMsg = wfMessage( $key );
3673 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3674 if ( !$valueMsg->exists() ) {
3675 $valueMsg = new RawMessage( '$1' );
3677 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3678 $limitReport .= Html
::openElement( 'tr' ) .
3679 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3680 Html
::rawElement( 'td', null,
3681 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3683 Html
::closeElement( 'tr' );
3688 $limitReport .= Html
::closeElement( 'tbody' ) .
3689 Html
::closeElement( 'table' ) .
3690 Html
::closeElement( 'div' );
3692 return $limitReport;
3695 protected function showStandardInputs( &$tabindex = 2 ) {
3696 $out = $this->context
->getOutput();
3697 $out->addHTML( "<div class='editOptions'>\n" );
3699 if ( $this->section
!= 'new' ) {
3700 $this->showSummaryInput( false, $this->summary
);
3701 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3704 $checkboxes = $this->getCheckboxesWidget(
3706 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3708 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3710 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3712 // Show copyright warning.
3713 $out->addWikiTextAsInterface( $this->getCopywarn() );
3714 $out->addHTML( $this->editFormTextAfterWarn
);
3716 $out->addHTML( "<div class='editButtons'>\n" );
3717 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3719 $cancel = $this->getCancelLink();
3721 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3722 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3725 $this->context
->msg( 'edithelp' )->text(),
3726 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3729 $this->context
->msg( 'word-separator' )->escaped() .
3730 $this->context
->msg( 'newwindow' )->parse();
3732 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3733 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3734 $out->addHTML( "</div><!-- editButtons -->\n" );
3736 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3738 $out->addHTML( "</div><!-- editOptions -->\n" );
3742 * Show an edit conflict. textbox1 is already shown in showEditForm().
3743 * If you want to use another entry point to this function, be careful.
3745 protected function showConflict() {
3746 $out = $this->context
->getOutput();
3747 // Avoid PHP 7.1 warning of passing $this by reference
3749 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3750 $this->incrementConflictStats();
3752 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3756 protected function incrementConflictStats() {
3757 $this->getEditConflictHelper()->incrementConflictStats();
3763 public function getCancelLink() {
3765 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3766 $cancelParams['oldid'] = $this->oldid
;
3767 } elseif ( $this->getContextTitle()->isRedirect() ) {
3768 $cancelParams['redirect'] = 'no';
3771 return new OOUI\
ButtonWidget( [
3772 'id' => 'mw-editform-cancel',
3773 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3774 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3776 'infusable' => true,
3777 'flags' => 'destructive',
3782 * Returns the URL to use in the form's action attribute.
3783 * This is used by EditPage subclasses when simply customizing the action
3784 * variable in the constructor is not enough. This can be used when the
3785 * EditPage lives inside of a Special page rather than a custom page action.
3787 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3790 protected function getActionURL( Title
$title ) {
3791 return $title->getLocalURL( [ 'action' => $this->action
] );
3795 * Check if a page was deleted while the user was editing it, before submit.
3796 * Note that we rely on the logging table, which hasn't been always there,
3797 * but that doesn't matter, because this only applies to brand new
3801 protected function wasDeletedSinceLastEdit() {
3802 if ( $this->deletedSinceEdit
!== null ) {
3803 return $this->deletedSinceEdit
;
3806 $this->deletedSinceEdit
= false;
3808 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3809 $this->lastDelete
= $this->getLastDelete();
3810 if ( $this->lastDelete
) {
3811 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3812 if ( $deleteTime > $this->starttime
) {
3813 $this->deletedSinceEdit
= true;
3818 return $this->deletedSinceEdit
;
3822 * Get the last log record of this page being deleted, if ever. This is
3823 * used to detect whether a delete occurred during editing.
3824 * @return bool|stdClass
3826 protected function getLastDelete() {
3827 $dbr = wfGetDB( DB_REPLICA
);
3828 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3829 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3830 $data = $dbr->selectRow(
3831 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3841 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3843 'log_namespace' => $this->mTitle
->getNamespace(),
3844 'log_title' => $this->mTitle
->getDBkey(),
3845 'log_type' => 'delete',
3846 'log_action' => 'delete',
3849 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3851 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3852 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3854 // Quick paranoid permission checks...
3855 if ( is_object( $data ) ) {
3856 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3857 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3860 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3861 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3862 $data->log_comment_data
= null;
3870 * Get the rendered text for previewing.
3871 * @throws MWException
3874 public function getPreviewText() {
3875 $out = $this->context
->getOutput();
3876 $config = $this->context
->getConfig();
3878 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3879 // Could be an offsite preview attempt. This is very unsafe if
3880 // HTML is enabled, as it could be an attack.
3882 if ( $this->textbox1
!== '' ) {
3883 // Do not put big scary notice, if previewing the empty
3884 // string, which happens when you initially edit
3885 // a category page, due to automatic preview-on-open.
3886 $parsedNote = Html
::rawElement( 'div', [ 'class' => 'previewnote' ],
3887 $out->parseAsInterface(
3888 $this->context
->msg( 'session_fail_preview_html' )->plain()
3891 $this->incrementEditFailureStats( 'session_loss' );
3898 $content = $this->toEditContent( $this->textbox1
);
3902 'AlternateEditPreview',
3903 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3905 return $previewHTML;
3908 # provide a anchor link to the editform
3909 $continueEditing = '<span class="mw-continue-editing">' .
3910 '[[#' . self
::EDITFORM_ID
. '|' .
3911 $this->context
->getLanguage()->getArrow() . ' ' .
3912 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3913 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3914 if ( $this->mTokenOkExceptSuffix
) {
3915 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3916 $this->incrementEditFailureStats( 'bad_token' );
3918 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3919 $this->incrementEditFailureStats( 'session_loss' );
3921 } elseif ( $this->incompleteForm
) {
3922 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3923 if ( $this->mTriedSave
) {
3924 $this->incrementEditFailureStats( 'incomplete_form' );
3927 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3930 # don't parse non-wikitext pages, show message about preview
3931 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3932 if ( $this->mTitle
->isUserConfigPage() ) {
3934 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3940 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3942 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3945 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3947 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3950 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3952 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3959 # Used messages to make sure grep find them:
3960 # Messages: usercsspreview, userjsonpreview, userjspreview,
3961 # sitecsspreview, sitejsonpreview, sitejspreview
3962 if ( $level && $format ) {
3963 $note = "<div id='mw-{$level}{$format}preview'>" .
3964 $this->context
->msg( "{$level}{$format}preview" )->plain() .
3965 ' ' . $continueEditing . "</div>";
3969 # If we're adding a comment, we need to show the
3970 # summary as the headline
3971 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3972 $content = $content->addSectionHeader( $this->summary
);
3975 $hook_args = [ $this, &$content ];
3976 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3978 $parserResult = $this->doPreviewParse( $content );
3979 $parserOutput = $parserResult['parserOutput'];
3980 $previewHTML = $parserResult['html'];
3981 $this->mParserOutput
= $parserOutput;
3982 $out->addParserOutputMetadata( $parserOutput );
3983 if ( $out->userCanPreview() ) {
3984 $out->addContentOverride( $this->getTitle(), $content );
3987 if ( count( $parserOutput->getWarnings() ) ) {
3988 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3991 } catch ( MWContentSerializationException
$ex ) {
3992 $m = $this->context
->msg(
3993 'content-failed-to-parse',
3994 $this->contentModel
,
3995 $this->contentFormat
,
3998 $note .= "\n\n" . $m->plain(); # gets parsed down below
4002 if ( $this->isConflict
) {
4003 $conflict = Html
::rawElement(
4004 'h2', [ 'id' => 'mw-previewconflict' ],
4005 $this->context
->msg( 'previewconflict' )->escaped()
4008 $conflict = '<hr />';
4011 $previewhead = Html
::rawElement(
4012 'div', [ 'class' => 'previewnote' ],
4014 'h2', [ 'id' => 'mw-previewheader' ],
4015 $this->context
->msg( 'preview' )->escaped()
4017 $out->parseAsInterface( $note ) . $conflict
4020 $pageViewLang = $this->mTitle
->getPageViewLanguage();
4021 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
4022 'class' => 'mw-content-' . $pageViewLang->getDir() ];
4023 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
4025 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
4028 private function incrementEditFailureStats( $failureType ) {
4029 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
4030 $stats->increment( 'edit.failures.' . $failureType );
4034 * Get parser options for a preview
4035 * @return ParserOptions
4037 protected function getPreviewParserOptions() {
4038 $parserOptions = $this->page
->makeParserOptions( $this->context
);
4039 $parserOptions->setIsPreview( true );
4040 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
4041 $parserOptions->enableLimitReport();
4043 // XXX: we could call $parserOptions->setCurrentRevisionCallback here to force the
4044 // current revision to be null during PST, until setupFakeRevision is called on
4045 // the ParserOptions. Currently, we rely on Parser::getRevisionObject() to ignore
4046 // existing revisions in preview mode.
4048 return $parserOptions;
4052 * Parse the page for a preview. Subclasses may override this class, in order
4053 * to parse with different options, or to otherwise modify the preview HTML.
4055 * @param Content $content The page content
4056 * @return array with keys:
4057 * - parserOutput: The ParserOutput object
4058 * - html: The HTML to be displayed
4060 protected function doPreviewParse( Content
$content ) {
4061 $user = $this->context
->getUser();
4062 $parserOptions = $this->getPreviewParserOptions();
4064 // NOTE: preSaveTransform doesn't have a fake revision to operate on.
4065 // Parser::getRevisionObject() will return null in preview mode,
4066 // causing the context user to be used for {{subst:REVISIONUSER}}.
4067 // XXX: Alternatively, we could also call setupFakeRevision() a second time:
4068 // once before PST with $content, and then after PST with $pstContent.
4069 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
4070 $scopedCallback = $parserOptions->setupFakeRevision( $this->mTitle
, $pstContent, $user );
4071 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
4072 ScopedCallback
::consume( $scopedCallback );
4074 'parserOutput' => $parserOutput,
4075 'html' => $parserOutput->getText( [
4076 'enableSectionEditLinks' => false
4084 public function getTemplates() {
4085 if ( $this->preview ||
$this->section
!= '' ) {
4087 if ( !isset( $this->mParserOutput
) ) {
4090 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
4091 foreach ( array_keys( $template ) as $dbk ) {
4092 $templates[] = Title
::makeTitle( $ns, $dbk );
4097 return $this->mTitle
->getTemplateLinksFrom();
4102 * Allow extensions to provide a toolbar.
4104 * @return string|null
4106 public static function getEditToolbar() {
4107 $startingToolbar = '<div id="toolbar"></div>';
4108 $toolbar = $startingToolbar;
4110 if ( !Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4113 // Don't add a pointless `<div>` to the page unless a hook caller populated it
4114 return ( $toolbar === $startingToolbar ) ?
null : $toolbar;
4118 * Return an array of checkbox definitions.
4120 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4122 * Array values are associative arrays with the following keys:
4123 * - 'label-message' (required): message for label text
4124 * - 'id' (required): 'id' attribute for the `<input>`
4125 * - 'default' (required): default checkedness (true or false)
4126 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4127 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4128 * from messages like 'tooltip-foo', 'accesskey-foo'
4129 * - 'label-id' (optional): 'id' attribute for the `<label>`
4130 * - 'legacy-name' (optional): short name for backwards-compatibility
4131 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4132 * where bool indicates the checked status of the checkbox
4135 public function getCheckboxesDefinition( $checked ) {
4138 $user = $this->context
->getUser();
4139 // don't show the minor edit checkbox if it's a new page or section
4140 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4141 $checkboxes['wpMinoredit'] = [
4142 'id' => 'wpMinoredit',
4143 'label-message' => 'minoredit',
4144 // Uses messages: tooltip-minoredit, accesskey-minoredit
4145 'tooltip' => 'minoredit',
4146 'label-id' => 'mw-editpage-minoredit',
4147 'legacy-name' => 'minor',
4148 'default' => $checked['minor'],
4152 if ( $user->isLoggedIn() ) {
4153 $checkboxes['wpWatchthis'] = [
4154 'id' => 'wpWatchthis',
4155 'label-message' => 'watchthis',
4156 // Uses messages: tooltip-watch, accesskey-watch
4157 'tooltip' => 'watch',
4158 'label-id' => 'mw-editpage-watch',
4159 'legacy-name' => 'watch',
4160 'default' => $checked['watch'],
4165 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4171 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4172 * any other added by extensions.
4174 * @param int &$tabindex Current tabindex
4175 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4176 * status of the checkbox
4178 * @return array Associative array of string keys to OOUI\FieldLayout instances
4180 public function getCheckboxesWidget( &$tabindex, $checked ) {
4182 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4184 foreach ( $checkboxesDef as $name => $options ) {
4185 $legacyName = $options['legacy-name'] ??
$name;
4189 if ( isset( $options['tooltip'] ) ) {
4190 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4191 $title = Linker
::titleAttrib( $options['tooltip'] );
4193 if ( isset( $options['title-message'] ) ) {
4194 $title = $this->context
->msg( $options['title-message'] )->text();
4197 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4198 new OOUI\
CheckboxInputWidget( [
4199 'tabIndex' => ++
$tabindex,
4200 'accessKey' => $accesskey,
4201 'id' => $options['id'] . 'Widget',
4202 'inputId' => $options['id'],
4204 'selected' => $options['default'],
4205 'infusable' => true,
4208 'align' => 'inline',
4209 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4211 'id' => $options['label-id'] ??
null,
4220 * Get the message key of the label for the button to save the page
4225 protected function getSubmitButtonLabel() {
4227 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4229 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4230 $newPage = !$this->mTitle
->exists();
4232 if ( $labelAsPublish ) {
4233 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4235 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4238 return $buttonLabelKey;
4242 * Returns an array of html code of the following buttons:
4243 * save, diff and preview
4245 * @param int &$tabindex Current tabindex
4249 public function getEditButtons( &$tabindex ) {
4253 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4255 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4256 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4258 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4260 'tabIndex' => ++
$tabindex,
4261 'id' => 'wpSaveWidget',
4262 'inputId' => 'wpSave',
4263 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4264 'useInputTag' => true,
4265 'flags' => [ 'progressive', 'primary' ],
4266 'label' => $buttonLabel,
4267 'infusable' => true,
4269 // Messages used: tooltip-save, tooltip-publish
4270 'title' => Linker
::titleAttrib( $buttonTooltip ),
4271 // Messages used: accesskey-save, accesskey-publish
4272 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4275 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4276 'name' => 'wpPreview',
4277 'tabIndex' => ++
$tabindex,
4278 'id' => 'wpPreviewWidget',
4279 'inputId' => 'wpPreview',
4280 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4281 'useInputTag' => true,
4282 'label' => $this->context
->msg( 'showpreview' )->text(),
4283 'infusable' => true,
4285 // Message used: tooltip-preview
4286 'title' => Linker
::titleAttrib( 'preview' ),
4287 // Message used: accesskey-preview
4288 'accessKey' => Linker
::accesskey( 'preview' ),
4291 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4293 'tabIndex' => ++
$tabindex,
4294 'id' => 'wpDiffWidget',
4295 'inputId' => 'wpDiff',
4296 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4297 'useInputTag' => true,
4298 'label' => $this->context
->msg( 'showdiff' )->text(),
4299 'infusable' => true,
4301 // Message used: tooltip-diff
4302 'title' => Linker
::titleAttrib( 'diff' ),
4303 // Message used: accesskey-diff
4304 'accessKey' => Linker
::accesskey( 'diff' ),
4307 // Avoid PHP 7.1 warning of passing $this by reference
4309 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4315 * Creates a basic error page which informs the user that
4316 * they have attempted to edit a nonexistent section.
4318 public function noSuchSectionPage() {
4319 $out = $this->context
->getOutput();
4320 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4322 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4324 // Avoid PHP 7.1 warning of passing $this by reference
4326 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4327 $out->addHTML( $res );
4329 $out->returnToMain( false, $this->mTitle
);
4333 * Show "your edit contains spam" page with your diff and text
4335 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4337 public function spamPageWithContent( $match = false ) {
4338 $this->textbox2
= $this->textbox1
;
4340 if ( is_array( $match ) ) {
4341 $match = $this->context
->getLanguage()->listToText( $match );
4343 $out = $this->context
->getOutput();
4344 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4346 $out->addHTML( '<div id="spamprotected">' );
4347 $out->addWikiMsg( 'spamprotectiontext' );
4349 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4351 $out->addHTML( '</div>' );
4353 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4356 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4357 $this->showTextbox2();
4359 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4365 protected function addEditNotices() {
4366 $out = $this->context
->getOutput();
4367 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4368 if ( count( $editNotices ) ) {
4369 $out->addHTML( implode( "\n", $editNotices ) );
4371 $msg = $this->context
->msg( 'editnotice-notext' );
4372 if ( !$msg->isDisabled() ) {
4374 '<div class="mw-editnotice-notext">'
4375 . $msg->parseAsBlock()
4385 protected function addTalkPageText() {
4386 if ( $this->mTitle
->isTalkPage() ) {
4387 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4394 protected function addLongPageWarningHeader() {
4395 if ( $this->contentLength
=== false ) {
4396 $this->contentLength
= strlen( $this->textbox1
);
4399 $out = $this->context
->getOutput();
4400 $lang = $this->context
->getLanguage();
4401 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4402 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4403 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4406 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4407 $lang->formatNum( $maxArticleSize )
4410 } elseif ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4411 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4414 $lang->formatSize( strlen( $this->textbox1
) ),
4415 strlen( $this->textbox1
)
4424 protected function addPageProtectionWarningHeaders() {
4425 $out = $this->context
->getOutput();
4426 if ( $this->mTitle
->isProtected( 'edit' ) &&
4427 MediaWikiServices
::getInstance()->getNamespaceInfo()->getRestrictionLevels(
4428 $this->mTitle
->getNamespace()
4431 # Is the title semi-protected?
4432 if ( $this->mTitle
->isSemiProtected() ) {
4433 $noticeMsg = 'semiprotectedpagewarning';
4435 # Then it must be protected based on static groups (regular)
4436 $noticeMsg = 'protectedpagewarning';
4438 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4439 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4441 if ( $this->mTitle
->isCascadeProtected() ) {
4442 # Is this page under cascading protection from some source pages?
4443 /** @var Title[] $cascadeSources */
4444 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4445 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4446 $cascadeSourcesCount = count( $cascadeSources );
4447 if ( $cascadeSourcesCount > 0 ) {
4448 # Explain, and list the titles responsible
4449 foreach ( $cascadeSources as $page ) {
4450 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4453 $notice .= '</div>';
4454 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4456 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4457 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4459 'showIfEmpty' => false,
4460 'msgKey' => [ 'titleprotectedwarning' ],
4461 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4466 * @param OutputPage $out
4469 protected function addExplainConflictHeader( OutputPage
$out ) {
4471 $this->getEditConflictHelper()->getExplainHeader()
4476 * @param string $name
4477 * @param mixed[] $customAttribs
4482 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4483 return ( new TextboxBuilder() )->buildTextboxAttribs(
4484 $name, $customAttribs, $user, $this->mTitle
4489 * @param string $wikitext
4493 protected function addNewLineAtEnd( $wikitext ) {
4494 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4498 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4499 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4500 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4501 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4502 * spread the new style links more efficiently.
4504 * @param string $text
4507 private function guessSectionName( $text ) {
4508 // Detect Microsoft browsers
4509 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4510 $parser = MediaWikiServices
::getInstance()->getParser();
4511 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4512 // ...and redirect them to legacy encoding, if available
4513 return $parser->guessLegacySectionNameFromWikiText( $text );
4515 // Meanwhile, real browsers get real anchors
4516 $name = $parser->guessSectionNameFromWikiText( $text );
4517 // With one little caveat: per T216029, fragments in HTTP redirects need to be urlencoded,
4518 // otherwise Chrome double-escapes the rest of the URL.
4519 return '#' . urlencode( mb_substr( $name, 1 ) );
4523 * Set a factory function to create an EditConflictHelper
4525 * @param callable $factory Factory function
4528 public function setEditConflictHelperFactory( callable
$factory ) {
4529 $this->editConflictHelperFactory
= $factory;
4530 $this->editConflictHelper
= null;
4534 * @return TextConflictHelper
4536 private function getEditConflictHelper() {
4537 if ( !$this->editConflictHelper
) {
4538 $this->editConflictHelper
= call_user_func(
4539 $this->editConflictHelperFactory
,
4540 $this->getSubmitButtonLabel()
4544 return $this->editConflictHelper
;
4548 * @param string $submitButtonLabel
4549 * @return TextConflictHelper
4551 private function newTextConflictHelper( $submitButtonLabel ) {
4552 return new TextConflictHelper(
4554 $this->getContext()->getOutput(),
4555 MediaWikiServices
::getInstance()->getStatsdDataFactory(),