3 * User interface for page editing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Block\DatabaseBlock
;
24 use MediaWiki\EditPage\TextboxBuilder
;
25 use MediaWiki\EditPage\TextConflictHelper
;
26 use MediaWiki\Logger\LoggerFactory
;
27 use MediaWiki\MediaWikiServices
;
28 use MediaWiki\Revision\RevisionRecord
;
29 use Wikimedia\ScopedCallback
;
32 * The edit page/HTML interface (split from Article)
33 * The actual database and text munging is still in Article,
34 * but it should get easier to call those from alternate
37 * EditPage cares about two distinct titles:
38 * $this->mContextTitle is the page that forms submit to, links point to,
39 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
40 * page in the database that is actually being edited. These are
41 * usually the same, but they are now allowed to be different.
43 * Surgeon General's Warning: prolonged exposure to this class is known to cause
44 * headaches, which may be fatal.
48 * Used for Unicode support checks
50 const UNICODE_CHECK
= 'β³π²β₯πππΎπΈβ΄πΉβ―';
53 * Status: Article successfully updated
55 const AS_SUCCESS_UPDATE
= 200;
58 * Status: Article successfully created
60 const AS_SUCCESS_NEW_ARTICLE
= 201;
63 * Status: Article update aborted by a hook function
65 const AS_HOOK_ERROR
= 210;
68 * Status: A hook function returned an error
70 const AS_HOOK_ERROR_EXPECTED
= 212;
73 * Status: User is blocked from editing this page
75 const AS_BLOCKED_PAGE_FOR_USER
= 215;
78 * Status: Content too big (> $wgMaxArticleSize)
80 const AS_CONTENT_TOO_BIG
= 216;
83 * Status: this anonymous user is not allowed to edit this page
85 const AS_READ_ONLY_PAGE_ANON
= 218;
88 * Status: this logged in user is not allowed to edit this page
90 const AS_READ_ONLY_PAGE_LOGGED
= 219;
93 * Status: wiki is in readonly mode (wfReadOnly() == true)
95 const AS_READ_ONLY_PAGE
= 220;
98 * Status: rate limiter for action 'edit' was tripped
100 const AS_RATE_LIMITED
= 221;
103 * Status: article was deleted while editing and param wpRecreate == false or form
106 const AS_ARTICLE_WAS_DELETED
= 222;
109 * Status: user tried to create this page, but is not allowed to do that
110 * ( Title->userCan('create') == false )
112 const AS_NO_CREATE_PERMISSION
= 223;
115 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
117 const AS_BLANK_ARTICLE
= 224;
120 * Status: (non-resolvable) edit conflict
122 const AS_CONFLICT_DETECTED
= 225;
125 * Status: no edit summary given and the user has forceeditsummary set and the user is not
126 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
128 const AS_SUMMARY_NEEDED
= 226;
131 * Status: user tried to create a new section without content
133 const AS_TEXTBOX_EMPTY
= 228;
136 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
138 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
141 * Status: WikiPage::doEdit() was unsuccessful
146 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
148 const AS_SPAM_ERROR
= 232;
151 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
153 const AS_IMAGE_REDIRECT_ANON
= 233;
156 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
158 const AS_IMAGE_REDIRECT_LOGGED
= 234;
161 * Status: user tried to modify the content model, but is not allowed to do that
162 * ( User::isAllowed('editcontentmodel') == false )
164 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
167 * Status: user tried to create self-redirect (redirect to the same article) and
168 * wpIgnoreSelfRedirect == false
170 const AS_SELF_REDIRECT
= 236;
173 * Status: an error relating to change tagging. Look at the message key for
176 const AS_CHANGE_TAG_ERROR
= 237;
179 * Status: can't parse content
181 const AS_PARSE_ERROR
= 240;
184 * Status: when changing the content model is disallowed due to
185 * $wgContentHandlerUseDB being false
187 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
190 * Status: edit rejected because browser doesn't support Unicode.
192 const AS_UNICODE_NOT_SUPPORTED
= 242;
195 * HTML id and name for the beginning of the edit form.
197 const EDITFORM_ID
= 'editform';
200 * Prefix of key for cookie used to pass post-edit state.
201 * The revision id edited is added after this
203 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
206 * Duration of PostEdit cookie, in seconds.
207 * The cookie will be removed instantly if the JavaScript runs.
209 * Otherwise, though, we don't want the cookies to accumulate.
210 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
211 * limit of only 20 cookies per domain. This still applies at least to some
212 * versions of IE without full updates:
213 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
215 * A value of 20 minutes should be enough to take into account slow loads and minor
216 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
218 const POST_EDIT_COOKIE_DURATION
= 1200;
221 * @deprecated for public usage since 1.30 use EditPage::getArticle()
229 * @deprecated for public usage since 1.30 use EditPage::getTitle()
234 /** @var null|Title */
235 private $mContextTitle = null;
238 public $action = 'submit';
240 /** @var bool Whether an edit conflict needs to be resolved. Detected based on whether
241 * $editRevId is different than the latest revision. When a conflict has successfully
242 * been resolved by a 3-way-merge, this field is set to false.
244 public $isConflict = false;
246 /** @var bool New page or new section */
247 public $isNew = false;
250 public $deletedSinceEdit;
256 * True the first time the edit form is rendered, false after re-rendering
257 * with diff, save prompts, etc.
261 /** @var bool|stdClass */
265 public $mTokenOk = false;
268 public $mTokenOkExceptSuffix = false;
271 public $mTriedSave = false;
274 public $incompleteForm = false;
277 public $tooBig = false;
280 public $missingComment = false;
283 public $missingSummary = false;
286 public $allowBlankSummary = false;
289 protected $blankArticle = false;
292 protected $allowBlankArticle = false;
295 protected $selfRedirect = false;
298 protected $allowSelfRedirect = false;
301 public $autoSumm = '';
304 public $hookError = '';
306 /** @var ParserOutput */
307 public $mParserOutput;
309 /** @var bool Has a summary been preset using GET parameter &summary= ? */
310 public $hasPresetSummary = false;
312 /** @var Revision|bool|null A revision object corresponding to $this->editRevId. */
313 public $mBaseRevision = false;
316 public $mShowSummaryField = true;
321 public $save = false;
324 public $preview = false;
327 public $diff = false;
330 public $minoredit = false;
333 public $watchthis = false;
336 public $recreate = false;
339 * Page content input field.
341 public $textbox1 = '';
344 public $textbox2 = '';
347 public $summary = '';
350 * If true, hide the summary field.
352 public $nosummary = false;
355 * Timestamp of the latest revision of the page when editing was initiated
358 public $edittime = '';
360 /** @var int Revision ID of the latest revision of the page when editing
361 * was initiated on the client. This is used to detect and resolve edit
364 * @note 0 if the page did not exist at that time.
365 * @note When starting an edit from an old revision, this still records the current
366 * revision at the time, not the one the edit is based on.
369 * @see getBaseRevision()
371 private $editRevId = null;
374 public $section = '';
377 public $sectiontitle = '';
380 * Timestamp from the first time the edit form was rendered.
382 public $starttime = '';
384 /** @var int Revision ID the edit is based on, or 0 if it's the current revision.
385 * FIXME: This isn't used in conflict resolution--provide a better
386 * justification or merge with parentRevId.
391 /** @var int Revision ID the edit is based on, adjusted when an edit conflict is resolved.
394 * @see getparentRevId()
396 public $parentRevId = 0;
399 public $editintro = '';
402 public $scrolltop = null;
408 public $contentModel;
410 /** @var null|string */
411 public $contentFormat = null;
413 /** @var null|array */
414 private $changeTags = null;
416 # Placeholders for text injection by hooks (must be HTML)
417 # extensions should take care to _append_ to the present value
419 /** @var string Before even the preview */
420 public $editFormPageTop = '';
421 public $editFormTextTop = '';
422 public $editFormTextBeforeContent = '';
423 public $editFormTextAfterWarn = '';
424 public $editFormTextAfterTools = '';
425 public $editFormTextBottom = '';
426 public $editFormTextAfterContent = '';
427 public $previewTextAfterContent = '';
428 public $mPreloadContent = null;
430 /* $didSave should be set to true whenever an article was successfully altered. */
431 public $didSave = false;
432 public $undidRev = 0;
434 public $suppressIntro = false;
440 protected $contentLength = false;
443 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
445 private $enableApiEditOverride = false;
448 * @var IContextSource
453 * @var bool Whether an old revision is edited
455 private $isOldRev = false;
458 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
460 private $unicodeCheck;
463 * Factory function to create an edit conflict helper
467 private $editConflictHelperFactory;
470 * @var TextConflictHelper|null
472 private $editConflictHelper;
475 * @param Article $article
477 public function __construct( Article
$article ) {
478 $this->mArticle
= $article;
479 $this->page
= $article->getPage(); // model object
480 $this->mTitle
= $article->getTitle();
482 // Make sure the local context is in sync with other member variables.
483 // Particularly make sure everything is using the same WikiPage instance.
484 // This should probably be the case in Article as well, but it's
485 // particularly important for EditPage, to make use of the in-place caching
486 // facility in WikiPage::prepareContentForEdit.
487 $this->context
= new DerivativeContext( $article->getContext() );
488 $this->context
->setWikiPage( $this->page
);
489 $this->context
->setTitle( $this->mTitle
);
491 $this->contentModel
= $this->mTitle
->getContentModel();
493 $handler = ContentHandler
::getForModelID( $this->contentModel
);
494 $this->contentFormat
= $handler->getDefaultFormat();
495 $this->editConflictHelperFactory
= [ $this, 'newTextConflictHelper' ];
501 public function getArticle() {
502 return $this->mArticle
;
507 * @return IContextSource
509 public function getContext() {
510 return $this->context
;
517 public function getTitle() {
518 return $this->mTitle
;
522 * Set the context Title object
524 * @param Title|null $title Title object or null
526 public function setContextTitle( $title ) {
527 $this->mContextTitle
= $title;
531 * Get the context title object.
533 * If not set, $wgTitle will be returned, but this is deprecated. This will
534 * throw an exception.
538 public function getContextTitle() {
539 if ( is_null( $this->mContextTitle
) ) {
540 wfDeprecated( __METHOD__
. ' called with no title set', '1.32' );
544 return $this->mContextTitle
;
549 * Returns if the given content model is editable.
551 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
553 * @throws MWException If $modelId has no known handler
555 public function isSupportedContentModel( $modelId ) {
556 return $this->enableApiEditOverride
=== true ||
557 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
561 * Allow editing of content that supports API direct editing, but not general
562 * direct editing. Set to false by default.
564 * @param bool $enableOverride
566 public function setApiEditOverride( $enableOverride ) {
567 $this->enableApiEditOverride
= $enableOverride;
571 * This is the function that gets called for "action=edit". It
572 * sets up various member variables, then passes execution to
573 * another function, usually showEditForm()
575 * The edit form is self-submitting, so that when things like
576 * preview and edit conflicts occur, we get the same form back
577 * with the extra stuff added. Only when the final submission
578 * is made and all is well do we actually save and redirect to
579 * the newly-edited page.
581 public function edit() {
582 // Allow extensions to modify/prevent this form or submission
583 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
587 wfDebug( __METHOD__
. ": enter\n" );
589 $request = $this->context
->getRequest();
590 // If they used redlink=1 and the page exists, redirect to the main article
591 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
592 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
596 $this->importFormData( $request );
597 $this->firsttime
= false;
599 if ( wfReadOnly() && $this->save
) {
602 $this->preview
= true;
606 $this->formtype
= 'save';
607 } elseif ( $this->preview
) {
608 $this->formtype
= 'preview';
609 } elseif ( $this->diff
) {
610 $this->formtype
= 'diff';
611 } else { # First time through
612 $this->firsttime
= true;
613 if ( $this->previewOnOpen() ) {
614 $this->formtype
= 'preview';
616 $this->formtype
= 'initial';
620 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
622 wfDebug( __METHOD__
. ": User can't edit\n" );
624 if ( $this->context
->getUser()->getBlock() ) {
625 // Track block with a cookie if it doesn't exist already
626 MediaWikiServices
::getInstance()->getBlockManager()
627 ->trackBlockWithCookie( $this->context
->getUser() );
629 // Auto-block user's IP if the account was "hard" blocked
630 if ( !wfReadOnly() ) {
631 DeferredUpdates
::addCallableUpdate( function () {
632 $this->context
->getUser()->spreadAnyEditBlock();
636 $this->displayPermissionsError( $permErrors );
641 $revision = $this->mArticle
->getRevisionFetched();
642 // Disallow editing revisions with content models different from the current one
643 // Undo edits being an exception in order to allow reverting content model changes.
645 && $revision->getContentModel() !== $this->contentModel
648 if ( $this->undidRev
) {
649 $undidRevObj = Revision
::newFromId( $this->undidRev
);
650 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
652 if ( !$this->undidRev
654 ||
$prevRev->getContentModel() !== $this->contentModel
656 $this->displayViewSourcePage(
657 $this->getContentObject(),
659 'contentmodelediterror',
660 $revision->getContentModel(),
668 $this->isConflict
= false;
670 # Show applicable editing introductions
671 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
675 # Attempt submission here. This will check for edit conflicts,
676 # and redundantly check for locked database, blocked IPs, etc.
677 # that edit() already checked just in case someone tries to sneak
678 # in the back door with a hand-edited submission URL.
680 if ( $this->formtype
== 'save' ) {
681 $resultDetails = null;
682 $status = $this->attemptSave( $resultDetails );
683 if ( !$this->handleStatus( $status, $resultDetails ) ) {
688 # First time through: get contents, set time for conflict
690 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
691 if ( $this->initialiseForm() === false ) {
695 if ( !$this->mTitle
->getArticleID() ) {
696 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
698 Hooks
::run( 'EditFormInitialText', [ $this ] );
703 $this->showEditForm();
707 * @param string $rigor Same format as Title::getUserPermissionErrors()
710 protected function getEditPermissionErrors( $rigor = 'secure' ) {
711 $user = $this->context
->getUser();
712 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
713 # Can this title be created?
714 if ( !$this->mTitle
->exists() ) {
715 $permErrors = array_merge(
718 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
723 # Ignore some permissions errors when a user is just previewing/viewing diffs
725 foreach ( $permErrors as $error ) {
726 if ( ( $this->preview ||
$this->diff
)
728 $error[0] == 'blockedtext' ||
729 $error[0] == 'autoblockedtext' ||
730 $error[0] == 'systemblockedtext'
736 $permErrors = wfArrayDiff2( $permErrors, $remove );
742 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
743 * but with the following differences:
744 * - If redlink=1, the user will be redirected to the page
745 * - If there is content to display or the error occurs while either saving,
746 * previewing or showing the difference, it will be a
747 * "View source for ..." page displaying the source code after the error message.
750 * @param array $permErrors Array of permissions errors, as returned by
751 * Title::getUserPermissionsErrors().
752 * @throws PermissionsError
754 protected function displayPermissionsError( array $permErrors ) {
755 $out = $this->context
->getOutput();
756 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
757 // The edit page was reached via a red link.
758 // Redirect to the article page and let them click the edit tab if
759 // they really want a permission error.
760 $out->redirect( $this->mTitle
->getFullURL() );
764 $content = $this->getContentObject();
766 # Use the normal message if there's nothing to display
767 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
768 $action = $this->mTitle
->exists() ?
'edit' :
769 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
770 throw new PermissionsError( $action, $permErrors );
773 $this->displayViewSourcePage(
775 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
780 * Display a read-only View Source page
781 * @param Content $content
782 * @param string $errorMessage additional wikitext error message to display
784 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
785 $out = $this->context
->getOutput();
786 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
788 $out->setRobotPolicy( 'noindex,nofollow' );
789 $out->setPageTitle( $this->context
->msg(
791 $this->getContextTitle()->getPrefixedText()
793 $out->addBacklinkSubtitle( $this->getContextTitle() );
794 $out->addHTML( $this->editFormPageTop
);
795 $out->addHTML( $this->editFormTextTop
);
797 if ( $errorMessage !== '' ) {
798 $out->addWikiTextAsInterface( $errorMessage );
799 $out->addHTML( "<hr />\n" );
802 # If the user made changes, preserve them when showing the markup
803 # (This happens when a user is blocked during edit, for instance)
804 if ( !$this->firsttime
) {
805 $text = $this->textbox1
;
806 $out->addWikiMsg( 'viewyourtext' );
809 $text = $this->toEditText( $content );
810 } catch ( MWException
$e ) {
811 # Serialize using the default format if the content model is not supported
812 # (e.g. for an old revision with a different model)
813 $text = $content->serialize();
815 $out->addWikiMsg( 'viewsourcetext' );
818 $out->addHTML( $this->editFormTextBeforeContent
);
819 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
820 $out->addHTML( $this->editFormTextAfterContent
);
822 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
824 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
826 $out->addHTML( $this->editFormTextBottom
);
827 if ( $this->mTitle
->exists() ) {
828 $out->returnToMain( null, $this->mTitle
);
833 * Should we show a preview when the edit form is first shown?
837 protected function previewOnOpen() {
838 $config = $this->context
->getConfig();
839 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
840 $request = $this->context
->getRequest();
841 if ( $config->get( 'RawHtml' ) ) {
842 // If raw HTML is enabled, disable preview on open
843 // since it has to be posted with a token for
847 if ( $request->getVal( 'preview' ) == 'yes' ) {
848 // Explicit override from request
850 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
851 // Explicit override from request
853 } elseif ( $this->section
== 'new' ) {
854 // Nothing *to* preview for new sections
856 } elseif ( ( $request->getCheck( 'preload' ) ||
$this->mTitle
->exists() )
857 && $this->context
->getUser()->getOption( 'previewonfirst' )
859 // Standard preference behavior
861 } elseif ( !$this->mTitle
->exists()
862 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
863 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
865 // Categories are special
873 * Checks whether the user entered a skin name in uppercase,
874 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
878 protected function isWrongCaseUserConfigPage() {
879 if ( $this->mTitle
->isUserConfigPage() ) {
880 $name = $this->mTitle
->getSkinFromConfigSubpage();
881 $skins = array_merge(
882 array_keys( Skin
::getSkinNames() ),
885 return !in_array( $name, $skins )
886 && in_array( strtolower( $name ), $skins );
893 * Returns whether section editing is supported for the current page.
894 * Subclasses may override this to replace the default behavior, which is
895 * to check ContentHandler::supportsSections.
897 * @return bool True if this edit page supports sections, false otherwise.
899 protected function isSectionEditSupported() {
900 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
901 return $contentHandler->supportsSections();
905 * This function collects the form data and uses it to populate various member variables.
906 * @param WebRequest &$request
907 * @throws ErrorPageError
909 public function importFormData( &$request ) {
910 # Section edit can come from either the form or a link
911 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
913 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
914 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
917 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
919 if ( $request->wasPosted() ) {
920 # These fields need to be checked for encoding.
921 # Also remove trailing whitespace, but don't remove _initial_
922 # whitespace from the text boxes. This may be significant formatting.
923 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
924 if ( !$request->getCheck( 'wpTextbox2' ) ) {
925 // Skip this if wpTextbox2 has input, it indicates that we came
926 // from a conflict page with raw page text, not a custom form
927 // modified by subclasses
928 $textbox1 = $this->importContentFormData( $request );
929 if ( $textbox1 !== null ) {
930 $this->textbox1
= $textbox1;
934 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
936 $this->summary
= $request->getText( 'wpSummary' );
938 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
939 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
941 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
943 # Treat sectiontitle the same way as summary.
944 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
945 # currently doing double duty as both edit summary and section title. Right now this
946 # is just to allow API edits to work around this limitation, but this should be
947 # incorporated into the actual edit form when EditPage is rewritten (T20654, T28312).
948 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
949 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
951 $this->edittime
= $request->getVal( 'wpEdittime' );
952 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
953 $this->starttime
= $request->getVal( 'wpStarttime' );
955 $undidRev = $request->getInt( 'wpUndidRevision' );
957 $this->undidRev
= $undidRev;
960 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
962 if ( $this->textbox1
=== '' && !$request->getCheck( 'wpTextbox1' ) ) {
963 // wpTextbox1 field is missing, possibly due to being "too big"
964 // according to some filter rules such as Suhosin's setting for
965 // suhosin.request.max_value_length (d'oh)
966 $this->incompleteForm
= true;
968 // If we receive the last parameter of the request, we can fairly
969 // claim the POST request has not been truncated.
970 $this->incompleteForm
= !$request->getVal( 'wpUltimateParam' );
972 if ( $this->incompleteForm
) {
973 # If the form is incomplete, force to preview.
974 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
975 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
976 $this->preview
= true;
978 $this->preview
= $request->getCheck( 'wpPreview' );
979 $this->diff
= $request->getCheck( 'wpDiff' );
981 // Remember whether a save was requested, so we can indicate
982 // if we forced preview due to session failure.
983 $this->mTriedSave
= !$this->preview
;
985 if ( $this->tokenOk( $request ) ) {
986 # Some browsers will not report any submit button
987 # if the user hits enter in the comment box.
988 # The unmarked state will be assumed to be a save,
989 # if the form seems otherwise complete.
990 wfDebug( __METHOD__
. ": Passed token check.\n" );
991 } elseif ( $this->diff
) {
992 # Failed token check, but only requested "Show Changes".
993 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
995 # Page might be a hack attempt posted from
996 # an external site. Preview instead of saving.
997 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
998 $this->preview
= true;
1001 $this->save
= !$this->preview
&& !$this->diff
;
1002 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
1003 $this->edittime
= null;
1006 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
1007 $this->starttime
= null;
1010 $this->recreate
= $request->getCheck( 'wpRecreate' );
1012 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
1013 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
1015 $user = $this->context
->getUser();
1016 # Don't force edit summaries when a user is editing their own user or talk page
1017 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
1018 && $this->mTitle
->getText() == $user->getName()
1020 $this->allowBlankSummary
= true;
1022 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1023 ||
!$user->getOption( 'forceeditsummary' );
1026 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1028 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1029 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1031 $changeTags = $request->getVal( 'wpChangeTags' );
1032 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1033 $this->changeTags
= [];
1035 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1039 # Not a posted form? Start with nothing.
1040 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1041 $this->textbox1
= '';
1042 $this->summary
= '';
1043 $this->sectiontitle
= '';
1044 $this->edittime
= '';
1045 $this->editRevId
= null;
1046 $this->starttime
= wfTimestampNow();
1047 $this->edit
= false;
1048 $this->preview
= false;
1049 $this->save
= false;
1050 $this->diff
= false;
1051 $this->minoredit
= false;
1052 // Watch may be overridden by request parameters
1053 $this->watchthis
= $request->getBool( 'watchthis', false );
1054 $this->recreate
= false;
1056 // When creating a new section, we can preload a section title by passing it as the
1057 // preloadtitle parameter in the URL (T15100)
1058 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1059 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1060 // Once wpSummary isn't being use for setting section titles, we should delete this.
1061 $this->summary
= $request->getVal( 'preloadtitle' );
1062 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) !== '' ) {
1063 $this->summary
= $request->getText( 'summary' );
1064 if ( $this->summary
!== '' ) {
1065 $this->hasPresetSummary
= true;
1069 if ( $request->getVal( 'minor' ) ) {
1070 $this->minoredit
= true;
1074 $this->oldid
= $request->getInt( 'oldid' );
1075 $this->parentRevId
= $request->getInt( 'parentRevId' );
1077 $this->bot
= $request->getBool( 'bot', true );
1078 $this->nosummary
= $request->getBool( 'nosummary' );
1080 // May be overridden by revision.
1081 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1082 // May be overridden by revision.
1083 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1086 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1087 } catch ( MWUnknownContentModelException
$e ) {
1088 throw new ErrorPageError(
1089 'editpage-invalidcontentmodel-title',
1090 'editpage-invalidcontentmodel-text',
1091 [ wfEscapeWikiText( $this->contentModel
) ]
1095 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1096 throw new ErrorPageError(
1097 'editpage-notsupportedcontentformat-title',
1098 'editpage-notsupportedcontentformat-text',
1100 wfEscapeWikiText( $this->contentFormat
),
1101 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1107 * @todo Check if the desired model is allowed in this namespace, and if
1108 * a transition from the page's current model to the new model is
1112 $this->editintro
= $request->getText( 'editintro',
1113 // Custom edit intro for new sections
1114 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1116 // Allow extensions to modify form data
1117 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1121 * Subpage overridable method for extracting the page content data from the
1122 * posted form to be placed in $this->textbox1, if using customized input
1123 * this method should be overridden and return the page text that will be used
1124 * for saving, preview parsing and so on...
1126 * @param WebRequest &$request
1127 * @return string|null
1129 protected function importContentFormData( &$request ) {
1130 return null; // Don't do anything, EditPage already extracted wpTextbox1
1134 * Initialise form fields in the object
1135 * Called on the first invocation, e.g. when a user clicks an edit link
1136 * @return bool If the requested section is valid
1138 public function initialiseForm() {
1139 $this->edittime
= $this->page
->getTimestamp();
1140 $this->editRevId
= $this->page
->getLatest();
1142 $content = $this->getContentObject( false ); # TODO: track content object?!
1143 if ( $content === false ) {
1144 $out = $this->context
->getOutput();
1145 if ( $out->getRedirect() === '' ) { // mcrundo hack redirects, don't override it
1146 $this->noSuchSectionPage();
1151 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
1152 $modelMsg = $this->getContext()->msg( 'content-model-' . $content->getModel() );
1153 $modelName = $modelMsg->exists() ?
$modelMsg->text() : $content->getModel();
1155 $out = $this->context
->getOutput();
1156 $out->showErrorPage(
1157 'modeleditnotsupported-title',
1158 'modeleditnotsupported-text',
1164 $this->textbox1
= $this->toEditText( $content );
1166 $user = $this->context
->getUser();
1167 // activate checkboxes if user wants them to be always active
1168 # Sort out the "watch" checkbox
1169 if ( $user->getOption( 'watchdefault' ) ) {
1171 $this->watchthis
= true;
1172 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1174 $this->watchthis
= true;
1175 } elseif ( $user->isWatched( $this->mTitle
) ) {
1177 $this->watchthis
= true;
1179 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1180 $this->minoredit
= true;
1182 if ( $this->textbox1
=== false ) {
1189 * @param Content|null $def_content The default value to return
1191 * @return Content|false|null Content on success, $def_content for invalid sections
1195 protected function getContentObject( $def_content = null ) {
1196 global $wgDisableAnonTalk;
1200 $user = $this->context
->getUser();
1201 $request = $this->context
->getRequest();
1202 // For message page not locally set, use the i18n message.
1203 // For other non-existent articles, use preload text if any.
1204 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1205 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1206 # If this is a system message, get the default text.
1207 $msg = $this->mTitle
->getDefaultMessageText();
1209 $content = $this->toEditContent( $msg );
1211 if ( $content === false ) {
1212 # If requested, preload some text.
1213 $preload = $request->getVal( 'preload',
1214 // Custom preload text for new sections
1215 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1216 $params = $request->getArray( 'preloadparams', [] );
1218 $content = $this->getPreloadedContent( $preload, $params );
1220 // For existing pages, get text based on "undo" or section parameters.
1221 } elseif ( $this->section
!= '' ) {
1222 // Get section edit text (returns $def_text for invalid sections)
1223 $orig = $this->getOriginalContent( $user );
1224 $content = $orig ?
$orig->getSection( $this->section
) : null;
1227 $content = $def_content;
1230 $undoafter = $request->getInt( 'undoafter' );
1231 $undo = $request->getInt( 'undo' );
1233 if ( $undo > 0 && $undoafter > 0 ) {
1234 $undorev = Revision
::newFromId( $undo );
1235 $oldrev = Revision
::newFromId( $undoafter );
1238 # Sanity check, make sure it's the right page,
1239 # the revisions exist and they were not deleted.
1240 # Otherwise, $content will be left as-is.
1241 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1242 !$undorev->isDeleted( RevisionRecord
::DELETED_TEXT
) &&
1243 !$oldrev->isDeleted( RevisionRecord
::DELETED_TEXT
)
1245 if ( WikiPage
::hasDifferencesOutsideMainSlot( $undorev, $oldrev )
1246 ||
!$this->isSupportedContentModel( $oldrev->getContentModel() )
1248 // Hack for undo while EditPage can't handle multi-slot editing
1249 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL( [
1250 'action' => 'mcrundo',
1252 'undoafter' => $undoafter,
1256 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1258 if ( $content === false ) {
1259 # Warn the user that something went wrong
1260 $undoMsg = 'failure';
1264 if ( $undoMsg === null ) {
1265 $oldContent = $this->page
->getContent( RevisionRecord
::RAW
);
1266 $popts = ParserOptions
::newFromUserAndLang(
1267 $user, MediaWikiServices
::getInstance()->getContentLanguage() );
1268 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1269 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1270 // The undo may change content
1271 // model if its reverting the top
1272 // edit. This can result in
1273 // mismatched content model/format.
1274 $this->contentModel
= $newContent->getModel();
1275 $this->contentFormat
= $oldrev->getContentFormat();
1278 if ( $newContent->equals( $oldContent ) ) {
1279 # Tell the user that the undo results in no change,
1280 # i.e. the revisions were already undone.
1281 $undoMsg = 'nochange';
1284 # Inform the user of our success and set an automatic edit summary
1285 $undoMsg = 'success';
1287 # If we just undid one rev, use an autosummary
1288 $firstrev = $oldrev->getNext();
1289 if ( $firstrev && $firstrev->getId() == $undo ) {
1290 $userText = $undorev->getUserText();
1291 if ( $userText === '' ) {
1292 $undoSummary = $this->context
->msg(
1293 'undo-summary-username-hidden',
1295 )->inContentLanguage()->text();
1297 $undoMessage = ( $undorev->getUser() === 0 && $wgDisableAnonTalk ) ?
1298 'undo-summary-anon' :
1300 $undoSummary = $this->context
->msg(
1304 )->inContentLanguage()->text();
1306 if ( $this->summary
=== '' ) {
1307 $this->summary
= $undoSummary;
1309 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1310 ->inContentLanguage()->text() . $this->summary
;
1312 $this->undidRev
= $undo;
1314 $this->formtype
= 'diff';
1318 // Failed basic sanity checks.
1319 // Older revisions may have been removed since the link
1320 // was created, or we may simply have got bogus input.
1324 $out = $this->context
->getOutput();
1325 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1327 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1328 $this->editFormPageTop
.= Html
::rawElement(
1329 'div', [ 'class' => $class ],
1330 $out->parseAsInterface(
1331 $this->context
->msg( 'undo-' . $undoMsg )->plain()
1336 if ( $content === false ) {
1337 // Hack for restoring old revisions while EditPage
1338 // can't handle multi-slot editing.
1340 $curRevision = $this->page
->getRevision();
1341 $oldRevision = $this->mArticle
->getRevisionFetched();
1345 && $curRevision->getId() !== $oldRevision->getId()
1346 && ( WikiPage
::hasDifferencesOutsideMainSlot( $oldRevision, $curRevision )
1347 ||
!$this->isSupportedContentModel( $oldRevision->getContentModel() ) )
1349 $this->context
->getOutput()->redirect(
1350 $this->mTitle
->getFullURL(
1352 'action' => 'mcrrestore',
1353 'restore' => $oldRevision->getId(),
1362 if ( $content === false ) {
1363 $content = $this->getOriginalContent( $user );
1371 * Get the content of the wanted revision, without section extraction.
1373 * The result of this function can be used to compare user's input with
1374 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1375 * to the original text of the edit.
1377 * This differs from Article::getContent() that when a missing revision is
1378 * encountered the result will be null and not the
1379 * 'missing-revision' message.
1382 * @param User $user The user to get the revision for
1383 * @return Content|null
1385 private function getOriginalContent( User
$user ) {
1386 if ( $this->section
== 'new' ) {
1387 return $this->getCurrentContent();
1389 $revision = $this->mArticle
->getRevisionFetched();
1390 if ( $revision === null ) {
1391 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1392 return $handler->makeEmptyContent();
1394 $content = $revision->getContent( RevisionRecord
::FOR_THIS_USER
, $user );
1399 * Get the edit's parent revision ID
1401 * The "parent" revision is the ancestor that should be recorded in this
1402 * page's revision history. It is either the revision ID of the in-memory
1403 * article content, or in the case of a 3-way merge in order to rebase
1404 * across a recoverable edit conflict, the ID of the newer revision to
1405 * which we have rebased this page.
1408 * @return int Revision ID
1410 public function getParentRevId() {
1411 if ( $this->parentRevId
) {
1412 return $this->parentRevId
;
1414 return $this->mArticle
->getRevIdFetched();
1419 * Get the current content of the page. This is basically similar to
1420 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1421 * content object is returned instead of null.
1426 protected function getCurrentContent() {
1427 $rev = $this->page
->getRevision();
1428 $content = $rev ?
$rev->getContent( RevisionRecord
::RAW
) : null;
1430 if ( $content === false ||
$content === null ) {
1431 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1432 return $handler->makeEmptyContent();
1433 } elseif ( !$this->undidRev
) {
1434 // Content models should always be the same since we error
1435 // out if they are different before this point (in ->edit()).
1436 // The exception being, during an undo, the current revision might
1437 // differ from the prior revision.
1438 $logger = LoggerFactory
::getInstance( 'editpage' );
1439 if ( $this->contentModel
!== $rev->getContentModel() ) {
1440 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1441 'prev' => $this->contentModel
,
1442 'new' => $rev->getContentModel(),
1443 'title' => $this->getTitle()->getPrefixedDBkey(),
1444 'method' => __METHOD__
1446 $this->contentModel
= $rev->getContentModel();
1449 // Given that the content models should match, the current selected
1450 // format should be supported.
1451 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1452 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1454 'prev' => $this->contentFormat
,
1455 'new' => $rev->getContentFormat(),
1456 'title' => $this->getTitle()->getPrefixedDBkey(),
1457 'method' => __METHOD__
1459 $this->contentFormat
= $rev->getContentFormat();
1466 * Use this method before edit() to preload some content into the edit box
1468 * @param Content $content
1472 public function setPreloadedContent( Content
$content ) {
1473 $this->mPreloadContent
= $content;
1477 * Get the contents to be preloaded into the box, either set by
1478 * an earlier setPreloadText() or by loading the given page.
1480 * @param string $preload Representing the title to preload from.
1481 * @param array $params Parameters to use (interface-message style) in the preloaded text
1487 protected function getPreloadedContent( $preload, $params = [] ) {
1488 if ( !empty( $this->mPreloadContent
) ) {
1489 return $this->mPreloadContent
;
1492 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1494 if ( $preload === '' ) {
1495 return $handler->makeEmptyContent();
1498 $user = $this->context
->getUser();
1499 $title = Title
::newFromText( $preload );
1501 # Check for existence to avoid getting MediaWiki:Noarticletext
1502 if ( !$this->isPageExistingAndViewable( $title, $user ) ) {
1503 // TODO: somehow show a warning to the user!
1504 return $handler->makeEmptyContent();
1507 $page = WikiPage
::factory( $title );
1508 if ( $page->isRedirect() ) {
1509 $title = $page->getRedirectTarget();
1511 if ( !$this->isPageExistingAndViewable( $title, $user ) ) {
1512 // TODO: somehow show a warning to the user!
1513 return $handler->makeEmptyContent();
1515 $page = WikiPage
::factory( $title );
1518 $parserOptions = ParserOptions
::newFromUser( $user );
1519 $content = $page->getContent( RevisionRecord
::RAW
);
1522 // TODO: somehow show a warning to the user!
1523 return $handler->makeEmptyContent();
1526 if ( $content->getModel() !== $handler->getModelID() ) {
1527 $converted = $content->convert( $handler->getModelID() );
1529 if ( !$converted ) {
1530 // TODO: somehow show a warning to the user!
1531 wfDebug( "Attempt to preload incompatible content: " .
1532 "can't convert " . $content->getModel() .
1533 " to " . $handler->getModelID() );
1535 return $handler->makeEmptyContent();
1538 $content = $converted;
1541 return $content->preloadTransform( $title, $parserOptions, $params );
1545 * Verify if a given title exists and the given user is allowed to view it
1547 * @see EditPage::getPreloadedContent()
1548 * @param Title|null $title
1553 private function isPageExistingAndViewable( $title, User
$user ) {
1554 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
1556 return $title && $title->exists() && $permissionManager->userCan( 'read', $user, $title );
1560 * Make sure the form isn't faking a user's credentials.
1562 * @param WebRequest &$request
1566 public function tokenOk( &$request ) {
1567 $token = $request->getVal( 'wpEditToken' );
1568 $user = $this->context
->getUser();
1569 $this->mTokenOk
= $user->matchEditToken( $token );
1570 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1571 return $this->mTokenOk
;
1575 * Sets post-edit cookie indicating the user just saved a particular revision.
1577 * This uses a temporary cookie for each revision ID so separate saves will never
1578 * interfere with each other.
1580 * Article::view deletes the cookie on server-side after the redirect and
1581 * converts the value to the global JavaScript variable wgPostEdit.
1583 * If the variable were set on the server, it would be cached, which is unwanted
1584 * since the post-edit state should only apply to the load right after the save.
1586 * @param int $statusValue The status value (to check for new article status)
1588 protected function setPostEditCookie( $statusValue ) {
1589 $revisionId = $this->page
->getLatest();
1590 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1593 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1595 } elseif ( $this->oldid
) {
1599 $response = $this->context
->getRequest()->response();
1600 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1604 * Attempt submission
1605 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1606 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1607 * @return Status The resulting status object.
1609 public function attemptSave( &$resultDetails = false ) {
1610 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1611 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1612 // This is needed since PageUpdater no longer checks these rights!
1614 // Allow bots to exempt some edits from bot flagging
1615 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
1616 $bot = $permissionManager->userHasRight( $this->context
->getUser(), 'bot' ) && $this->bot
;
1617 $status = $this->internalAttemptSave( $resultDetails, $bot );
1619 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1625 * Log when a page was successfully saved after the edit conflict view
1627 private function incrementResolvedConflicts() {
1628 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1632 $this->getEditConflictHelper()->incrementResolvedStats();
1636 * Handle status, such as after attempt save
1638 * @param Status $status
1639 * @param array|bool $resultDetails
1641 * @throws ErrorPageError
1642 * @return bool False, if output is done, true if rest of the form should be displayed
1644 private function handleStatus( Status
$status, $resultDetails ) {
1646 * @todo FIXME: once the interface for internalAttemptSave() is made
1647 * nicer, this should use the message in $status
1649 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1650 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1652 $this->incrementResolvedConflicts();
1654 $this->didSave
= true;
1655 if ( !$resultDetails['nullEdit'] ) {
1656 $this->setPostEditCookie( $status->value
);
1660 $out = $this->context
->getOutput();
1662 // "wpExtraQueryRedirect" is a hidden input to modify
1663 // after save URL and is not used by actual edit form
1664 $request = $this->context
->getRequest();
1665 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1667 switch ( $status->value
) {
1668 case self
::AS_HOOK_ERROR_EXPECTED
:
1669 case self
::AS_CONTENT_TOO_BIG
:
1670 case self
::AS_ARTICLE_WAS_DELETED
:
1671 case self
::AS_CONFLICT_DETECTED
:
1672 case self
::AS_SUMMARY_NEEDED
:
1673 case self
::AS_TEXTBOX_EMPTY
:
1674 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1676 case self
::AS_BLANK_ARTICLE
:
1677 case self
::AS_SELF_REDIRECT
:
1680 case self
::AS_HOOK_ERROR
:
1683 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1684 case self
::AS_PARSE_ERROR
:
1685 case self
::AS_UNICODE_NOT_SUPPORTED
:
1686 $out->wrapWikiTextAsInterface( 'error',
1687 $status->getWikiText( false, false, $this->context
->getLanguage() )
1691 case self
::AS_SUCCESS_NEW_ARTICLE
:
1692 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1693 if ( $extraQueryRedirect ) {
1694 if ( $query !== '' ) {
1697 $query .= $extraQueryRedirect;
1699 $anchor = $resultDetails['sectionanchor'] ??
'';
1700 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1703 case self
::AS_SUCCESS_UPDATE
:
1705 $sectionanchor = $resultDetails['sectionanchor'];
1707 // Give extensions a chance to modify URL query on update
1709 'ArticleUpdateBeforeRedirect',
1710 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1713 if ( $resultDetails['redirect'] ) {
1714 if ( $extraQuery !== '' ) {
1715 $extraQuery = '&' . $extraQuery;
1717 $extraQuery = 'redirect=no' . $extraQuery;
1719 if ( $extraQueryRedirect ) {
1720 if ( $extraQuery !== '' ) {
1723 $extraQuery .= $extraQueryRedirect;
1726 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1729 case self
::AS_SPAM_ERROR
:
1730 $this->spamPageWithContent( $resultDetails['spam'] );
1733 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1734 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1736 case self
::AS_IMAGE_REDIRECT_ANON
:
1737 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1738 throw new PermissionsError( 'upload' );
1740 case self
::AS_READ_ONLY_PAGE_ANON
:
1741 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1742 throw new PermissionsError( 'edit' );
1744 case self
::AS_READ_ONLY_PAGE
:
1745 throw new ReadOnlyError
;
1747 case self
::AS_RATE_LIMITED
:
1748 throw new ThrottledError();
1750 case self
::AS_NO_CREATE_PERMISSION
:
1751 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1752 throw new PermissionsError( $permission );
1754 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1755 throw new PermissionsError( 'editcontentmodel' );
1758 // We don't recognize $status->value. The only way that can happen
1759 // is if an extension hook aborted from inside ArticleSave.
1760 // Render the status object into $this->hookError
1761 // FIXME this sucks, we should just use the Status object throughout
1762 $this->hookError
= '<div class="error">' . "\n" .
1763 $status->getWikiText( false, false, $this->context
->getLanguage() ) .
1770 * Run hooks that can filter edits just before they get saved.
1772 * @param Content $content The Content to filter.
1773 * @param Status $status For reporting the outcome to the caller
1774 * @param User $user The user performing the edit
1778 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1779 // Run old style post-section-merge edit filter
1780 if ( $this->hookError
!= '' ) {
1781 # ...or the hook could be expecting us to produce an error
1782 $status->fatal( 'hookaborted' );
1783 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1787 // Run new style post-section-merge edit filter
1788 if ( !Hooks
::run( 'EditFilterMergedContent',
1789 [ $this->context
, $content, $status, $this->summary
,
1790 $user, $this->minoredit
] )
1792 # Error messages etc. could be handled within the hook...
1793 if ( $status->isGood() ) {
1794 $status->fatal( 'hookaborted' );
1795 // Not setting $this->hookError here is a hack to allow the hook
1796 // to cause a return to the edit page without $this->hookError
1797 // being set. This is used by ConfirmEdit to display a captcha
1798 // without any error message cruft.
1800 $this->hookError
= $this->formatStatusErrors( $status );
1802 // Use the existing $status->value if the hook set it
1803 if ( !$status->value
) {
1804 $status->value
= self
::AS_HOOK_ERROR
;
1807 } elseif ( !$status->isOK() ) {
1808 # ...or the hook could be expecting us to produce an error
1809 // FIXME this sucks, we should just use the Status object throughout
1810 if ( !$status->getErrors() ) {
1811 // Provide a fallback error message if none was set
1812 $status->fatal( 'hookaborted' );
1814 $this->hookError
= $this->formatStatusErrors( $status );
1815 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1823 * Wrap status errors in an errorbox for increased visibility
1825 * @param Status $status
1826 * @return string Wikitext
1828 private function formatStatusErrors( Status
$status ) {
1829 $errmsg = $status->getWikiText(
1832 $this->context
->getLanguage()
1835 <div class="errorbox">
1843 * Return the summary to be used for a new section.
1845 * @param string $sectionanchor Set to the section anchor text
1848 private function newSectionSummary( &$sectionanchor = null ) {
1849 if ( $this->sectiontitle
!== '' ) {
1850 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1851 // If no edit summary was specified, create one automatically from the section
1852 // title and have it link to the new section. Otherwise, respect the summary as
1854 if ( $this->summary
=== '' ) {
1855 $cleanSectionTitle = MediaWikiServices
::getInstance()->getParser()
1856 ->stripSectionName( $this->sectiontitle
);
1857 return $this->context
->msg( 'newsectionsummary' )
1858 ->plaintextParams( $cleanSectionTitle )->inContentLanguage()->text();
1860 } elseif ( $this->summary
!== '' ) {
1861 $sectionanchor = $this->guessSectionName( $this->summary
);
1862 # This is a new section, so create a link to the new section
1863 # in the revision summary.
1864 $cleanSummary = MediaWikiServices
::getInstance()->getParser()
1865 ->stripSectionName( $this->summary
);
1866 return $this->context
->msg( 'newsectionsummary' )
1867 ->plaintextParams( $cleanSummary )->inContentLanguage()->text();
1869 return $this->summary
;
1873 * Attempt submission (no UI)
1875 * @param array &$result Array to add statuses to, currently with the
1877 * - spam (string): Spam string from content if any spam is detected by
1879 * - sectionanchor (string): Section anchor for a section save.
1880 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1882 * - redirect (bool): Set if doEditContent is OK. True if resulting
1883 * revision is a redirect.
1884 * @param bool $bot True if edit is being made under the bot right.
1886 * @return Status Status object, possibly with a message, but always with
1887 * one of the AS_* constants in $status->value,
1889 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1890 * various error display idiosyncrasies. There are also lots of cases
1891 * where error metadata is set in the object and retrieved later instead
1892 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1893 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1896 public function internalAttemptSave( &$result, $bot = false ) {
1897 $status = Status
::newGood();
1898 $user = $this->context
->getUser();
1899 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
1901 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1902 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1903 $status->fatal( 'hookaborted' );
1904 $status->value
= self
::AS_HOOK_ERROR
;
1908 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1909 $status->fatal( 'unicode-support-fail' );
1910 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1914 $request = $this->context
->getRequest();
1915 $spam = $request->getText( 'wpAntispam' );
1916 if ( $spam !== '' ) {
1921 $this->mTitle
->getPrefixedText() .
1922 '" submitted bogus field "' .
1926 $status->fatal( 'spamprotectionmatch', false );
1927 $status->value
= self
::AS_SPAM_ERROR
;
1932 # Construct Content object
1933 $textbox_content = $this->toEditContent( $this->textbox1
);
1934 } catch ( MWContentSerializationException
$ex ) {
1936 'content-failed-to-parse',
1937 $this->contentModel
,
1938 $this->contentFormat
,
1941 $status->value
= self
::AS_PARSE_ERROR
;
1945 # Check image redirect
1946 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1947 $textbox_content->isRedirect() &&
1948 !$permissionManager->userHasRight( $user, 'upload' )
1950 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1951 $status->setResult( false, $code );
1957 $match = self
::matchSummarySpamRegex( $this->summary
);
1958 if ( $match === false && $this->section
== 'new' ) {
1959 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1960 # regular summaries, it is added to the actual wikitext.
1961 if ( $this->sectiontitle
!== '' ) {
1962 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1963 $match = self
::matchSpamRegex( $this->sectiontitle
);
1965 # This branch is taken when the "Add Topic" user interface is used, or the API
1966 # is used with the 'summary' parameter.
1967 $match = self
::matchSpamRegex( $this->summary
);
1970 if ( $match === false ) {
1971 $match = self
::matchSpamRegex( $this->textbox1
);
1973 if ( $match !== false ) {
1974 $result['spam'] = $match;
1975 $ip = $request->getIP();
1976 $pdbk = $this->mTitle
->getPrefixedDBkey();
1977 $match = str_replace( "\n", '', $match );
1978 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1979 $status->fatal( 'spamprotectionmatch', $match );
1980 $status->value
= self
::AS_SPAM_ERROR
;
1985 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1987 # Error messages etc. could be handled within the hook...
1988 $status->fatal( 'hookaborted' );
1989 $status->value
= self
::AS_HOOK_ERROR
;
1991 } elseif ( $this->hookError
!= '' ) {
1992 # ...or the hook could be expecting us to produce an error
1993 $status->fatal( 'hookaborted' );
1994 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1998 if ( $permissionManager->isBlockedFrom( $user, $this->mTitle
) ) {
1999 // Auto-block user's IP if the account was "hard" blocked
2000 if ( !wfReadOnly() ) {
2001 $user->spreadAnyEditBlock();
2003 # Check block state against master, thus 'false'.
2004 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
2008 $this->contentLength
= strlen( $this->textbox1
);
2009 $config = $this->context
->getConfig();
2010 $maxArticleSize = $config->get( 'MaxArticleSize' );
2011 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2012 // Error will be displayed by showEditForm()
2013 $this->tooBig
= true;
2014 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
2018 if ( !$permissionManager->userHasRight( $user, 'edit' ) ) {
2019 if ( $user->isAnon() ) {
2020 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
2023 $status->fatal( 'readonlytext' );
2024 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
2029 $changingContentModel = false;
2030 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
2031 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
2032 $status->fatal( 'editpage-cannot-use-custom-model' );
2033 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
2035 } elseif ( !$permissionManager->userHasRight( $user, 'editcontentmodel' ) ) {
2036 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2039 // Make sure the user can edit the page under the new content model too
2040 $titleWithNewContentModel = clone $this->mTitle
;
2041 $titleWithNewContentModel->setContentModel( $this->contentModel
);
2043 $canEditModel = $permissionManager->userCan(
2046 $titleWithNewContentModel
2051 ||
!$permissionManager->userCan( 'edit', $user, $titleWithNewContentModel )
2053 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2058 $changingContentModel = true;
2059 $oldContentModel = $this->mTitle
->getContentModel();
2062 if ( $this->changeTags
) {
2063 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
2064 $this->changeTags
, $user );
2065 if ( !$changeTagsStatus->isOK() ) {
2066 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
2067 return $changeTagsStatus;
2071 if ( wfReadOnly() ) {
2072 $status->fatal( 'readonlytext' );
2073 $status->value
= self
::AS_READ_ONLY_PAGE
;
2076 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
2077 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
2079 $status->fatal( 'actionthrottledtext' );
2080 $status->value
= self
::AS_RATE_LIMITED
;
2084 # If the article has been deleted while editing, don't save it without
2086 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
2087 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
2091 # Load the page data from the master. If anything changes in the meantime,
2092 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
2093 $this->page
->loadPageData( 'fromdbmaster' );
2094 $new = !$this->page
->exists();
2097 // Late check for create permission, just in case *PARANOIA*
2098 if ( !$permissionManager->userCan( 'create', $user, $this->mTitle
) ) {
2099 $status->fatal( 'nocreatetext' );
2100 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
2101 wfDebug( __METHOD__
. ": no create permission\n" );
2105 // Don't save a new page if it's blank or if it's a MediaWiki:
2106 // message with content equivalent to default (allow empty pages
2107 // in this case to disable messages, see T52124)
2108 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2109 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
2110 $defaultText = $defaultMessageText;
2115 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
2116 $this->blankArticle
= true;
2117 $status->fatal( 'blankarticle' );
2118 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
2122 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2126 $content = $textbox_content;
2128 $result['sectionanchor'] = '';
2129 if ( $this->section
== 'new' ) {
2130 if ( $this->sectiontitle
!== '' ) {
2131 // Insert the section title above the content.
2132 $content = $content->addSectionHeader( $this->sectiontitle
);
2133 } elseif ( $this->summary
!== '' ) {
2134 // Insert the section title above the content.
2135 $content = $content->addSectionHeader( $this->summary
);
2137 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2140 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2144 # Article exists. Check for edit conflict.
2146 $this->page
->clear(); # Force reload of dates, etc.
2147 $timestamp = $this->page
->getTimestamp();
2148 $latest = $this->page
->getLatest();
2150 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2152 // An edit conflict is detected if the current revision is different from the
2153 // revision that was current when editing was initiated on the client.
2154 // This is checked based on the timestamp and revision ID.
2155 // TODO: the timestamp based check can probably go away now.
2156 if ( $timestamp != $this->edittime
2157 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2159 $this->isConflict
= true;
2160 if ( $this->section
== 'new' ) {
2161 if ( $this->page
->getUserText() == $user->getName() &&
2162 $this->page
->getComment() == $this->newSectionSummary()
2164 // Probably a duplicate submission of a new comment.
2165 // This can happen when CDN resends a request after
2166 // a timeout but the first one actually went through.
2168 . ": duplicate new section submission; trigger edit conflict!\n" );
2170 // New comment; suppress conflict.
2171 $this->isConflict
= false;
2172 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2174 } elseif ( $this->section
== ''
2175 && Revision
::userWasLastToEdit(
2176 DB_MASTER
, $this->mTitle
->getArticleID(),
2177 $user->getId(), $this->edittime
2180 # Suppress edit conflict with self, except for section edits where merging is required.
2181 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2182 $this->isConflict
= false;
2186 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2187 if ( $this->sectiontitle
!== '' ) {
2188 $sectionTitle = $this->sectiontitle
;
2190 $sectionTitle = $this->summary
;
2195 if ( $this->isConflict
) {
2197 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2198 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2199 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2200 // ...or disable section editing for non-current revisions (not exposed anyway).
2201 if ( $this->editRevId
!== null ) {
2202 $content = $this->page
->replaceSectionAtRev(
2209 $content = $this->page
->replaceSectionContent(
2217 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2218 $content = $this->page
->replaceSectionContent(
2225 if ( is_null( $content ) ) {
2226 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2227 $this->isConflict
= true;
2228 $content = $textbox_content; // do not try to merge here!
2229 } elseif ( $this->isConflict
) {
2231 if ( $this->mergeChangesIntoContent( $content ) ) {
2232 // Successful merge! Maybe we should tell the user the good news?
2233 $this->isConflict
= false;
2234 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2236 $this->section
= '';
2237 $this->textbox1
= ContentHandler
::getContentText( $content );
2238 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2242 if ( $this->isConflict
) {
2243 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2247 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2251 if ( $this->section
== 'new' ) {
2252 // Handle the user preference to force summaries here
2253 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2254 $this->missingSummary
= true;
2255 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2256 $status->value
= self
::AS_SUMMARY_NEEDED
;
2260 // Do not allow the user to post an empty comment
2261 if ( $this->textbox1
== '' ) {
2262 $this->missingComment
= true;
2263 $status->fatal( 'missingcommenttext' );
2264 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2267 } elseif ( !$this->allowBlankSummary
2268 && !$content->equals( $this->getOriginalContent( $user ) )
2269 && !$content->isRedirect()
2270 && md5( $this->summary
) == $this->autoSumm
2272 $this->missingSummary
= true;
2273 $status->fatal( 'missingsummary' );
2274 $status->value
= self
::AS_SUMMARY_NEEDED
;
2279 $sectionanchor = '';
2280 if ( $this->section
== 'new' ) {
2281 $this->summary
= $this->newSectionSummary( $sectionanchor );
2282 } elseif ( $this->section
!= '' ) {
2283 # Try to get a section anchor from the section source, redirect
2284 # to edited section if header found.
2285 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2286 # for duplicate heading checking and maybe parsing.
2287 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2288 # We can't deal with anchors, includes, html etc in the header for now,
2289 # headline would need to be parsed to improve this.
2290 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2291 $sectionanchor = $this->guessSectionName( $matches[2] );
2294 $result['sectionanchor'] = $sectionanchor;
2296 // Save errors may fall down to the edit form, but we've now
2297 // merged the section into full text. Clear the section field
2298 // so that later submission of conflict forms won't try to
2299 // replace that into a duplicated mess.
2300 $this->textbox1
= $this->toEditText( $content );
2301 $this->section
= '';
2303 $status->value
= self
::AS_SUCCESS_UPDATE
;
2306 if ( !$this->allowSelfRedirect
2307 && $content->isRedirect()
2308 && $content->getRedirectTarget()->equals( $this->getTitle() )
2310 // If the page already redirects to itself, don't warn.
2311 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2312 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2313 $this->selfRedirect
= true;
2314 $status->fatal( 'selfredirect' );
2315 $status->value
= self
::AS_SELF_REDIRECT
;
2320 // Check for length errors again now that the section is merged in
2321 $this->contentLength
= strlen( $this->toEditText( $content ) );
2322 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2323 $this->tooBig
= true;
2324 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2328 $flags = EDIT_AUTOSUMMARY |
2329 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2330 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2331 ( $bot ? EDIT_FORCE_BOT
: 0 );
2333 $doEditStatus = $this->page
->doEditContent(
2339 $content->getDefaultFormat(),
2344 if ( !$doEditStatus->isOK() ) {
2345 // Failure from doEdit()
2346 // Show the edit conflict page for certain recognized errors from doEdit(),
2347 // but don't show it for errors from extension hooks
2348 $errors = $doEditStatus->getErrorsArray();
2349 if ( in_array( $errors[0][0],
2350 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2352 $this->isConflict
= true;
2353 // Destroys data doEdit() put in $status->value but who cares
2354 $doEditStatus->value
= self
::AS_END
;
2356 return $doEditStatus;
2359 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2360 if ( $result['nullEdit'] ) {
2361 // We don't know if it was a null edit until now, so increment here
2362 $user->pingLimiter( 'linkpurge' );
2364 $result['redirect'] = $content->isRedirect();
2366 $this->updateWatchlist();
2368 // If the content model changed, add a log entry
2369 if ( $changingContentModel ) {
2370 $this->addContentModelChangeLogEntry(
2372 $new ?
false : $oldContentModel,
2373 $this->contentModel
,
2383 * @param string|false $oldModel false if the page is being newly created
2384 * @param string $newModel
2385 * @param string $reason
2387 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2388 $new = $oldModel === false;
2389 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2390 $log->setPerformer( $user );
2391 $log->setTarget( $this->mTitle
);
2392 $log->setComment( $reason );
2393 $log->setParameters( [
2394 '4::oldmodel' => $oldModel,
2395 '5::newmodel' => $newModel
2397 $logid = $log->insert();
2398 $log->publish( $logid );
2402 * Register the change of watch status
2404 protected function updateWatchlist() {
2405 $user = $this->context
->getUser();
2406 if ( !$user->isLoggedIn() ) {
2410 $title = $this->mTitle
;
2411 $watch = $this->watchthis
;
2412 // Do this in its own transaction to reduce contention...
2413 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2414 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2415 return; // nothing to change
2417 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2422 * Attempts to do 3-way merge of edit content with a base revision
2423 * and current content, in case of edit conflict, in whichever way appropriate
2424 * for the content type.
2428 * @param Content $editContent
2432 private function mergeChangesIntoContent( &$editContent ) {
2433 $db = wfGetDB( DB_MASTER
);
2435 // This is the revision that was current at the time editing was initiated on the client,
2436 // even if the edit was based on an old revision.
2437 $baseRevision = $this->getBaseRevision();
2438 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2440 if ( is_null( $baseContent ) ) {
2444 // The current state, we want to merge updates into it
2445 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2446 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2448 if ( is_null( $currentContent ) ) {
2452 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2454 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2457 $editContent = $result;
2458 // Update parentRevId to what we just merged.
2459 $this->parentRevId
= $currentRevision->getId();
2467 * Returns the revision that was current at the time editing was initiated on the client,
2468 * even if the edit was based on an old revision.
2470 * @warning this method is very poorly named. If the user opened the form with ?oldid=X,
2471 * one might think of X as the "base revision", which is NOT what this returns,
2472 * see oldid for that. One might further assume that this corresponds to the $baseRevId
2473 * parameter of WikiPage::doEditContent, which is not the case either.
2474 * getExpectedParentRevision() would perhaps be a better name.
2476 * @return Revision|null Current version when editing was initiated on the client
2478 public function getBaseRevision() {
2479 if ( !$this->mBaseRevision
) {
2480 $db = wfGetDB( DB_MASTER
);
2481 $this->mBaseRevision
= $this->editRevId
2482 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2483 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2485 return $this->mBaseRevision
;
2489 * Check given input text against $wgSpamRegex, and return the text of the first match.
2491 * @param string $text
2493 * @return string|bool Matching string or false
2495 public static function matchSpamRegex( $text ) {
2496 global $wgSpamRegex;
2497 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2498 $regexes = (array)$wgSpamRegex;
2499 return self
::matchSpamRegexInternal( $text, $regexes );
2503 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2505 * @param string $text
2507 * @return string|bool Matching string or false
2509 public static function matchSummarySpamRegex( $text ) {
2510 global $wgSummarySpamRegex;
2511 $regexes = (array)$wgSummarySpamRegex;
2512 return self
::matchSpamRegexInternal( $text, $regexes );
2516 * @param string $text
2517 * @param array $regexes
2518 * @return bool|string
2520 protected static function matchSpamRegexInternal( $text, $regexes ) {
2521 foreach ( $regexes as $regex ) {
2523 if ( preg_match( $regex, $text, $matches ) ) {
2530 public function setHeaders() {
2531 $out = $this->context
->getOutput();
2533 $out->addModules( 'mediawiki.action.edit' );
2534 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2535 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2537 $user = $this->context
->getUser();
2539 if ( $user->getOption( 'uselivepreview' ) ) {
2540 $out->addModules( 'mediawiki.action.edit.preview' );
2543 if ( $user->getOption( 'useeditwarning' ) ) {
2544 $out->addModules( 'mediawiki.action.edit.editWarning' );
2547 # Enabled article-related sidebar, toplinks, etc.
2548 $out->setArticleRelated( true );
2550 $contextTitle = $this->getContextTitle();
2551 if ( $this->isConflict
) {
2552 $msg = 'editconflict';
2553 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2554 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2556 $msg = $contextTitle->exists()
2557 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2558 && $contextTitle->getDefaultMessageText() !== false
2564 # Use the title defined by DISPLAYTITLE magic word when present
2565 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2566 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2567 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2568 if ( $displayTitle === false ) {
2569 $displayTitle = $contextTitle->getPrefixedText();
2571 $out->setDisplayTitle( $displayTitle );
2573 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2575 $config = $this->context
->getConfig();
2577 # Transmit the name of the message to JavaScript for live preview
2578 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2579 $out->addJsConfigVars( [
2580 'wgEditMessage' => $msg,
2581 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2584 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2586 $out->addJsConfigVars(
2587 'wgEditSubmitButtonLabelPublish',
2588 $config->get( 'EditSubmitButtonLabelPublish' )
2593 * Show all applicable editing introductions
2595 protected function showIntro() {
2596 if ( $this->suppressIntro
) {
2600 $out = $this->context
->getOutput();
2601 $namespace = $this->mTitle
->getNamespace();
2603 if ( $namespace == NS_MEDIAWIKI
) {
2604 # Show a warning if editing an interface message
2605 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2606 # If this is a default message (but not css, json, or js),
2607 # show a hint that it is translatable on translatewiki.net
2609 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2610 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2611 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2613 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2614 if ( $defaultMessageText !== false ) {
2615 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2616 'translateinterface' );
2619 } elseif ( $namespace == NS_FILE
) {
2620 # Show a hint to shared repo
2621 $file = MediaWikiServices
::getInstance()->getRepoGroup()->findFile( $this->mTitle
);
2622 if ( $file && !$file->isLocal() ) {
2623 $descUrl = $file->getDescriptionUrl();
2624 # there must be a description url to show a hint to shared repo
2626 if ( !$this->mTitle
->exists() ) {
2627 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2628 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2631 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2632 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2639 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2640 # Show log extract when the user is currently blocked
2641 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2642 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2643 $user = User
::newFromName( $username, false /* allow IP users */ );
2644 $ip = User
::isIP( $username );
2645 $block = DatabaseBlock
::newFromTarget( $user, $user );
2646 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2647 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2648 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2650 !is_null( $block ) &&
2651 $block->getType() != DatabaseBlock
::TYPE_AUTO
&&
2652 ( $block->isSitewide() ||
$user->isBlockedFrom( $this->mTitle
) )
2654 // Show log extract if the user is sitewide blocked or is partially
2655 // blocked and not allowed to edit their user page or user talk page
2656 LogEventsList
::showLogExtract(
2659 MediaWikiServices
::getInstance()->getNamespaceInfo()->
2660 getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2664 'showIfEmpty' => false,
2666 'blocked-notice-logextract',
2667 $user->getName() # Support GENDER in notice
2673 # Try to add a custom edit intro, or use the standard one if this is not possible.
2674 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2675 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2676 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2678 if ( $this->context
->getUser()->isLoggedIn() ) {
2680 // Suppress the external link icon, consider the help url an internal one
2681 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2689 // Suppress the external link icon, consider the help url an internal one
2690 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2692 'newarticletextanon',
2698 # Give a notice if the user is editing a deleted/moved page...
2699 if ( !$this->mTitle
->exists() ) {
2700 $dbr = wfGetDB( DB_REPLICA
);
2702 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2706 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2707 'showIfEmpty' => false,
2708 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2715 * Attempt to show a custom editing introduction, if supplied
2719 protected function showCustomIntro() {
2720 if ( $this->editintro
) {
2721 $title = Title
::newFromText( $this->editintro
);
2722 if ( $this->isPageExistingAndViewable( $title, $this->context
->getUser() ) ) {
2723 // Added using template syntax, to take <noinclude>'s into account.
2724 $this->context
->getOutput()->addWikiTextAsContent(
2725 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2736 * Gets an editable textual representation of $content.
2737 * The textual representation can be turned by into a Content object by the
2738 * toEditContent() method.
2740 * If $content is null or false or a string, $content is returned unchanged.
2742 * If the given Content object is not of a type that can be edited using
2743 * the text base EditPage, an exception will be raised. Set
2744 * $this->allowNonTextContent to true to allow editing of non-textual
2747 * @param Content|null|bool|string $content
2748 * @return string|false|null The editable text form of the content.
2750 * @throws MWException If $content is not an instance of TextContent and
2751 * $this->allowNonTextContent is not true.
2753 protected function toEditText( $content ) {
2754 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2758 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2759 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2762 return $content->serialize( $this->contentFormat
);
2766 * Turns the given text into a Content object by unserializing it.
2768 * If the resulting Content object is not of a type that can be edited using
2769 * the text base EditPage, an exception will be raised. Set
2770 * $this->allowNonTextContent to true to allow editing of non-textual
2773 * @param string|null|bool $text Text to unserialize
2774 * @return Content|bool|null The content object created from $text. If $text was false
2775 * or null, then false or null will be returned instead.
2777 * @throws MWException If unserializing the text results in a Content
2778 * object that is not an instance of TextContent and
2779 * $this->allowNonTextContent is not true.
2781 protected function toEditContent( $text ) {
2782 if ( $text === false ||
$text === null ) {
2786 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2787 $this->contentModel
, $this->contentFormat
);
2789 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2790 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2797 * Send the edit form and related headers to OutputPage
2798 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2799 * during form output near the top, for captchas and the like.
2801 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2802 * use the EditPage::showEditForm:fields hook instead.
2804 public function showEditForm( $formCallback = null ) {
2805 # need to parse the preview early so that we know which templates are used,
2806 # otherwise users with "show preview after edit box" will get a blank list
2807 # we parse this near the beginning so that setHeaders can do the title
2808 # setting work instead of leaving it in getPreviewText
2809 $previewOutput = '';
2810 if ( $this->formtype
== 'preview' ) {
2811 $previewOutput = $this->getPreviewText();
2814 $out = $this->context
->getOutput();
2816 // Avoid PHP 7.1 warning of passing $this by reference
2818 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2820 $this->setHeaders();
2822 $this->addTalkPageText();
2823 $this->addEditNotices();
2825 if ( !$this->isConflict
&&
2826 $this->section
!= '' &&
2827 !$this->isSectionEditSupported() ) {
2828 // We use $this->section to much before this and getVal('wgSection') directly in other places
2829 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2830 // Someone is welcome to try refactoring though
2831 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2835 $this->showHeader();
2837 $out->addHTML( $this->editFormPageTop
);
2839 $user = $this->context
->getUser();
2840 if ( $user->getOption( 'previewontop' ) ) {
2841 $this->displayPreviewArea( $previewOutput, true );
2844 $out->addHTML( $this->editFormTextTop
);
2846 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
!== 'save' ) {
2847 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2848 'deletedwhileediting' );
2851 // @todo add EditForm plugin interface and use it here!
2852 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2853 $out->addHTML( Html
::openElement(
2856 'class' => 'mw-editform',
2857 'id' => self
::EDITFORM_ID
,
2858 'name' => self
::EDITFORM_ID
,
2860 'action' => $this->getActionURL( $this->getContextTitle() ),
2861 'enctype' => 'multipart/form-data'
2865 if ( is_callable( $formCallback ) ) {
2866 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2867 call_user_func_array( $formCallback, [ &$out ] );
2870 // Add a check for Unicode support
2871 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2873 // Add an empty field to trip up spambots
2875 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2878 [ 'for' => 'wpAntispam' ],
2879 $this->context
->msg( 'simpleantispam-label' )->parse()
2885 'name' => 'wpAntispam',
2886 'id' => 'wpAntispam',
2890 . Xml
::closeElement( 'div' )
2893 // Avoid PHP 7.1 warning of passing $this by reference
2895 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2897 // Put these up at the top to ensure they aren't lost on early form submission
2898 $this->showFormBeforeText();
2900 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2901 $username = $this->lastDelete
->user_name
;
2902 $comment = CommentStore
::getStore()
2903 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2905 // It is better to not parse the comment at all than to have templates expanded in the middle
2906 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2907 $key = $comment === ''
2908 ?
'confirmrecreate-noreason'
2909 : 'confirmrecreate';
2911 '<div class="mw-confirm-recreate">' .
2912 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2913 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2914 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2920 # When the summary is hidden, also hide them on preview/show changes
2921 if ( $this->nosummary
) {
2922 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2925 # If a blank edit summary was previously provided, and the appropriate
2926 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2927 # user being bounced back more than once in the event that a summary
2930 # For a bit more sophisticated detection of blank summaries, hash the
2931 # automatic one and pass that in the hidden field wpAutoSummary.
2932 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2933 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2936 if ( $this->undidRev
) {
2937 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2940 if ( $this->selfRedirect
) {
2941 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2944 if ( $this->hasPresetSummary
) {
2945 // If a summary has been preset using &summary= we don't want to prompt for
2946 // a different summary. Only prompt for a summary if the summary is blanked.
2948 $this->autoSumm
= md5( '' );
2951 $autosumm = $this->autoSumm
!== '' ?
$this->autoSumm
: md5( $this->summary
);
2952 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2954 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2955 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2957 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2958 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2962 if ( $this->section
== 'new' ) {
2963 $this->showSummaryInput( true, $this->summary
);
2964 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2967 $out->addHTML( $this->editFormTextBeforeContent
);
2968 if ( $this->isConflict
) {
2969 // In an edit conflict, we turn textbox2 into the user's text,
2970 // and textbox1 into the stored version
2971 $this->textbox2
= $this->textbox1
;
2973 $content = $this->getCurrentContent();
2974 $this->textbox1
= $this->toEditText( $content );
2976 $editConflictHelper = $this->getEditConflictHelper();
2977 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2978 $editConflictHelper->setContentModel( $this->contentModel
);
2979 $editConflictHelper->setContentFormat( $this->contentFormat
);
2980 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2983 if ( !$this->mTitle
->isUserConfigPage() ) {
2984 $out->addHTML( self
::getEditToolbar() );
2987 if ( $this->blankArticle
) {
2988 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2991 if ( $this->isConflict
) {
2992 // In an edit conflict bypass the overridable content form method
2993 // and fallback to the raw wpTextbox1 since editconflicts can't be
2994 // resolved between page source edits and custom ui edits using the
2996 $conflictTextBoxAttribs = [];
2997 if ( $this->wasDeletedSinceLastEdit() ) {
2998 $conflictTextBoxAttribs['style'] = 'display:none;';
2999 } elseif ( $this->isOldRev
) {
3000 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
3003 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
3004 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
3006 $this->showContentForm();
3009 $out->addHTML( $this->editFormTextAfterContent
);
3011 $this->showStandardInputs();
3013 $this->showFormAfterText();
3015 $this->showTosSummary();
3017 $this->showEditTools();
3019 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
3021 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
3023 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
3024 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
3026 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
3027 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
3029 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
3031 if ( $this->isConflict
) {
3033 $this->showConflict();
3034 } catch ( MWContentSerializationException
$ex ) {
3035 // this can't really happen, but be nice if it does.
3036 $msg = $this->context
->msg(
3037 'content-failed-to-parse',
3038 $this->contentModel
,
3039 $this->contentFormat
,
3042 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3046 // Set a hidden field so JS knows what edit form mode we are in
3047 if ( $this->isConflict
) {
3049 } elseif ( $this->preview
) {
3051 } elseif ( $this->diff
) {
3056 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
3058 // Marker for detecting truncated form data. This must be the last
3059 // parameter sent in order to be of use, so do not move me.
3060 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
3061 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
3063 if ( !$user->getOption( 'previewontop' ) ) {
3064 $this->displayPreviewArea( $previewOutput, false );
3069 * Wrapper around TemplatesOnThisPageFormatter to make
3070 * a "templates on this page" list.
3072 * @param Title[] $templates
3073 * @return string HTML
3075 public function makeTemplatesOnThisPageList( array $templates ) {
3076 $templateListFormatter = new TemplatesOnThisPageFormatter(
3077 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
3080 // preview if preview, else section if section, else false
3082 if ( $this->preview
) {
3084 } elseif ( $this->section
!= '' ) {
3088 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
3089 $templateListFormatter->format( $templates, $type )
3094 * Extract the section title from current section text, if any.
3096 * @param string $text
3097 * @return string|bool String or false
3099 public static function extractSectionTitle( $text ) {
3100 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
3101 if ( !empty( $matches[2] ) ) {
3102 return MediaWikiServices
::getInstance()->getParser()
3103 ->stripSectionName( trim( $matches[2] ) );
3109 protected function showHeader() {
3110 $out = $this->context
->getOutput();
3111 $user = $this->context
->getUser();
3112 if ( $this->isConflict
) {
3113 $this->addExplainConflictHeader( $out );
3114 $this->editRevId
= $this->page
->getLatest();
3116 if ( $this->section
!= '' && $this->section
!= 'new' && !$this->summary
&&
3117 !$this->preview
&& !$this->diff
3119 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
3120 if ( $sectionTitle !== false ) {
3121 $this->summary
= "/* $sectionTitle */ ";
3125 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
3127 if ( $this->missingComment
) {
3128 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3131 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
3133 "<div id='mw-missingsummary'>\n$1\n</div>",
3134 [ 'missingsummary', $buttonLabel ]
3138 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3140 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3141 [ 'missingcommentheader', $buttonLabel ]
3145 if ( $this->blankArticle
) {
3147 "<div id='mw-blankarticle'>\n$1\n</div>",
3148 [ 'blankarticle', $buttonLabel ]
3152 if ( $this->selfRedirect
) {
3154 "<div id='mw-selfredirect'>\n$1\n</div>",
3155 [ 'selfredirect', $buttonLabel ]
3159 if ( $this->hookError
!== '' ) {
3160 $out->addWikiTextAsInterface( $this->hookError
);
3163 if ( $this->section
!= 'new' ) {
3164 $revision = $this->mArticle
->getRevisionFetched();
3166 // Let sysop know that this will make private content public if saved
3168 if ( !$revision->userCan( RevisionRecord
::DELETED_TEXT
, $user ) ) {
3170 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3171 'rev-deleted-text-permission'
3173 } elseif ( $revision->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
3175 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3176 'rev-deleted-text-view'
3180 if ( !$revision->isCurrent() ) {
3181 $this->mArticle
->setOldSubtitle( $revision->getId() );
3183 Html
::warningBox( "\n$1\n" ),
3186 $this->isOldRev
= true;
3188 } elseif ( $this->mTitle
->exists() ) {
3189 // Something went wrong
3191 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3192 [ 'missing-revision', $this->oldid
] );
3197 if ( wfReadOnly() ) {
3199 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3200 [ 'readonlywarning', wfReadOnlyReason() ]
3202 } elseif ( $user->isAnon() ) {
3203 if ( $this->formtype
!= 'preview' ) {
3204 $returntoquery = array_diff_key(
3205 $this->context
->getRequest()->getValues(),
3206 [ 'title' => true, 'returnto' => true, 'returntoquery' => true ]
3209 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3210 [ 'anoneditwarning',
3212 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3213 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3214 'returntoquery' => wfArrayToCgi( $returntoquery ),
3217 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3218 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3219 'returntoquery' => wfArrayToCgi( $returntoquery ),
3224 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3225 'anonpreviewwarning'
3228 } elseif ( $this->mTitle
->isUserConfigPage() ) {
3229 # Check the skin exists
3230 if ( $this->isWrongCaseUserConfigPage() ) {
3232 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3233 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3236 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3237 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3238 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3239 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3241 $warning = $isUserCssConfig
3243 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3245 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3247 if ( $this->formtype
!== 'preview' ) {
3248 $config = $this->context
->getConfig();
3249 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3251 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3252 [ 'usercssyoucanpreview' ]
3254 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3256 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3257 [ 'userjsonyoucanpreview' ]
3259 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3261 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3262 [ 'userjsyoucanpreview' ]
3269 $this->addPageProtectionWarningHeaders();
3271 $this->addLongPageWarningHeader();
3273 # Add header copyright warning
3274 $this->showHeaderCopyrightWarning();
3278 * Helper function for summary input functions, which returns the necessary
3279 * attributes for the input.
3281 * @param array|null $inputAttrs Array of attrs to use on the input
3284 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3285 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3286 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3287 // Unicode codepoints.
3288 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3289 'id' => 'wpSummary',
3290 'name' => 'wpSummary',
3291 'maxlength' => CommentStore
::COMMENT_CHARACTER_LIMIT
,
3294 'spellcheck' => 'true',
3299 * Builds a standard summary input with a label.
3301 * @param string $summary The value of the summary input
3302 * @param string|null $labelText The html to place inside the label
3303 * @param array|null $inputAttrs Array of attrs to use on the input
3305 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3307 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3308 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3309 $this->getSummaryInputAttributes( $inputAttrs )
3312 'title' => Linker
::titleAttrib( 'summary' ),
3313 'accessKey' => Linker
::accesskey( 'summary' ),
3316 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3317 $inputAttrs['inputId'] = $inputAttrs['id'];
3318 $inputAttrs['id'] = 'wpSummaryWidget';
3320 return new OOUI\
FieldLayout(
3321 new OOUI\
TextInputWidget( [
3322 'value' => $summary,
3323 'infusable' => true,
3326 'label' => new OOUI\
HtmlSnippet( $labelText ),
3328 'id' => 'wpSummaryLabel',
3329 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3335 * @param bool $isSubjectPreview True if this is the section subject/title
3336 * up top, or false if this is the comment summary
3337 * down below the textarea
3338 * @param string $summary The text of the summary to display
3340 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3341 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3342 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3343 if ( $isSubjectPreview ) {
3344 if ( $this->nosummary
) {
3347 } elseif ( !$this->mShowSummaryField
) {
3351 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3352 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3355 [ 'class' => $summaryClass ]
3360 * @param bool $isSubjectPreview True if this is the section subject/title
3361 * up top, or false if this is the comment summary
3362 * down below the textarea
3363 * @param string $summary The text of the summary to display
3366 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3367 // avoid spaces in preview, gets always trimmed on save
3368 $summary = trim( $summary );
3369 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3373 if ( $isSubjectPreview ) {
3374 $summary = $this->context
->msg( 'newsectionsummary' )
3375 ->rawParams( MediaWikiServices
::getInstance()->getParser()
3376 ->stripSectionName( $summary ) )
3377 ->inContentLanguage()->text();
3380 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3382 $summary = $this->context
->msg( $message )->parse()
3383 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3384 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3387 protected function showFormBeforeText() {
3388 $out = $this->context
->getOutput();
3389 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3390 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3391 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3392 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3393 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3396 protected function showFormAfterText() {
3398 * To make it harder for someone to slip a user a page
3399 * which submits an edit form to the wiki without their
3400 * knowledge, a random token is associated with the login
3401 * session. If it's not passed back with the submission,
3402 * we won't save the page, or render user JavaScript and
3405 * For anon editors, who may not have a session, we just
3406 * include the constant suffix to prevent editing from
3407 * broken text-mangling proxies.
3409 $this->context
->getOutput()->addHTML(
3411 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3417 * Subpage overridable method for printing the form for page content editing
3418 * By default this simply outputs wpTextbox1
3419 * Subclasses can override this to provide a custom UI for editing;
3420 * be it a form, or simply wpTextbox1 with a modified content that will be
3421 * reverse modified when extracted from the post data.
3422 * Note that this is basically the inverse for importContentFormData
3424 protected function showContentForm() {
3425 $this->showTextbox1();
3429 * Method to output wpTextbox1
3430 * The $textoverride method can be used by subclasses overriding showContentForm
3431 * to pass back to this method.
3433 * @param array|null $customAttribs Array of html attributes to use in the textarea
3434 * @param string|null $textoverride Optional text to override $this->textarea1 with
3436 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3437 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3438 $attribs = [ 'style' => 'display:none;' ];
3440 $builder = new TextboxBuilder();
3441 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3443 # Is an old revision being edited?
3444 if ( $this->isOldRev
) {
3445 $classes[] = 'mw-textarea-oldrev';
3448 $attribs = [ 'tabindex' => 1 ];
3450 if ( is_array( $customAttribs ) ) {
3451 $attribs +
= $customAttribs;
3454 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3458 $textoverride ??
$this->textbox1
,
3464 protected function showTextbox2() {
3465 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3468 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3469 $builder = new TextboxBuilder();
3470 $attribs = $builder->buildTextboxAttribs(
3473 $this->context
->getUser(),
3477 $this->context
->getOutput()->addHTML(
3478 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3482 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3485 $classes[] = 'ontop';
3488 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3490 if ( $this->formtype
!= 'preview' ) {
3491 $attribs['style'] = 'display: none;';
3494 $out = $this->context
->getOutput();
3495 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3497 if ( $this->formtype
== 'preview' ) {
3498 $this->showPreview( $previewOutput );
3500 // Empty content container for LivePreview
3501 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3502 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3503 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3504 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3507 $out->addHTML( '</div>' );
3509 if ( $this->formtype
== 'diff' ) {
3512 } catch ( MWContentSerializationException
$ex ) {
3513 $msg = $this->context
->msg(
3514 'content-failed-to-parse',
3515 $this->contentModel
,
3516 $this->contentFormat
,
3519 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3525 * Append preview output to OutputPage.
3526 * Includes category rendering if this is a category page.
3528 * @param string $text The HTML to be output for the preview.
3530 protected function showPreview( $text ) {
3531 if ( $this->mArticle
instanceof CategoryPage
) {
3532 $this->mArticle
->openShowCategory();
3534 # This hook seems slightly odd here, but makes things more
3535 # consistent for extensions.
3536 $out = $this->context
->getOutput();
3537 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3538 $out->addHTML( $text );
3539 if ( $this->mArticle
instanceof CategoryPage
) {
3540 $this->mArticle
->closeShowCategory();
3545 * Get a diff between the current contents of the edit box and the
3546 * version of the page we're editing from.
3548 * If this is a section edit, we'll replace the section as for final
3549 * save and then make a comparison.
3551 public function showDiff() {
3552 $oldtitlemsg = 'currentrev';
3553 # if message does not exist, show diff against the preloaded default
3554 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3555 $oldtext = $this->mTitle
->getDefaultMessageText();
3556 if ( $oldtext !== false ) {
3557 $oldtitlemsg = 'defaultmessagetext';
3558 $oldContent = $this->toEditContent( $oldtext );
3563 $oldContent = $this->getCurrentContent();
3566 $textboxContent = $this->toEditContent( $this->textbox1
);
3567 if ( $this->editRevId
!== null ) {
3568 $newContent = $this->page
->replaceSectionAtRev(
3569 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3572 $newContent = $this->page
->replaceSectionContent(
3573 $this->section
, $textboxContent, $this->summary
, $this->edittime
3577 if ( $newContent ) {
3578 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3580 $user = $this->context
->getUser();
3581 $popts = ParserOptions
::newFromUserAndLang( $user,
3582 MediaWikiServices
::getInstance()->getContentLanguage() );
3583 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3586 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3587 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3588 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3590 if ( !$oldContent ) {
3591 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3594 if ( !$newContent ) {
3595 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3598 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3599 $de->setContent( $oldContent, $newContent );
3601 $difftext = $de->getDiff( $oldtitle, $newtitle );
3602 $de->showDiffStyle();
3607 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3611 * Show the header copyright warning.
3613 protected function showHeaderCopyrightWarning() {
3614 $msg = 'editpage-head-copy-warn';
3615 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3616 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3617 'editpage-head-copy-warn' );
3622 * Give a chance for site and per-namespace customizations of
3623 * terms of service summary link that might exist separately
3624 * from the copyright notice.
3626 * This will display between the save button and the edit tools,
3627 * so should remain short!
3629 protected function showTosSummary() {
3630 $msg = 'editpage-tos-summary';
3631 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3632 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3633 $out = $this->context
->getOutput();
3634 $out->addHTML( '<div class="mw-tos-summary">' );
3635 $out->addWikiMsg( $msg );
3636 $out->addHTML( '</div>' );
3641 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3642 * characters not present on most keyboards for copying/pasting.
3644 protected function showEditTools() {
3645 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3646 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3651 * Get the copyright warning
3653 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3656 protected function getCopywarn() {
3657 return self
::getCopyrightWarning( $this->mTitle
);
3661 * Get the copyright warning, by default returns wikitext
3663 * @param Title $title
3664 * @param string $format Output format, valid values are any function of a Message object
3665 * @param Language|string|null $langcode Language code or Language object.
3668 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3669 global $wgRightsText;
3670 if ( $wgRightsText ) {
3671 $copywarnMsg = [ 'copyrightwarning',
3672 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3675 $copywarnMsg = [ 'copyrightwarning2',
3676 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3678 // Allow for site and per-namespace customization of contribution/copyright notice.
3679 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3681 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3683 $msg->inLanguage( $langcode );
3685 return "<div id=\"editpage-copywarn\">\n" .
3686 $msg->$format() . "\n</div>";
3690 * Get the Limit report for page previews
3693 * @param ParserOutput|null $output ParserOutput object from the parse
3694 * @return string HTML
3696 public static function getPreviewLimitReport( ParserOutput
$output = null ) {
3699 if ( !$output ||
!$output->getLimitReportData() ) {
3703 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3704 wfMessage( 'limitreport-title' )->parseAsBlock()
3707 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3708 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3710 $limitReport .= Html
::openElement( 'table', [
3711 'class' => 'preview-limit-report wikitable'
3713 Html
::openElement( 'tbody' );
3715 foreach ( $output->getLimitReportData() as $key => $value ) {
3716 if ( Hooks
::run( 'ParserLimitReportFormat',
3717 [ $key, &$value, &$limitReport, true, true ]
3719 $keyMsg = wfMessage( $key );
3720 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3721 if ( !$valueMsg->exists() ) {
3722 $valueMsg = new RawMessage( '$1' );
3724 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3725 $limitReport .= Html
::openElement( 'tr' ) .
3726 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3727 Html
::rawElement( 'td', null,
3728 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3730 Html
::closeElement( 'tr' );
3735 $limitReport .= Html
::closeElement( 'tbody' ) .
3736 Html
::closeElement( 'table' ) .
3737 Html
::closeElement( 'div' );
3739 return $limitReport;
3742 protected function showStandardInputs( &$tabindex = 2 ) {
3743 $out = $this->context
->getOutput();
3744 $out->addHTML( "<div class='editOptions'>\n" );
3746 if ( $this->section
!= 'new' ) {
3747 $this->showSummaryInput( false, $this->summary
);
3748 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3751 $checkboxes = $this->getCheckboxesWidget(
3753 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3755 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3757 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3759 // Show copyright warning.
3760 $out->addWikiTextAsInterface( $this->getCopywarn() );
3761 $out->addHTML( $this->editFormTextAfterWarn
);
3763 $out->addHTML( "<div class='editButtons'>\n" );
3764 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3766 $cancel = $this->getCancelLink();
3768 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3769 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3772 $this->context
->msg( 'edithelp' )->text(),
3773 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3776 $this->context
->msg( 'word-separator' )->escaped() .
3777 $this->context
->msg( 'newwindow' )->parse();
3779 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3780 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3781 $out->addHTML( "</div><!-- editButtons -->\n" );
3783 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3785 $out->addHTML( "</div><!-- editOptions -->\n" );
3789 * Show an edit conflict. textbox1 is already shown in showEditForm().
3790 * If you want to use another entry point to this function, be careful.
3792 protected function showConflict() {
3793 $out = $this->context
->getOutput();
3794 // Avoid PHP 7.1 warning of passing $this by reference
3796 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3797 $this->incrementConflictStats();
3799 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3803 protected function incrementConflictStats() {
3804 $this->getEditConflictHelper()->incrementConflictStats();
3810 public function getCancelLink() {
3812 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3813 $cancelParams['oldid'] = $this->oldid
;
3814 } elseif ( $this->getContextTitle()->isRedirect() ) {
3815 $cancelParams['redirect'] = 'no';
3818 return new OOUI\
ButtonWidget( [
3819 'id' => 'mw-editform-cancel',
3820 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3821 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3823 'infusable' => true,
3824 'flags' => 'destructive',
3829 * Returns the URL to use in the form's action attribute.
3830 * This is used by EditPage subclasses when simply customizing the action
3831 * variable in the constructor is not enough. This can be used when the
3832 * EditPage lives inside of a Special page rather than a custom page action.
3834 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3837 protected function getActionURL( Title
$title ) {
3838 return $title->getLocalURL( [ 'action' => $this->action
] );
3842 * Check if a page was deleted while the user was editing it, before submit.
3843 * Note that we rely on the logging table, which hasn't been always there,
3844 * but that doesn't matter, because this only applies to brand new
3848 protected function wasDeletedSinceLastEdit() {
3849 if ( $this->deletedSinceEdit
!== null ) {
3850 return $this->deletedSinceEdit
;
3853 $this->deletedSinceEdit
= false;
3855 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3856 $this->lastDelete
= $this->getLastDelete();
3857 if ( $this->lastDelete
) {
3858 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3859 if ( $deleteTime > $this->starttime
) {
3860 $this->deletedSinceEdit
= true;
3865 return $this->deletedSinceEdit
;
3869 * Get the last log record of this page being deleted, if ever. This is
3870 * used to detect whether a delete occurred during editing.
3871 * @return bool|stdClass
3873 protected function getLastDelete() {
3874 $dbr = wfGetDB( DB_REPLICA
);
3875 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3876 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3877 $data = $dbr->selectRow(
3878 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3888 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3890 'log_namespace' => $this->mTitle
->getNamespace(),
3891 'log_title' => $this->mTitle
->getDBkey(),
3892 'log_type' => 'delete',
3893 'log_action' => 'delete',
3896 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3898 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3899 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3901 // Quick paranoid permission checks...
3902 if ( is_object( $data ) ) {
3903 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3904 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3907 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3908 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3909 $data->log_comment_data
= null;
3917 * Get the rendered text for previewing.
3918 * @throws MWException
3921 public function getPreviewText() {
3922 $out = $this->context
->getOutput();
3923 $config = $this->context
->getConfig();
3925 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3926 // Could be an offsite preview attempt. This is very unsafe if
3927 // HTML is enabled, as it could be an attack.
3929 if ( $this->textbox1
!== '' ) {
3930 // Do not put big scary notice, if previewing the empty
3931 // string, which happens when you initially edit
3932 // a category page, due to automatic preview-on-open.
3933 $parsedNote = Html
::rawElement( 'div', [ 'class' => 'previewnote' ],
3934 $out->parseAsInterface(
3935 $this->context
->msg( 'session_fail_preview_html' )->plain()
3938 $this->incrementEditFailureStats( 'session_loss' );
3945 $content = $this->toEditContent( $this->textbox1
);
3949 'AlternateEditPreview',
3950 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3952 return $previewHTML;
3955 # provide a anchor link to the editform
3956 $continueEditing = '<span class="mw-continue-editing">' .
3957 '[[#' . self
::EDITFORM_ID
. '|' .
3958 $this->context
->getLanguage()->getArrow() . ' ' .
3959 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3960 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3961 if ( $this->mTokenOkExceptSuffix
) {
3962 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3963 $this->incrementEditFailureStats( 'bad_token' );
3965 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3966 $this->incrementEditFailureStats( 'session_loss' );
3968 } elseif ( $this->incompleteForm
) {
3969 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3970 if ( $this->mTriedSave
) {
3971 $this->incrementEditFailureStats( 'incomplete_form' );
3974 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3977 # don't parse non-wikitext pages, show message about preview
3978 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3979 if ( $this->mTitle
->isUserConfigPage() ) {
3981 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3987 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3989 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3992 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3994 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3997 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3999 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
4006 # Used messages to make sure grep find them:
4007 # Messages: usercsspreview, userjsonpreview, userjspreview,
4008 # sitecsspreview, sitejsonpreview, sitejspreview
4009 if ( $level && $format ) {
4010 $note = "<div id='mw-{$level}{$format}preview'>" .
4011 $this->context
->msg( "{$level}{$format}preview" )->plain() .
4012 ' ' . $continueEditing . "</div>";
4016 # If we're adding a comment, we need to show the
4017 # summary as the headline
4018 if ( $this->section
=== "new" && $this->summary
!== "" ) {
4019 $content = $content->addSectionHeader( $this->summary
);
4022 $hook_args = [ $this, &$content ];
4023 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
4025 $parserResult = $this->doPreviewParse( $content );
4026 $parserOutput = $parserResult['parserOutput'];
4027 $previewHTML = $parserResult['html'];
4028 $this->mParserOutput
= $parserOutput;
4029 $out->addParserOutputMetadata( $parserOutput );
4030 if ( $out->userCanPreview() ) {
4031 $out->addContentOverride( $this->getTitle(), $content );
4034 if ( count( $parserOutput->getWarnings() ) ) {
4035 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
4038 } catch ( MWContentSerializationException
$ex ) {
4039 $m = $this->context
->msg(
4040 'content-failed-to-parse',
4041 $this->contentModel
,
4042 $this->contentFormat
,
4045 $note .= "\n\n" . $m->plain(); # gets parsed down below
4049 if ( $this->isConflict
) {
4050 $conflict = Html
::rawElement(
4051 'div', [ 'id' => 'mw-previewconflict', 'class' => 'warningbox' ],
4052 $this->context
->msg( 'previewconflict' )->escaped()
4058 $previewhead = Html
::rawElement(
4059 'div', [ 'class' => 'previewnote' ],
4061 'h2', [ 'id' => 'mw-previewheader' ],
4062 $this->context
->msg( 'preview' )->escaped()
4064 Html
::rawElement( 'div', [ 'class' => 'warningbox' ],
4065 $out->parseAsInterface( $note )
4069 $pageViewLang = $this->mTitle
->getPageViewLanguage();
4070 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
4071 'class' => 'mw-content-' . $pageViewLang->getDir() ];
4072 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
4074 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
4077 private function incrementEditFailureStats( $failureType ) {
4078 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
4079 $stats->increment( 'edit.failures.' . $failureType );
4083 * Get parser options for a preview
4084 * @return ParserOptions
4086 protected function getPreviewParserOptions() {
4087 $parserOptions = $this->page
->makeParserOptions( $this->context
);
4088 $parserOptions->setIsPreview( true );
4089 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
4090 $parserOptions->enableLimitReport();
4092 // XXX: we could call $parserOptions->setCurrentRevisionCallback here to force the
4093 // current revision to be null during PST, until setupFakeRevision is called on
4094 // the ParserOptions. Currently, we rely on Parser::getRevisionObject() to ignore
4095 // existing revisions in preview mode.
4097 return $parserOptions;
4101 * Parse the page for a preview. Subclasses may override this class, in order
4102 * to parse with different options, or to otherwise modify the preview HTML.
4104 * @param Content $content The page content
4105 * @return array with keys:
4106 * - parserOutput: The ParserOutput object
4107 * - html: The HTML to be displayed
4109 protected function doPreviewParse( Content
$content ) {
4110 $user = $this->context
->getUser();
4111 $parserOptions = $this->getPreviewParserOptions();
4113 // NOTE: preSaveTransform doesn't have a fake revision to operate on.
4114 // Parser::getRevisionObject() will return null in preview mode,
4115 // causing the context user to be used for {{subst:REVISIONUSER}}.
4116 // XXX: Alternatively, we could also call setupFakeRevision() a second time:
4117 // once before PST with $content, and then after PST with $pstContent.
4118 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
4119 $scopedCallback = $parserOptions->setupFakeRevision( $this->mTitle
, $pstContent, $user );
4120 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
4121 ScopedCallback
::consume( $scopedCallback );
4123 'parserOutput' => $parserOutput,
4124 'html' => $parserOutput->getText( [
4125 'enableSectionEditLinks' => false
4133 public function getTemplates() {
4134 if ( $this->preview ||
$this->section
!= '' ) {
4136 if ( !isset( $this->mParserOutput
) ) {
4139 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
4140 foreach ( array_keys( $template ) as $dbk ) {
4141 $templates[] = Title
::makeTitle( $ns, $dbk );
4146 return $this->mTitle
->getTemplateLinksFrom();
4151 * Allow extensions to provide a toolbar.
4153 * @return string|null
4155 public static function getEditToolbar() {
4156 $startingToolbar = '<div id="toolbar"></div>';
4157 $toolbar = $startingToolbar;
4159 if ( !Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4162 // Don't add a pointless `<div>` to the page unless a hook caller populated it
4163 return ( $toolbar === $startingToolbar ) ?
null : $toolbar;
4167 * Return an array of checkbox definitions.
4169 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4171 * Array values are associative arrays with the following keys:
4172 * - 'label-message' (required): message for label text
4173 * - 'id' (required): 'id' attribute for the `<input>`
4174 * - 'default' (required): default checkedness (true or false)
4175 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4176 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4177 * from messages like 'tooltip-foo', 'accesskey-foo'
4178 * - 'label-id' (optional): 'id' attribute for the `<label>`
4179 * - 'legacy-name' (optional): short name for backwards-compatibility
4180 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4181 * where bool indicates the checked status of the checkbox
4184 public function getCheckboxesDefinition( $checked ) {
4187 $user = $this->context
->getUser();
4188 // don't show the minor edit checkbox if it's a new page or section
4189 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
4190 if ( !$this->isNew
&& $permissionManager->userHasRight( $user, 'minoredit' ) ) {
4191 $checkboxes['wpMinoredit'] = [
4192 'id' => 'wpMinoredit',
4193 'label-message' => 'minoredit',
4194 // Uses messages: tooltip-minoredit, accesskey-minoredit
4195 'tooltip' => 'minoredit',
4196 'label-id' => 'mw-editpage-minoredit',
4197 'legacy-name' => 'minor',
4198 'default' => $checked['minor'],
4202 if ( $user->isLoggedIn() ) {
4203 $checkboxes['wpWatchthis'] = [
4204 'id' => 'wpWatchthis',
4205 'label-message' => 'watchthis',
4206 // Uses messages: tooltip-watch, accesskey-watch
4207 'tooltip' => 'watch',
4208 'label-id' => 'mw-editpage-watch',
4209 'legacy-name' => 'watch',
4210 'default' => $checked['watch'],
4215 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4221 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4222 * any other added by extensions.
4224 * @param int &$tabindex Current tabindex
4225 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4226 * status of the checkbox
4228 * @return array Associative array of string keys to OOUI\FieldLayout instances
4230 public function getCheckboxesWidget( &$tabindex, $checked ) {
4232 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4234 foreach ( $checkboxesDef as $name => $options ) {
4235 $legacyName = $options['legacy-name'] ??
$name;
4239 if ( isset( $options['tooltip'] ) ) {
4240 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4241 $title = Linker
::titleAttrib( $options['tooltip'] );
4243 if ( isset( $options['title-message'] ) ) {
4244 $title = $this->context
->msg( $options['title-message'] )->text();
4247 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4248 new OOUI\
CheckboxInputWidget( [
4249 'tabIndex' => ++
$tabindex,
4250 'accessKey' => $accesskey,
4251 'id' => $options['id'] . 'Widget',
4252 'inputId' => $options['id'],
4254 'selected' => $options['default'],
4255 'infusable' => true,
4258 'align' => 'inline',
4259 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4261 'id' => $options['label-id'] ??
null,
4270 * Get the message key of the label for the button to save the page
4275 protected function getSubmitButtonLabel() {
4277 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4279 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4280 $newPage = !$this->mTitle
->exists();
4282 if ( $labelAsPublish ) {
4283 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4285 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4288 return $buttonLabelKey;
4292 * Returns an array of html code of the following buttons:
4293 * save, diff and preview
4295 * @param int &$tabindex Current tabindex
4299 public function getEditButtons( &$tabindex ) {
4303 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4305 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4306 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4308 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4310 'tabIndex' => ++
$tabindex,
4311 'id' => 'wpSaveWidget',
4312 'inputId' => 'wpSave',
4313 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4314 'useInputTag' => true,
4315 'flags' => [ 'progressive', 'primary' ],
4316 'label' => $buttonLabel,
4317 'infusable' => true,
4319 // Messages used: tooltip-save, tooltip-publish
4320 'title' => Linker
::titleAttrib( $buttonTooltip ),
4321 // Messages used: accesskey-save, accesskey-publish
4322 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4325 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4326 'name' => 'wpPreview',
4327 'tabIndex' => ++
$tabindex,
4328 'id' => 'wpPreviewWidget',
4329 'inputId' => 'wpPreview',
4330 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4331 'useInputTag' => true,
4332 'label' => $this->context
->msg( 'showpreview' )->text(),
4333 'infusable' => true,
4335 // Message used: tooltip-preview
4336 'title' => Linker
::titleAttrib( 'preview' ),
4337 // Message used: accesskey-preview
4338 'accessKey' => Linker
::accesskey( 'preview' ),
4341 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4343 'tabIndex' => ++
$tabindex,
4344 'id' => 'wpDiffWidget',
4345 'inputId' => 'wpDiff',
4346 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4347 'useInputTag' => true,
4348 'label' => $this->context
->msg( 'showdiff' )->text(),
4349 'infusable' => true,
4351 // Message used: tooltip-diff
4352 'title' => Linker
::titleAttrib( 'diff' ),
4353 // Message used: accesskey-diff
4354 'accessKey' => Linker
::accesskey( 'diff' ),
4357 // Avoid PHP 7.1 warning of passing $this by reference
4359 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4365 * Creates a basic error page which informs the user that
4366 * they have attempted to edit a nonexistent section.
4368 public function noSuchSectionPage() {
4369 $out = $this->context
->getOutput();
4370 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4372 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4374 // Avoid PHP 7.1 warning of passing $this by reference
4376 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4377 $out->addHTML( $res );
4379 $out->returnToMain( false, $this->mTitle
);
4383 * Show "your edit contains spam" page with your diff and text
4385 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4387 public function spamPageWithContent( $match = false ) {
4388 $this->textbox2
= $this->textbox1
;
4390 if ( is_array( $match ) ) {
4391 $match = $this->context
->getLanguage()->listToText( $match );
4393 $out = $this->context
->getOutput();
4394 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4396 $out->addHTML( '<div id="spamprotected">' );
4397 $out->addWikiMsg( 'spamprotectiontext' );
4399 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4401 $out->addHTML( '</div>' );
4403 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4406 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4407 $this->showTextbox2();
4409 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4415 protected function addEditNotices() {
4416 $out = $this->context
->getOutput();
4417 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4418 if ( count( $editNotices ) ) {
4419 $out->addHTML( implode( "\n", $editNotices ) );
4421 $msg = $this->context
->msg( 'editnotice-notext' );
4422 if ( !$msg->isDisabled() ) {
4424 '<div class="mw-editnotice-notext">'
4425 . $msg->parseAsBlock()
4435 protected function addTalkPageText() {
4436 if ( $this->mTitle
->isTalkPage() ) {
4437 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4444 protected function addLongPageWarningHeader() {
4445 if ( $this->contentLength
=== false ) {
4446 $this->contentLength
= strlen( $this->textbox1
);
4449 $out = $this->context
->getOutput();
4450 $lang = $this->context
->getLanguage();
4451 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4452 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4453 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4456 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4457 $lang->formatNum( $maxArticleSize )
4460 } elseif ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4461 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4464 $lang->formatSize( strlen( $this->textbox1
) ),
4465 strlen( $this->textbox1
)
4474 protected function addPageProtectionWarningHeaders() {
4475 $out = $this->context
->getOutput();
4476 if ( $this->mTitle
->isProtected( 'edit' ) &&
4477 MediaWikiServices
::getInstance()->getPermissionManager()->getNamespaceRestrictionLevels(
4478 $this->getTitle()->getNamespace()
4481 # Is the title semi-protected?
4482 if ( $this->mTitle
->isSemiProtected() ) {
4483 $noticeMsg = 'semiprotectedpagewarning';
4485 # Then it must be protected based on static groups (regular)
4486 $noticeMsg = 'protectedpagewarning';
4488 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4489 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4491 if ( $this->mTitle
->isCascadeProtected() ) {
4492 # Is this page under cascading protection from some source pages?
4493 /** @var Title[] $cascadeSources */
4494 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4495 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4496 $cascadeSourcesCount = count( $cascadeSources );
4497 if ( $cascadeSourcesCount > 0 ) {
4498 # Explain, and list the titles responsible
4499 foreach ( $cascadeSources as $page ) {
4500 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4503 $notice .= '</div>';
4504 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4506 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4507 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4509 'showIfEmpty' => false,
4510 'msgKey' => [ 'titleprotectedwarning' ],
4511 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4516 * @param OutputPage $out
4519 protected function addExplainConflictHeader( OutputPage
$out ) {
4521 $this->getEditConflictHelper()->getExplainHeader()
4526 * @param string $name
4527 * @param mixed[] $customAttribs
4532 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4533 return ( new TextboxBuilder() )->buildTextboxAttribs(
4534 $name, $customAttribs, $user, $this->mTitle
4539 * @param string $wikitext
4543 protected function addNewLineAtEnd( $wikitext ) {
4544 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4548 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4549 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4550 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4551 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4552 * spread the new style links more efficiently.
4554 * @param string $text
4557 private function guessSectionName( $text ) {
4558 // Detect Microsoft browsers
4559 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4560 $parser = MediaWikiServices
::getInstance()->getParser();
4561 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4562 // ...and redirect them to legacy encoding, if available
4563 return $parser->guessLegacySectionNameFromWikiText( $text );
4565 // Meanwhile, real browsers get real anchors
4566 $name = $parser->guessSectionNameFromWikiText( $text );
4567 // With one little caveat: per T216029, fragments in HTTP redirects need to be urlencoded,
4568 // otherwise Chrome double-escapes the rest of the URL.
4569 return '#' . urlencode( mb_substr( $name, 1 ) );
4573 * Set a factory function to create an EditConflictHelper
4575 * @param callable $factory Factory function
4578 public function setEditConflictHelperFactory( callable
$factory ) {
4579 $this->editConflictHelperFactory
= $factory;
4580 $this->editConflictHelper
= null;
4584 * @return TextConflictHelper
4586 private function getEditConflictHelper() {
4587 if ( !$this->editConflictHelper
) {
4588 $this->editConflictHelper
= call_user_func(
4589 $this->editConflictHelperFactory
,
4590 $this->getSubmitButtonLabel()
4594 return $this->editConflictHelper
;
4598 * @param string $submitButtonLabel
4599 * @return TextConflictHelper
4601 private function newTextConflictHelper( $submitButtonLabel ) {
4602 return new TextConflictHelper(
4604 $this->getContext()->getOutput(),
4605 MediaWikiServices
::getInstance()->getStatsdDataFactory(),