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\Block\DatabaseBlock
;
24 use MediaWiki\EditPage\TextboxBuilder
;
25 use MediaWiki\EditPage\TextConflictHelper
;
26 use MediaWiki\Logger\LoggerFactory
;
27 use MediaWiki\MediaWikiServices
;
28 use Wikimedia\ScopedCallback
;
31 * The edit page/HTML interface (split from Article)
32 * The actual database and text munging is still in Article,
33 * but it should get easier to call those from alternate
36 * EditPage cares about two distinct titles:
37 * $this->mContextTitle is the page that forms submit to, links point to,
38 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
39 * page in the database that is actually being edited. These are
40 * usually the same, but they are now allowed to be different.
42 * Surgeon General's Warning: prolonged exposure to this class is known to cause
43 * headaches, which may be fatal.
47 * Used for Unicode support checks
49 const UNICODE_CHECK
= 'β³π²β₯πππΎπΈβ΄πΉβ―';
52 * Status: Article successfully updated
54 const AS_SUCCESS_UPDATE
= 200;
57 * Status: Article successfully created
59 const AS_SUCCESS_NEW_ARTICLE
= 201;
62 * Status: Article update aborted by a hook function
64 const AS_HOOK_ERROR
= 210;
67 * Status: A hook function returned an error
69 const AS_HOOK_ERROR_EXPECTED
= 212;
72 * Status: User is blocked from editing this page
74 const AS_BLOCKED_PAGE_FOR_USER
= 215;
77 * Status: Content too big (> $wgMaxArticleSize)
79 const AS_CONTENT_TOO_BIG
= 216;
82 * Status: this anonymous user is not allowed to edit this page
84 const AS_READ_ONLY_PAGE_ANON
= 218;
87 * Status: this logged in user is not allowed to edit this page
89 const AS_READ_ONLY_PAGE_LOGGED
= 219;
92 * Status: wiki is in readonly mode (wfReadOnly() == true)
94 const AS_READ_ONLY_PAGE
= 220;
97 * Status: rate limiter for action 'edit' was tripped
99 const AS_RATE_LIMITED
= 221;
102 * Status: article was deleted while editing and param wpRecreate == false or form
105 const AS_ARTICLE_WAS_DELETED
= 222;
108 * Status: user tried to create this page, but is not allowed to do that
109 * ( Title->userCan('create') == false )
111 const AS_NO_CREATE_PERMISSION
= 223;
114 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
116 const AS_BLANK_ARTICLE
= 224;
119 * Status: (non-resolvable) edit conflict
121 const AS_CONFLICT_DETECTED
= 225;
124 * Status: no edit summary given and the user has forceeditsummary set and the user is not
125 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
127 const AS_SUMMARY_NEEDED
= 226;
130 * Status: user tried to create a new section without content
132 const AS_TEXTBOX_EMPTY
= 228;
135 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
137 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
140 * Status: WikiPage::doEdit() was unsuccessful
145 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
147 const AS_SPAM_ERROR
= 232;
150 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
152 const AS_IMAGE_REDIRECT_ANON
= 233;
155 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
157 const AS_IMAGE_REDIRECT_LOGGED
= 234;
160 * Status: user tried to modify the content model, but is not allowed to do that
161 * ( User::isAllowed('editcontentmodel') == false )
163 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
166 * Status: user tried to create self-redirect (redirect to the same article) and
167 * wpIgnoreSelfRedirect == false
169 const AS_SELF_REDIRECT
= 236;
172 * Status: an error relating to change tagging. Look at the message key for
175 const AS_CHANGE_TAG_ERROR
= 237;
178 * Status: can't parse content
180 const AS_PARSE_ERROR
= 240;
183 * Status: when changing the content model is disallowed due to
184 * $wgContentHandlerUseDB being false
186 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
189 * Status: edit rejected because browser doesn't support Unicode.
191 const AS_UNICODE_NOT_SUPPORTED
= 242;
194 * HTML id and name for the beginning of the edit form.
196 const EDITFORM_ID
= 'editform';
199 * Prefix of key for cookie used to pass post-edit state.
200 * The revision id edited is added after this
202 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
205 * Duration of PostEdit cookie, in seconds.
206 * The cookie will be removed instantly if the JavaScript runs.
208 * Otherwise, though, we don't want the cookies to accumulate.
209 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
210 * limit of only 20 cookies per domain. This still applies at least to some
211 * versions of IE without full updates:
212 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
214 * A value of 20 minutes should be enough to take into account slow loads and minor
215 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
217 const POST_EDIT_COOKIE_DURATION
= 1200;
220 * @deprecated for public usage since 1.30 use EditPage::getArticle()
228 * @deprecated for public usage since 1.30 use EditPage::getTitle()
233 /** @var null|Title */
234 private $mContextTitle = null;
237 public $action = 'submit';
239 /** @var bool Whether an edit conflict needs to be resolved. Detected based on whether
240 * $editRevId is different than the latest revision. When a conflict has successfully
241 * been resolved by a 3-way-merge, this field is set to false.
243 public $isConflict = false;
245 /** @var bool New page or new section */
246 public $isNew = false;
249 public $deletedSinceEdit;
255 * True the first time the edit form is rendered, false after re-rendering
256 * with diff, save prompts, etc.
260 /** @var bool|stdClass */
264 public $mTokenOk = false;
267 public $mTokenOkExceptSuffix = false;
270 public $mTriedSave = false;
273 public $incompleteForm = false;
276 public $tooBig = false;
279 public $missingComment = false;
282 public $missingSummary = false;
285 public $allowBlankSummary = false;
288 protected $blankArticle = false;
291 protected $allowBlankArticle = false;
294 protected $selfRedirect = false;
297 protected $allowSelfRedirect = false;
300 public $autoSumm = '';
303 public $hookError = '';
305 /** @var ParserOutput */
306 public $mParserOutput;
308 /** @var bool Has a summary been preset using GET parameter &summary= ? */
309 public $hasPresetSummary = false;
311 /** @var Revision|bool|null A revision object corresponding to $this->editRevId. */
312 public $mBaseRevision = false;
315 public $mShowSummaryField = true;
320 public $save = false;
323 public $preview = false;
326 public $diff = false;
329 public $minoredit = false;
332 public $watchthis = false;
335 public $recreate = false;
338 * Page content input field.
340 public $textbox1 = '';
343 public $textbox2 = '';
346 public $summary = '';
349 * If true, hide the summary field.
351 public $nosummary = false;
354 * Timestamp of the latest revision of the page when editing was initiated
357 public $edittime = '';
359 /** @var int Revision ID of the latest revision of the page when editing
360 * was initiated on the client. This is used to detect and resolve edit
363 * @note 0 if the page did not exist at that time.
364 * @note When starting an edit from an old revision, this still records the current
365 * revision at the time, not the one the edit is based on.
368 * @see getBaseRevision()
370 private $editRevId = null;
373 public $section = '';
376 public $sectiontitle = '';
379 * Timestamp from the first time the edit form was rendered.
381 public $starttime = '';
383 /** @var int Revision ID the edit is based on, or 0 if it's the current revision.
384 * FIXME: This isn't used in conflict resolution--provide a better
385 * justification or merge with parentRevId.
390 /** @var int Revision ID the edit is based on, adjusted when an edit conflict is resolved.
393 * @see getparentRevId()
395 public $parentRevId = 0;
398 public $editintro = '';
401 public $scrolltop = null;
407 public $contentModel;
409 /** @var null|string */
410 public $contentFormat = null;
412 /** @var null|array */
413 private $changeTags = null;
415 # Placeholders for text injection by hooks (must be HTML)
416 # extensions should take care to _append_ to the present value
418 /** @var string Before even the preview */
419 public $editFormPageTop = '';
420 public $editFormTextTop = '';
421 public $editFormTextBeforeContent = '';
422 public $editFormTextAfterWarn = '';
423 public $editFormTextAfterTools = '';
424 public $editFormTextBottom = '';
425 public $editFormTextAfterContent = '';
426 public $previewTextAfterContent = '';
427 public $mPreloadContent = null;
429 /* $didSave should be set to true whenever an article was successfully altered. */
430 public $didSave = false;
431 public $undidRev = 0;
433 public $suppressIntro = false;
439 protected $contentLength = false;
442 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
444 private $enableApiEditOverride = false;
447 * @var IContextSource
452 * @var bool Whether an old revision is edited
454 private $isOldRev = false;
457 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
459 private $unicodeCheck;
462 * Factory function to create an edit conflict helper
466 private $editConflictHelperFactory;
469 * @var TextConflictHelper|null
471 private $editConflictHelper;
474 * @param Article $article
476 public function __construct( Article
$article ) {
477 $this->mArticle
= $article;
478 $this->page
= $article->getPage(); // model object
479 $this->mTitle
= $article->getTitle();
481 // Make sure the local context is in sync with other member variables.
482 // Particularly make sure everything is using the same WikiPage instance.
483 // This should probably be the case in Article as well, but it's
484 // particularly important for EditPage, to make use of the in-place caching
485 // facility in WikiPage::prepareContentForEdit.
486 $this->context
= new DerivativeContext( $article->getContext() );
487 $this->context
->setWikiPage( $this->page
);
488 $this->context
->setTitle( $this->mTitle
);
490 $this->contentModel
= $this->mTitle
->getContentModel();
492 $handler = ContentHandler
::getForModelID( $this->contentModel
);
493 $this->contentFormat
= $handler->getDefaultFormat();
494 $this->editConflictHelperFactory
= [ $this, 'newTextConflictHelper' ];
500 public function getArticle() {
501 return $this->mArticle
;
506 * @return IContextSource
508 public function getContext() {
509 return $this->context
;
516 public function getTitle() {
517 return $this->mTitle
;
521 * Set the context Title object
523 * @param Title|null $title Title object or null
525 public function setContextTitle( $title ) {
526 $this->mContextTitle
= $title;
530 * Get the context title object.
532 * If not set, $wgTitle will be returned, but this is deprecated. This will
533 * throw an exception.
537 public function getContextTitle() {
538 if ( is_null( $this->mContextTitle
) ) {
539 wfDeprecated( __METHOD__
. ' called with no title set', '1.32' );
543 return $this->mContextTitle
;
548 * Returns if the given content model is editable.
550 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
552 * @throws MWException If $modelId has no known handler
554 public function isSupportedContentModel( $modelId ) {
555 return $this->enableApiEditOverride
=== true ||
556 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
560 * Allow editing of content that supports API direct editing, but not general
561 * direct editing. Set to false by default.
563 * @param bool $enableOverride
565 public function setApiEditOverride( $enableOverride ) {
566 $this->enableApiEditOverride
= $enableOverride;
570 * This is the function that gets called for "action=edit". It
571 * sets up various member variables, then passes execution to
572 * another function, usually showEditForm()
574 * The edit form is self-submitting, so that when things like
575 * preview and edit conflicts occur, we get the same form back
576 * with the extra stuff added. Only when the final submission
577 * is made and all is well do we actually save and redirect to
578 * the newly-edited page.
580 public function edit() {
581 // Allow extensions to modify/prevent this form or submission
582 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
586 wfDebug( __METHOD__
. ": enter\n" );
588 $request = $this->context
->getRequest();
589 // If they used redlink=1 and the page exists, redirect to the main article
590 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
591 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
595 $this->importFormData( $request );
596 $this->firsttime
= false;
598 if ( wfReadOnly() && $this->save
) {
601 $this->preview
= true;
605 $this->formtype
= 'save';
606 } elseif ( $this->preview
) {
607 $this->formtype
= 'preview';
608 } elseif ( $this->diff
) {
609 $this->formtype
= 'diff';
610 } else { # First time through
611 $this->firsttime
= true;
612 if ( $this->previewOnOpen() ) {
613 $this->formtype
= 'preview';
615 $this->formtype
= 'initial';
619 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
621 wfDebug( __METHOD__
. ": User can't edit\n" );
623 if ( $this->context
->getUser()->getBlock() ) {
624 // track block with a cookie if it doesn't exists already
625 MediaWikiServices
::getInstance()->getBlockManager()
626 ->trackBlockWithCookie( $this->context
->getUser() );
628 // Auto-block user's IP if the account was "hard" blocked
629 if ( !wfReadOnly() ) {
630 DeferredUpdates
::addCallableUpdate( function () {
631 $this->context
->getUser()->spreadAnyEditBlock();
635 $this->displayPermissionsError( $permErrors );
640 $revision = $this->mArticle
->getRevisionFetched();
641 // Disallow editing revisions with content models different from the current one
642 // Undo edits being an exception in order to allow reverting content model changes.
644 && $revision->getContentModel() !== $this->contentModel
647 if ( $this->undidRev
) {
648 $undidRevObj = Revision
::newFromId( $this->undidRev
);
649 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
651 if ( !$this->undidRev
653 ||
$prevRev->getContentModel() !== $this->contentModel
655 $this->displayViewSourcePage(
656 $this->getContentObject(),
658 'contentmodelediterror',
659 $revision->getContentModel(),
667 $this->isConflict
= false;
669 # Show applicable editing introductions
670 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
674 # Attempt submission here. This will check for edit conflicts,
675 # and redundantly check for locked database, blocked IPs, etc.
676 # that edit() already checked just in case someone tries to sneak
677 # in the back door with a hand-edited submission URL.
679 if ( $this->formtype
== 'save' ) {
680 $resultDetails = null;
681 $status = $this->attemptSave( $resultDetails );
682 if ( !$this->handleStatus( $status, $resultDetails ) ) {
687 # First time through: get contents, set time for conflict
689 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
690 if ( $this->initialiseForm() === false ) {
691 $out = $this->context
->getOutput();
692 if ( $out->getRedirect() === '' ) { // mcrundo hack redirects, don't override it
693 $this->noSuchSectionPage();
698 if ( !$this->mTitle
->getArticleID() ) {
699 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
701 Hooks
::run( 'EditFormInitialText', [ $this ] );
706 $this->showEditForm();
710 * @param string $rigor Same format as Title::getUserPermissionErrors()
713 protected function getEditPermissionErrors( $rigor = 'secure' ) {
714 $user = $this->context
->getUser();
715 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
716 # Can this title be created?
717 if ( !$this->mTitle
->exists() ) {
718 $permErrors = array_merge(
721 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
726 # Ignore some permissions errors when a user is just previewing/viewing diffs
728 foreach ( $permErrors as $error ) {
729 if ( ( $this->preview ||
$this->diff
)
731 $error[0] == 'blockedtext' ||
732 $error[0] == 'autoblockedtext' ||
733 $error[0] == 'systemblockedtext'
739 $permErrors = wfArrayDiff2( $permErrors, $remove );
745 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
746 * but with the following differences:
747 * - If redlink=1, the user will be redirected to the page
748 * - If there is content to display or the error occurs while either saving,
749 * previewing or showing the difference, it will be a
750 * "View source for ..." page displaying the source code after the error message.
753 * @param array $permErrors Array of permissions errors, as returned by
754 * Title::getUserPermissionsErrors().
755 * @throws PermissionsError
757 protected function displayPermissionsError( array $permErrors ) {
758 $out = $this->context
->getOutput();
759 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
760 // The edit page was reached via a red link.
761 // Redirect to the article page and let them click the edit tab if
762 // they really want a permission error.
763 $out->redirect( $this->mTitle
->getFullURL() );
767 $content = $this->getContentObject();
769 # Use the normal message if there's nothing to display
770 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
771 $action = $this->mTitle
->exists() ?
'edit' :
772 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
773 throw new PermissionsError( $action, $permErrors );
776 $this->displayViewSourcePage(
778 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
783 * Display a read-only View Source page
784 * @param Content $content
785 * @param string $errorMessage additional wikitext error message to display
787 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
788 $out = $this->context
->getOutput();
789 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
791 $out->setRobotPolicy( 'noindex,nofollow' );
792 $out->setPageTitle( $this->context
->msg(
794 $this->getContextTitle()->getPrefixedText()
796 $out->addBacklinkSubtitle( $this->getContextTitle() );
797 $out->addHTML( $this->editFormPageTop
);
798 $out->addHTML( $this->editFormTextTop
);
800 if ( $errorMessage !== '' ) {
801 $out->addWikiTextAsInterface( $errorMessage );
802 $out->addHTML( "<hr />\n" );
805 # If the user made changes, preserve them when showing the markup
806 # (This happens when a user is blocked during edit, for instance)
807 if ( !$this->firsttime
) {
808 $text = $this->textbox1
;
809 $out->addWikiMsg( 'viewyourtext' );
812 $text = $this->toEditText( $content );
813 } catch ( MWException
$e ) {
814 # Serialize using the default format if the content model is not supported
815 # (e.g. for an old revision with a different model)
816 $text = $content->serialize();
818 $out->addWikiMsg( 'viewsourcetext' );
821 $out->addHTML( $this->editFormTextBeforeContent
);
822 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
823 $out->addHTML( $this->editFormTextAfterContent
);
825 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
827 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
829 $out->addHTML( $this->editFormTextBottom
);
830 if ( $this->mTitle
->exists() ) {
831 $out->returnToMain( null, $this->mTitle
);
836 * Should we show a preview when the edit form is first shown?
840 protected function previewOnOpen() {
841 $config = $this->context
->getConfig();
842 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
843 $request = $this->context
->getRequest();
844 if ( $config->get( 'RawHtml' ) ) {
845 // If raw HTML is enabled, disable preview on open
846 // since it has to be posted with a token for
850 if ( $request->getVal( 'preview' ) == 'yes' ) {
851 // Explicit override from request
853 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
854 // Explicit override from request
856 } elseif ( $this->section
== 'new' ) {
857 // Nothing *to* preview for new sections
859 } elseif ( ( $request->getCheck( 'preload' ) ||
$this->mTitle
->exists() )
860 && $this->context
->getUser()->getOption( 'previewonfirst' )
862 // Standard preference behavior
864 } elseif ( !$this->mTitle
->exists()
865 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
866 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
868 // Categories are special
876 * Checks whether the user entered a skin name in uppercase,
877 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
881 protected function isWrongCaseUserConfigPage() {
882 if ( $this->mTitle
->isUserConfigPage() ) {
883 $name = $this->mTitle
->getSkinFromConfigSubpage();
884 $skins = array_merge(
885 array_keys( Skin
::getSkinNames() ),
888 return !in_array( $name, $skins )
889 && in_array( strtolower( $name ), $skins );
896 * Returns whether section editing is supported for the current page.
897 * Subclasses may override this to replace the default behavior, which is
898 * to check ContentHandler::supportsSections.
900 * @return bool True if this edit page supports sections, false otherwise.
902 protected function isSectionEditSupported() {
903 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
904 return $contentHandler->supportsSections();
908 * This function collects the form data and uses it to populate various member variables.
909 * @param WebRequest &$request
910 * @throws ErrorPageError
912 public function importFormData( &$request ) {
913 # Section edit can come from either the form or a link
914 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
916 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
917 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
920 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
922 if ( $request->wasPosted() ) {
923 # These fields need to be checked for encoding.
924 # Also remove trailing whitespace, but don't remove _initial_
925 # whitespace from the text boxes. This may be significant formatting.
926 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
927 if ( !$request->getCheck( 'wpTextbox2' ) ) {
928 // Skip this if wpTextbox2 has input, it indicates that we came
929 // from a conflict page with raw page text, not a custom form
930 // modified by subclasses
931 $textbox1 = $this->importContentFormData( $request );
932 if ( $textbox1 !== null ) {
933 $this->textbox1
= $textbox1;
937 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
939 $this->summary
= $request->getText( 'wpSummary' );
941 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
942 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
944 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
946 # Treat sectiontitle the same way as summary.
947 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
948 # currently doing double duty as both edit summary and section title. Right now this
949 # is just to allow API edits to work around this limitation, but this should be
950 # incorporated into the actual edit form when EditPage is rewritten (T20654, T28312).
951 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
952 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
954 $this->edittime
= $request->getVal( 'wpEdittime' );
955 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
956 $this->starttime
= $request->getVal( 'wpStarttime' );
958 $undidRev = $request->getInt( 'wpUndidRevision' );
960 $this->undidRev
= $undidRev;
963 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
965 if ( $this->textbox1
=== '' && !$request->getCheck( 'wpTextbox1' ) ) {
966 // wpTextbox1 field is missing, possibly due to being "too big"
967 // according to some filter rules such as Suhosin's setting for
968 // suhosin.request.max_value_length (d'oh)
969 $this->incompleteForm
= true;
971 // If we receive the last parameter of the request, we can fairly
972 // claim the POST request has not been truncated.
973 $this->incompleteForm
= !$request->getVal( 'wpUltimateParam' );
975 if ( $this->incompleteForm
) {
976 # If the form is incomplete, force to preview.
977 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
978 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
979 $this->preview
= true;
981 $this->preview
= $request->getCheck( 'wpPreview' );
982 $this->diff
= $request->getCheck( 'wpDiff' );
984 // Remember whether a save was requested, so we can indicate
985 // if we forced preview due to session failure.
986 $this->mTriedSave
= !$this->preview
;
988 if ( $this->tokenOk( $request ) ) {
989 # Some browsers will not report any submit button
990 # if the user hits enter in the comment box.
991 # The unmarked state will be assumed to be a save,
992 # if the form seems otherwise complete.
993 wfDebug( __METHOD__
. ": Passed token check.\n" );
994 } elseif ( $this->diff
) {
995 # Failed token check, but only requested "Show Changes".
996 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
998 # Page might be a hack attempt posted from
999 # an external site. Preview instead of saving.
1000 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
1001 $this->preview
= true;
1004 $this->save
= !$this->preview
&& !$this->diff
;
1005 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
1006 $this->edittime
= null;
1009 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
1010 $this->starttime
= null;
1013 $this->recreate
= $request->getCheck( 'wpRecreate' );
1015 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
1016 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
1018 $user = $this->context
->getUser();
1019 # Don't force edit summaries when a user is editing their own user or talk page
1020 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
1021 && $this->mTitle
->getText() == $user->getName()
1023 $this->allowBlankSummary
= true;
1025 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1026 ||
!$user->getOption( 'forceeditsummary' );
1029 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1031 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1032 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1034 $changeTags = $request->getVal( 'wpChangeTags' );
1035 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1036 $this->changeTags
= [];
1038 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1042 # Not a posted form? Start with nothing.
1043 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1044 $this->textbox1
= '';
1045 $this->summary
= '';
1046 $this->sectiontitle
= '';
1047 $this->edittime
= '';
1048 $this->editRevId
= null;
1049 $this->starttime
= wfTimestampNow();
1050 $this->edit
= false;
1051 $this->preview
= false;
1052 $this->save
= false;
1053 $this->diff
= false;
1054 $this->minoredit
= false;
1055 // Watch may be overridden by request parameters
1056 $this->watchthis
= $request->getBool( 'watchthis', false );
1057 $this->recreate
= false;
1059 // When creating a new section, we can preload a section title by passing it as the
1060 // preloadtitle parameter in the URL (T15100)
1061 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1062 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1063 // Once wpSummary isn't being use for setting section titles, we should delete this.
1064 $this->summary
= $request->getVal( 'preloadtitle' );
1065 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) !== '' ) {
1066 $this->summary
= $request->getText( 'summary' );
1067 if ( $this->summary
!== '' ) {
1068 $this->hasPresetSummary
= true;
1072 if ( $request->getVal( 'minor' ) ) {
1073 $this->minoredit
= true;
1077 $this->oldid
= $request->getInt( 'oldid' );
1078 $this->parentRevId
= $request->getInt( 'parentRevId' );
1080 $this->bot
= $request->getBool( 'bot', true );
1081 $this->nosummary
= $request->getBool( 'nosummary' );
1083 // May be overridden by revision.
1084 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1085 // May be overridden by revision.
1086 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1089 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1090 } catch ( MWUnknownContentModelException
$e ) {
1091 throw new ErrorPageError(
1092 'editpage-invalidcontentmodel-title',
1093 'editpage-invalidcontentmodel-text',
1094 [ wfEscapeWikiText( $this->contentModel
) ]
1098 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1099 throw new ErrorPageError(
1100 'editpage-notsupportedcontentformat-title',
1101 'editpage-notsupportedcontentformat-text',
1103 wfEscapeWikiText( $this->contentFormat
),
1104 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1110 * @todo Check if the desired model is allowed in this namespace, and if
1111 * a transition from the page's current model to the new model is
1115 $this->editintro
= $request->getText( 'editintro',
1116 // Custom edit intro for new sections
1117 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1119 // Allow extensions to modify form data
1120 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1124 * Subpage overridable method for extracting the page content data from the
1125 * posted form to be placed in $this->textbox1, if using customized input
1126 * this method should be overridden and return the page text that will be used
1127 * for saving, preview parsing and so on...
1129 * @param WebRequest &$request
1130 * @return string|null
1132 protected function importContentFormData( &$request ) {
1133 return; // Don't do anything, EditPage already extracted wpTextbox1
1137 * Initialise form fields in the object
1138 * Called on the first invocation, e.g. when a user clicks an edit link
1139 * @return bool If the requested section is valid
1141 public function initialiseForm() {
1142 $this->edittime
= $this->page
->getTimestamp();
1143 $this->editRevId
= $this->page
->getLatest();
1145 $content = $this->getContentObject( false ); # TODO: track content object?!
1146 if ( $content === false ) {
1149 $this->textbox1
= $this->toEditText( $content );
1151 $user = $this->context
->getUser();
1152 // activate checkboxes if user wants them to be always active
1153 # Sort out the "watch" checkbox
1154 if ( $user->getOption( 'watchdefault' ) ) {
1156 $this->watchthis
= true;
1157 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1159 $this->watchthis
= true;
1160 } elseif ( $user->isWatched( $this->mTitle
) ) {
1162 $this->watchthis
= true;
1164 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1165 $this->minoredit
= true;
1167 if ( $this->textbox1
=== false ) {
1174 * @param Content|null $def_content The default value to return
1176 * @return Content|null Content on success, $def_content for invalid sections
1180 protected function getContentObject( $def_content = null ) {
1183 $user = $this->context
->getUser();
1184 $request = $this->context
->getRequest();
1185 // For message page not locally set, use the i18n message.
1186 // For other non-existent articles, use preload text if any.
1187 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1188 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1189 # If this is a system message, get the default text.
1190 $msg = $this->mTitle
->getDefaultMessageText();
1192 $content = $this->toEditContent( $msg );
1194 if ( $content === false ) {
1195 # If requested, preload some text.
1196 $preload = $request->getVal( 'preload',
1197 // Custom preload text for new sections
1198 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1199 $params = $request->getArray( 'preloadparams', [] );
1201 $content = $this->getPreloadedContent( $preload, $params );
1203 // For existing pages, get text based on "undo" or section parameters.
1204 } elseif ( $this->section
!= '' ) {
1205 // Get section edit text (returns $def_text for invalid sections)
1206 $orig = $this->getOriginalContent( $user );
1207 $content = $orig ?
$orig->getSection( $this->section
) : null;
1210 $content = $def_content;
1213 $undoafter = $request->getInt( 'undoafter' );
1214 $undo = $request->getInt( 'undo' );
1216 if ( $undo > 0 && $undoafter > 0 ) {
1217 $undorev = Revision
::newFromId( $undo );
1218 $oldrev = Revision
::newFromId( $undoafter );
1221 # Sanity check, make sure it's the right page,
1222 # the revisions exist and they were not deleted.
1223 # Otherwise, $content will be left as-is.
1224 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1225 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1226 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1228 if ( WikiPage
::hasDifferencesOutsideMainSlot( $undorev, $oldrev )
1229 ||
!$this->isSupportedContentModel( $oldrev->getContentModel() )
1231 // Hack for undo while EditPage can't handle multi-slot editing
1232 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL( [
1233 'action' => 'mcrundo',
1235 'undoafter' => $undoafter,
1239 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1241 if ( $content === false ) {
1242 # Warn the user that something went wrong
1243 $undoMsg = 'failure';
1247 if ( $undoMsg === null ) {
1248 $oldContent = $this->page
->getContent( Revision
::RAW
);
1249 $popts = ParserOptions
::newFromUserAndLang(
1250 $user, MediaWikiServices
::getInstance()->getContentLanguage() );
1251 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1252 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1253 // The undo may change content
1254 // model if its reverting the top
1255 // edit. This can result in
1256 // mismatched content model/format.
1257 $this->contentModel
= $newContent->getModel();
1258 $this->contentFormat
= $oldrev->getContentFormat();
1261 if ( $newContent->equals( $oldContent ) ) {
1262 # Tell the user that the undo results in no change,
1263 # i.e. the revisions were already undone.
1264 $undoMsg = 'nochange';
1267 # Inform the user of our success and set an automatic edit summary
1268 $undoMsg = 'success';
1270 # If we just undid one rev, use an autosummary
1271 $firstrev = $oldrev->getNext();
1272 if ( $firstrev && $firstrev->getId() == $undo ) {
1273 $userText = $undorev->getUserText();
1274 if ( $userText === '' ) {
1275 $undoSummary = $this->context
->msg(
1276 'undo-summary-username-hidden',
1278 )->inContentLanguage()->text();
1280 $undoSummary = $this->context
->msg(
1284 )->inContentLanguage()->text();
1286 if ( $this->summary
=== '' ) {
1287 $this->summary
= $undoSummary;
1289 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1290 ->inContentLanguage()->text() . $this->summary
;
1292 $this->undidRev
= $undo;
1294 $this->formtype
= 'diff';
1298 // Failed basic sanity checks.
1299 // Older revisions may have been removed since the link
1300 // was created, or we may simply have got bogus input.
1304 $out = $this->context
->getOutput();
1305 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1307 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1308 $this->editFormPageTop
.= Html
::rawElement(
1309 'div', [ 'class' => $class ],
1310 $out->parseAsInterface(
1311 $this->context
->msg( 'undo-' . $undoMsg )->plain()
1316 if ( $content === false ) {
1317 // Hack for restoring old revisions while EditPage
1318 // can't handle multi-slot editing.
1320 $curRevision = $this->page
->getRevision();
1321 $oldRevision = $this->mArticle
->getRevisionFetched();
1325 && $curRevision->getId() !== $oldRevision->getId()
1326 && ( WikiPage
::hasDifferencesOutsideMainSlot( $oldRevision, $curRevision )
1327 ||
!$this->isSupportedContentModel( $oldRevision->getContentModel() ) )
1329 $this->context
->getOutput()->redirect(
1330 $this->mTitle
->getFullURL(
1332 'action' => 'mcrrestore',
1333 'restore' => $oldRevision->getId(),
1342 if ( $content === false ) {
1343 $content = $this->getOriginalContent( $user );
1351 * Get the content of the wanted revision, without section extraction.
1353 * The result of this function can be used to compare user's input with
1354 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1355 * to the original text of the edit.
1357 * This differs from Article::getContent() that when a missing revision is
1358 * encountered the result will be null and not the
1359 * 'missing-revision' message.
1362 * @param User $user The user to get the revision for
1363 * @return Content|null
1365 private function getOriginalContent( User
$user ) {
1366 if ( $this->section
== 'new' ) {
1367 return $this->getCurrentContent();
1369 $revision = $this->mArticle
->getRevisionFetched();
1370 if ( $revision === null ) {
1371 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1372 return $handler->makeEmptyContent();
1374 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1379 * Get the edit's parent revision ID
1381 * The "parent" revision is the ancestor that should be recorded in this
1382 * page's revision history. It is either the revision ID of the in-memory
1383 * article content, or in the case of a 3-way merge in order to rebase
1384 * across a recoverable edit conflict, the ID of the newer revision to
1385 * which we have rebased this page.
1388 * @return int Revision ID
1390 public function getParentRevId() {
1391 if ( $this->parentRevId
) {
1392 return $this->parentRevId
;
1394 return $this->mArticle
->getRevIdFetched();
1399 * Get the current content of the page. This is basically similar to
1400 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1401 * content object is returned instead of null.
1406 protected function getCurrentContent() {
1407 $rev = $this->page
->getRevision();
1408 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1410 if ( $content === false ||
$content === null ) {
1411 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1412 return $handler->makeEmptyContent();
1413 } elseif ( !$this->undidRev
) {
1414 // Content models should always be the same since we error
1415 // out if they are different before this point (in ->edit()).
1416 // The exception being, during an undo, the current revision might
1417 // differ from the prior revision.
1418 $logger = LoggerFactory
::getInstance( 'editpage' );
1419 if ( $this->contentModel
!== $rev->getContentModel() ) {
1420 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1421 'prev' => $this->contentModel
,
1422 'new' => $rev->getContentModel(),
1423 'title' => $this->getTitle()->getPrefixedDBkey(),
1424 'method' => __METHOD__
1426 $this->contentModel
= $rev->getContentModel();
1429 // Given that the content models should match, the current selected
1430 // format should be supported.
1431 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1432 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1434 'prev' => $this->contentFormat
,
1435 'new' => $rev->getContentFormat(),
1436 'title' => $this->getTitle()->getPrefixedDBkey(),
1437 'method' => __METHOD__
1439 $this->contentFormat
= $rev->getContentFormat();
1446 * Use this method before edit() to preload some content into the edit box
1448 * @param Content $content
1452 public function setPreloadedContent( Content
$content ) {
1453 $this->mPreloadContent
= $content;
1457 * Get the contents to be preloaded into the box, either set by
1458 * an earlier setPreloadText() or by loading the given page.
1460 * @param string $preload Representing the title to preload from.
1461 * @param array $params Parameters to use (interface-message style) in the preloaded text
1467 protected function getPreloadedContent( $preload, $params = [] ) {
1468 if ( !empty( $this->mPreloadContent
) ) {
1469 return $this->mPreloadContent
;
1472 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1474 if ( $preload === '' ) {
1475 return $handler->makeEmptyContent();
1478 $user = $this->context
->getUser();
1479 $title = Title
::newFromText( $preload );
1481 # Check for existence to avoid getting MediaWiki:Noarticletext
1482 if ( !$this->isPageExistingAndViewable( $title, $user ) ) {
1483 // TODO: somehow show a warning to the user!
1484 return $handler->makeEmptyContent();
1487 $page = WikiPage
::factory( $title );
1488 if ( $page->isRedirect() ) {
1489 $title = $page->getRedirectTarget();
1491 if ( !$this->isPageExistingAndViewable( $title, $user ) ) {
1492 // TODO: somehow show a warning to the user!
1493 return $handler->makeEmptyContent();
1495 $page = WikiPage
::factory( $title );
1498 $parserOptions = ParserOptions
::newFromUser( $user );
1499 $content = $page->getContent( Revision
::RAW
);
1502 // TODO: somehow show a warning to the user!
1503 return $handler->makeEmptyContent();
1506 if ( $content->getModel() !== $handler->getModelID() ) {
1507 $converted = $content->convert( $handler->getModelID() );
1509 if ( !$converted ) {
1510 // TODO: somehow show a warning to the user!
1511 wfDebug( "Attempt to preload incompatible content: " .
1512 "can't convert " . $content->getModel() .
1513 " to " . $handler->getModelID() );
1515 return $handler->makeEmptyContent();
1518 $content = $converted;
1521 return $content->preloadTransform( $title, $parserOptions, $params );
1525 * Verify if a given title exists and the given user is allowed to view it
1527 * @see EditPage::getPreloadedContent()
1528 * @param Title|null $title
1533 private function isPageExistingAndViewable( $title, User
$user ) {
1534 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
1536 return $title && $title->exists() && $permissionManager->userCan( 'read', $user, $title );
1540 * Make sure the form isn't faking a user's credentials.
1542 * @param WebRequest &$request
1546 public function tokenOk( &$request ) {
1547 $token = $request->getVal( 'wpEditToken' );
1548 $user = $this->context
->getUser();
1549 $this->mTokenOk
= $user->matchEditToken( $token );
1550 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1551 return $this->mTokenOk
;
1555 * Sets post-edit cookie indicating the user just saved a particular revision.
1557 * This uses a temporary cookie for each revision ID so separate saves will never
1558 * interfere with each other.
1560 * Article::view deletes the cookie on server-side after the redirect and
1561 * converts the value to the global JavaScript variable wgPostEdit.
1563 * If the variable were set on the server, it would be cached, which is unwanted
1564 * since the post-edit state should only apply to the load right after the save.
1566 * @param int $statusValue The status value (to check for new article status)
1568 protected function setPostEditCookie( $statusValue ) {
1569 $revisionId = $this->page
->getLatest();
1570 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1573 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1575 } elseif ( $this->oldid
) {
1579 $response = $this->context
->getRequest()->response();
1580 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1584 * Attempt submission
1585 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1586 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1587 * @return Status The resulting status object.
1589 public function attemptSave( &$resultDetails = false ) {
1590 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1591 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1592 // This is needed since PageUpdater no longer checks these rights!
1594 // Allow bots to exempt some edits from bot flagging
1595 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1596 $status = $this->internalAttemptSave( $resultDetails, $bot );
1598 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1604 * Log when a page was successfully saved after the edit conflict view
1606 private function incrementResolvedConflicts() {
1607 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1611 $this->getEditConflictHelper()->incrementResolvedStats();
1615 * Handle status, such as after attempt save
1617 * @param Status $status
1618 * @param array|bool $resultDetails
1620 * @throws ErrorPageError
1621 * @return bool False, if output is done, true if rest of the form should be displayed
1623 private function handleStatus( Status
$status, $resultDetails ) {
1625 * @todo FIXME: once the interface for internalAttemptSave() is made
1626 * nicer, this should use the message in $status
1628 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1629 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1631 $this->incrementResolvedConflicts();
1633 $this->didSave
= true;
1634 if ( !$resultDetails['nullEdit'] ) {
1635 $this->setPostEditCookie( $status->value
);
1639 $out = $this->context
->getOutput();
1641 // "wpExtraQueryRedirect" is a hidden input to modify
1642 // after save URL and is not used by actual edit form
1643 $request = $this->context
->getRequest();
1644 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1646 switch ( $status->value
) {
1647 case self
::AS_HOOK_ERROR_EXPECTED
:
1648 case self
::AS_CONTENT_TOO_BIG
:
1649 case self
::AS_ARTICLE_WAS_DELETED
:
1650 case self
::AS_CONFLICT_DETECTED
:
1651 case self
::AS_SUMMARY_NEEDED
:
1652 case self
::AS_TEXTBOX_EMPTY
:
1653 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1655 case self
::AS_BLANK_ARTICLE
:
1656 case self
::AS_SELF_REDIRECT
:
1659 case self
::AS_HOOK_ERROR
:
1662 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1663 case self
::AS_PARSE_ERROR
:
1664 case self
::AS_UNICODE_NOT_SUPPORTED
:
1665 $out->wrapWikiTextAsInterface( 'error', $status->getWikiText() );
1668 case self
::AS_SUCCESS_NEW_ARTICLE
:
1669 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1670 if ( $extraQueryRedirect ) {
1671 if ( $query !== '' ) {
1674 $query .= $extraQueryRedirect;
1676 $anchor = $resultDetails['sectionanchor'] ??
'';
1677 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1680 case self
::AS_SUCCESS_UPDATE
:
1682 $sectionanchor = $resultDetails['sectionanchor'];
1684 // Give extensions a chance to modify URL query on update
1686 'ArticleUpdateBeforeRedirect',
1687 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1690 if ( $resultDetails['redirect'] ) {
1691 if ( $extraQuery !== '' ) {
1692 $extraQuery = '&' . $extraQuery;
1694 $extraQuery = 'redirect=no' . $extraQuery;
1696 if ( $extraQueryRedirect ) {
1697 if ( $extraQuery !== '' ) {
1700 $extraQuery .= $extraQueryRedirect;
1703 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1706 case self
::AS_SPAM_ERROR
:
1707 $this->spamPageWithContent( $resultDetails['spam'] );
1710 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1711 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1713 case self
::AS_IMAGE_REDIRECT_ANON
:
1714 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1715 throw new PermissionsError( 'upload' );
1717 case self
::AS_READ_ONLY_PAGE_ANON
:
1718 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1719 throw new PermissionsError( 'edit' );
1721 case self
::AS_READ_ONLY_PAGE
:
1722 throw new ReadOnlyError
;
1724 case self
::AS_RATE_LIMITED
:
1725 throw new ThrottledError();
1727 case self
::AS_NO_CREATE_PERMISSION
:
1728 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1729 throw new PermissionsError( $permission );
1731 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1732 throw new PermissionsError( 'editcontentmodel' );
1735 // We don't recognize $status->value. The only way that can happen
1736 // is if an extension hook aborted from inside ArticleSave.
1737 // Render the status object into $this->hookError
1738 // FIXME this sucks, we should just use the Status object throughout
1739 $this->hookError
= '<div class="error">' . "\n" . $status->getWikiText() .
1746 * Run hooks that can filter edits just before they get saved.
1748 * @param Content $content The Content to filter.
1749 * @param Status $status For reporting the outcome to the caller
1750 * @param User $user The user performing the edit
1754 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1755 // Run old style post-section-merge edit filter
1756 if ( $this->hookError
!= '' ) {
1757 # ...or the hook could be expecting us to produce an error
1758 $status->fatal( 'hookaborted' );
1759 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1763 // Run new style post-section-merge edit filter
1764 if ( !Hooks
::run( 'EditFilterMergedContent',
1765 [ $this->context
, $content, $status, $this->summary
,
1766 $user, $this->minoredit
] )
1768 # Error messages etc. could be handled within the hook...
1769 if ( $status->isGood() ) {
1770 $status->fatal( 'hookaborted' );
1771 // Not setting $this->hookError here is a hack to allow the hook
1772 // to cause a return to the edit page without $this->hookError
1773 // being set. This is used by ConfirmEdit to display a captcha
1774 // without any error message cruft.
1776 $this->hookError
= $this->formatStatusErrors( $status );
1778 // Use the existing $status->value if the hook set it
1779 if ( !$status->value
) {
1780 $status->value
= self
::AS_HOOK_ERROR
;
1783 } elseif ( !$status->isOK() ) {
1784 # ...or the hook could be expecting us to produce an error
1785 // FIXME this sucks, we should just use the Status object throughout
1786 $this->hookError
= $this->formatStatusErrors( $status );
1787 $status->fatal( 'hookaborted' );
1788 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1796 * Wrap status errors in an errorbox for increased visibility
1798 * @param Status $status
1799 * @return string Wikitext
1801 private function formatStatusErrors( Status
$status ) {
1802 $errmsg = $status->getWikiText(
1805 $this->context
->getLanguage()
1808 <div class="errorbox">
1816 * Return the summary to be used for a new section.
1818 * @param string $sectionanchor Set to the section anchor text
1821 private function newSectionSummary( &$sectionanchor = null ) {
1822 if ( $this->sectiontitle
!== '' ) {
1823 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1824 // If no edit summary was specified, create one automatically from the section
1825 // title and have it link to the new section. Otherwise, respect the summary as
1827 if ( $this->summary
=== '' ) {
1828 $cleanSectionTitle = MediaWikiServices
::getInstance()->getParser()
1829 ->stripSectionName( $this->sectiontitle
);
1830 return $this->context
->msg( 'newsectionsummary' )
1831 ->plaintextParams( $cleanSectionTitle )->inContentLanguage()->text();
1833 } elseif ( $this->summary
!== '' ) {
1834 $sectionanchor = $this->guessSectionName( $this->summary
);
1835 # This is a new section, so create a link to the new section
1836 # in the revision summary.
1837 $cleanSummary = MediaWikiServices
::getInstance()->getParser()
1838 ->stripSectionName( $this->summary
);
1839 return $this->context
->msg( 'newsectionsummary' )
1840 ->plaintextParams( $cleanSummary )->inContentLanguage()->text();
1842 return $this->summary
;
1846 * Attempt submission (no UI)
1848 * @param array &$result Array to add statuses to, currently with the
1850 * - spam (string): Spam string from content if any spam is detected by
1852 * - sectionanchor (string): Section anchor for a section save.
1853 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1855 * - redirect (bool): Set if doEditContent is OK. True if resulting
1856 * revision is a redirect.
1857 * @param bool $bot True if edit is being made under the bot right.
1859 * @return Status Status object, possibly with a message, but always with
1860 * one of the AS_* constants in $status->value,
1862 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1863 * various error display idiosyncrasies. There are also lots of cases
1864 * where error metadata is set in the object and retrieved later instead
1865 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1866 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1869 public function internalAttemptSave( &$result, $bot = false ) {
1870 $status = Status
::newGood();
1871 $user = $this->context
->getUser();
1873 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1874 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1875 $status->fatal( 'hookaborted' );
1876 $status->value
= self
::AS_HOOK_ERROR
;
1880 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1881 $status->fatal( 'unicode-support-fail' );
1882 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1886 $request = $this->context
->getRequest();
1887 $spam = $request->getText( 'wpAntispam' );
1888 if ( $spam !== '' ) {
1893 $this->mTitle
->getPrefixedText() .
1894 '" submitted bogus field "' .
1898 $status->fatal( 'spamprotectionmatch', false );
1899 $status->value
= self
::AS_SPAM_ERROR
;
1904 # Construct Content object
1905 $textbox_content = $this->toEditContent( $this->textbox1
);
1906 } catch ( MWContentSerializationException
$ex ) {
1908 'content-failed-to-parse',
1909 $this->contentModel
,
1910 $this->contentFormat
,
1913 $status->value
= self
::AS_PARSE_ERROR
;
1917 # Check image redirect
1918 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1919 $textbox_content->isRedirect() &&
1920 !$user->isAllowed( 'upload' )
1922 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1923 $status->setResult( false, $code );
1929 $match = self
::matchSummarySpamRegex( $this->summary
);
1930 if ( $match === false && $this->section
== 'new' ) {
1931 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1932 # regular summaries, it is added to the actual wikitext.
1933 if ( $this->sectiontitle
!== '' ) {
1934 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1935 $match = self
::matchSpamRegex( $this->sectiontitle
);
1937 # This branch is taken when the "Add Topic" user interface is used, or the API
1938 # is used with the 'summary' parameter.
1939 $match = self
::matchSpamRegex( $this->summary
);
1942 if ( $match === false ) {
1943 $match = self
::matchSpamRegex( $this->textbox1
);
1945 if ( $match !== false ) {
1946 $result['spam'] = $match;
1947 $ip = $request->getIP();
1948 $pdbk = $this->mTitle
->getPrefixedDBkey();
1949 $match = str_replace( "\n", '', $match );
1950 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1951 $status->fatal( 'spamprotectionmatch', $match );
1952 $status->value
= self
::AS_SPAM_ERROR
;
1957 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1959 # Error messages etc. could be handled within the hook...
1960 $status->fatal( 'hookaborted' );
1961 $status->value
= self
::AS_HOOK_ERROR
;
1963 } elseif ( $this->hookError
!= '' ) {
1964 # ...or the hook could be expecting us to produce an error
1965 $status->fatal( 'hookaborted' );
1966 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1970 if ( $user->isBlockedFrom( $this->mTitle
) ) {
1971 // Auto-block user's IP if the account was "hard" blocked
1972 if ( !wfReadOnly() ) {
1973 $user->spreadAnyEditBlock();
1975 # Check block state against master, thus 'false'.
1976 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1980 $this->contentLength
= strlen( $this->textbox1
);
1981 $config = $this->context
->getConfig();
1982 $maxArticleSize = $config->get( 'MaxArticleSize' );
1983 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1984 // Error will be displayed by showEditForm()
1985 $this->tooBig
= true;
1986 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1990 if ( !$user->isAllowed( 'edit' ) ) {
1991 if ( $user->isAnon() ) {
1992 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1995 $status->fatal( 'readonlytext' );
1996 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
2001 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
2003 $changingContentModel = false;
2004 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
2005 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
2006 $status->fatal( 'editpage-cannot-use-custom-model' );
2007 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
2009 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
2010 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2013 // Make sure the user can edit the page under the new content model too
2014 $titleWithNewContentModel = clone $this->mTitle
;
2015 $titleWithNewContentModel->setContentModel( $this->contentModel
);
2017 $canEditModel = $permissionManager->userCan(
2020 $titleWithNewContentModel
2025 ||
!$permissionManager->userCan( 'edit', $user, $titleWithNewContentModel )
2027 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2032 $changingContentModel = true;
2033 $oldContentModel = $this->mTitle
->getContentModel();
2036 if ( $this->changeTags
) {
2037 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
2038 $this->changeTags
, $user );
2039 if ( !$changeTagsStatus->isOK() ) {
2040 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
2041 return $changeTagsStatus;
2045 if ( wfReadOnly() ) {
2046 $status->fatal( 'readonlytext' );
2047 $status->value
= self
::AS_READ_ONLY_PAGE
;
2050 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
2051 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
2053 $status->fatal( 'actionthrottledtext' );
2054 $status->value
= self
::AS_RATE_LIMITED
;
2058 # If the article has been deleted while editing, don't save it without
2060 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
2061 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
2065 # Load the page data from the master. If anything changes in the meantime,
2066 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
2067 $this->page
->loadPageData( 'fromdbmaster' );
2068 $new = !$this->page
->exists();
2071 // Late check for create permission, just in case *PARANOIA*
2072 if ( !$permissionManager->userCan( 'create', $user, $this->mTitle
) ) {
2073 $status->fatal( 'nocreatetext' );
2074 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
2075 wfDebug( __METHOD__
. ": no create permission\n" );
2079 // Don't save a new page if it's blank or if it's a MediaWiki:
2080 // message with content equivalent to default (allow empty pages
2081 // in this case to disable messages, see T52124)
2082 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2083 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
2084 $defaultText = $defaultMessageText;
2089 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
2090 $this->blankArticle
= true;
2091 $status->fatal( 'blankarticle' );
2092 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
2096 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2100 $content = $textbox_content;
2102 $result['sectionanchor'] = '';
2103 if ( $this->section
== 'new' ) {
2104 if ( $this->sectiontitle
!== '' ) {
2105 // Insert the section title above the content.
2106 $content = $content->addSectionHeader( $this->sectiontitle
);
2107 } elseif ( $this->summary
!== '' ) {
2108 // Insert the section title above the content.
2109 $content = $content->addSectionHeader( $this->summary
);
2111 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2114 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2118 # Article exists. Check for edit conflict.
2120 $this->page
->clear(); # Force reload of dates, etc.
2121 $timestamp = $this->page
->getTimestamp();
2122 $latest = $this->page
->getLatest();
2124 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2126 // An edit conflict is detected if the current revision is different from the
2127 // revision that was current when editing was initiated on the client.
2128 // This is checked based on the timestamp and revision ID.
2129 // TODO: the timestamp based check can probably go away now.
2130 if ( $timestamp != $this->edittime
2131 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2133 $this->isConflict
= true;
2134 if ( $this->section
== 'new' ) {
2135 if ( $this->page
->getUserText() == $user->getName() &&
2136 $this->page
->getComment() == $this->newSectionSummary()
2138 // Probably a duplicate submission of a new comment.
2139 // This can happen when CDN resends a request after
2140 // a timeout but the first one actually went through.
2142 . ": duplicate new section submission; trigger edit conflict!\n" );
2144 // New comment; suppress conflict.
2145 $this->isConflict
= false;
2146 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2148 } elseif ( $this->section
== ''
2149 && Revision
::userWasLastToEdit(
2150 DB_MASTER
, $this->mTitle
->getArticleID(),
2151 $user->getId(), $this->edittime
2154 # Suppress edit conflict with self, except for section edits where merging is required.
2155 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2156 $this->isConflict
= false;
2160 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2161 if ( $this->sectiontitle
!== '' ) {
2162 $sectionTitle = $this->sectiontitle
;
2164 $sectionTitle = $this->summary
;
2169 if ( $this->isConflict
) {
2171 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2172 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2173 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2174 // ...or disable section editing for non-current revisions (not exposed anyway).
2175 if ( $this->editRevId
!== null ) {
2176 $content = $this->page
->replaceSectionAtRev(
2183 $content = $this->page
->replaceSectionContent(
2191 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2192 $content = $this->page
->replaceSectionContent(
2199 if ( is_null( $content ) ) {
2200 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2201 $this->isConflict
= true;
2202 $content = $textbox_content; // do not try to merge here!
2203 } elseif ( $this->isConflict
) {
2205 if ( $this->mergeChangesIntoContent( $content ) ) {
2206 // Successful merge! Maybe we should tell the user the good news?
2207 $this->isConflict
= false;
2208 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2210 $this->section
= '';
2211 $this->textbox1
= ContentHandler
::getContentText( $content );
2212 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2216 if ( $this->isConflict
) {
2217 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2221 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2225 if ( $this->section
== 'new' ) {
2226 // Handle the user preference to force summaries here
2227 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2228 $this->missingSummary
= true;
2229 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2230 $status->value
= self
::AS_SUMMARY_NEEDED
;
2234 // Do not allow the user to post an empty comment
2235 if ( $this->textbox1
== '' ) {
2236 $this->missingComment
= true;
2237 $status->fatal( 'missingcommenttext' );
2238 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2241 } elseif ( !$this->allowBlankSummary
2242 && !$content->equals( $this->getOriginalContent( $user ) )
2243 && !$content->isRedirect()
2244 && md5( $this->summary
) == $this->autoSumm
2246 $this->missingSummary
= true;
2247 $status->fatal( 'missingsummary' );
2248 $status->value
= self
::AS_SUMMARY_NEEDED
;
2253 $sectionanchor = '';
2254 if ( $this->section
== 'new' ) {
2255 $this->summary
= $this->newSectionSummary( $sectionanchor );
2256 } elseif ( $this->section
!= '' ) {
2257 # Try to get a section anchor from the section source, redirect
2258 # to edited section if header found.
2259 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2260 # for duplicate heading checking and maybe parsing.
2261 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2262 # We can't deal with anchors, includes, html etc in the header for now,
2263 # headline would need to be parsed to improve this.
2264 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2265 $sectionanchor = $this->guessSectionName( $matches[2] );
2268 $result['sectionanchor'] = $sectionanchor;
2270 // Save errors may fall down to the edit form, but we've now
2271 // merged the section into full text. Clear the section field
2272 // so that later submission of conflict forms won't try to
2273 // replace that into a duplicated mess.
2274 $this->textbox1
= $this->toEditText( $content );
2275 $this->section
= '';
2277 $status->value
= self
::AS_SUCCESS_UPDATE
;
2280 if ( !$this->allowSelfRedirect
2281 && $content->isRedirect()
2282 && $content->getRedirectTarget()->equals( $this->getTitle() )
2284 // If the page already redirects to itself, don't warn.
2285 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2286 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2287 $this->selfRedirect
= true;
2288 $status->fatal( 'selfredirect' );
2289 $status->value
= self
::AS_SELF_REDIRECT
;
2294 // Check for length errors again now that the section is merged in
2295 $this->contentLength
= strlen( $this->toEditText( $content ) );
2296 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2297 $this->tooBig
= true;
2298 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2302 $flags = EDIT_AUTOSUMMARY |
2303 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2304 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2305 ( $bot ? EDIT_FORCE_BOT
: 0 );
2307 $doEditStatus = $this->page
->doEditContent(
2313 $content->getDefaultFormat(),
2318 if ( !$doEditStatus->isOK() ) {
2319 // Failure from doEdit()
2320 // Show the edit conflict page for certain recognized errors from doEdit(),
2321 // but don't show it for errors from extension hooks
2322 $errors = $doEditStatus->getErrorsArray();
2323 if ( in_array( $errors[0][0],
2324 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2326 $this->isConflict
= true;
2327 // Destroys data doEdit() put in $status->value but who cares
2328 $doEditStatus->value
= self
::AS_END
;
2330 return $doEditStatus;
2333 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2334 if ( $result['nullEdit'] ) {
2335 // We don't know if it was a null edit until now, so increment here
2336 $user->pingLimiter( 'linkpurge' );
2338 $result['redirect'] = $content->isRedirect();
2340 $this->updateWatchlist();
2342 // If the content model changed, add a log entry
2343 if ( $changingContentModel ) {
2344 $this->addContentModelChangeLogEntry(
2346 $new ?
false : $oldContentModel,
2347 $this->contentModel
,
2357 * @param string|false $oldModel false if the page is being newly created
2358 * @param string $newModel
2359 * @param string $reason
2361 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2362 $new = $oldModel === false;
2363 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2364 $log->setPerformer( $user );
2365 $log->setTarget( $this->mTitle
);
2366 $log->setComment( $reason );
2367 $log->setParameters( [
2368 '4::oldmodel' => $oldModel,
2369 '5::newmodel' => $newModel
2371 $logid = $log->insert();
2372 $log->publish( $logid );
2376 * Register the change of watch status
2378 protected function updateWatchlist() {
2379 $user = $this->context
->getUser();
2380 if ( !$user->isLoggedIn() ) {
2384 $title = $this->mTitle
;
2385 $watch = $this->watchthis
;
2386 // Do this in its own transaction to reduce contention...
2387 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2388 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2389 return; // nothing to change
2391 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2396 * Attempts to do 3-way merge of edit content with a base revision
2397 * and current content, in case of edit conflict, in whichever way appropriate
2398 * for the content type.
2402 * @param Content $editContent
2406 private function mergeChangesIntoContent( &$editContent ) {
2407 $db = wfGetDB( DB_MASTER
);
2409 // This is the revision that was current at the time editing was initiated on the client,
2410 // even if the edit was based on an old revision.
2411 $baseRevision = $this->getBaseRevision();
2412 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2414 if ( is_null( $baseContent ) ) {
2418 // The current state, we want to merge updates into it
2419 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2420 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2422 if ( is_null( $currentContent ) ) {
2426 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2428 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2431 $editContent = $result;
2432 // Update parentRevId to what we just merged.
2433 $this->parentRevId
= $currentRevision->getId();
2441 * Returns the revision that was current at the time editing was initiated on the client,
2442 * even if the edit was based on an old revision.
2444 * @warning this method is very poorly named. If the user opened the form with ?oldid=X,
2445 * one might think of X as the "base revision", which is NOT what this returns,
2446 * see oldid for that. One might further assume that this corresponds to the $baseRevId
2447 * parameter of WikiPage::doEditContent, which is not the case either.
2448 * getExpectedParentRevision() would perhaps be a better name.
2450 * @return Revision|null Current version when editing was initiated on the client
2452 public function getBaseRevision() {
2453 if ( !$this->mBaseRevision
) {
2454 $db = wfGetDB( DB_MASTER
);
2455 $this->mBaseRevision
= $this->editRevId
2456 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2457 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2459 return $this->mBaseRevision
;
2463 * Check given input text against $wgSpamRegex, and return the text of the first match.
2465 * @param string $text
2467 * @return string|bool Matching string or false
2469 public static function matchSpamRegex( $text ) {
2470 global $wgSpamRegex;
2471 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2472 $regexes = (array)$wgSpamRegex;
2473 return self
::matchSpamRegexInternal( $text, $regexes );
2477 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2479 * @param string $text
2481 * @return string|bool Matching string or false
2483 public static function matchSummarySpamRegex( $text ) {
2484 global $wgSummarySpamRegex;
2485 $regexes = (array)$wgSummarySpamRegex;
2486 return self
::matchSpamRegexInternal( $text, $regexes );
2490 * @param string $text
2491 * @param array $regexes
2492 * @return bool|string
2494 protected static function matchSpamRegexInternal( $text, $regexes ) {
2495 foreach ( $regexes as $regex ) {
2497 if ( preg_match( $regex, $text, $matches ) ) {
2504 public function setHeaders() {
2505 $out = $this->context
->getOutput();
2507 $out->addModules( 'mediawiki.action.edit' );
2508 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2509 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2511 $user = $this->context
->getUser();
2513 if ( $user->getOption( 'uselivepreview' ) ) {
2514 $out->addModules( 'mediawiki.action.edit.preview' );
2517 if ( $user->getOption( 'useeditwarning' ) ) {
2518 $out->addModules( 'mediawiki.action.edit.editWarning' );
2521 # Enabled article-related sidebar, toplinks, etc.
2522 $out->setArticleRelated( true );
2524 $contextTitle = $this->getContextTitle();
2525 if ( $this->isConflict
) {
2526 $msg = 'editconflict';
2527 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2528 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2530 $msg = $contextTitle->exists()
2531 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2532 && $contextTitle->getDefaultMessageText() !== false
2538 # Use the title defined by DISPLAYTITLE magic word when present
2539 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2540 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2541 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2542 if ( $displayTitle === false ) {
2543 $displayTitle = $contextTitle->getPrefixedText();
2545 $out->setDisplayTitle( $displayTitle );
2547 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2549 $config = $this->context
->getConfig();
2551 # Transmit the name of the message to JavaScript for live preview
2552 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2553 $out->addJsConfigVars( [
2554 'wgEditMessage' => $msg,
2555 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2558 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2560 $out->addJsConfigVars(
2561 'wgEditSubmitButtonLabelPublish',
2562 $config->get( 'EditSubmitButtonLabelPublish' )
2567 * Show all applicable editing introductions
2569 protected function showIntro() {
2570 if ( $this->suppressIntro
) {
2574 $out = $this->context
->getOutput();
2575 $namespace = $this->mTitle
->getNamespace();
2577 if ( $namespace == NS_MEDIAWIKI
) {
2578 # Show a warning if editing an interface message
2579 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2580 # If this is a default message (but not css, json, or js),
2581 # show a hint that it is translatable on translatewiki.net
2583 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2584 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2585 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2587 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2588 if ( $defaultMessageText !== false ) {
2589 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2590 'translateinterface' );
2593 } elseif ( $namespace == NS_FILE
) {
2594 # Show a hint to shared repo
2595 $file = wfFindFile( $this->mTitle
);
2596 if ( $file && !$file->isLocal() ) {
2597 $descUrl = $file->getDescriptionUrl();
2598 # there must be a description url to show a hint to shared repo
2600 if ( !$this->mTitle
->exists() ) {
2601 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2602 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2605 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2606 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2613 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2614 # Show log extract when the user is currently blocked
2615 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2616 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2617 $user = User
::newFromName( $username, false /* allow IP users */ );
2618 $ip = User
::isIP( $username );
2619 $block = DatabaseBlock
::newFromTarget( $user, $user );
2620 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2621 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2622 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2624 !is_null( $block ) &&
2625 $block->getType() != DatabaseBlock
::TYPE_AUTO
&&
2626 ( $block->isSitewide() ||
$user->isBlockedFrom( $this->mTitle
) )
2628 // Show log extract if the user is sitewide blocked or is partially
2629 // blocked and not allowed to edit their user page or user talk page
2630 LogEventsList
::showLogExtract(
2633 MediaWikiServices
::getInstance()->getNamespaceInfo()->
2634 getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2638 'showIfEmpty' => false,
2640 'blocked-notice-logextract',
2641 $user->getName() # Support GENDER in notice
2647 # Try to add a custom edit intro, or use the standard one if this is not possible.
2648 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2649 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2650 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2652 if ( $this->context
->getUser()->isLoggedIn() ) {
2654 // Suppress the external link icon, consider the help url an internal one
2655 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2663 // Suppress the external link icon, consider the help url an internal one
2664 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2666 'newarticletextanon',
2672 # Give a notice if the user is editing a deleted/moved page...
2673 if ( !$this->mTitle
->exists() ) {
2674 $dbr = wfGetDB( DB_REPLICA
);
2676 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2680 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2681 'showIfEmpty' => false,
2682 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2689 * Attempt to show a custom editing introduction, if supplied
2693 protected function showCustomIntro() {
2694 if ( $this->editintro
) {
2695 $title = Title
::newFromText( $this->editintro
);
2696 if ( $this->isPageExistingAndViewable( $title, $this->context
->getUser() ) ) {
2697 // Added using template syntax, to take <noinclude>'s into account.
2698 $this->context
->getOutput()->addWikiTextAsContent(
2699 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2710 * Gets an editable textual representation of $content.
2711 * The textual representation can be turned by into a Content object by the
2712 * toEditContent() method.
2714 * If $content is null or false or a string, $content is returned unchanged.
2716 * If the given Content object is not of a type that can be edited using
2717 * the text base EditPage, an exception will be raised. Set
2718 * $this->allowNonTextContent to true to allow editing of non-textual
2721 * @param Content|null|bool|string $content
2722 * @return string The editable text form of the content.
2724 * @throws MWException If $content is not an instance of TextContent and
2725 * $this->allowNonTextContent is not true.
2727 protected function toEditText( $content ) {
2728 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2732 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2733 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2736 return $content->serialize( $this->contentFormat
);
2740 * Turns the given text into a Content object by unserializing it.
2742 * If the resulting Content object is not of a type that can be edited using
2743 * the text base EditPage, an exception will be raised. Set
2744 * $this->allowNonTextContent to true to allow editing of non-textual
2747 * @param string|null|bool $text Text to unserialize
2748 * @return Content|bool|null The content object created from $text. If $text was false
2749 * or null, then false or null will be returned instead.
2751 * @throws MWException If unserializing the text results in a Content
2752 * object that is not an instance of TextContent and
2753 * $this->allowNonTextContent is not true.
2755 protected function toEditContent( $text ) {
2756 if ( $text === false ||
$text === null ) {
2760 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2761 $this->contentModel
, $this->contentFormat
);
2763 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2764 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2771 * Send the edit form and related headers to OutputPage
2772 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2773 * during form output near the top, for captchas and the like.
2775 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2776 * use the EditPage::showEditForm:fields hook instead.
2778 public function showEditForm( $formCallback = null ) {
2779 # need to parse the preview early so that we know which templates are used,
2780 # otherwise users with "show preview after edit box" will get a blank list
2781 # we parse this near the beginning so that setHeaders can do the title
2782 # setting work instead of leaving it in getPreviewText
2783 $previewOutput = '';
2784 if ( $this->formtype
== 'preview' ) {
2785 $previewOutput = $this->getPreviewText();
2788 $out = $this->context
->getOutput();
2790 // Avoid PHP 7.1 warning of passing $this by reference
2792 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2794 $this->setHeaders();
2796 $this->addTalkPageText();
2797 $this->addEditNotices();
2799 if ( !$this->isConflict
&&
2800 $this->section
!= '' &&
2801 !$this->isSectionEditSupported() ) {
2802 // We use $this->section to much before this and getVal('wgSection') directly in other places
2803 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2804 // Someone is welcome to try refactoring though
2805 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2809 $this->showHeader();
2811 $out->addHTML( $this->editFormPageTop
);
2813 $user = $this->context
->getUser();
2814 if ( $user->getOption( 'previewontop' ) ) {
2815 $this->displayPreviewArea( $previewOutput, true );
2818 $out->addHTML( $this->editFormTextTop
);
2820 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
!== 'save' ) {
2821 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2822 'deletedwhileediting' );
2825 // @todo add EditForm plugin interface and use it here!
2826 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2827 $out->addHTML( Html
::openElement(
2830 'class' => 'mw-editform',
2831 'id' => self
::EDITFORM_ID
,
2832 'name' => self
::EDITFORM_ID
,
2834 'action' => $this->getActionURL( $this->getContextTitle() ),
2835 'enctype' => 'multipart/form-data'
2839 if ( is_callable( $formCallback ) ) {
2840 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2841 call_user_func_array( $formCallback, [ &$out ] );
2844 // Add a check for Unicode support
2845 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2847 // Add an empty field to trip up spambots
2849 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2852 [ 'for' => 'wpAntispam' ],
2853 $this->context
->msg( 'simpleantispam-label' )->parse()
2859 'name' => 'wpAntispam',
2860 'id' => 'wpAntispam',
2864 . Xml
::closeElement( 'div' )
2867 // Avoid PHP 7.1 warning of passing $this by reference
2869 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2871 // Put these up at the top to ensure they aren't lost on early form submission
2872 $this->showFormBeforeText();
2874 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2875 $username = $this->lastDelete
->user_name
;
2876 $comment = CommentStore
::getStore()
2877 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2879 // It is better to not parse the comment at all than to have templates expanded in the middle
2880 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2881 $key = $comment === ''
2882 ?
'confirmrecreate-noreason'
2883 : 'confirmrecreate';
2885 '<div class="mw-confirm-recreate">' .
2886 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2887 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2888 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2894 # When the summary is hidden, also hide them on preview/show changes
2895 if ( $this->nosummary
) {
2896 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2899 # If a blank edit summary was previously provided, and the appropriate
2900 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2901 # user being bounced back more than once in the event that a summary
2904 # For a bit more sophisticated detection of blank summaries, hash the
2905 # automatic one and pass that in the hidden field wpAutoSummary.
2906 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2907 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2910 if ( $this->undidRev
) {
2911 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2914 if ( $this->selfRedirect
) {
2915 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2918 if ( $this->hasPresetSummary
) {
2919 // If a summary has been preset using &summary= we don't want to prompt for
2920 // a different summary. Only prompt for a summary if the summary is blanked.
2922 $this->autoSumm
= md5( '' );
2925 $autosumm = $this->autoSumm
!== '' ?
$this->autoSumm
: md5( $this->summary
);
2926 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2928 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2929 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2931 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2932 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2936 if ( $this->section
== 'new' ) {
2937 $this->showSummaryInput( true, $this->summary
);
2938 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2941 $out->addHTML( $this->editFormTextBeforeContent
);
2942 if ( $this->isConflict
) {
2943 // In an edit conflict, we turn textbox2 into the user's text,
2944 // and textbox1 into the stored version
2945 $this->textbox2
= $this->textbox1
;
2947 $content = $this->getCurrentContent();
2948 $this->textbox1
= $this->toEditText( $content );
2950 $editConflictHelper = $this->getEditConflictHelper();
2951 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2952 $editConflictHelper->setContentModel( $this->contentModel
);
2953 $editConflictHelper->setContentFormat( $this->contentFormat
);
2954 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2957 if ( !$this->mTitle
->isUserConfigPage() ) {
2958 $out->addHTML( self
::getEditToolbar() );
2961 if ( $this->blankArticle
) {
2962 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2965 if ( $this->isConflict
) {
2966 // In an edit conflict bypass the overridable content form method
2967 // and fallback to the raw wpTextbox1 since editconflicts can't be
2968 // resolved between page source edits and custom ui edits using the
2970 $conflictTextBoxAttribs = [];
2971 if ( $this->wasDeletedSinceLastEdit() ) {
2972 $conflictTextBoxAttribs['style'] = 'display:none;';
2973 } elseif ( $this->isOldRev
) {
2974 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2977 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2978 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2980 $this->showContentForm();
2983 $out->addHTML( $this->editFormTextAfterContent
);
2985 $this->showStandardInputs();
2987 $this->showFormAfterText();
2989 $this->showTosSummary();
2991 $this->showEditTools();
2993 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2995 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2997 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2998 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
3000 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
3001 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
3003 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
3005 if ( $this->isConflict
) {
3007 $this->showConflict();
3008 } catch ( MWContentSerializationException
$ex ) {
3009 // this can't really happen, but be nice if it does.
3010 $msg = $this->context
->msg(
3011 'content-failed-to-parse',
3012 $this->contentModel
,
3013 $this->contentFormat
,
3016 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3020 // Set a hidden field so JS knows what edit form mode we are in
3021 if ( $this->isConflict
) {
3023 } elseif ( $this->preview
) {
3025 } elseif ( $this->diff
) {
3030 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
3032 // Marker for detecting truncated form data. This must be the last
3033 // parameter sent in order to be of use, so do not move me.
3034 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
3035 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
3037 if ( !$user->getOption( 'previewontop' ) ) {
3038 $this->displayPreviewArea( $previewOutput, false );
3043 * Wrapper around TemplatesOnThisPageFormatter to make
3044 * a "templates on this page" list.
3046 * @param Title[] $templates
3047 * @return string HTML
3049 public function makeTemplatesOnThisPageList( array $templates ) {
3050 $templateListFormatter = new TemplatesOnThisPageFormatter(
3051 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
3054 // preview if preview, else section if section, else false
3056 if ( $this->preview
) {
3058 } elseif ( $this->section
!= '' ) {
3062 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
3063 $templateListFormatter->format( $templates, $type )
3068 * Extract the section title from current section text, if any.
3070 * @param string $text
3071 * @return string|bool String or false
3073 public static function extractSectionTitle( $text ) {
3074 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
3075 if ( !empty( $matches[2] ) ) {
3076 return MediaWikiServices
::getInstance()->getParser()
3077 ->stripSectionName( trim( $matches[2] ) );
3083 protected function showHeader() {
3084 $out = $this->context
->getOutput();
3085 $user = $this->context
->getUser();
3086 if ( $this->isConflict
) {
3087 $this->addExplainConflictHeader( $out );
3088 $this->editRevId
= $this->page
->getLatest();
3090 if ( $this->section
!= '' && $this->section
!= 'new' && !$this->summary
&&
3091 !$this->preview
&& !$this->diff
3093 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
3094 if ( $sectionTitle !== false ) {
3095 $this->summary
= "/* $sectionTitle */ ";
3099 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
3101 if ( $this->missingComment
) {
3102 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3105 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
3107 "<div id='mw-missingsummary'>\n$1\n</div>",
3108 [ 'missingsummary', $buttonLabel ]
3112 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3114 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3115 [ 'missingcommentheader', $buttonLabel ]
3119 if ( $this->blankArticle
) {
3121 "<div id='mw-blankarticle'>\n$1\n</div>",
3122 [ 'blankarticle', $buttonLabel ]
3126 if ( $this->selfRedirect
) {
3128 "<div id='mw-selfredirect'>\n$1\n</div>",
3129 [ 'selfredirect', $buttonLabel ]
3133 if ( $this->hookError
!== '' ) {
3134 $out->addWikiTextAsInterface( $this->hookError
);
3137 if ( $this->section
!= 'new' ) {
3138 $revision = $this->mArticle
->getRevisionFetched();
3140 // Let sysop know that this will make private content public if saved
3142 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3144 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3145 'rev-deleted-text-permission'
3147 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3149 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3150 'rev-deleted-text-view'
3154 if ( !$revision->isCurrent() ) {
3155 $this->mArticle
->setOldSubtitle( $revision->getId() );
3157 Html
::warningBox( "\n$1\n" ),
3160 $this->isOldRev
= true;
3162 } elseif ( $this->mTitle
->exists() ) {
3163 // Something went wrong
3165 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3166 [ 'missing-revision', $this->oldid
] );
3171 if ( wfReadOnly() ) {
3173 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3174 [ 'readonlywarning', wfReadOnlyReason() ]
3176 } elseif ( $user->isAnon() ) {
3177 if ( $this->formtype
!= 'preview' ) {
3178 $returntoquery = array_diff_key(
3179 $this->context
->getRequest()->getValues(),
3180 [ 'title' => true, 'returnto' => true, 'returntoquery' => true ]
3183 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3184 [ 'anoneditwarning',
3186 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3187 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3188 'returntoquery' => wfArrayToCgi( $returntoquery ),
3191 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3192 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3193 'returntoquery' => wfArrayToCgi( $returntoquery ),
3198 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3199 'anonpreviewwarning'
3202 } elseif ( $this->mTitle
->isUserConfigPage() ) {
3203 # Check the skin exists
3204 if ( $this->isWrongCaseUserConfigPage() ) {
3206 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3207 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3210 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3211 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3212 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3213 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3215 $warning = $isUserCssConfig
3217 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3219 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3221 if ( $this->formtype
!== 'preview' ) {
3222 $config = $this->context
->getConfig();
3223 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3225 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3226 [ 'usercssyoucanpreview' ]
3228 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3230 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3231 [ 'userjsonyoucanpreview' ]
3233 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3235 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3236 [ 'userjsyoucanpreview' ]
3243 $this->addPageProtectionWarningHeaders();
3245 $this->addLongPageWarningHeader();
3247 # Add header copyright warning
3248 $this->showHeaderCopyrightWarning();
3252 * Helper function for summary input functions, which returns the necessary
3253 * attributes for the input.
3255 * @param array|null $inputAttrs Array of attrs to use on the input
3258 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3259 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3260 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3261 // Unicode codepoints.
3262 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3263 'id' => 'wpSummary',
3264 'name' => 'wpSummary',
3265 'maxlength' => CommentStore
::COMMENT_CHARACTER_LIMIT
,
3268 'spellcheck' => 'true',
3273 * Builds a standard summary input with a label.
3275 * @param string $summary The value of the summary input
3276 * @param string|null $labelText The html to place inside the label
3277 * @param array|null $inputAttrs Array of attrs to use on the input
3279 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3281 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3282 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3283 $this->getSummaryInputAttributes( $inputAttrs )
3286 'title' => Linker
::titleAttrib( 'summary' ),
3287 'accessKey' => Linker
::accesskey( 'summary' ),
3290 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3291 $inputAttrs['inputId'] = $inputAttrs['id'];
3292 $inputAttrs['id'] = 'wpSummaryWidget';
3294 return new OOUI\
FieldLayout(
3295 new OOUI\
TextInputWidget( [
3296 'value' => $summary,
3297 'infusable' => true,
3300 'label' => new OOUI\
HtmlSnippet( $labelText ),
3302 'id' => 'wpSummaryLabel',
3303 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3309 * @param bool $isSubjectPreview True if this is the section subject/title
3310 * up top, or false if this is the comment summary
3311 * down below the textarea
3312 * @param string $summary The text of the summary to display
3314 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3315 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3316 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3317 if ( $isSubjectPreview ) {
3318 if ( $this->nosummary
) {
3321 } elseif ( !$this->mShowSummaryField
) {
3325 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3326 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3329 [ 'class' => $summaryClass ]
3334 * @param bool $isSubjectPreview True if this is the section subject/title
3335 * up top, or false if this is the comment summary
3336 * down below the textarea
3337 * @param string $summary The text of the summary to display
3340 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3341 // avoid spaces in preview, gets always trimmed on save
3342 $summary = trim( $summary );
3343 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3347 if ( $isSubjectPreview ) {
3348 $summary = $this->context
->msg( 'newsectionsummary' )
3349 ->rawParams( MediaWikiServices
::getInstance()->getParser()
3350 ->stripSectionName( $summary ) )
3351 ->inContentLanguage()->text();
3354 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3356 $summary = $this->context
->msg( $message )->parse()
3357 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3358 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3361 protected function showFormBeforeText() {
3362 $out = $this->context
->getOutput();
3363 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3364 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3365 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3366 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3367 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3370 protected function showFormAfterText() {
3372 * To make it harder for someone to slip a user a page
3373 * which submits an edit form to the wiki without their
3374 * knowledge, a random token is associated with the login
3375 * session. If it's not passed back with the submission,
3376 * we won't save the page, or render user JavaScript and
3379 * For anon editors, who may not have a session, we just
3380 * include the constant suffix to prevent editing from
3381 * broken text-mangling proxies.
3383 $this->context
->getOutput()->addHTML(
3385 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3391 * Subpage overridable method for printing the form for page content editing
3392 * By default this simply outputs wpTextbox1
3393 * Subclasses can override this to provide a custom UI for editing;
3394 * be it a form, or simply wpTextbox1 with a modified content that will be
3395 * reverse modified when extracted from the post data.
3396 * Note that this is basically the inverse for importContentFormData
3398 protected function showContentForm() {
3399 $this->showTextbox1();
3403 * Method to output wpTextbox1
3404 * The $textoverride method can be used by subclasses overriding showContentForm
3405 * to pass back to this method.
3407 * @param array|null $customAttribs Array of html attributes to use in the textarea
3408 * @param string|null $textoverride Optional text to override $this->textarea1 with
3410 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3411 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3412 $attribs = [ 'style' => 'display:none;' ];
3414 $builder = new TextboxBuilder();
3415 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3417 # Is an old revision being edited?
3418 if ( $this->isOldRev
) {
3419 $classes[] = 'mw-textarea-oldrev';
3422 $attribs = [ 'tabindex' => 1 ];
3424 if ( is_array( $customAttribs ) ) {
3425 $attribs +
= $customAttribs;
3428 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3432 $textoverride ??
$this->textbox1
,
3438 protected function showTextbox2() {
3439 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3442 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3443 $builder = new TextboxBuilder();
3444 $attribs = $builder->buildTextboxAttribs(
3447 $this->context
->getUser(),
3451 $this->context
->getOutput()->addHTML(
3452 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3456 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3459 $classes[] = 'ontop';
3462 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3464 if ( $this->formtype
!= 'preview' ) {
3465 $attribs['style'] = 'display: none;';
3468 $out = $this->context
->getOutput();
3469 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3471 if ( $this->formtype
== 'preview' ) {
3472 $this->showPreview( $previewOutput );
3474 // Empty content container for LivePreview
3475 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3476 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3477 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3478 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3481 $out->addHTML( '</div>' );
3483 if ( $this->formtype
== 'diff' ) {
3486 } catch ( MWContentSerializationException
$ex ) {
3487 $msg = $this->context
->msg(
3488 'content-failed-to-parse',
3489 $this->contentModel
,
3490 $this->contentFormat
,
3493 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3499 * Append preview output to OutputPage.
3500 * Includes category rendering if this is a category page.
3502 * @param string $text The HTML to be output for the preview.
3504 protected function showPreview( $text ) {
3505 if ( $this->mArticle
instanceof CategoryPage
) {
3506 $this->mArticle
->openShowCategory();
3508 # This hook seems slightly odd here, but makes things more
3509 # consistent for extensions.
3510 $out = $this->context
->getOutput();
3511 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3512 $out->addHTML( $text );
3513 if ( $this->mArticle
instanceof CategoryPage
) {
3514 $this->mArticle
->closeShowCategory();
3519 * Get a diff between the current contents of the edit box and the
3520 * version of the page we're editing from.
3522 * If this is a section edit, we'll replace the section as for final
3523 * save and then make a comparison.
3525 public function showDiff() {
3526 $oldtitlemsg = 'currentrev';
3527 # if message does not exist, show diff against the preloaded default
3528 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3529 $oldtext = $this->mTitle
->getDefaultMessageText();
3530 if ( $oldtext !== false ) {
3531 $oldtitlemsg = 'defaultmessagetext';
3532 $oldContent = $this->toEditContent( $oldtext );
3537 $oldContent = $this->getCurrentContent();
3540 $textboxContent = $this->toEditContent( $this->textbox1
);
3541 if ( $this->editRevId
!== null ) {
3542 $newContent = $this->page
->replaceSectionAtRev(
3543 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3546 $newContent = $this->page
->replaceSectionContent(
3547 $this->section
, $textboxContent, $this->summary
, $this->edittime
3551 if ( $newContent ) {
3552 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3554 $user = $this->context
->getUser();
3555 $popts = ParserOptions
::newFromUserAndLang( $user,
3556 MediaWikiServices
::getInstance()->getContentLanguage() );
3557 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3560 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3561 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3562 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3564 if ( !$oldContent ) {
3565 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3568 if ( !$newContent ) {
3569 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3572 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3573 $de->setContent( $oldContent, $newContent );
3575 $difftext = $de->getDiff( $oldtitle, $newtitle );
3576 $de->showDiffStyle();
3581 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3585 * Show the header copyright warning.
3587 protected function showHeaderCopyrightWarning() {
3588 $msg = 'editpage-head-copy-warn';
3589 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3590 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3591 'editpage-head-copy-warn' );
3596 * Give a chance for site and per-namespace customizations of
3597 * terms of service summary link that might exist separately
3598 * from the copyright notice.
3600 * This will display between the save button and the edit tools,
3601 * so should remain short!
3603 protected function showTosSummary() {
3604 $msg = 'editpage-tos-summary';
3605 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3606 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3607 $out = $this->context
->getOutput();
3608 $out->addHTML( '<div class="mw-tos-summary">' );
3609 $out->addWikiMsg( $msg );
3610 $out->addHTML( '</div>' );
3615 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3616 * characters not present on most keyboards for copying/pasting.
3618 protected function showEditTools() {
3619 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3620 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3625 * Get the copyright warning
3627 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3630 protected function getCopywarn() {
3631 return self
::getCopyrightWarning( $this->mTitle
);
3635 * Get the copyright warning, by default returns wikitext
3637 * @param Title $title
3638 * @param string $format Output format, valid values are any function of a Message object
3639 * @param Language|string|null $langcode Language code or Language object.
3642 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3643 global $wgRightsText;
3644 if ( $wgRightsText ) {
3645 $copywarnMsg = [ 'copyrightwarning',
3646 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3649 $copywarnMsg = [ 'copyrightwarning2',
3650 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3652 // Allow for site and per-namespace customization of contribution/copyright notice.
3653 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3655 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3657 $msg->inLanguage( $langcode );
3659 return "<div id=\"editpage-copywarn\">\n" .
3660 $msg->$format() . "\n</div>";
3664 * Get the Limit report for page previews
3667 * @param ParserOutput|null $output ParserOutput object from the parse
3668 * @return string HTML
3670 public static function getPreviewLimitReport( ParserOutput
$output = null ) {
3673 if ( !$output ||
!$output->getLimitReportData() ) {
3677 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3678 wfMessage( 'limitreport-title' )->parseAsBlock()
3681 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3682 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3684 $limitReport .= Html
::openElement( 'table', [
3685 'class' => 'preview-limit-report wikitable'
3687 Html
::openElement( 'tbody' );
3689 foreach ( $output->getLimitReportData() as $key => $value ) {
3690 if ( Hooks
::run( 'ParserLimitReportFormat',
3691 [ $key, &$value, &$limitReport, true, true ]
3693 $keyMsg = wfMessage( $key );
3694 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3695 if ( !$valueMsg->exists() ) {
3696 $valueMsg = new RawMessage( '$1' );
3698 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3699 $limitReport .= Html
::openElement( 'tr' ) .
3700 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3701 Html
::rawElement( 'td', null,
3702 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3704 Html
::closeElement( 'tr' );
3709 $limitReport .= Html
::closeElement( 'tbody' ) .
3710 Html
::closeElement( 'table' ) .
3711 Html
::closeElement( 'div' );
3713 return $limitReport;
3716 protected function showStandardInputs( &$tabindex = 2 ) {
3717 $out = $this->context
->getOutput();
3718 $out->addHTML( "<div class='editOptions'>\n" );
3720 if ( $this->section
!= 'new' ) {
3721 $this->showSummaryInput( false, $this->summary
);
3722 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3725 $checkboxes = $this->getCheckboxesWidget(
3727 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3729 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3731 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3733 // Show copyright warning.
3734 $out->addWikiTextAsInterface( $this->getCopywarn() );
3735 $out->addHTML( $this->editFormTextAfterWarn
);
3737 $out->addHTML( "<div class='editButtons'>\n" );
3738 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3740 $cancel = $this->getCancelLink();
3742 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3743 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3746 $this->context
->msg( 'edithelp' )->text(),
3747 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3750 $this->context
->msg( 'word-separator' )->escaped() .
3751 $this->context
->msg( 'newwindow' )->parse();
3753 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3754 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3755 $out->addHTML( "</div><!-- editButtons -->\n" );
3757 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3759 $out->addHTML( "</div><!-- editOptions -->\n" );
3763 * Show an edit conflict. textbox1 is already shown in showEditForm().
3764 * If you want to use another entry point to this function, be careful.
3766 protected function showConflict() {
3767 $out = $this->context
->getOutput();
3768 // Avoid PHP 7.1 warning of passing $this by reference
3770 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3771 $this->incrementConflictStats();
3773 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3777 protected function incrementConflictStats() {
3778 $this->getEditConflictHelper()->incrementConflictStats();
3784 public function getCancelLink() {
3786 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3787 $cancelParams['oldid'] = $this->oldid
;
3788 } elseif ( $this->getContextTitle()->isRedirect() ) {
3789 $cancelParams['redirect'] = 'no';
3792 return new OOUI\
ButtonWidget( [
3793 'id' => 'mw-editform-cancel',
3794 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3795 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3797 'infusable' => true,
3798 'flags' => 'destructive',
3803 * Returns the URL to use in the form's action attribute.
3804 * This is used by EditPage subclasses when simply customizing the action
3805 * variable in the constructor is not enough. This can be used when the
3806 * EditPage lives inside of a Special page rather than a custom page action.
3808 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3811 protected function getActionURL( Title
$title ) {
3812 return $title->getLocalURL( [ 'action' => $this->action
] );
3816 * Check if a page was deleted while the user was editing it, before submit.
3817 * Note that we rely on the logging table, which hasn't been always there,
3818 * but that doesn't matter, because this only applies to brand new
3822 protected function wasDeletedSinceLastEdit() {
3823 if ( $this->deletedSinceEdit
!== null ) {
3824 return $this->deletedSinceEdit
;
3827 $this->deletedSinceEdit
= false;
3829 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3830 $this->lastDelete
= $this->getLastDelete();
3831 if ( $this->lastDelete
) {
3832 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3833 if ( $deleteTime > $this->starttime
) {
3834 $this->deletedSinceEdit
= true;
3839 return $this->deletedSinceEdit
;
3843 * Get the last log record of this page being deleted, if ever. This is
3844 * used to detect whether a delete occurred during editing.
3845 * @return bool|stdClass
3847 protected function getLastDelete() {
3848 $dbr = wfGetDB( DB_REPLICA
);
3849 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3850 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3851 $data = $dbr->selectRow(
3852 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3862 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3864 'log_namespace' => $this->mTitle
->getNamespace(),
3865 'log_title' => $this->mTitle
->getDBkey(),
3866 'log_type' => 'delete',
3867 'log_action' => 'delete',
3870 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3872 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3873 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3875 // Quick paranoid permission checks...
3876 if ( is_object( $data ) ) {
3877 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3878 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3881 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3882 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3883 $data->log_comment_data
= null;
3891 * Get the rendered text for previewing.
3892 * @throws MWException
3895 public function getPreviewText() {
3896 $out = $this->context
->getOutput();
3897 $config = $this->context
->getConfig();
3899 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3900 // Could be an offsite preview attempt. This is very unsafe if
3901 // HTML is enabled, as it could be an attack.
3903 if ( $this->textbox1
!== '' ) {
3904 // Do not put big scary notice, if previewing the empty
3905 // string, which happens when you initially edit
3906 // a category page, due to automatic preview-on-open.
3907 $parsedNote = Html
::rawElement( 'div', [ 'class' => 'previewnote' ],
3908 $out->parseAsInterface(
3909 $this->context
->msg( 'session_fail_preview_html' )->plain()
3912 $this->incrementEditFailureStats( 'session_loss' );
3919 $content = $this->toEditContent( $this->textbox1
);
3923 'AlternateEditPreview',
3924 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3926 return $previewHTML;
3929 # provide a anchor link to the editform
3930 $continueEditing = '<span class="mw-continue-editing">' .
3931 '[[#' . self
::EDITFORM_ID
. '|' .
3932 $this->context
->getLanguage()->getArrow() . ' ' .
3933 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3934 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3935 if ( $this->mTokenOkExceptSuffix
) {
3936 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3937 $this->incrementEditFailureStats( 'bad_token' );
3939 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3940 $this->incrementEditFailureStats( 'session_loss' );
3942 } elseif ( $this->incompleteForm
) {
3943 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3944 if ( $this->mTriedSave
) {
3945 $this->incrementEditFailureStats( 'incomplete_form' );
3948 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3951 # don't parse non-wikitext pages, show message about preview
3952 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3953 if ( $this->mTitle
->isUserConfigPage() ) {
3955 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3961 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3963 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3966 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3968 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3971 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3973 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3980 # Used messages to make sure grep find them:
3981 # Messages: usercsspreview, userjsonpreview, userjspreview,
3982 # sitecsspreview, sitejsonpreview, sitejspreview
3983 if ( $level && $format ) {
3984 $note = "<div id='mw-{$level}{$format}preview'>" .
3985 $this->context
->msg( "{$level}{$format}preview" )->plain() .
3986 ' ' . $continueEditing . "</div>";
3990 # If we're adding a comment, we need to show the
3991 # summary as the headline
3992 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3993 $content = $content->addSectionHeader( $this->summary
);
3996 $hook_args = [ $this, &$content ];
3997 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3999 $parserResult = $this->doPreviewParse( $content );
4000 $parserOutput = $parserResult['parserOutput'];
4001 $previewHTML = $parserResult['html'];
4002 $this->mParserOutput
= $parserOutput;
4003 $out->addParserOutputMetadata( $parserOutput );
4004 if ( $out->userCanPreview() ) {
4005 $out->addContentOverride( $this->getTitle(), $content );
4008 if ( count( $parserOutput->getWarnings() ) ) {
4009 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
4012 } catch ( MWContentSerializationException
$ex ) {
4013 $m = $this->context
->msg(
4014 'content-failed-to-parse',
4015 $this->contentModel
,
4016 $this->contentFormat
,
4019 $note .= "\n\n" . $m->plain(); # gets parsed down below
4023 if ( $this->isConflict
) {
4024 $conflict = Html
::rawElement(
4025 'h2', [ 'id' => 'mw-previewconflict' ],
4026 $this->context
->msg( 'previewconflict' )->escaped()
4029 $conflict = '<hr />';
4032 $previewhead = Html
::rawElement(
4033 'div', [ 'class' => 'previewnote' ],
4035 'h2', [ 'id' => 'mw-previewheader' ],
4036 $this->context
->msg( 'preview' )->escaped()
4038 $out->parseAsInterface( $note ) . $conflict
4041 $pageViewLang = $this->mTitle
->getPageViewLanguage();
4042 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
4043 'class' => 'mw-content-' . $pageViewLang->getDir() ];
4044 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
4046 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
4049 private function incrementEditFailureStats( $failureType ) {
4050 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
4051 $stats->increment( 'edit.failures.' . $failureType );
4055 * Get parser options for a preview
4056 * @return ParserOptions
4058 protected function getPreviewParserOptions() {
4059 $parserOptions = $this->page
->makeParserOptions( $this->context
);
4060 $parserOptions->setIsPreview( true );
4061 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
4062 $parserOptions->enableLimitReport();
4064 // XXX: we could call $parserOptions->setCurrentRevisionCallback here to force the
4065 // current revision to be null during PST, until setupFakeRevision is called on
4066 // the ParserOptions. Currently, we rely on Parser::getRevisionObject() to ignore
4067 // existing revisions in preview mode.
4069 return $parserOptions;
4073 * Parse the page for a preview. Subclasses may override this class, in order
4074 * to parse with different options, or to otherwise modify the preview HTML.
4076 * @param Content $content The page content
4077 * @return array with keys:
4078 * - parserOutput: The ParserOutput object
4079 * - html: The HTML to be displayed
4081 protected function doPreviewParse( Content
$content ) {
4082 $user = $this->context
->getUser();
4083 $parserOptions = $this->getPreviewParserOptions();
4085 // NOTE: preSaveTransform doesn't have a fake revision to operate on.
4086 // Parser::getRevisionObject() will return null in preview mode,
4087 // causing the context user to be used for {{subst:REVISIONUSER}}.
4088 // XXX: Alternatively, we could also call setupFakeRevision() a second time:
4089 // once before PST with $content, and then after PST with $pstContent.
4090 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
4091 $scopedCallback = $parserOptions->setupFakeRevision( $this->mTitle
, $pstContent, $user );
4092 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
4093 ScopedCallback
::consume( $scopedCallback );
4095 'parserOutput' => $parserOutput,
4096 'html' => $parserOutput->getText( [
4097 'enableSectionEditLinks' => false
4105 public function getTemplates() {
4106 if ( $this->preview ||
$this->section
!= '' ) {
4108 if ( !isset( $this->mParserOutput
) ) {
4111 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
4112 foreach ( array_keys( $template ) as $dbk ) {
4113 $templates[] = Title
::makeTitle( $ns, $dbk );
4118 return $this->mTitle
->getTemplateLinksFrom();
4123 * Allow extensions to provide a toolbar.
4125 * @return string|null
4127 public static function getEditToolbar() {
4128 $startingToolbar = '<div id="toolbar"></div>';
4129 $toolbar = $startingToolbar;
4131 if ( !Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4134 // Don't add a pointless `<div>` to the page unless a hook caller populated it
4135 return ( $toolbar === $startingToolbar ) ?
null : $toolbar;
4139 * Return an array of checkbox definitions.
4141 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4143 * Array values are associative arrays with the following keys:
4144 * - 'label-message' (required): message for label text
4145 * - 'id' (required): 'id' attribute for the `<input>`
4146 * - 'default' (required): default checkedness (true or false)
4147 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4148 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4149 * from messages like 'tooltip-foo', 'accesskey-foo'
4150 * - 'label-id' (optional): 'id' attribute for the `<label>`
4151 * - 'legacy-name' (optional): short name for backwards-compatibility
4152 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4153 * where bool indicates the checked status of the checkbox
4156 public function getCheckboxesDefinition( $checked ) {
4159 $user = $this->context
->getUser();
4160 // don't show the minor edit checkbox if it's a new page or section
4161 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4162 $checkboxes['wpMinoredit'] = [
4163 'id' => 'wpMinoredit',
4164 'label-message' => 'minoredit',
4165 // Uses messages: tooltip-minoredit, accesskey-minoredit
4166 'tooltip' => 'minoredit',
4167 'label-id' => 'mw-editpage-minoredit',
4168 'legacy-name' => 'minor',
4169 'default' => $checked['minor'],
4173 if ( $user->isLoggedIn() ) {
4174 $checkboxes['wpWatchthis'] = [
4175 'id' => 'wpWatchthis',
4176 'label-message' => 'watchthis',
4177 // Uses messages: tooltip-watch, accesskey-watch
4178 'tooltip' => 'watch',
4179 'label-id' => 'mw-editpage-watch',
4180 'legacy-name' => 'watch',
4181 'default' => $checked['watch'],
4186 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4192 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4193 * any other added by extensions.
4195 * @param int &$tabindex Current tabindex
4196 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4197 * status of the checkbox
4199 * @return array Associative array of string keys to OOUI\FieldLayout instances
4201 public function getCheckboxesWidget( &$tabindex, $checked ) {
4203 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4205 foreach ( $checkboxesDef as $name => $options ) {
4206 $legacyName = $options['legacy-name'] ??
$name;
4210 if ( isset( $options['tooltip'] ) ) {
4211 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4212 $title = Linker
::titleAttrib( $options['tooltip'] );
4214 if ( isset( $options['title-message'] ) ) {
4215 $title = $this->context
->msg( $options['title-message'] )->text();
4218 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4219 new OOUI\
CheckboxInputWidget( [
4220 'tabIndex' => ++
$tabindex,
4221 'accessKey' => $accesskey,
4222 'id' => $options['id'] . 'Widget',
4223 'inputId' => $options['id'],
4225 'selected' => $options['default'],
4226 'infusable' => true,
4229 'align' => 'inline',
4230 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4232 'id' => $options['label-id'] ??
null,
4241 * Get the message key of the label for the button to save the page
4246 protected function getSubmitButtonLabel() {
4248 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4250 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4251 $newPage = !$this->mTitle
->exists();
4253 if ( $labelAsPublish ) {
4254 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4256 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4259 return $buttonLabelKey;
4263 * Returns an array of html code of the following buttons:
4264 * save, diff and preview
4266 * @param int &$tabindex Current tabindex
4270 public function getEditButtons( &$tabindex ) {
4274 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4276 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4277 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4279 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4281 'tabIndex' => ++
$tabindex,
4282 'id' => 'wpSaveWidget',
4283 'inputId' => 'wpSave',
4284 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4285 'useInputTag' => true,
4286 'flags' => [ 'progressive', 'primary' ],
4287 'label' => $buttonLabel,
4288 'infusable' => true,
4290 // Messages used: tooltip-save, tooltip-publish
4291 'title' => Linker
::titleAttrib( $buttonTooltip ),
4292 // Messages used: accesskey-save, accesskey-publish
4293 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4296 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4297 'name' => 'wpPreview',
4298 'tabIndex' => ++
$tabindex,
4299 'id' => 'wpPreviewWidget',
4300 'inputId' => 'wpPreview',
4301 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4302 'useInputTag' => true,
4303 'label' => $this->context
->msg( 'showpreview' )->text(),
4304 'infusable' => true,
4306 // Message used: tooltip-preview
4307 'title' => Linker
::titleAttrib( 'preview' ),
4308 // Message used: accesskey-preview
4309 'accessKey' => Linker
::accesskey( 'preview' ),
4312 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4314 'tabIndex' => ++
$tabindex,
4315 'id' => 'wpDiffWidget',
4316 'inputId' => 'wpDiff',
4317 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4318 'useInputTag' => true,
4319 'label' => $this->context
->msg( 'showdiff' )->text(),
4320 'infusable' => true,
4322 // Message used: tooltip-diff
4323 'title' => Linker
::titleAttrib( 'diff' ),
4324 // Message used: accesskey-diff
4325 'accessKey' => Linker
::accesskey( 'diff' ),
4328 // Avoid PHP 7.1 warning of passing $this by reference
4330 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4336 * Creates a basic error page which informs the user that
4337 * they have attempted to edit a nonexistent section.
4339 public function noSuchSectionPage() {
4340 $out = $this->context
->getOutput();
4341 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4343 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4345 // Avoid PHP 7.1 warning of passing $this by reference
4347 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4348 $out->addHTML( $res );
4350 $out->returnToMain( false, $this->mTitle
);
4354 * Show "your edit contains spam" page with your diff and text
4356 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4358 public function spamPageWithContent( $match = false ) {
4359 $this->textbox2
= $this->textbox1
;
4361 if ( is_array( $match ) ) {
4362 $match = $this->context
->getLanguage()->listToText( $match );
4364 $out = $this->context
->getOutput();
4365 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4367 $out->addHTML( '<div id="spamprotected">' );
4368 $out->addWikiMsg( 'spamprotectiontext' );
4370 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4372 $out->addHTML( '</div>' );
4374 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4377 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4378 $this->showTextbox2();
4380 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4386 protected function addEditNotices() {
4387 $out = $this->context
->getOutput();
4388 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4389 if ( count( $editNotices ) ) {
4390 $out->addHTML( implode( "\n", $editNotices ) );
4392 $msg = $this->context
->msg( 'editnotice-notext' );
4393 if ( !$msg->isDisabled() ) {
4395 '<div class="mw-editnotice-notext">'
4396 . $msg->parseAsBlock()
4406 protected function addTalkPageText() {
4407 if ( $this->mTitle
->isTalkPage() ) {
4408 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4415 protected function addLongPageWarningHeader() {
4416 if ( $this->contentLength
=== false ) {
4417 $this->contentLength
= strlen( $this->textbox1
);
4420 $out = $this->context
->getOutput();
4421 $lang = $this->context
->getLanguage();
4422 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4423 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4424 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4427 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4428 $lang->formatNum( $maxArticleSize )
4431 } elseif ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4432 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4435 $lang->formatSize( strlen( $this->textbox1
) ),
4436 strlen( $this->textbox1
)
4445 protected function addPageProtectionWarningHeaders() {
4446 $out = $this->context
->getOutput();
4447 if ( $this->mTitle
->isProtected( 'edit' ) &&
4448 MediaWikiServices
::getInstance()->getNamespaceInfo()->getRestrictionLevels(
4449 $this->mTitle
->getNamespace()
4452 # Is the title semi-protected?
4453 if ( $this->mTitle
->isSemiProtected() ) {
4454 $noticeMsg = 'semiprotectedpagewarning';
4456 # Then it must be protected based on static groups (regular)
4457 $noticeMsg = 'protectedpagewarning';
4459 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4460 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4462 if ( $this->mTitle
->isCascadeProtected() ) {
4463 # Is this page under cascading protection from some source pages?
4464 /** @var Title[] $cascadeSources */
4465 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4466 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4467 $cascadeSourcesCount = count( $cascadeSources );
4468 if ( $cascadeSourcesCount > 0 ) {
4469 # Explain, and list the titles responsible
4470 foreach ( $cascadeSources as $page ) {
4471 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4474 $notice .= '</div>';
4475 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4477 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4478 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4480 'showIfEmpty' => false,
4481 'msgKey' => [ 'titleprotectedwarning' ],
4482 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4487 * @param OutputPage $out
4490 protected function addExplainConflictHeader( OutputPage
$out ) {
4492 $this->getEditConflictHelper()->getExplainHeader()
4497 * @param string $name
4498 * @param mixed[] $customAttribs
4503 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4504 return ( new TextboxBuilder() )->buildTextboxAttribs(
4505 $name, $customAttribs, $user, $this->mTitle
4510 * @param string $wikitext
4514 protected function addNewLineAtEnd( $wikitext ) {
4515 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4519 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4520 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4521 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4522 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4523 * spread the new style links more efficiently.
4525 * @param string $text
4528 private function guessSectionName( $text ) {
4529 // Detect Microsoft browsers
4530 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4531 $parser = MediaWikiServices
::getInstance()->getParser();
4532 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4533 // ...and redirect them to legacy encoding, if available
4534 return $parser->guessLegacySectionNameFromWikiText( $text );
4536 // Meanwhile, real browsers get real anchors
4537 $name = $parser->guessSectionNameFromWikiText( $text );
4538 // With one little caveat: per T216029, fragments in HTTP redirects need to be urlencoded,
4539 // otherwise Chrome double-escapes the rest of the URL.
4540 return '#' . urlencode( mb_substr( $name, 1 ) );
4544 * Set a factory function to create an EditConflictHelper
4546 * @param callable $factory Factory function
4549 public function setEditConflictHelperFactory( callable
$factory ) {
4550 $this->editConflictHelperFactory
= $factory;
4551 $this->editConflictHelper
= null;
4555 * @return TextConflictHelper
4557 private function getEditConflictHelper() {
4558 if ( !$this->editConflictHelper
) {
4559 $this->editConflictHelper
= call_user_func(
4560 $this->editConflictHelperFactory
,
4561 $this->getSubmitButtonLabel()
4565 return $this->editConflictHelper
;
4569 * @param string $submitButtonLabel
4570 * @return TextConflictHelper
4572 private function newTextConflictHelper( $submitButtonLabel ) {
4573 return new TextConflictHelper(
4575 $this->getContext()->getOutput(),
4576 MediaWikiServices
::getInstance()->getStatsdDataFactory(),