3 * User interface for page editing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\EditPage\TextboxBuilder
;
24 use MediaWiki\EditPage\TextConflictHelper
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\ScopedCallback
;
30 * The edit page/HTML interface (split from Article)
31 * The actual database and text munging is still in Article,
32 * but it should get easier to call those from alternate
35 * EditPage cares about two distinct titles:
36 * $this->mContextTitle is the page that forms submit to, links point to,
37 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
38 * page in the database that is actually being edited. These are
39 * usually the same, but they are now allowed to be different.
41 * Surgeon General's Warning: prolonged exposure to this class is known to cause
42 * headaches, which may be fatal.
46 * Used for Unicode support checks
48 const UNICODE_CHECK
= 'β³π²β₯πππΎπΈβ΄πΉβ―';
51 * Status: Article successfully updated
53 const AS_SUCCESS_UPDATE
= 200;
56 * Status: Article successfully created
58 const AS_SUCCESS_NEW_ARTICLE
= 201;
61 * Status: Article update aborted by a hook function
63 const AS_HOOK_ERROR
= 210;
66 * Status: A hook function returned an error
68 const AS_HOOK_ERROR_EXPECTED
= 212;
71 * Status: User is blocked from editing this page
73 const AS_BLOCKED_PAGE_FOR_USER
= 215;
76 * Status: Content too big (> $wgMaxArticleSize)
78 const AS_CONTENT_TOO_BIG
= 216;
81 * Status: this anonymous user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_ANON
= 218;
86 * Status: this logged in user is not allowed to edit this page
88 const AS_READ_ONLY_PAGE_LOGGED
= 219;
91 * Status: wiki is in readonly mode (wfReadOnly() == true)
93 const AS_READ_ONLY_PAGE
= 220;
96 * Status: rate limiter for action 'edit' was tripped
98 const AS_RATE_LIMITED
= 221;
101 * Status: article was deleted while editing and param wpRecreate == false or form
104 const AS_ARTICLE_WAS_DELETED
= 222;
107 * Status: user tried to create this page, but is not allowed to do that
108 * ( Title->userCan('create') == false )
110 const AS_NO_CREATE_PERMISSION
= 223;
113 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
115 const AS_BLANK_ARTICLE
= 224;
118 * Status: (non-resolvable) edit conflict
120 const AS_CONFLICT_DETECTED
= 225;
123 * Status: no edit summary given and the user has forceeditsummary set and the user is not
124 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
126 const AS_SUMMARY_NEEDED
= 226;
129 * Status: user tried to create a new section without content
131 const AS_TEXTBOX_EMPTY
= 228;
134 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
136 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
139 * Status: WikiPage::doEdit() was unsuccessful
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
146 const AS_SPAM_ERROR
= 232;
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
151 const AS_IMAGE_REDIRECT_ANON
= 233;
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
156 const AS_IMAGE_REDIRECT_LOGGED
= 234;
159 * Status: user tried to modify the content model, but is not allowed to do that
160 * ( User::isAllowed('editcontentmodel') == false )
162 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
165 * Status: user tried to create self-redirect (redirect to the same article) and
166 * wpIgnoreSelfRedirect == false
168 const AS_SELF_REDIRECT
= 236;
171 * Status: an error relating to change tagging. Look at the message key for
174 const AS_CHANGE_TAG_ERROR
= 237;
177 * Status: can't parse content
179 const AS_PARSE_ERROR
= 240;
182 * Status: when changing the content model is disallowed due to
183 * $wgContentHandlerUseDB being false
185 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
188 * Status: edit rejected because browser doesn't support Unicode.
190 const AS_UNICODE_NOT_SUPPORTED
= 242;
193 * HTML id and name for the beginning of the edit form.
195 const EDITFORM_ID
= 'editform';
198 * Prefix of key for cookie used to pass post-edit state.
199 * The revision id edited is added after this
201 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
204 * Duration of PostEdit cookie, in seconds.
205 * The cookie will be removed instantly if the JavaScript runs.
207 * Otherwise, though, we don't want the cookies to accumulate.
208 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
209 * limit of only 20 cookies per domain. This still applies at least to some
210 * versions of IE without full updates:
211 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
213 * A value of 20 minutes should be enough to take into account slow loads and minor
214 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
216 const POST_EDIT_COOKIE_DURATION
= 1200;
219 * @deprecated for public usage since 1.30 use EditPage::getArticle()
227 * @deprecated for public usage since 1.30 use EditPage::getTitle()
232 /** @var null|Title */
233 private $mContextTitle = null;
236 public $action = 'submit';
238 /** @var bool Whether an edit conflict needs to be resolved. Detected based on whether
239 * $editRevId is different than the latest revision. When a conflict has successfully
240 * been resolved by a 3-way-merge, this field is set to false.
242 public $isConflict = false;
244 /** @var bool New page or new section */
245 public $isNew = false;
248 public $deletedSinceEdit;
254 * True the first time the edit form is rendered, false after re-rendering
255 * with diff, save prompts, etc.
259 /** @var bool|stdClass */
263 public $mTokenOk = false;
266 public $mTokenOkExceptSuffix = false;
269 public $mTriedSave = false;
272 public $incompleteForm = false;
275 public $tooBig = false;
278 public $missingComment = false;
281 public $missingSummary = false;
284 public $allowBlankSummary = false;
287 protected $blankArticle = false;
290 protected $allowBlankArticle = false;
293 protected $selfRedirect = false;
296 protected $allowSelfRedirect = false;
299 public $autoSumm = '';
302 public $hookError = '';
304 /** @var ParserOutput */
305 public $mParserOutput;
307 /** @var bool Has a summary been preset using GET parameter &summary= ? */
308 public $hasPresetSummary = false;
310 /** @var Revision|bool|null A revision object corresponding to $this->editRevId. */
311 public $mBaseRevision = false;
314 public $mShowSummaryField = true;
319 public $save = false;
322 public $preview = false;
325 public $diff = false;
328 public $minoredit = false;
331 public $watchthis = false;
334 public $recreate = false;
337 * Page content input field.
339 public $textbox1 = '';
342 public $textbox2 = '';
345 public $summary = '';
348 * If true, hide the summary field.
350 public $nosummary = false;
353 * Timestamp of the latest revision of the page when editing was initiated
356 public $edittime = '';
358 /** @var int Revision ID of the latest revision of the page when editing
359 * was initiated on the client. This is used to detect and resolve edit
362 * @note 0 if the page did not exist at that time.
363 * @note When starting an edit from an old revision, this still records the current
364 * revision at the time, not the one the edit is based on.
367 * @see getBaseRevision()
369 private $editRevId = null;
372 public $section = '';
375 public $sectiontitle = '';
378 * Timestamp from the first time the edit form was rendered.
380 public $starttime = '';
382 /** @var int Revision ID the edit is based on, or 0 if it's the current revision.
383 * FIXME: This isn't used in conflict resolution--provide a better
384 * justification or merge with parentRevId.
389 /** @var int Revision ID the edit is based on, adjusted when an edit conflict is resolved.
392 * @see getparentRevId()
394 public $parentRevId = 0;
397 public $editintro = '';
400 public $scrolltop = null;
406 public $contentModel;
408 /** @var null|string */
409 public $contentFormat = null;
411 /** @var null|array */
412 private $changeTags = null;
414 # Placeholders for text injection by hooks (must be HTML)
415 # extensions should take care to _append_ to the present value
417 /** @var string Before even the preview */
418 public $editFormPageTop = '';
419 public $editFormTextTop = '';
420 public $editFormTextBeforeContent = '';
421 public $editFormTextAfterWarn = '';
422 public $editFormTextAfterTools = '';
423 public $editFormTextBottom = '';
424 public $editFormTextAfterContent = '';
425 public $previewTextAfterContent = '';
426 public $mPreloadContent = null;
428 /* $didSave should be set to true whenever an article was successfully altered. */
429 public $didSave = false;
430 public $undidRev = 0;
432 public $suppressIntro = false;
438 protected $contentLength = false;
441 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
443 private $enableApiEditOverride = false;
446 * @var IContextSource
451 * @var bool Whether an old revision is edited
453 private $isOldRev = false;
456 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
458 private $unicodeCheck;
461 * Factory function to create an edit conflict helper
465 private $editConflictHelperFactory;
468 * @var TextConflictHelper|null
470 private $editConflictHelper;
473 * @param Article $article
475 public function __construct( Article
$article ) {
476 $this->mArticle
= $article;
477 $this->page
= $article->getPage(); // model object
478 $this->mTitle
= $article->getTitle();
480 // Make sure the local context is in sync with other member variables.
481 // Particularly make sure everything is using the same WikiPage instance.
482 // This should probably be the case in Article as well, but it's
483 // particularly important for EditPage, to make use of the in-place caching
484 // facility in WikiPage::prepareContentForEdit.
485 $this->context
= new DerivativeContext( $article->getContext() );
486 $this->context
->setWikiPage( $this->page
);
487 $this->context
->setTitle( $this->mTitle
);
489 $this->contentModel
= $this->mTitle
->getContentModel();
491 $handler = ContentHandler
::getForModelID( $this->contentModel
);
492 $this->contentFormat
= $handler->getDefaultFormat();
493 $this->editConflictHelperFactory
= [ $this, 'newTextConflictHelper' ];
499 public function getArticle() {
500 return $this->mArticle
;
505 * @return IContextSource
507 public function getContext() {
508 return $this->context
;
515 public function getTitle() {
516 return $this->mTitle
;
520 * Set the context Title object
522 * @param Title|null $title Title object or null
524 public function setContextTitle( $title ) {
525 $this->mContextTitle
= $title;
529 * Get the context title object.
531 * If not set, $wgTitle will be returned, but this is deprecated. This will
532 * throw an exception.
536 public function getContextTitle() {
537 if ( is_null( $this->mContextTitle
) ) {
538 wfDeprecated( __METHOD__
. ' called with no title set', '1.32' );
542 return $this->mContextTitle
;
547 * Returns if the given content model is editable.
549 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
551 * @throws MWException If $modelId has no known handler
553 public function isSupportedContentModel( $modelId ) {
554 return $this->enableApiEditOverride
=== true ||
555 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
559 * Allow editing of content that supports API direct editing, but not general
560 * direct editing. Set to false by default.
562 * @param bool $enableOverride
564 public function setApiEditOverride( $enableOverride ) {
565 $this->enableApiEditOverride
= $enableOverride;
569 * This is the function that gets called for "action=edit". It
570 * sets up various member variables, then passes execution to
571 * another function, usually showEditForm()
573 * The edit form is self-submitting, so that when things like
574 * preview and edit conflicts occur, we get the same form back
575 * with the extra stuff added. Only when the final submission
576 * is made and all is well do we actually save and redirect to
577 * the newly-edited page.
579 public function edit() {
580 // Allow extensions to modify/prevent this form or submission
581 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
585 wfDebug( __METHOD__
. ": enter\n" );
587 $request = $this->context
->getRequest();
588 // If they used redlink=1 and the page exists, redirect to the main article
589 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
590 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
594 $this->importFormData( $request );
595 $this->firsttime
= false;
597 if ( wfReadOnly() && $this->save
) {
600 $this->preview
= true;
604 $this->formtype
= 'save';
605 } elseif ( $this->preview
) {
606 $this->formtype
= 'preview';
607 } elseif ( $this->diff
) {
608 $this->formtype
= 'diff';
609 } else { # First time through
610 $this->firsttime
= true;
611 if ( $this->previewOnOpen() ) {
612 $this->formtype
= 'preview';
614 $this->formtype
= 'initial';
618 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
620 wfDebug( __METHOD__
. ": User can't edit\n" );
622 if ( $this->context
->getUser()->getBlock() ) {
623 // track block with a cookie if it doesn't exists already
624 $this->context
->getUser()->trackBlockWithCookie();
626 // Auto-block user's IP if the account was "hard" blocked
627 if ( !wfReadOnly() ) {
628 DeferredUpdates
::addCallableUpdate( function () {
629 $this->context
->getUser()->spreadAnyEditBlock();
633 $this->displayPermissionsError( $permErrors );
638 $revision = $this->mArticle
->getRevisionFetched();
639 // Disallow editing revisions with content models different from the current one
640 // Undo edits being an exception in order to allow reverting content model changes.
642 && $revision->getContentModel() !== $this->contentModel
645 if ( $this->undidRev
) {
646 $undidRevObj = Revision
::newFromId( $this->undidRev
);
647 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
649 if ( !$this->undidRev
651 ||
$prevRev->getContentModel() !== $this->contentModel
653 $this->displayViewSourcePage(
654 $this->getContentObject(),
656 'contentmodelediterror',
657 $revision->getContentModel(),
665 $this->isConflict
= false;
667 # Show applicable editing introductions
668 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
672 # Attempt submission here. This will check for edit conflicts,
673 # and redundantly check for locked database, blocked IPs, etc.
674 # that edit() already checked just in case someone tries to sneak
675 # in the back door with a hand-edited submission URL.
677 if ( $this->formtype
== 'save' ) {
678 $resultDetails = null;
679 $status = $this->attemptSave( $resultDetails );
680 if ( !$this->handleStatus( $status, $resultDetails ) ) {
685 # First time through: get contents, set time for conflict
687 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
688 if ( $this->initialiseForm() === false ) {
689 $out = $this->context
->getOutput();
690 if ( $out->getRedirect() === '' ) { // mcrundo hack redirects, don't override it
691 $this->noSuchSectionPage();
696 if ( !$this->mTitle
->getArticleID() ) {
697 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
699 Hooks
::run( 'EditFormInitialText', [ $this ] );
704 $this->showEditForm();
708 * @param string $rigor Same format as Title::getUserPermissionErrors()
711 protected function getEditPermissionErrors( $rigor = 'secure' ) {
712 $user = $this->context
->getUser();
713 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
714 # Can this title be created?
715 if ( !$this->mTitle
->exists() ) {
716 $permErrors = array_merge(
719 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
724 # Ignore some permissions errors when a user is just previewing/viewing diffs
726 foreach ( $permErrors as $error ) {
727 if ( ( $this->preview ||
$this->diff
)
729 $error[0] == 'blockedtext' ||
730 $error[0] == 'autoblockedtext' ||
731 $error[0] == 'systemblockedtext'
737 $permErrors = wfArrayDiff2( $permErrors, $remove );
743 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
744 * but with the following differences:
745 * - If redlink=1, the user will be redirected to the page
746 * - If there is content to display or the error occurs while either saving,
747 * previewing or showing the difference, it will be a
748 * "View source for ..." page displaying the source code after the error message.
751 * @param array $permErrors Array of permissions errors, as returned by
752 * Title::getUserPermissionsErrors().
753 * @throws PermissionsError
755 protected function displayPermissionsError( array $permErrors ) {
756 $out = $this->context
->getOutput();
757 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
758 // The edit page was reached via a red link.
759 // Redirect to the article page and let them click the edit tab if
760 // they really want a permission error.
761 $out->redirect( $this->mTitle
->getFullURL() );
765 $content = $this->getContentObject();
767 # Use the normal message if there's nothing to display
768 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
769 $action = $this->mTitle
->exists() ?
'edit' :
770 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
771 throw new PermissionsError( $action, $permErrors );
774 $this->displayViewSourcePage(
776 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
781 * Display a read-only View Source page
782 * @param Content $content
783 * @param string $errorMessage additional wikitext error message to display
785 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
786 $out = $this->context
->getOutput();
787 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
789 $out->setRobotPolicy( 'noindex,nofollow' );
790 $out->setPageTitle( $this->context
->msg(
792 $this->getContextTitle()->getPrefixedText()
794 $out->addBacklinkSubtitle( $this->getContextTitle() );
795 $out->addHTML( $this->editFormPageTop
);
796 $out->addHTML( $this->editFormTextTop
);
798 if ( $errorMessage !== '' ) {
799 $out->addWikiTextAsInterface( $errorMessage );
800 $out->addHTML( "<hr />\n" );
803 # If the user made changes, preserve them when showing the markup
804 # (This happens when a user is blocked during edit, for instance)
805 if ( !$this->firsttime
) {
806 $text = $this->textbox1
;
807 $out->addWikiMsg( 'viewyourtext' );
810 $text = $this->toEditText( $content );
811 } catch ( MWException
$e ) {
812 # Serialize using the default format if the content model is not supported
813 # (e.g. for an old revision with a different model)
814 $text = $content->serialize();
816 $out->addWikiMsg( 'viewsourcetext' );
819 $out->addHTML( $this->editFormTextBeforeContent
);
820 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
821 $out->addHTML( $this->editFormTextAfterContent
);
823 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
825 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
827 $out->addHTML( $this->editFormTextBottom
);
828 if ( $this->mTitle
->exists() ) {
829 $out->returnToMain( null, $this->mTitle
);
834 * Should we show a preview when the edit form is first shown?
838 protected function previewOnOpen() {
839 $config = $this->context
->getConfig();
840 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
841 $request = $this->context
->getRequest();
842 if ( $config->get( 'RawHtml' ) ) {
843 // If raw HTML is enabled, disable preview on open
844 // since it has to be posted with a token for
848 if ( $request->getVal( 'preview' ) == 'yes' ) {
849 // Explicit override from request
851 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
852 // Explicit override from request
854 } elseif ( $this->section
== 'new' ) {
855 // Nothing *to* preview for new sections
857 } elseif ( ( $request->getCheck( 'preload' ) ||
$this->mTitle
->exists() )
858 && $this->context
->getUser()->getOption( 'previewonfirst' )
860 // Standard preference behavior
862 } elseif ( !$this->mTitle
->exists()
863 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
864 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
866 // Categories are special
874 * Checks whether the user entered a skin name in uppercase,
875 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
879 protected function isWrongCaseUserConfigPage() {
880 if ( $this->mTitle
->isUserConfigPage() ) {
881 $name = $this->mTitle
->getSkinFromConfigSubpage();
882 $skins = array_merge(
883 array_keys( Skin
::getSkinNames() ),
886 return !in_array( $name, $skins )
887 && in_array( strtolower( $name ), $skins );
894 * Returns whether section editing is supported for the current page.
895 * Subclasses may override this to replace the default behavior, which is
896 * to check ContentHandler::supportsSections.
898 * @return bool True if this edit page supports sections, false otherwise.
900 protected function isSectionEditSupported() {
901 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
902 return $contentHandler->supportsSections();
906 * This function collects the form data and uses it to populate various member variables.
907 * @param WebRequest &$request
908 * @throws ErrorPageError
910 public function importFormData( &$request ) {
911 # Section edit can come from either the form or a link
912 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
914 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
915 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
918 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
920 if ( $request->wasPosted() ) {
921 # These fields need to be checked for encoding.
922 # Also remove trailing whitespace, but don't remove _initial_
923 # whitespace from the text boxes. This may be significant formatting.
924 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
925 if ( !$request->getCheck( 'wpTextbox2' ) ) {
926 // Skip this if wpTextbox2 has input, it indicates that we came
927 // from a conflict page with raw page text, not a custom form
928 // modified by subclasses
929 $textbox1 = $this->importContentFormData( $request );
930 if ( $textbox1 !== null ) {
931 $this->textbox1
= $textbox1;
935 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
937 $this->summary
= $request->getText( 'wpSummary' );
939 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
940 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
942 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
944 # Treat sectiontitle the same way as summary.
945 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
946 # currently doing double duty as both edit summary and section title. Right now this
947 # is just to allow API edits to work around this limitation, but this should be
948 # incorporated into the actual edit form when EditPage is rewritten (T20654, T28312).
949 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
950 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
952 $this->edittime
= $request->getVal( 'wpEdittime' );
953 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
954 $this->starttime
= $request->getVal( 'wpStarttime' );
956 $undidRev = $request->getInt( 'wpUndidRevision' );
958 $this->undidRev
= $undidRev;
961 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
963 if ( $this->textbox1
=== '' && !$request->getCheck( 'wpTextbox1' ) ) {
964 // wpTextbox1 field is missing, possibly due to being "too big"
965 // according to some filter rules such as Suhosin's setting for
966 // suhosin.request.max_value_length (d'oh)
967 $this->incompleteForm
= true;
969 // If we receive the last parameter of the request, we can fairly
970 // claim the POST request has not been truncated.
971 $this->incompleteForm
= !$request->getVal( 'wpUltimateParam' );
973 if ( $this->incompleteForm
) {
974 # If the form is incomplete, force to preview.
975 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
976 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
977 $this->preview
= true;
979 $this->preview
= $request->getCheck( 'wpPreview' );
980 $this->diff
= $request->getCheck( 'wpDiff' );
982 // Remember whether a save was requested, so we can indicate
983 // if we forced preview due to session failure.
984 $this->mTriedSave
= !$this->preview
;
986 if ( $this->tokenOk( $request ) ) {
987 # Some browsers will not report any submit button
988 # if the user hits enter in the comment box.
989 # The unmarked state will be assumed to be a save,
990 # if the form seems otherwise complete.
991 wfDebug( __METHOD__
. ": Passed token check.\n" );
992 } elseif ( $this->diff
) {
993 # Failed token check, but only requested "Show Changes".
994 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
996 # Page might be a hack attempt posted from
997 # an external site. Preview instead of saving.
998 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
999 $this->preview
= true;
1002 $this->save
= !$this->preview
&& !$this->diff
;
1003 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
1004 $this->edittime
= null;
1007 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
1008 $this->starttime
= null;
1011 $this->recreate
= $request->getCheck( 'wpRecreate' );
1013 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
1014 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
1016 $user = $this->context
->getUser();
1017 # Don't force edit summaries when a user is editing their own user or talk page
1018 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
1019 && $this->mTitle
->getText() == $user->getName()
1021 $this->allowBlankSummary
= true;
1023 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1024 ||
!$user->getOption( 'forceeditsummary' );
1027 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1029 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1030 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1032 $changeTags = $request->getVal( 'wpChangeTags' );
1033 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1034 $this->changeTags
= [];
1036 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1040 # Not a posted form? Start with nothing.
1041 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1042 $this->textbox1
= '';
1043 $this->summary
= '';
1044 $this->sectiontitle
= '';
1045 $this->edittime
= '';
1046 $this->editRevId
= null;
1047 $this->starttime
= wfTimestampNow();
1048 $this->edit
= false;
1049 $this->preview
= false;
1050 $this->save
= false;
1051 $this->diff
= false;
1052 $this->minoredit
= false;
1053 // Watch may be overridden by request parameters
1054 $this->watchthis
= $request->getBool( 'watchthis', false );
1055 $this->recreate
= false;
1057 // When creating a new section, we can preload a section title by passing it as the
1058 // preloadtitle parameter in the URL (T15100)
1059 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1060 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1061 // Once wpSummary isn't being use for setting section titles, we should delete this.
1062 $this->summary
= $request->getVal( 'preloadtitle' );
1063 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) !== '' ) {
1064 $this->summary
= $request->getText( 'summary' );
1065 if ( $this->summary
!== '' ) {
1066 $this->hasPresetSummary
= true;
1070 if ( $request->getVal( 'minor' ) ) {
1071 $this->minoredit
= true;
1075 $this->oldid
= $request->getInt( 'oldid' );
1076 $this->parentRevId
= $request->getInt( 'parentRevId' );
1078 $this->bot
= $request->getBool( 'bot', true );
1079 $this->nosummary
= $request->getBool( 'nosummary' );
1081 // May be overridden by revision.
1082 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1083 // May be overridden by revision.
1084 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1087 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1088 } catch ( MWUnknownContentModelException
$e ) {
1089 throw new ErrorPageError(
1090 'editpage-invalidcontentmodel-title',
1091 'editpage-invalidcontentmodel-text',
1092 [ wfEscapeWikiText( $this->contentModel
) ]
1096 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1097 throw new ErrorPageError(
1098 'editpage-notsupportedcontentformat-title',
1099 'editpage-notsupportedcontentformat-text',
1101 wfEscapeWikiText( $this->contentFormat
),
1102 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1108 * @todo Check if the desired model is allowed in this namespace, and if
1109 * a transition from the page's current model to the new model is
1113 $this->editintro
= $request->getText( 'editintro',
1114 // Custom edit intro for new sections
1115 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1117 // Allow extensions to modify form data
1118 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1122 * Subpage overridable method for extracting the page content data from the
1123 * posted form to be placed in $this->textbox1, if using customized input
1124 * this method should be overridden and return the page text that will be used
1125 * for saving, preview parsing and so on...
1127 * @param WebRequest &$request
1128 * @return string|null
1130 protected function importContentFormData( &$request ) {
1131 return; // Don't do anything, EditPage already extracted wpTextbox1
1135 * Initialise form fields in the object
1136 * Called on the first invocation, e.g. when a user clicks an edit link
1137 * @return bool If the requested section is valid
1139 public function initialiseForm() {
1140 $this->edittime
= $this->page
->getTimestamp();
1141 $this->editRevId
= $this->page
->getLatest();
1143 $content = $this->getContentObject( false ); # TODO: track content object?!
1144 if ( $content === false ) {
1147 $this->textbox1
= $this->toEditText( $content );
1149 $user = $this->context
->getUser();
1150 // activate checkboxes if user wants them to be always active
1151 # Sort out the "watch" checkbox
1152 if ( $user->getOption( 'watchdefault' ) ) {
1154 $this->watchthis
= true;
1155 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1157 $this->watchthis
= true;
1158 } elseif ( $user->isWatched( $this->mTitle
) ) {
1160 $this->watchthis
= true;
1162 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1163 $this->minoredit
= true;
1165 if ( $this->textbox1
=== false ) {
1172 * @param Content|null $def_content The default value to return
1174 * @return Content|null Content on success, $def_content for invalid sections
1178 protected function getContentObject( $def_content = null ) {
1181 $user = $this->context
->getUser();
1182 $request = $this->context
->getRequest();
1183 // For message page not locally set, use the i18n message.
1184 // For other non-existent articles, use preload text if any.
1185 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1186 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1187 # If this is a system message, get the default text.
1188 $msg = $this->mTitle
->getDefaultMessageText();
1190 $content = $this->toEditContent( $msg );
1192 if ( $content === false ) {
1193 # If requested, preload some text.
1194 $preload = $request->getVal( 'preload',
1195 // Custom preload text for new sections
1196 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1197 $params = $request->getArray( 'preloadparams', [] );
1199 $content = $this->getPreloadedContent( $preload, $params );
1201 // For existing pages, get text based on "undo" or section parameters.
1202 } elseif ( $this->section
!= '' ) {
1203 // Get section edit text (returns $def_text for invalid sections)
1204 $orig = $this->getOriginalContent( $user );
1205 $content = $orig ?
$orig->getSection( $this->section
) : null;
1208 $content = $def_content;
1211 $undoafter = $request->getInt( 'undoafter' );
1212 $undo = $request->getInt( 'undo' );
1214 if ( $undo > 0 && $undoafter > 0 ) {
1215 $undorev = Revision
::newFromId( $undo );
1216 $oldrev = Revision
::newFromId( $undoafter );
1219 # Sanity check, make sure it's the right page,
1220 # the revisions exist and they were not deleted.
1221 # Otherwise, $content will be left as-is.
1222 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1223 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1224 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1226 if ( WikiPage
::hasDifferencesOutsideMainSlot( $undorev, $oldrev )
1227 ||
!$this->isSupportedContentModel( $oldrev->getContentModel() )
1229 // Hack for undo while EditPage can't handle multi-slot editing
1230 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL( [
1231 'action' => 'mcrundo',
1233 'undoafter' => $undoafter,
1237 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1239 if ( $content === false ) {
1240 # Warn the user that something went wrong
1241 $undoMsg = 'failure';
1245 if ( $undoMsg === null ) {
1246 $oldContent = $this->page
->getContent( Revision
::RAW
);
1247 $popts = ParserOptions
::newFromUserAndLang(
1248 $user, MediaWikiServices
::getInstance()->getContentLanguage() );
1249 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1250 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1251 // The undo may change content
1252 // model if its reverting the top
1253 // edit. This can result in
1254 // mismatched content model/format.
1255 $this->contentModel
= $newContent->getModel();
1256 $this->contentFormat
= $oldrev->getContentFormat();
1259 if ( $newContent->equals( $oldContent ) ) {
1260 # Tell the user that the undo results in no change,
1261 # i.e. the revisions were already undone.
1262 $undoMsg = 'nochange';
1265 # Inform the user of our success and set an automatic edit summary
1266 $undoMsg = 'success';
1268 # If we just undid one rev, use an autosummary
1269 $firstrev = $oldrev->getNext();
1270 if ( $firstrev && $firstrev->getId() == $undo ) {
1271 $userText = $undorev->getUserText();
1272 if ( $userText === '' ) {
1273 $undoSummary = $this->context
->msg(
1274 'undo-summary-username-hidden',
1276 )->inContentLanguage()->text();
1278 $undoSummary = $this->context
->msg(
1282 )->inContentLanguage()->text();
1284 if ( $this->summary
=== '' ) {
1285 $this->summary
= $undoSummary;
1287 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1288 ->inContentLanguage()->text() . $this->summary
;
1290 $this->undidRev
= $undo;
1292 $this->formtype
= 'diff';
1296 // Failed basic sanity checks.
1297 // Older revisions may have been removed since the link
1298 // was created, or we may simply have got bogus input.
1302 $out = $this->context
->getOutput();
1303 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1305 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1306 $this->editFormPageTop
.= Html
::rawElement(
1307 'div', [ 'class' => $class ],
1308 $out->parseAsInterface(
1309 $this->context
->msg( 'undo-' . $undoMsg )->plain()
1314 if ( $content === false ) {
1315 // Hack for restoring old revisions while EditPage
1316 // can't handle multi-slot editing.
1318 $curRevision = $this->page
->getRevision();
1319 $oldRevision = $this->mArticle
->getRevisionFetched();
1323 && $curRevision->getId() !== $oldRevision->getId()
1324 && ( WikiPage
::hasDifferencesOutsideMainSlot( $oldRevision, $curRevision )
1325 ||
!$this->isSupportedContentModel( $oldRevision->getContentModel() ) )
1327 $this->context
->getOutput()->redirect(
1328 $this->mTitle
->getFullURL(
1330 'action' => 'mcrrestore',
1331 'restore' => $oldRevision->getId(),
1340 if ( $content === false ) {
1341 $content = $this->getOriginalContent( $user );
1349 * Get the content of the wanted revision, without section extraction.
1351 * The result of this function can be used to compare user's input with
1352 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1353 * to the original text of the edit.
1355 * This differs from Article::getContent() that when a missing revision is
1356 * encountered the result will be null and not the
1357 * 'missing-revision' message.
1360 * @param User $user The user to get the revision for
1361 * @return Content|null
1363 private function getOriginalContent( User
$user ) {
1364 if ( $this->section
== 'new' ) {
1365 return $this->getCurrentContent();
1367 $revision = $this->mArticle
->getRevisionFetched();
1368 if ( $revision === null ) {
1369 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1370 return $handler->makeEmptyContent();
1372 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1377 * Get the edit's parent revision ID
1379 * The "parent" revision is the ancestor that should be recorded in this
1380 * page's revision history. It is either the revision ID of the in-memory
1381 * article content, or in the case of a 3-way merge in order to rebase
1382 * across a recoverable edit conflict, the ID of the newer revision to
1383 * which we have rebased this page.
1386 * @return int Revision ID
1388 public function getParentRevId() {
1389 if ( $this->parentRevId
) {
1390 return $this->parentRevId
;
1392 return $this->mArticle
->getRevIdFetched();
1397 * Get the current content of the page. This is basically similar to
1398 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1399 * content object is returned instead of null.
1404 protected function getCurrentContent() {
1405 $rev = $this->page
->getRevision();
1406 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1408 if ( $content === false ||
$content === null ) {
1409 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1410 return $handler->makeEmptyContent();
1411 } elseif ( !$this->undidRev
) {
1412 // Content models should always be the same since we error
1413 // out if they are different before this point (in ->edit()).
1414 // The exception being, during an undo, the current revision might
1415 // differ from the prior revision.
1416 $logger = LoggerFactory
::getInstance( 'editpage' );
1417 if ( $this->contentModel
!== $rev->getContentModel() ) {
1418 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1419 'prev' => $this->contentModel
,
1420 'new' => $rev->getContentModel(),
1421 'title' => $this->getTitle()->getPrefixedDBkey(),
1422 'method' => __METHOD__
1424 $this->contentModel
= $rev->getContentModel();
1427 // Given that the content models should match, the current selected
1428 // format should be supported.
1429 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1430 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1432 'prev' => $this->contentFormat
,
1433 'new' => $rev->getContentFormat(),
1434 'title' => $this->getTitle()->getPrefixedDBkey(),
1435 'method' => __METHOD__
1437 $this->contentFormat
= $rev->getContentFormat();
1444 * Use this method before edit() to preload some content into the edit box
1446 * @param Content $content
1450 public function setPreloadedContent( Content
$content ) {
1451 $this->mPreloadContent
= $content;
1455 * Get the contents to be preloaded into the box, either set by
1456 * an earlier setPreloadText() or by loading the given page.
1458 * @param string $preload Representing the title to preload from.
1459 * @param array $params Parameters to use (interface-message style) in the preloaded text
1465 protected function getPreloadedContent( $preload, $params = [] ) {
1466 if ( !empty( $this->mPreloadContent
) ) {
1467 return $this->mPreloadContent
;
1470 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1472 if ( $preload === '' ) {
1473 return $handler->makeEmptyContent();
1476 $user = $this->context
->getUser();
1477 $title = Title
::newFromText( $preload );
1479 # Check for existence to avoid getting MediaWiki:Noarticletext
1480 if ( !$this->isPageExistingAndViewable( $title, $user ) ) {
1481 // TODO: somehow show a warning to the user!
1482 return $handler->makeEmptyContent();
1485 $page = WikiPage
::factory( $title );
1486 if ( $page->isRedirect() ) {
1487 $title = $page->getRedirectTarget();
1489 if ( !$this->isPageExistingAndViewable( $title, $user ) ) {
1490 // TODO: somehow show a warning to the user!
1491 return $handler->makeEmptyContent();
1493 $page = WikiPage
::factory( $title );
1496 $parserOptions = ParserOptions
::newFromUser( $user );
1497 $content = $page->getContent( Revision
::RAW
);
1500 // TODO: somehow show a warning to the user!
1501 return $handler->makeEmptyContent();
1504 if ( $content->getModel() !== $handler->getModelID() ) {
1505 $converted = $content->convert( $handler->getModelID() );
1507 if ( !$converted ) {
1508 // TODO: somehow show a warning to the user!
1509 wfDebug( "Attempt to preload incompatible content: " .
1510 "can't convert " . $content->getModel() .
1511 " to " . $handler->getModelID() );
1513 return $handler->makeEmptyContent();
1516 $content = $converted;
1519 return $content->preloadTransform( $title, $parserOptions, $params );
1523 * Verify if a given title exists and the given user is allowed to view it
1525 * @see EditPage::getPreloadedContent()
1526 * @param Title|null $title
1531 private function isPageExistingAndViewable( $title, User
$user ) {
1532 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
1534 return $title && $title->exists() && $permissionManager->userCan( 'read', $user, $title );
1538 * Make sure the form isn't faking a user's credentials.
1540 * @param WebRequest &$request
1544 public function tokenOk( &$request ) {
1545 $token = $request->getVal( 'wpEditToken' );
1546 $user = $this->context
->getUser();
1547 $this->mTokenOk
= $user->matchEditToken( $token );
1548 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1549 return $this->mTokenOk
;
1553 * Sets post-edit cookie indicating the user just saved a particular revision.
1555 * This uses a temporary cookie for each revision ID so separate saves will never
1556 * interfere with each other.
1558 * Article::view deletes the cookie on server-side after the redirect and
1559 * converts the value to the global JavaScript variable wgPostEdit.
1561 * If the variable were set on the server, it would be cached, which is unwanted
1562 * since the post-edit state should only apply to the load right after the save.
1564 * @param int $statusValue The status value (to check for new article status)
1566 protected function setPostEditCookie( $statusValue ) {
1567 $revisionId = $this->page
->getLatest();
1568 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1571 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1573 } elseif ( $this->oldid
) {
1577 $response = $this->context
->getRequest()->response();
1578 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1582 * Attempt submission
1583 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1584 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1585 * @return Status The resulting status object.
1587 public function attemptSave( &$resultDetails = false ) {
1588 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1589 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1590 // This is needed since PageUpdater no longer checks these rights!
1592 // Allow bots to exempt some edits from bot flagging
1593 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1594 $status = $this->internalAttemptSave( $resultDetails, $bot );
1596 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1602 * Log when a page was successfully saved after the edit conflict view
1604 private function incrementResolvedConflicts() {
1605 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1609 $this->getEditConflictHelper()->incrementResolvedStats();
1613 * Handle status, such as after attempt save
1615 * @param Status $status
1616 * @param array|bool $resultDetails
1618 * @throws ErrorPageError
1619 * @return bool False, if output is done, true if rest of the form should be displayed
1621 private function handleStatus( Status
$status, $resultDetails ) {
1623 * @todo FIXME: once the interface for internalAttemptSave() is made
1624 * nicer, this should use the message in $status
1626 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1627 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1629 $this->incrementResolvedConflicts();
1631 $this->didSave
= true;
1632 if ( !$resultDetails['nullEdit'] ) {
1633 $this->setPostEditCookie( $status->value
);
1637 $out = $this->context
->getOutput();
1639 // "wpExtraQueryRedirect" is a hidden input to modify
1640 // after save URL and is not used by actual edit form
1641 $request = $this->context
->getRequest();
1642 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1644 switch ( $status->value
) {
1645 case self
::AS_HOOK_ERROR_EXPECTED
:
1646 case self
::AS_CONTENT_TOO_BIG
:
1647 case self
::AS_ARTICLE_WAS_DELETED
:
1648 case self
::AS_CONFLICT_DETECTED
:
1649 case self
::AS_SUMMARY_NEEDED
:
1650 case self
::AS_TEXTBOX_EMPTY
:
1651 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1653 case self
::AS_BLANK_ARTICLE
:
1654 case self
::AS_SELF_REDIRECT
:
1657 case self
::AS_HOOK_ERROR
:
1660 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1661 case self
::AS_PARSE_ERROR
:
1662 case self
::AS_UNICODE_NOT_SUPPORTED
:
1663 $out->wrapWikiTextAsInterface( 'error', $status->getWikiText() );
1666 case self
::AS_SUCCESS_NEW_ARTICLE
:
1667 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1668 if ( $extraQueryRedirect ) {
1669 if ( $query !== '' ) {
1672 $query .= $extraQueryRedirect;
1674 $anchor = $resultDetails['sectionanchor'] ??
'';
1675 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1678 case self
::AS_SUCCESS_UPDATE
:
1680 $sectionanchor = $resultDetails['sectionanchor'];
1682 // Give extensions a chance to modify URL query on update
1684 'ArticleUpdateBeforeRedirect',
1685 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1688 if ( $resultDetails['redirect'] ) {
1689 if ( $extraQuery !== '' ) {
1690 $extraQuery = '&' . $extraQuery;
1692 $extraQuery = 'redirect=no' . $extraQuery;
1694 if ( $extraQueryRedirect ) {
1695 if ( $extraQuery !== '' ) {
1698 $extraQuery .= $extraQueryRedirect;
1701 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1704 case self
::AS_SPAM_ERROR
:
1705 $this->spamPageWithContent( $resultDetails['spam'] );
1708 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1709 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1711 case self
::AS_IMAGE_REDIRECT_ANON
:
1712 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1713 throw new PermissionsError( 'upload' );
1715 case self
::AS_READ_ONLY_PAGE_ANON
:
1716 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1717 throw new PermissionsError( 'edit' );
1719 case self
::AS_READ_ONLY_PAGE
:
1720 throw new ReadOnlyError
;
1722 case self
::AS_RATE_LIMITED
:
1723 throw new ThrottledError();
1725 case self
::AS_NO_CREATE_PERMISSION
:
1726 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1727 throw new PermissionsError( $permission );
1729 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1730 throw new PermissionsError( 'editcontentmodel' );
1733 // We don't recognize $status->value. The only way that can happen
1734 // is if an extension hook aborted from inside ArticleSave.
1735 // Render the status object into $this->hookError
1736 // FIXME this sucks, we should just use the Status object throughout
1737 $this->hookError
= '<div class="error">' . "\n" . $status->getWikiText() .
1744 * Run hooks that can filter edits just before they get saved.
1746 * @param Content $content The Content to filter.
1747 * @param Status $status For reporting the outcome to the caller
1748 * @param User $user The user performing the edit
1752 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1753 // Run old style post-section-merge edit filter
1754 if ( $this->hookError
!= '' ) {
1755 # ...or the hook could be expecting us to produce an error
1756 $status->fatal( 'hookaborted' );
1757 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1761 // Run new style post-section-merge edit filter
1762 if ( !Hooks
::run( 'EditFilterMergedContent',
1763 [ $this->context
, $content, $status, $this->summary
,
1764 $user, $this->minoredit
] )
1766 # Error messages etc. could be handled within the hook...
1767 if ( $status->isGood() ) {
1768 $status->fatal( 'hookaborted' );
1769 // Not setting $this->hookError here is a hack to allow the hook
1770 // to cause a return to the edit page without $this->hookError
1771 // being set. This is used by ConfirmEdit to display a captcha
1772 // without any error message cruft.
1774 $this->hookError
= $this->formatStatusErrors( $status );
1776 // Use the existing $status->value if the hook set it
1777 if ( !$status->value
) {
1778 $status->value
= self
::AS_HOOK_ERROR
;
1781 } elseif ( !$status->isOK() ) {
1782 # ...or the hook could be expecting us to produce an error
1783 // FIXME this sucks, we should just use the Status object throughout
1784 $this->hookError
= $this->formatStatusErrors( $status );
1785 $status->fatal( 'hookaborted' );
1786 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1794 * Wrap status errors in an errorbox for increased visibility
1796 * @param Status $status
1797 * @return string Wikitext
1799 private function formatStatusErrors( Status
$status ) {
1800 $errmsg = $status->getWikiText(
1803 $this->context
->getLanguage()
1806 <div class="errorbox">
1814 * Return the summary to be used for a new section.
1816 * @param string $sectionanchor Set to the section anchor text
1819 private function newSectionSummary( &$sectionanchor = null ) {
1820 if ( $this->sectiontitle
!== '' ) {
1821 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1822 // If no edit summary was specified, create one automatically from the section
1823 // title and have it link to the new section. Otherwise, respect the summary as
1825 if ( $this->summary
=== '' ) {
1826 $cleanSectionTitle = MediaWikiServices
::getInstance()->getParser()
1827 ->stripSectionName( $this->sectiontitle
);
1828 return $this->context
->msg( 'newsectionsummary' )
1829 ->plaintextParams( $cleanSectionTitle )->inContentLanguage()->text();
1831 } elseif ( $this->summary
!== '' ) {
1832 $sectionanchor = $this->guessSectionName( $this->summary
);
1833 # This is a new section, so create a link to the new section
1834 # in the revision summary.
1835 $cleanSummary = MediaWikiServices
::getInstance()->getParser()
1836 ->stripSectionName( $this->summary
);
1837 return $this->context
->msg( 'newsectionsummary' )
1838 ->plaintextParams( $cleanSummary )->inContentLanguage()->text();
1840 return $this->summary
;
1844 * Attempt submission (no UI)
1846 * @param array &$result Array to add statuses to, currently with the
1848 * - spam (string): Spam string from content if any spam is detected by
1850 * - sectionanchor (string): Section anchor for a section save.
1851 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1853 * - redirect (bool): Set if doEditContent is OK. True if resulting
1854 * revision is a redirect.
1855 * @param bool $bot True if edit is being made under the bot right.
1857 * @return Status Status object, possibly with a message, but always with
1858 * one of the AS_* constants in $status->value,
1860 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1861 * various error display idiosyncrasies. There are also lots of cases
1862 * where error metadata is set in the object and retrieved later instead
1863 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1864 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1867 public function internalAttemptSave( &$result, $bot = false ) {
1868 $status = Status
::newGood();
1869 $user = $this->context
->getUser();
1871 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1872 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1873 $status->fatal( 'hookaborted' );
1874 $status->value
= self
::AS_HOOK_ERROR
;
1878 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1879 $status->fatal( 'unicode-support-fail' );
1880 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1884 $request = $this->context
->getRequest();
1885 $spam = $request->getText( 'wpAntispam' );
1886 if ( $spam !== '' ) {
1891 $this->mTitle
->getPrefixedText() .
1892 '" submitted bogus field "' .
1896 $status->fatal( 'spamprotectionmatch', false );
1897 $status->value
= self
::AS_SPAM_ERROR
;
1902 # Construct Content object
1903 $textbox_content = $this->toEditContent( $this->textbox1
);
1904 } catch ( MWContentSerializationException
$ex ) {
1906 'content-failed-to-parse',
1907 $this->contentModel
,
1908 $this->contentFormat
,
1911 $status->value
= self
::AS_PARSE_ERROR
;
1915 # Check image redirect
1916 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1917 $textbox_content->isRedirect() &&
1918 !$user->isAllowed( 'upload' )
1920 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1921 $status->setResult( false, $code );
1927 $match = self
::matchSummarySpamRegex( $this->summary
);
1928 if ( $match === false && $this->section
== 'new' ) {
1929 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1930 # regular summaries, it is added to the actual wikitext.
1931 if ( $this->sectiontitle
!== '' ) {
1932 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1933 $match = self
::matchSpamRegex( $this->sectiontitle
);
1935 # This branch is taken when the "Add Topic" user interface is used, or the API
1936 # is used with the 'summary' parameter.
1937 $match = self
::matchSpamRegex( $this->summary
);
1940 if ( $match === false ) {
1941 $match = self
::matchSpamRegex( $this->textbox1
);
1943 if ( $match !== false ) {
1944 $result['spam'] = $match;
1945 $ip = $request->getIP();
1946 $pdbk = $this->mTitle
->getPrefixedDBkey();
1947 $match = str_replace( "\n", '', $match );
1948 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1949 $status->fatal( 'spamprotectionmatch', $match );
1950 $status->value
= self
::AS_SPAM_ERROR
;
1955 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1957 # Error messages etc. could be handled within the hook...
1958 $status->fatal( 'hookaborted' );
1959 $status->value
= self
::AS_HOOK_ERROR
;
1961 } elseif ( $this->hookError
!= '' ) {
1962 # ...or the hook could be expecting us to produce an error
1963 $status->fatal( 'hookaborted' );
1964 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1968 if ( $user->isBlockedFrom( $this->mTitle
) ) {
1969 // Auto-block user's IP if the account was "hard" blocked
1970 if ( !wfReadOnly() ) {
1971 $user->spreadAnyEditBlock();
1973 # Check block state against master, thus 'false'.
1974 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1978 $this->contentLength
= strlen( $this->textbox1
);
1979 $config = $this->context
->getConfig();
1980 $maxArticleSize = $config->get( 'MaxArticleSize' );
1981 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1982 // Error will be displayed by showEditForm()
1983 $this->tooBig
= true;
1984 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1988 if ( !$user->isAllowed( 'edit' ) ) {
1989 if ( $user->isAnon() ) {
1990 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1993 $status->fatal( 'readonlytext' );
1994 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1999 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
2001 $changingContentModel = false;
2002 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
2003 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
2004 $status->fatal( 'editpage-cannot-use-custom-model' );
2005 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
2007 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
2008 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2011 // Make sure the user can edit the page under the new content model too
2012 $titleWithNewContentModel = clone $this->mTitle
;
2013 $titleWithNewContentModel->setContentModel( $this->contentModel
);
2015 $canEditModel = $permissionManager->userCan(
2018 $titleWithNewContentModel
2023 ||
!$permissionManager->userCan( 'edit', $user, $titleWithNewContentModel )
2025 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2030 $changingContentModel = true;
2031 $oldContentModel = $this->mTitle
->getContentModel();
2034 if ( $this->changeTags
) {
2035 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
2036 $this->changeTags
, $user );
2037 if ( !$changeTagsStatus->isOK() ) {
2038 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
2039 return $changeTagsStatus;
2043 if ( wfReadOnly() ) {
2044 $status->fatal( 'readonlytext' );
2045 $status->value
= self
::AS_READ_ONLY_PAGE
;
2048 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
2049 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
2051 $status->fatal( 'actionthrottledtext' );
2052 $status->value
= self
::AS_RATE_LIMITED
;
2056 # If the article has been deleted while editing, don't save it without
2058 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
2059 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
2063 # Load the page data from the master. If anything changes in the meantime,
2064 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
2065 $this->page
->loadPageData( 'fromdbmaster' );
2066 $new = !$this->page
->exists();
2069 // Late check for create permission, just in case *PARANOIA*
2070 if ( !$permissionManager->userCan( 'create', $user, $this->mTitle
) ) {
2071 $status->fatal( 'nocreatetext' );
2072 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
2073 wfDebug( __METHOD__
. ": no create permission\n" );
2077 // Don't save a new page if it's blank or if it's a MediaWiki:
2078 // message with content equivalent to default (allow empty pages
2079 // in this case to disable messages, see T52124)
2080 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2081 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
2082 $defaultText = $defaultMessageText;
2087 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
2088 $this->blankArticle
= true;
2089 $status->fatal( 'blankarticle' );
2090 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
2094 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2098 $content = $textbox_content;
2100 $result['sectionanchor'] = '';
2101 if ( $this->section
== 'new' ) {
2102 if ( $this->sectiontitle
!== '' ) {
2103 // Insert the section title above the content.
2104 $content = $content->addSectionHeader( $this->sectiontitle
);
2105 } elseif ( $this->summary
!== '' ) {
2106 // Insert the section title above the content.
2107 $content = $content->addSectionHeader( $this->summary
);
2109 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2112 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2116 # Article exists. Check for edit conflict.
2118 $this->page
->clear(); # Force reload of dates, etc.
2119 $timestamp = $this->page
->getTimestamp();
2120 $latest = $this->page
->getLatest();
2122 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2124 // An edit conflict is detected if the current revision is different from the
2125 // revision that was current when editing was initiated on the client.
2126 // This is checked based on the timestamp and revision ID.
2127 // TODO: the timestamp based check can probably go away now.
2128 if ( $timestamp != $this->edittime
2129 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2131 $this->isConflict
= true;
2132 if ( $this->section
== 'new' ) {
2133 if ( $this->page
->getUserText() == $user->getName() &&
2134 $this->page
->getComment() == $this->newSectionSummary()
2136 // Probably a duplicate submission of a new comment.
2137 // This can happen when CDN resends a request after
2138 // a timeout but the first one actually went through.
2140 . ": duplicate new section submission; trigger edit conflict!\n" );
2142 // New comment; suppress conflict.
2143 $this->isConflict
= false;
2144 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2146 } elseif ( $this->section
== ''
2147 && Revision
::userWasLastToEdit(
2148 DB_MASTER
, $this->mTitle
->getArticleID(),
2149 $user->getId(), $this->edittime
2152 # Suppress edit conflict with self, except for section edits where merging is required.
2153 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2154 $this->isConflict
= false;
2158 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2159 if ( $this->sectiontitle
!== '' ) {
2160 $sectionTitle = $this->sectiontitle
;
2162 $sectionTitle = $this->summary
;
2167 if ( $this->isConflict
) {
2169 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2170 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2171 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2172 // ...or disable section editing for non-current revisions (not exposed anyway).
2173 if ( $this->editRevId
!== null ) {
2174 $content = $this->page
->replaceSectionAtRev(
2181 $content = $this->page
->replaceSectionContent(
2189 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2190 $content = $this->page
->replaceSectionContent(
2197 if ( is_null( $content ) ) {
2198 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2199 $this->isConflict
= true;
2200 $content = $textbox_content; // do not try to merge here!
2201 } elseif ( $this->isConflict
) {
2203 if ( $this->mergeChangesIntoContent( $content ) ) {
2204 // Successful merge! Maybe we should tell the user the good news?
2205 $this->isConflict
= false;
2206 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2208 $this->section
= '';
2209 $this->textbox1
= ContentHandler
::getContentText( $content );
2210 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2214 if ( $this->isConflict
) {
2215 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2219 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2223 if ( $this->section
== 'new' ) {
2224 // Handle the user preference to force summaries here
2225 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2226 $this->missingSummary
= true;
2227 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2228 $status->value
= self
::AS_SUMMARY_NEEDED
;
2232 // Do not allow the user to post an empty comment
2233 if ( $this->textbox1
== '' ) {
2234 $this->missingComment
= true;
2235 $status->fatal( 'missingcommenttext' );
2236 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2239 } elseif ( !$this->allowBlankSummary
2240 && !$content->equals( $this->getOriginalContent( $user ) )
2241 && !$content->isRedirect()
2242 && md5( $this->summary
) == $this->autoSumm
2244 $this->missingSummary
= true;
2245 $status->fatal( 'missingsummary' );
2246 $status->value
= self
::AS_SUMMARY_NEEDED
;
2251 $sectionanchor = '';
2252 if ( $this->section
== 'new' ) {
2253 $this->summary
= $this->newSectionSummary( $sectionanchor );
2254 } elseif ( $this->section
!= '' ) {
2255 # Try to get a section anchor from the section source, redirect
2256 # to edited section if header found.
2257 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2258 # for duplicate heading checking and maybe parsing.
2259 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2260 # We can't deal with anchors, includes, html etc in the header for now,
2261 # headline would need to be parsed to improve this.
2262 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2263 $sectionanchor = $this->guessSectionName( $matches[2] );
2266 $result['sectionanchor'] = $sectionanchor;
2268 // Save errors may fall down to the edit form, but we've now
2269 // merged the section into full text. Clear the section field
2270 // so that later submission of conflict forms won't try to
2271 // replace that into a duplicated mess.
2272 $this->textbox1
= $this->toEditText( $content );
2273 $this->section
= '';
2275 $status->value
= self
::AS_SUCCESS_UPDATE
;
2278 if ( !$this->allowSelfRedirect
2279 && $content->isRedirect()
2280 && $content->getRedirectTarget()->equals( $this->getTitle() )
2282 // If the page already redirects to itself, don't warn.
2283 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2284 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2285 $this->selfRedirect
= true;
2286 $status->fatal( 'selfredirect' );
2287 $status->value
= self
::AS_SELF_REDIRECT
;
2292 // Check for length errors again now that the section is merged in
2293 $this->contentLength
= strlen( $this->toEditText( $content ) );
2294 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2295 $this->tooBig
= true;
2296 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2300 $flags = EDIT_AUTOSUMMARY |
2301 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2302 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2303 ( $bot ? EDIT_FORCE_BOT
: 0 );
2305 $doEditStatus = $this->page
->doEditContent(
2311 $content->getDefaultFormat(),
2316 if ( !$doEditStatus->isOK() ) {
2317 // Failure from doEdit()
2318 // Show the edit conflict page for certain recognized errors from doEdit(),
2319 // but don't show it for errors from extension hooks
2320 $errors = $doEditStatus->getErrorsArray();
2321 if ( in_array( $errors[0][0],
2322 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2324 $this->isConflict
= true;
2325 // Destroys data doEdit() put in $status->value but who cares
2326 $doEditStatus->value
= self
::AS_END
;
2328 return $doEditStatus;
2331 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2332 if ( $result['nullEdit'] ) {
2333 // We don't know if it was a null edit until now, so increment here
2334 $user->pingLimiter( 'linkpurge' );
2336 $result['redirect'] = $content->isRedirect();
2338 $this->updateWatchlist();
2340 // If the content model changed, add a log entry
2341 if ( $changingContentModel ) {
2342 $this->addContentModelChangeLogEntry(
2344 $new ?
false : $oldContentModel,
2345 $this->contentModel
,
2355 * @param string|false $oldModel false if the page is being newly created
2356 * @param string $newModel
2357 * @param string $reason
2359 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2360 $new = $oldModel === false;
2361 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2362 $log->setPerformer( $user );
2363 $log->setTarget( $this->mTitle
);
2364 $log->setComment( $reason );
2365 $log->setParameters( [
2366 '4::oldmodel' => $oldModel,
2367 '5::newmodel' => $newModel
2369 $logid = $log->insert();
2370 $log->publish( $logid );
2374 * Register the change of watch status
2376 protected function updateWatchlist() {
2377 $user = $this->context
->getUser();
2378 if ( !$user->isLoggedIn() ) {
2382 $title = $this->mTitle
;
2383 $watch = $this->watchthis
;
2384 // Do this in its own transaction to reduce contention...
2385 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2386 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2387 return; // nothing to change
2389 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2394 * Attempts to do 3-way merge of edit content with a base revision
2395 * and current content, in case of edit conflict, in whichever way appropriate
2396 * for the content type.
2400 * @param Content $editContent
2404 private function mergeChangesIntoContent( &$editContent ) {
2405 $db = wfGetDB( DB_MASTER
);
2407 // This is the revision that was current at the time editing was initiated on the client,
2408 // even if the edit was based on an old revision.
2409 $baseRevision = $this->getBaseRevision();
2410 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2412 if ( is_null( $baseContent ) ) {
2416 // The current state, we want to merge updates into it
2417 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2418 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2420 if ( is_null( $currentContent ) ) {
2424 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2426 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2429 $editContent = $result;
2430 // Update parentRevId to what we just merged.
2431 $this->parentRevId
= $currentRevision->getId();
2439 * Returns the revision that was current at the time editing was initiated on the client,
2440 * even if the edit was based on an old revision.
2442 * @warning this method is very poorly named. If the user opened the form with ?oldid=X,
2443 * one might think of X as the "base revision", which is NOT what this returns,
2444 * see oldid for that. One might further assume that this corresponds to the $baseRevId
2445 * parameter of WikiPage::doEditContent, which is not the case either.
2446 * getExpectedParentRevision() would perhaps be a better name.
2448 * @return Revision|null Current version when editing was initiated on the client
2450 public function getBaseRevision() {
2451 if ( !$this->mBaseRevision
) {
2452 $db = wfGetDB( DB_MASTER
);
2453 $this->mBaseRevision
= $this->editRevId
2454 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2455 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2457 return $this->mBaseRevision
;
2461 * Check given input text against $wgSpamRegex, and return the text of the first match.
2463 * @param string $text
2465 * @return string|bool Matching string or false
2467 public static function matchSpamRegex( $text ) {
2468 global $wgSpamRegex;
2469 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2470 $regexes = (array)$wgSpamRegex;
2471 return self
::matchSpamRegexInternal( $text, $regexes );
2475 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2477 * @param string $text
2479 * @return string|bool Matching string or false
2481 public static function matchSummarySpamRegex( $text ) {
2482 global $wgSummarySpamRegex;
2483 $regexes = (array)$wgSummarySpamRegex;
2484 return self
::matchSpamRegexInternal( $text, $regexes );
2488 * @param string $text
2489 * @param array $regexes
2490 * @return bool|string
2492 protected static function matchSpamRegexInternal( $text, $regexes ) {
2493 foreach ( $regexes as $regex ) {
2495 if ( preg_match( $regex, $text, $matches ) ) {
2502 public function setHeaders() {
2503 $out = $this->context
->getOutput();
2505 $out->addModules( 'mediawiki.action.edit' );
2506 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2507 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2509 $user = $this->context
->getUser();
2511 if ( $user->getOption( 'uselivepreview' ) ) {
2512 $out->addModules( 'mediawiki.action.edit.preview' );
2515 if ( $user->getOption( 'useeditwarning' ) ) {
2516 $out->addModules( 'mediawiki.action.edit.editWarning' );
2519 # Enabled article-related sidebar, toplinks, etc.
2520 $out->setArticleRelated( true );
2522 $contextTitle = $this->getContextTitle();
2523 if ( $this->isConflict
) {
2524 $msg = 'editconflict';
2525 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2526 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2528 $msg = $contextTitle->exists()
2529 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2530 && $contextTitle->getDefaultMessageText() !== false
2536 # Use the title defined by DISPLAYTITLE magic word when present
2537 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2538 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2539 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2540 if ( $displayTitle === false ) {
2541 $displayTitle = $contextTitle->getPrefixedText();
2543 $out->setDisplayTitle( $displayTitle );
2545 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2547 $config = $this->context
->getConfig();
2549 # Transmit the name of the message to JavaScript for live preview
2550 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2551 $out->addJsConfigVars( [
2552 'wgEditMessage' => $msg,
2553 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2556 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2558 $out->addJsConfigVars(
2559 'wgEditSubmitButtonLabelPublish',
2560 $config->get( 'EditSubmitButtonLabelPublish' )
2565 * Show all applicable editing introductions
2567 protected function showIntro() {
2568 if ( $this->suppressIntro
) {
2572 $out = $this->context
->getOutput();
2573 $namespace = $this->mTitle
->getNamespace();
2575 if ( $namespace == NS_MEDIAWIKI
) {
2576 # Show a warning if editing an interface message
2577 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2578 # If this is a default message (but not css, json, or js),
2579 # show a hint that it is translatable on translatewiki.net
2581 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2582 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2583 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2585 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2586 if ( $defaultMessageText !== false ) {
2587 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2588 'translateinterface' );
2591 } elseif ( $namespace == NS_FILE
) {
2592 # Show a hint to shared repo
2593 $file = wfFindFile( $this->mTitle
);
2594 if ( $file && !$file->isLocal() ) {
2595 $descUrl = $file->getDescriptionUrl();
2596 # there must be a description url to show a hint to shared repo
2598 if ( !$this->mTitle
->exists() ) {
2599 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2600 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2603 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2604 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2611 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2612 # Show log extract when the user is currently blocked
2613 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2614 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2615 $user = User
::newFromName( $username, false /* allow IP users */ );
2616 $ip = User
::isIP( $username );
2617 $block = Block
::newFromTarget( $user, $user );
2618 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2619 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2620 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2622 !is_null( $block ) &&
2623 $block->getType() != Block
::TYPE_AUTO
&&
2624 ( $block->isSitewide() ||
$user->isBlockedFrom( $this->mTitle
) )
2626 // Show log extract if the user is sitewide blocked or is partially
2627 // blocked and not allowed to edit their user page or user talk page
2628 LogEventsList
::showLogExtract(
2631 MediaWikiServices
::getInstance()->getNamespaceInfo()->
2632 getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2636 'showIfEmpty' => false,
2638 'blocked-notice-logextract',
2639 $user->getName() # Support GENDER in notice
2645 # Try to add a custom edit intro, or use the standard one if this is not possible.
2646 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2647 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2648 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2650 if ( $this->context
->getUser()->isLoggedIn() ) {
2652 // Suppress the external link icon, consider the help url an internal one
2653 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2661 // Suppress the external link icon, consider the help url an internal one
2662 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2664 'newarticletextanon',
2670 # Give a notice if the user is editing a deleted/moved page...
2671 if ( !$this->mTitle
->exists() ) {
2672 $dbr = wfGetDB( DB_REPLICA
);
2674 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2678 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2679 'showIfEmpty' => false,
2680 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2687 * Attempt to show a custom editing introduction, if supplied
2691 protected function showCustomIntro() {
2692 if ( $this->editintro
) {
2693 $title = Title
::newFromText( $this->editintro
);
2694 if ( $this->isPageExistingAndViewable( $title, $this->context
->getUser() ) ) {
2695 // Added using template syntax, to take <noinclude>'s into account.
2696 $this->context
->getOutput()->addWikiTextAsContent(
2697 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2708 * Gets an editable textual representation of $content.
2709 * The textual representation can be turned by into a Content object by the
2710 * toEditContent() method.
2712 * If $content is null or false or a string, $content is returned unchanged.
2714 * If the given Content object is not of a type that can be edited using
2715 * the text base EditPage, an exception will be raised. Set
2716 * $this->allowNonTextContent to true to allow editing of non-textual
2719 * @param Content|null|bool|string $content
2720 * @return string The editable text form of the content.
2722 * @throws MWException If $content is not an instance of TextContent and
2723 * $this->allowNonTextContent is not true.
2725 protected function toEditText( $content ) {
2726 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2730 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2731 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2734 return $content->serialize( $this->contentFormat
);
2738 * Turns the given text into a Content object by unserializing it.
2740 * If the resulting Content object is not of a type that can be edited using
2741 * the text base EditPage, an exception will be raised. Set
2742 * $this->allowNonTextContent to true to allow editing of non-textual
2745 * @param string|null|bool $text Text to unserialize
2746 * @return Content|bool|null The content object created from $text. If $text was false
2747 * or null, then false or null will be returned instead.
2749 * @throws MWException If unserializing the text results in a Content
2750 * object that is not an instance of TextContent and
2751 * $this->allowNonTextContent is not true.
2753 protected function toEditContent( $text ) {
2754 if ( $text === false ||
$text === null ) {
2758 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2759 $this->contentModel
, $this->contentFormat
);
2761 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2762 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2769 * Send the edit form and related headers to OutputPage
2770 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2771 * during form output near the top, for captchas and the like.
2773 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2774 * use the EditPage::showEditForm:fields hook instead.
2776 public function showEditForm( $formCallback = null ) {
2777 # need to parse the preview early so that we know which templates are used,
2778 # otherwise users with "show preview after edit box" will get a blank list
2779 # we parse this near the beginning so that setHeaders can do the title
2780 # setting work instead of leaving it in getPreviewText
2781 $previewOutput = '';
2782 if ( $this->formtype
== 'preview' ) {
2783 $previewOutput = $this->getPreviewText();
2786 $out = $this->context
->getOutput();
2788 // Avoid PHP 7.1 warning of passing $this by reference
2790 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2792 $this->setHeaders();
2794 $this->addTalkPageText();
2795 $this->addEditNotices();
2797 if ( !$this->isConflict
&&
2798 $this->section
!= '' &&
2799 !$this->isSectionEditSupported() ) {
2800 // We use $this->section to much before this and getVal('wgSection') directly in other places
2801 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2802 // Someone is welcome to try refactoring though
2803 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2807 $this->showHeader();
2809 $out->addHTML( $this->editFormPageTop
);
2811 $user = $this->context
->getUser();
2812 if ( $user->getOption( 'previewontop' ) ) {
2813 $this->displayPreviewArea( $previewOutput, true );
2816 $out->addHTML( $this->editFormTextTop
);
2818 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
!== 'save' ) {
2819 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2820 'deletedwhileediting' );
2823 // @todo add EditForm plugin interface and use it here!
2824 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2825 $out->addHTML( Html
::openElement(
2828 'class' => 'mw-editform',
2829 'id' => self
::EDITFORM_ID
,
2830 'name' => self
::EDITFORM_ID
,
2832 'action' => $this->getActionURL( $this->getContextTitle() ),
2833 'enctype' => 'multipart/form-data'
2837 if ( is_callable( $formCallback ) ) {
2838 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2839 call_user_func_array( $formCallback, [ &$out ] );
2842 // Add a check for Unicode support
2843 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2845 // Add an empty field to trip up spambots
2847 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2850 [ 'for' => 'wpAntispam' ],
2851 $this->context
->msg( 'simpleantispam-label' )->parse()
2857 'name' => 'wpAntispam',
2858 'id' => 'wpAntispam',
2862 . Xml
::closeElement( 'div' )
2865 // Avoid PHP 7.1 warning of passing $this by reference
2867 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2869 // Put these up at the top to ensure they aren't lost on early form submission
2870 $this->showFormBeforeText();
2872 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2873 $username = $this->lastDelete
->user_name
;
2874 $comment = CommentStore
::getStore()
2875 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2877 // It is better to not parse the comment at all than to have templates expanded in the middle
2878 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2879 $key = $comment === ''
2880 ?
'confirmrecreate-noreason'
2881 : 'confirmrecreate';
2883 '<div class="mw-confirm-recreate">' .
2884 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2885 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2886 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2892 # When the summary is hidden, also hide them on preview/show changes
2893 if ( $this->nosummary
) {
2894 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2897 # If a blank edit summary was previously provided, and the appropriate
2898 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2899 # user being bounced back more than once in the event that a summary
2902 # For a bit more sophisticated detection of blank summaries, hash the
2903 # automatic one and pass that in the hidden field wpAutoSummary.
2904 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2905 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2908 if ( $this->undidRev
) {
2909 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2912 if ( $this->selfRedirect
) {
2913 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2916 if ( $this->hasPresetSummary
) {
2917 // If a summary has been preset using &summary= we don't want to prompt for
2918 // a different summary. Only prompt for a summary if the summary is blanked.
2920 $this->autoSumm
= md5( '' );
2923 $autosumm = $this->autoSumm
!== '' ?
$this->autoSumm
: md5( $this->summary
);
2924 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2926 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2927 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2929 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2930 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2934 if ( $this->section
== 'new' ) {
2935 $this->showSummaryInput( true, $this->summary
);
2936 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2939 $out->addHTML( $this->editFormTextBeforeContent
);
2940 if ( $this->isConflict
) {
2941 // In an edit conflict, we turn textbox2 into the user's text,
2942 // and textbox1 into the stored version
2943 $this->textbox2
= $this->textbox1
;
2945 $content = $this->getCurrentContent();
2946 $this->textbox1
= $this->toEditText( $content );
2948 $editConflictHelper = $this->getEditConflictHelper();
2949 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2950 $editConflictHelper->setContentModel( $this->contentModel
);
2951 $editConflictHelper->setContentFormat( $this->contentFormat
);
2952 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2955 if ( !$this->mTitle
->isUserConfigPage() ) {
2956 $out->addHTML( self
::getEditToolbar() );
2959 if ( $this->blankArticle
) {
2960 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2963 if ( $this->isConflict
) {
2964 // In an edit conflict bypass the overridable content form method
2965 // and fallback to the raw wpTextbox1 since editconflicts can't be
2966 // resolved between page source edits and custom ui edits using the
2968 $conflictTextBoxAttribs = [];
2969 if ( $this->wasDeletedSinceLastEdit() ) {
2970 $conflictTextBoxAttribs['style'] = 'display:none;';
2971 } elseif ( $this->isOldRev
) {
2972 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2975 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2976 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2978 $this->showContentForm();
2981 $out->addHTML( $this->editFormTextAfterContent
);
2983 $this->showStandardInputs();
2985 $this->showFormAfterText();
2987 $this->showTosSummary();
2989 $this->showEditTools();
2991 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2993 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2995 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2996 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2998 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2999 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
3001 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
3003 if ( $this->isConflict
) {
3005 $this->showConflict();
3006 } catch ( MWContentSerializationException
$ex ) {
3007 // this can't really happen, but be nice if it does.
3008 $msg = $this->context
->msg(
3009 'content-failed-to-parse',
3010 $this->contentModel
,
3011 $this->contentFormat
,
3014 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3018 // Set a hidden field so JS knows what edit form mode we are in
3019 if ( $this->isConflict
) {
3021 } elseif ( $this->preview
) {
3023 } elseif ( $this->diff
) {
3028 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
3030 // Marker for detecting truncated form data. This must be the last
3031 // parameter sent in order to be of use, so do not move me.
3032 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
3033 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
3035 if ( !$user->getOption( 'previewontop' ) ) {
3036 $this->displayPreviewArea( $previewOutput, false );
3041 * Wrapper around TemplatesOnThisPageFormatter to make
3042 * a "templates on this page" list.
3044 * @param Title[] $templates
3045 * @return string HTML
3047 public function makeTemplatesOnThisPageList( array $templates ) {
3048 $templateListFormatter = new TemplatesOnThisPageFormatter(
3049 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
3052 // preview if preview, else section if section, else false
3054 if ( $this->preview
) {
3056 } elseif ( $this->section
!= '' ) {
3060 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
3061 $templateListFormatter->format( $templates, $type )
3066 * Extract the section title from current section text, if any.
3068 * @param string $text
3069 * @return string|bool String or false
3071 public static function extractSectionTitle( $text ) {
3072 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
3073 if ( !empty( $matches[2] ) ) {
3074 return MediaWikiServices
::getInstance()->getParser()
3075 ->stripSectionName( trim( $matches[2] ) );
3081 protected function showHeader() {
3082 $out = $this->context
->getOutput();
3083 $user = $this->context
->getUser();
3084 if ( $this->isConflict
) {
3085 $this->addExplainConflictHeader( $out );
3086 $this->editRevId
= $this->page
->getLatest();
3088 if ( $this->section
!= '' && $this->section
!= 'new' && !$this->summary
&&
3089 !$this->preview
&& !$this->diff
3091 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
3092 if ( $sectionTitle !== false ) {
3093 $this->summary
= "/* $sectionTitle */ ";
3097 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
3099 if ( $this->missingComment
) {
3100 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3103 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
3105 "<div id='mw-missingsummary'>\n$1\n</div>",
3106 [ 'missingsummary', $buttonLabel ]
3110 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3112 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3113 [ 'missingcommentheader', $buttonLabel ]
3117 if ( $this->blankArticle
) {
3119 "<div id='mw-blankarticle'>\n$1\n</div>",
3120 [ 'blankarticle', $buttonLabel ]
3124 if ( $this->selfRedirect
) {
3126 "<div id='mw-selfredirect'>\n$1\n</div>",
3127 [ 'selfredirect', $buttonLabel ]
3131 if ( $this->hookError
!== '' ) {
3132 $out->addWikiTextAsInterface( $this->hookError
);
3135 if ( $this->section
!= 'new' ) {
3136 $revision = $this->mArticle
->getRevisionFetched();
3138 // Let sysop know that this will make private content public if saved
3140 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3142 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3143 'rev-deleted-text-permission'
3145 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3147 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3148 'rev-deleted-text-view'
3152 if ( !$revision->isCurrent() ) {
3153 $this->mArticle
->setOldSubtitle( $revision->getId() );
3155 Html
::warningBox( "\n$1\n" ),
3158 $this->isOldRev
= true;
3160 } elseif ( $this->mTitle
->exists() ) {
3161 // Something went wrong
3163 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3164 [ 'missing-revision', $this->oldid
] );
3169 if ( wfReadOnly() ) {
3171 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3172 [ 'readonlywarning', wfReadOnlyReason() ]
3174 } elseif ( $user->isAnon() ) {
3175 if ( $this->formtype
!= 'preview' ) {
3176 $returntoquery = array_diff_key(
3177 $this->context
->getRequest()->getValues(),
3178 [ 'title' => true, 'returnto' => true, 'returntoquery' => true ]
3181 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3182 [ 'anoneditwarning',
3184 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3185 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3186 'returntoquery' => wfArrayToCgi( $returntoquery ),
3189 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3190 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3191 'returntoquery' => wfArrayToCgi( $returntoquery ),
3196 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3197 'anonpreviewwarning'
3200 } elseif ( $this->mTitle
->isUserConfigPage() ) {
3201 # Check the skin exists
3202 if ( $this->isWrongCaseUserConfigPage() ) {
3204 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3205 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3208 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3209 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3210 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3211 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3213 $warning = $isUserCssConfig
3215 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3217 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3219 if ( $this->formtype
!== 'preview' ) {
3220 $config = $this->context
->getConfig();
3221 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3223 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3224 [ 'usercssyoucanpreview' ]
3226 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3228 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3229 [ 'userjsonyoucanpreview' ]
3231 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3233 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3234 [ 'userjsyoucanpreview' ]
3241 $this->addPageProtectionWarningHeaders();
3243 $this->addLongPageWarningHeader();
3245 # Add header copyright warning
3246 $this->showHeaderCopyrightWarning();
3250 * Helper function for summary input functions, which returns the necessary
3251 * attributes for the input.
3253 * @param array|null $inputAttrs Array of attrs to use on the input
3256 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3257 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3258 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3259 // Unicode codepoints.
3260 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3261 'id' => 'wpSummary',
3262 'name' => 'wpSummary',
3263 'maxlength' => CommentStore
::COMMENT_CHARACTER_LIMIT
,
3266 'spellcheck' => 'true',
3271 * Builds a standard summary input with a label.
3273 * @param string $summary The value of the summary input
3274 * @param string|null $labelText The html to place inside the label
3275 * @param array|null $inputAttrs Array of attrs to use on the input
3277 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3279 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3280 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3281 $this->getSummaryInputAttributes( $inputAttrs )
3284 'title' => Linker
::titleAttrib( 'summary' ),
3285 'accessKey' => Linker
::accesskey( 'summary' ),
3288 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3289 $inputAttrs['inputId'] = $inputAttrs['id'];
3290 $inputAttrs['id'] = 'wpSummaryWidget';
3292 return new OOUI\
FieldLayout(
3293 new OOUI\
TextInputWidget( [
3294 'value' => $summary,
3295 'infusable' => true,
3298 'label' => new OOUI\
HtmlSnippet( $labelText ),
3300 'id' => 'wpSummaryLabel',
3301 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3307 * @param bool $isSubjectPreview True if this is the section subject/title
3308 * up top, or false if this is the comment summary
3309 * down below the textarea
3310 * @param string $summary The text of the summary to display
3312 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3313 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3314 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3315 if ( $isSubjectPreview ) {
3316 if ( $this->nosummary
) {
3319 } elseif ( !$this->mShowSummaryField
) {
3323 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3324 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3327 [ 'class' => $summaryClass ]
3332 * @param bool $isSubjectPreview True if this is the section subject/title
3333 * up top, or false if this is the comment summary
3334 * down below the textarea
3335 * @param string $summary The text of the summary to display
3338 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3339 // avoid spaces in preview, gets always trimmed on save
3340 $summary = trim( $summary );
3341 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3345 if ( $isSubjectPreview ) {
3346 $summary = $this->context
->msg( 'newsectionsummary' )
3347 ->rawParams( MediaWikiServices
::getInstance()->getParser()
3348 ->stripSectionName( $summary ) )
3349 ->inContentLanguage()->text();
3352 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3354 $summary = $this->context
->msg( $message )->parse()
3355 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3356 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3359 protected function showFormBeforeText() {
3360 $out = $this->context
->getOutput();
3361 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3362 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3363 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3364 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3365 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3368 protected function showFormAfterText() {
3370 * To make it harder for someone to slip a user a page
3371 * which submits an edit form to the wiki without their
3372 * knowledge, a random token is associated with the login
3373 * session. If it's not passed back with the submission,
3374 * we won't save the page, or render user JavaScript and
3377 * For anon editors, who may not have a session, we just
3378 * include the constant suffix to prevent editing from
3379 * broken text-mangling proxies.
3381 $this->context
->getOutput()->addHTML(
3383 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3389 * Subpage overridable method for printing the form for page content editing
3390 * By default this simply outputs wpTextbox1
3391 * Subclasses can override this to provide a custom UI for editing;
3392 * be it a form, or simply wpTextbox1 with a modified content that will be
3393 * reverse modified when extracted from the post data.
3394 * Note that this is basically the inverse for importContentFormData
3396 protected function showContentForm() {
3397 $this->showTextbox1();
3401 * Method to output wpTextbox1
3402 * The $textoverride method can be used by subclasses overriding showContentForm
3403 * to pass back to this method.
3405 * @param array|null $customAttribs Array of html attributes to use in the textarea
3406 * @param string|null $textoverride Optional text to override $this->textarea1 with
3408 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3409 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3410 $attribs = [ 'style' => 'display:none;' ];
3412 $builder = new TextboxBuilder();
3413 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3415 # Is an old revision being edited?
3416 if ( $this->isOldRev
) {
3417 $classes[] = 'mw-textarea-oldrev';
3420 $attribs = [ 'tabindex' => 1 ];
3422 if ( is_array( $customAttribs ) ) {
3423 $attribs +
= $customAttribs;
3426 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3430 $textoverride ??
$this->textbox1
,
3436 protected function showTextbox2() {
3437 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3440 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3441 $builder = new TextboxBuilder();
3442 $attribs = $builder->buildTextboxAttribs(
3445 $this->context
->getUser(),
3449 $this->context
->getOutput()->addHTML(
3450 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3454 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3457 $classes[] = 'ontop';
3460 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3462 if ( $this->formtype
!= 'preview' ) {
3463 $attribs['style'] = 'display: none;';
3466 $out = $this->context
->getOutput();
3467 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3469 if ( $this->formtype
== 'preview' ) {
3470 $this->showPreview( $previewOutput );
3472 // Empty content container for LivePreview
3473 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3474 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3475 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3476 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3479 $out->addHTML( '</div>' );
3481 if ( $this->formtype
== 'diff' ) {
3484 } catch ( MWContentSerializationException
$ex ) {
3485 $msg = $this->context
->msg(
3486 'content-failed-to-parse',
3487 $this->contentModel
,
3488 $this->contentFormat
,
3491 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3497 * Append preview output to OutputPage.
3498 * Includes category rendering if this is a category page.
3500 * @param string $text The HTML to be output for the preview.
3502 protected function showPreview( $text ) {
3503 if ( $this->mArticle
instanceof CategoryPage
) {
3504 $this->mArticle
->openShowCategory();
3506 # This hook seems slightly odd here, but makes things more
3507 # consistent for extensions.
3508 $out = $this->context
->getOutput();
3509 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3510 $out->addHTML( $text );
3511 if ( $this->mArticle
instanceof CategoryPage
) {
3512 $this->mArticle
->closeShowCategory();
3517 * Get a diff between the current contents of the edit box and the
3518 * version of the page we're editing from.
3520 * If this is a section edit, we'll replace the section as for final
3521 * save and then make a comparison.
3523 public function showDiff() {
3524 $oldtitlemsg = 'currentrev';
3525 # if message does not exist, show diff against the preloaded default
3526 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3527 $oldtext = $this->mTitle
->getDefaultMessageText();
3528 if ( $oldtext !== false ) {
3529 $oldtitlemsg = 'defaultmessagetext';
3530 $oldContent = $this->toEditContent( $oldtext );
3535 $oldContent = $this->getCurrentContent();
3538 $textboxContent = $this->toEditContent( $this->textbox1
);
3539 if ( $this->editRevId
!== null ) {
3540 $newContent = $this->page
->replaceSectionAtRev(
3541 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3544 $newContent = $this->page
->replaceSectionContent(
3545 $this->section
, $textboxContent, $this->summary
, $this->edittime
3549 if ( $newContent ) {
3550 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3552 $user = $this->context
->getUser();
3553 $popts = ParserOptions
::newFromUserAndLang( $user,
3554 MediaWikiServices
::getInstance()->getContentLanguage() );
3555 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3558 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3559 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3560 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3562 if ( !$oldContent ) {
3563 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3566 if ( !$newContent ) {
3567 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3570 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3571 $de->setContent( $oldContent, $newContent );
3573 $difftext = $de->getDiff( $oldtitle, $newtitle );
3574 $de->showDiffStyle();
3579 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3583 * Show the header copyright warning.
3585 protected function showHeaderCopyrightWarning() {
3586 $msg = 'editpage-head-copy-warn';
3587 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3588 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3589 'editpage-head-copy-warn' );
3594 * Give a chance for site and per-namespace customizations of
3595 * terms of service summary link that might exist separately
3596 * from the copyright notice.
3598 * This will display between the save button and the edit tools,
3599 * so should remain short!
3601 protected function showTosSummary() {
3602 $msg = 'editpage-tos-summary';
3603 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3604 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3605 $out = $this->context
->getOutput();
3606 $out->addHTML( '<div class="mw-tos-summary">' );
3607 $out->addWikiMsg( $msg );
3608 $out->addHTML( '</div>' );
3613 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3614 * characters not present on most keyboards for copying/pasting.
3616 protected function showEditTools() {
3617 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3618 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3623 * Get the copyright warning
3625 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3628 protected function getCopywarn() {
3629 return self
::getCopyrightWarning( $this->mTitle
);
3633 * Get the copyright warning, by default returns wikitext
3635 * @param Title $title
3636 * @param string $format Output format, valid values are any function of a Message object
3637 * @param Language|string|null $langcode Language code or Language object.
3640 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3641 global $wgRightsText;
3642 if ( $wgRightsText ) {
3643 $copywarnMsg = [ 'copyrightwarning',
3644 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3647 $copywarnMsg = [ 'copyrightwarning2',
3648 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3650 // Allow for site and per-namespace customization of contribution/copyright notice.
3651 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3653 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3655 $msg->inLanguage( $langcode );
3657 return "<div id=\"editpage-copywarn\">\n" .
3658 $msg->$format() . "\n</div>";
3662 * Get the Limit report for page previews
3665 * @param ParserOutput|null $output ParserOutput object from the parse
3666 * @return string HTML
3668 public static function getPreviewLimitReport( ParserOutput
$output = null ) {
3671 if ( !$output ||
!$output->getLimitReportData() ) {
3675 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3676 wfMessage( 'limitreport-title' )->parseAsBlock()
3679 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3680 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3682 $limitReport .= Html
::openElement( 'table', [
3683 'class' => 'preview-limit-report wikitable'
3685 Html
::openElement( 'tbody' );
3687 foreach ( $output->getLimitReportData() as $key => $value ) {
3688 if ( Hooks
::run( 'ParserLimitReportFormat',
3689 [ $key, &$value, &$limitReport, true, true ]
3691 $keyMsg = wfMessage( $key );
3692 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3693 if ( !$valueMsg->exists() ) {
3694 $valueMsg = new RawMessage( '$1' );
3696 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3697 $limitReport .= Html
::openElement( 'tr' ) .
3698 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3699 Html
::rawElement( 'td', null,
3700 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3702 Html
::closeElement( 'tr' );
3707 $limitReport .= Html
::closeElement( 'tbody' ) .
3708 Html
::closeElement( 'table' ) .
3709 Html
::closeElement( 'div' );
3711 return $limitReport;
3714 protected function showStandardInputs( &$tabindex = 2 ) {
3715 $out = $this->context
->getOutput();
3716 $out->addHTML( "<div class='editOptions'>\n" );
3718 if ( $this->section
!= 'new' ) {
3719 $this->showSummaryInput( false, $this->summary
);
3720 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3723 $checkboxes = $this->getCheckboxesWidget(
3725 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3727 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3729 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3731 // Show copyright warning.
3732 $out->addWikiTextAsInterface( $this->getCopywarn() );
3733 $out->addHTML( $this->editFormTextAfterWarn
);
3735 $out->addHTML( "<div class='editButtons'>\n" );
3736 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3738 $cancel = $this->getCancelLink();
3740 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3741 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3744 $this->context
->msg( 'edithelp' )->text(),
3745 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3748 $this->context
->msg( 'word-separator' )->escaped() .
3749 $this->context
->msg( 'newwindow' )->parse();
3751 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3752 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3753 $out->addHTML( "</div><!-- editButtons -->\n" );
3755 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3757 $out->addHTML( "</div><!-- editOptions -->\n" );
3761 * Show an edit conflict. textbox1 is already shown in showEditForm().
3762 * If you want to use another entry point to this function, be careful.
3764 protected function showConflict() {
3765 $out = $this->context
->getOutput();
3766 // Avoid PHP 7.1 warning of passing $this by reference
3768 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3769 $this->incrementConflictStats();
3771 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3775 protected function incrementConflictStats() {
3776 $this->getEditConflictHelper()->incrementConflictStats();
3782 public function getCancelLink() {
3784 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3785 $cancelParams['oldid'] = $this->oldid
;
3786 } elseif ( $this->getContextTitle()->isRedirect() ) {
3787 $cancelParams['redirect'] = 'no';
3790 return new OOUI\
ButtonWidget( [
3791 'id' => 'mw-editform-cancel',
3792 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3793 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3795 'infusable' => true,
3796 'flags' => 'destructive',
3801 * Returns the URL to use in the form's action attribute.
3802 * This is used by EditPage subclasses when simply customizing the action
3803 * variable in the constructor is not enough. This can be used when the
3804 * EditPage lives inside of a Special page rather than a custom page action.
3806 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3809 protected function getActionURL( Title
$title ) {
3810 return $title->getLocalURL( [ 'action' => $this->action
] );
3814 * Check if a page was deleted while the user was editing it, before submit.
3815 * Note that we rely on the logging table, which hasn't been always there,
3816 * but that doesn't matter, because this only applies to brand new
3820 protected function wasDeletedSinceLastEdit() {
3821 if ( $this->deletedSinceEdit
!== null ) {
3822 return $this->deletedSinceEdit
;
3825 $this->deletedSinceEdit
= false;
3827 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3828 $this->lastDelete
= $this->getLastDelete();
3829 if ( $this->lastDelete
) {
3830 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3831 if ( $deleteTime > $this->starttime
) {
3832 $this->deletedSinceEdit
= true;
3837 return $this->deletedSinceEdit
;
3841 * Get the last log record of this page being deleted, if ever. This is
3842 * used to detect whether a delete occurred during editing.
3843 * @return bool|stdClass
3845 protected function getLastDelete() {
3846 $dbr = wfGetDB( DB_REPLICA
);
3847 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3848 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3849 $data = $dbr->selectRow(
3850 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3860 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3862 'log_namespace' => $this->mTitle
->getNamespace(),
3863 'log_title' => $this->mTitle
->getDBkey(),
3864 'log_type' => 'delete',
3865 'log_action' => 'delete',
3868 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3870 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3871 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3873 // Quick paranoid permission checks...
3874 if ( is_object( $data ) ) {
3875 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3876 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3879 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3880 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3881 $data->log_comment_data
= null;
3889 * Get the rendered text for previewing.
3890 * @throws MWException
3893 public function getPreviewText() {
3894 $out = $this->context
->getOutput();
3895 $config = $this->context
->getConfig();
3897 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3898 // Could be an offsite preview attempt. This is very unsafe if
3899 // HTML is enabled, as it could be an attack.
3901 if ( $this->textbox1
!== '' ) {
3902 // Do not put big scary notice, if previewing the empty
3903 // string, which happens when you initially edit
3904 // a category page, due to automatic preview-on-open.
3905 $parsedNote = Html
::rawElement( 'div', [ 'class' => 'previewnote' ],
3906 $out->parseAsInterface(
3907 $this->context
->msg( 'session_fail_preview_html' )->plain()
3910 $this->incrementEditFailureStats( 'session_loss' );
3917 $content = $this->toEditContent( $this->textbox1
);
3921 'AlternateEditPreview',
3922 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3924 return $previewHTML;
3927 # provide a anchor link to the editform
3928 $continueEditing = '<span class="mw-continue-editing">' .
3929 '[[#' . self
::EDITFORM_ID
. '|' .
3930 $this->context
->getLanguage()->getArrow() . ' ' .
3931 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3932 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3933 if ( $this->mTokenOkExceptSuffix
) {
3934 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3935 $this->incrementEditFailureStats( 'bad_token' );
3937 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3938 $this->incrementEditFailureStats( 'session_loss' );
3940 } elseif ( $this->incompleteForm
) {
3941 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3942 if ( $this->mTriedSave
) {
3943 $this->incrementEditFailureStats( 'incomplete_form' );
3946 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3949 # don't parse non-wikitext pages, show message about preview
3950 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3951 if ( $this->mTitle
->isUserConfigPage() ) {
3953 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3959 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3961 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3964 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3966 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3969 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3971 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3978 # Used messages to make sure grep find them:
3979 # Messages: usercsspreview, userjsonpreview, userjspreview,
3980 # sitecsspreview, sitejsonpreview, sitejspreview
3981 if ( $level && $format ) {
3982 $note = "<div id='mw-{$level}{$format}preview'>" .
3983 $this->context
->msg( "{$level}{$format}preview" )->plain() .
3984 ' ' . $continueEditing . "</div>";
3988 # If we're adding a comment, we need to show the
3989 # summary as the headline
3990 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3991 $content = $content->addSectionHeader( $this->summary
);
3994 $hook_args = [ $this, &$content ];
3995 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3997 $parserResult = $this->doPreviewParse( $content );
3998 $parserOutput = $parserResult['parserOutput'];
3999 $previewHTML = $parserResult['html'];
4000 $this->mParserOutput
= $parserOutput;
4001 $out->addParserOutputMetadata( $parserOutput );
4002 if ( $out->userCanPreview() ) {
4003 $out->addContentOverride( $this->getTitle(), $content );
4006 if ( count( $parserOutput->getWarnings() ) ) {
4007 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
4010 } catch ( MWContentSerializationException
$ex ) {
4011 $m = $this->context
->msg(
4012 'content-failed-to-parse',
4013 $this->contentModel
,
4014 $this->contentFormat
,
4017 $note .= "\n\n" . $m->plain(); # gets parsed down below
4021 if ( $this->isConflict
) {
4022 $conflict = Html
::rawElement(
4023 'h2', [ 'id' => 'mw-previewconflict' ],
4024 $this->context
->msg( 'previewconflict' )->escaped()
4027 $conflict = '<hr />';
4030 $previewhead = Html
::rawElement(
4031 'div', [ 'class' => 'previewnote' ],
4033 'h2', [ 'id' => 'mw-previewheader' ],
4034 $this->context
->msg( 'preview' )->escaped()
4036 $out->parseAsInterface( $note ) . $conflict
4039 $pageViewLang = $this->mTitle
->getPageViewLanguage();
4040 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
4041 'class' => 'mw-content-' . $pageViewLang->getDir() ];
4042 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
4044 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
4047 private function incrementEditFailureStats( $failureType ) {
4048 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
4049 $stats->increment( 'edit.failures.' . $failureType );
4053 * Get parser options for a preview
4054 * @return ParserOptions
4056 protected function getPreviewParserOptions() {
4057 $parserOptions = $this->page
->makeParserOptions( $this->context
);
4058 $parserOptions->setIsPreview( true );
4059 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
4060 $parserOptions->enableLimitReport();
4062 // XXX: we could call $parserOptions->setCurrentRevisionCallback here to force the
4063 // current revision to be null during PST, until setupFakeRevision is called on
4064 // the ParserOptions. Currently, we rely on Parser::getRevisionObject() to ignore
4065 // existing revisions in preview mode.
4067 return $parserOptions;
4071 * Parse the page for a preview. Subclasses may override this class, in order
4072 * to parse with different options, or to otherwise modify the preview HTML.
4074 * @param Content $content The page content
4075 * @return array with keys:
4076 * - parserOutput: The ParserOutput object
4077 * - html: The HTML to be displayed
4079 protected function doPreviewParse( Content
$content ) {
4080 $user = $this->context
->getUser();
4081 $parserOptions = $this->getPreviewParserOptions();
4083 // NOTE: preSaveTransform doesn't have a fake revision to operate on.
4084 // Parser::getRevisionObject() will return null in preview mode,
4085 // causing the context user to be used for {{subst:REVISIONUSER}}.
4086 // XXX: Alternatively, we could also call setupFakeRevision() a second time:
4087 // once before PST with $content, and then after PST with $pstContent.
4088 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
4089 $scopedCallback = $parserOptions->setupFakeRevision( $this->mTitle
, $pstContent, $user );
4090 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
4091 ScopedCallback
::consume( $scopedCallback );
4093 'parserOutput' => $parserOutput,
4094 'html' => $parserOutput->getText( [
4095 'enableSectionEditLinks' => false
4103 public function getTemplates() {
4104 if ( $this->preview ||
$this->section
!= '' ) {
4106 if ( !isset( $this->mParserOutput
) ) {
4109 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
4110 foreach ( array_keys( $template ) as $dbk ) {
4111 $templates[] = Title
::makeTitle( $ns, $dbk );
4116 return $this->mTitle
->getTemplateLinksFrom();
4121 * Allow extensions to provide a toolbar.
4123 * @return string|null
4125 public static function getEditToolbar() {
4126 $startingToolbar = '<div id="toolbar"></div>';
4127 $toolbar = $startingToolbar;
4129 if ( !Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4132 // Don't add a pointless `<div>` to the page unless a hook caller populated it
4133 return ( $toolbar === $startingToolbar ) ?
null : $toolbar;
4137 * Return an array of checkbox definitions.
4139 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4141 * Array values are associative arrays with the following keys:
4142 * - 'label-message' (required): message for label text
4143 * - 'id' (required): 'id' attribute for the `<input>`
4144 * - 'default' (required): default checkedness (true or false)
4145 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4146 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4147 * from messages like 'tooltip-foo', 'accesskey-foo'
4148 * - 'label-id' (optional): 'id' attribute for the `<label>`
4149 * - 'legacy-name' (optional): short name for backwards-compatibility
4150 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4151 * where bool indicates the checked status of the checkbox
4154 public function getCheckboxesDefinition( $checked ) {
4157 $user = $this->context
->getUser();
4158 // don't show the minor edit checkbox if it's a new page or section
4159 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4160 $checkboxes['wpMinoredit'] = [
4161 'id' => 'wpMinoredit',
4162 'label-message' => 'minoredit',
4163 // Uses messages: tooltip-minoredit, accesskey-minoredit
4164 'tooltip' => 'minoredit',
4165 'label-id' => 'mw-editpage-minoredit',
4166 'legacy-name' => 'minor',
4167 'default' => $checked['minor'],
4171 if ( $user->isLoggedIn() ) {
4172 $checkboxes['wpWatchthis'] = [
4173 'id' => 'wpWatchthis',
4174 'label-message' => 'watchthis',
4175 // Uses messages: tooltip-watch, accesskey-watch
4176 'tooltip' => 'watch',
4177 'label-id' => 'mw-editpage-watch',
4178 'legacy-name' => 'watch',
4179 'default' => $checked['watch'],
4184 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4190 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4191 * any other added by extensions.
4193 * @param int &$tabindex Current tabindex
4194 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4195 * status of the checkbox
4197 * @return array Associative array of string keys to OOUI\FieldLayout instances
4199 public function getCheckboxesWidget( &$tabindex, $checked ) {
4201 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4203 foreach ( $checkboxesDef as $name => $options ) {
4204 $legacyName = $options['legacy-name'] ??
$name;
4208 if ( isset( $options['tooltip'] ) ) {
4209 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4210 $title = Linker
::titleAttrib( $options['tooltip'] );
4212 if ( isset( $options['title-message'] ) ) {
4213 $title = $this->context
->msg( $options['title-message'] )->text();
4216 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4217 new OOUI\
CheckboxInputWidget( [
4218 'tabIndex' => ++
$tabindex,
4219 'accessKey' => $accesskey,
4220 'id' => $options['id'] . 'Widget',
4221 'inputId' => $options['id'],
4223 'selected' => $options['default'],
4224 'infusable' => true,
4227 'align' => 'inline',
4228 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4230 'id' => $options['label-id'] ??
null,
4239 * Get the message key of the label for the button to save the page
4244 protected function getSubmitButtonLabel() {
4246 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4248 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4249 $newPage = !$this->mTitle
->exists();
4251 if ( $labelAsPublish ) {
4252 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4254 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4257 return $buttonLabelKey;
4261 * Returns an array of html code of the following buttons:
4262 * save, diff and preview
4264 * @param int &$tabindex Current tabindex
4268 public function getEditButtons( &$tabindex ) {
4272 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4274 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4275 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4277 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4279 'tabIndex' => ++
$tabindex,
4280 'id' => 'wpSaveWidget',
4281 'inputId' => 'wpSave',
4282 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4283 'useInputTag' => true,
4284 'flags' => [ 'progressive', 'primary' ],
4285 'label' => $buttonLabel,
4286 'infusable' => true,
4288 // Messages used: tooltip-save, tooltip-publish
4289 'title' => Linker
::titleAttrib( $buttonTooltip ),
4290 // Messages used: accesskey-save, accesskey-publish
4291 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4294 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4295 'name' => 'wpPreview',
4296 'tabIndex' => ++
$tabindex,
4297 'id' => 'wpPreviewWidget',
4298 'inputId' => 'wpPreview',
4299 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4300 'useInputTag' => true,
4301 'label' => $this->context
->msg( 'showpreview' )->text(),
4302 'infusable' => true,
4304 // Message used: tooltip-preview
4305 'title' => Linker
::titleAttrib( 'preview' ),
4306 // Message used: accesskey-preview
4307 'accessKey' => Linker
::accesskey( 'preview' ),
4310 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4312 'tabIndex' => ++
$tabindex,
4313 'id' => 'wpDiffWidget',
4314 'inputId' => 'wpDiff',
4315 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4316 'useInputTag' => true,
4317 'label' => $this->context
->msg( 'showdiff' )->text(),
4318 'infusable' => true,
4320 // Message used: tooltip-diff
4321 'title' => Linker
::titleAttrib( 'diff' ),
4322 // Message used: accesskey-diff
4323 'accessKey' => Linker
::accesskey( 'diff' ),
4326 // Avoid PHP 7.1 warning of passing $this by reference
4328 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4334 * Creates a basic error page which informs the user that
4335 * they have attempted to edit a nonexistent section.
4337 public function noSuchSectionPage() {
4338 $out = $this->context
->getOutput();
4339 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4341 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4343 // Avoid PHP 7.1 warning of passing $this by reference
4345 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4346 $out->addHTML( $res );
4348 $out->returnToMain( false, $this->mTitle
);
4352 * Show "your edit contains spam" page with your diff and text
4354 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4356 public function spamPageWithContent( $match = false ) {
4357 $this->textbox2
= $this->textbox1
;
4359 if ( is_array( $match ) ) {
4360 $match = $this->context
->getLanguage()->listToText( $match );
4362 $out = $this->context
->getOutput();
4363 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4365 $out->addHTML( '<div id="spamprotected">' );
4366 $out->addWikiMsg( 'spamprotectiontext' );
4368 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4370 $out->addHTML( '</div>' );
4372 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4375 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4376 $this->showTextbox2();
4378 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4384 protected function addEditNotices() {
4385 $out = $this->context
->getOutput();
4386 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4387 if ( count( $editNotices ) ) {
4388 $out->addHTML( implode( "\n", $editNotices ) );
4390 $msg = $this->context
->msg( 'editnotice-notext' );
4391 if ( !$msg->isDisabled() ) {
4393 '<div class="mw-editnotice-notext">'
4394 . $msg->parseAsBlock()
4404 protected function addTalkPageText() {
4405 if ( $this->mTitle
->isTalkPage() ) {
4406 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4413 protected function addLongPageWarningHeader() {
4414 if ( $this->contentLength
=== false ) {
4415 $this->contentLength
= strlen( $this->textbox1
);
4418 $out = $this->context
->getOutput();
4419 $lang = $this->context
->getLanguage();
4420 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4421 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4422 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4425 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4426 $lang->formatNum( $maxArticleSize )
4429 } elseif ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4430 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4433 $lang->formatSize( strlen( $this->textbox1
) ),
4434 strlen( $this->textbox1
)
4443 protected function addPageProtectionWarningHeaders() {
4444 $out = $this->context
->getOutput();
4445 if ( $this->mTitle
->isProtected( 'edit' ) &&
4446 MediaWikiServices
::getInstance()->getNamespaceInfo()->getRestrictionLevels(
4447 $this->mTitle
->getNamespace()
4450 # Is the title semi-protected?
4451 if ( $this->mTitle
->isSemiProtected() ) {
4452 $noticeMsg = 'semiprotectedpagewarning';
4454 # Then it must be protected based on static groups (regular)
4455 $noticeMsg = 'protectedpagewarning';
4457 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4458 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4460 if ( $this->mTitle
->isCascadeProtected() ) {
4461 # Is this page under cascading protection from some source pages?
4462 /** @var Title[] $cascadeSources */
4463 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4464 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4465 $cascadeSourcesCount = count( $cascadeSources );
4466 if ( $cascadeSourcesCount > 0 ) {
4467 # Explain, and list the titles responsible
4468 foreach ( $cascadeSources as $page ) {
4469 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4472 $notice .= '</div>';
4473 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4475 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4476 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4478 'showIfEmpty' => false,
4479 'msgKey' => [ 'titleprotectedwarning' ],
4480 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4485 * @param OutputPage $out
4488 protected function addExplainConflictHeader( OutputPage
$out ) {
4490 $this->getEditConflictHelper()->getExplainHeader()
4495 * @param string $name
4496 * @param mixed[] $customAttribs
4501 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4502 return ( new TextboxBuilder() )->buildTextboxAttribs(
4503 $name, $customAttribs, $user, $this->mTitle
4508 * @param string $wikitext
4512 protected function addNewLineAtEnd( $wikitext ) {
4513 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4517 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4518 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4519 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4520 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4521 * spread the new style links more efficiently.
4523 * @param string $text
4526 private function guessSectionName( $text ) {
4527 // Detect Microsoft browsers
4528 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4529 $parser = MediaWikiServices
::getInstance()->getParser();
4530 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4531 // ...and redirect them to legacy encoding, if available
4532 return $parser->guessLegacySectionNameFromWikiText( $text );
4534 // Meanwhile, real browsers get real anchors
4535 $name = $parser->guessSectionNameFromWikiText( $text );
4536 // With one little caveat: per T216029, fragments in HTTP redirects need to be urlencoded,
4537 // otherwise Chrome double-escapes the rest of the URL.
4538 return '#' . urlencode( mb_substr( $name, 1 ) );
4542 * Set a factory function to create an EditConflictHelper
4544 * @param callable $factory Factory function
4547 public function setEditConflictHelperFactory( callable
$factory ) {
4548 $this->editConflictHelperFactory
= $factory;
4549 $this->editConflictHelper
= null;
4553 * @return TextConflictHelper
4555 private function getEditConflictHelper() {
4556 if ( !$this->editConflictHelper
) {
4557 $this->editConflictHelper
= call_user_func(
4558 $this->editConflictHelperFactory
,
4559 $this->getSubmitButtonLabel()
4563 return $this->editConflictHelper
;
4567 * @param string $submitButtonLabel
4568 * @return TextConflictHelper
4570 private function newTextConflictHelper( $submitButtonLabel ) {
4571 return new TextConflictHelper(
4573 $this->getContext()->getOutput(),
4574 MediaWikiServices
::getInstance()->getStatsdDataFactory(),