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 * @deprecated since 1.29, call edit directly
572 public function submit() {
573 wfDeprecated( __METHOD__
, '1.29' );
578 * This is the function that gets called for "action=edit". It
579 * sets up various member variables, then passes execution to
580 * another function, usually showEditForm()
582 * The edit form is self-submitting, so that when things like
583 * preview and edit conflicts occur, we get the same form back
584 * with the extra stuff added. Only when the final submission
585 * is made and all is well do we actually save and redirect to
586 * the newly-edited page.
588 public function edit() {
589 // Allow extensions to modify/prevent this form or submission
590 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
594 wfDebug( __METHOD__
. ": enter\n" );
596 $request = $this->context
->getRequest();
597 // If they used redlink=1 and the page exists, redirect to the main article
598 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
599 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
603 $this->importFormData( $request );
604 $this->firsttime
= false;
606 if ( wfReadOnly() && $this->save
) {
609 $this->preview
= true;
613 $this->formtype
= 'save';
614 } elseif ( $this->preview
) {
615 $this->formtype
= 'preview';
616 } elseif ( $this->diff
) {
617 $this->formtype
= 'diff';
618 } else { # First time through
619 $this->firsttime
= true;
620 if ( $this->previewOnOpen() ) {
621 $this->formtype
= 'preview';
623 $this->formtype
= 'initial';
627 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
629 wfDebug( __METHOD__
. ": User can't edit\n" );
631 if ( $this->context
->getUser()->getBlock() ) {
632 // track block with a cookie if it doesn't exists already
633 $this->context
->getUser()->trackBlockWithCookie();
635 // Auto-block user's IP if the account was "hard" blocked
636 if ( !wfReadOnly() ) {
637 DeferredUpdates
::addCallableUpdate( function () {
638 $this->context
->getUser()->spreadAnyEditBlock();
642 $this->displayPermissionsError( $permErrors );
647 $revision = $this->mArticle
->getRevisionFetched();
648 // Disallow editing revisions with content models different from the current one
649 // Undo edits being an exception in order to allow reverting content model changes.
651 && $revision->getContentModel() !== $this->contentModel
654 if ( $this->undidRev
) {
655 $undidRevObj = Revision
::newFromId( $this->undidRev
);
656 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
658 if ( !$this->undidRev
660 ||
$prevRev->getContentModel() !== $this->contentModel
662 $this->displayViewSourcePage(
663 $this->getContentObject(),
665 'contentmodelediterror',
666 $revision->getContentModel(),
674 $this->isConflict
= false;
676 # Show applicable editing introductions
677 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
681 # Attempt submission here. This will check for edit conflicts,
682 # and redundantly check for locked database, blocked IPs, etc.
683 # that edit() already checked just in case someone tries to sneak
684 # in the back door with a hand-edited submission URL.
686 if ( $this->formtype
== 'save' ) {
687 $resultDetails = null;
688 $status = $this->attemptSave( $resultDetails );
689 if ( !$this->handleStatus( $status, $resultDetails ) ) {
694 # First time through: get contents, set time for conflict
696 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
697 if ( $this->initialiseForm() === false ) {
698 $out = $this->context
->getOutput();
699 if ( $out->getRedirect() === '' ) { // mcrundo hack redirects, don't override it
700 $this->noSuchSectionPage();
705 if ( !$this->mTitle
->getArticleID() ) {
706 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
708 Hooks
::run( 'EditFormInitialText', [ $this ] );
713 $this->showEditForm();
717 * @param string $rigor Same format as Title::getUserPermissionErrors()
720 protected function getEditPermissionErrors( $rigor = 'secure' ) {
721 $user = $this->context
->getUser();
722 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
723 # Can this title be created?
724 if ( !$this->mTitle
->exists() ) {
725 $permErrors = array_merge(
728 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
733 # Ignore some permissions errors when a user is just previewing/viewing diffs
735 foreach ( $permErrors as $error ) {
736 if ( ( $this->preview ||
$this->diff
)
738 $error[0] == 'blockedtext' ||
739 $error[0] == 'autoblockedtext' ||
740 $error[0] == 'systemblockedtext'
746 $permErrors = wfArrayDiff2( $permErrors, $remove );
752 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
753 * but with the following differences:
754 * - If redlink=1, the user will be redirected to the page
755 * - If there is content to display or the error occurs while either saving,
756 * previewing or showing the difference, it will be a
757 * "View source for ..." page displaying the source code after the error message.
760 * @param array $permErrors Array of permissions errors, as returned by
761 * Title::getUserPermissionsErrors().
762 * @throws PermissionsError
764 protected function displayPermissionsError( array $permErrors ) {
765 $out = $this->context
->getOutput();
766 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
767 // The edit page was reached via a red link.
768 // Redirect to the article page and let them click the edit tab if
769 // they really want a permission error.
770 $out->redirect( $this->mTitle
->getFullURL() );
774 $content = $this->getContentObject();
776 # Use the normal message if there's nothing to display
777 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
778 $action = $this->mTitle
->exists() ?
'edit' :
779 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
780 throw new PermissionsError( $action, $permErrors );
783 $this->displayViewSourcePage(
785 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
790 * Display a read-only View Source page
791 * @param Content $content
792 * @param string $errorMessage additional wikitext error message to display
794 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
795 $out = $this->context
->getOutput();
796 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
798 $out->setRobotPolicy( 'noindex,nofollow' );
799 $out->setPageTitle( $this->context
->msg(
801 $this->getContextTitle()->getPrefixedText()
803 $out->addBacklinkSubtitle( $this->getContextTitle() );
804 $out->addHTML( $this->editFormPageTop
);
805 $out->addHTML( $this->editFormTextTop
);
807 if ( $errorMessage !== '' ) {
808 $out->addWikiTextAsInterface( $errorMessage );
809 $out->addHTML( "<hr />\n" );
812 # If the user made changes, preserve them when showing the markup
813 # (This happens when a user is blocked during edit, for instance)
814 if ( !$this->firsttime
) {
815 $text = $this->textbox1
;
816 $out->addWikiMsg( 'viewyourtext' );
819 $text = $this->toEditText( $content );
820 } catch ( MWException
$e ) {
821 # Serialize using the default format if the content model is not supported
822 # (e.g. for an old revision with a different model)
823 $text = $content->serialize();
825 $out->addWikiMsg( 'viewsourcetext' );
828 $out->addHTML( $this->editFormTextBeforeContent
);
829 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
830 $out->addHTML( $this->editFormTextAfterContent
);
832 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
834 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
836 $out->addHTML( $this->editFormTextBottom
);
837 if ( $this->mTitle
->exists() ) {
838 $out->returnToMain( null, $this->mTitle
);
843 * Should we show a preview when the edit form is first shown?
847 protected function previewOnOpen() {
848 $config = $this->context
->getConfig();
849 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
850 $request = $this->context
->getRequest();
851 if ( $config->get( 'RawHtml' ) ) {
852 // If raw HTML is enabled, disable preview on open
853 // since it has to be posted with a token for
857 if ( $request->getVal( 'preview' ) == 'yes' ) {
858 // Explicit override from request
860 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
861 // Explicit override from request
863 } elseif ( $this->section
== 'new' ) {
864 // Nothing *to* preview for new sections
866 } elseif ( ( $request->getCheck( 'preload' ) ||
$this->mTitle
->exists() )
867 && $this->context
->getUser()->getOption( 'previewonfirst' )
869 // Standard preference behavior
871 } elseif ( !$this->mTitle
->exists()
872 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
873 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
875 // Categories are special
883 * Checks whether the user entered a skin name in uppercase,
884 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
888 protected function isWrongCaseUserConfigPage() {
889 if ( $this->mTitle
->isUserConfigPage() ) {
890 $name = $this->mTitle
->getSkinFromConfigSubpage();
891 $skins = array_merge(
892 array_keys( Skin
::getSkinNames() ),
895 return !in_array( $name, $skins )
896 && in_array( strtolower( $name ), $skins );
903 * Returns whether section editing is supported for the current page.
904 * Subclasses may override this to replace the default behavior, which is
905 * to check ContentHandler::supportsSections.
907 * @return bool True if this edit page supports sections, false otherwise.
909 protected function isSectionEditSupported() {
910 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
911 return $contentHandler->supportsSections();
915 * This function collects the form data and uses it to populate various member variables.
916 * @param WebRequest &$request
917 * @throws ErrorPageError
919 public function importFormData( &$request ) {
920 # Section edit can come from either the form or a link
921 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
923 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
924 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
927 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
929 if ( $request->wasPosted() ) {
930 # These fields need to be checked for encoding.
931 # Also remove trailing whitespace, but don't remove _initial_
932 # whitespace from the text boxes. This may be significant formatting.
933 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
934 if ( !$request->getCheck( 'wpTextbox2' ) ) {
935 // Skip this if wpTextbox2 has input, it indicates that we came
936 // from a conflict page with raw page text, not a custom form
937 // modified by subclasses
938 $textbox1 = $this->importContentFormData( $request );
939 if ( $textbox1 !== null ) {
940 $this->textbox1
= $textbox1;
944 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
946 $this->summary
= $request->getText( 'wpSummary' );
948 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
949 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
951 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
953 # Treat sectiontitle the same way as summary.
954 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
955 # currently doing double duty as both edit summary and section title. Right now this
956 # is just to allow API edits to work around this limitation, but this should be
957 # incorporated into the actual edit form when EditPage is rewritten (T20654, T28312).
958 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
959 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
961 $this->edittime
= $request->getVal( 'wpEdittime' );
962 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
963 $this->starttime
= $request->getVal( 'wpStarttime' );
965 $undidRev = $request->getInt( 'wpUndidRevision' );
967 $this->undidRev
= $undidRev;
970 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
972 if ( $this->textbox1
=== '' && !$request->getCheck( 'wpTextbox1' ) ) {
973 // wpTextbox1 field is missing, possibly due to being "too big"
974 // according to some filter rules such as Suhosin's setting for
975 // suhosin.request.max_value_length (d'oh)
976 $this->incompleteForm
= true;
978 // If we receive the last parameter of the request, we can fairly
979 // claim the POST request has not been truncated.
980 $this->incompleteForm
= !$request->getVal( 'wpUltimateParam' );
982 if ( $this->incompleteForm
) {
983 # If the form is incomplete, force to preview.
984 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
985 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
986 $this->preview
= true;
988 $this->preview
= $request->getCheck( 'wpPreview' );
989 $this->diff
= $request->getCheck( 'wpDiff' );
991 // Remember whether a save was requested, so we can indicate
992 // if we forced preview due to session failure.
993 $this->mTriedSave
= !$this->preview
;
995 if ( $this->tokenOk( $request ) ) {
996 # Some browsers will not report any submit button
997 # if the user hits enter in the comment box.
998 # The unmarked state will be assumed to be a save,
999 # if the form seems otherwise complete.
1000 wfDebug( __METHOD__
. ": Passed token check.\n" );
1001 } elseif ( $this->diff
) {
1002 # Failed token check, but only requested "Show Changes".
1003 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
1005 # Page might be a hack attempt posted from
1006 # an external site. Preview instead of saving.
1007 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
1008 $this->preview
= true;
1011 $this->save
= !$this->preview
&& !$this->diff
;
1012 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
1013 $this->edittime
= null;
1016 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
1017 $this->starttime
= null;
1020 $this->recreate
= $request->getCheck( 'wpRecreate' );
1022 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
1023 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
1025 $user = $this->context
->getUser();
1026 # Don't force edit summaries when a user is editing their own user or talk page
1027 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
1028 && $this->mTitle
->getText() == $user->getName()
1030 $this->allowBlankSummary
= true;
1032 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1033 ||
!$user->getOption( 'forceeditsummary' );
1036 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1038 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1039 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1041 $changeTags = $request->getVal( 'wpChangeTags' );
1042 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1043 $this->changeTags
= [];
1045 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1049 # Not a posted form? Start with nothing.
1050 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1051 $this->textbox1
= '';
1052 $this->summary
= '';
1053 $this->sectiontitle
= '';
1054 $this->edittime
= '';
1055 $this->editRevId
= null;
1056 $this->starttime
= wfTimestampNow();
1057 $this->edit
= false;
1058 $this->preview
= false;
1059 $this->save
= false;
1060 $this->diff
= false;
1061 $this->minoredit
= false;
1062 // Watch may be overridden by request parameters
1063 $this->watchthis
= $request->getBool( 'watchthis', false );
1064 $this->recreate
= false;
1066 // When creating a new section, we can preload a section title by passing it as the
1067 // preloadtitle parameter in the URL (T15100)
1068 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1069 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1070 // Once wpSummary isn't being use for setting section titles, we should delete this.
1071 $this->summary
= $request->getVal( 'preloadtitle' );
1072 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) !== '' ) {
1073 $this->summary
= $request->getText( 'summary' );
1074 if ( $this->summary
!== '' ) {
1075 $this->hasPresetSummary
= true;
1079 if ( $request->getVal( 'minor' ) ) {
1080 $this->minoredit
= true;
1084 $this->oldid
= $request->getInt( 'oldid' );
1085 $this->parentRevId
= $request->getInt( 'parentRevId' );
1087 $this->bot
= $request->getBool( 'bot', true );
1088 $this->nosummary
= $request->getBool( 'nosummary' );
1090 // May be overridden by revision.
1091 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1092 // May be overridden by revision.
1093 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1096 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1097 } catch ( MWUnknownContentModelException
$e ) {
1098 throw new ErrorPageError(
1099 'editpage-invalidcontentmodel-title',
1100 'editpage-invalidcontentmodel-text',
1101 [ wfEscapeWikiText( $this->contentModel
) ]
1105 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1106 throw new ErrorPageError(
1107 'editpage-notsupportedcontentformat-title',
1108 'editpage-notsupportedcontentformat-text',
1110 wfEscapeWikiText( $this->contentFormat
),
1111 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1117 * @todo Check if the desired model is allowed in this namespace, and if
1118 * a transition from the page's current model to the new model is
1122 $this->editintro
= $request->getText( 'editintro',
1123 // Custom edit intro for new sections
1124 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1126 // Allow extensions to modify form data
1127 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1131 * Subpage overridable method for extracting the page content data from the
1132 * posted form to be placed in $this->textbox1, if using customized input
1133 * this method should be overridden and return the page text that will be used
1134 * for saving, preview parsing and so on...
1136 * @param WebRequest &$request
1137 * @return string|null
1139 protected function importContentFormData( &$request ) {
1140 return; // Don't do anything, EditPage already extracted wpTextbox1
1144 * Initialise form fields in the object
1145 * Called on the first invocation, e.g. when a user clicks an edit link
1146 * @return bool If the requested section is valid
1148 public function initialiseForm() {
1149 $this->edittime
= $this->page
->getTimestamp();
1150 $this->editRevId
= $this->page
->getLatest();
1152 $content = $this->getContentObject( false ); # TODO: track content object?!
1153 if ( $content === false ) {
1156 $this->textbox1
= $this->toEditText( $content );
1158 $user = $this->context
->getUser();
1159 // activate checkboxes if user wants them to be always active
1160 # Sort out the "watch" checkbox
1161 if ( $user->getOption( 'watchdefault' ) ) {
1163 $this->watchthis
= true;
1164 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1166 $this->watchthis
= true;
1167 } elseif ( $user->isWatched( $this->mTitle
) ) {
1169 $this->watchthis
= true;
1171 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1172 $this->minoredit
= true;
1174 if ( $this->textbox1
=== false ) {
1181 * @param Content|null $def_content The default value to return
1183 * @return Content|null Content on success, $def_content for invalid sections
1187 protected function getContentObject( $def_content = null ) {
1190 $user = $this->context
->getUser();
1191 $request = $this->context
->getRequest();
1192 // For message page not locally set, use the i18n message.
1193 // For other non-existent articles, use preload text if any.
1194 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1195 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1196 # If this is a system message, get the default text.
1197 $msg = $this->mTitle
->getDefaultMessageText();
1199 $content = $this->toEditContent( $msg );
1201 if ( $content === false ) {
1202 # If requested, preload some text.
1203 $preload = $request->getVal( 'preload',
1204 // Custom preload text for new sections
1205 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1206 $params = $request->getArray( 'preloadparams', [] );
1208 $content = $this->getPreloadedContent( $preload, $params );
1210 // For existing pages, get text based on "undo" or section parameters.
1211 } elseif ( $this->section
!= '' ) {
1212 // Get section edit text (returns $def_text for invalid sections)
1213 $orig = $this->getOriginalContent( $user );
1214 $content = $orig ?
$orig->getSection( $this->section
) : null;
1217 $content = $def_content;
1220 $undoafter = $request->getInt( 'undoafter' );
1221 $undo = $request->getInt( 'undo' );
1223 if ( $undo > 0 && $undoafter > 0 ) {
1224 $undorev = Revision
::newFromId( $undo );
1225 $oldrev = Revision
::newFromId( $undoafter );
1228 # Sanity check, make sure it's the right page,
1229 # the revisions exist and they were not deleted.
1230 # Otherwise, $content will be left as-is.
1231 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1232 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1233 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1235 if ( WikiPage
::hasDifferencesOutsideMainSlot( $undorev, $oldrev )
1236 ||
!$this->isSupportedContentModel( $oldrev->getContentModel() )
1238 // Hack for undo while EditPage can't handle multi-slot editing
1239 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL( [
1240 'action' => 'mcrundo',
1242 'undoafter' => $undoafter,
1246 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1248 if ( $content === false ) {
1249 # Warn the user that something went wrong
1250 $undoMsg = 'failure';
1254 if ( $undoMsg === null ) {
1255 $oldContent = $this->page
->getContent( Revision
::RAW
);
1256 $popts = ParserOptions
::newFromUserAndLang(
1257 $user, MediaWikiServices
::getInstance()->getContentLanguage() );
1258 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1259 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1260 // The undo may change content
1261 // model if its reverting the top
1262 // edit. This can result in
1263 // mismatched content model/format.
1264 $this->contentModel
= $newContent->getModel();
1265 $this->contentFormat
= $oldrev->getContentFormat();
1268 if ( $newContent->equals( $oldContent ) ) {
1269 # Tell the user that the undo results in no change,
1270 # i.e. the revisions were already undone.
1271 $undoMsg = 'nochange';
1274 # Inform the user of our success and set an automatic edit summary
1275 $undoMsg = 'success';
1277 # If we just undid one rev, use an autosummary
1278 $firstrev = $oldrev->getNext();
1279 if ( $firstrev && $firstrev->getId() == $undo ) {
1280 $userText = $undorev->getUserText();
1281 if ( $userText === '' ) {
1282 $undoSummary = $this->context
->msg(
1283 'undo-summary-username-hidden',
1285 )->inContentLanguage()->text();
1287 $undoSummary = $this->context
->msg(
1291 )->inContentLanguage()->text();
1293 if ( $this->summary
=== '' ) {
1294 $this->summary
= $undoSummary;
1296 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1297 ->inContentLanguage()->text() . $this->summary
;
1299 $this->undidRev
= $undo;
1301 $this->formtype
= 'diff';
1305 // Failed basic sanity checks.
1306 // Older revisions may have been removed since the link
1307 // was created, or we may simply have got bogus input.
1311 $out = $this->context
->getOutput();
1312 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1314 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1315 $this->editFormPageTop
.= Html
::rawElement(
1316 'div', [ 'class' => $class ],
1317 $out->parseAsInterface(
1318 $this->context
->msg( 'undo-' . $undoMsg )->plain()
1323 if ( $content === false ) {
1324 // Hack for restoring old revisions while EditPage
1325 // can't handle multi-slot editing.
1327 $curRevision = $this->page
->getRevision();
1328 $oldRevision = $this->mArticle
->getRevisionFetched();
1332 && $curRevision->getId() !== $oldRevision->getId()
1333 && ( WikiPage
::hasDifferencesOutsideMainSlot( $oldRevision, $curRevision )
1334 ||
!$this->isSupportedContentModel( $oldRevision->getContentModel() ) )
1336 $this->context
->getOutput()->redirect(
1337 $this->mTitle
->getFullURL(
1339 'action' => 'mcrrestore',
1340 'restore' => $oldRevision->getId(),
1349 if ( $content === false ) {
1350 $content = $this->getOriginalContent( $user );
1358 * Get the content of the wanted revision, without section extraction.
1360 * The result of this function can be used to compare user's input with
1361 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1362 * to the original text of the edit.
1364 * This differs from Article::getContent() that when a missing revision is
1365 * encountered the result will be null and not the
1366 * 'missing-revision' message.
1369 * @param User $user The user to get the revision for
1370 * @return Content|null
1372 private function getOriginalContent( User
$user ) {
1373 if ( $this->section
== 'new' ) {
1374 return $this->getCurrentContent();
1376 $revision = $this->mArticle
->getRevisionFetched();
1377 if ( $revision === null ) {
1378 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1379 return $handler->makeEmptyContent();
1381 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1386 * Get the edit's parent revision ID
1388 * The "parent" revision is the ancestor that should be recorded in this
1389 * page's revision history. It is either the revision ID of the in-memory
1390 * article content, or in the case of a 3-way merge in order to rebase
1391 * across a recoverable edit conflict, the ID of the newer revision to
1392 * which we have rebased this page.
1395 * @return int Revision ID
1397 public function getParentRevId() {
1398 if ( $this->parentRevId
) {
1399 return $this->parentRevId
;
1401 return $this->mArticle
->getRevIdFetched();
1406 * Get the current content of the page. This is basically similar to
1407 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1408 * content object is returned instead of null.
1413 protected function getCurrentContent() {
1414 $rev = $this->page
->getRevision();
1415 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1417 if ( $content === false ||
$content === null ) {
1418 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1419 return $handler->makeEmptyContent();
1420 } elseif ( !$this->undidRev
) {
1421 // Content models should always be the same since we error
1422 // out if they are different before this point (in ->edit()).
1423 // The exception being, during an undo, the current revision might
1424 // differ from the prior revision.
1425 $logger = LoggerFactory
::getInstance( 'editpage' );
1426 if ( $this->contentModel
!== $rev->getContentModel() ) {
1427 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1428 'prev' => $this->contentModel
,
1429 'new' => $rev->getContentModel(),
1430 'title' => $this->getTitle()->getPrefixedDBkey(),
1431 'method' => __METHOD__
1433 $this->contentModel
= $rev->getContentModel();
1436 // Given that the content models should match, the current selected
1437 // format should be supported.
1438 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1439 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1441 'prev' => $this->contentFormat
,
1442 'new' => $rev->getContentFormat(),
1443 'title' => $this->getTitle()->getPrefixedDBkey(),
1444 'method' => __METHOD__
1446 $this->contentFormat
= $rev->getContentFormat();
1453 * Use this method before edit() to preload some content into the edit box
1455 * @param Content $content
1459 public function setPreloadedContent( Content
$content ) {
1460 $this->mPreloadContent
= $content;
1464 * Get the contents to be preloaded into the box, either set by
1465 * an earlier setPreloadText() or by loading the given page.
1467 * @param string $preload Representing the title to preload from.
1468 * @param array $params Parameters to use (interface-message style) in the preloaded text
1474 protected function getPreloadedContent( $preload, $params = [] ) {
1475 if ( !empty( $this->mPreloadContent
) ) {
1476 return $this->mPreloadContent
;
1479 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1481 if ( $preload === '' ) {
1482 return $handler->makeEmptyContent();
1485 $user = $this->context
->getUser();
1486 $title = Title
::newFromText( $preload );
1488 # Check for existence to avoid getting MediaWiki:Noarticletext
1489 if ( !$this->isPageExistingAndViewable( $title, $user ) ) {
1490 // TODO: somehow show a warning to the user!
1491 return $handler->makeEmptyContent();
1494 $page = WikiPage
::factory( $title );
1495 if ( $page->isRedirect() ) {
1496 $title = $page->getRedirectTarget();
1498 if ( !$this->isPageExistingAndViewable( $title, $user ) ) {
1499 // TODO: somehow show a warning to the user!
1500 return $handler->makeEmptyContent();
1502 $page = WikiPage
::factory( $title );
1505 $parserOptions = ParserOptions
::newFromUser( $user );
1506 $content = $page->getContent( Revision
::RAW
);
1509 // TODO: somehow show a warning to the user!
1510 return $handler->makeEmptyContent();
1513 if ( $content->getModel() !== $handler->getModelID() ) {
1514 $converted = $content->convert( $handler->getModelID() );
1516 if ( !$converted ) {
1517 // TODO: somehow show a warning to the user!
1518 wfDebug( "Attempt to preload incompatible content: " .
1519 "can't convert " . $content->getModel() .
1520 " to " . $handler->getModelID() );
1522 return $handler->makeEmptyContent();
1525 $content = $converted;
1528 return $content->preloadTransform( $title, $parserOptions, $params );
1532 * Verify if a given title exists and the given user is allowed to view it
1534 * @see EditPage::getPreloadedContent()
1535 * @param Title|null $title
1540 private function isPageExistingAndViewable( $title, User
$user ) {
1541 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
1543 return $title && $title->exists() && $permissionManager->userCan( 'read', $user, $title );
1547 * Make sure the form isn't faking a user's credentials.
1549 * @param WebRequest &$request
1553 public function tokenOk( &$request ) {
1554 $token = $request->getVal( 'wpEditToken' );
1555 $user = $this->context
->getUser();
1556 $this->mTokenOk
= $user->matchEditToken( $token );
1557 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1558 return $this->mTokenOk
;
1562 * Sets post-edit cookie indicating the user just saved a particular revision.
1564 * This uses a temporary cookie for each revision ID so separate saves will never
1565 * interfere with each other.
1567 * Article::view deletes the cookie on server-side after the redirect and
1568 * converts the value to the global JavaScript variable wgPostEdit.
1570 * If the variable were set on the server, it would be cached, which is unwanted
1571 * since the post-edit state should only apply to the load right after the save.
1573 * @param int $statusValue The status value (to check for new article status)
1575 protected function setPostEditCookie( $statusValue ) {
1576 $revisionId = $this->page
->getLatest();
1577 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1580 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1582 } elseif ( $this->oldid
) {
1586 $response = $this->context
->getRequest()->response();
1587 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1591 * Attempt submission
1592 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1593 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1594 * @return Status The resulting status object.
1596 public function attemptSave( &$resultDetails = false ) {
1597 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1598 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1599 // This is needed since PageUpdater no longer checks these rights!
1601 // Allow bots to exempt some edits from bot flagging
1602 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1603 $status = $this->internalAttemptSave( $resultDetails, $bot );
1605 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1611 * Log when a page was successfully saved after the edit conflict view
1613 private function incrementResolvedConflicts() {
1614 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1618 $this->getEditConflictHelper()->incrementResolvedStats();
1622 * Handle status, such as after attempt save
1624 * @param Status $status
1625 * @param array|bool $resultDetails
1627 * @throws ErrorPageError
1628 * @return bool False, if output is done, true if rest of the form should be displayed
1630 private function handleStatus( Status
$status, $resultDetails ) {
1632 * @todo FIXME: once the interface for internalAttemptSave() is made
1633 * nicer, this should use the message in $status
1635 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1636 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1638 $this->incrementResolvedConflicts();
1640 $this->didSave
= true;
1641 if ( !$resultDetails['nullEdit'] ) {
1642 $this->setPostEditCookie( $status->value
);
1646 $out = $this->context
->getOutput();
1648 // "wpExtraQueryRedirect" is a hidden input to modify
1649 // after save URL and is not used by actual edit form
1650 $request = $this->context
->getRequest();
1651 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1653 switch ( $status->value
) {
1654 case self
::AS_HOOK_ERROR_EXPECTED
:
1655 case self
::AS_CONTENT_TOO_BIG
:
1656 case self
::AS_ARTICLE_WAS_DELETED
:
1657 case self
::AS_CONFLICT_DETECTED
:
1658 case self
::AS_SUMMARY_NEEDED
:
1659 case self
::AS_TEXTBOX_EMPTY
:
1660 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1662 case self
::AS_BLANK_ARTICLE
:
1663 case self
::AS_SELF_REDIRECT
:
1666 case self
::AS_HOOK_ERROR
:
1669 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1670 case self
::AS_PARSE_ERROR
:
1671 case self
::AS_UNICODE_NOT_SUPPORTED
:
1672 $out->wrapWikiTextAsInterface( 'error', $status->getWikiText() );
1675 case self
::AS_SUCCESS_NEW_ARTICLE
:
1676 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1677 if ( $extraQueryRedirect ) {
1678 if ( $query !== '' ) {
1681 $query .= $extraQueryRedirect;
1683 $anchor = $resultDetails['sectionanchor'] ??
'';
1684 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1687 case self
::AS_SUCCESS_UPDATE
:
1689 $sectionanchor = $resultDetails['sectionanchor'];
1691 // Give extensions a chance to modify URL query on update
1693 'ArticleUpdateBeforeRedirect',
1694 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1697 if ( $resultDetails['redirect'] ) {
1698 if ( $extraQuery !== '' ) {
1699 $extraQuery = '&' . $extraQuery;
1701 $extraQuery = 'redirect=no' . $extraQuery;
1703 if ( $extraQueryRedirect ) {
1704 if ( $extraQuery !== '' ) {
1707 $extraQuery .= $extraQueryRedirect;
1710 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1713 case self
::AS_SPAM_ERROR
:
1714 $this->spamPageWithContent( $resultDetails['spam'] );
1717 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1718 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1720 case self
::AS_IMAGE_REDIRECT_ANON
:
1721 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1722 throw new PermissionsError( 'upload' );
1724 case self
::AS_READ_ONLY_PAGE_ANON
:
1725 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1726 throw new PermissionsError( 'edit' );
1728 case self
::AS_READ_ONLY_PAGE
:
1729 throw new ReadOnlyError
;
1731 case self
::AS_RATE_LIMITED
:
1732 throw new ThrottledError();
1734 case self
::AS_NO_CREATE_PERMISSION
:
1735 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1736 throw new PermissionsError( $permission );
1738 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1739 throw new PermissionsError( 'editcontentmodel' );
1742 // We don't recognize $status->value. The only way that can happen
1743 // is if an extension hook aborted from inside ArticleSave.
1744 // Render the status object into $this->hookError
1745 // FIXME this sucks, we should just use the Status object throughout
1746 $this->hookError
= '<div class="error">' . "\n" . $status->getWikiText() .
1753 * Run hooks that can filter edits just before they get saved.
1755 * @param Content $content The Content to filter.
1756 * @param Status $status For reporting the outcome to the caller
1757 * @param User $user The user performing the edit
1761 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1762 // Run old style post-section-merge edit filter
1763 if ( $this->hookError
!= '' ) {
1764 # ...or the hook could be expecting us to produce an error
1765 $status->fatal( 'hookaborted' );
1766 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1770 // Run new style post-section-merge edit filter
1771 if ( !Hooks
::run( 'EditFilterMergedContent',
1772 [ $this->context
, $content, $status, $this->summary
,
1773 $user, $this->minoredit
] )
1775 # Error messages etc. could be handled within the hook...
1776 if ( $status->isGood() ) {
1777 $status->fatal( 'hookaborted' );
1778 // Not setting $this->hookError here is a hack to allow the hook
1779 // to cause a return to the edit page without $this->hookError
1780 // being set. This is used by ConfirmEdit to display a captcha
1781 // without any error message cruft.
1783 $this->hookError
= $this->formatStatusErrors( $status );
1785 // Use the existing $status->value if the hook set it
1786 if ( !$status->value
) {
1787 $status->value
= self
::AS_HOOK_ERROR
;
1790 } elseif ( !$status->isOK() ) {
1791 # ...or the hook could be expecting us to produce an error
1792 // FIXME this sucks, we should just use the Status object throughout
1793 $this->hookError
= $this->formatStatusErrors( $status );
1794 $status->fatal( 'hookaborted' );
1795 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1803 * Wrap status errors in an errorbox for increased visibility
1805 * @param Status $status
1806 * @return string Wikitext
1808 private function formatStatusErrors( Status
$status ) {
1809 $errmsg = $status->getWikiText(
1812 $this->context
->getLanguage()
1815 <div class="errorbox">
1823 * Return the summary to be used for a new section.
1825 * @param string $sectionanchor Set to the section anchor text
1828 private function newSectionSummary( &$sectionanchor = null ) {
1829 if ( $this->sectiontitle
!== '' ) {
1830 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1831 // If no edit summary was specified, create one automatically from the section
1832 // title and have it link to the new section. Otherwise, respect the summary as
1834 if ( $this->summary
=== '' ) {
1835 $cleanSectionTitle = MediaWikiServices
::getInstance()->getParser()
1836 ->stripSectionName( $this->sectiontitle
);
1837 return $this->context
->msg( 'newsectionsummary' )
1838 ->plaintextParams( $cleanSectionTitle )->inContentLanguage()->text();
1840 } elseif ( $this->summary
!== '' ) {
1841 $sectionanchor = $this->guessSectionName( $this->summary
);
1842 # This is a new section, so create a link to the new section
1843 # in the revision summary.
1844 $cleanSummary = MediaWikiServices
::getInstance()->getParser()
1845 ->stripSectionName( $this->summary
);
1846 return $this->context
->msg( 'newsectionsummary' )
1847 ->plaintextParams( $cleanSummary )->inContentLanguage()->text();
1849 return $this->summary
;
1853 * Attempt submission (no UI)
1855 * @param array &$result Array to add statuses to, currently with the
1857 * - spam (string): Spam string from content if any spam is detected by
1859 * - sectionanchor (string): Section anchor for a section save.
1860 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1862 * - redirect (bool): Set if doEditContent is OK. True if resulting
1863 * revision is a redirect.
1864 * @param bool $bot True if edit is being made under the bot right.
1866 * @return Status Status object, possibly with a message, but always with
1867 * one of the AS_* constants in $status->value,
1869 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1870 * various error display idiosyncrasies. There are also lots of cases
1871 * where error metadata is set in the object and retrieved later instead
1872 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1873 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1876 public function internalAttemptSave( &$result, $bot = false ) {
1877 $status = Status
::newGood();
1878 $user = $this->context
->getUser();
1880 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1881 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1882 $status->fatal( 'hookaborted' );
1883 $status->value
= self
::AS_HOOK_ERROR
;
1887 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1888 $status->fatal( 'unicode-support-fail' );
1889 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1893 $request = $this->context
->getRequest();
1894 $spam = $request->getText( 'wpAntispam' );
1895 if ( $spam !== '' ) {
1900 $this->mTitle
->getPrefixedText() .
1901 '" submitted bogus field "' .
1905 $status->fatal( 'spamprotectionmatch', false );
1906 $status->value
= self
::AS_SPAM_ERROR
;
1911 # Construct Content object
1912 $textbox_content = $this->toEditContent( $this->textbox1
);
1913 } catch ( MWContentSerializationException
$ex ) {
1915 'content-failed-to-parse',
1916 $this->contentModel
,
1917 $this->contentFormat
,
1920 $status->value
= self
::AS_PARSE_ERROR
;
1924 # Check image redirect
1925 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1926 $textbox_content->isRedirect() &&
1927 !$user->isAllowed( 'upload' )
1929 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1930 $status->setResult( false, $code );
1936 $match = self
::matchSummarySpamRegex( $this->summary
);
1937 if ( $match === false && $this->section
== 'new' ) {
1938 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1939 # regular summaries, it is added to the actual wikitext.
1940 if ( $this->sectiontitle
!== '' ) {
1941 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1942 $match = self
::matchSpamRegex( $this->sectiontitle
);
1944 # This branch is taken when the "Add Topic" user interface is used, or the API
1945 # is used with the 'summary' parameter.
1946 $match = self
::matchSpamRegex( $this->summary
);
1949 if ( $match === false ) {
1950 $match = self
::matchSpamRegex( $this->textbox1
);
1952 if ( $match !== false ) {
1953 $result['spam'] = $match;
1954 $ip = $request->getIP();
1955 $pdbk = $this->mTitle
->getPrefixedDBkey();
1956 $match = str_replace( "\n", '', $match );
1957 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1958 $status->fatal( 'spamprotectionmatch', $match );
1959 $status->value
= self
::AS_SPAM_ERROR
;
1964 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1966 # Error messages etc. could be handled within the hook...
1967 $status->fatal( 'hookaborted' );
1968 $status->value
= self
::AS_HOOK_ERROR
;
1970 } elseif ( $this->hookError
!= '' ) {
1971 # ...or the hook could be expecting us to produce an error
1972 $status->fatal( 'hookaborted' );
1973 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1977 if ( $user->isBlockedFrom( $this->mTitle
) ) {
1978 // Auto-block user's IP if the account was "hard" blocked
1979 if ( !wfReadOnly() ) {
1980 $user->spreadAnyEditBlock();
1982 # Check block state against master, thus 'false'.
1983 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1987 $this->contentLength
= strlen( $this->textbox1
);
1988 $config = $this->context
->getConfig();
1989 $maxArticleSize = $config->get( 'MaxArticleSize' );
1990 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1991 // Error will be displayed by showEditForm()
1992 $this->tooBig
= true;
1993 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1997 if ( !$user->isAllowed( 'edit' ) ) {
1998 if ( $user->isAnon() ) {
1999 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
2002 $status->fatal( 'readonlytext' );
2003 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
2008 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
2010 $changingContentModel = false;
2011 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
2012 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
2013 $status->fatal( 'editpage-cannot-use-custom-model' );
2014 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
2016 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
2017 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2020 // Make sure the user can edit the page under the new content model too
2021 $titleWithNewContentModel = clone $this->mTitle
;
2022 $titleWithNewContentModel->setContentModel( $this->contentModel
);
2024 $canEditModel = $permissionManager->userCan(
2027 $titleWithNewContentModel
2032 ||
!$permissionManager->userCan( 'edit', $user, $titleWithNewContentModel )
2034 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2039 $changingContentModel = true;
2040 $oldContentModel = $this->mTitle
->getContentModel();
2043 if ( $this->changeTags
) {
2044 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
2045 $this->changeTags
, $user );
2046 if ( !$changeTagsStatus->isOK() ) {
2047 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
2048 return $changeTagsStatus;
2052 if ( wfReadOnly() ) {
2053 $status->fatal( 'readonlytext' );
2054 $status->value
= self
::AS_READ_ONLY_PAGE
;
2057 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
2058 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
2060 $status->fatal( 'actionthrottledtext' );
2061 $status->value
= self
::AS_RATE_LIMITED
;
2065 # If the article has been deleted while editing, don't save it without
2067 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
2068 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
2072 # Load the page data from the master. If anything changes in the meantime,
2073 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
2074 $this->page
->loadPageData( 'fromdbmaster' );
2075 $new = !$this->page
->exists();
2078 // Late check for create permission, just in case *PARANOIA*
2079 if ( !$permissionManager->userCan( 'create', $user, $this->mTitle
) ) {
2080 $status->fatal( 'nocreatetext' );
2081 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
2082 wfDebug( __METHOD__
. ": no create permission\n" );
2086 // Don't save a new page if it's blank or if it's a MediaWiki:
2087 // message with content equivalent to default (allow empty pages
2088 // in this case to disable messages, see T52124)
2089 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2090 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
2091 $defaultText = $defaultMessageText;
2096 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
2097 $this->blankArticle
= true;
2098 $status->fatal( 'blankarticle' );
2099 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
2103 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2107 $content = $textbox_content;
2109 $result['sectionanchor'] = '';
2110 if ( $this->section
== 'new' ) {
2111 if ( $this->sectiontitle
!== '' ) {
2112 // Insert the section title above the content.
2113 $content = $content->addSectionHeader( $this->sectiontitle
);
2114 } elseif ( $this->summary
!== '' ) {
2115 // Insert the section title above the content.
2116 $content = $content->addSectionHeader( $this->summary
);
2118 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2121 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2125 # Article exists. Check for edit conflict.
2127 $this->page
->clear(); # Force reload of dates, etc.
2128 $timestamp = $this->page
->getTimestamp();
2129 $latest = $this->page
->getLatest();
2131 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2133 // An edit conflict is detected if the current revision is different from the
2134 // revision that was current when editing was initiated on the client.
2135 // This is checked based on the timestamp and revision ID.
2136 // TODO: the timestamp based check can probably go away now.
2137 if ( $timestamp != $this->edittime
2138 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2140 $this->isConflict
= true;
2141 if ( $this->section
== 'new' ) {
2142 if ( $this->page
->getUserText() == $user->getName() &&
2143 $this->page
->getComment() == $this->newSectionSummary()
2145 // Probably a duplicate submission of a new comment.
2146 // This can happen when CDN resends a request after
2147 // a timeout but the first one actually went through.
2149 . ": duplicate new section submission; trigger edit conflict!\n" );
2151 // New comment; suppress conflict.
2152 $this->isConflict
= false;
2153 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2155 } elseif ( $this->section
== ''
2156 && Revision
::userWasLastToEdit(
2157 DB_MASTER
, $this->mTitle
->getArticleID(),
2158 $user->getId(), $this->edittime
2161 # Suppress edit conflict with self, except for section edits where merging is required.
2162 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2163 $this->isConflict
= false;
2167 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2168 if ( $this->sectiontitle
!== '' ) {
2169 $sectionTitle = $this->sectiontitle
;
2171 $sectionTitle = $this->summary
;
2176 if ( $this->isConflict
) {
2178 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2179 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2180 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2181 // ...or disable section editing for non-current revisions (not exposed anyway).
2182 if ( $this->editRevId
!== null ) {
2183 $content = $this->page
->replaceSectionAtRev(
2190 $content = $this->page
->replaceSectionContent(
2198 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2199 $content = $this->page
->replaceSectionContent(
2206 if ( is_null( $content ) ) {
2207 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2208 $this->isConflict
= true;
2209 $content = $textbox_content; // do not try to merge here!
2210 } elseif ( $this->isConflict
) {
2212 if ( $this->mergeChangesIntoContent( $content ) ) {
2213 // Successful merge! Maybe we should tell the user the good news?
2214 $this->isConflict
= false;
2215 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2217 $this->section
= '';
2218 $this->textbox1
= ContentHandler
::getContentText( $content );
2219 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2223 if ( $this->isConflict
) {
2224 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2228 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2232 if ( $this->section
== 'new' ) {
2233 // Handle the user preference to force summaries here
2234 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2235 $this->missingSummary
= true;
2236 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2237 $status->value
= self
::AS_SUMMARY_NEEDED
;
2241 // Do not allow the user to post an empty comment
2242 if ( $this->textbox1
== '' ) {
2243 $this->missingComment
= true;
2244 $status->fatal( 'missingcommenttext' );
2245 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2248 } elseif ( !$this->allowBlankSummary
2249 && !$content->equals( $this->getOriginalContent( $user ) )
2250 && !$content->isRedirect()
2251 && md5( $this->summary
) == $this->autoSumm
2253 $this->missingSummary
= true;
2254 $status->fatal( 'missingsummary' );
2255 $status->value
= self
::AS_SUMMARY_NEEDED
;
2260 $sectionanchor = '';
2261 if ( $this->section
== 'new' ) {
2262 $this->summary
= $this->newSectionSummary( $sectionanchor );
2263 } elseif ( $this->section
!= '' ) {
2264 # Try to get a section anchor from the section source, redirect
2265 # to edited section if header found.
2266 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2267 # for duplicate heading checking and maybe parsing.
2268 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2269 # We can't deal with anchors, includes, html etc in the header for now,
2270 # headline would need to be parsed to improve this.
2271 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2272 $sectionanchor = $this->guessSectionName( $matches[2] );
2275 $result['sectionanchor'] = $sectionanchor;
2277 // Save errors may fall down to the edit form, but we've now
2278 // merged the section into full text. Clear the section field
2279 // so that later submission of conflict forms won't try to
2280 // replace that into a duplicated mess.
2281 $this->textbox1
= $this->toEditText( $content );
2282 $this->section
= '';
2284 $status->value
= self
::AS_SUCCESS_UPDATE
;
2287 if ( !$this->allowSelfRedirect
2288 && $content->isRedirect()
2289 && $content->getRedirectTarget()->equals( $this->getTitle() )
2291 // If the page already redirects to itself, don't warn.
2292 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2293 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2294 $this->selfRedirect
= true;
2295 $status->fatal( 'selfredirect' );
2296 $status->value
= self
::AS_SELF_REDIRECT
;
2301 // Check for length errors again now that the section is merged in
2302 $this->contentLength
= strlen( $this->toEditText( $content ) );
2303 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2304 $this->tooBig
= true;
2305 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2309 $flags = EDIT_AUTOSUMMARY |
2310 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2311 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2312 ( $bot ? EDIT_FORCE_BOT
: 0 );
2314 $doEditStatus = $this->page
->doEditContent(
2320 $content->getDefaultFormat(),
2325 if ( !$doEditStatus->isOK() ) {
2326 // Failure from doEdit()
2327 // Show the edit conflict page for certain recognized errors from doEdit(),
2328 // but don't show it for errors from extension hooks
2329 $errors = $doEditStatus->getErrorsArray();
2330 if ( in_array( $errors[0][0],
2331 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2333 $this->isConflict
= true;
2334 // Destroys data doEdit() put in $status->value but who cares
2335 $doEditStatus->value
= self
::AS_END
;
2337 return $doEditStatus;
2340 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2341 if ( $result['nullEdit'] ) {
2342 // We don't know if it was a null edit until now, so increment here
2343 $user->pingLimiter( 'linkpurge' );
2345 $result['redirect'] = $content->isRedirect();
2347 $this->updateWatchlist();
2349 // If the content model changed, add a log entry
2350 if ( $changingContentModel ) {
2351 $this->addContentModelChangeLogEntry(
2353 $new ?
false : $oldContentModel,
2354 $this->contentModel
,
2364 * @param string|false $oldModel false if the page is being newly created
2365 * @param string $newModel
2366 * @param string $reason
2368 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2369 $new = $oldModel === false;
2370 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2371 $log->setPerformer( $user );
2372 $log->setTarget( $this->mTitle
);
2373 $log->setComment( $reason );
2374 $log->setParameters( [
2375 '4::oldmodel' => $oldModel,
2376 '5::newmodel' => $newModel
2378 $logid = $log->insert();
2379 $log->publish( $logid );
2383 * Register the change of watch status
2385 protected function updateWatchlist() {
2386 $user = $this->context
->getUser();
2387 if ( !$user->isLoggedIn() ) {
2391 $title = $this->mTitle
;
2392 $watch = $this->watchthis
;
2393 // Do this in its own transaction to reduce contention...
2394 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2395 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2396 return; // nothing to change
2398 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2403 * Attempts to do 3-way merge of edit content with a base revision
2404 * and current content, in case of edit conflict, in whichever way appropriate
2405 * for the content type.
2409 * @param Content $editContent
2413 private function mergeChangesIntoContent( &$editContent ) {
2414 $db = wfGetDB( DB_MASTER
);
2416 // This is the revision that was current at the time editing was initiated on the client,
2417 // even if the edit was based on an old revision.
2418 $baseRevision = $this->getBaseRevision();
2419 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2421 if ( is_null( $baseContent ) ) {
2425 // The current state, we want to merge updates into it
2426 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2427 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2429 if ( is_null( $currentContent ) ) {
2433 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2435 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2438 $editContent = $result;
2439 // Update parentRevId to what we just merged.
2440 $this->parentRevId
= $currentRevision->getId();
2448 * Returns the revision that was current at the time editing was initiated on the client,
2449 * even if the edit was based on an old revision.
2451 * @warning this method is very poorly named. If the user opened the form with ?oldid=X,
2452 * one might think of X as the "base revision", which is NOT what this returns,
2453 * see oldid for that. One might further assume that this corresponds to the $baseRevId
2454 * parameter of WikiPage::doEditContent, which is not the case either.
2455 * getExpectedParentRevision() would perhaps be a better name.
2457 * @return Revision|null Current version when editing was initiated on the client
2459 public function getBaseRevision() {
2460 if ( !$this->mBaseRevision
) {
2461 $db = wfGetDB( DB_MASTER
);
2462 $this->mBaseRevision
= $this->editRevId
2463 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2464 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2466 return $this->mBaseRevision
;
2470 * Check given input text against $wgSpamRegex, and return the text of the first match.
2472 * @param string $text
2474 * @return string|bool Matching string or false
2476 public static function matchSpamRegex( $text ) {
2477 global $wgSpamRegex;
2478 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2479 $regexes = (array)$wgSpamRegex;
2480 return self
::matchSpamRegexInternal( $text, $regexes );
2484 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2486 * @param string $text
2488 * @return string|bool Matching string or false
2490 public static function matchSummarySpamRegex( $text ) {
2491 global $wgSummarySpamRegex;
2492 $regexes = (array)$wgSummarySpamRegex;
2493 return self
::matchSpamRegexInternal( $text, $regexes );
2497 * @param string $text
2498 * @param array $regexes
2499 * @return bool|string
2501 protected static function matchSpamRegexInternal( $text, $regexes ) {
2502 foreach ( $regexes as $regex ) {
2504 if ( preg_match( $regex, $text, $matches ) ) {
2511 public function setHeaders() {
2512 $out = $this->context
->getOutput();
2514 $out->addModules( 'mediawiki.action.edit' );
2515 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2516 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2518 $user = $this->context
->getUser();
2520 if ( $user->getOption( 'uselivepreview' ) ) {
2521 $out->addModules( 'mediawiki.action.edit.preview' );
2524 if ( $user->getOption( 'useeditwarning' ) ) {
2525 $out->addModules( 'mediawiki.action.edit.editWarning' );
2528 # Enabled article-related sidebar, toplinks, etc.
2529 $out->setArticleRelated( true );
2531 $contextTitle = $this->getContextTitle();
2532 if ( $this->isConflict
) {
2533 $msg = 'editconflict';
2534 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2535 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2537 $msg = $contextTitle->exists()
2538 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2539 && $contextTitle->getDefaultMessageText() !== false
2545 # Use the title defined by DISPLAYTITLE magic word when present
2546 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2547 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2548 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2549 if ( $displayTitle === false ) {
2550 $displayTitle = $contextTitle->getPrefixedText();
2552 $out->setDisplayTitle( $displayTitle );
2554 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2556 $config = $this->context
->getConfig();
2558 # Transmit the name of the message to JavaScript for live preview
2559 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2560 $out->addJsConfigVars( [
2561 'wgEditMessage' => $msg,
2562 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2565 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2567 $out->addJsConfigVars(
2568 'wgEditSubmitButtonLabelPublish',
2569 $config->get( 'EditSubmitButtonLabelPublish' )
2574 * Show all applicable editing introductions
2576 protected function showIntro() {
2577 if ( $this->suppressIntro
) {
2581 $out = $this->context
->getOutput();
2582 $namespace = $this->mTitle
->getNamespace();
2584 if ( $namespace == NS_MEDIAWIKI
) {
2585 # Show a warning if editing an interface message
2586 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2587 # If this is a default message (but not css, json, or js),
2588 # show a hint that it is translatable on translatewiki.net
2590 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2591 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2592 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2594 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2595 if ( $defaultMessageText !== false ) {
2596 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2597 'translateinterface' );
2600 } elseif ( $namespace == NS_FILE
) {
2601 # Show a hint to shared repo
2602 $file = wfFindFile( $this->mTitle
);
2603 if ( $file && !$file->isLocal() ) {
2604 $descUrl = $file->getDescriptionUrl();
2605 # there must be a description url to show a hint to shared repo
2607 if ( !$this->mTitle
->exists() ) {
2608 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2609 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2612 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2613 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2620 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2621 # Show log extract when the user is currently blocked
2622 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2623 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2624 $user = User
::newFromName( $username, false /* allow IP users */ );
2625 $ip = User
::isIP( $username );
2626 $block = DatabaseBlock
::newFromTarget( $user, $user );
2627 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2628 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2629 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2631 !is_null( $block ) &&
2632 $block->getType() != DatabaseBlock
::TYPE_AUTO
&&
2633 ( $block->isSitewide() ||
$user->isBlockedFrom( $this->mTitle
) )
2635 // Show log extract if the user is sitewide blocked or is partially
2636 // blocked and not allowed to edit their user page or user talk page
2637 LogEventsList
::showLogExtract(
2640 MediaWikiServices
::getInstance()->getNamespaceInfo()->
2641 getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2645 'showIfEmpty' => false,
2647 'blocked-notice-logextract',
2648 $user->getName() # Support GENDER in notice
2654 # Try to add a custom edit intro, or use the standard one if this is not possible.
2655 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2656 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2657 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2659 if ( $this->context
->getUser()->isLoggedIn() ) {
2661 // Suppress the external link icon, consider the help url an internal one
2662 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2670 // Suppress the external link icon, consider the help url an internal one
2671 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2673 'newarticletextanon',
2679 # Give a notice if the user is editing a deleted/moved page...
2680 if ( !$this->mTitle
->exists() ) {
2681 $dbr = wfGetDB( DB_REPLICA
);
2683 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2687 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2688 'showIfEmpty' => false,
2689 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2696 * Attempt to show a custom editing introduction, if supplied
2700 protected function showCustomIntro() {
2701 if ( $this->editintro
) {
2702 $title = Title
::newFromText( $this->editintro
);
2703 if ( $this->isPageExistingAndViewable( $title, $this->context
->getUser() ) ) {
2704 // Added using template syntax, to take <noinclude>'s into account.
2705 $this->context
->getOutput()->addWikiTextAsContent(
2706 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2717 * Gets an editable textual representation of $content.
2718 * The textual representation can be turned by into a Content object by the
2719 * toEditContent() method.
2721 * If $content is null or false or a string, $content is returned unchanged.
2723 * If the given Content object is not of a type that can be edited using
2724 * the text base EditPage, an exception will be raised. Set
2725 * $this->allowNonTextContent to true to allow editing of non-textual
2728 * @param Content|null|bool|string $content
2729 * @return string The editable text form of the content.
2731 * @throws MWException If $content is not an instance of TextContent and
2732 * $this->allowNonTextContent is not true.
2734 protected function toEditText( $content ) {
2735 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2739 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2740 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2743 return $content->serialize( $this->contentFormat
);
2747 * Turns the given text into a Content object by unserializing it.
2749 * If the resulting Content object is not of a type that can be edited using
2750 * the text base EditPage, an exception will be raised. Set
2751 * $this->allowNonTextContent to true to allow editing of non-textual
2754 * @param string|null|bool $text Text to unserialize
2755 * @return Content|bool|null The content object created from $text. If $text was false
2756 * or null, then false or null will be returned instead.
2758 * @throws MWException If unserializing the text results in a Content
2759 * object that is not an instance of TextContent and
2760 * $this->allowNonTextContent is not true.
2762 protected function toEditContent( $text ) {
2763 if ( $text === false ||
$text === null ) {
2767 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2768 $this->contentModel
, $this->contentFormat
);
2770 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2771 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2778 * Send the edit form and related headers to OutputPage
2779 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2780 * during form output near the top, for captchas and the like.
2782 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2783 * use the EditPage::showEditForm:fields hook instead.
2785 public function showEditForm( $formCallback = null ) {
2786 # need to parse the preview early so that we know which templates are used,
2787 # otherwise users with "show preview after edit box" will get a blank list
2788 # we parse this near the beginning so that setHeaders can do the title
2789 # setting work instead of leaving it in getPreviewText
2790 $previewOutput = '';
2791 if ( $this->formtype
== 'preview' ) {
2792 $previewOutput = $this->getPreviewText();
2795 $out = $this->context
->getOutput();
2797 // Avoid PHP 7.1 warning of passing $this by reference
2799 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2801 $this->setHeaders();
2803 $this->addTalkPageText();
2804 $this->addEditNotices();
2806 if ( !$this->isConflict
&&
2807 $this->section
!= '' &&
2808 !$this->isSectionEditSupported() ) {
2809 // We use $this->section to much before this and getVal('wgSection') directly in other places
2810 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2811 // Someone is welcome to try refactoring though
2812 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2816 $this->showHeader();
2818 $out->addHTML( $this->editFormPageTop
);
2820 $user = $this->context
->getUser();
2821 if ( $user->getOption( 'previewontop' ) ) {
2822 $this->displayPreviewArea( $previewOutput, true );
2825 $out->addHTML( $this->editFormTextTop
);
2827 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
!== 'save' ) {
2828 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2829 'deletedwhileediting' );
2832 // @todo add EditForm plugin interface and use it here!
2833 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2834 $out->addHTML( Html
::openElement(
2837 'class' => 'mw-editform',
2838 'id' => self
::EDITFORM_ID
,
2839 'name' => self
::EDITFORM_ID
,
2841 'action' => $this->getActionURL( $this->getContextTitle() ),
2842 'enctype' => 'multipart/form-data'
2846 if ( is_callable( $formCallback ) ) {
2847 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2848 call_user_func_array( $formCallback, [ &$out ] );
2851 // Add a check for Unicode support
2852 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2854 // Add an empty field to trip up spambots
2856 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2859 [ 'for' => 'wpAntispam' ],
2860 $this->context
->msg( 'simpleantispam-label' )->parse()
2866 'name' => 'wpAntispam',
2867 'id' => 'wpAntispam',
2871 . Xml
::closeElement( 'div' )
2874 // Avoid PHP 7.1 warning of passing $this by reference
2876 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2878 // Put these up at the top to ensure they aren't lost on early form submission
2879 $this->showFormBeforeText();
2881 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2882 $username = $this->lastDelete
->user_name
;
2883 $comment = CommentStore
::getStore()
2884 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2886 // It is better to not parse the comment at all than to have templates expanded in the middle
2887 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2888 $key = $comment === ''
2889 ?
'confirmrecreate-noreason'
2890 : 'confirmrecreate';
2892 '<div class="mw-confirm-recreate">' .
2893 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2894 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2895 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2901 # When the summary is hidden, also hide them on preview/show changes
2902 if ( $this->nosummary
) {
2903 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2906 # If a blank edit summary was previously provided, and the appropriate
2907 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2908 # user being bounced back more than once in the event that a summary
2911 # For a bit more sophisticated detection of blank summaries, hash the
2912 # automatic one and pass that in the hidden field wpAutoSummary.
2913 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2914 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2917 if ( $this->undidRev
) {
2918 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2921 if ( $this->selfRedirect
) {
2922 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2925 if ( $this->hasPresetSummary
) {
2926 // If a summary has been preset using &summary= we don't want to prompt for
2927 // a different summary. Only prompt for a summary if the summary is blanked.
2929 $this->autoSumm
= md5( '' );
2932 $autosumm = $this->autoSumm
!== '' ?
$this->autoSumm
: md5( $this->summary
);
2933 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2935 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2936 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2938 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2939 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2943 if ( $this->section
== 'new' ) {
2944 $this->showSummaryInput( true, $this->summary
);
2945 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2948 $out->addHTML( $this->editFormTextBeforeContent
);
2949 if ( $this->isConflict
) {
2950 // In an edit conflict, we turn textbox2 into the user's text,
2951 // and textbox1 into the stored version
2952 $this->textbox2
= $this->textbox1
;
2954 $content = $this->getCurrentContent();
2955 $this->textbox1
= $this->toEditText( $content );
2957 $editConflictHelper = $this->getEditConflictHelper();
2958 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2959 $editConflictHelper->setContentModel( $this->contentModel
);
2960 $editConflictHelper->setContentFormat( $this->contentFormat
);
2961 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2964 if ( !$this->mTitle
->isUserConfigPage() ) {
2965 $out->addHTML( self
::getEditToolbar() );
2968 if ( $this->blankArticle
) {
2969 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2972 if ( $this->isConflict
) {
2973 // In an edit conflict bypass the overridable content form method
2974 // and fallback to the raw wpTextbox1 since editconflicts can't be
2975 // resolved between page source edits and custom ui edits using the
2977 $conflictTextBoxAttribs = [];
2978 if ( $this->wasDeletedSinceLastEdit() ) {
2979 $conflictTextBoxAttribs['style'] = 'display:none;';
2980 } elseif ( $this->isOldRev
) {
2981 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2984 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2985 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2987 $this->showContentForm();
2990 $out->addHTML( $this->editFormTextAfterContent
);
2992 $this->showStandardInputs();
2994 $this->showFormAfterText();
2996 $this->showTosSummary();
2998 $this->showEditTools();
3000 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
3002 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
3004 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
3005 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
3007 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
3008 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
3010 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
3012 if ( $this->isConflict
) {
3014 $this->showConflict();
3015 } catch ( MWContentSerializationException
$ex ) {
3016 // this can't really happen, but be nice if it does.
3017 $msg = $this->context
->msg(
3018 'content-failed-to-parse',
3019 $this->contentModel
,
3020 $this->contentFormat
,
3023 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3027 // Set a hidden field so JS knows what edit form mode we are in
3028 if ( $this->isConflict
) {
3030 } elseif ( $this->preview
) {
3032 } elseif ( $this->diff
) {
3037 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
3039 // Marker for detecting truncated form data. This must be the last
3040 // parameter sent in order to be of use, so do not move me.
3041 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
3042 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
3044 if ( !$user->getOption( 'previewontop' ) ) {
3045 $this->displayPreviewArea( $previewOutput, false );
3050 * Wrapper around TemplatesOnThisPageFormatter to make
3051 * a "templates on this page" list.
3053 * @param Title[] $templates
3054 * @return string HTML
3056 public function makeTemplatesOnThisPageList( array $templates ) {
3057 $templateListFormatter = new TemplatesOnThisPageFormatter(
3058 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
3061 // preview if preview, else section if section, else false
3063 if ( $this->preview
) {
3065 } elseif ( $this->section
!= '' ) {
3069 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
3070 $templateListFormatter->format( $templates, $type )
3075 * Extract the section title from current section text, if any.
3077 * @param string $text
3078 * @return string|bool String or false
3080 public static function extractSectionTitle( $text ) {
3081 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
3082 if ( !empty( $matches[2] ) ) {
3083 return MediaWikiServices
::getInstance()->getParser()
3084 ->stripSectionName( trim( $matches[2] ) );
3090 protected function showHeader() {
3091 $out = $this->context
->getOutput();
3092 $user = $this->context
->getUser();
3093 if ( $this->isConflict
) {
3094 $this->addExplainConflictHeader( $out );
3095 $this->editRevId
= $this->page
->getLatest();
3097 if ( $this->section
!= '' && $this->section
!= 'new' && !$this->summary
&&
3098 !$this->preview
&& !$this->diff
3100 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
3101 if ( $sectionTitle !== false ) {
3102 $this->summary
= "/* $sectionTitle */ ";
3106 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
3108 if ( $this->missingComment
) {
3109 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3112 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
3114 "<div id='mw-missingsummary'>\n$1\n</div>",
3115 [ 'missingsummary', $buttonLabel ]
3119 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3121 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3122 [ 'missingcommentheader', $buttonLabel ]
3126 if ( $this->blankArticle
) {
3128 "<div id='mw-blankarticle'>\n$1\n</div>",
3129 [ 'blankarticle', $buttonLabel ]
3133 if ( $this->selfRedirect
) {
3135 "<div id='mw-selfredirect'>\n$1\n</div>",
3136 [ 'selfredirect', $buttonLabel ]
3140 if ( $this->hookError
!== '' ) {
3141 $out->addWikiTextAsInterface( $this->hookError
);
3144 if ( $this->section
!= 'new' ) {
3145 $revision = $this->mArticle
->getRevisionFetched();
3147 // Let sysop know that this will make private content public if saved
3149 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3151 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3152 'rev-deleted-text-permission'
3154 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3156 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3157 'rev-deleted-text-view'
3161 if ( !$revision->isCurrent() ) {
3162 $this->mArticle
->setOldSubtitle( $revision->getId() );
3164 Html
::warningBox( "\n$1\n" ),
3167 $this->isOldRev
= true;
3169 } elseif ( $this->mTitle
->exists() ) {
3170 // Something went wrong
3172 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3173 [ 'missing-revision', $this->oldid
] );
3178 if ( wfReadOnly() ) {
3180 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3181 [ 'readonlywarning', wfReadOnlyReason() ]
3183 } elseif ( $user->isAnon() ) {
3184 if ( $this->formtype
!= 'preview' ) {
3185 $returntoquery = array_diff_key(
3186 $this->context
->getRequest()->getValues(),
3187 [ 'title' => true, 'returnto' => true, 'returntoquery' => true ]
3190 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3191 [ 'anoneditwarning',
3193 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3194 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3195 'returntoquery' => wfArrayToCgi( $returntoquery ),
3198 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3199 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3200 'returntoquery' => wfArrayToCgi( $returntoquery ),
3205 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3206 'anonpreviewwarning'
3209 } elseif ( $this->mTitle
->isUserConfigPage() ) {
3210 # Check the skin exists
3211 if ( $this->isWrongCaseUserConfigPage() ) {
3213 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3214 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3217 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3218 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3219 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3220 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3222 $warning = $isUserCssConfig
3224 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3226 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3228 if ( $this->formtype
!== 'preview' ) {
3229 $config = $this->context
->getConfig();
3230 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3232 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3233 [ 'usercssyoucanpreview' ]
3235 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3237 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3238 [ 'userjsonyoucanpreview' ]
3240 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3242 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3243 [ 'userjsyoucanpreview' ]
3250 $this->addPageProtectionWarningHeaders();
3252 $this->addLongPageWarningHeader();
3254 # Add header copyright warning
3255 $this->showHeaderCopyrightWarning();
3259 * Helper function for summary input functions, which returns the necessary
3260 * attributes for the input.
3262 * @param array|null $inputAttrs Array of attrs to use on the input
3265 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3266 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3267 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3268 // Unicode codepoints.
3269 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3270 'id' => 'wpSummary',
3271 'name' => 'wpSummary',
3272 'maxlength' => CommentStore
::COMMENT_CHARACTER_LIMIT
,
3275 'spellcheck' => 'true',
3280 * Builds a standard summary input with a label.
3282 * @param string $summary The value of the summary input
3283 * @param string|null $labelText The html to place inside the label
3284 * @param array|null $inputAttrs Array of attrs to use on the input
3286 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3288 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3289 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3290 $this->getSummaryInputAttributes( $inputAttrs )
3293 'title' => Linker
::titleAttrib( 'summary' ),
3294 'accessKey' => Linker
::accesskey( 'summary' ),
3297 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3298 $inputAttrs['inputId'] = $inputAttrs['id'];
3299 $inputAttrs['id'] = 'wpSummaryWidget';
3301 return new OOUI\
FieldLayout(
3302 new OOUI\
TextInputWidget( [
3303 'value' => $summary,
3304 'infusable' => true,
3307 'label' => new OOUI\
HtmlSnippet( $labelText ),
3309 'id' => 'wpSummaryLabel',
3310 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3316 * @param bool $isSubjectPreview True if this is the section subject/title
3317 * up top, or false if this is the comment summary
3318 * down below the textarea
3319 * @param string $summary The text of the summary to display
3321 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3322 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3323 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3324 if ( $isSubjectPreview ) {
3325 if ( $this->nosummary
) {
3328 } elseif ( !$this->mShowSummaryField
) {
3332 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3333 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3336 [ 'class' => $summaryClass ]
3341 * @param bool $isSubjectPreview True if this is the section subject/title
3342 * up top, or false if this is the comment summary
3343 * down below the textarea
3344 * @param string $summary The text of the summary to display
3347 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3348 // avoid spaces in preview, gets always trimmed on save
3349 $summary = trim( $summary );
3350 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3354 if ( $isSubjectPreview ) {
3355 $summary = $this->context
->msg( 'newsectionsummary' )
3356 ->rawParams( MediaWikiServices
::getInstance()->getParser()
3357 ->stripSectionName( $summary ) )
3358 ->inContentLanguage()->text();
3361 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3363 $summary = $this->context
->msg( $message )->parse()
3364 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3365 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3368 protected function showFormBeforeText() {
3369 $out = $this->context
->getOutput();
3370 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3371 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3372 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3373 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3374 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3377 protected function showFormAfterText() {
3379 * To make it harder for someone to slip a user a page
3380 * which submits an edit form to the wiki without their
3381 * knowledge, a random token is associated with the login
3382 * session. If it's not passed back with the submission,
3383 * we won't save the page, or render user JavaScript and
3386 * For anon editors, who may not have a session, we just
3387 * include the constant suffix to prevent editing from
3388 * broken text-mangling proxies.
3390 $this->context
->getOutput()->addHTML(
3392 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3398 * Subpage overridable method for printing the form for page content editing
3399 * By default this simply outputs wpTextbox1
3400 * Subclasses can override this to provide a custom UI for editing;
3401 * be it a form, or simply wpTextbox1 with a modified content that will be
3402 * reverse modified when extracted from the post data.
3403 * Note that this is basically the inverse for importContentFormData
3405 protected function showContentForm() {
3406 $this->showTextbox1();
3410 * Method to output wpTextbox1
3411 * The $textoverride method can be used by subclasses overriding showContentForm
3412 * to pass back to this method.
3414 * @param array|null $customAttribs Array of html attributes to use in the textarea
3415 * @param string|null $textoverride Optional text to override $this->textarea1 with
3417 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3418 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3419 $attribs = [ 'style' => 'display:none;' ];
3421 $builder = new TextboxBuilder();
3422 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3424 # Is an old revision being edited?
3425 if ( $this->isOldRev
) {
3426 $classes[] = 'mw-textarea-oldrev';
3429 $attribs = [ 'tabindex' => 1 ];
3431 if ( is_array( $customAttribs ) ) {
3432 $attribs +
= $customAttribs;
3435 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3439 $textoverride ??
$this->textbox1
,
3445 protected function showTextbox2() {
3446 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3449 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3450 $builder = new TextboxBuilder();
3451 $attribs = $builder->buildTextboxAttribs(
3454 $this->context
->getUser(),
3458 $this->context
->getOutput()->addHTML(
3459 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3463 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3466 $classes[] = 'ontop';
3469 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3471 if ( $this->formtype
!= 'preview' ) {
3472 $attribs['style'] = 'display: none;';
3475 $out = $this->context
->getOutput();
3476 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3478 if ( $this->formtype
== 'preview' ) {
3479 $this->showPreview( $previewOutput );
3481 // Empty content container for LivePreview
3482 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3483 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3484 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3485 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3488 $out->addHTML( '</div>' );
3490 if ( $this->formtype
== 'diff' ) {
3493 } catch ( MWContentSerializationException
$ex ) {
3494 $msg = $this->context
->msg(
3495 'content-failed-to-parse',
3496 $this->contentModel
,
3497 $this->contentFormat
,
3500 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3506 * Append preview output to OutputPage.
3507 * Includes category rendering if this is a category page.
3509 * @param string $text The HTML to be output for the preview.
3511 protected function showPreview( $text ) {
3512 if ( $this->mArticle
instanceof CategoryPage
) {
3513 $this->mArticle
->openShowCategory();
3515 # This hook seems slightly odd here, but makes things more
3516 # consistent for extensions.
3517 $out = $this->context
->getOutput();
3518 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3519 $out->addHTML( $text );
3520 if ( $this->mArticle
instanceof CategoryPage
) {
3521 $this->mArticle
->closeShowCategory();
3526 * Get a diff between the current contents of the edit box and the
3527 * version of the page we're editing from.
3529 * If this is a section edit, we'll replace the section as for final
3530 * save and then make a comparison.
3532 public function showDiff() {
3533 $oldtitlemsg = 'currentrev';
3534 # if message does not exist, show diff against the preloaded default
3535 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3536 $oldtext = $this->mTitle
->getDefaultMessageText();
3537 if ( $oldtext !== false ) {
3538 $oldtitlemsg = 'defaultmessagetext';
3539 $oldContent = $this->toEditContent( $oldtext );
3544 $oldContent = $this->getCurrentContent();
3547 $textboxContent = $this->toEditContent( $this->textbox1
);
3548 if ( $this->editRevId
!== null ) {
3549 $newContent = $this->page
->replaceSectionAtRev(
3550 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3553 $newContent = $this->page
->replaceSectionContent(
3554 $this->section
, $textboxContent, $this->summary
, $this->edittime
3558 if ( $newContent ) {
3559 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3561 $user = $this->context
->getUser();
3562 $popts = ParserOptions
::newFromUserAndLang( $user,
3563 MediaWikiServices
::getInstance()->getContentLanguage() );
3564 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3567 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3568 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3569 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3571 if ( !$oldContent ) {
3572 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3575 if ( !$newContent ) {
3576 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3579 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3580 $de->setContent( $oldContent, $newContent );
3582 $difftext = $de->getDiff( $oldtitle, $newtitle );
3583 $de->showDiffStyle();
3588 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3592 * Show the header copyright warning.
3594 protected function showHeaderCopyrightWarning() {
3595 $msg = 'editpage-head-copy-warn';
3596 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3597 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3598 'editpage-head-copy-warn' );
3603 * Give a chance for site and per-namespace customizations of
3604 * terms of service summary link that might exist separately
3605 * from the copyright notice.
3607 * This will display between the save button and the edit tools,
3608 * so should remain short!
3610 protected function showTosSummary() {
3611 $msg = 'editpage-tos-summary';
3612 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3613 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3614 $out = $this->context
->getOutput();
3615 $out->addHTML( '<div class="mw-tos-summary">' );
3616 $out->addWikiMsg( $msg );
3617 $out->addHTML( '</div>' );
3622 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3623 * characters not present on most keyboards for copying/pasting.
3625 protected function showEditTools() {
3626 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3627 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3632 * Get the copyright warning
3634 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3637 protected function getCopywarn() {
3638 return self
::getCopyrightWarning( $this->mTitle
);
3642 * Get the copyright warning, by default returns wikitext
3644 * @param Title $title
3645 * @param string $format Output format, valid values are any function of a Message object
3646 * @param Language|string|null $langcode Language code or Language object.
3649 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3650 global $wgRightsText;
3651 if ( $wgRightsText ) {
3652 $copywarnMsg = [ 'copyrightwarning',
3653 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3656 $copywarnMsg = [ 'copyrightwarning2',
3657 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3659 // Allow for site and per-namespace customization of contribution/copyright notice.
3660 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3662 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3664 $msg->inLanguage( $langcode );
3666 return "<div id=\"editpage-copywarn\">\n" .
3667 $msg->$format() . "\n</div>";
3671 * Get the Limit report for page previews
3674 * @param ParserOutput|null $output ParserOutput object from the parse
3675 * @return string HTML
3677 public static function getPreviewLimitReport( ParserOutput
$output = null ) {
3680 if ( !$output ||
!$output->getLimitReportData() ) {
3684 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3685 wfMessage( 'limitreport-title' )->parseAsBlock()
3688 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3689 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3691 $limitReport .= Html
::openElement( 'table', [
3692 'class' => 'preview-limit-report wikitable'
3694 Html
::openElement( 'tbody' );
3696 foreach ( $output->getLimitReportData() as $key => $value ) {
3697 if ( Hooks
::run( 'ParserLimitReportFormat',
3698 [ $key, &$value, &$limitReport, true, true ]
3700 $keyMsg = wfMessage( $key );
3701 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3702 if ( !$valueMsg->exists() ) {
3703 $valueMsg = new RawMessage( '$1' );
3705 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3706 $limitReport .= Html
::openElement( 'tr' ) .
3707 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3708 Html
::rawElement( 'td', null,
3709 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3711 Html
::closeElement( 'tr' );
3716 $limitReport .= Html
::closeElement( 'tbody' ) .
3717 Html
::closeElement( 'table' ) .
3718 Html
::closeElement( 'div' );
3720 return $limitReport;
3723 protected function showStandardInputs( &$tabindex = 2 ) {
3724 $out = $this->context
->getOutput();
3725 $out->addHTML( "<div class='editOptions'>\n" );
3727 if ( $this->section
!= 'new' ) {
3728 $this->showSummaryInput( false, $this->summary
);
3729 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3732 $checkboxes = $this->getCheckboxesWidget(
3734 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3736 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3738 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3740 // Show copyright warning.
3741 $out->addWikiTextAsInterface( $this->getCopywarn() );
3742 $out->addHTML( $this->editFormTextAfterWarn
);
3744 $out->addHTML( "<div class='editButtons'>\n" );
3745 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3747 $cancel = $this->getCancelLink();
3749 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3750 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3753 $this->context
->msg( 'edithelp' )->text(),
3754 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3757 $this->context
->msg( 'word-separator' )->escaped() .
3758 $this->context
->msg( 'newwindow' )->parse();
3760 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3761 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3762 $out->addHTML( "</div><!-- editButtons -->\n" );
3764 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3766 $out->addHTML( "</div><!-- editOptions -->\n" );
3770 * Show an edit conflict. textbox1 is already shown in showEditForm().
3771 * If you want to use another entry point to this function, be careful.
3773 protected function showConflict() {
3774 $out = $this->context
->getOutput();
3775 // Avoid PHP 7.1 warning of passing $this by reference
3777 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3778 $this->incrementConflictStats();
3780 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3784 protected function incrementConflictStats() {
3785 $this->getEditConflictHelper()->incrementConflictStats();
3791 public function getCancelLink() {
3793 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3794 $cancelParams['oldid'] = $this->oldid
;
3795 } elseif ( $this->getContextTitle()->isRedirect() ) {
3796 $cancelParams['redirect'] = 'no';
3799 return new OOUI\
ButtonWidget( [
3800 'id' => 'mw-editform-cancel',
3801 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3802 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3804 'infusable' => true,
3805 'flags' => 'destructive',
3810 * Returns the URL to use in the form's action attribute.
3811 * This is used by EditPage subclasses when simply customizing the action
3812 * variable in the constructor is not enough. This can be used when the
3813 * EditPage lives inside of a Special page rather than a custom page action.
3815 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3818 protected function getActionURL( Title
$title ) {
3819 return $title->getLocalURL( [ 'action' => $this->action
] );
3823 * Check if a page was deleted while the user was editing it, before submit.
3824 * Note that we rely on the logging table, which hasn't been always there,
3825 * but that doesn't matter, because this only applies to brand new
3829 protected function wasDeletedSinceLastEdit() {
3830 if ( $this->deletedSinceEdit
!== null ) {
3831 return $this->deletedSinceEdit
;
3834 $this->deletedSinceEdit
= false;
3836 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3837 $this->lastDelete
= $this->getLastDelete();
3838 if ( $this->lastDelete
) {
3839 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3840 if ( $deleteTime > $this->starttime
) {
3841 $this->deletedSinceEdit
= true;
3846 return $this->deletedSinceEdit
;
3850 * Get the last log record of this page being deleted, if ever. This is
3851 * used to detect whether a delete occurred during editing.
3852 * @return bool|stdClass
3854 protected function getLastDelete() {
3855 $dbr = wfGetDB( DB_REPLICA
);
3856 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3857 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3858 $data = $dbr->selectRow(
3859 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3869 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3871 'log_namespace' => $this->mTitle
->getNamespace(),
3872 'log_title' => $this->mTitle
->getDBkey(),
3873 'log_type' => 'delete',
3874 'log_action' => 'delete',
3877 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3879 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3880 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3882 // Quick paranoid permission checks...
3883 if ( is_object( $data ) ) {
3884 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3885 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3888 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3889 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3890 $data->log_comment_data
= null;
3898 * Get the rendered text for previewing.
3899 * @throws MWException
3902 public function getPreviewText() {
3903 $out = $this->context
->getOutput();
3904 $config = $this->context
->getConfig();
3906 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3907 // Could be an offsite preview attempt. This is very unsafe if
3908 // HTML is enabled, as it could be an attack.
3910 if ( $this->textbox1
!== '' ) {
3911 // Do not put big scary notice, if previewing the empty
3912 // string, which happens when you initially edit
3913 // a category page, due to automatic preview-on-open.
3914 $parsedNote = Html
::rawElement( 'div', [ 'class' => 'previewnote' ],
3915 $out->parseAsInterface(
3916 $this->context
->msg( 'session_fail_preview_html' )->plain()
3919 $this->incrementEditFailureStats( 'session_loss' );
3926 $content = $this->toEditContent( $this->textbox1
);
3930 'AlternateEditPreview',
3931 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3933 return $previewHTML;
3936 # provide a anchor link to the editform
3937 $continueEditing = '<span class="mw-continue-editing">' .
3938 '[[#' . self
::EDITFORM_ID
. '|' .
3939 $this->context
->getLanguage()->getArrow() . ' ' .
3940 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3941 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3942 if ( $this->mTokenOkExceptSuffix
) {
3943 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3944 $this->incrementEditFailureStats( 'bad_token' );
3946 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3947 $this->incrementEditFailureStats( 'session_loss' );
3949 } elseif ( $this->incompleteForm
) {
3950 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3951 if ( $this->mTriedSave
) {
3952 $this->incrementEditFailureStats( 'incomplete_form' );
3955 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3958 # don't parse non-wikitext pages, show message about preview
3959 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3960 if ( $this->mTitle
->isUserConfigPage() ) {
3962 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3968 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3970 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3973 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3975 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3978 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3980 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3987 # Used messages to make sure grep find them:
3988 # Messages: usercsspreview, userjsonpreview, userjspreview,
3989 # sitecsspreview, sitejsonpreview, sitejspreview
3990 if ( $level && $format ) {
3991 $note = "<div id='mw-{$level}{$format}preview'>" .
3992 $this->context
->msg( "{$level}{$format}preview" )->plain() .
3993 ' ' . $continueEditing . "</div>";
3997 # If we're adding a comment, we need to show the
3998 # summary as the headline
3999 if ( $this->section
=== "new" && $this->summary
!== "" ) {
4000 $content = $content->addSectionHeader( $this->summary
);
4003 $hook_args = [ $this, &$content ];
4004 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
4006 $parserResult = $this->doPreviewParse( $content );
4007 $parserOutput = $parserResult['parserOutput'];
4008 $previewHTML = $parserResult['html'];
4009 $this->mParserOutput
= $parserOutput;
4010 $out->addParserOutputMetadata( $parserOutput );
4011 if ( $out->userCanPreview() ) {
4012 $out->addContentOverride( $this->getTitle(), $content );
4015 if ( count( $parserOutput->getWarnings() ) ) {
4016 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
4019 } catch ( MWContentSerializationException
$ex ) {
4020 $m = $this->context
->msg(
4021 'content-failed-to-parse',
4022 $this->contentModel
,
4023 $this->contentFormat
,
4026 $note .= "\n\n" . $m->plain(); # gets parsed down below
4030 if ( $this->isConflict
) {
4031 $conflict = Html
::rawElement(
4032 'h2', [ 'id' => 'mw-previewconflict' ],
4033 $this->context
->msg( 'previewconflict' )->escaped()
4036 $conflict = '<hr />';
4039 $previewhead = Html
::rawElement(
4040 'div', [ 'class' => 'previewnote' ],
4042 'h2', [ 'id' => 'mw-previewheader' ],
4043 $this->context
->msg( 'preview' )->escaped()
4045 $out->parseAsInterface( $note ) . $conflict
4048 $pageViewLang = $this->mTitle
->getPageViewLanguage();
4049 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
4050 'class' => 'mw-content-' . $pageViewLang->getDir() ];
4051 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
4053 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
4056 private function incrementEditFailureStats( $failureType ) {
4057 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
4058 $stats->increment( 'edit.failures.' . $failureType );
4062 * Get parser options for a preview
4063 * @return ParserOptions
4065 protected function getPreviewParserOptions() {
4066 $parserOptions = $this->page
->makeParserOptions( $this->context
);
4067 $parserOptions->setIsPreview( true );
4068 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
4069 $parserOptions->enableLimitReport();
4071 // XXX: we could call $parserOptions->setCurrentRevisionCallback here to force the
4072 // current revision to be null during PST, until setupFakeRevision is called on
4073 // the ParserOptions. Currently, we rely on Parser::getRevisionObject() to ignore
4074 // existing revisions in preview mode.
4076 return $parserOptions;
4080 * Parse the page for a preview. Subclasses may override this class, in order
4081 * to parse with different options, or to otherwise modify the preview HTML.
4083 * @param Content $content The page content
4084 * @return array with keys:
4085 * - parserOutput: The ParserOutput object
4086 * - html: The HTML to be displayed
4088 protected function doPreviewParse( Content
$content ) {
4089 $user = $this->context
->getUser();
4090 $parserOptions = $this->getPreviewParserOptions();
4092 // NOTE: preSaveTransform doesn't have a fake revision to operate on.
4093 // Parser::getRevisionObject() will return null in preview mode,
4094 // causing the context user to be used for {{subst:REVISIONUSER}}.
4095 // XXX: Alternatively, we could also call setupFakeRevision() a second time:
4096 // once before PST with $content, and then after PST with $pstContent.
4097 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
4098 $scopedCallback = $parserOptions->setupFakeRevision( $this->mTitle
, $pstContent, $user );
4099 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
4100 ScopedCallback
::consume( $scopedCallback );
4102 'parserOutput' => $parserOutput,
4103 'html' => $parserOutput->getText( [
4104 'enableSectionEditLinks' => false
4112 public function getTemplates() {
4113 if ( $this->preview ||
$this->section
!= '' ) {
4115 if ( !isset( $this->mParserOutput
) ) {
4118 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
4119 foreach ( array_keys( $template ) as $dbk ) {
4120 $templates[] = Title
::makeTitle( $ns, $dbk );
4125 return $this->mTitle
->getTemplateLinksFrom();
4130 * Allow extensions to provide a toolbar.
4132 * @return string|null
4134 public static function getEditToolbar() {
4135 $startingToolbar = '<div id="toolbar"></div>';
4136 $toolbar = $startingToolbar;
4138 if ( !Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4141 // Don't add a pointless `<div>` to the page unless a hook caller populated it
4142 return ( $toolbar === $startingToolbar ) ?
null : $toolbar;
4146 * Return an array of checkbox definitions.
4148 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4150 * Array values are associative arrays with the following keys:
4151 * - 'label-message' (required): message for label text
4152 * - 'id' (required): 'id' attribute for the `<input>`
4153 * - 'default' (required): default checkedness (true or false)
4154 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4155 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4156 * from messages like 'tooltip-foo', 'accesskey-foo'
4157 * - 'label-id' (optional): 'id' attribute for the `<label>`
4158 * - 'legacy-name' (optional): short name for backwards-compatibility
4159 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4160 * where bool indicates the checked status of the checkbox
4163 public function getCheckboxesDefinition( $checked ) {
4166 $user = $this->context
->getUser();
4167 // don't show the minor edit checkbox if it's a new page or section
4168 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4169 $checkboxes['wpMinoredit'] = [
4170 'id' => 'wpMinoredit',
4171 'label-message' => 'minoredit',
4172 // Uses messages: tooltip-minoredit, accesskey-minoredit
4173 'tooltip' => 'minoredit',
4174 'label-id' => 'mw-editpage-minoredit',
4175 'legacy-name' => 'minor',
4176 'default' => $checked['minor'],
4180 if ( $user->isLoggedIn() ) {
4181 $checkboxes['wpWatchthis'] = [
4182 'id' => 'wpWatchthis',
4183 'label-message' => 'watchthis',
4184 // Uses messages: tooltip-watch, accesskey-watch
4185 'tooltip' => 'watch',
4186 'label-id' => 'mw-editpage-watch',
4187 'legacy-name' => 'watch',
4188 'default' => $checked['watch'],
4193 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4199 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4200 * any other added by extensions.
4202 * @param int &$tabindex Current tabindex
4203 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4204 * status of the checkbox
4206 * @return array Associative array of string keys to OOUI\FieldLayout instances
4208 public function getCheckboxesWidget( &$tabindex, $checked ) {
4210 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4212 foreach ( $checkboxesDef as $name => $options ) {
4213 $legacyName = $options['legacy-name'] ??
$name;
4217 if ( isset( $options['tooltip'] ) ) {
4218 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4219 $title = Linker
::titleAttrib( $options['tooltip'] );
4221 if ( isset( $options['title-message'] ) ) {
4222 $title = $this->context
->msg( $options['title-message'] )->text();
4225 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4226 new OOUI\
CheckboxInputWidget( [
4227 'tabIndex' => ++
$tabindex,
4228 'accessKey' => $accesskey,
4229 'id' => $options['id'] . 'Widget',
4230 'inputId' => $options['id'],
4232 'selected' => $options['default'],
4233 'infusable' => true,
4236 'align' => 'inline',
4237 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4239 'id' => $options['label-id'] ??
null,
4248 * Get the message key of the label for the button to save the page
4253 protected function getSubmitButtonLabel() {
4255 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4257 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4258 $newPage = !$this->mTitle
->exists();
4260 if ( $labelAsPublish ) {
4261 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4263 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4266 return $buttonLabelKey;
4270 * Returns an array of html code of the following buttons:
4271 * save, diff and preview
4273 * @param int &$tabindex Current tabindex
4277 public function getEditButtons( &$tabindex ) {
4281 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4283 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4284 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4286 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4288 'tabIndex' => ++
$tabindex,
4289 'id' => 'wpSaveWidget',
4290 'inputId' => 'wpSave',
4291 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4292 'useInputTag' => true,
4293 'flags' => [ 'progressive', 'primary' ],
4294 'label' => $buttonLabel,
4295 'infusable' => true,
4297 // Messages used: tooltip-save, tooltip-publish
4298 'title' => Linker
::titleAttrib( $buttonTooltip ),
4299 // Messages used: accesskey-save, accesskey-publish
4300 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4303 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4304 'name' => 'wpPreview',
4305 'tabIndex' => ++
$tabindex,
4306 'id' => 'wpPreviewWidget',
4307 'inputId' => 'wpPreview',
4308 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4309 'useInputTag' => true,
4310 'label' => $this->context
->msg( 'showpreview' )->text(),
4311 'infusable' => true,
4313 // Message used: tooltip-preview
4314 'title' => Linker
::titleAttrib( 'preview' ),
4315 // Message used: accesskey-preview
4316 'accessKey' => Linker
::accesskey( 'preview' ),
4319 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4321 'tabIndex' => ++
$tabindex,
4322 'id' => 'wpDiffWidget',
4323 'inputId' => 'wpDiff',
4324 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4325 'useInputTag' => true,
4326 'label' => $this->context
->msg( 'showdiff' )->text(),
4327 'infusable' => true,
4329 // Message used: tooltip-diff
4330 'title' => Linker
::titleAttrib( 'diff' ),
4331 // Message used: accesskey-diff
4332 'accessKey' => Linker
::accesskey( 'diff' ),
4335 // Avoid PHP 7.1 warning of passing $this by reference
4337 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4343 * Creates a basic error page which informs the user that
4344 * they have attempted to edit a nonexistent section.
4346 public function noSuchSectionPage() {
4347 $out = $this->context
->getOutput();
4348 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4350 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4352 // Avoid PHP 7.1 warning of passing $this by reference
4354 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4355 $out->addHTML( $res );
4357 $out->returnToMain( false, $this->mTitle
);
4361 * Show "your edit contains spam" page with your diff and text
4363 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4365 public function spamPageWithContent( $match = false ) {
4366 $this->textbox2
= $this->textbox1
;
4368 if ( is_array( $match ) ) {
4369 $match = $this->context
->getLanguage()->listToText( $match );
4371 $out = $this->context
->getOutput();
4372 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4374 $out->addHTML( '<div id="spamprotected">' );
4375 $out->addWikiMsg( 'spamprotectiontext' );
4377 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4379 $out->addHTML( '</div>' );
4381 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4384 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4385 $this->showTextbox2();
4387 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4393 protected function addEditNotices() {
4394 $out = $this->context
->getOutput();
4395 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4396 if ( count( $editNotices ) ) {
4397 $out->addHTML( implode( "\n", $editNotices ) );
4399 $msg = $this->context
->msg( 'editnotice-notext' );
4400 if ( !$msg->isDisabled() ) {
4402 '<div class="mw-editnotice-notext">'
4403 . $msg->parseAsBlock()
4413 protected function addTalkPageText() {
4414 if ( $this->mTitle
->isTalkPage() ) {
4415 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4422 protected function addLongPageWarningHeader() {
4423 if ( $this->contentLength
=== false ) {
4424 $this->contentLength
= strlen( $this->textbox1
);
4427 $out = $this->context
->getOutput();
4428 $lang = $this->context
->getLanguage();
4429 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4430 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4431 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4434 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4435 $lang->formatNum( $maxArticleSize )
4438 } elseif ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4439 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4442 $lang->formatSize( strlen( $this->textbox1
) ),
4443 strlen( $this->textbox1
)
4452 protected function addPageProtectionWarningHeaders() {
4453 $out = $this->context
->getOutput();
4454 if ( $this->mTitle
->isProtected( 'edit' ) &&
4455 MediaWikiServices
::getInstance()->getNamespaceInfo()->getRestrictionLevels(
4456 $this->mTitle
->getNamespace()
4459 # Is the title semi-protected?
4460 if ( $this->mTitle
->isSemiProtected() ) {
4461 $noticeMsg = 'semiprotectedpagewarning';
4463 # Then it must be protected based on static groups (regular)
4464 $noticeMsg = 'protectedpagewarning';
4466 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4467 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4469 if ( $this->mTitle
->isCascadeProtected() ) {
4470 # Is this page under cascading protection from some source pages?
4471 /** @var Title[] $cascadeSources */
4472 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4473 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4474 $cascadeSourcesCount = count( $cascadeSources );
4475 if ( $cascadeSourcesCount > 0 ) {
4476 # Explain, and list the titles responsible
4477 foreach ( $cascadeSources as $page ) {
4478 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4481 $notice .= '</div>';
4482 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4484 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4485 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4487 'showIfEmpty' => false,
4488 'msgKey' => [ 'titleprotectedwarning' ],
4489 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4494 * @param OutputPage $out
4497 protected function addExplainConflictHeader( OutputPage
$out ) {
4499 $this->getEditConflictHelper()->getExplainHeader()
4504 * @param string $name
4505 * @param mixed[] $customAttribs
4510 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4511 return ( new TextboxBuilder() )->buildTextboxAttribs(
4512 $name, $customAttribs, $user, $this->mTitle
4517 * @param string $wikitext
4521 protected function addNewLineAtEnd( $wikitext ) {
4522 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4526 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4527 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4528 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4529 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4530 * spread the new style links more efficiently.
4532 * @param string $text
4535 private function guessSectionName( $text ) {
4536 // Detect Microsoft browsers
4537 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4538 $parser = MediaWikiServices
::getInstance()->getParser();
4539 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4540 // ...and redirect them to legacy encoding, if available
4541 return $parser->guessLegacySectionNameFromWikiText( $text );
4543 // Meanwhile, real browsers get real anchors
4544 $name = $parser->guessSectionNameFromWikiText( $text );
4545 // With one little caveat: per T216029, fragments in HTTP redirects need to be urlencoded,
4546 // otherwise Chrome double-escapes the rest of the URL.
4547 return '#' . urlencode( mb_substr( $name, 1 ) );
4551 * Set a factory function to create an EditConflictHelper
4553 * @param callable $factory Factory function
4556 public function setEditConflictHelperFactory( callable
$factory ) {
4557 $this->editConflictHelperFactory
= $factory;
4558 $this->editConflictHelper
= null;
4562 * @return TextConflictHelper
4564 private function getEditConflictHelper() {
4565 if ( !$this->editConflictHelper
) {
4566 $this->editConflictHelper
= call_user_func(
4567 $this->editConflictHelperFactory
,
4568 $this->getSubmitButtonLabel()
4572 return $this->editConflictHelper
;
4576 * @param string $submitButtonLabel
4577 * @return TextConflictHelper
4579 private function newTextConflictHelper( $submitButtonLabel ) {
4580 return new TextConflictHelper(
4582 $this->getContext()->getOutput(),
4583 MediaWikiServices
::getInstance()->getStatsdDataFactory(),