3 * User interface for page editing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\EditPage\TextboxBuilder
;
24 use MediaWiki\EditPage\TextConflictHelper
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\ScopedCallback
;
30 * The edit page/HTML interface (split from Article)
31 * The actual database and text munging is still in Article,
32 * but it should get easier to call those from alternate
35 * EditPage cares about two distinct titles:
36 * $this->mContextTitle is the page that forms submit to, links point to,
37 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
38 * page in the database that is actually being edited. These are
39 * usually the same, but they are now allowed to be different.
41 * Surgeon General's Warning: prolonged exposure to this class is known to cause
42 * headaches, which may be fatal.
46 * Used for Unicode support checks
48 const UNICODE_CHECK
= 'β³π²β₯πππΎπΈβ΄πΉβ―';
51 * Status: Article successfully updated
53 const AS_SUCCESS_UPDATE
= 200;
56 * Status: Article successfully created
58 const AS_SUCCESS_NEW_ARTICLE
= 201;
61 * Status: Article update aborted by a hook function
63 const AS_HOOK_ERROR
= 210;
66 * Status: A hook function returned an error
68 const AS_HOOK_ERROR_EXPECTED
= 212;
71 * Status: User is blocked from editing this page
73 const AS_BLOCKED_PAGE_FOR_USER
= 215;
76 * Status: Content too big (> $wgMaxArticleSize)
78 const AS_CONTENT_TOO_BIG
= 216;
81 * Status: this anonymous user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_ANON
= 218;
86 * Status: this logged in user is not allowed to edit this page
88 const AS_READ_ONLY_PAGE_LOGGED
= 219;
91 * Status: wiki is in readonly mode (wfReadOnly() == true)
93 const AS_READ_ONLY_PAGE
= 220;
96 * Status: rate limiter for action 'edit' was tripped
98 const AS_RATE_LIMITED
= 221;
101 * Status: article was deleted while editing and param wpRecreate == false or form
104 const AS_ARTICLE_WAS_DELETED
= 222;
107 * Status: user tried to create this page, but is not allowed to do that
108 * ( Title->userCan('create') == false )
110 const AS_NO_CREATE_PERMISSION
= 223;
113 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
115 const AS_BLANK_ARTICLE
= 224;
118 * Status: (non-resolvable) edit conflict
120 const AS_CONFLICT_DETECTED
= 225;
123 * Status: no edit summary given and the user has forceeditsummary set and the user is not
124 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
126 const AS_SUMMARY_NEEDED
= 226;
129 * Status: user tried to create a new section without content
131 const AS_TEXTBOX_EMPTY
= 228;
134 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
136 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
139 * Status: WikiPage::doEdit() was unsuccessful
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
146 const AS_SPAM_ERROR
= 232;
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
151 const AS_IMAGE_REDIRECT_ANON
= 233;
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
156 const AS_IMAGE_REDIRECT_LOGGED
= 234;
159 * Status: user tried to modify the content model, but is not allowed to do that
160 * ( User::isAllowed('editcontentmodel') == false )
162 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
165 * Status: user tried to create self-redirect (redirect to the same article) and
166 * wpIgnoreSelfRedirect == false
168 const AS_SELF_REDIRECT
= 236;
171 * Status: an error relating to change tagging. Look at the message key for
174 const AS_CHANGE_TAG_ERROR
= 237;
177 * Status: can't parse content
179 const AS_PARSE_ERROR
= 240;
182 * Status: when changing the content model is disallowed due to
183 * $wgContentHandlerUseDB being false
185 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
188 * Status: edit rejected because browser doesn't support Unicode.
190 const AS_UNICODE_NOT_SUPPORTED
= 242;
193 * HTML id and name for the beginning of the edit form.
195 const EDITFORM_ID
= 'editform';
198 * Prefix of key for cookie used to pass post-edit state.
199 * The revision id edited is added after this
201 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
204 * Duration of PostEdit cookie, in seconds.
205 * The cookie will be removed instantly if the JavaScript runs.
207 * Otherwise, though, we don't want the cookies to accumulate.
208 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
209 * limit of only 20 cookies per domain. This still applies at least to some
210 * versions of IE without full updates:
211 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
213 * A value of 20 minutes should be enough to take into account slow loads and minor
214 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
216 const POST_EDIT_COOKIE_DURATION
= 1200;
219 * @deprecated for public usage since 1.30 use EditPage::getArticle()
227 * @deprecated for public usage since 1.30 use EditPage::getTitle()
232 /** @var null|Title */
233 private $mContextTitle = null;
236 public $action = 'submit';
239 public $isConflict = false;
241 /** @var bool New page or new section */
242 public $isNew = false;
245 public $deletedSinceEdit;
253 /** @var bool|stdClass */
257 public $mTokenOk = false;
260 public $mTokenOkExceptSuffix = false;
263 public $mTriedSave = false;
266 public $incompleteForm = false;
269 public $tooBig = false;
272 public $missingComment = false;
275 public $missingSummary = false;
278 public $allowBlankSummary = false;
281 protected $blankArticle = false;
284 protected $allowBlankArticle = false;
287 protected $selfRedirect = false;
290 protected $allowSelfRedirect = false;
293 public $autoSumm = '';
296 public $hookError = '';
298 /** @var ParserOutput */
299 public $mParserOutput;
301 /** @var bool Has a summary been preset using GET parameter &summary= ? */
302 public $hasPresetSummary = false;
304 /** @var Revision|bool|null */
305 public $mBaseRevision = false;
308 public $mShowSummaryField = true;
313 public $save = false;
316 public $preview = false;
319 public $diff = false;
322 public $minoredit = false;
325 public $watchthis = false;
328 public $recreate = false;
331 public $textbox1 = '';
334 public $textbox2 = '';
337 public $summary = '';
340 public $nosummary = false;
343 public $edittime = '';
346 private $editRevId = null;
349 public $section = '';
352 public $sectiontitle = '';
355 public $starttime = '';
361 public $parentRevId = 0;
364 public $editintro = '';
367 public $scrolltop = null;
373 public $contentModel;
375 /** @var null|string */
376 public $contentFormat = null;
378 /** @var null|array */
379 private $changeTags = null;
381 # Placeholders for text injection by hooks (must be HTML)
382 # extensions should take care to _append_ to the present value
384 /** @var string Before even the preview */
385 public $editFormPageTop = '';
386 public $editFormTextTop = '';
387 public $editFormTextBeforeContent = '';
388 public $editFormTextAfterWarn = '';
389 public $editFormTextAfterTools = '';
390 public $editFormTextBottom = '';
391 public $editFormTextAfterContent = '';
392 public $previewTextAfterContent = '';
393 public $mPreloadContent = null;
395 /* $didSave should be set to true whenever an article was successfully altered. */
396 public $didSave = false;
397 public $undidRev = 0;
399 public $suppressIntro = false;
405 protected $contentLength = false;
408 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
410 private $enableApiEditOverride = false;
413 * @var IContextSource
418 * @var bool Whether an old revision is edited
420 private $isOldRev = false;
423 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
425 private $unicodeCheck;
428 * Factory function to create an edit conflict helper
432 private $editConflictHelperFactory;
435 * @var TextConflictHelper|null
437 private $editConflictHelper;
440 * @param Article $article
442 public function __construct( Article
$article ) {
443 $this->mArticle
= $article;
444 $this->page
= $article->getPage(); // model object
445 $this->mTitle
= $article->getTitle();
446 $this->context
= $article->getContext();
448 $this->contentModel
= $this->mTitle
->getContentModel();
450 $handler = ContentHandler
::getForModelID( $this->contentModel
);
451 $this->contentFormat
= $handler->getDefaultFormat();
452 $this->editConflictHelperFactory
= [ $this, 'newTextConflictHelper' ];
458 public function getArticle() {
459 return $this->mArticle
;
464 * @return IContextSource
466 public function getContext() {
467 return $this->context
;
474 public function getTitle() {
475 return $this->mTitle
;
479 * Set the context Title object
481 * @param Title|null $title Title object or null
483 public function setContextTitle( $title ) {
484 $this->mContextTitle
= $title;
488 * Get the context title object.
490 * If not set, $wgTitle will be returned, but this is deprecated. This will
491 * throw an exception.
495 public function getContextTitle() {
496 if ( is_null( $this->mContextTitle
) ) {
497 wfDeprecated( __METHOD__
. ' called with no title set', '1.32' );
501 return $this->mContextTitle
;
506 * Returns if the given content model is editable.
508 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
510 * @throws MWException If $modelId has no known handler
512 public function isSupportedContentModel( $modelId ) {
513 return $this->enableApiEditOverride
=== true ||
514 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
518 * Allow editing of content that supports API direct editing, but not general
519 * direct editing. Set to false by default.
521 * @param bool $enableOverride
523 public function setApiEditOverride( $enableOverride ) {
524 $this->enableApiEditOverride
= $enableOverride;
528 * @deprecated since 1.29, call edit directly
530 public function submit() {
531 wfDeprecated( __METHOD__
, '1.29' );
536 * This is the function that gets called for "action=edit". It
537 * sets up various member variables, then passes execution to
538 * another function, usually showEditForm()
540 * The edit form is self-submitting, so that when things like
541 * preview and edit conflicts occur, we get the same form back
542 * with the extra stuff added. Only when the final submission
543 * is made and all is well do we actually save and redirect to
544 * the newly-edited page.
546 public function edit() {
547 // Allow extensions to modify/prevent this form or submission
548 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
552 wfDebug( __METHOD__
. ": enter\n" );
554 $request = $this->context
->getRequest();
555 // If they used redlink=1 and the page exists, redirect to the main article
556 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
557 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
561 $this->importFormData( $request );
562 $this->firsttime
= false;
564 if ( wfReadOnly() && $this->save
) {
567 $this->preview
= true;
571 $this->formtype
= 'save';
572 } elseif ( $this->preview
) {
573 $this->formtype
= 'preview';
574 } elseif ( $this->diff
) {
575 $this->formtype
= 'diff';
576 } else { # First time through
577 $this->firsttime
= true;
578 if ( $this->previewOnOpen() ) {
579 $this->formtype
= 'preview';
581 $this->formtype
= 'initial';
585 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
587 wfDebug( __METHOD__
. ": User can't edit\n" );
589 // track block with a cookie if it doesn't exists already
590 $this->context
->getUser()->trackBlockWithCookie();
592 // Auto-block user's IP if the account was "hard" blocked
593 if ( !wfReadOnly() ) {
594 DeferredUpdates
::addCallableUpdate( function () {
595 $this->context
->getUser()->spreadAnyEditBlock();
598 $this->displayPermissionsError( $permErrors );
603 $revision = $this->mArticle
->getRevisionFetched();
604 // Disallow editing revisions with content models different from the current one
605 // Undo edits being an exception in order to allow reverting content model changes.
607 && $revision->getContentModel() !== $this->contentModel
610 if ( $this->undidRev
) {
611 $undidRevObj = Revision
::newFromId( $this->undidRev
);
612 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
614 if ( !$this->undidRev
616 ||
$prevRev->getContentModel() !== $this->contentModel
618 $this->displayViewSourcePage(
619 $this->getContentObject(),
621 'contentmodelediterror',
622 $revision->getContentModel(),
630 $this->isConflict
= false;
632 # Show applicable editing introductions
633 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
637 # Attempt submission here. This will check for edit conflicts,
638 # and redundantly check for locked database, blocked IPs, etc.
639 # that edit() already checked just in case someone tries to sneak
640 # in the back door with a hand-edited submission URL.
642 if ( 'save' == $this->formtype
) {
643 $resultDetails = null;
644 $status = $this->attemptSave( $resultDetails );
645 if ( !$this->handleStatus( $status, $resultDetails ) ) {
650 # First time through: get contents, set time for conflict
652 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
653 if ( $this->initialiseForm() === false ) {
654 $this->noSuchSectionPage();
658 if ( !$this->mTitle
->getArticleID() ) {
659 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
661 Hooks
::run( 'EditFormInitialText', [ $this ] );
666 $this->showEditForm();
670 * @param string $rigor Same format as Title::getUserPermissionErrors()
673 protected function getEditPermissionErrors( $rigor = 'secure' ) {
674 $user = $this->context
->getUser();
675 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
676 # Can this title be created?
677 if ( !$this->mTitle
->exists() ) {
678 $permErrors = array_merge(
681 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
686 # Ignore some permissions errors when a user is just previewing/viewing diffs
688 foreach ( $permErrors as $error ) {
689 if ( ( $this->preview ||
$this->diff
)
691 $error[0] == 'blockedtext' ||
692 $error[0] == 'autoblockedtext' ||
693 $error[0] == 'systemblockedtext'
699 $permErrors = wfArrayDiff2( $permErrors, $remove );
705 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
706 * but with the following differences:
707 * - If redlink=1, the user will be redirected to the page
708 * - If there is content to display or the error occurs while either saving,
709 * previewing or showing the difference, it will be a
710 * "View source for ..." page displaying the source code after the error message.
713 * @param array $permErrors Array of permissions errors, as returned by
714 * Title::getUserPermissionsErrors().
715 * @throws PermissionsError
717 protected function displayPermissionsError( array $permErrors ) {
718 $out = $this->context
->getOutput();
719 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
720 // The edit page was reached via a red link.
721 // Redirect to the article page and let them click the edit tab if
722 // they really want a permission error.
723 $out->redirect( $this->mTitle
->getFullURL() );
727 $content = $this->getContentObject();
729 # Use the normal message if there's nothing to display
730 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
731 $action = $this->mTitle
->exists() ?
'edit' :
732 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
733 throw new PermissionsError( $action, $permErrors );
736 $this->displayViewSourcePage(
738 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
743 * Display a read-only View Source page
744 * @param Content $content
745 * @param string $errorMessage additional wikitext error message to display
747 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
748 $out = $this->context
->getOutput();
749 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
751 $out->setRobotPolicy( 'noindex,nofollow' );
752 $out->setPageTitle( $this->context
->msg(
754 $this->getContextTitle()->getPrefixedText()
756 $out->addBacklinkSubtitle( $this->getContextTitle() );
757 $out->addHTML( $this->editFormPageTop
);
758 $out->addHTML( $this->editFormTextTop
);
760 if ( $errorMessage !== '' ) {
761 $out->addWikiText( $errorMessage );
762 $out->addHTML( "<hr />\n" );
765 # If the user made changes, preserve them when showing the markup
766 # (This happens when a user is blocked during edit, for instance)
767 if ( !$this->firsttime
) {
768 $text = $this->textbox1
;
769 $out->addWikiMsg( 'viewyourtext' );
772 $text = $this->toEditText( $content );
773 } catch ( MWException
$e ) {
774 # Serialize using the default format if the content model is not supported
775 # (e.g. for an old revision with a different model)
776 $text = $content->serialize();
778 $out->addWikiMsg( 'viewsourcetext' );
781 $out->addHTML( $this->editFormTextBeforeContent
);
782 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
783 $out->addHTML( $this->editFormTextAfterContent
);
785 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
787 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
789 $out->addHTML( $this->editFormTextBottom
);
790 if ( $this->mTitle
->exists() ) {
791 $out->returnToMain( null, $this->mTitle
);
796 * Should we show a preview when the edit form is first shown?
800 protected function previewOnOpen() {
801 $config = $this->context
->getConfig();
802 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
803 $request = $this->context
->getRequest();
804 if ( $config->get( 'RawHtml' ) ) {
805 // If raw HTML is enabled, disable preview on open
806 // since it has to be posted with a token for
810 if ( $request->getVal( 'preview' ) == 'yes' ) {
811 // Explicit override from request
813 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
814 // Explicit override from request
816 } elseif ( $this->section
== 'new' ) {
817 // Nothing *to* preview for new sections
819 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
820 && $this->context
->getUser()->getOption( 'previewonfirst' )
822 // Standard preference behavior
824 } elseif ( !$this->mTitle
->exists()
825 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
826 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
828 // Categories are special
836 * Checks whether the user entered a skin name in uppercase,
837 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
841 protected function isWrongCaseUserConfigPage() {
842 if ( $this->mTitle
->isUserConfigPage() ) {
843 $name = $this->mTitle
->getSkinFromConfigSubpage();
844 $skins = array_merge(
845 array_keys( Skin
::getSkinNames() ),
848 return !in_array( $name, $skins )
849 && in_array( strtolower( $name ), $skins );
856 * Returns whether section editing is supported for the current page.
857 * Subclasses may override this to replace the default behavior, which is
858 * to check ContentHandler::supportsSections.
860 * @return bool True if this edit page supports sections, false otherwise.
862 protected function isSectionEditSupported() {
863 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
864 return $contentHandler->supportsSections();
868 * This function collects the form data and uses it to populate various member variables.
869 * @param WebRequest &$request
870 * @throws ErrorPageError
872 public function importFormData( &$request ) {
873 # Section edit can come from either the form or a link
874 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
876 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
877 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
880 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
882 if ( $request->wasPosted() ) {
883 # These fields need to be checked for encoding.
884 # Also remove trailing whitespace, but don't remove _initial_
885 # whitespace from the text boxes. This may be significant formatting.
886 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
887 if ( !$request->getCheck( 'wpTextbox2' ) ) {
888 // Skip this if wpTextbox2 has input, it indicates that we came
889 // from a conflict page with raw page text, not a custom form
890 // modified by subclasses
891 $textbox1 = $this->importContentFormData( $request );
892 if ( $textbox1 !== null ) {
893 $this->textbox1
= $textbox1;
897 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
899 $this->summary
= $request->getText( 'wpSummary' );
901 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
902 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
904 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
906 # Treat sectiontitle the same way as summary.
907 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
908 # currently doing double duty as both edit summary and section title. Right now this
909 # is just to allow API edits to work around this limitation, but this should be
910 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
911 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
912 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
914 $this->edittime
= $request->getVal( 'wpEdittime' );
915 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
916 $this->starttime
= $request->getVal( 'wpStarttime' );
918 $undidRev = $request->getInt( 'wpUndidRevision' );
920 $this->undidRev
= $undidRev;
923 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
925 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
926 // wpTextbox1 field is missing, possibly due to being "too big"
927 // according to some filter rules such as Suhosin's setting for
928 // suhosin.request.max_value_length (d'oh)
929 $this->incompleteForm
= true;
931 // If we receive the last parameter of the request, we can fairly
932 // claim the POST request has not been truncated.
934 // TODO: softened the check for cutover. Once we determine
935 // that it is safe, we should complete the transition by
936 // removing the "edittime" clause.
937 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
938 && is_null( $this->edittime
) );
940 if ( $this->incompleteForm
) {
941 # If the form is incomplete, force to preview.
942 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
943 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
944 $this->preview
= true;
946 $this->preview
= $request->getCheck( 'wpPreview' );
947 $this->diff
= $request->getCheck( 'wpDiff' );
949 // Remember whether a save was requested, so we can indicate
950 // if we forced preview due to session failure.
951 $this->mTriedSave
= !$this->preview
;
953 if ( $this->tokenOk( $request ) ) {
954 # Some browsers will not report any submit button
955 # if the user hits enter in the comment box.
956 # The unmarked state will be assumed to be a save,
957 # if the form seems otherwise complete.
958 wfDebug( __METHOD__
. ": Passed token check.\n" );
959 } elseif ( $this->diff
) {
960 # Failed token check, but only requested "Show Changes".
961 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
963 # Page might be a hack attempt posted from
964 # an external site. Preview instead of saving.
965 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
966 $this->preview
= true;
969 $this->save
= !$this->preview
&& !$this->diff
;
970 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
971 $this->edittime
= null;
974 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
975 $this->starttime
= null;
978 $this->recreate
= $request->getCheck( 'wpRecreate' );
980 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
981 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
983 $user = $this->context
->getUser();
984 # Don't force edit summaries when a user is editing their own user or talk page
985 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
986 && $this->mTitle
->getText() == $user->getName()
988 $this->allowBlankSummary
= true;
990 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
991 ||
!$user->getOption( 'forceeditsummary' );
994 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
996 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
997 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
999 $changeTags = $request->getVal( 'wpChangeTags' );
1000 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1001 $this->changeTags
= [];
1003 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1007 # Not a posted form? Start with nothing.
1008 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1009 $this->textbox1
= '';
1010 $this->summary
= '';
1011 $this->sectiontitle
= '';
1012 $this->edittime
= '';
1013 $this->editRevId
= null;
1014 $this->starttime
= wfTimestampNow();
1015 $this->edit
= false;
1016 $this->preview
= false;
1017 $this->save
= false;
1018 $this->diff
= false;
1019 $this->minoredit
= false;
1020 // Watch may be overridden by request parameters
1021 $this->watchthis
= $request->getBool( 'watchthis', false );
1022 $this->recreate
= false;
1024 // When creating a new section, we can preload a section title by passing it as the
1025 // preloadtitle parameter in the URL (T15100)
1026 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1027 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1028 // Once wpSummary isn't being use for setting section titles, we should delete this.
1029 $this->summary
= $request->getVal( 'preloadtitle' );
1030 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1031 $this->summary
= $request->getText( 'summary' );
1032 if ( $this->summary
!== '' ) {
1033 $this->hasPresetSummary
= true;
1037 if ( $request->getVal( 'minor' ) ) {
1038 $this->minoredit
= true;
1042 $this->oldid
= $request->getInt( 'oldid' );
1043 $this->parentRevId
= $request->getInt( 'parentRevId' );
1045 $this->bot
= $request->getBool( 'bot', true );
1046 $this->nosummary
= $request->getBool( 'nosummary' );
1048 // May be overridden by revision.
1049 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1050 // May be overridden by revision.
1051 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1054 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1055 } catch ( MWUnknownContentModelException
$e ) {
1056 throw new ErrorPageError(
1057 'editpage-invalidcontentmodel-title',
1058 'editpage-invalidcontentmodel-text',
1059 [ wfEscapeWikiText( $this->contentModel
) ]
1063 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1064 throw new ErrorPageError(
1065 'editpage-notsupportedcontentformat-title',
1066 'editpage-notsupportedcontentformat-text',
1068 wfEscapeWikiText( $this->contentFormat
),
1069 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1075 * @todo Check if the desired model is allowed in this namespace, and if
1076 * a transition from the page's current model to the new model is
1080 $this->editintro
= $request->getText( 'editintro',
1081 // Custom edit intro for new sections
1082 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1084 // Allow extensions to modify form data
1085 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1089 * Subpage overridable method for extracting the page content data from the
1090 * posted form to be placed in $this->textbox1, if using customized input
1091 * this method should be overridden and return the page text that will be used
1092 * for saving, preview parsing and so on...
1094 * @param WebRequest &$request
1095 * @return string|null
1097 protected function importContentFormData( &$request ) {
1098 return; // Don't do anything, EditPage already extracted wpTextbox1
1102 * Initialise form fields in the object
1103 * Called on the first invocation, e.g. when a user clicks an edit link
1104 * @return bool If the requested section is valid
1106 public function initialiseForm() {
1107 $this->edittime
= $this->page
->getTimestamp();
1108 $this->editRevId
= $this->page
->getLatest();
1110 $content = $this->getContentObject( false ); # TODO: track content object?!
1111 if ( $content === false ) {
1114 $this->textbox1
= $this->toEditText( $content );
1116 $user = $this->context
->getUser();
1117 // activate checkboxes if user wants them to be always active
1118 # Sort out the "watch" checkbox
1119 if ( $user->getOption( 'watchdefault' ) ) {
1121 $this->watchthis
= true;
1122 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1124 $this->watchthis
= true;
1125 } elseif ( $user->isWatched( $this->mTitle
) ) {
1127 $this->watchthis
= true;
1129 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1130 $this->minoredit
= true;
1132 if ( $this->textbox1
=== false ) {
1139 * @param Content|null $def_content The default value to return
1141 * @return Content|null Content on success, $def_content for invalid sections
1145 protected function getContentObject( $def_content = null ) {
1150 $user = $this->context
->getUser();
1151 $request = $this->context
->getRequest();
1152 // For message page not locally set, use the i18n message.
1153 // For other non-existent articles, use preload text if any.
1154 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1155 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1156 # If this is a system message, get the default text.
1157 $msg = $this->mTitle
->getDefaultMessageText();
1159 $content = $this->toEditContent( $msg );
1161 if ( $content === false ) {
1162 # If requested, preload some text.
1163 $preload = $request->getVal( 'preload',
1164 // Custom preload text for new sections
1165 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1166 $params = $request->getArray( 'preloadparams', [] );
1168 $content = $this->getPreloadedContent( $preload, $params );
1170 // For existing pages, get text based on "undo" or section parameters.
1172 if ( $this->section
!= '' ) {
1173 // Get section edit text (returns $def_text for invalid sections)
1174 $orig = $this->getOriginalContent( $user );
1175 $content = $orig ?
$orig->getSection( $this->section
) : null;
1178 $content = $def_content;
1181 $undoafter = $request->getInt( 'undoafter' );
1182 $undo = $request->getInt( 'undo' );
1184 if ( $undo > 0 && $undoafter > 0 ) {
1185 $undorev = Revision
::newFromId( $undo );
1186 $oldrev = Revision
::newFromId( $undoafter );
1189 # Sanity check, make sure it's the right page,
1190 # the revisions exist and they were not deleted.
1191 # Otherwise, $content will be left as-is.
1192 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1193 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1194 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1196 if ( WikiPage
::hasDifferencesOutsideMainSlot( $undorev, $oldrev ) ) {
1197 // Cannot yet undo edits that involve anything other the main slot.
1198 $undoMsg = 'main-slot-only';
1200 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1202 if ( $content === false ) {
1203 # Warn the user that something went wrong
1204 $undoMsg = 'failure';
1208 if ( $undoMsg === null ) {
1209 $oldContent = $this->page
->getContent( Revision
::RAW
);
1210 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1211 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1212 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1213 // The undo may change content
1214 // model if its reverting the top
1215 // edit. This can result in
1216 // mismatched content model/format.
1217 $this->contentModel
= $newContent->getModel();
1218 $this->contentFormat
= $oldrev->getContentFormat();
1221 if ( $newContent->equals( $oldContent ) ) {
1222 # Tell the user that the undo results in no change,
1223 # i.e. the revisions were already undone.
1224 $undoMsg = 'nochange';
1227 # Inform the user of our success and set an automatic edit summary
1228 $undoMsg = 'success';
1230 # If we just undid one rev, use an autosummary
1231 $firstrev = $oldrev->getNext();
1232 if ( $firstrev && $firstrev->getId() == $undo ) {
1233 $userText = $undorev->getUserText();
1234 if ( $userText === '' ) {
1235 $undoSummary = $this->context
->msg(
1236 'undo-summary-username-hidden',
1238 )->inContentLanguage()->text();
1240 $undoSummary = $this->context
->msg(
1244 )->inContentLanguage()->text();
1246 if ( $this->summary
=== '' ) {
1247 $this->summary
= $undoSummary;
1249 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1250 ->inContentLanguage()->text() . $this->summary
;
1252 $this->undidRev
= $undo;
1254 $this->formtype
= 'diff';
1258 // Failed basic sanity checks.
1259 // Older revisions may have been removed since the link
1260 // was created, or we may simply have got bogus input.
1264 $out = $this->context
->getOutput();
1265 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1267 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1268 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1269 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1272 if ( $content === false ) {
1273 $content = $this->getOriginalContent( $user );
1282 * Get the content of the wanted revision, without section extraction.
1284 * The result of this function can be used to compare user's input with
1285 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1286 * to the original text of the edit.
1288 * This differs from Article::getContent() that when a missing revision is
1289 * encountered the result will be null and not the
1290 * 'missing-revision' message.
1293 * @param User $user The user to get the revision for
1294 * @return Content|null
1296 private function getOriginalContent( User
$user ) {
1297 if ( $this->section
== 'new' ) {
1298 return $this->getCurrentContent();
1300 $revision = $this->mArticle
->getRevisionFetched();
1301 if ( $revision === null ) {
1302 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1303 return $handler->makeEmptyContent();
1305 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1310 * Get the edit's parent revision ID
1312 * The "parent" revision is the ancestor that should be recorded in this
1313 * page's revision history. It is either the revision ID of the in-memory
1314 * article content, or in the case of a 3-way merge in order to rebase
1315 * across a recoverable edit conflict, the ID of the newer revision to
1316 * which we have rebased this page.
1319 * @return int Revision ID
1321 public function getParentRevId() {
1322 if ( $this->parentRevId
) {
1323 return $this->parentRevId
;
1325 return $this->mArticle
->getRevIdFetched();
1330 * Get the current content of the page. This is basically similar to
1331 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1332 * content object is returned instead of null.
1337 protected function getCurrentContent() {
1338 $rev = $this->page
->getRevision();
1339 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1341 if ( $content === false ||
$content === null ) {
1342 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1343 return $handler->makeEmptyContent();
1344 } elseif ( !$this->undidRev
) {
1345 // Content models should always be the same since we error
1346 // out if they are different before this point (in ->edit()).
1347 // The exception being, during an undo, the current revision might
1348 // differ from the prior revision.
1349 $logger = LoggerFactory
::getInstance( 'editpage' );
1350 if ( $this->contentModel
!== $rev->getContentModel() ) {
1351 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1352 'prev' => $this->contentModel
,
1353 'new' => $rev->getContentModel(),
1354 'title' => $this->getTitle()->getPrefixedDBkey(),
1355 'method' => __METHOD__
1357 $this->contentModel
= $rev->getContentModel();
1360 // Given that the content models should match, the current selected
1361 // format should be supported.
1362 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1363 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1365 'prev' => $this->contentFormat
,
1366 'new' => $rev->getContentFormat(),
1367 'title' => $this->getTitle()->getPrefixedDBkey(),
1368 'method' => __METHOD__
1370 $this->contentFormat
= $rev->getContentFormat();
1377 * Use this method before edit() to preload some content into the edit box
1379 * @param Content $content
1383 public function setPreloadedContent( Content
$content ) {
1384 $this->mPreloadContent
= $content;
1388 * Get the contents to be preloaded into the box, either set by
1389 * an earlier setPreloadText() or by loading the given page.
1391 * @param string $preload Representing the title to preload from.
1392 * @param array $params Parameters to use (interface-message style) in the preloaded text
1398 protected function getPreloadedContent( $preload, $params = [] ) {
1399 if ( !empty( $this->mPreloadContent
) ) {
1400 return $this->mPreloadContent
;
1403 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1405 if ( $preload === '' ) {
1406 return $handler->makeEmptyContent();
1409 $user = $this->context
->getUser();
1410 $title = Title
::newFromText( $preload );
1411 # Check for existence to avoid getting MediaWiki:Noarticletext
1412 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1413 // TODO: somehow show a warning to the user!
1414 return $handler->makeEmptyContent();
1417 $page = WikiPage
::factory( $title );
1418 if ( $page->isRedirect() ) {
1419 $title = $page->getRedirectTarget();
1421 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1422 // TODO: somehow show a warning to the user!
1423 return $handler->makeEmptyContent();
1425 $page = WikiPage
::factory( $title );
1428 $parserOptions = ParserOptions
::newFromUser( $user );
1429 $content = $page->getContent( Revision
::RAW
);
1432 // TODO: somehow show a warning to the user!
1433 return $handler->makeEmptyContent();
1436 if ( $content->getModel() !== $handler->getModelID() ) {
1437 $converted = $content->convert( $handler->getModelID() );
1439 if ( !$converted ) {
1440 // TODO: somehow show a warning to the user!
1441 wfDebug( "Attempt to preload incompatible content: " .
1442 "can't convert " . $content->getModel() .
1443 " to " . $handler->getModelID() );
1445 return $handler->makeEmptyContent();
1448 $content = $converted;
1451 return $content->preloadTransform( $title, $parserOptions, $params );
1455 * Make sure the form isn't faking a user's credentials.
1457 * @param WebRequest &$request
1461 public function tokenOk( &$request ) {
1462 $token = $request->getVal( 'wpEditToken' );
1463 $user = $this->context
->getUser();
1464 $this->mTokenOk
= $user->matchEditToken( $token );
1465 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1466 return $this->mTokenOk
;
1470 * Sets post-edit cookie indicating the user just saved a particular revision.
1472 * This uses a temporary cookie for each revision ID so separate saves will never
1473 * interfere with each other.
1475 * Article::view deletes the cookie on server-side after the redirect and
1476 * converts the value to the global JavaScript variable wgPostEdit.
1478 * If the variable were set on the server, it would be cached, which is unwanted
1479 * since the post-edit state should only apply to the load right after the save.
1481 * @param int $statusValue The status value (to check for new article status)
1483 protected function setPostEditCookie( $statusValue ) {
1484 $revisionId = $this->page
->getLatest();
1485 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1488 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1490 } elseif ( $this->oldid
) {
1494 $response = $this->context
->getRequest()->response();
1495 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1499 * Attempt submission
1500 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1501 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1502 * @return Status The resulting status object.
1504 public function attemptSave( &$resultDetails = false ) {
1505 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1506 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1507 // This is needed since PageUpdater no longer checks these rights!
1509 // Allow bots to exempt some edits from bot flagging
1510 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1511 $status = $this->internalAttemptSave( $resultDetails, $bot );
1513 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1519 * Log when a page was successfully saved after the edit conflict view
1521 private function incrementResolvedConflicts() {
1522 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1526 $this->getEditConflictHelper()->incrementResolvedStats();
1530 * Handle status, such as after attempt save
1532 * @param Status $status
1533 * @param array|bool $resultDetails
1535 * @throws ErrorPageError
1536 * @return bool False, if output is done, true if rest of the form should be displayed
1538 private function handleStatus( Status
$status, $resultDetails ) {
1540 * @todo FIXME: once the interface for internalAttemptSave() is made
1541 * nicer, this should use the message in $status
1543 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1544 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1546 $this->incrementResolvedConflicts();
1548 $this->didSave
= true;
1549 if ( !$resultDetails['nullEdit'] ) {
1550 $this->setPostEditCookie( $status->value
);
1554 $out = $this->context
->getOutput();
1556 // "wpExtraQueryRedirect" is a hidden input to modify
1557 // after save URL and is not used by actual edit form
1558 $request = $this->context
->getRequest();
1559 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1561 switch ( $status->value
) {
1562 case self
::AS_HOOK_ERROR_EXPECTED
:
1563 case self
::AS_CONTENT_TOO_BIG
:
1564 case self
::AS_ARTICLE_WAS_DELETED
:
1565 case self
::AS_CONFLICT_DETECTED
:
1566 case self
::AS_SUMMARY_NEEDED
:
1567 case self
::AS_TEXTBOX_EMPTY
:
1568 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1570 case self
::AS_BLANK_ARTICLE
:
1571 case self
::AS_SELF_REDIRECT
:
1574 case self
::AS_HOOK_ERROR
:
1577 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1578 case self
::AS_PARSE_ERROR
:
1579 case self
::AS_UNICODE_NOT_SUPPORTED
:
1580 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1583 case self
::AS_SUCCESS_NEW_ARTICLE
:
1584 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1585 if ( $extraQueryRedirect ) {
1586 if ( $query === '' ) {
1587 $query = $extraQueryRedirect;
1589 $query = $query . '&' . $extraQueryRedirect;
1592 $anchor = $resultDetails['sectionanchor'] ??
'';
1593 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1596 case self
::AS_SUCCESS_UPDATE
:
1598 $sectionanchor = $resultDetails['sectionanchor'];
1600 // Give extensions a chance to modify URL query on update
1602 'ArticleUpdateBeforeRedirect',
1603 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1606 if ( $resultDetails['redirect'] ) {
1607 if ( $extraQuery == '' ) {
1608 $extraQuery = 'redirect=no';
1610 $extraQuery = 'redirect=no&' . $extraQuery;
1613 if ( $extraQueryRedirect ) {
1614 if ( $extraQuery === '' ) {
1615 $extraQuery = $extraQueryRedirect;
1617 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1621 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1624 case self
::AS_SPAM_ERROR
:
1625 $this->spamPageWithContent( $resultDetails['spam'] );
1628 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1629 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1631 case self
::AS_IMAGE_REDIRECT_ANON
:
1632 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1633 throw new PermissionsError( 'upload' );
1635 case self
::AS_READ_ONLY_PAGE_ANON
:
1636 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1637 throw new PermissionsError( 'edit' );
1639 case self
::AS_READ_ONLY_PAGE
:
1640 throw new ReadOnlyError
;
1642 case self
::AS_RATE_LIMITED
:
1643 throw new ThrottledError();
1645 case self
::AS_NO_CREATE_PERMISSION
:
1646 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1647 throw new PermissionsError( $permission );
1649 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1650 throw new PermissionsError( 'editcontentmodel' );
1653 // We don't recognize $status->value. The only way that can happen
1654 // is if an extension hook aborted from inside ArticleSave.
1655 // Render the status object into $this->hookError
1656 // FIXME this sucks, we should just use the Status object throughout
1657 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1664 * Run hooks that can filter edits just before they get saved.
1666 * @param Content $content The Content to filter.
1667 * @param Status $status For reporting the outcome to the caller
1668 * @param User $user The user performing the edit
1672 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1673 // Run old style post-section-merge edit filter
1674 if ( $this->hookError
!= '' ) {
1675 # ...or the hook could be expecting us to produce an error
1676 $status->fatal( 'hookaborted' );
1677 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1681 // Run new style post-section-merge edit filter
1682 if ( !Hooks
::run( 'EditFilterMergedContent',
1683 [ $this->context
, $content, $status, $this->summary
,
1684 $user, $this->minoredit
] )
1686 # Error messages etc. could be handled within the hook...
1687 if ( $status->isGood() ) {
1688 $status->fatal( 'hookaborted' );
1689 // Not setting $this->hookError here is a hack to allow the hook
1690 // to cause a return to the edit page without $this->hookError
1691 // being set. This is used by ConfirmEdit to display a captcha
1692 // without any error message cruft.
1694 $this->hookError
= $this->formatStatusErrors( $status );
1696 // Use the existing $status->value if the hook set it
1697 if ( !$status->value
) {
1698 $status->value
= self
::AS_HOOK_ERROR
;
1701 } elseif ( !$status->isOK() ) {
1702 # ...or the hook could be expecting us to produce an error
1703 // FIXME this sucks, we should just use the Status object throughout
1704 $this->hookError
= $this->formatStatusErrors( $status );
1705 $status->fatal( 'hookaborted' );
1706 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1714 * Wrap status errors in an errorbox for increased visibility
1716 * @param Status $status
1717 * @return string Wikitext
1719 private function formatStatusErrors( Status
$status ) {
1720 $errmsg = $status->getWikiText(
1723 $this->context
->getLanguage()
1726 <div class="errorbox">
1734 * Return the summary to be used for a new section.
1736 * @param string $sectionanchor Set to the section anchor text
1739 private function newSectionSummary( &$sectionanchor = null ) {
1742 if ( $this->sectiontitle
!== '' ) {
1743 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1744 // If no edit summary was specified, create one automatically from the section
1745 // title and have it link to the new section. Otherwise, respect the summary as
1747 if ( $this->summary
=== '' ) {
1748 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1749 return $this->context
->msg( 'newsectionsummary' )
1750 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1752 } elseif ( $this->summary
!== '' ) {
1753 $sectionanchor = $this->guessSectionName( $this->summary
);
1754 # This is a new section, so create a link to the new section
1755 # in the revision summary.
1756 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1757 return $this->context
->msg( 'newsectionsummary' )
1758 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1760 return $this->summary
;
1764 * Attempt submission (no UI)
1766 * @param array &$result Array to add statuses to, currently with the
1768 * - spam (string): Spam string from content if any spam is detected by
1770 * - sectionanchor (string): Section anchor for a section save.
1771 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1773 * - redirect (bool): Set if doEditContent is OK. True if resulting
1774 * revision is a redirect.
1775 * @param bool $bot True if edit is being made under the bot right.
1777 * @return Status Status object, possibly with a message, but always with
1778 * one of the AS_* constants in $status->value,
1780 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1781 * various error display idiosyncrasies. There are also lots of cases
1782 * where error metadata is set in the object and retrieved later instead
1783 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1784 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1787 public function internalAttemptSave( &$result, $bot = false ) {
1788 $status = Status
::newGood();
1789 $user = $this->context
->getUser();
1791 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1792 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1793 $status->fatal( 'hookaborted' );
1794 $status->value
= self
::AS_HOOK_ERROR
;
1798 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1799 $status->fatal( 'unicode-support-fail' );
1800 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1804 $request = $this->context
->getRequest();
1805 $spam = $request->getText( 'wpAntispam' );
1806 if ( $spam !== '' ) {
1811 $this->mTitle
->getPrefixedText() .
1812 '" submitted bogus field "' .
1816 $status->fatal( 'spamprotectionmatch', false );
1817 $status->value
= self
::AS_SPAM_ERROR
;
1822 # Construct Content object
1823 $textbox_content = $this->toEditContent( $this->textbox1
);
1824 } catch ( MWContentSerializationException
$ex ) {
1826 'content-failed-to-parse',
1827 $this->contentModel
,
1828 $this->contentFormat
,
1831 $status->value
= self
::AS_PARSE_ERROR
;
1835 # Check image redirect
1836 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1837 $textbox_content->isRedirect() &&
1838 !$user->isAllowed( 'upload' )
1840 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1841 $status->setResult( false, $code );
1847 $match = self
::matchSummarySpamRegex( $this->summary
);
1848 if ( $match === false && $this->section
== 'new' ) {
1849 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1850 # regular summaries, it is added to the actual wikitext.
1851 if ( $this->sectiontitle
!== '' ) {
1852 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1853 $match = self
::matchSpamRegex( $this->sectiontitle
);
1855 # This branch is taken when the "Add Topic" user interface is used, or the API
1856 # is used with the 'summary' parameter.
1857 $match = self
::matchSpamRegex( $this->summary
);
1860 if ( $match === false ) {
1861 $match = self
::matchSpamRegex( $this->textbox1
);
1863 if ( $match !== false ) {
1864 $result['spam'] = $match;
1865 $ip = $request->getIP();
1866 $pdbk = $this->mTitle
->getPrefixedDBkey();
1867 $match = str_replace( "\n", '', $match );
1868 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1869 $status->fatal( 'spamprotectionmatch', $match );
1870 $status->value
= self
::AS_SPAM_ERROR
;
1875 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1877 # Error messages etc. could be handled within the hook...
1878 $status->fatal( 'hookaborted' );
1879 $status->value
= self
::AS_HOOK_ERROR
;
1881 } elseif ( $this->hookError
!= '' ) {
1882 # ...or the hook could be expecting us to produce an error
1883 $status->fatal( 'hookaborted' );
1884 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1888 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1889 // Auto-block user's IP if the account was "hard" blocked
1890 if ( !wfReadOnly() ) {
1891 $user->spreadAnyEditBlock();
1893 # Check block state against master, thus 'false'.
1894 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1898 $this->contentLength
= strlen( $this->textbox1
);
1899 $config = $this->context
->getConfig();
1900 $maxArticleSize = $config->get( 'MaxArticleSize' );
1901 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1902 // Error will be displayed by showEditForm()
1903 $this->tooBig
= true;
1904 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1908 if ( !$user->isAllowed( 'edit' ) ) {
1909 if ( $user->isAnon() ) {
1910 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1913 $status->fatal( 'readonlytext' );
1914 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1919 $changingContentModel = false;
1920 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1921 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1922 $status->fatal( 'editpage-cannot-use-custom-model' );
1923 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1925 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1926 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1929 // Make sure the user can edit the page under the new content model too
1930 $titleWithNewContentModel = clone $this->mTitle
;
1931 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1932 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1933 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1935 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1939 $changingContentModel = true;
1940 $oldContentModel = $this->mTitle
->getContentModel();
1943 if ( $this->changeTags
) {
1944 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1945 $this->changeTags
, $user );
1946 if ( !$changeTagsStatus->isOK() ) {
1947 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1948 return $changeTagsStatus;
1952 if ( wfReadOnly() ) {
1953 $status->fatal( 'readonlytext' );
1954 $status->value
= self
::AS_READ_ONLY_PAGE
;
1957 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1958 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1960 $status->fatal( 'actionthrottledtext' );
1961 $status->value
= self
::AS_RATE_LIMITED
;
1965 # If the article has been deleted while editing, don't save it without
1967 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1968 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1972 # Load the page data from the master. If anything changes in the meantime,
1973 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1974 $this->page
->loadPageData( 'fromdbmaster' );
1975 $new = !$this->page
->exists();
1978 // Late check for create permission, just in case *PARANOIA*
1979 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1980 $status->fatal( 'nocreatetext' );
1981 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1982 wfDebug( __METHOD__
. ": no create permission\n" );
1986 // Don't save a new page if it's blank or if it's a MediaWiki:
1987 // message with content equivalent to default (allow empty pages
1988 // in this case to disable messages, see T52124)
1989 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1990 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1991 $defaultText = $defaultMessageText;
1996 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1997 $this->blankArticle
= true;
1998 $status->fatal( 'blankarticle' );
1999 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
2003 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2007 $content = $textbox_content;
2009 $result['sectionanchor'] = '';
2010 if ( $this->section
== 'new' ) {
2011 if ( $this->sectiontitle
!== '' ) {
2012 // Insert the section title above the content.
2013 $content = $content->addSectionHeader( $this->sectiontitle
);
2014 } elseif ( $this->summary
!== '' ) {
2015 // Insert the section title above the content.
2016 $content = $content->addSectionHeader( $this->summary
);
2018 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2021 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2025 # Article exists. Check for edit conflict.
2027 $this->page
->clear(); # Force reload of dates, etc.
2028 $timestamp = $this->page
->getTimestamp();
2029 $latest = $this->page
->getLatest();
2031 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2033 // Check editRevId if set, which handles same-second timestamp collisions
2034 if ( $timestamp != $this->edittime
2035 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2037 $this->isConflict
= true;
2038 if ( $this->section
== 'new' ) {
2039 if ( $this->page
->getUserText() == $user->getName() &&
2040 $this->page
->getComment() == $this->newSectionSummary()
2042 // Probably a duplicate submission of a new comment.
2043 // This can happen when CDN resends a request after
2044 // a timeout but the first one actually went through.
2046 . ": duplicate new section submission; trigger edit conflict!\n" );
2048 // New comment; suppress conflict.
2049 $this->isConflict
= false;
2050 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2052 } elseif ( $this->section
== ''
2053 && Revision
::userWasLastToEdit(
2054 DB_MASTER
, $this->mTitle
->getArticleID(),
2055 $user->getId(), $this->edittime
2058 # Suppress edit conflict with self, except for section edits where merging is required.
2059 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2060 $this->isConflict
= false;
2064 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2065 if ( $this->sectiontitle
!== '' ) {
2066 $sectionTitle = $this->sectiontitle
;
2068 $sectionTitle = $this->summary
;
2073 if ( $this->isConflict
) {
2075 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2076 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2077 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2078 // ...or disable section editing for non-current revisions (not exposed anyway).
2079 if ( $this->editRevId
!== null ) {
2080 $content = $this->page
->replaceSectionAtRev(
2087 $content = $this->page
->replaceSectionContent(
2095 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2096 $content = $this->page
->replaceSectionContent(
2103 if ( is_null( $content ) ) {
2104 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2105 $this->isConflict
= true;
2106 $content = $textbox_content; // do not try to merge here!
2107 } elseif ( $this->isConflict
) {
2109 if ( $this->mergeChangesIntoContent( $content ) ) {
2110 // Successful merge! Maybe we should tell the user the good news?
2111 $this->isConflict
= false;
2112 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2114 $this->section
= '';
2115 $this->textbox1
= ContentHandler
::getContentText( $content );
2116 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2120 if ( $this->isConflict
) {
2121 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2125 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2129 if ( $this->section
== 'new' ) {
2130 // Handle the user preference to force summaries here
2131 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2132 $this->missingSummary
= true;
2133 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2134 $status->value
= self
::AS_SUMMARY_NEEDED
;
2138 // Do not allow the user to post an empty comment
2139 if ( $this->textbox1
== '' ) {
2140 $this->missingComment
= true;
2141 $status->fatal( 'missingcommenttext' );
2142 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2145 } elseif ( !$this->allowBlankSummary
2146 && !$content->equals( $this->getOriginalContent( $user ) )
2147 && !$content->isRedirect()
2148 && md5( $this->summary
) == $this->autoSumm
2150 $this->missingSummary
= true;
2151 $status->fatal( 'missingsummary' );
2152 $status->value
= self
::AS_SUMMARY_NEEDED
;
2157 $sectionanchor = '';
2158 if ( $this->section
== 'new' ) {
2159 $this->summary
= $this->newSectionSummary( $sectionanchor );
2160 } elseif ( $this->section
!= '' ) {
2161 # Try to get a section anchor from the section source, redirect
2162 # to edited section if header found.
2163 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2164 # for duplicate heading checking and maybe parsing.
2165 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2166 # We can't deal with anchors, includes, html etc in the header for now,
2167 # headline would need to be parsed to improve this.
2168 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2169 $sectionanchor = $this->guessSectionName( $matches[2] );
2172 $result['sectionanchor'] = $sectionanchor;
2174 // Save errors may fall down to the edit form, but we've now
2175 // merged the section into full text. Clear the section field
2176 // so that later submission of conflict forms won't try to
2177 // replace that into a duplicated mess.
2178 $this->textbox1
= $this->toEditText( $content );
2179 $this->section
= '';
2181 $status->value
= self
::AS_SUCCESS_UPDATE
;
2184 if ( !$this->allowSelfRedirect
2185 && $content->isRedirect()
2186 && $content->getRedirectTarget()->equals( $this->getTitle() )
2188 // If the page already redirects to itself, don't warn.
2189 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2190 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2191 $this->selfRedirect
= true;
2192 $status->fatal( 'selfredirect' );
2193 $status->value
= self
::AS_SELF_REDIRECT
;
2198 // Check for length errors again now that the section is merged in
2199 $this->contentLength
= strlen( $this->toEditText( $content ) );
2200 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2201 $this->tooBig
= true;
2202 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2206 $flags = EDIT_AUTOSUMMARY |
2207 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2208 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2209 ( $bot ? EDIT_FORCE_BOT
: 0 );
2211 $doEditStatus = $this->page
->doEditContent(
2217 $content->getDefaultFormat(),
2222 if ( !$doEditStatus->isOK() ) {
2223 // Failure from doEdit()
2224 // Show the edit conflict page for certain recognized errors from doEdit(),
2225 // but don't show it for errors from extension hooks
2226 $errors = $doEditStatus->getErrorsArray();
2227 if ( in_array( $errors[0][0],
2228 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2230 $this->isConflict
= true;
2231 // Destroys data doEdit() put in $status->value but who cares
2232 $doEditStatus->value
= self
::AS_END
;
2234 return $doEditStatus;
2237 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2238 if ( $result['nullEdit'] ) {
2239 // We don't know if it was a null edit until now, so increment here
2240 $user->pingLimiter( 'linkpurge' );
2242 $result['redirect'] = $content->isRedirect();
2244 $this->updateWatchlist();
2246 // If the content model changed, add a log entry
2247 if ( $changingContentModel ) {
2248 $this->addContentModelChangeLogEntry(
2250 $new ?
false : $oldContentModel,
2251 $this->contentModel
,
2261 * @param string|false $oldModel false if the page is being newly created
2262 * @param string $newModel
2263 * @param string $reason
2265 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2266 $new = $oldModel === false;
2267 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2268 $log->setPerformer( $user );
2269 $log->setTarget( $this->mTitle
);
2270 $log->setComment( $reason );
2271 $log->setParameters( [
2272 '4::oldmodel' => $oldModel,
2273 '5::newmodel' => $newModel
2275 $logid = $log->insert();
2276 $log->publish( $logid );
2280 * Register the change of watch status
2282 protected function updateWatchlist() {
2283 $user = $this->context
->getUser();
2284 if ( !$user->isLoggedIn() ) {
2288 $title = $this->mTitle
;
2289 $watch = $this->watchthis
;
2290 // Do this in its own transaction to reduce contention...
2291 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2292 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2293 return; // nothing to change
2295 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2300 * Attempts to do 3-way merge of edit content with a base revision
2301 * and current content, in case of edit conflict, in whichever way appropriate
2302 * for the content type.
2306 * @param Content $editContent
2310 private function mergeChangesIntoContent( &$editContent ) {
2311 $db = wfGetDB( DB_MASTER
);
2313 // This is the revision the editor started from
2314 $baseRevision = $this->getBaseRevision();
2315 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2317 if ( is_null( $baseContent ) ) {
2321 // The current state, we want to merge updates into it
2322 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2323 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2325 if ( is_null( $currentContent ) ) {
2329 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2331 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2334 $editContent = $result;
2335 // Update parentRevId to what we just merged.
2336 $this->parentRevId
= $currentRevision->getId();
2344 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2345 * one might think of X as the "base revision", which is NOT what this returns.
2346 * @return Revision|null Current version when the edit was started
2348 public function getBaseRevision() {
2349 if ( !$this->mBaseRevision
) {
2350 $db = wfGetDB( DB_MASTER
);
2351 $this->mBaseRevision
= $this->editRevId
2352 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2353 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2355 return $this->mBaseRevision
;
2359 * Check given input text against $wgSpamRegex, and return the text of the first match.
2361 * @param string $text
2363 * @return string|bool Matching string or false
2365 public static function matchSpamRegex( $text ) {
2366 global $wgSpamRegex;
2367 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2368 $regexes = (array)$wgSpamRegex;
2369 return self
::matchSpamRegexInternal( $text, $regexes );
2373 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2375 * @param string $text
2377 * @return string|bool Matching string or false
2379 public static function matchSummarySpamRegex( $text ) {
2380 global $wgSummarySpamRegex;
2381 $regexes = (array)$wgSummarySpamRegex;
2382 return self
::matchSpamRegexInternal( $text, $regexes );
2386 * @param string $text
2387 * @param array $regexes
2388 * @return bool|string
2390 protected static function matchSpamRegexInternal( $text, $regexes ) {
2391 foreach ( $regexes as $regex ) {
2393 if ( preg_match( $regex, $text, $matches ) ) {
2400 public function setHeaders() {
2401 $out = $this->context
->getOutput();
2403 $out->addModules( 'mediawiki.action.edit' );
2404 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2405 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2407 $user = $this->context
->getUser();
2408 if ( $user->getOption( 'showtoolbar' ) ) {
2409 // The addition of default buttons is handled by getEditToolbar() which
2410 // has its own dependency on this module. The call here ensures the module
2411 // is loaded in time (it has position "top") for other modules to register
2412 // buttons (e.g. extensions, gadgets, user scripts).
2413 $out->addModules( 'mediawiki.toolbar' );
2416 if ( $user->getOption( 'uselivepreview' ) ) {
2417 $out->addModules( 'mediawiki.action.edit.preview' );
2420 if ( $user->getOption( 'useeditwarning' ) ) {
2421 $out->addModules( 'mediawiki.action.edit.editWarning' );
2424 # Enabled article-related sidebar, toplinks, etc.
2425 $out->setArticleRelated( true );
2427 $contextTitle = $this->getContextTitle();
2428 if ( $this->isConflict
) {
2429 $msg = 'editconflict';
2430 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2431 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2433 $msg = $contextTitle->exists()
2434 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2435 && $contextTitle->getDefaultMessageText() !== false
2441 # Use the title defined by DISPLAYTITLE magic word when present
2442 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2443 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2444 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2445 if ( $displayTitle === false ) {
2446 $displayTitle = $contextTitle->getPrefixedText();
2448 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2450 $config = $this->context
->getConfig();
2452 # Transmit the name of the message to JavaScript for live preview
2453 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2454 $out->addJsConfigVars( [
2455 'wgEditMessage' => $msg,
2456 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2459 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2461 $out->addJsConfigVars(
2462 'wgEditSubmitButtonLabelPublish',
2463 $config->get( 'EditSubmitButtonLabelPublish' )
2468 * Show all applicable editing introductions
2470 protected function showIntro() {
2471 if ( $this->suppressIntro
) {
2475 $out = $this->context
->getOutput();
2476 $namespace = $this->mTitle
->getNamespace();
2478 if ( $namespace == NS_MEDIAWIKI
) {
2479 # Show a warning if editing an interface message
2480 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2481 # If this is a default message (but not css, json, or js),
2482 # show a hint that it is translatable on translatewiki.net
2484 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2485 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2486 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2488 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2489 if ( $defaultMessageText !== false ) {
2490 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2491 'translateinterface' );
2494 } elseif ( $namespace == NS_FILE
) {
2495 # Show a hint to shared repo
2496 $file = wfFindFile( $this->mTitle
);
2497 if ( $file && !$file->isLocal() ) {
2498 $descUrl = $file->getDescriptionUrl();
2499 # there must be a description url to show a hint to shared repo
2501 if ( !$this->mTitle
->exists() ) {
2502 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2503 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2506 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2507 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2514 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2515 # Show log extract when the user is currently blocked
2516 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2517 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2518 $user = User
::newFromName( $username, false /* allow IP users */ );
2519 $ip = User
::isIP( $username );
2520 $block = Block
::newFromTarget( $user, $user );
2521 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2522 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2523 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2524 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2525 # Show log extract if the user is currently blocked
2526 LogEventsList
::showLogExtract(
2529 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2533 'showIfEmpty' => false,
2535 'blocked-notice-logextract',
2536 $user->getName() # Support GENDER in notice
2542 # Try to add a custom edit intro, or use the standard one if this is not possible.
2543 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2544 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2545 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2547 if ( $this->context
->getUser()->isLoggedIn() ) {
2549 // Suppress the external link icon, consider the help url an internal one
2550 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2558 // Suppress the external link icon, consider the help url an internal one
2559 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2561 'newarticletextanon',
2567 # Give a notice if the user is editing a deleted/moved page...
2568 if ( !$this->mTitle
->exists() ) {
2569 $dbr = wfGetDB( DB_REPLICA
);
2571 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2575 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2576 'showIfEmpty' => false,
2577 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2584 * Attempt to show a custom editing introduction, if supplied
2588 protected function showCustomIntro() {
2589 if ( $this->editintro
) {
2590 $title = Title
::newFromText( $this->editintro
);
2591 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2592 // Added using template syntax, to take <noinclude>'s into account.
2593 $this->context
->getOutput()->addWikiTextTitleTidy(
2594 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2604 * Gets an editable textual representation of $content.
2605 * The textual representation can be turned by into a Content object by the
2606 * toEditContent() method.
2608 * If $content is null or false or a string, $content is returned unchanged.
2610 * If the given Content object is not of a type that can be edited using
2611 * the text base EditPage, an exception will be raised. Set
2612 * $this->allowNonTextContent to true to allow editing of non-textual
2615 * @param Content|null|bool|string $content
2616 * @return string The editable text form of the content.
2618 * @throws MWException If $content is not an instance of TextContent and
2619 * $this->allowNonTextContent is not true.
2621 protected function toEditText( $content ) {
2622 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2626 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2627 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2630 return $content->serialize( $this->contentFormat
);
2634 * Turns the given text into a Content object by unserializing it.
2636 * If the resulting Content object is not of a type that can be edited using
2637 * the text base EditPage, an exception will be raised. Set
2638 * $this->allowNonTextContent to true to allow editing of non-textual
2641 * @param string|null|bool $text Text to unserialize
2642 * @return Content|bool|null The content object created from $text. If $text was false
2643 * or null, false resp. null will be returned instead.
2645 * @throws MWException If unserializing the text results in a Content
2646 * object that is not an instance of TextContent and
2647 * $this->allowNonTextContent is not true.
2649 protected function toEditContent( $text ) {
2650 if ( $text === false ||
$text === null ) {
2654 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2655 $this->contentModel
, $this->contentFormat
);
2657 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2658 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2665 * Send the edit form and related headers to OutputPage
2666 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2667 * during form output near the top, for captchas and the like.
2669 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2670 * use the EditPage::showEditForm:fields hook instead.
2672 public function showEditForm( $formCallback = null ) {
2673 # need to parse the preview early so that we know which templates are used,
2674 # otherwise users with "show preview after edit box" will get a blank list
2675 # we parse this near the beginning so that setHeaders can do the title
2676 # setting work instead of leaving it in getPreviewText
2677 $previewOutput = '';
2678 if ( $this->formtype
== 'preview' ) {
2679 $previewOutput = $this->getPreviewText();
2682 $out = $this->context
->getOutput();
2684 // Avoid PHP 7.1 warning of passing $this by reference
2686 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2688 $this->setHeaders();
2690 $this->addTalkPageText();
2691 $this->addEditNotices();
2693 if ( !$this->isConflict
&&
2694 $this->section
!= '' &&
2695 !$this->isSectionEditSupported() ) {
2696 // We use $this->section to much before this and getVal('wgSection') directly in other places
2697 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2698 // Someone is welcome to try refactoring though
2699 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2703 $this->showHeader();
2705 $out->addHTML( $this->editFormPageTop
);
2707 $user = $this->context
->getUser();
2708 if ( $user->getOption( 'previewontop' ) ) {
2709 $this->displayPreviewArea( $previewOutput, true );
2712 $out->addHTML( $this->editFormTextTop
);
2714 $showToolbar = true;
2715 if ( $this->wasDeletedSinceLastEdit() ) {
2716 if ( $this->formtype
== 'save' ) {
2717 // Hide the toolbar and edit area, user can click preview to get it back
2718 // Add an confirmation checkbox and explanation.
2719 $showToolbar = false;
2721 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2722 'deletedwhileediting' );
2726 // @todo add EditForm plugin interface and use it here!
2727 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2728 $out->addHTML( Html
::openElement(
2731 'class' => 'mw-editform',
2732 'id' => self
::EDITFORM_ID
,
2733 'name' => self
::EDITFORM_ID
,
2735 'action' => $this->getActionURL( $this->getContextTitle() ),
2736 'enctype' => 'multipart/form-data'
2740 if ( is_callable( $formCallback ) ) {
2741 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2742 call_user_func_array( $formCallback, [ &$out ] );
2745 // Add a check for Unicode support
2746 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2748 // Add an empty field to trip up spambots
2750 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2753 [ 'for' => 'wpAntispam' ],
2754 $this->context
->msg( 'simpleantispam-label' )->parse()
2760 'name' => 'wpAntispam',
2761 'id' => 'wpAntispam',
2765 . Xml
::closeElement( 'div' )
2768 // Avoid PHP 7.1 warning of passing $this by reference
2770 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2772 // Put these up at the top to ensure they aren't lost on early form submission
2773 $this->showFormBeforeText();
2775 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2776 $username = $this->lastDelete
->user_name
;
2777 $comment = CommentStore
::getStore()
2778 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2780 // It is better to not parse the comment at all than to have templates expanded in the middle
2781 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2782 $key = $comment === ''
2783 ?
'confirmrecreate-noreason'
2784 : 'confirmrecreate';
2786 '<div class="mw-confirm-recreate">' .
2787 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2788 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2789 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2795 # When the summary is hidden, also hide them on preview/show changes
2796 if ( $this->nosummary
) {
2797 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2800 # If a blank edit summary was previously provided, and the appropriate
2801 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2802 # user being bounced back more than once in the event that a summary
2805 # For a bit more sophisticated detection of blank summaries, hash the
2806 # automatic one and pass that in the hidden field wpAutoSummary.
2807 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2808 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2811 if ( $this->undidRev
) {
2812 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2815 if ( $this->selfRedirect
) {
2816 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2819 if ( $this->hasPresetSummary
) {
2820 // If a summary has been preset using &summary= we don't want to prompt for
2821 // a different summary. Only prompt for a summary if the summary is blanked.
2823 $this->autoSumm
= md5( '' );
2826 $autosumm = $this->autoSumm ?
: md5( $this->summary
);
2827 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2829 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2830 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2832 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2833 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2837 if ( $this->section
== 'new' ) {
2838 $this->showSummaryInput( true, $this->summary
);
2839 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2842 $out->addHTML( $this->editFormTextBeforeContent
);
2843 if ( $this->isConflict
) {
2844 // In an edit conflict, we turn textbox2 into the user's text,
2845 // and textbox1 into the stored version
2846 $this->textbox2
= $this->textbox1
;
2848 $content = $this->getCurrentContent();
2849 $this->textbox1
= $this->toEditText( $content );
2851 $editConflictHelper = $this->getEditConflictHelper();
2852 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2853 $editConflictHelper->setContentModel( $this->contentModel
);
2854 $editConflictHelper->setContentFormat( $this->contentFormat
);
2855 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2858 if ( !$this->mTitle
->isUserConfigPage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2859 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2862 if ( $this->blankArticle
) {
2863 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2866 if ( $this->isConflict
) {
2867 // In an edit conflict bypass the overridable content form method
2868 // and fallback to the raw wpTextbox1 since editconflicts can't be
2869 // resolved between page source edits and custom ui edits using the
2871 $conflictTextBoxAttribs = [];
2872 if ( $this->wasDeletedSinceLastEdit() ) {
2873 $conflictTextBoxAttribs['style'] = 'display:none;';
2874 } elseif ( $this->isOldRev
) {
2875 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2878 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2879 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2881 $this->showContentForm();
2884 $out->addHTML( $this->editFormTextAfterContent
);
2886 $this->showStandardInputs();
2888 $this->showFormAfterText();
2890 $this->showTosSummary();
2892 $this->showEditTools();
2894 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2896 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2898 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2899 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2901 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2902 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2904 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2906 if ( $this->isConflict
) {
2908 $this->showConflict();
2909 } catch ( MWContentSerializationException
$ex ) {
2910 // this can't really happen, but be nice if it does.
2911 $msg = $this->context
->msg(
2912 'content-failed-to-parse',
2913 $this->contentModel
,
2914 $this->contentFormat
,
2917 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2921 // Set a hidden field so JS knows what edit form mode we are in
2922 if ( $this->isConflict
) {
2924 } elseif ( $this->preview
) {
2926 } elseif ( $this->diff
) {
2931 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2933 // Marker for detecting truncated form data. This must be the last
2934 // parameter sent in order to be of use, so do not move me.
2935 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2936 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2938 if ( !$user->getOption( 'previewontop' ) ) {
2939 $this->displayPreviewArea( $previewOutput, false );
2944 * Wrapper around TemplatesOnThisPageFormatter to make
2945 * a "templates on this page" list.
2947 * @param Title[] $templates
2948 * @return string HTML
2950 public function makeTemplatesOnThisPageList( array $templates ) {
2951 $templateListFormatter = new TemplatesOnThisPageFormatter(
2952 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2955 // preview if preview, else section if section, else false
2957 if ( $this->preview
) {
2959 } elseif ( $this->section
!= '' ) {
2963 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2964 $templateListFormatter->format( $templates, $type )
2969 * Extract the section title from current section text, if any.
2971 * @param string $text
2972 * @return string|bool String or false
2974 public static function extractSectionTitle( $text ) {
2975 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2976 if ( !empty( $matches[2] ) ) {
2978 return $wgParser->stripSectionName( trim( $matches[2] ) );
2984 protected function showHeader() {
2985 $out = $this->context
->getOutput();
2986 $user = $this->context
->getUser();
2987 if ( $this->isConflict
) {
2988 $this->addExplainConflictHeader( $out );
2989 $this->editRevId
= $this->page
->getLatest();
2991 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2992 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2993 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2994 if ( $sectionTitle !== false ) {
2995 $this->summary
= "/* $sectionTitle */ ";
3000 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
3002 if ( $this->missingComment
) {
3003 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3006 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
3008 "<div id='mw-missingsummary'>\n$1\n</div>",
3009 [ 'missingsummary', $buttonLabel ]
3013 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3015 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3016 [ 'missingcommentheader', $buttonLabel ]
3020 if ( $this->blankArticle
) {
3022 "<div id='mw-blankarticle'>\n$1\n</div>",
3023 [ 'blankarticle', $buttonLabel ]
3027 if ( $this->selfRedirect
) {
3029 "<div id='mw-selfredirect'>\n$1\n</div>",
3030 [ 'selfredirect', $buttonLabel ]
3034 if ( $this->hookError
!== '' ) {
3035 $out->addWikiText( $this->hookError
);
3038 if ( $this->section
!= 'new' ) {
3039 $revision = $this->mArticle
->getRevisionFetched();
3041 // Let sysop know that this will make private content public if saved
3043 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3045 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3046 'rev-deleted-text-permission'
3048 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3050 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3051 'rev-deleted-text-view'
3055 if ( !$revision->isCurrent() ) {
3056 $this->mArticle
->setOldSubtitle( $revision->getId() );
3057 $out->addWikiMsg( 'editingold' );
3058 $this->isOldRev
= true;
3060 } elseif ( $this->mTitle
->exists() ) {
3061 // Something went wrong
3063 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3064 [ 'missing-revision', $this->oldid
] );
3069 if ( wfReadOnly() ) {
3071 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3072 [ 'readonlywarning', wfReadOnlyReason() ]
3074 } elseif ( $user->isAnon() ) {
3075 if ( $this->formtype
!= 'preview' ) {
3077 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3078 [ 'anoneditwarning',
3080 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3081 'returnto' => $this->getTitle()->getPrefixedDBkey()
3084 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3085 'returnto' => $this->getTitle()->getPrefixedDBkey()
3090 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3091 'anonpreviewwarning'
3095 if ( $this->mTitle
->isUserConfigPage() ) {
3096 # Check the skin exists
3097 if ( $this->isWrongCaseUserConfigPage() ) {
3099 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3100 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3103 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3104 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3105 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3106 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3108 $warning = $isUserCssConfig
3110 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3112 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3114 if ( $this->formtype
!== 'preview' ) {
3115 $config = $this->context
->getConfig();
3116 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3118 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3119 [ 'usercssyoucanpreview' ]
3121 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3123 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3124 [ 'userjsonyoucanpreview' ]
3126 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3128 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3129 [ 'userjsyoucanpreview' ]
3137 $this->addPageProtectionWarningHeaders();
3139 $this->addLongPageWarningHeader();
3141 # Add header copyright warning
3142 $this->showHeaderCopyrightWarning();
3146 * Helper function for summary input functions, which returns the neccessary
3147 * attributes for the input.
3149 * @param array|null $inputAttrs Array of attrs to use on the input
3152 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3153 $conf = $this->context
->getConfig();
3154 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
3155 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3156 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3157 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
3158 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3159 'id' => 'wpSummary',
3160 'name' => 'wpSummary',
3161 'maxlength' => $oldCommentSchema ?
200 : CommentStore
::COMMENT_CHARACTER_LIMIT
,
3164 'spellcheck' => 'true',
3169 * Builds a standard summary input with a label.
3171 * @param string $summary The value of the summary input
3172 * @param string $labelText The html to place inside the label
3173 * @param array $inputAttrs Array of attrs to use on the input
3175 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3177 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3178 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3179 $this->getSummaryInputAttributes( $inputAttrs )
3182 'title' => Linker
::titleAttrib( 'summary' ),
3183 'accessKey' => Linker
::accesskey( 'summary' ),
3186 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3187 $inputAttrs['inputId'] = $inputAttrs['id'];
3188 $inputAttrs['id'] = 'wpSummaryWidget';
3190 return new OOUI\
FieldLayout(
3191 new OOUI\
TextInputWidget( [
3192 'value' => $summary,
3193 'infusable' => true,
3196 'label' => new OOUI\
HtmlSnippet( $labelText ),
3198 'id' => 'wpSummaryLabel',
3199 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3205 * @param bool $isSubjectPreview True if this is the section subject/title
3206 * up top, or false if this is the comment summary
3207 * down below the textarea
3208 * @param string $summary The text of the summary to display
3210 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3211 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3212 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3213 if ( $isSubjectPreview ) {
3214 if ( $this->nosummary
) {
3218 if ( !$this->mShowSummaryField
) {
3223 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3224 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3227 [ 'class' => $summaryClass ]
3232 * @param bool $isSubjectPreview True if this is the section subject/title
3233 * up top, or false if this is the comment summary
3234 * down below the textarea
3235 * @param string $summary The text of the summary to display
3238 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3239 // avoid spaces in preview, gets always trimmed on save
3240 $summary = trim( $summary );
3241 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3247 if ( $isSubjectPreview ) {
3248 $summary = $this->context
->msg( 'newsectionsummary' )
3249 ->rawParams( $wgParser->stripSectionName( $summary ) )
3250 ->inContentLanguage()->text();
3253 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3255 $summary = $this->context
->msg( $message )->parse()
3256 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3257 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3260 protected function showFormBeforeText() {
3261 $out = $this->context
->getOutput();
3262 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3263 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3264 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3265 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3266 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3269 protected function showFormAfterText() {
3271 * To make it harder for someone to slip a user a page
3272 * which submits an edit form to the wiki without their
3273 * knowledge, a random token is associated with the login
3274 * session. If it's not passed back with the submission,
3275 * we won't save the page, or render user JavaScript and
3278 * For anon editors, who may not have a session, we just
3279 * include the constant suffix to prevent editing from
3280 * broken text-mangling proxies.
3282 $this->context
->getOutput()->addHTML(
3284 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3290 * Subpage overridable method for printing the form for page content editing
3291 * By default this simply outputs wpTextbox1
3292 * Subclasses can override this to provide a custom UI for editing;
3293 * be it a form, or simply wpTextbox1 with a modified content that will be
3294 * reverse modified when extracted from the post data.
3295 * Note that this is basically the inverse for importContentFormData
3297 protected function showContentForm() {
3298 $this->showTextbox1();
3302 * Method to output wpTextbox1
3303 * The $textoverride method can be used by subclasses overriding showContentForm
3304 * to pass back to this method.
3306 * @param array $customAttribs Array of html attributes to use in the textarea
3307 * @param string $textoverride Optional text to override $this->textarea1 with
3309 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3310 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3311 $attribs = [ 'style' => 'display:none;' ];
3313 $builder = new TextboxBuilder();
3314 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3316 # Is an old revision being edited?
3317 if ( $this->isOldRev
) {
3318 $classes[] = 'mw-textarea-oldrev';
3321 $attribs = [ 'tabindex' => 1 ];
3323 if ( is_array( $customAttribs ) ) {
3324 $attribs +
= $customAttribs;
3327 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3331 $textoverride !== null ?
$textoverride : $this->textbox1
,
3337 protected function showTextbox2() {
3338 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3341 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3342 $builder = new TextboxBuilder();
3343 $attribs = $builder->buildTextboxAttribs(
3346 $this->context
->getUser(),
3350 $this->context
->getOutput()->addHTML(
3351 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3355 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3358 $classes[] = 'ontop';
3361 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3363 if ( $this->formtype
!= 'preview' ) {
3364 $attribs['style'] = 'display: none;';
3367 $out = $this->context
->getOutput();
3368 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3370 if ( $this->formtype
== 'preview' ) {
3371 $this->showPreview( $previewOutput );
3373 // Empty content container for LivePreview
3374 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3375 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3376 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3377 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3380 $out->addHTML( '</div>' );
3382 if ( $this->formtype
== 'diff' ) {
3385 } catch ( MWContentSerializationException
$ex ) {
3386 $msg = $this->context
->msg(
3387 'content-failed-to-parse',
3388 $this->contentModel
,
3389 $this->contentFormat
,
3392 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3398 * Append preview output to OutputPage.
3399 * Includes category rendering if this is a category page.
3401 * @param string $text The HTML to be output for the preview.
3403 protected function showPreview( $text ) {
3404 if ( $this->mArticle
instanceof CategoryPage
) {
3405 $this->mArticle
->openShowCategory();
3407 # This hook seems slightly odd here, but makes things more
3408 # consistent for extensions.
3409 $out = $this->context
->getOutput();
3410 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3411 $out->addHTML( $text );
3412 if ( $this->mArticle
instanceof CategoryPage
) {
3413 $this->mArticle
->closeShowCategory();
3418 * Get a diff between the current contents of the edit box and the
3419 * version of the page we're editing from.
3421 * If this is a section edit, we'll replace the section as for final
3422 * save and then make a comparison.
3424 public function showDiff() {
3427 $oldtitlemsg = 'currentrev';
3428 # if message does not exist, show diff against the preloaded default
3429 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3430 $oldtext = $this->mTitle
->getDefaultMessageText();
3431 if ( $oldtext !== false ) {
3432 $oldtitlemsg = 'defaultmessagetext';
3433 $oldContent = $this->toEditContent( $oldtext );
3438 $oldContent = $this->getCurrentContent();
3441 $textboxContent = $this->toEditContent( $this->textbox1
);
3442 if ( $this->editRevId
!== null ) {
3443 $newContent = $this->page
->replaceSectionAtRev(
3444 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3447 $newContent = $this->page
->replaceSectionContent(
3448 $this->section
, $textboxContent, $this->summary
, $this->edittime
3452 if ( $newContent ) {
3453 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3455 $user = $this->context
->getUser();
3456 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
3457 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3460 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3461 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3462 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3464 if ( !$oldContent ) {
3465 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3468 if ( !$newContent ) {
3469 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3472 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3473 $de->setContent( $oldContent, $newContent );
3475 $difftext = $de->getDiff( $oldtitle, $newtitle );
3476 $de->showDiffStyle();
3481 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3485 * Show the header copyright warning.
3487 protected function showHeaderCopyrightWarning() {
3488 $msg = 'editpage-head-copy-warn';
3489 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3490 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3491 'editpage-head-copy-warn' );
3496 * Give a chance for site and per-namespace customizations of
3497 * terms of service summary link that might exist separately
3498 * from the copyright notice.
3500 * This will display between the save button and the edit tools,
3501 * so should remain short!
3503 protected function showTosSummary() {
3504 $msg = 'editpage-tos-summary';
3505 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3506 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3507 $out = $this->context
->getOutput();
3508 $out->addHTML( '<div class="mw-tos-summary">' );
3509 $out->addWikiMsg( $msg );
3510 $out->addHTML( '</div>' );
3515 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3516 * characters not present on most keyboards for copying/pasting.
3518 protected function showEditTools() {
3519 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3520 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3525 * Get the copyright warning
3527 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3530 protected function getCopywarn() {
3531 return self
::getCopyrightWarning( $this->mTitle
);
3535 * Get the copyright warning, by default returns wikitext
3537 * @param Title $title
3538 * @param string $format Output format, valid values are any function of a Message object
3539 * @param Language|string|null $langcode Language code or Language object.
3542 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3543 global $wgRightsText;
3544 if ( $wgRightsText ) {
3545 $copywarnMsg = [ 'copyrightwarning',
3546 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3549 $copywarnMsg = [ 'copyrightwarning2',
3550 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3552 // Allow for site and per-namespace customization of contribution/copyright notice.
3553 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3555 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3557 $msg->inLanguage( $langcode );
3559 return "<div id=\"editpage-copywarn\">\n" .
3560 $msg->$format() . "\n</div>";
3564 * Get the Limit report for page previews
3567 * @param ParserOutput $output ParserOutput object from the parse
3568 * @return string HTML
3570 public static function getPreviewLimitReport( $output ) {
3573 if ( !$output ||
!$output->getLimitReportData() ) {
3577 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3578 wfMessage( 'limitreport-title' )->parseAsBlock()
3581 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3582 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3584 $limitReport .= Html
::openElement( 'table', [
3585 'class' => 'preview-limit-report wikitable'
3587 Html
::openElement( 'tbody' );
3589 foreach ( $output->getLimitReportData() as $key => $value ) {
3590 if ( Hooks
::run( 'ParserLimitReportFormat',
3591 [ $key, &$value, &$limitReport, true, true ]
3593 $keyMsg = wfMessage( $key );
3594 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3595 if ( !$valueMsg->exists() ) {
3596 $valueMsg = new RawMessage( '$1' );
3598 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3599 $limitReport .= Html
::openElement( 'tr' ) .
3600 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3601 Html
::rawElement( 'td', null,
3602 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3604 Html
::closeElement( 'tr' );
3609 $limitReport .= Html
::closeElement( 'tbody' ) .
3610 Html
::closeElement( 'table' ) .
3611 Html
::closeElement( 'div' );
3613 return $limitReport;
3616 protected function showStandardInputs( &$tabindex = 2 ) {
3617 $out = $this->context
->getOutput();
3618 $out->addHTML( "<div class='editOptions'>\n" );
3620 if ( $this->section
!= 'new' ) {
3621 $this->showSummaryInput( false, $this->summary
);
3622 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3625 $checkboxes = $this->getCheckboxesWidget(
3627 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3629 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3631 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3633 // Show copyright warning.
3634 $out->addWikiText( $this->getCopywarn() );
3635 $out->addHTML( $this->editFormTextAfterWarn
);
3637 $out->addHTML( "<div class='editButtons'>\n" );
3638 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3640 $cancel = $this->getCancelLink();
3642 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3643 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3646 $this->context
->msg( 'edithelp' )->text(),
3647 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3650 $this->context
->msg( 'word-separator' )->escaped() .
3651 $this->context
->msg( 'newwindow' )->parse();
3653 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3654 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3655 $out->addHTML( "</div><!-- editButtons -->\n" );
3657 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3659 $out->addHTML( "</div><!-- editOptions -->\n" );
3663 * Show an edit conflict. textbox1 is already shown in showEditForm().
3664 * If you want to use another entry point to this function, be careful.
3666 protected function showConflict() {
3667 $out = $this->context
->getOutput();
3668 // Avoid PHP 7.1 warning of passing $this by reference
3670 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3671 $this->incrementConflictStats();
3673 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3677 protected function incrementConflictStats() {
3678 $this->getEditConflictHelper()->incrementConflictStats();
3684 public function getCancelLink() {
3686 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3687 $cancelParams['oldid'] = $this->oldid
;
3688 } elseif ( $this->getContextTitle()->isRedirect() ) {
3689 $cancelParams['redirect'] = 'no';
3692 return new OOUI\
ButtonWidget( [
3693 'id' => 'mw-editform-cancel',
3694 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3695 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3697 'infusable' => true,
3698 'flags' => 'destructive',
3703 * Returns the URL to use in the form's action attribute.
3704 * This is used by EditPage subclasses when simply customizing the action
3705 * variable in the constructor is not enough. This can be used when the
3706 * EditPage lives inside of a Special page rather than a custom page action.
3708 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3711 protected function getActionURL( Title
$title ) {
3712 return $title->getLocalURL( [ 'action' => $this->action
] );
3716 * Check if a page was deleted while the user was editing it, before submit.
3717 * Note that we rely on the logging table, which hasn't been always there,
3718 * but that doesn't matter, because this only applies to brand new
3722 protected function wasDeletedSinceLastEdit() {
3723 if ( $this->deletedSinceEdit
!== null ) {
3724 return $this->deletedSinceEdit
;
3727 $this->deletedSinceEdit
= false;
3729 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3730 $this->lastDelete
= $this->getLastDelete();
3731 if ( $this->lastDelete
) {
3732 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3733 if ( $deleteTime > $this->starttime
) {
3734 $this->deletedSinceEdit
= true;
3739 return $this->deletedSinceEdit
;
3743 * @return bool|stdClass
3745 protected function getLastDelete() {
3746 $dbr = wfGetDB( DB_REPLICA
);
3747 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3748 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3749 $data = $dbr->selectRow(
3750 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3760 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3762 'log_namespace' => $this->mTitle
->getNamespace(),
3763 'log_title' => $this->mTitle
->getDBkey(),
3764 'log_type' => 'delete',
3765 'log_action' => 'delete',
3768 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3770 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3771 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3773 // Quick paranoid permission checks...
3774 if ( is_object( $data ) ) {
3775 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3776 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3779 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3780 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3781 $data->log_comment_data
= null;
3789 * Get the rendered text for previewing.
3790 * @throws MWException
3793 public function getPreviewText() {
3794 $out = $this->context
->getOutput();
3795 $config = $this->context
->getConfig();
3797 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3798 // Could be an offsite preview attempt. This is very unsafe if
3799 // HTML is enabled, as it could be an attack.
3801 if ( $this->textbox1
!== '' ) {
3802 // Do not put big scary notice, if previewing the empty
3803 // string, which happens when you initially edit
3804 // a category page, due to automatic preview-on-open.
3805 $parsedNote = $out->parse( "<div class='previewnote'>" .
3806 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3807 true, /* interface */true );
3809 $this->incrementEditFailureStats( 'session_loss' );
3816 $content = $this->toEditContent( $this->textbox1
);
3820 'AlternateEditPreview',
3821 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3823 return $previewHTML;
3826 # provide a anchor link to the editform
3827 $continueEditing = '<span class="mw-continue-editing">' .
3828 '[[#' . self
::EDITFORM_ID
. '|' .
3829 $this->context
->getLanguage()->getArrow() . ' ' .
3830 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3831 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3832 if ( $this->mTokenOkExceptSuffix
) {
3833 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3834 $this->incrementEditFailureStats( 'bad_token' );
3836 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3837 $this->incrementEditFailureStats( 'session_loss' );
3839 } elseif ( $this->incompleteForm
) {
3840 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3841 if ( $this->mTriedSave
) {
3842 $this->incrementEditFailureStats( 'incomplete_form' );
3845 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3848 # don't parse non-wikitext pages, show message about preview
3849 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3850 if ( $this->mTitle
->isUserConfigPage() ) {
3852 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3858 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3860 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3863 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3865 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3868 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3870 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3877 # Used messages to make sure grep find them:
3878 # Messages: usercsspreview, userjsonpreview, userjspreview,
3879 # sitecsspreview, sitejsonpreview, sitejspreview
3880 if ( $level && $format ) {
3881 $note = "<div id='mw-{$level}{$format}preview'>" .
3882 $this->context
->msg( "{$level}{$format}preview" )->text() .
3883 ' ' . $continueEditing . "</div>";
3887 # If we're adding a comment, we need to show the
3888 # summary as the headline
3889 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3890 $content = $content->addSectionHeader( $this->summary
);
3893 $hook_args = [ $this, &$content ];
3894 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3896 $parserResult = $this->doPreviewParse( $content );
3897 $parserOutput = $parserResult['parserOutput'];
3898 $previewHTML = $parserResult['html'];
3899 $this->mParserOutput
= $parserOutput;
3900 $out->addParserOutputMetadata( $parserOutput );
3901 if ( $out->userCanPreview() ) {
3902 $out->addContentOverride( $this->getTitle(), $content );
3905 if ( count( $parserOutput->getWarnings() ) ) {
3906 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3909 } catch ( MWContentSerializationException
$ex ) {
3910 $m = $this->context
->msg(
3911 'content-failed-to-parse',
3912 $this->contentModel
,
3913 $this->contentFormat
,
3916 $note .= "\n\n" . $m->parse();
3920 if ( $this->isConflict
) {
3921 $conflict = '<h2 id="mw-previewconflict">'
3922 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3924 $conflict = '<hr />';
3927 $previewhead = "<div class='previewnote'>\n" .
3928 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3929 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3931 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3932 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3933 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3934 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3936 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3939 private function incrementEditFailureStats( $failureType ) {
3940 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3941 $stats->increment( 'edit.failures.' . $failureType );
3945 * Get parser options for a preview
3946 * @return ParserOptions
3948 protected function getPreviewParserOptions() {
3949 $parserOptions = $this->page
->makeParserOptions( $this->context
);
3950 $parserOptions->setIsPreview( true );
3951 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3952 $parserOptions->enableLimitReport();
3953 return $parserOptions;
3957 * Parse the page for a preview. Subclasses may override this class, in order
3958 * to parse with different options, or to otherwise modify the preview HTML.
3960 * @param Content $content The page content
3961 * @return array with keys:
3962 * - parserOutput: The ParserOutput object
3963 * - html: The HTML to be displayed
3965 protected function doPreviewParse( Content
$content ) {
3966 $user = $this->context
->getUser();
3967 $parserOptions = $this->getPreviewParserOptions();
3968 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
3969 $scopedCallback = $parserOptions->setupFakeRevision(
3970 $this->mTitle
, $pstContent, $user );
3971 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3972 ScopedCallback
::consume( $scopedCallback );
3974 'parserOutput' => $parserOutput,
3975 'html' => $parserOutput->getText( [
3976 'enableSectionEditLinks' => false
3984 public function getTemplates() {
3985 if ( $this->preview ||
$this->section
!= '' ) {
3987 if ( !isset( $this->mParserOutput
) ) {
3990 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3991 foreach ( array_keys( $template ) as $dbk ) {
3992 $templates[] = Title
::makeTitle( $ns, $dbk );
3997 return $this->mTitle
->getTemplateLinksFrom();
4002 * Shows a bulletin board style toolbar for common editing functions.
4003 * It can be disabled in the user preferences.
4005 * @param Title $title Title object for the page being edited (optional)
4008 public static function getEditToolbar( $title = null ) {
4009 global $wgContLang, $wgOut;
4010 global $wgEnableUploads, $wgForeignFileRepos;
4012 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
4013 $showSignature = true;
4015 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4019 * $toolarray is an array of arrays each of which includes the
4020 * opening tag, the closing tag, optionally a sample text that is
4021 * inserted between the two when no selection is highlighted
4022 * and. The tip text is shown when the user moves the mouse
4025 * Images are defined in ResourceLoaderEditToolbarModule.
4029 'id' => 'mw-editbutton-bold',
4031 'close' => '\'\'\'',
4032 'sample' => wfMessage( 'bold_sample' )->text(),
4033 'tip' => wfMessage( 'bold_tip' )->text(),
4036 'id' => 'mw-editbutton-italic',
4039 'sample' => wfMessage( 'italic_sample' )->text(),
4040 'tip' => wfMessage( 'italic_tip' )->text(),
4043 'id' => 'mw-editbutton-link',
4046 'sample' => wfMessage( 'link_sample' )->text(),
4047 'tip' => wfMessage( 'link_tip' )->text(),
4050 'id' => 'mw-editbutton-extlink',
4053 'sample' => wfMessage( 'extlink_sample' )->text(),
4054 'tip' => wfMessage( 'extlink_tip' )->text(),
4057 'id' => 'mw-editbutton-headline',
4060 'sample' => wfMessage( 'headline_sample' )->text(),
4061 'tip' => wfMessage( 'headline_tip' )->text(),
4063 $imagesAvailable ?
[
4064 'id' => 'mw-editbutton-image',
4065 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4067 'sample' => wfMessage( 'image_sample' )->text(),
4068 'tip' => wfMessage( 'image_tip' )->text(),
4070 $imagesAvailable ?
[
4071 'id' => 'mw-editbutton-media',
4072 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4074 'sample' => wfMessage( 'media_sample' )->text(),
4075 'tip' => wfMessage( 'media_tip' )->text(),
4078 'id' => 'mw-editbutton-nowiki',
4079 'open' => "<nowiki>",
4080 'close' => "</nowiki>",
4081 'sample' => wfMessage( 'nowiki_sample' )->text(),
4082 'tip' => wfMessage( 'nowiki_tip' )->text(),
4085 'id' => 'mw-editbutton-signature',
4086 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4089 'tip' => wfMessage( 'sig_tip' )->text(),
4092 'id' => 'mw-editbutton-hr',
4093 'open' => "\n----\n",
4096 'tip' => wfMessage( 'hr_tip' )->text(),
4100 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4101 foreach ( $toolarray as $tool ) {
4107 // Images are defined in ResourceLoaderEditToolbarModule
4109 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4110 // Older browsers show a "speedtip" type message only for ALT.
4111 // Ideally these should be different, realistically they
4112 // probably don't need to be.
4120 $script .= Xml
::encodeJsCall(
4121 'mw.toolbar.addButton',
4123 ResourceLoader
::inDebugMode()
4129 $toolbar = '<div id="toolbar"></div>';
4131 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4132 // Only add the old toolbar cruft to the page payload if the toolbar has not
4133 // been over-written by a hook caller
4134 $nonce = $wgOut->getCSPNonce();
4135 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script, $nonce ) );
4142 * Return an array of checkbox definitions.
4144 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4146 * Array values are associative arrays with the following keys:
4147 * - 'label-message' (required): message for label text
4148 * - 'id' (required): 'id' attribute for the `<input>`
4149 * - 'default' (required): default checkedness (true or false)
4150 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4151 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4152 * from messages like 'tooltip-foo', 'accesskey-foo'
4153 * - 'label-id' (optional): 'id' attribute for the `<label>`
4154 * - 'legacy-name' (optional): short name for backwards-compatibility
4155 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4156 * where bool indicates the checked status of the checkbox
4159 public function getCheckboxesDefinition( $checked ) {
4162 $user = $this->context
->getUser();
4163 // don't show the minor edit checkbox if it's a new page or section
4164 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4165 $checkboxes['wpMinoredit'] = [
4166 'id' => 'wpMinoredit',
4167 'label-message' => 'minoredit',
4168 // Uses messages: tooltip-minoredit, accesskey-minoredit
4169 'tooltip' => 'minoredit',
4170 'label-id' => 'mw-editpage-minoredit',
4171 'legacy-name' => 'minor',
4172 'default' => $checked['minor'],
4176 if ( $user->isLoggedIn() ) {
4177 $checkboxes['wpWatchthis'] = [
4178 'id' => 'wpWatchthis',
4179 'label-message' => 'watchthis',
4180 // Uses messages: tooltip-watch, accesskey-watch
4181 'tooltip' => 'watch',
4182 'label-id' => 'mw-editpage-watch',
4183 'legacy-name' => 'watch',
4184 'default' => $checked['watch'],
4189 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4195 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4196 * any other added by extensions.
4198 * @param int &$tabindex Current tabindex
4199 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4200 * status of the checkbox
4202 * @return array Associative array of string keys to OOUI\FieldLayout instances
4204 public function getCheckboxesWidget( &$tabindex, $checked ) {
4206 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4208 foreach ( $checkboxesDef as $name => $options ) {
4209 $legacyName = $options['legacy-name'] ??
$name;
4213 if ( isset( $options['tooltip'] ) ) {
4214 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4215 $title = Linker
::titleAttrib( $options['tooltip'] );
4217 if ( isset( $options['title-message'] ) ) {
4218 $title = $this->context
->msg( $options['title-message'] )->text();
4221 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4222 new OOUI\
CheckboxInputWidget( [
4223 'tabIndex' => ++
$tabindex,
4224 'accessKey' => $accesskey,
4225 'id' => $options['id'] . 'Widget',
4226 'inputId' => $options['id'],
4228 'selected' => $options['default'],
4229 'infusable' => true,
4232 'align' => 'inline',
4233 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4235 'id' => $options['label-id'] ??
null,
4244 * Get the message key of the label for the button to save the page
4249 protected function getSubmitButtonLabel() {
4251 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4253 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4254 $newPage = !$this->mTitle
->exists();
4256 if ( $labelAsPublish ) {
4257 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4259 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4262 return $buttonLabelKey;
4266 * Returns an array of html code of the following buttons:
4267 * save, diff and preview
4269 * @param int &$tabindex Current tabindex
4273 public function getEditButtons( &$tabindex ) {
4277 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4279 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4280 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4282 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4284 'tabIndex' => ++
$tabindex,
4285 'id' => 'wpSaveWidget',
4286 'inputId' => 'wpSave',
4287 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4288 'useInputTag' => true,
4289 'flags' => [ 'progressive', 'primary' ],
4290 'label' => $buttonLabel,
4291 'infusable' => true,
4293 // Messages used: tooltip-save, tooltip-publish
4294 'title' => Linker
::titleAttrib( $buttonTooltip ),
4295 // Messages used: accesskey-save, accesskey-publish
4296 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4299 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4300 'name' => 'wpPreview',
4301 'tabIndex' => ++
$tabindex,
4302 'id' => 'wpPreviewWidget',
4303 'inputId' => 'wpPreview',
4304 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4305 'useInputTag' => true,
4306 'label' => $this->context
->msg( 'showpreview' )->text(),
4307 'infusable' => true,
4309 // Message used: tooltip-preview
4310 'title' => Linker
::titleAttrib( 'preview' ),
4311 // Message used: accesskey-preview
4312 'accessKey' => Linker
::accesskey( 'preview' ),
4315 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4317 'tabIndex' => ++
$tabindex,
4318 'id' => 'wpDiffWidget',
4319 'inputId' => 'wpDiff',
4320 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4321 'useInputTag' => true,
4322 'label' => $this->context
->msg( 'showdiff' )->text(),
4323 'infusable' => true,
4325 // Message used: tooltip-diff
4326 'title' => Linker
::titleAttrib( 'diff' ),
4327 // Message used: accesskey-diff
4328 'accessKey' => Linker
::accesskey( 'diff' ),
4331 // Avoid PHP 7.1 warning of passing $this by reference
4333 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4339 * Creates a basic error page which informs the user that
4340 * they have attempted to edit a nonexistent section.
4342 public function noSuchSectionPage() {
4343 $out = $this->context
->getOutput();
4344 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4346 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4348 // Avoid PHP 7.1 warning of passing $this by reference
4350 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4351 $out->addHTML( $res );
4353 $out->returnToMain( false, $this->mTitle
);
4357 * Show "your edit contains spam" page with your diff and text
4359 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4361 public function spamPageWithContent( $match = false ) {
4362 $this->textbox2
= $this->textbox1
;
4364 if ( is_array( $match ) ) {
4365 $match = $this->context
->getLanguage()->listToText( $match );
4367 $out = $this->context
->getOutput();
4368 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4370 $out->addHTML( '<div id="spamprotected">' );
4371 $out->addWikiMsg( 'spamprotectiontext' );
4373 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4375 $out->addHTML( '</div>' );
4377 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4380 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4381 $this->showTextbox2();
4383 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4387 * Filter an input field through a Unicode de-armoring process if it
4388 * came from an old browser with known broken Unicode editing issues.
4390 * @deprecated since 1.30, does nothing
4392 * @param WebRequest $request
4393 * @param string $field
4396 protected function safeUnicodeInput( $request, $field ) {
4397 return rtrim( $request->getText( $field ) );
4401 * Filter an output field through a Unicode armoring process if it is
4402 * going to an old browser with known broken Unicode editing issues.
4404 * @deprecated since 1.30, does nothing
4406 * @param string $text
4409 protected function safeUnicodeOutput( $text ) {
4416 protected function addEditNotices() {
4417 $out = $this->context
->getOutput();
4418 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4419 if ( count( $editNotices ) ) {
4420 $out->addHTML( implode( "\n", $editNotices ) );
4422 $msg = $this->context
->msg( 'editnotice-notext' );
4423 if ( !$msg->isDisabled() ) {
4425 '<div class="mw-editnotice-notext">'
4426 . $msg->parseAsBlock()
4436 protected function addTalkPageText() {
4437 if ( $this->mTitle
->isTalkPage() ) {
4438 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4445 protected function addLongPageWarningHeader() {
4446 if ( $this->contentLength
=== false ) {
4447 $this->contentLength
= strlen( $this->textbox1
);
4450 $out = $this->context
->getOutput();
4451 $lang = $this->context
->getLanguage();
4452 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4453 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4454 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4457 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4458 $lang->formatNum( $maxArticleSize )
4462 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4463 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4466 $lang->formatSize( strlen( $this->textbox1
) ),
4467 strlen( $this->textbox1
)
4477 protected function addPageProtectionWarningHeaders() {
4478 $out = $this->context
->getOutput();
4479 if ( $this->mTitle
->isProtected( 'edit' ) &&
4480 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4482 # Is the title semi-protected?
4483 if ( $this->mTitle
->isSemiProtected() ) {
4484 $noticeMsg = 'semiprotectedpagewarning';
4486 # Then it must be protected based on static groups (regular)
4487 $noticeMsg = 'protectedpagewarning';
4489 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4490 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4492 if ( $this->mTitle
->isCascadeProtected() ) {
4493 # Is this page under cascading protection from some source pages?
4494 /** @var Title[] $cascadeSources */
4495 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4496 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4497 $cascadeSourcesCount = count( $cascadeSources );
4498 if ( $cascadeSourcesCount > 0 ) {
4499 # Explain, and list the titles responsible
4500 foreach ( $cascadeSources as $page ) {
4501 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4504 $notice .= '</div>';
4505 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4507 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4508 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4510 'showIfEmpty' => false,
4511 'msgKey' => [ 'titleprotectedwarning' ],
4512 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4517 * @param OutputPage $out
4520 protected function addExplainConflictHeader( OutputPage
$out ) {
4522 $this->getEditConflictHelper()->getExplainHeader()
4527 * @param string $name
4528 * @param mixed[] $customAttribs
4533 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4534 return ( new TextboxBuilder() )->buildTextboxAttribs(
4535 $name, $customAttribs, $user, $this->mTitle
4540 * @param string $wikitext
4544 protected function addNewLineAtEnd( $wikitext ) {
4545 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4549 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4550 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4551 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4552 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4553 * spread the new style links more efficiently.
4555 * @param string $text
4558 private function guessSectionName( $text ) {
4561 // Detect Microsoft browsers
4562 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4563 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4564 // ...and redirect them to legacy encoding, if available
4565 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4567 // Meanwhile, real browsers get real anchors
4568 return $wgParser->guessSectionNameFromWikiText( $text );
4572 * Set a factory function to create an EditConflictHelper
4574 * @param callable $factory Factory function
4577 public function setEditConflictHelperFactory( callable
$factory ) {
4578 $this->editConflictHelperFactory
= $factory;
4579 $this->editConflictHelper
= null;
4583 * @return TextConflictHelper
4585 private function getEditConflictHelper() {
4586 if ( !$this->editConflictHelper
) {
4587 $this->editConflictHelper
= call_user_func(
4588 $this->editConflictHelperFactory
,
4589 $this->getSubmitButtonLabel()
4593 return $this->editConflictHelper
;
4597 * @param string $submitButtonLabel
4598 * @return TextConflictHelper
4600 private function newTextConflictHelper( $submitButtonLabel ) {
4601 return new TextConflictHelper(
4603 $this->getContext()->getOutput(),
4604 MediaWikiServices
::getInstance()->getStatsdDataFactory(),