3 * User interface for page editing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\EditPage\TextboxBuilder
;
24 use MediaWiki\EditPage\TextConflictHelper
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\ScopedCallback
;
30 * The edit page/HTML interface (split from Article)
31 * The actual database and text munging is still in Article,
32 * but it should get easier to call those from alternate
35 * EditPage cares about two distinct titles:
36 * $this->mContextTitle is the page that forms submit to, links point to,
37 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
38 * page in the database that is actually being edited. These are
39 * usually the same, but they are now allowed to be different.
41 * Surgeon General's Warning: prolonged exposure to this class is known to cause
42 * headaches, which may be fatal.
46 * Used for Unicode support checks
48 const UNICODE_CHECK
= 'β³π²β₯πππΎπΈβ΄πΉβ―';
51 * Status: Article successfully updated
53 const AS_SUCCESS_UPDATE
= 200;
56 * Status: Article successfully created
58 const AS_SUCCESS_NEW_ARTICLE
= 201;
61 * Status: Article update aborted by a hook function
63 const AS_HOOK_ERROR
= 210;
66 * Status: A hook function returned an error
68 const AS_HOOK_ERROR_EXPECTED
= 212;
71 * Status: User is blocked from editing this page
73 const AS_BLOCKED_PAGE_FOR_USER
= 215;
76 * Status: Content too big (> $wgMaxArticleSize)
78 const AS_CONTENT_TOO_BIG
= 216;
81 * Status: this anonymous user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_ANON
= 218;
86 * Status: this logged in user is not allowed to edit this page
88 const AS_READ_ONLY_PAGE_LOGGED
= 219;
91 * Status: wiki is in readonly mode (wfReadOnly() == true)
93 const AS_READ_ONLY_PAGE
= 220;
96 * Status: rate limiter for action 'edit' was tripped
98 const AS_RATE_LIMITED
= 221;
101 * Status: article was deleted while editing and param wpRecreate == false or form
104 const AS_ARTICLE_WAS_DELETED
= 222;
107 * Status: user tried to create this page, but is not allowed to do that
108 * ( Title->userCan('create') == false )
110 const AS_NO_CREATE_PERMISSION
= 223;
113 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
115 const AS_BLANK_ARTICLE
= 224;
118 * Status: (non-resolvable) edit conflict
120 const AS_CONFLICT_DETECTED
= 225;
123 * Status: no edit summary given and the user has forceeditsummary set and the user is not
124 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
126 const AS_SUMMARY_NEEDED
= 226;
129 * Status: user tried to create a new section without content
131 const AS_TEXTBOX_EMPTY
= 228;
134 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
136 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
139 * Status: WikiPage::doEdit() was unsuccessful
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
146 const AS_SPAM_ERROR
= 232;
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
151 const AS_IMAGE_REDIRECT_ANON
= 233;
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
156 const AS_IMAGE_REDIRECT_LOGGED
= 234;
159 * Status: user tried to modify the content model, but is not allowed to do that
160 * ( User::isAllowed('editcontentmodel') == false )
162 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
165 * Status: user tried to create self-redirect (redirect to the same article) and
166 * wpIgnoreSelfRedirect == false
168 const AS_SELF_REDIRECT
= 236;
171 * Status: an error relating to change tagging. Look at the message key for
174 const AS_CHANGE_TAG_ERROR
= 237;
177 * Status: can't parse content
179 const AS_PARSE_ERROR
= 240;
182 * Status: when changing the content model is disallowed due to
183 * $wgContentHandlerUseDB being false
185 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
188 * Status: edit rejected because browser doesn't support Unicode.
190 const AS_UNICODE_NOT_SUPPORTED
= 242;
193 * HTML id and name for the beginning of the edit form.
195 const EDITFORM_ID
= 'editform';
198 * Prefix of key for cookie used to pass post-edit state.
199 * The revision id edited is added after this
201 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
204 * Duration of PostEdit cookie, in seconds.
205 * The cookie will be removed instantly if the JavaScript runs.
207 * Otherwise, though, we don't want the cookies to accumulate.
208 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
209 * limit of only 20 cookies per domain. This still applies at least to some
210 * versions of IE without full updates:
211 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
213 * A value of 20 minutes should be enough to take into account slow loads and minor
214 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
216 const POST_EDIT_COOKIE_DURATION
= 1200;
219 * @deprecated for public usage since 1.30 use EditPage::getArticle()
227 * @deprecated for public usage since 1.30 use EditPage::getTitle()
232 /** @var null|Title */
233 private $mContextTitle = null;
236 public $action = 'submit';
238 /** @var bool Whether an edit conflict needs to be resolved. Detected based on whether
239 * $editRevId is different than the latest revision. When a conflict has successfully
240 * been resolved by a 3-way-merge, this field is set to false.
242 public $isConflict = false;
244 /** @var bool New page or new section */
245 public $isNew = false;
248 public $deletedSinceEdit;
254 * True the first time the edit form is rendered, false after re-rendering
255 * with diff, save prompts, etc.
259 /** @var bool|stdClass */
263 public $mTokenOk = false;
266 public $mTokenOkExceptSuffix = false;
269 public $mTriedSave = false;
272 public $incompleteForm = false;
275 public $tooBig = false;
278 public $missingComment = false;
281 public $missingSummary = false;
284 public $allowBlankSummary = false;
287 protected $blankArticle = false;
290 protected $allowBlankArticle = false;
293 protected $selfRedirect = false;
296 protected $allowSelfRedirect = false;
299 public $autoSumm = '';
302 public $hookError = '';
304 /** @var ParserOutput */
305 public $mParserOutput;
307 /** @var bool Has a summary been preset using GET parameter &summary= ? */
308 public $hasPresetSummary = false;
310 /** @var Revision|bool|null A revision object corresponding to $this->editRevId. */
311 public $mBaseRevision = false;
314 public $mShowSummaryField = true;
319 public $save = false;
322 public $preview = false;
325 public $diff = false;
328 public $minoredit = false;
331 public $watchthis = false;
334 public $recreate = false;
337 * Page content input field.
339 public $textbox1 = '';
342 public $textbox2 = '';
345 public $summary = '';
348 * If true, hide the summary field.
350 public $nosummary = false;
353 * Timestamp of the latest revision of the page when editing was initiated
356 public $edittime = '';
358 /** @var int Revision ID of the latest revision of the page when editing
359 * was initiated on the client. This is used to detect and resolve edit
362 * @note 0 if the page did not exist at that time.
363 * @note When starting an edit from an old revision, this still records the current
364 * revision at the time, not the one the edit is based on.
367 * @see getBaseRevision()
369 private $editRevId = null;
372 public $section = '';
375 public $sectiontitle = '';
378 * Timestamp from the first time the edit form was rendered.
380 public $starttime = '';
382 /** @var int Revision ID the edit is based on, or 0 if it's the current revision.
383 * FIXME: This isn't used in conflict resolution--provide a better
384 * justification or merge with parentRevId.
389 /** @var int Revision ID the edit is based on, adjusted when an edit conflict is resolved.
392 * @see getparentRevId()
394 public $parentRevId = 0;
397 public $editintro = '';
400 public $scrolltop = null;
406 public $contentModel;
408 /** @var null|string */
409 public $contentFormat = null;
411 /** @var null|array */
412 private $changeTags = null;
414 # Placeholders for text injection by hooks (must be HTML)
415 # extensions should take care to _append_ to the present value
417 /** @var string Before even the preview */
418 public $editFormPageTop = '';
419 public $editFormTextTop = '';
420 public $editFormTextBeforeContent = '';
421 public $editFormTextAfterWarn = '';
422 public $editFormTextAfterTools = '';
423 public $editFormTextBottom = '';
424 public $editFormTextAfterContent = '';
425 public $previewTextAfterContent = '';
426 public $mPreloadContent = null;
428 /* $didSave should be set to true whenever an article was successfully altered. */
429 public $didSave = false;
430 public $undidRev = 0;
432 public $suppressIntro = false;
438 protected $contentLength = false;
441 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
443 private $enableApiEditOverride = false;
446 * @var IContextSource
451 * @var bool Whether an old revision is edited
453 private $isOldRev = false;
456 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
458 private $unicodeCheck;
461 * Factory function to create an edit conflict helper
465 private $editConflictHelperFactory;
468 * @var TextConflictHelper|null
470 private $editConflictHelper;
473 * @param Article $article
475 public function __construct( Article
$article ) {
476 $this->mArticle
= $article;
477 $this->page
= $article->getPage(); // model object
478 $this->mTitle
= $article->getTitle();
480 // Make sure the local context is in sync with other member variables.
481 // Particularly make sure everything is using the same WikiPage instance.
482 // This should probably be the case in Article as well, but it's
483 // particularly important for EditPage, to make use of the in-place caching
484 // facility in WikiPage::prepareContentForEdit.
485 $this->context
= new DerivativeContext( $article->getContext() );
486 $this->context
->setWikiPage( $this->page
);
487 $this->context
->setTitle( $this->mTitle
);
489 $this->contentModel
= $this->mTitle
->getContentModel();
491 $handler = ContentHandler
::getForModelID( $this->contentModel
);
492 $this->contentFormat
= $handler->getDefaultFormat();
493 $this->editConflictHelperFactory
= [ $this, 'newTextConflictHelper' ];
499 public function getArticle() {
500 return $this->mArticle
;
505 * @return IContextSource
507 public function getContext() {
508 return $this->context
;
515 public function getTitle() {
516 return $this->mTitle
;
520 * Set the context Title object
522 * @param Title|null $title Title object or null
524 public function setContextTitle( $title ) {
525 $this->mContextTitle
= $title;
529 * Get the context title object.
531 * If not set, $wgTitle will be returned, but this is deprecated. This will
532 * throw an exception.
536 public function getContextTitle() {
537 if ( is_null( $this->mContextTitle
) ) {
538 wfDeprecated( __METHOD__
. ' called with no title set', '1.32' );
542 return $this->mContextTitle
;
547 * Returns if the given content model is editable.
549 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
551 * @throws MWException If $modelId has no known handler
553 public function isSupportedContentModel( $modelId ) {
554 return $this->enableApiEditOverride
=== true ||
555 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
559 * Allow editing of content that supports API direct editing, but not general
560 * direct editing. Set to false by default.
562 * @param bool $enableOverride
564 public function setApiEditOverride( $enableOverride ) {
565 $this->enableApiEditOverride
= $enableOverride;
569 * @deprecated since 1.29, call edit directly
571 public function submit() {
572 wfDeprecated( __METHOD__
, '1.29' );
577 * This is the function that gets called for "action=edit". It
578 * sets up various member variables, then passes execution to
579 * another function, usually showEditForm()
581 * The edit form is self-submitting, so that when things like
582 * preview and edit conflicts occur, we get the same form back
583 * with the extra stuff added. Only when the final submission
584 * is made and all is well do we actually save and redirect to
585 * the newly-edited page.
587 public function edit() {
588 // Allow extensions to modify/prevent this form or submission
589 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
593 wfDebug( __METHOD__
. ": enter\n" );
595 $request = $this->context
->getRequest();
596 // If they used redlink=1 and the page exists, redirect to the main article
597 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
598 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
602 $this->importFormData( $request );
603 $this->firsttime
= false;
605 if ( wfReadOnly() && $this->save
) {
608 $this->preview
= true;
612 $this->formtype
= 'save';
613 } elseif ( $this->preview
) {
614 $this->formtype
= 'preview';
615 } elseif ( $this->diff
) {
616 $this->formtype
= 'diff';
617 } else { # First time through
618 $this->firsttime
= true;
619 if ( $this->previewOnOpen() ) {
620 $this->formtype
= 'preview';
622 $this->formtype
= 'initial';
626 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
628 wfDebug( __METHOD__
. ": User can't edit\n" );
630 if ( $this->context
->getUser()->getBlock() ) {
631 // track block with a cookie if it doesn't exists already
632 $this->context
->getUser()->trackBlockWithCookie();
634 // Auto-block user's IP if the account was "hard" blocked
635 if ( !wfReadOnly() ) {
636 DeferredUpdates
::addCallableUpdate( function () {
637 $this->context
->getUser()->spreadAnyEditBlock();
641 $config = $this->context
->getConfig();
642 if ( $config->get( 'EnableBlockNoticeStats' ) ) {
643 $wiki = $config->get( 'DBname' );
644 $statsd = MediaWikiServices
::getInstance()->getStatsdDataFactory();
645 $statsd->increment( 'BlockNotices.' . $wiki . '.WikitextEditor.shown' );
648 $this->displayPermissionsError( $permErrors );
653 $revision = $this->mArticle
->getRevisionFetched();
654 // Disallow editing revisions with content models different from the current one
655 // Undo edits being an exception in order to allow reverting content model changes.
657 && $revision->getContentModel() !== $this->contentModel
660 if ( $this->undidRev
) {
661 $undidRevObj = Revision
::newFromId( $this->undidRev
);
662 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
664 if ( !$this->undidRev
666 ||
$prevRev->getContentModel() !== $this->contentModel
668 $this->displayViewSourcePage(
669 $this->getContentObject(),
671 'contentmodelediterror',
672 $revision->getContentModel(),
680 $this->isConflict
= false;
682 # Show applicable editing introductions
683 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
687 # Attempt submission here. This will check for edit conflicts,
688 # and redundantly check for locked database, blocked IPs, etc.
689 # that edit() already checked just in case someone tries to sneak
690 # in the back door with a hand-edited submission URL.
692 if ( $this->formtype
== 'save' ) {
693 $resultDetails = null;
694 $status = $this->attemptSave( $resultDetails );
695 if ( !$this->handleStatus( $status, $resultDetails ) ) {
700 # First time through: get contents, set time for conflict
702 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
703 if ( $this->initialiseForm() === false ) {
704 $out = $this->context
->getOutput();
705 if ( $out->getRedirect() === '' ) { // mcrundo hack redirects, don't override it
706 $this->noSuchSectionPage();
711 if ( !$this->mTitle
->getArticleID() ) {
712 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
714 Hooks
::run( 'EditFormInitialText', [ $this ] );
719 $this->showEditForm();
723 * @param string $rigor Same format as Title::getUserPermissionErrors()
726 protected function getEditPermissionErrors( $rigor = 'secure' ) {
727 $user = $this->context
->getUser();
728 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
729 # Can this title be created?
730 if ( !$this->mTitle
->exists() ) {
731 $permErrors = array_merge(
734 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
739 # Ignore some permissions errors when a user is just previewing/viewing diffs
741 foreach ( $permErrors as $error ) {
742 if ( ( $this->preview ||
$this->diff
)
744 $error[0] == 'blockedtext' ||
745 $error[0] == 'autoblockedtext' ||
746 $error[0] == 'systemblockedtext'
752 $permErrors = wfArrayDiff2( $permErrors, $remove );
758 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
759 * but with the following differences:
760 * - If redlink=1, the user will be redirected to the page
761 * - If there is content to display or the error occurs while either saving,
762 * previewing or showing the difference, it will be a
763 * "View source for ..." page displaying the source code after the error message.
766 * @param array $permErrors Array of permissions errors, as returned by
767 * Title::getUserPermissionsErrors().
768 * @throws PermissionsError
770 protected function displayPermissionsError( array $permErrors ) {
771 $out = $this->context
->getOutput();
772 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
773 // The edit page was reached via a red link.
774 // Redirect to the article page and let them click the edit tab if
775 // they really want a permission error.
776 $out->redirect( $this->mTitle
->getFullURL() );
780 $content = $this->getContentObject();
782 # Use the normal message if there's nothing to display
783 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
784 $action = $this->mTitle
->exists() ?
'edit' :
785 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
786 throw new PermissionsError( $action, $permErrors );
789 $this->displayViewSourcePage(
791 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
796 * Display a read-only View Source page
797 * @param Content $content
798 * @param string $errorMessage additional wikitext error message to display
800 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
801 $out = $this->context
->getOutput();
802 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
804 $out->setRobotPolicy( 'noindex,nofollow' );
805 $out->setPageTitle( $this->context
->msg(
807 $this->getContextTitle()->getPrefixedText()
809 $out->addBacklinkSubtitle( $this->getContextTitle() );
810 $out->addHTML( $this->editFormPageTop
);
811 $out->addHTML( $this->editFormTextTop
);
813 if ( $errorMessage !== '' ) {
814 $out->addWikiTextAsInterface( $errorMessage );
815 $out->addHTML( "<hr />\n" );
818 # If the user made changes, preserve them when showing the markup
819 # (This happens when a user is blocked during edit, for instance)
820 if ( !$this->firsttime
) {
821 $text = $this->textbox1
;
822 $out->addWikiMsg( 'viewyourtext' );
825 $text = $this->toEditText( $content );
826 } catch ( MWException
$e ) {
827 # Serialize using the default format if the content model is not supported
828 # (e.g. for an old revision with a different model)
829 $text = $content->serialize();
831 $out->addWikiMsg( 'viewsourcetext' );
834 $out->addHTML( $this->editFormTextBeforeContent
);
835 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
836 $out->addHTML( $this->editFormTextAfterContent
);
838 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
840 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
842 $out->addHTML( $this->editFormTextBottom
);
843 if ( $this->mTitle
->exists() ) {
844 $out->returnToMain( null, $this->mTitle
);
849 * Should we show a preview when the edit form is first shown?
853 protected function previewOnOpen() {
854 $config = $this->context
->getConfig();
855 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
856 $request = $this->context
->getRequest();
857 if ( $config->get( 'RawHtml' ) ) {
858 // If raw HTML is enabled, disable preview on open
859 // since it has to be posted with a token for
863 if ( $request->getVal( 'preview' ) == 'yes' ) {
864 // Explicit override from request
866 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
867 // Explicit override from request
869 } elseif ( $this->section
== 'new' ) {
870 // Nothing *to* preview for new sections
872 } elseif ( ( $request->getCheck( 'preload' ) ||
$this->mTitle
->exists() )
873 && $this->context
->getUser()->getOption( 'previewonfirst' )
875 // Standard preference behavior
877 } elseif ( !$this->mTitle
->exists()
878 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
879 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
881 // Categories are special
889 * Checks whether the user entered a skin name in uppercase,
890 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
894 protected function isWrongCaseUserConfigPage() {
895 if ( $this->mTitle
->isUserConfigPage() ) {
896 $name = $this->mTitle
->getSkinFromConfigSubpage();
897 $skins = array_merge(
898 array_keys( Skin
::getSkinNames() ),
901 return !in_array( $name, $skins )
902 && in_array( strtolower( $name ), $skins );
909 * Returns whether section editing is supported for the current page.
910 * Subclasses may override this to replace the default behavior, which is
911 * to check ContentHandler::supportsSections.
913 * @return bool True if this edit page supports sections, false otherwise.
915 protected function isSectionEditSupported() {
916 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
917 return $contentHandler->supportsSections();
921 * This function collects the form data and uses it to populate various member variables.
922 * @param WebRequest &$request
923 * @throws ErrorPageError
925 public function importFormData( &$request ) {
926 # Section edit can come from either the form or a link
927 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
929 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
930 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
933 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
935 if ( $request->wasPosted() ) {
936 # These fields need to be checked for encoding.
937 # Also remove trailing whitespace, but don't remove _initial_
938 # whitespace from the text boxes. This may be significant formatting.
939 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
940 if ( !$request->getCheck( 'wpTextbox2' ) ) {
941 // Skip this if wpTextbox2 has input, it indicates that we came
942 // from a conflict page with raw page text, not a custom form
943 // modified by subclasses
944 $textbox1 = $this->importContentFormData( $request );
945 if ( $textbox1 !== null ) {
946 $this->textbox1
= $textbox1;
950 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
952 $this->summary
= $request->getText( 'wpSummary' );
954 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
955 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
957 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
959 # Treat sectiontitle the same way as summary.
960 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
961 # currently doing double duty as both edit summary and section title. Right now this
962 # is just to allow API edits to work around this limitation, but this should be
963 # incorporated into the actual edit form when EditPage is rewritten (T20654, T28312).
964 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
965 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
967 $this->edittime
= $request->getVal( 'wpEdittime' );
968 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
969 $this->starttime
= $request->getVal( 'wpStarttime' );
971 $undidRev = $request->getInt( 'wpUndidRevision' );
973 $this->undidRev
= $undidRev;
976 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
978 if ( $this->textbox1
=== '' && !$request->getCheck( 'wpTextbox1' ) ) {
979 // wpTextbox1 field is missing, possibly due to being "too big"
980 // according to some filter rules such as Suhosin's setting for
981 // suhosin.request.max_value_length (d'oh)
982 $this->incompleteForm
= true;
984 // If we receive the last parameter of the request, we can fairly
985 // claim the POST request has not been truncated.
986 $this->incompleteForm
= !$request->getVal( 'wpUltimateParam' );
988 if ( $this->incompleteForm
) {
989 # If the form is incomplete, force to preview.
990 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
991 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
992 $this->preview
= true;
994 $this->preview
= $request->getCheck( 'wpPreview' );
995 $this->diff
= $request->getCheck( 'wpDiff' );
997 // Remember whether a save was requested, so we can indicate
998 // if we forced preview due to session failure.
999 $this->mTriedSave
= !$this->preview
;
1001 if ( $this->tokenOk( $request ) ) {
1002 # Some browsers will not report any submit button
1003 # if the user hits enter in the comment box.
1004 # The unmarked state will be assumed to be a save,
1005 # if the form seems otherwise complete.
1006 wfDebug( __METHOD__
. ": Passed token check.\n" );
1007 } elseif ( $this->diff
) {
1008 # Failed token check, but only requested "Show Changes".
1009 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
1011 # Page might be a hack attempt posted from
1012 # an external site. Preview instead of saving.
1013 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
1014 $this->preview
= true;
1017 $this->save
= !$this->preview
&& !$this->diff
;
1018 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
1019 $this->edittime
= null;
1022 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
1023 $this->starttime
= null;
1026 $this->recreate
= $request->getCheck( 'wpRecreate' );
1028 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
1029 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
1031 $user = $this->context
->getUser();
1032 # Don't force edit summaries when a user is editing their own user or talk page
1033 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
1034 && $this->mTitle
->getText() == $user->getName()
1036 $this->allowBlankSummary
= true;
1038 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1039 ||
!$user->getOption( 'forceeditsummary' );
1042 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1044 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1045 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1047 $changeTags = $request->getVal( 'wpChangeTags' );
1048 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1049 $this->changeTags
= [];
1051 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1055 # Not a posted form? Start with nothing.
1056 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1057 $this->textbox1
= '';
1058 $this->summary
= '';
1059 $this->sectiontitle
= '';
1060 $this->edittime
= '';
1061 $this->editRevId
= null;
1062 $this->starttime
= wfTimestampNow();
1063 $this->edit
= false;
1064 $this->preview
= false;
1065 $this->save
= false;
1066 $this->diff
= false;
1067 $this->minoredit
= false;
1068 // Watch may be overridden by request parameters
1069 $this->watchthis
= $request->getBool( 'watchthis', false );
1070 $this->recreate
= false;
1072 // When creating a new section, we can preload a section title by passing it as the
1073 // preloadtitle parameter in the URL (T15100)
1074 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1075 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1076 // Once wpSummary isn't being use for setting section titles, we should delete this.
1077 $this->summary
= $request->getVal( 'preloadtitle' );
1078 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) !== '' ) {
1079 $this->summary
= $request->getText( 'summary' );
1080 if ( $this->summary
!== '' ) {
1081 $this->hasPresetSummary
= true;
1085 if ( $request->getVal( 'minor' ) ) {
1086 $this->minoredit
= true;
1090 $this->oldid
= $request->getInt( 'oldid' );
1091 $this->parentRevId
= $request->getInt( 'parentRevId' );
1093 $this->bot
= $request->getBool( 'bot', true );
1094 $this->nosummary
= $request->getBool( 'nosummary' );
1096 // May be overridden by revision.
1097 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1098 // May be overridden by revision.
1099 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1102 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1103 } catch ( MWUnknownContentModelException
$e ) {
1104 throw new ErrorPageError(
1105 'editpage-invalidcontentmodel-title',
1106 'editpage-invalidcontentmodel-text',
1107 [ wfEscapeWikiText( $this->contentModel
) ]
1111 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1112 throw new ErrorPageError(
1113 'editpage-notsupportedcontentformat-title',
1114 'editpage-notsupportedcontentformat-text',
1116 wfEscapeWikiText( $this->contentFormat
),
1117 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1123 * @todo Check if the desired model is allowed in this namespace, and if
1124 * a transition from the page's current model to the new model is
1128 $this->editintro
= $request->getText( 'editintro',
1129 // Custom edit intro for new sections
1130 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1132 // Allow extensions to modify form data
1133 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1137 * Subpage overridable method for extracting the page content data from the
1138 * posted form to be placed in $this->textbox1, if using customized input
1139 * this method should be overridden and return the page text that will be used
1140 * for saving, preview parsing and so on...
1142 * @param WebRequest &$request
1143 * @return string|null
1145 protected function importContentFormData( &$request ) {
1146 return; // Don't do anything, EditPage already extracted wpTextbox1
1150 * Initialise form fields in the object
1151 * Called on the first invocation, e.g. when a user clicks an edit link
1152 * @return bool If the requested section is valid
1154 public function initialiseForm() {
1155 $this->edittime
= $this->page
->getTimestamp();
1156 $this->editRevId
= $this->page
->getLatest();
1158 $content = $this->getContentObject( false ); # TODO: track content object?!
1159 if ( $content === false ) {
1162 $this->textbox1
= $this->toEditText( $content );
1164 $user = $this->context
->getUser();
1165 // activate checkboxes if user wants them to be always active
1166 # Sort out the "watch" checkbox
1167 if ( $user->getOption( 'watchdefault' ) ) {
1169 $this->watchthis
= true;
1170 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1172 $this->watchthis
= true;
1173 } elseif ( $user->isWatched( $this->mTitle
) ) {
1175 $this->watchthis
= true;
1177 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1178 $this->minoredit
= true;
1180 if ( $this->textbox1
=== false ) {
1187 * @param Content|null $def_content The default value to return
1189 * @return Content|null Content on success, $def_content for invalid sections
1193 protected function getContentObject( $def_content = null ) {
1196 $user = $this->context
->getUser();
1197 $request = $this->context
->getRequest();
1198 // For message page not locally set, use the i18n message.
1199 // For other non-existent articles, use preload text if any.
1200 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1201 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1202 # If this is a system message, get the default text.
1203 $msg = $this->mTitle
->getDefaultMessageText();
1205 $content = $this->toEditContent( $msg );
1207 if ( $content === false ) {
1208 # If requested, preload some text.
1209 $preload = $request->getVal( 'preload',
1210 // Custom preload text for new sections
1211 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1212 $params = $request->getArray( 'preloadparams', [] );
1214 $content = $this->getPreloadedContent( $preload, $params );
1216 // For existing pages, get text based on "undo" or section parameters.
1217 } elseif ( $this->section
!= '' ) {
1218 // Get section edit text (returns $def_text for invalid sections)
1219 $orig = $this->getOriginalContent( $user );
1220 $content = $orig ?
$orig->getSection( $this->section
) : null;
1223 $content = $def_content;
1226 $undoafter = $request->getInt( 'undoafter' );
1227 $undo = $request->getInt( 'undo' );
1229 if ( $undo > 0 && $undoafter > 0 ) {
1230 $undorev = Revision
::newFromId( $undo );
1231 $oldrev = Revision
::newFromId( $undoafter );
1234 # Sanity check, make sure it's the right page,
1235 # the revisions exist and they were not deleted.
1236 # Otherwise, $content will be left as-is.
1237 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1238 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1239 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1241 if ( WikiPage
::hasDifferencesOutsideMainSlot( $undorev, $oldrev )
1242 ||
!$this->isSupportedContentModel( $oldrev->getContentModel() )
1244 // Hack for undo while EditPage can't handle multi-slot editing
1245 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL( [
1246 'action' => 'mcrundo',
1248 'undoafter' => $undoafter,
1252 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1254 if ( $content === false ) {
1255 # Warn the user that something went wrong
1256 $undoMsg = 'failure';
1260 if ( $undoMsg === null ) {
1261 $oldContent = $this->page
->getContent( Revision
::RAW
);
1262 $popts = ParserOptions
::newFromUserAndLang(
1263 $user, MediaWikiServices
::getInstance()->getContentLanguage() );
1264 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1265 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1266 // The undo may change content
1267 // model if its reverting the top
1268 // edit. This can result in
1269 // mismatched content model/format.
1270 $this->contentModel
= $newContent->getModel();
1271 $this->contentFormat
= $oldrev->getContentFormat();
1274 if ( $newContent->equals( $oldContent ) ) {
1275 # Tell the user that the undo results in no change,
1276 # i.e. the revisions were already undone.
1277 $undoMsg = 'nochange';
1280 # Inform the user of our success and set an automatic edit summary
1281 $undoMsg = 'success';
1283 # If we just undid one rev, use an autosummary
1284 $firstrev = $oldrev->getNext();
1285 if ( $firstrev && $firstrev->getId() == $undo ) {
1286 $userText = $undorev->getUserText();
1287 if ( $userText === '' ) {
1288 $undoSummary = $this->context
->msg(
1289 'undo-summary-username-hidden',
1291 )->inContentLanguage()->text();
1293 $undoSummary = $this->context
->msg(
1297 )->inContentLanguage()->text();
1299 if ( $this->summary
=== '' ) {
1300 $this->summary
= $undoSummary;
1302 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1303 ->inContentLanguage()->text() . $this->summary
;
1305 $this->undidRev
= $undo;
1307 $this->formtype
= 'diff';
1311 // Failed basic sanity checks.
1312 // Older revisions may have been removed since the link
1313 // was created, or we may simply have got bogus input.
1317 $out = $this->context
->getOutput();
1318 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1320 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1321 $this->editFormPageTop
.= Html
::rawElement(
1322 'div', [ 'class' => $class ],
1323 $out->parseAsInterface(
1324 $this->context
->msg( 'undo-' . $undoMsg )->plain()
1329 if ( $content === false ) {
1330 // Hack for restoring old revisions while EditPage
1331 // can't handle multi-slot editing.
1333 $curRevision = $this->page
->getRevision();
1334 $oldRevision = $this->mArticle
->getRevisionFetched();
1338 && $curRevision->getId() !== $oldRevision->getId()
1339 && ( WikiPage
::hasDifferencesOutsideMainSlot( $oldRevision, $curRevision )
1340 ||
!$this->isSupportedContentModel( $oldRevision->getContentModel() ) )
1342 $this->context
->getOutput()->redirect(
1343 $this->mTitle
->getFullURL(
1345 'action' => 'mcrrestore',
1346 'restore' => $oldRevision->getId(),
1355 if ( $content === false ) {
1356 $content = $this->getOriginalContent( $user );
1364 * Get the content of the wanted revision, without section extraction.
1366 * The result of this function can be used to compare user's input with
1367 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1368 * to the original text of the edit.
1370 * This differs from Article::getContent() that when a missing revision is
1371 * encountered the result will be null and not the
1372 * 'missing-revision' message.
1375 * @param User $user The user to get the revision for
1376 * @return Content|null
1378 private function getOriginalContent( User
$user ) {
1379 if ( $this->section
== 'new' ) {
1380 return $this->getCurrentContent();
1382 $revision = $this->mArticle
->getRevisionFetched();
1383 if ( $revision === null ) {
1384 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1385 return $handler->makeEmptyContent();
1387 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1392 * Get the edit's parent revision ID
1394 * The "parent" revision is the ancestor that should be recorded in this
1395 * page's revision history. It is either the revision ID of the in-memory
1396 * article content, or in the case of a 3-way merge in order to rebase
1397 * across a recoverable edit conflict, the ID of the newer revision to
1398 * which we have rebased this page.
1401 * @return int Revision ID
1403 public function getParentRevId() {
1404 if ( $this->parentRevId
) {
1405 return $this->parentRevId
;
1407 return $this->mArticle
->getRevIdFetched();
1412 * Get the current content of the page. This is basically similar to
1413 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1414 * content object is returned instead of null.
1419 protected function getCurrentContent() {
1420 $rev = $this->page
->getRevision();
1421 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1423 if ( $content === false ||
$content === null ) {
1424 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1425 return $handler->makeEmptyContent();
1426 } elseif ( !$this->undidRev
) {
1427 // Content models should always be the same since we error
1428 // out if they are different before this point (in ->edit()).
1429 // The exception being, during an undo, the current revision might
1430 // differ from the prior revision.
1431 $logger = LoggerFactory
::getInstance( 'editpage' );
1432 if ( $this->contentModel
!== $rev->getContentModel() ) {
1433 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1434 'prev' => $this->contentModel
,
1435 'new' => $rev->getContentModel(),
1436 'title' => $this->getTitle()->getPrefixedDBkey(),
1437 'method' => __METHOD__
1439 $this->contentModel
= $rev->getContentModel();
1442 // Given that the content models should match, the current selected
1443 // format should be supported.
1444 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1445 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1447 'prev' => $this->contentFormat
,
1448 'new' => $rev->getContentFormat(),
1449 'title' => $this->getTitle()->getPrefixedDBkey(),
1450 'method' => __METHOD__
1452 $this->contentFormat
= $rev->getContentFormat();
1459 * Use this method before edit() to preload some content into the edit box
1461 * @param Content $content
1465 public function setPreloadedContent( Content
$content ) {
1466 $this->mPreloadContent
= $content;
1470 * Get the contents to be preloaded into the box, either set by
1471 * an earlier setPreloadText() or by loading the given page.
1473 * @param string $preload Representing the title to preload from.
1474 * @param array $params Parameters to use (interface-message style) in the preloaded text
1480 protected function getPreloadedContent( $preload, $params = [] ) {
1481 if ( !empty( $this->mPreloadContent
) ) {
1482 return $this->mPreloadContent
;
1485 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1487 if ( $preload === '' ) {
1488 return $handler->makeEmptyContent();
1491 $user = $this->context
->getUser();
1492 $title = Title
::newFromText( $preload );
1493 # Check for existence to avoid getting MediaWiki:Noarticletext
1494 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1495 // TODO: somehow show a warning to the user!
1496 return $handler->makeEmptyContent();
1499 $page = WikiPage
::factory( $title );
1500 if ( $page->isRedirect() ) {
1501 $title = $page->getRedirectTarget();
1503 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1504 // TODO: somehow show a warning to the user!
1505 return $handler->makeEmptyContent();
1507 $page = WikiPage
::factory( $title );
1510 $parserOptions = ParserOptions
::newFromUser( $user );
1511 $content = $page->getContent( Revision
::RAW
);
1514 // TODO: somehow show a warning to the user!
1515 return $handler->makeEmptyContent();
1518 if ( $content->getModel() !== $handler->getModelID() ) {
1519 $converted = $content->convert( $handler->getModelID() );
1521 if ( !$converted ) {
1522 // TODO: somehow show a warning to the user!
1523 wfDebug( "Attempt to preload incompatible content: " .
1524 "can't convert " . $content->getModel() .
1525 " to " . $handler->getModelID() );
1527 return $handler->makeEmptyContent();
1530 $content = $converted;
1533 return $content->preloadTransform( $title, $parserOptions, $params );
1537 * Make sure the form isn't faking a user's credentials.
1539 * @param WebRequest &$request
1543 public function tokenOk( &$request ) {
1544 $token = $request->getVal( 'wpEditToken' );
1545 $user = $this->context
->getUser();
1546 $this->mTokenOk
= $user->matchEditToken( $token );
1547 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1548 return $this->mTokenOk
;
1552 * Sets post-edit cookie indicating the user just saved a particular revision.
1554 * This uses a temporary cookie for each revision ID so separate saves will never
1555 * interfere with each other.
1557 * Article::view deletes the cookie on server-side after the redirect and
1558 * converts the value to the global JavaScript variable wgPostEdit.
1560 * If the variable were set on the server, it would be cached, which is unwanted
1561 * since the post-edit state should only apply to the load right after the save.
1563 * @param int $statusValue The status value (to check for new article status)
1565 protected function setPostEditCookie( $statusValue ) {
1566 $revisionId = $this->page
->getLatest();
1567 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1570 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1572 } elseif ( $this->oldid
) {
1576 $response = $this->context
->getRequest()->response();
1577 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1581 * Attempt submission
1582 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1583 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1584 * @return Status The resulting status object.
1586 public function attemptSave( &$resultDetails = false ) {
1587 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1588 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1589 // This is needed since PageUpdater no longer checks these rights!
1591 // Allow bots to exempt some edits from bot flagging
1592 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1593 $status = $this->internalAttemptSave( $resultDetails, $bot );
1595 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1601 * Log when a page was successfully saved after the edit conflict view
1603 private function incrementResolvedConflicts() {
1604 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1608 $this->getEditConflictHelper()->incrementResolvedStats();
1612 * Handle status, such as after attempt save
1614 * @param Status $status
1615 * @param array|bool $resultDetails
1617 * @throws ErrorPageError
1618 * @return bool False, if output is done, true if rest of the form should be displayed
1620 private function handleStatus( Status
$status, $resultDetails ) {
1622 * @todo FIXME: once the interface for internalAttemptSave() is made
1623 * nicer, this should use the message in $status
1625 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1626 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1628 $this->incrementResolvedConflicts();
1630 $this->didSave
= true;
1631 if ( !$resultDetails['nullEdit'] ) {
1632 $this->setPostEditCookie( $status->value
);
1636 $out = $this->context
->getOutput();
1638 // "wpExtraQueryRedirect" is a hidden input to modify
1639 // after save URL and is not used by actual edit form
1640 $request = $this->context
->getRequest();
1641 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1643 switch ( $status->value
) {
1644 case self
::AS_HOOK_ERROR_EXPECTED
:
1645 case self
::AS_CONTENT_TOO_BIG
:
1646 case self
::AS_ARTICLE_WAS_DELETED
:
1647 case self
::AS_CONFLICT_DETECTED
:
1648 case self
::AS_SUMMARY_NEEDED
:
1649 case self
::AS_TEXTBOX_EMPTY
:
1650 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1652 case self
::AS_BLANK_ARTICLE
:
1653 case self
::AS_SELF_REDIRECT
:
1656 case self
::AS_HOOK_ERROR
:
1659 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1660 case self
::AS_PARSE_ERROR
:
1661 case self
::AS_UNICODE_NOT_SUPPORTED
:
1662 $out->wrapWikiTextAsInterface( 'error', $status->getWikiText() );
1665 case self
::AS_SUCCESS_NEW_ARTICLE
:
1666 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1667 if ( $extraQueryRedirect ) {
1668 if ( $query !== '' ) {
1671 $query .= $extraQueryRedirect;
1673 $anchor = $resultDetails['sectionanchor'] ??
'';
1674 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1677 case self
::AS_SUCCESS_UPDATE
:
1679 $sectionanchor = $resultDetails['sectionanchor'];
1681 // Give extensions a chance to modify URL query on update
1683 'ArticleUpdateBeforeRedirect',
1684 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1687 if ( $resultDetails['redirect'] ) {
1688 if ( $extraQuery !== '' ) {
1689 $extraQuery = '&' . $extraQuery;
1691 $extraQuery = 'redirect=no' . $extraQuery;
1693 if ( $extraQueryRedirect ) {
1694 if ( $extraQuery !== '' ) {
1697 $extraQuery .= $extraQueryRedirect;
1700 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1703 case self
::AS_SPAM_ERROR
:
1704 $this->spamPageWithContent( $resultDetails['spam'] );
1707 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1708 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1710 case self
::AS_IMAGE_REDIRECT_ANON
:
1711 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1712 throw new PermissionsError( 'upload' );
1714 case self
::AS_READ_ONLY_PAGE_ANON
:
1715 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1716 throw new PermissionsError( 'edit' );
1718 case self
::AS_READ_ONLY_PAGE
:
1719 throw new ReadOnlyError
;
1721 case self
::AS_RATE_LIMITED
:
1722 throw new ThrottledError();
1724 case self
::AS_NO_CREATE_PERMISSION
:
1725 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1726 throw new PermissionsError( $permission );
1728 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1729 throw new PermissionsError( 'editcontentmodel' );
1732 // We don't recognize $status->value. The only way that can happen
1733 // is if an extension hook aborted from inside ArticleSave.
1734 // Render the status object into $this->hookError
1735 // FIXME this sucks, we should just use the Status object throughout
1736 $this->hookError
= '<div class="error">' . "\n" . $status->getWikiText() .
1743 * Run hooks that can filter edits just before they get saved.
1745 * @param Content $content The Content to filter.
1746 * @param Status $status For reporting the outcome to the caller
1747 * @param User $user The user performing the edit
1751 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1752 // Run old style post-section-merge edit filter
1753 if ( $this->hookError
!= '' ) {
1754 # ...or the hook could be expecting us to produce an error
1755 $status->fatal( 'hookaborted' );
1756 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1760 // Run new style post-section-merge edit filter
1761 if ( !Hooks
::run( 'EditFilterMergedContent',
1762 [ $this->context
, $content, $status, $this->summary
,
1763 $user, $this->minoredit
] )
1765 # Error messages etc. could be handled within the hook...
1766 if ( $status->isGood() ) {
1767 $status->fatal( 'hookaborted' );
1768 // Not setting $this->hookError here is a hack to allow the hook
1769 // to cause a return to the edit page without $this->hookError
1770 // being set. This is used by ConfirmEdit to display a captcha
1771 // without any error message cruft.
1773 $this->hookError
= $this->formatStatusErrors( $status );
1775 // Use the existing $status->value if the hook set it
1776 if ( !$status->value
) {
1777 $status->value
= self
::AS_HOOK_ERROR
;
1780 } elseif ( !$status->isOK() ) {
1781 # ...or the hook could be expecting us to produce an error
1782 // FIXME this sucks, we should just use the Status object throughout
1783 $this->hookError
= $this->formatStatusErrors( $status );
1784 $status->fatal( 'hookaborted' );
1785 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1793 * Wrap status errors in an errorbox for increased visibility
1795 * @param Status $status
1796 * @return string Wikitext
1798 private function formatStatusErrors( Status
$status ) {
1799 $errmsg = $status->getWikiText(
1802 $this->context
->getLanguage()
1805 <div class="errorbox">
1813 * Return the summary to be used for a new section.
1815 * @param string $sectionanchor Set to the section anchor text
1818 private function newSectionSummary( &$sectionanchor = null ) {
1821 if ( $this->sectiontitle
!== '' ) {
1822 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1823 // If no edit summary was specified, create one automatically from the section
1824 // title and have it link to the new section. Otherwise, respect the summary as
1826 if ( $this->summary
=== '' ) {
1827 $cleanSectionTitle = $wgParser->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 = $wgParser->stripSectionName( $this->summary
);
1836 return $this->context
->msg( 'newsectionsummary' )
1837 ->plaintextParams( $cleanSummary )->inContentLanguage()->text();
1839 return $this->summary
;
1843 * Attempt submission (no UI)
1845 * @param array &$result Array to add statuses to, currently with the
1847 * - spam (string): Spam string from content if any spam is detected by
1849 * - sectionanchor (string): Section anchor for a section save.
1850 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1852 * - redirect (bool): Set if doEditContent is OK. True if resulting
1853 * revision is a redirect.
1854 * @param bool $bot True if edit is being made under the bot right.
1856 * @return Status Status object, possibly with a message, but always with
1857 * one of the AS_* constants in $status->value,
1859 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1860 * various error display idiosyncrasies. There are also lots of cases
1861 * where error metadata is set in the object and retrieved later instead
1862 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1863 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1866 public function internalAttemptSave( &$result, $bot = false ) {
1867 $status = Status
::newGood();
1868 $user = $this->context
->getUser();
1870 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1871 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1872 $status->fatal( 'hookaborted' );
1873 $status->value
= self
::AS_HOOK_ERROR
;
1877 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1878 $status->fatal( 'unicode-support-fail' );
1879 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1883 $request = $this->context
->getRequest();
1884 $spam = $request->getText( 'wpAntispam' );
1885 if ( $spam !== '' ) {
1890 $this->mTitle
->getPrefixedText() .
1891 '" submitted bogus field "' .
1895 $status->fatal( 'spamprotectionmatch', false );
1896 $status->value
= self
::AS_SPAM_ERROR
;
1901 # Construct Content object
1902 $textbox_content = $this->toEditContent( $this->textbox1
);
1903 } catch ( MWContentSerializationException
$ex ) {
1905 'content-failed-to-parse',
1906 $this->contentModel
,
1907 $this->contentFormat
,
1910 $status->value
= self
::AS_PARSE_ERROR
;
1914 # Check image redirect
1915 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1916 $textbox_content->isRedirect() &&
1917 !$user->isAllowed( 'upload' )
1919 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1920 $status->setResult( false, $code );
1926 $match = self
::matchSummarySpamRegex( $this->summary
);
1927 if ( $match === false && $this->section
== 'new' ) {
1928 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1929 # regular summaries, it is added to the actual wikitext.
1930 if ( $this->sectiontitle
!== '' ) {
1931 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1932 $match = self
::matchSpamRegex( $this->sectiontitle
);
1934 # This branch is taken when the "Add Topic" user interface is used, or the API
1935 # is used with the 'summary' parameter.
1936 $match = self
::matchSpamRegex( $this->summary
);
1939 if ( $match === false ) {
1940 $match = self
::matchSpamRegex( $this->textbox1
);
1942 if ( $match !== false ) {
1943 $result['spam'] = $match;
1944 $ip = $request->getIP();
1945 $pdbk = $this->mTitle
->getPrefixedDBkey();
1946 $match = str_replace( "\n", '', $match );
1947 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1948 $status->fatal( 'spamprotectionmatch', $match );
1949 $status->value
= self
::AS_SPAM_ERROR
;
1954 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1956 # Error messages etc. could be handled within the hook...
1957 $status->fatal( 'hookaborted' );
1958 $status->value
= self
::AS_HOOK_ERROR
;
1960 } elseif ( $this->hookError
!= '' ) {
1961 # ...or the hook could be expecting us to produce an error
1962 $status->fatal( 'hookaborted' );
1963 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1967 if ( $user->isBlockedFrom( $this->mTitle
) ) {
1968 // Auto-block user's IP if the account was "hard" blocked
1969 if ( !wfReadOnly() ) {
1970 $user->spreadAnyEditBlock();
1972 # Check block state against master, thus 'false'.
1973 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1977 $this->contentLength
= strlen( $this->textbox1
);
1978 $config = $this->context
->getConfig();
1979 $maxArticleSize = $config->get( 'MaxArticleSize' );
1980 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1981 // Error will be displayed by showEditForm()
1982 $this->tooBig
= true;
1983 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1987 if ( !$user->isAllowed( 'edit' ) ) {
1988 if ( $user->isAnon() ) {
1989 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1992 $status->fatal( 'readonlytext' );
1993 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1998 $changingContentModel = false;
1999 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
2000 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
2001 $status->fatal( 'editpage-cannot-use-custom-model' );
2002 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
2004 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
2005 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2008 // Make sure the user can edit the page under the new content model too
2009 $titleWithNewContentModel = clone $this->mTitle
;
2010 $titleWithNewContentModel->setContentModel( $this->contentModel
);
2011 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
2012 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
2014 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2018 $changingContentModel = true;
2019 $oldContentModel = $this->mTitle
->getContentModel();
2022 if ( $this->changeTags
) {
2023 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
2024 $this->changeTags
, $user );
2025 if ( !$changeTagsStatus->isOK() ) {
2026 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
2027 return $changeTagsStatus;
2031 if ( wfReadOnly() ) {
2032 $status->fatal( 'readonlytext' );
2033 $status->value
= self
::AS_READ_ONLY_PAGE
;
2036 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
2037 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
2039 $status->fatal( 'actionthrottledtext' );
2040 $status->value
= self
::AS_RATE_LIMITED
;
2044 # If the article has been deleted while editing, don't save it without
2046 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
2047 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
2051 # Load the page data from the master. If anything changes in the meantime,
2052 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
2053 $this->page
->loadPageData( 'fromdbmaster' );
2054 $new = !$this->page
->exists();
2057 // Late check for create permission, just in case *PARANOIA*
2058 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
2059 $status->fatal( 'nocreatetext' );
2060 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
2061 wfDebug( __METHOD__
. ": no create permission\n" );
2065 // Don't save a new page if it's blank or if it's a MediaWiki:
2066 // message with content equivalent to default (allow empty pages
2067 // in this case to disable messages, see T52124)
2068 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2069 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
2070 $defaultText = $defaultMessageText;
2075 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
2076 $this->blankArticle
= true;
2077 $status->fatal( 'blankarticle' );
2078 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
2082 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2086 $content = $textbox_content;
2088 $result['sectionanchor'] = '';
2089 if ( $this->section
== 'new' ) {
2090 if ( $this->sectiontitle
!== '' ) {
2091 // Insert the section title above the content.
2092 $content = $content->addSectionHeader( $this->sectiontitle
);
2093 } elseif ( $this->summary
!== '' ) {
2094 // Insert the section title above the content.
2095 $content = $content->addSectionHeader( $this->summary
);
2097 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2100 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2104 # Article exists. Check for edit conflict.
2106 $this->page
->clear(); # Force reload of dates, etc.
2107 $timestamp = $this->page
->getTimestamp();
2108 $latest = $this->page
->getLatest();
2110 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2112 // An edit conflict is detected if the current revision is different from the
2113 // revision that was current when editing was initiated on the client.
2114 // This is checked based on the timestamp and revision ID.
2115 // TODO: the timestamp based check can probably go away now.
2116 if ( $timestamp != $this->edittime
2117 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2119 $this->isConflict
= true;
2120 if ( $this->section
== 'new' ) {
2121 if ( $this->page
->getUserText() == $user->getName() &&
2122 $this->page
->getComment() == $this->newSectionSummary()
2124 // Probably a duplicate submission of a new comment.
2125 // This can happen when CDN resends a request after
2126 // a timeout but the first one actually went through.
2128 . ": duplicate new section submission; trigger edit conflict!\n" );
2130 // New comment; suppress conflict.
2131 $this->isConflict
= false;
2132 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2134 } elseif ( $this->section
== ''
2135 && Revision
::userWasLastToEdit(
2136 DB_MASTER
, $this->mTitle
->getArticleID(),
2137 $user->getId(), $this->edittime
2140 # Suppress edit conflict with self, except for section edits where merging is required.
2141 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2142 $this->isConflict
= false;
2146 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2147 if ( $this->sectiontitle
!== '' ) {
2148 $sectionTitle = $this->sectiontitle
;
2150 $sectionTitle = $this->summary
;
2155 if ( $this->isConflict
) {
2157 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2158 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2159 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2160 // ...or disable section editing for non-current revisions (not exposed anyway).
2161 if ( $this->editRevId
!== null ) {
2162 $content = $this->page
->replaceSectionAtRev(
2169 $content = $this->page
->replaceSectionContent(
2177 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2178 $content = $this->page
->replaceSectionContent(
2185 if ( is_null( $content ) ) {
2186 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2187 $this->isConflict
= true;
2188 $content = $textbox_content; // do not try to merge here!
2189 } elseif ( $this->isConflict
) {
2191 if ( $this->mergeChangesIntoContent( $content ) ) {
2192 // Successful merge! Maybe we should tell the user the good news?
2193 $this->isConflict
= false;
2194 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2196 $this->section
= '';
2197 $this->textbox1
= ContentHandler
::getContentText( $content );
2198 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2202 if ( $this->isConflict
) {
2203 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2207 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2211 if ( $this->section
== 'new' ) {
2212 // Handle the user preference to force summaries here
2213 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2214 $this->missingSummary
= true;
2215 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2216 $status->value
= self
::AS_SUMMARY_NEEDED
;
2220 // Do not allow the user to post an empty comment
2221 if ( $this->textbox1
== '' ) {
2222 $this->missingComment
= true;
2223 $status->fatal( 'missingcommenttext' );
2224 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2227 } elseif ( !$this->allowBlankSummary
2228 && !$content->equals( $this->getOriginalContent( $user ) )
2229 && !$content->isRedirect()
2230 && md5( $this->summary
) == $this->autoSumm
2232 $this->missingSummary
= true;
2233 $status->fatal( 'missingsummary' );
2234 $status->value
= self
::AS_SUMMARY_NEEDED
;
2239 $sectionanchor = '';
2240 if ( $this->section
== 'new' ) {
2241 $this->summary
= $this->newSectionSummary( $sectionanchor );
2242 } elseif ( $this->section
!= '' ) {
2243 # Try to get a section anchor from the section source, redirect
2244 # to edited section if header found.
2245 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2246 # for duplicate heading checking and maybe parsing.
2247 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2248 # We can't deal with anchors, includes, html etc in the header for now,
2249 # headline would need to be parsed to improve this.
2250 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2251 $sectionanchor = $this->guessSectionName( $matches[2] );
2254 $result['sectionanchor'] = $sectionanchor;
2256 // Save errors may fall down to the edit form, but we've now
2257 // merged the section into full text. Clear the section field
2258 // so that later submission of conflict forms won't try to
2259 // replace that into a duplicated mess.
2260 $this->textbox1
= $this->toEditText( $content );
2261 $this->section
= '';
2263 $status->value
= self
::AS_SUCCESS_UPDATE
;
2266 if ( !$this->allowSelfRedirect
2267 && $content->isRedirect()
2268 && $content->getRedirectTarget()->equals( $this->getTitle() )
2270 // If the page already redirects to itself, don't warn.
2271 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2272 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2273 $this->selfRedirect
= true;
2274 $status->fatal( 'selfredirect' );
2275 $status->value
= self
::AS_SELF_REDIRECT
;
2280 // Check for length errors again now that the section is merged in
2281 $this->contentLength
= strlen( $this->toEditText( $content ) );
2282 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2283 $this->tooBig
= true;
2284 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2288 $flags = EDIT_AUTOSUMMARY |
2289 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2290 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2291 ( $bot ? EDIT_FORCE_BOT
: 0 );
2293 $doEditStatus = $this->page
->doEditContent(
2299 $content->getDefaultFormat(),
2304 if ( !$doEditStatus->isOK() ) {
2305 // Failure from doEdit()
2306 // Show the edit conflict page for certain recognized errors from doEdit(),
2307 // but don't show it for errors from extension hooks
2308 $errors = $doEditStatus->getErrorsArray();
2309 if ( in_array( $errors[0][0],
2310 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2312 $this->isConflict
= true;
2313 // Destroys data doEdit() put in $status->value but who cares
2314 $doEditStatus->value
= self
::AS_END
;
2316 return $doEditStatus;
2319 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2320 if ( $result['nullEdit'] ) {
2321 // We don't know if it was a null edit until now, so increment here
2322 $user->pingLimiter( 'linkpurge' );
2324 $result['redirect'] = $content->isRedirect();
2326 $this->updateWatchlist();
2328 // If the content model changed, add a log entry
2329 if ( $changingContentModel ) {
2330 $this->addContentModelChangeLogEntry(
2332 $new ?
false : $oldContentModel,
2333 $this->contentModel
,
2343 * @param string|false $oldModel false if the page is being newly created
2344 * @param string $newModel
2345 * @param string $reason
2347 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2348 $new = $oldModel === false;
2349 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2350 $log->setPerformer( $user );
2351 $log->setTarget( $this->mTitle
);
2352 $log->setComment( $reason );
2353 $log->setParameters( [
2354 '4::oldmodel' => $oldModel,
2355 '5::newmodel' => $newModel
2357 $logid = $log->insert();
2358 $log->publish( $logid );
2362 * Register the change of watch status
2364 protected function updateWatchlist() {
2365 $user = $this->context
->getUser();
2366 if ( !$user->isLoggedIn() ) {
2370 $title = $this->mTitle
;
2371 $watch = $this->watchthis
;
2372 // Do this in its own transaction to reduce contention...
2373 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2374 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2375 return; // nothing to change
2377 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2382 * Attempts to do 3-way merge of edit content with a base revision
2383 * and current content, in case of edit conflict, in whichever way appropriate
2384 * for the content type.
2388 * @param Content $editContent
2392 private function mergeChangesIntoContent( &$editContent ) {
2393 $db = wfGetDB( DB_MASTER
);
2395 // This is the revision that was current at the time editing was initiated on the client,
2396 // even if the edit was based on an old revision.
2397 $baseRevision = $this->getBaseRevision();
2398 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2400 if ( is_null( $baseContent ) ) {
2404 // The current state, we want to merge updates into it
2405 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2406 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2408 if ( is_null( $currentContent ) ) {
2412 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2414 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2417 $editContent = $result;
2418 // Update parentRevId to what we just merged.
2419 $this->parentRevId
= $currentRevision->getId();
2427 * Returns the revision that was current at the time editing was initiated on the client,
2428 * even if the edit was based on an old revision.
2430 * @warning this method is very poorly named. If the user opened the form with ?oldid=X,
2431 * one might think of X as the "base revision", which is NOT what this returns,
2432 * see oldid for that. One might further assume that this corresponds to the $baseRevId
2433 * parameter of WikiPage::doEditContent, which is not the case either.
2434 * getExpectedParentRevision() would perhaps be a better name.
2436 * @return Revision|null Current version when editing was initiated on the client
2438 public function getBaseRevision() {
2439 if ( !$this->mBaseRevision
) {
2440 $db = wfGetDB( DB_MASTER
);
2441 $this->mBaseRevision
= $this->editRevId
2442 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2443 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2445 return $this->mBaseRevision
;
2449 * Check given input text against $wgSpamRegex, and return the text of the first match.
2451 * @param string $text
2453 * @return string|bool Matching string or false
2455 public static function matchSpamRegex( $text ) {
2456 global $wgSpamRegex;
2457 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2458 $regexes = (array)$wgSpamRegex;
2459 return self
::matchSpamRegexInternal( $text, $regexes );
2463 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2465 * @param string $text
2467 * @return string|bool Matching string or false
2469 public static function matchSummarySpamRegex( $text ) {
2470 global $wgSummarySpamRegex;
2471 $regexes = (array)$wgSummarySpamRegex;
2472 return self
::matchSpamRegexInternal( $text, $regexes );
2476 * @param string $text
2477 * @param array $regexes
2478 * @return bool|string
2480 protected static function matchSpamRegexInternal( $text, $regexes ) {
2481 foreach ( $regexes as $regex ) {
2483 if ( preg_match( $regex, $text, $matches ) ) {
2490 public function setHeaders() {
2491 $out = $this->context
->getOutput();
2493 $out->addModules( 'mediawiki.action.edit' );
2494 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2495 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2497 $user = $this->context
->getUser();
2499 if ( $user->getOption( 'uselivepreview' ) ) {
2500 $out->addModules( 'mediawiki.action.edit.preview' );
2503 if ( $user->getOption( 'useeditwarning' ) ) {
2504 $out->addModules( 'mediawiki.action.edit.editWarning' );
2507 # Enabled article-related sidebar, toplinks, etc.
2508 $out->setArticleRelated( true );
2510 $contextTitle = $this->getContextTitle();
2511 if ( $this->isConflict
) {
2512 $msg = 'editconflict';
2513 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2514 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2516 $msg = $contextTitle->exists()
2517 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2518 && $contextTitle->getDefaultMessageText() !== false
2524 # Use the title defined by DISPLAYTITLE magic word when present
2525 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2526 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2527 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2528 if ( $displayTitle === false ) {
2529 $displayTitle = $contextTitle->getPrefixedText();
2531 $out->setDisplayTitle( $displayTitle );
2533 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2535 $config = $this->context
->getConfig();
2537 # Transmit the name of the message to JavaScript for live preview
2538 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2539 $out->addJsConfigVars( [
2540 'wgEditMessage' => $msg,
2541 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2544 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2546 $out->addJsConfigVars(
2547 'wgEditSubmitButtonLabelPublish',
2548 $config->get( 'EditSubmitButtonLabelPublish' )
2553 * Show all applicable editing introductions
2555 protected function showIntro() {
2556 if ( $this->suppressIntro
) {
2560 $out = $this->context
->getOutput();
2561 $namespace = $this->mTitle
->getNamespace();
2563 if ( $namespace == NS_MEDIAWIKI
) {
2564 # Show a warning if editing an interface message
2565 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2566 # If this is a default message (but not css, json, or js),
2567 # show a hint that it is translatable on translatewiki.net
2569 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2570 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2571 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2573 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2574 if ( $defaultMessageText !== false ) {
2575 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2576 'translateinterface' );
2579 } elseif ( $namespace == NS_FILE
) {
2580 # Show a hint to shared repo
2581 $file = wfFindFile( $this->mTitle
);
2582 if ( $file && !$file->isLocal() ) {
2583 $descUrl = $file->getDescriptionUrl();
2584 # there must be a description url to show a hint to shared repo
2586 if ( !$this->mTitle
->exists() ) {
2587 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2588 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2591 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2592 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2599 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2600 # Show log extract when the user is currently blocked
2601 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2602 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2603 $user = User
::newFromName( $username, false /* allow IP users */ );
2604 $ip = User
::isIP( $username );
2605 $block = Block
::newFromTarget( $user, $user );
2606 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2607 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2608 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2610 !is_null( $block ) &&
2611 $block->getType() != Block
::TYPE_AUTO
&&
2612 ( $block->isSitewide() ||
$user->isBlockedFrom( $this->mTitle
) )
2614 // Show log extract if the user is sitewide blocked or is partially
2615 // blocked and not allowed to edit their user page or user talk page
2616 LogEventsList
::showLogExtract(
2619 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2623 'showIfEmpty' => false,
2625 'blocked-notice-logextract',
2626 $user->getName() # Support GENDER in notice
2632 # Try to add a custom edit intro, or use the standard one if this is not possible.
2633 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2634 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2635 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2637 if ( $this->context
->getUser()->isLoggedIn() ) {
2639 // Suppress the external link icon, consider the help url an internal one
2640 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2648 // Suppress the external link icon, consider the help url an internal one
2649 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2651 'newarticletextanon',
2657 # Give a notice if the user is editing a deleted/moved page...
2658 if ( !$this->mTitle
->exists() ) {
2659 $dbr = wfGetDB( DB_REPLICA
);
2661 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2665 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2666 'showIfEmpty' => false,
2667 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2674 * Attempt to show a custom editing introduction, if supplied
2678 protected function showCustomIntro() {
2679 if ( $this->editintro
) {
2680 $title = Title
::newFromText( $this->editintro
);
2681 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2682 // Added using template syntax, to take <noinclude>'s into account.
2683 $this->context
->getOutput()->addWikiTextAsContent(
2684 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2695 * Gets an editable textual representation of $content.
2696 * The textual representation can be turned by into a Content object by the
2697 * toEditContent() method.
2699 * If $content is null or false or a string, $content is returned unchanged.
2701 * If the given Content object is not of a type that can be edited using
2702 * the text base EditPage, an exception will be raised. Set
2703 * $this->allowNonTextContent to true to allow editing of non-textual
2706 * @param Content|null|bool|string $content
2707 * @return string The editable text form of the content.
2709 * @throws MWException If $content is not an instance of TextContent and
2710 * $this->allowNonTextContent is not true.
2712 protected function toEditText( $content ) {
2713 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2717 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2718 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2721 return $content->serialize( $this->contentFormat
);
2725 * Turns the given text into a Content object by unserializing it.
2727 * If the resulting Content object is not of a type that can be edited using
2728 * the text base EditPage, an exception will be raised. Set
2729 * $this->allowNonTextContent to true to allow editing of non-textual
2732 * @param string|null|bool $text Text to unserialize
2733 * @return Content|bool|null The content object created from $text. If $text was false
2734 * or null, then false or null will be returned instead.
2736 * @throws MWException If unserializing the text results in a Content
2737 * object that is not an instance of TextContent and
2738 * $this->allowNonTextContent is not true.
2740 protected function toEditContent( $text ) {
2741 if ( $text === false ||
$text === null ) {
2745 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2746 $this->contentModel
, $this->contentFormat
);
2748 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2749 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2756 * Send the edit form and related headers to OutputPage
2757 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2758 * during form output near the top, for captchas and the like.
2760 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2761 * use the EditPage::showEditForm:fields hook instead.
2763 public function showEditForm( $formCallback = null ) {
2764 # need to parse the preview early so that we know which templates are used,
2765 # otherwise users with "show preview after edit box" will get a blank list
2766 # we parse this near the beginning so that setHeaders can do the title
2767 # setting work instead of leaving it in getPreviewText
2768 $previewOutput = '';
2769 if ( $this->formtype
== 'preview' ) {
2770 $previewOutput = $this->getPreviewText();
2773 $out = $this->context
->getOutput();
2775 // Avoid PHP 7.1 warning of passing $this by reference
2777 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2779 $this->setHeaders();
2781 $this->addTalkPageText();
2782 $this->addEditNotices();
2784 if ( !$this->isConflict
&&
2785 $this->section
!= '' &&
2786 !$this->isSectionEditSupported() ) {
2787 // We use $this->section to much before this and getVal('wgSection') directly in other places
2788 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2789 // Someone is welcome to try refactoring though
2790 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2794 $this->showHeader();
2796 $out->addHTML( $this->editFormPageTop
);
2798 $user = $this->context
->getUser();
2799 if ( $user->getOption( 'previewontop' ) ) {
2800 $this->displayPreviewArea( $previewOutput, true );
2803 $out->addHTML( $this->editFormTextTop
);
2805 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
!== 'save' ) {
2806 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2807 'deletedwhileediting' );
2810 // @todo add EditForm plugin interface and use it here!
2811 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2812 $out->addHTML( Html
::openElement(
2815 'class' => 'mw-editform',
2816 'id' => self
::EDITFORM_ID
,
2817 'name' => self
::EDITFORM_ID
,
2819 'action' => $this->getActionURL( $this->getContextTitle() ),
2820 'enctype' => 'multipart/form-data'
2824 if ( is_callable( $formCallback ) ) {
2825 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2826 call_user_func_array( $formCallback, [ &$out ] );
2829 // Add a check for Unicode support
2830 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2832 // Add an empty field to trip up spambots
2834 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2837 [ 'for' => 'wpAntispam' ],
2838 $this->context
->msg( 'simpleantispam-label' )->parse()
2844 'name' => 'wpAntispam',
2845 'id' => 'wpAntispam',
2849 . Xml
::closeElement( 'div' )
2852 // Avoid PHP 7.1 warning of passing $this by reference
2854 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2856 // Put these up at the top to ensure they aren't lost on early form submission
2857 $this->showFormBeforeText();
2859 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2860 $username = $this->lastDelete
->user_name
;
2861 $comment = CommentStore
::getStore()
2862 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2864 // It is better to not parse the comment at all than to have templates expanded in the middle
2865 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2866 $key = $comment === ''
2867 ?
'confirmrecreate-noreason'
2868 : 'confirmrecreate';
2870 '<div class="mw-confirm-recreate">' .
2871 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2872 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2873 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2879 # When the summary is hidden, also hide them on preview/show changes
2880 if ( $this->nosummary
) {
2881 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2884 # If a blank edit summary was previously provided, and the appropriate
2885 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2886 # user being bounced back more than once in the event that a summary
2889 # For a bit more sophisticated detection of blank summaries, hash the
2890 # automatic one and pass that in the hidden field wpAutoSummary.
2891 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2892 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2895 if ( $this->undidRev
) {
2896 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2899 if ( $this->selfRedirect
) {
2900 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2903 if ( $this->hasPresetSummary
) {
2904 // If a summary has been preset using &summary= we don't want to prompt for
2905 // a different summary. Only prompt for a summary if the summary is blanked.
2907 $this->autoSumm
= md5( '' );
2910 $autosumm = $this->autoSumm
!== '' ?
$this->autoSumm
: md5( $this->summary
);
2911 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2913 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2914 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2916 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2917 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2921 if ( $this->section
== 'new' ) {
2922 $this->showSummaryInput( true, $this->summary
);
2923 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2926 $out->addHTML( $this->editFormTextBeforeContent
);
2927 if ( $this->isConflict
) {
2928 // In an edit conflict, we turn textbox2 into the user's text,
2929 // and textbox1 into the stored version
2930 $this->textbox2
= $this->textbox1
;
2932 $content = $this->getCurrentContent();
2933 $this->textbox1
= $this->toEditText( $content );
2935 $editConflictHelper = $this->getEditConflictHelper();
2936 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2937 $editConflictHelper->setContentModel( $this->contentModel
);
2938 $editConflictHelper->setContentFormat( $this->contentFormat
);
2939 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2942 if ( !$this->mTitle
->isUserConfigPage() ) {
2943 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2946 if ( $this->blankArticle
) {
2947 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2950 if ( $this->isConflict
) {
2951 // In an edit conflict bypass the overridable content form method
2952 // and fallback to the raw wpTextbox1 since editconflicts can't be
2953 // resolved between page source edits and custom ui edits using the
2955 $conflictTextBoxAttribs = [];
2956 if ( $this->wasDeletedSinceLastEdit() ) {
2957 $conflictTextBoxAttribs['style'] = 'display:none;';
2958 } elseif ( $this->isOldRev
) {
2959 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2962 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2963 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2965 $this->showContentForm();
2968 $out->addHTML( $this->editFormTextAfterContent
);
2970 $this->showStandardInputs();
2972 $this->showFormAfterText();
2974 $this->showTosSummary();
2976 $this->showEditTools();
2978 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2980 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2982 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2983 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2985 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2986 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2988 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2990 if ( $this->isConflict
) {
2992 $this->showConflict();
2993 } catch ( MWContentSerializationException
$ex ) {
2994 // this can't really happen, but be nice if it does.
2995 $msg = $this->context
->msg(
2996 'content-failed-to-parse',
2997 $this->contentModel
,
2998 $this->contentFormat
,
3001 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3005 // Set a hidden field so JS knows what edit form mode we are in
3006 if ( $this->isConflict
) {
3008 } elseif ( $this->preview
) {
3010 } elseif ( $this->diff
) {
3015 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
3017 // Marker for detecting truncated form data. This must be the last
3018 // parameter sent in order to be of use, so do not move me.
3019 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
3020 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
3022 if ( !$user->getOption( 'previewontop' ) ) {
3023 $this->displayPreviewArea( $previewOutput, false );
3028 * Wrapper around TemplatesOnThisPageFormatter to make
3029 * a "templates on this page" list.
3031 * @param Title[] $templates
3032 * @return string HTML
3034 public function makeTemplatesOnThisPageList( array $templates ) {
3035 $templateListFormatter = new TemplatesOnThisPageFormatter(
3036 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
3039 // preview if preview, else section if section, else false
3041 if ( $this->preview
) {
3043 } elseif ( $this->section
!= '' ) {
3047 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
3048 $templateListFormatter->format( $templates, $type )
3053 * Extract the section title from current section text, if any.
3055 * @param string $text
3056 * @return string|bool String or false
3058 public static function extractSectionTitle( $text ) {
3059 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
3060 if ( !empty( $matches[2] ) ) {
3062 return $wgParser->stripSectionName( trim( $matches[2] ) );
3068 protected function showHeader() {
3069 $out = $this->context
->getOutput();
3070 $user = $this->context
->getUser();
3071 if ( $this->isConflict
) {
3072 $this->addExplainConflictHeader( $out );
3073 $this->editRevId
= $this->page
->getLatest();
3075 if ( $this->section
!= '' && $this->section
!= 'new' && !$this->summary
&&
3076 !$this->preview
&& !$this->diff
3078 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
3079 if ( $sectionTitle !== false ) {
3080 $this->summary
= "/* $sectionTitle */ ";
3084 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
3086 if ( $this->missingComment
) {
3087 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3090 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
3092 "<div id='mw-missingsummary'>\n$1\n</div>",
3093 [ 'missingsummary', $buttonLabel ]
3097 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3099 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3100 [ 'missingcommentheader', $buttonLabel ]
3104 if ( $this->blankArticle
) {
3106 "<div id='mw-blankarticle'>\n$1\n</div>",
3107 [ 'blankarticle', $buttonLabel ]
3111 if ( $this->selfRedirect
) {
3113 "<div id='mw-selfredirect'>\n$1\n</div>",
3114 [ 'selfredirect', $buttonLabel ]
3118 if ( $this->hookError
!== '' ) {
3119 $out->addWikiTextAsInterface( $this->hookError
);
3122 if ( $this->section
!= 'new' ) {
3123 $revision = $this->mArticle
->getRevisionFetched();
3125 // Let sysop know that this will make private content public if saved
3127 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3129 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3130 'rev-deleted-text-permission'
3132 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3134 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3135 'rev-deleted-text-view'
3139 if ( !$revision->isCurrent() ) {
3140 $this->mArticle
->setOldSubtitle( $revision->getId() );
3142 Html
::warningBox( "\n$1\n" ),
3145 $this->isOldRev
= true;
3147 } elseif ( $this->mTitle
->exists() ) {
3148 // Something went wrong
3150 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3151 [ 'missing-revision', $this->oldid
] );
3156 if ( wfReadOnly() ) {
3158 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3159 [ 'readonlywarning', wfReadOnlyReason() ]
3161 } elseif ( $user->isAnon() ) {
3162 if ( $this->formtype
!= 'preview' ) {
3163 $returntoquery = array_diff_key(
3164 $this->context
->getRequest()->getValues(),
3165 [ 'title' => true, 'returnto' => true, 'returntoquery' => true ]
3168 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3169 [ 'anoneditwarning',
3171 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3172 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3173 'returntoquery' => wfArrayToCgi( $returntoquery ),
3176 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3177 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3178 'returntoquery' => wfArrayToCgi( $returntoquery ),
3183 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3184 'anonpreviewwarning'
3187 } elseif ( $this->mTitle
->isUserConfigPage() ) {
3188 # Check the skin exists
3189 if ( $this->isWrongCaseUserConfigPage() ) {
3191 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3192 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3195 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3196 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3197 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3198 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3200 $warning = $isUserCssConfig
3202 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3204 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3206 if ( $this->formtype
!== 'preview' ) {
3207 $config = $this->context
->getConfig();
3208 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3210 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3211 [ 'usercssyoucanpreview' ]
3213 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3215 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3216 [ 'userjsonyoucanpreview' ]
3218 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3220 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3221 [ 'userjsyoucanpreview' ]
3228 $this->addPageProtectionWarningHeaders();
3230 $this->addLongPageWarningHeader();
3232 # Add header copyright warning
3233 $this->showHeaderCopyrightWarning();
3237 * Helper function for summary input functions, which returns the necessary
3238 * attributes for the input.
3240 * @param array|null $inputAttrs Array of attrs to use on the input
3243 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3244 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3245 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3246 // Unicode codepoints.
3247 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3248 'id' => 'wpSummary',
3249 'name' => 'wpSummary',
3250 'maxlength' => CommentStore
::COMMENT_CHARACTER_LIMIT
,
3253 'spellcheck' => 'true',
3258 * Builds a standard summary input with a label.
3260 * @param string $summary The value of the summary input
3261 * @param string|null $labelText The html to place inside the label
3262 * @param array|null $inputAttrs Array of attrs to use on the input
3264 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3266 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3267 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3268 $this->getSummaryInputAttributes( $inputAttrs )
3271 'title' => Linker
::titleAttrib( 'summary' ),
3272 'accessKey' => Linker
::accesskey( 'summary' ),
3275 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3276 $inputAttrs['inputId'] = $inputAttrs['id'];
3277 $inputAttrs['id'] = 'wpSummaryWidget';
3279 return new OOUI\
FieldLayout(
3280 new OOUI\
TextInputWidget( [
3281 'value' => $summary,
3282 'infusable' => true,
3285 'label' => new OOUI\
HtmlSnippet( $labelText ),
3287 'id' => 'wpSummaryLabel',
3288 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3294 * @param bool $isSubjectPreview True if this is the section subject/title
3295 * up top, or false if this is the comment summary
3296 * down below the textarea
3297 * @param string $summary The text of the summary to display
3299 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3300 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3301 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3302 if ( $isSubjectPreview ) {
3303 if ( $this->nosummary
) {
3306 } elseif ( !$this->mShowSummaryField
) {
3310 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3311 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3314 [ 'class' => $summaryClass ]
3319 * @param bool $isSubjectPreview True if this is the section subject/title
3320 * up top, or false if this is the comment summary
3321 * down below the textarea
3322 * @param string $summary The text of the summary to display
3325 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3326 // avoid spaces in preview, gets always trimmed on save
3327 $summary = trim( $summary );
3328 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3334 if ( $isSubjectPreview ) {
3335 $summary = $this->context
->msg( 'newsectionsummary' )
3336 ->rawParams( $wgParser->stripSectionName( $summary ) )
3337 ->inContentLanguage()->text();
3340 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3342 $summary = $this->context
->msg( $message )->parse()
3343 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3344 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3347 protected function showFormBeforeText() {
3348 $out = $this->context
->getOutput();
3349 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3350 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3351 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3352 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3353 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3356 protected function showFormAfterText() {
3358 * To make it harder for someone to slip a user a page
3359 * which submits an edit form to the wiki without their
3360 * knowledge, a random token is associated with the login
3361 * session. If it's not passed back with the submission,
3362 * we won't save the page, or render user JavaScript and
3365 * For anon editors, who may not have a session, we just
3366 * include the constant suffix to prevent editing from
3367 * broken text-mangling proxies.
3369 $this->context
->getOutput()->addHTML(
3371 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3377 * Subpage overridable method for printing the form for page content editing
3378 * By default this simply outputs wpTextbox1
3379 * Subclasses can override this to provide a custom UI for editing;
3380 * be it a form, or simply wpTextbox1 with a modified content that will be
3381 * reverse modified when extracted from the post data.
3382 * Note that this is basically the inverse for importContentFormData
3384 protected function showContentForm() {
3385 $this->showTextbox1();
3389 * Method to output wpTextbox1
3390 * The $textoverride method can be used by subclasses overriding showContentForm
3391 * to pass back to this method.
3393 * @param array|null $customAttribs Array of html attributes to use in the textarea
3394 * @param string|null $textoverride Optional text to override $this->textarea1 with
3396 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3397 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3398 $attribs = [ 'style' => 'display:none;' ];
3400 $builder = new TextboxBuilder();
3401 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3403 # Is an old revision being edited?
3404 if ( $this->isOldRev
) {
3405 $classes[] = 'mw-textarea-oldrev';
3408 $attribs = [ 'tabindex' => 1 ];
3410 if ( is_array( $customAttribs ) ) {
3411 $attribs +
= $customAttribs;
3414 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3418 $textoverride ??
$this->textbox1
,
3424 protected function showTextbox2() {
3425 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3428 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3429 $builder = new TextboxBuilder();
3430 $attribs = $builder->buildTextboxAttribs(
3433 $this->context
->getUser(),
3437 $this->context
->getOutput()->addHTML(
3438 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3442 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3445 $classes[] = 'ontop';
3448 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3450 if ( $this->formtype
!= 'preview' ) {
3451 $attribs['style'] = 'display: none;';
3454 $out = $this->context
->getOutput();
3455 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3457 if ( $this->formtype
== 'preview' ) {
3458 $this->showPreview( $previewOutput );
3460 // Empty content container for LivePreview
3461 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3462 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3463 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3464 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3467 $out->addHTML( '</div>' );
3469 if ( $this->formtype
== 'diff' ) {
3472 } catch ( MWContentSerializationException
$ex ) {
3473 $msg = $this->context
->msg(
3474 'content-failed-to-parse',
3475 $this->contentModel
,
3476 $this->contentFormat
,
3479 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3485 * Append preview output to OutputPage.
3486 * Includes category rendering if this is a category page.
3488 * @param string $text The HTML to be output for the preview.
3490 protected function showPreview( $text ) {
3491 if ( $this->mArticle
instanceof CategoryPage
) {
3492 $this->mArticle
->openShowCategory();
3494 # This hook seems slightly odd here, but makes things more
3495 # consistent for extensions.
3496 $out = $this->context
->getOutput();
3497 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3498 $out->addHTML( $text );
3499 if ( $this->mArticle
instanceof CategoryPage
) {
3500 $this->mArticle
->closeShowCategory();
3505 * Get a diff between the current contents of the edit box and the
3506 * version of the page we're editing from.
3508 * If this is a section edit, we'll replace the section as for final
3509 * save and then make a comparison.
3511 public function showDiff() {
3512 $oldtitlemsg = 'currentrev';
3513 # if message does not exist, show diff against the preloaded default
3514 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3515 $oldtext = $this->mTitle
->getDefaultMessageText();
3516 if ( $oldtext !== false ) {
3517 $oldtitlemsg = 'defaultmessagetext';
3518 $oldContent = $this->toEditContent( $oldtext );
3523 $oldContent = $this->getCurrentContent();
3526 $textboxContent = $this->toEditContent( $this->textbox1
);
3527 if ( $this->editRevId
!== null ) {
3528 $newContent = $this->page
->replaceSectionAtRev(
3529 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3532 $newContent = $this->page
->replaceSectionContent(
3533 $this->section
, $textboxContent, $this->summary
, $this->edittime
3537 if ( $newContent ) {
3538 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3540 $user = $this->context
->getUser();
3541 $popts = ParserOptions
::newFromUserAndLang( $user,
3542 MediaWikiServices
::getInstance()->getContentLanguage() );
3543 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3546 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3547 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3548 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3550 if ( !$oldContent ) {
3551 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3554 if ( !$newContent ) {
3555 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3558 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3559 $de->setContent( $oldContent, $newContent );
3561 $difftext = $de->getDiff( $oldtitle, $newtitle );
3562 $de->showDiffStyle();
3567 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3571 * Show the header copyright warning.
3573 protected function showHeaderCopyrightWarning() {
3574 $msg = 'editpage-head-copy-warn';
3575 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3576 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3577 'editpage-head-copy-warn' );
3582 * Give a chance for site and per-namespace customizations of
3583 * terms of service summary link that might exist separately
3584 * from the copyright notice.
3586 * This will display between the save button and the edit tools,
3587 * so should remain short!
3589 protected function showTosSummary() {
3590 $msg = 'editpage-tos-summary';
3591 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3592 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3593 $out = $this->context
->getOutput();
3594 $out->addHTML( '<div class="mw-tos-summary">' );
3595 $out->addWikiMsg( $msg );
3596 $out->addHTML( '</div>' );
3601 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3602 * characters not present on most keyboards for copying/pasting.
3604 protected function showEditTools() {
3605 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3606 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3611 * Get the copyright warning
3613 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3616 protected function getCopywarn() {
3617 return self
::getCopyrightWarning( $this->mTitle
);
3621 * Get the copyright warning, by default returns wikitext
3623 * @param Title $title
3624 * @param string $format Output format, valid values are any function of a Message object
3625 * @param Language|string|null $langcode Language code or Language object.
3628 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3629 global $wgRightsText;
3630 if ( $wgRightsText ) {
3631 $copywarnMsg = [ 'copyrightwarning',
3632 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3635 $copywarnMsg = [ 'copyrightwarning2',
3636 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3638 // Allow for site and per-namespace customization of contribution/copyright notice.
3639 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3641 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3643 $msg->inLanguage( $langcode );
3645 return "<div id=\"editpage-copywarn\">\n" .
3646 $msg->$format() . "\n</div>";
3650 * Get the Limit report for page previews
3653 * @param ParserOutput|null $output ParserOutput object from the parse
3654 * @return string HTML
3656 public static function getPreviewLimitReport( ParserOutput
$output = null ) {
3659 if ( !$output ||
!$output->getLimitReportData() ) {
3663 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3664 wfMessage( 'limitreport-title' )->parseAsBlock()
3667 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3668 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3670 $limitReport .= Html
::openElement( 'table', [
3671 'class' => 'preview-limit-report wikitable'
3673 Html
::openElement( 'tbody' );
3675 foreach ( $output->getLimitReportData() as $key => $value ) {
3676 if ( Hooks
::run( 'ParserLimitReportFormat',
3677 [ $key, &$value, &$limitReport, true, true ]
3679 $keyMsg = wfMessage( $key );
3680 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3681 if ( !$valueMsg->exists() ) {
3682 $valueMsg = new RawMessage( '$1' );
3684 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3685 $limitReport .= Html
::openElement( 'tr' ) .
3686 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3687 Html
::rawElement( 'td', null,
3688 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3690 Html
::closeElement( 'tr' );
3695 $limitReport .= Html
::closeElement( 'tbody' ) .
3696 Html
::closeElement( 'table' ) .
3697 Html
::closeElement( 'div' );
3699 return $limitReport;
3702 protected function showStandardInputs( &$tabindex = 2 ) {
3703 $out = $this->context
->getOutput();
3704 $out->addHTML( "<div class='editOptions'>\n" );
3706 if ( $this->section
!= 'new' ) {
3707 $this->showSummaryInput( false, $this->summary
);
3708 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3711 $checkboxes = $this->getCheckboxesWidget(
3713 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3715 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3717 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3719 // Show copyright warning.
3720 $out->addWikiTextAsInterface( $this->getCopywarn() );
3721 $out->addHTML( $this->editFormTextAfterWarn
);
3723 $out->addHTML( "<div class='editButtons'>\n" );
3724 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3726 $cancel = $this->getCancelLink();
3728 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3729 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3732 $this->context
->msg( 'edithelp' )->text(),
3733 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3736 $this->context
->msg( 'word-separator' )->escaped() .
3737 $this->context
->msg( 'newwindow' )->parse();
3739 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3740 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3741 $out->addHTML( "</div><!-- editButtons -->\n" );
3743 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3745 $out->addHTML( "</div><!-- editOptions -->\n" );
3749 * Show an edit conflict. textbox1 is already shown in showEditForm().
3750 * If you want to use another entry point to this function, be careful.
3752 protected function showConflict() {
3753 $out = $this->context
->getOutput();
3754 // Avoid PHP 7.1 warning of passing $this by reference
3756 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3757 $this->incrementConflictStats();
3759 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3763 protected function incrementConflictStats() {
3764 $this->getEditConflictHelper()->incrementConflictStats();
3770 public function getCancelLink() {
3772 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3773 $cancelParams['oldid'] = $this->oldid
;
3774 } elseif ( $this->getContextTitle()->isRedirect() ) {
3775 $cancelParams['redirect'] = 'no';
3778 return new OOUI\
ButtonWidget( [
3779 'id' => 'mw-editform-cancel',
3780 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3781 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3783 'infusable' => true,
3784 'flags' => 'destructive',
3789 * Returns the URL to use in the form's action attribute.
3790 * This is used by EditPage subclasses when simply customizing the action
3791 * variable in the constructor is not enough. This can be used when the
3792 * EditPage lives inside of a Special page rather than a custom page action.
3794 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3797 protected function getActionURL( Title
$title ) {
3798 return $title->getLocalURL( [ 'action' => $this->action
] );
3802 * Check if a page was deleted while the user was editing it, before submit.
3803 * Note that we rely on the logging table, which hasn't been always there,
3804 * but that doesn't matter, because this only applies to brand new
3808 protected function wasDeletedSinceLastEdit() {
3809 if ( $this->deletedSinceEdit
!== null ) {
3810 return $this->deletedSinceEdit
;
3813 $this->deletedSinceEdit
= false;
3815 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3816 $this->lastDelete
= $this->getLastDelete();
3817 if ( $this->lastDelete
) {
3818 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3819 if ( $deleteTime > $this->starttime
) {
3820 $this->deletedSinceEdit
= true;
3825 return $this->deletedSinceEdit
;
3829 * Get the last log record of this page being deleted, if ever. This is
3830 * used to detect whether a delete occurred during editing.
3831 * @return bool|stdClass
3833 protected function getLastDelete() {
3834 $dbr = wfGetDB( DB_REPLICA
);
3835 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3836 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3837 $data = $dbr->selectRow(
3838 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3848 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3850 'log_namespace' => $this->mTitle
->getNamespace(),
3851 'log_title' => $this->mTitle
->getDBkey(),
3852 'log_type' => 'delete',
3853 'log_action' => 'delete',
3856 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3858 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3859 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3861 // Quick paranoid permission checks...
3862 if ( is_object( $data ) ) {
3863 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3864 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3867 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3868 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3869 $data->log_comment_data
= null;
3877 * Get the rendered text for previewing.
3878 * @throws MWException
3881 public function getPreviewText() {
3882 $out = $this->context
->getOutput();
3883 $config = $this->context
->getConfig();
3885 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3886 // Could be an offsite preview attempt. This is very unsafe if
3887 // HTML is enabled, as it could be an attack.
3889 if ( $this->textbox1
!== '' ) {
3890 // Do not put big scary notice, if previewing the empty
3891 // string, which happens when you initially edit
3892 // a category page, due to automatic preview-on-open.
3893 $parsedNote = Html
::rawElement( 'div', [ 'class' => 'previewnote' ],
3894 $out->parseAsInterface(
3895 $this->context
->msg( 'session_fail_preview_html' )->plain()
3898 $this->incrementEditFailureStats( 'session_loss' );
3905 $content = $this->toEditContent( $this->textbox1
);
3909 'AlternateEditPreview',
3910 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3912 return $previewHTML;
3915 # provide a anchor link to the editform
3916 $continueEditing = '<span class="mw-continue-editing">' .
3917 '[[#' . self
::EDITFORM_ID
. '|' .
3918 $this->context
->getLanguage()->getArrow() . ' ' .
3919 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3920 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3921 if ( $this->mTokenOkExceptSuffix
) {
3922 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3923 $this->incrementEditFailureStats( 'bad_token' );
3925 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3926 $this->incrementEditFailureStats( 'session_loss' );
3928 } elseif ( $this->incompleteForm
) {
3929 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3930 if ( $this->mTriedSave
) {
3931 $this->incrementEditFailureStats( 'incomplete_form' );
3934 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3937 # don't parse non-wikitext pages, show message about preview
3938 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3939 if ( $this->mTitle
->isUserConfigPage() ) {
3941 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3947 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3949 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3952 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3954 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3957 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3959 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3966 # Used messages to make sure grep find them:
3967 # Messages: usercsspreview, userjsonpreview, userjspreview,
3968 # sitecsspreview, sitejsonpreview, sitejspreview
3969 if ( $level && $format ) {
3970 $note = "<div id='mw-{$level}{$format}preview'>" .
3971 $this->context
->msg( "{$level}{$format}preview" )->plain() .
3972 ' ' . $continueEditing . "</div>";
3976 # If we're adding a comment, we need to show the
3977 # summary as the headline
3978 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3979 $content = $content->addSectionHeader( $this->summary
);
3982 $hook_args = [ $this, &$content ];
3983 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3985 $parserResult = $this->doPreviewParse( $content );
3986 $parserOutput = $parserResult['parserOutput'];
3987 $previewHTML = $parserResult['html'];
3988 $this->mParserOutput
= $parserOutput;
3989 $out->addParserOutputMetadata( $parserOutput );
3990 if ( $out->userCanPreview() ) {
3991 $out->addContentOverride( $this->getTitle(), $content );
3994 if ( count( $parserOutput->getWarnings() ) ) {
3995 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3998 } catch ( MWContentSerializationException
$ex ) {
3999 $m = $this->context
->msg(
4000 'content-failed-to-parse',
4001 $this->contentModel
,
4002 $this->contentFormat
,
4005 $note .= "\n\n" . $m->plain(); # gets parsed down below
4009 if ( $this->isConflict
) {
4010 $conflict = Html
::rawElement(
4011 'h2', [ 'id' => 'mw-previewconflict' ],
4012 $this->context
->msg( 'previewconflict' )->escaped()
4015 $conflict = '<hr />';
4018 $previewhead = Html
::rawElement(
4019 'div', [ 'class' => 'previewnote' ],
4021 'h2', [ 'id' => 'mw-previewheader' ],
4022 $this->context
->msg( 'preview' )->escaped()
4024 $out->parseAsInterface( $note ) . $conflict
4027 $pageViewLang = $this->mTitle
->getPageViewLanguage();
4028 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
4029 'class' => 'mw-content-' . $pageViewLang->getDir() ];
4030 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
4032 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
4035 private function incrementEditFailureStats( $failureType ) {
4036 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
4037 $stats->increment( 'edit.failures.' . $failureType );
4041 * Get parser options for a preview
4042 * @return ParserOptions
4044 protected function getPreviewParserOptions() {
4045 $parserOptions = $this->page
->makeParserOptions( $this->context
);
4046 $parserOptions->setIsPreview( true );
4047 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
4048 $parserOptions->enableLimitReport();
4050 // XXX: we could call $parserOptions->setCurrentRevisionCallback here to force the
4051 // current revision to be null during PST, until setupFakeRevision is called on
4052 // the ParserOptions. Currently, we rely on Parser::getRevisionObject() to ignore
4053 // existing revisions in preview mode.
4055 return $parserOptions;
4059 * Parse the page for a preview. Subclasses may override this class, in order
4060 * to parse with different options, or to otherwise modify the preview HTML.
4062 * @param Content $content The page content
4063 * @return array with keys:
4064 * - parserOutput: The ParserOutput object
4065 * - html: The HTML to be displayed
4067 protected function doPreviewParse( Content
$content ) {
4068 $user = $this->context
->getUser();
4069 $parserOptions = $this->getPreviewParserOptions();
4071 // NOTE: preSaveTransform doesn't have a fake revision to operate on.
4072 // Parser::getRevisionObject() will return null in preview mode,
4073 // causing the context user to be used for {{subst:REVISIONUSER}}.
4074 // XXX: Alternatively, we could also call setupFakeRevision() a second time:
4075 // once before PST with $content, and then after PST with $pstContent.
4076 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
4077 $scopedCallback = $parserOptions->setupFakeRevision( $this->mTitle
, $pstContent, $user );
4078 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
4079 ScopedCallback
::consume( $scopedCallback );
4081 'parserOutput' => $parserOutput,
4082 'html' => $parserOutput->getText( [
4083 'enableSectionEditLinks' => false
4091 public function getTemplates() {
4092 if ( $this->preview ||
$this->section
!= '' ) {
4094 if ( !isset( $this->mParserOutput
) ) {
4097 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
4098 foreach ( array_keys( $template ) as $dbk ) {
4099 $templates[] = Title
::makeTitle( $ns, $dbk );
4104 return $this->mTitle
->getTemplateLinksFrom();
4109 * Allow extensions to provide a toolbar.
4111 * @param Title|null $title Title object for the page being edited (optional)
4112 * @return string|null
4114 public static function getEditToolbar( $title = null ) {
4115 $startingToolbar = '<div id="toolbar"></div>';
4116 $toolbar = $startingToolbar;
4118 if ( !Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4121 // Don't add a pointless `<div>` to the page unless a hook caller populated it
4122 return ( $toolbar === $startingToolbar ) ?
null : $toolbar;
4126 * Return an array of checkbox definitions.
4128 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4130 * Array values are associative arrays with the following keys:
4131 * - 'label-message' (required): message for label text
4132 * - 'id' (required): 'id' attribute for the `<input>`
4133 * - 'default' (required): default checkedness (true or false)
4134 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4135 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4136 * from messages like 'tooltip-foo', 'accesskey-foo'
4137 * - 'label-id' (optional): 'id' attribute for the `<label>`
4138 * - 'legacy-name' (optional): short name for backwards-compatibility
4139 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4140 * where bool indicates the checked status of the checkbox
4143 public function getCheckboxesDefinition( $checked ) {
4146 $user = $this->context
->getUser();
4147 // don't show the minor edit checkbox if it's a new page or section
4148 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4149 $checkboxes['wpMinoredit'] = [
4150 'id' => 'wpMinoredit',
4151 'label-message' => 'minoredit',
4152 // Uses messages: tooltip-minoredit, accesskey-minoredit
4153 'tooltip' => 'minoredit',
4154 'label-id' => 'mw-editpage-minoredit',
4155 'legacy-name' => 'minor',
4156 'default' => $checked['minor'],
4160 if ( $user->isLoggedIn() ) {
4161 $checkboxes['wpWatchthis'] = [
4162 'id' => 'wpWatchthis',
4163 'label-message' => 'watchthis',
4164 // Uses messages: tooltip-watch, accesskey-watch
4165 'tooltip' => 'watch',
4166 'label-id' => 'mw-editpage-watch',
4167 'legacy-name' => 'watch',
4168 'default' => $checked['watch'],
4173 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4179 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4180 * any other added by extensions.
4182 * @param int &$tabindex Current tabindex
4183 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4184 * status of the checkbox
4186 * @return array Associative array of string keys to OOUI\FieldLayout instances
4188 public function getCheckboxesWidget( &$tabindex, $checked ) {
4190 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4192 foreach ( $checkboxesDef as $name => $options ) {
4193 $legacyName = $options['legacy-name'] ??
$name;
4197 if ( isset( $options['tooltip'] ) ) {
4198 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4199 $title = Linker
::titleAttrib( $options['tooltip'] );
4201 if ( isset( $options['title-message'] ) ) {
4202 $title = $this->context
->msg( $options['title-message'] )->text();
4205 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4206 new OOUI\
CheckboxInputWidget( [
4207 'tabIndex' => ++
$tabindex,
4208 'accessKey' => $accesskey,
4209 'id' => $options['id'] . 'Widget',
4210 'inputId' => $options['id'],
4212 'selected' => $options['default'],
4213 'infusable' => true,
4216 'align' => 'inline',
4217 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4219 'id' => $options['label-id'] ??
null,
4228 * Get the message key of the label for the button to save the page
4233 protected function getSubmitButtonLabel() {
4235 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4237 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4238 $newPage = !$this->mTitle
->exists();
4240 if ( $labelAsPublish ) {
4241 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4243 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4246 return $buttonLabelKey;
4250 * Returns an array of html code of the following buttons:
4251 * save, diff and preview
4253 * @param int &$tabindex Current tabindex
4257 public function getEditButtons( &$tabindex ) {
4261 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4263 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4264 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4266 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4268 'tabIndex' => ++
$tabindex,
4269 'id' => 'wpSaveWidget',
4270 'inputId' => 'wpSave',
4271 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4272 'useInputTag' => true,
4273 'flags' => [ 'progressive', 'primary' ],
4274 'label' => $buttonLabel,
4275 'infusable' => true,
4277 // Messages used: tooltip-save, tooltip-publish
4278 'title' => Linker
::titleAttrib( $buttonTooltip ),
4279 // Messages used: accesskey-save, accesskey-publish
4280 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4283 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4284 'name' => 'wpPreview',
4285 'tabIndex' => ++
$tabindex,
4286 'id' => 'wpPreviewWidget',
4287 'inputId' => 'wpPreview',
4288 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4289 'useInputTag' => true,
4290 'label' => $this->context
->msg( 'showpreview' )->text(),
4291 'infusable' => true,
4293 // Message used: tooltip-preview
4294 'title' => Linker
::titleAttrib( 'preview' ),
4295 // Message used: accesskey-preview
4296 'accessKey' => Linker
::accesskey( 'preview' ),
4299 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4301 'tabIndex' => ++
$tabindex,
4302 'id' => 'wpDiffWidget',
4303 'inputId' => 'wpDiff',
4304 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4305 'useInputTag' => true,
4306 'label' => $this->context
->msg( 'showdiff' )->text(),
4307 'infusable' => true,
4309 // Message used: tooltip-diff
4310 'title' => Linker
::titleAttrib( 'diff' ),
4311 // Message used: accesskey-diff
4312 'accessKey' => Linker
::accesskey( 'diff' ),
4315 // Avoid PHP 7.1 warning of passing $this by reference
4317 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4323 * Creates a basic error page which informs the user that
4324 * they have attempted to edit a nonexistent section.
4326 public function noSuchSectionPage() {
4327 $out = $this->context
->getOutput();
4328 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4330 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4332 // Avoid PHP 7.1 warning of passing $this by reference
4334 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4335 $out->addHTML( $res );
4337 $out->returnToMain( false, $this->mTitle
);
4341 * Show "your edit contains spam" page with your diff and text
4343 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4345 public function spamPageWithContent( $match = false ) {
4346 $this->textbox2
= $this->textbox1
;
4348 if ( is_array( $match ) ) {
4349 $match = $this->context
->getLanguage()->listToText( $match );
4351 $out = $this->context
->getOutput();
4352 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4354 $out->addHTML( '<div id="spamprotected">' );
4355 $out->addWikiMsg( 'spamprotectiontext' );
4357 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4359 $out->addHTML( '</div>' );
4361 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4364 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4365 $this->showTextbox2();
4367 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4371 * Filter an input field through a Unicode de-armoring process if it
4372 * came from an old browser with known broken Unicode editing issues.
4374 * @deprecated since 1.30, does nothing
4376 * @param WebRequest $request
4377 * @param string $field
4380 protected function safeUnicodeInput( $request, $field ) {
4381 return rtrim( $request->getText( $field ) );
4385 * Filter an output field through a Unicode armoring process if it is
4386 * going to an old browser with known broken Unicode editing issues.
4388 * @deprecated since 1.30, does nothing
4390 * @param string $text
4393 protected function safeUnicodeOutput( $text ) {
4400 protected function addEditNotices() {
4401 $out = $this->context
->getOutput();
4402 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4403 if ( count( $editNotices ) ) {
4404 $out->addHTML( implode( "\n", $editNotices ) );
4406 $msg = $this->context
->msg( 'editnotice-notext' );
4407 if ( !$msg->isDisabled() ) {
4409 '<div class="mw-editnotice-notext">'
4410 . $msg->parseAsBlock()
4420 protected function addTalkPageText() {
4421 if ( $this->mTitle
->isTalkPage() ) {
4422 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4429 protected function addLongPageWarningHeader() {
4430 if ( $this->contentLength
=== false ) {
4431 $this->contentLength
= strlen( $this->textbox1
);
4434 $out = $this->context
->getOutput();
4435 $lang = $this->context
->getLanguage();
4436 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4437 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4438 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4441 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4442 $lang->formatNum( $maxArticleSize )
4445 } elseif ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4446 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4449 $lang->formatSize( strlen( $this->textbox1
) ),
4450 strlen( $this->textbox1
)
4459 protected function addPageProtectionWarningHeaders() {
4460 $out = $this->context
->getOutput();
4461 if ( $this->mTitle
->isProtected( 'edit' ) &&
4462 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4464 # Is the title semi-protected?
4465 if ( $this->mTitle
->isSemiProtected() ) {
4466 $noticeMsg = 'semiprotectedpagewarning';
4468 # Then it must be protected based on static groups (regular)
4469 $noticeMsg = 'protectedpagewarning';
4471 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4472 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4474 if ( $this->mTitle
->isCascadeProtected() ) {
4475 # Is this page under cascading protection from some source pages?
4476 /** @var Title[] $cascadeSources */
4477 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4478 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4479 $cascadeSourcesCount = count( $cascadeSources );
4480 if ( $cascadeSourcesCount > 0 ) {
4481 # Explain, and list the titles responsible
4482 foreach ( $cascadeSources as $page ) {
4483 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4486 $notice .= '</div>';
4487 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4489 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4490 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4492 'showIfEmpty' => false,
4493 'msgKey' => [ 'titleprotectedwarning' ],
4494 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4499 * @param OutputPage $out
4502 protected function addExplainConflictHeader( OutputPage
$out ) {
4504 $this->getEditConflictHelper()->getExplainHeader()
4509 * @param string $name
4510 * @param mixed[] $customAttribs
4515 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4516 return ( new TextboxBuilder() )->buildTextboxAttribs(
4517 $name, $customAttribs, $user, $this->mTitle
4522 * @param string $wikitext
4526 protected function addNewLineAtEnd( $wikitext ) {
4527 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4531 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4532 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4533 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4534 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4535 * spread the new style links more efficiently.
4537 * @param string $text
4540 private function guessSectionName( $text ) {
4543 // Detect Microsoft browsers
4544 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4545 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4546 // ...and redirect them to legacy encoding, if available
4547 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4549 // Meanwhile, real browsers get real anchors
4550 $name = $wgParser->guessSectionNameFromWikiText( $text );
4551 // With one little caveat: per T216029, fragments in HTTP redirects need to be urlencoded,
4552 // otherwise Chrome double-escapes the rest of the URL.
4553 return '#' . urlencode( mb_substr( $name, 1 ) );
4557 * Set a factory function to create an EditConflictHelper
4559 * @param callable $factory Factory function
4562 public function setEditConflictHelperFactory( callable
$factory ) {
4563 $this->editConflictHelperFactory
= $factory;
4564 $this->editConflictHelper
= null;
4568 * @return TextConflictHelper
4570 private function getEditConflictHelper() {
4571 if ( !$this->editConflictHelper
) {
4572 $this->editConflictHelper
= call_user_func(
4573 $this->editConflictHelperFactory
,
4574 $this->getSubmitButtonLabel()
4578 return $this->editConflictHelper
;
4582 * @param string $submitButtonLabel
4583 * @return TextConflictHelper
4585 private function newTextConflictHelper( $submitButtonLabel ) {
4586 return new TextConflictHelper(
4588 $this->getContext()->getOutput(),
4589 MediaWikiServices
::getInstance()->getStatsdDataFactory(),