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.
489 * If not set, $wgTitle will be returned. This behavior might change in
490 * the future to return $this->mTitle instead.
494 public function getContextTitle() {
495 if ( is_null( $this->mContextTitle
) ) {
498 __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.'
503 return $this->mContextTitle
;
508 * Returns if the given content model is editable.
510 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
512 * @throws MWException If $modelId has no known handler
514 public function isSupportedContentModel( $modelId ) {
515 return $this->enableApiEditOverride
=== true ||
516 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
520 * Allow editing of content that supports API direct editing, but not general
521 * direct editing. Set to false by default.
523 * @param bool $enableOverride
525 public function setApiEditOverride( $enableOverride ) {
526 $this->enableApiEditOverride
= $enableOverride;
530 * @deprecated since 1.29, call edit directly
532 public function submit() {
533 wfDeprecated( __METHOD__
, '1.29' );
538 * This is the function that gets called for "action=edit". It
539 * sets up various member variables, then passes execution to
540 * another function, usually showEditForm()
542 * The edit form is self-submitting, so that when things like
543 * preview and edit conflicts occur, we get the same form back
544 * with the extra stuff added. Only when the final submission
545 * is made and all is well do we actually save and redirect to
546 * the newly-edited page.
548 public function edit() {
549 // Allow extensions to modify/prevent this form or submission
550 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
554 wfDebug( __METHOD__
. ": enter\n" );
556 $request = $this->context
->getRequest();
557 // If they used redlink=1 and the page exists, redirect to the main article
558 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
559 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
563 $this->importFormData( $request );
564 $this->firsttime
= false;
566 if ( wfReadOnly() && $this->save
) {
569 $this->preview
= true;
573 $this->formtype
= 'save';
574 } elseif ( $this->preview
) {
575 $this->formtype
= 'preview';
576 } elseif ( $this->diff
) {
577 $this->formtype
= 'diff';
578 } else { # First time through
579 $this->firsttime
= true;
580 if ( $this->previewOnOpen() ) {
581 $this->formtype
= 'preview';
583 $this->formtype
= 'initial';
587 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
589 wfDebug( __METHOD__
. ": User can't edit\n" );
591 // track block with a cookie if it doesn't exists already
592 $this->context
->getUser()->trackBlockWithCookie();
594 // Auto-block user's IP if the account was "hard" blocked
595 if ( !wfReadOnly() ) {
596 DeferredUpdates
::addCallableUpdate( function () {
597 $this->context
->getUser()->spreadAnyEditBlock();
600 $this->displayPermissionsError( $permErrors );
605 $revision = $this->mArticle
->getRevisionFetched();
606 // Disallow editing revisions with content models different from the current one
607 // Undo edits being an exception in order to allow reverting content model changes.
609 && $revision->getContentModel() !== $this->contentModel
612 if ( $this->undidRev
) {
613 $undidRevObj = Revision
::newFromId( $this->undidRev
);
614 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
616 if ( !$this->undidRev
618 ||
$prevRev->getContentModel() !== $this->contentModel
620 $this->displayViewSourcePage(
621 $this->getContentObject(),
623 'contentmodelediterror',
624 $revision->getContentModel(),
632 $this->isConflict
= false;
634 # Show applicable editing introductions
635 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
639 # Attempt submission here. This will check for edit conflicts,
640 # and redundantly check for locked database, blocked IPs, etc.
641 # that edit() already checked just in case someone tries to sneak
642 # in the back door with a hand-edited submission URL.
644 if ( 'save' == $this->formtype
) {
645 $resultDetails = null;
646 $status = $this->attemptSave( $resultDetails );
647 if ( !$this->handleStatus( $status, $resultDetails ) ) {
652 # First time through: get contents, set time for conflict
654 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
655 if ( $this->initialiseForm() === false ) {
656 $this->noSuchSectionPage();
660 if ( !$this->mTitle
->getArticleID() ) {
661 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
663 Hooks
::run( 'EditFormInitialText', [ $this ] );
668 $this->showEditForm();
672 * @param string $rigor Same format as Title::getUserPermissionErrors()
675 protected function getEditPermissionErrors( $rigor = 'secure' ) {
676 $user = $this->context
->getUser();
677 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
678 # Can this title be created?
679 if ( !$this->mTitle
->exists() ) {
680 $permErrors = array_merge(
683 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
688 # Ignore some permissions errors when a user is just previewing/viewing diffs
690 foreach ( $permErrors as $error ) {
691 if ( ( $this->preview ||
$this->diff
)
693 $error[0] == 'blockedtext' ||
694 $error[0] == 'autoblockedtext' ||
695 $error[0] == 'systemblockedtext'
701 $permErrors = wfArrayDiff2( $permErrors, $remove );
707 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
708 * but with the following differences:
709 * - If redlink=1, the user will be redirected to the page
710 * - If there is content to display or the error occurs while either saving,
711 * previewing or showing the difference, it will be a
712 * "View source for ..." page displaying the source code after the error message.
715 * @param array $permErrors Array of permissions errors, as returned by
716 * Title::getUserPermissionsErrors().
717 * @throws PermissionsError
719 protected function displayPermissionsError( array $permErrors ) {
720 $out = $this->context
->getOutput();
721 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
722 // The edit page was reached via a red link.
723 // Redirect to the article page and let them click the edit tab if
724 // they really want a permission error.
725 $out->redirect( $this->mTitle
->getFullURL() );
729 $content = $this->getContentObject();
731 # Use the normal message if there's nothing to display
732 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
733 $action = $this->mTitle
->exists() ?
'edit' :
734 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
735 throw new PermissionsError( $action, $permErrors );
738 $this->displayViewSourcePage(
740 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
745 * Display a read-only View Source page
746 * @param Content $content
747 * @param string $errorMessage additional wikitext error message to display
749 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
750 $out = $this->context
->getOutput();
751 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
753 $out->setRobotPolicy( 'noindex,nofollow' );
754 $out->setPageTitle( $this->context
->msg(
756 $this->getContextTitle()->getPrefixedText()
758 $out->addBacklinkSubtitle( $this->getContextTitle() );
759 $out->addHTML( $this->editFormPageTop
);
760 $out->addHTML( $this->editFormTextTop
);
762 if ( $errorMessage !== '' ) {
763 $out->addWikiText( $errorMessage );
764 $out->addHTML( "<hr />\n" );
767 # If the user made changes, preserve them when showing the markup
768 # (This happens when a user is blocked during edit, for instance)
769 if ( !$this->firsttime
) {
770 $text = $this->textbox1
;
771 $out->addWikiMsg( 'viewyourtext' );
774 $text = $this->toEditText( $content );
775 } catch ( MWException
$e ) {
776 # Serialize using the default format if the content model is not supported
777 # (e.g. for an old revision with a different model)
778 $text = $content->serialize();
780 $out->addWikiMsg( 'viewsourcetext' );
783 $out->addHTML( $this->editFormTextBeforeContent
);
784 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
785 $out->addHTML( $this->editFormTextAfterContent
);
787 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
789 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
791 $out->addHTML( $this->editFormTextBottom
);
792 if ( $this->mTitle
->exists() ) {
793 $out->returnToMain( null, $this->mTitle
);
798 * Should we show a preview when the edit form is first shown?
802 protected function previewOnOpen() {
803 $config = $this->context
->getConfig();
804 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
805 $request = $this->context
->getRequest();
806 if ( $config->get( 'RawHtml' ) ) {
807 // If raw HTML is enabled, disable preview on open
808 // since it has to be posted with a token for
812 if ( $request->getVal( 'preview' ) == 'yes' ) {
813 // Explicit override from request
815 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
816 // Explicit override from request
818 } elseif ( $this->section
== 'new' ) {
819 // Nothing *to* preview for new sections
821 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
822 && $this->context
->getUser()->getOption( 'previewonfirst' )
824 // Standard preference behavior
826 } elseif ( !$this->mTitle
->exists()
827 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
828 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
830 // Categories are special
838 * Checks whether the user entered a skin name in uppercase,
839 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
843 protected function isWrongCaseUserConfigPage() {
844 if ( $this->mTitle
->isUserConfigPage() ) {
845 $name = $this->mTitle
->getSkinFromConfigSubpage();
846 $skins = array_merge(
847 array_keys( Skin
::getSkinNames() ),
850 return !in_array( $name, $skins )
851 && in_array( strtolower( $name ), $skins );
858 * Returns whether section editing is supported for the current page.
859 * Subclasses may override this to replace the default behavior, which is
860 * to check ContentHandler::supportsSections.
862 * @return bool True if this edit page supports sections, false otherwise.
864 protected function isSectionEditSupported() {
865 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
866 return $contentHandler->supportsSections();
870 * This function collects the form data and uses it to populate various member variables.
871 * @param WebRequest &$request
872 * @throws ErrorPageError
874 public function importFormData( &$request ) {
875 # Section edit can come from either the form or a link
876 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
878 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
879 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
882 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
884 if ( $request->wasPosted() ) {
885 # These fields need to be checked for encoding.
886 # Also remove trailing whitespace, but don't remove _initial_
887 # whitespace from the text boxes. This may be significant formatting.
888 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
889 if ( !$request->getCheck( 'wpTextbox2' ) ) {
890 // Skip this if wpTextbox2 has input, it indicates that we came
891 // from a conflict page with raw page text, not a custom form
892 // modified by subclasses
893 $textbox1 = $this->importContentFormData( $request );
894 if ( $textbox1 !== null ) {
895 $this->textbox1
= $textbox1;
899 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
901 $this->summary
= $request->getText( 'wpSummary' );
903 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
904 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
906 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
908 # Treat sectiontitle the same way as summary.
909 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
910 # currently doing double duty as both edit summary and section title. Right now this
911 # is just to allow API edits to work around this limitation, but this should be
912 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
913 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
914 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
916 $this->edittime
= $request->getVal( 'wpEdittime' );
917 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
918 $this->starttime
= $request->getVal( 'wpStarttime' );
920 $undidRev = $request->getInt( 'wpUndidRevision' );
922 $this->undidRev
= $undidRev;
925 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
927 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
928 // wpTextbox1 field is missing, possibly due to being "too big"
929 // according to some filter rules such as Suhosin's setting for
930 // suhosin.request.max_value_length (d'oh)
931 $this->incompleteForm
= true;
933 // If we receive the last parameter of the request, we can fairly
934 // claim the POST request has not been truncated.
936 // TODO: softened the check for cutover. Once we determine
937 // that it is safe, we should complete the transition by
938 // removing the "edittime" clause.
939 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
940 && is_null( $this->edittime
) );
942 if ( $this->incompleteForm
) {
943 # If the form is incomplete, force to preview.
944 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
945 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
946 $this->preview
= true;
948 $this->preview
= $request->getCheck( 'wpPreview' );
949 $this->diff
= $request->getCheck( 'wpDiff' );
951 // Remember whether a save was requested, so we can indicate
952 // if we forced preview due to session failure.
953 $this->mTriedSave
= !$this->preview
;
955 if ( $this->tokenOk( $request ) ) {
956 # Some browsers will not report any submit button
957 # if the user hits enter in the comment box.
958 # The unmarked state will be assumed to be a save,
959 # if the form seems otherwise complete.
960 wfDebug( __METHOD__
. ": Passed token check.\n" );
961 } elseif ( $this->diff
) {
962 # Failed token check, but only requested "Show Changes".
963 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
965 # Page might be a hack attempt posted from
966 # an external site. Preview instead of saving.
967 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
968 $this->preview
= true;
971 $this->save
= !$this->preview
&& !$this->diff
;
972 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
973 $this->edittime
= null;
976 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
977 $this->starttime
= null;
980 $this->recreate
= $request->getCheck( 'wpRecreate' );
982 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
983 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
985 $user = $this->context
->getUser();
986 # Don't force edit summaries when a user is editing their own user or talk page
987 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
988 && $this->mTitle
->getText() == $user->getName()
990 $this->allowBlankSummary
= true;
992 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
993 ||
!$user->getOption( 'forceeditsummary' );
996 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
998 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
999 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1001 $changeTags = $request->getVal( 'wpChangeTags' );
1002 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1003 $this->changeTags
= [];
1005 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1009 # Not a posted form? Start with nothing.
1010 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1011 $this->textbox1
= '';
1012 $this->summary
= '';
1013 $this->sectiontitle
= '';
1014 $this->edittime
= '';
1015 $this->editRevId
= null;
1016 $this->starttime
= wfTimestampNow();
1017 $this->edit
= false;
1018 $this->preview
= false;
1019 $this->save
= false;
1020 $this->diff
= false;
1021 $this->minoredit
= false;
1022 // Watch may be overridden by request parameters
1023 $this->watchthis
= $request->getBool( 'watchthis', false );
1024 $this->recreate
= false;
1026 // When creating a new section, we can preload a section title by passing it as the
1027 // preloadtitle parameter in the URL (T15100)
1028 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1029 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1030 // Once wpSummary isn't being use for setting section titles, we should delete this.
1031 $this->summary
= $request->getVal( 'preloadtitle' );
1032 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1033 $this->summary
= $request->getText( 'summary' );
1034 if ( $this->summary
!== '' ) {
1035 $this->hasPresetSummary
= true;
1039 if ( $request->getVal( 'minor' ) ) {
1040 $this->minoredit
= true;
1044 $this->oldid
= $request->getInt( 'oldid' );
1045 $this->parentRevId
= $request->getInt( 'parentRevId' );
1047 $this->bot
= $request->getBool( 'bot', true );
1048 $this->nosummary
= $request->getBool( 'nosummary' );
1050 // May be overridden by revision.
1051 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1052 // May be overridden by revision.
1053 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1056 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1057 } catch ( MWUnknownContentModelException
$e ) {
1058 throw new ErrorPageError(
1059 'editpage-invalidcontentmodel-title',
1060 'editpage-invalidcontentmodel-text',
1061 [ wfEscapeWikiText( $this->contentModel
) ]
1065 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1066 throw new ErrorPageError(
1067 'editpage-notsupportedcontentformat-title',
1068 'editpage-notsupportedcontentformat-text',
1070 wfEscapeWikiText( $this->contentFormat
),
1071 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1077 * @todo Check if the desired model is allowed in this namespace, and if
1078 * a transition from the page's current model to the new model is
1082 $this->editintro
= $request->getText( 'editintro',
1083 // Custom edit intro for new sections
1084 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1086 // Allow extensions to modify form data
1087 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1091 * Subpage overridable method for extracting the page content data from the
1092 * posted form to be placed in $this->textbox1, if using customized input
1093 * this method should be overridden and return the page text that will be used
1094 * for saving, preview parsing and so on...
1096 * @param WebRequest &$request
1097 * @return string|null
1099 protected function importContentFormData( &$request ) {
1100 return; // Don't do anything, EditPage already extracted wpTextbox1
1104 * Initialise form fields in the object
1105 * Called on the first invocation, e.g. when a user clicks an edit link
1106 * @return bool If the requested section is valid
1108 public function initialiseForm() {
1109 $this->edittime
= $this->page
->getTimestamp();
1110 $this->editRevId
= $this->page
->getLatest();
1112 $content = $this->getContentObject( false ); # TODO: track content object?!
1113 if ( $content === false ) {
1116 $this->textbox1
= $this->toEditText( $content );
1118 $user = $this->context
->getUser();
1119 // activate checkboxes if user wants them to be always active
1120 # Sort out the "watch" checkbox
1121 if ( $user->getOption( 'watchdefault' ) ) {
1123 $this->watchthis
= true;
1124 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1126 $this->watchthis
= true;
1127 } elseif ( $user->isWatched( $this->mTitle
) ) {
1129 $this->watchthis
= true;
1131 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1132 $this->minoredit
= true;
1134 if ( $this->textbox1
=== false ) {
1141 * @param Content|null $def_content The default value to return
1143 * @return Content|null Content on success, $def_content for invalid sections
1147 protected function getContentObject( $def_content = null ) {
1152 $user = $this->context
->getUser();
1153 $request = $this->context
->getRequest();
1154 // For message page not locally set, use the i18n message.
1155 // For other non-existent articles, use preload text if any.
1156 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1157 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1158 # If this is a system message, get the default text.
1159 $msg = $this->mTitle
->getDefaultMessageText();
1161 $content = $this->toEditContent( $msg );
1163 if ( $content === false ) {
1164 # If requested, preload some text.
1165 $preload = $request->getVal( 'preload',
1166 // Custom preload text for new sections
1167 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1168 $params = $request->getArray( 'preloadparams', [] );
1170 $content = $this->getPreloadedContent( $preload, $params );
1172 // For existing pages, get text based on "undo" or section parameters.
1174 if ( $this->section
!= '' ) {
1175 // Get section edit text (returns $def_text for invalid sections)
1176 $orig = $this->getOriginalContent( $user );
1177 $content = $orig ?
$orig->getSection( $this->section
) : null;
1180 $content = $def_content;
1183 $undoafter = $request->getInt( 'undoafter' );
1184 $undo = $request->getInt( 'undo' );
1186 if ( $undo > 0 && $undoafter > 0 ) {
1187 $undorev = Revision
::newFromId( $undo );
1188 $oldrev = Revision
::newFromId( $undoafter );
1190 # Sanity check, make sure it's the right page,
1191 # the revisions exist and they were not deleted.
1192 # Otherwise, $content will be left as-is.
1193 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1194 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1195 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1197 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1199 if ( $content === false ) {
1200 # Warn the user that something went wrong
1201 $undoMsg = 'failure';
1203 $oldContent = $this->page
->getContent( Revision
::RAW
);
1204 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1205 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1206 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1207 // The undo may change content
1208 // model if its reverting the top
1209 // edit. This can result in
1210 // mismatched content model/format.
1211 $this->contentModel
= $newContent->getModel();
1212 $this->contentFormat
= $oldrev->getContentFormat();
1215 if ( $newContent->equals( $oldContent ) ) {
1216 # Tell the user that the undo results in no change,
1217 # i.e. the revisions were already undone.
1218 $undoMsg = 'nochange';
1221 # Inform the user of our success and set an automatic edit summary
1222 $undoMsg = 'success';
1224 # If we just undid one rev, use an autosummary
1225 $firstrev = $oldrev->getNext();
1226 if ( $firstrev && $firstrev->getId() == $undo ) {
1227 $userText = $undorev->getUserText();
1228 if ( $userText === '' ) {
1229 $undoSummary = $this->context
->msg(
1230 'undo-summary-username-hidden',
1232 )->inContentLanguage()->text();
1234 $undoSummary = $this->context
->msg(
1238 )->inContentLanguage()->text();
1240 if ( $this->summary
=== '' ) {
1241 $this->summary
= $undoSummary;
1243 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1244 ->inContentLanguage()->text() . $this->summary
;
1246 $this->undidRev
= $undo;
1248 $this->formtype
= 'diff';
1252 // Failed basic sanity checks.
1253 // Older revisions may have been removed since the link
1254 // was created, or we may simply have got bogus input.
1258 $out = $this->context
->getOutput();
1259 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1260 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1261 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1262 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1265 if ( $content === false ) {
1266 $content = $this->getOriginalContent( $user );
1275 * Get the content of the wanted revision, without section extraction.
1277 * The result of this function can be used to compare user's input with
1278 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1279 * to the original text of the edit.
1281 * This differs from Article::getContent() that when a missing revision is
1282 * encountered the result will be null and not the
1283 * 'missing-revision' message.
1286 * @param User $user The user to get the revision for
1287 * @return Content|null
1289 private function getOriginalContent( User
$user ) {
1290 if ( $this->section
== 'new' ) {
1291 return $this->getCurrentContent();
1293 $revision = $this->mArticle
->getRevisionFetched();
1294 if ( $revision === null ) {
1295 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1296 return $handler->makeEmptyContent();
1298 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1303 * Get the edit's parent revision ID
1305 * The "parent" revision is the ancestor that should be recorded in this
1306 * page's revision history. It is either the revision ID of the in-memory
1307 * article content, or in the case of a 3-way merge in order to rebase
1308 * across a recoverable edit conflict, the ID of the newer revision to
1309 * which we have rebased this page.
1312 * @return int Revision ID
1314 public function getParentRevId() {
1315 if ( $this->parentRevId
) {
1316 return $this->parentRevId
;
1318 return $this->mArticle
->getRevIdFetched();
1323 * Get the current content of the page. This is basically similar to
1324 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1325 * content object is returned instead of null.
1330 protected function getCurrentContent() {
1331 $rev = $this->page
->getRevision();
1332 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1334 if ( $content === false ||
$content === null ) {
1335 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1336 return $handler->makeEmptyContent();
1337 } elseif ( !$this->undidRev
) {
1338 // Content models should always be the same since we error
1339 // out if they are different before this point (in ->edit()).
1340 // The exception being, during an undo, the current revision might
1341 // differ from the prior revision.
1342 $logger = LoggerFactory
::getInstance( 'editpage' );
1343 if ( $this->contentModel
!== $rev->getContentModel() ) {
1344 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1345 'prev' => $this->contentModel
,
1346 'new' => $rev->getContentModel(),
1347 'title' => $this->getTitle()->getPrefixedDBkey(),
1348 'method' => __METHOD__
1350 $this->contentModel
= $rev->getContentModel();
1353 // Given that the content models should match, the current selected
1354 // format should be supported.
1355 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1356 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1358 'prev' => $this->contentFormat
,
1359 'new' => $rev->getContentFormat(),
1360 'title' => $this->getTitle()->getPrefixedDBkey(),
1361 'method' => __METHOD__
1363 $this->contentFormat
= $rev->getContentFormat();
1370 * Use this method before edit() to preload some content into the edit box
1372 * @param Content $content
1376 public function setPreloadedContent( Content
$content ) {
1377 $this->mPreloadContent
= $content;
1381 * Get the contents to be preloaded into the box, either set by
1382 * an earlier setPreloadText() or by loading the given page.
1384 * @param string $preload Representing the title to preload from.
1385 * @param array $params Parameters to use (interface-message style) in the preloaded text
1391 protected function getPreloadedContent( $preload, $params = [] ) {
1392 if ( !empty( $this->mPreloadContent
) ) {
1393 return $this->mPreloadContent
;
1396 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1398 if ( $preload === '' ) {
1399 return $handler->makeEmptyContent();
1402 $user = $this->context
->getUser();
1403 $title = Title
::newFromText( $preload );
1404 # Check for existence to avoid getting MediaWiki:Noarticletext
1405 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1406 // TODO: somehow show a warning to the user!
1407 return $handler->makeEmptyContent();
1410 $page = WikiPage
::factory( $title );
1411 if ( $page->isRedirect() ) {
1412 $title = $page->getRedirectTarget();
1414 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1415 // TODO: somehow show a warning to the user!
1416 return $handler->makeEmptyContent();
1418 $page = WikiPage
::factory( $title );
1421 $parserOptions = ParserOptions
::newFromUser( $user );
1422 $content = $page->getContent( Revision
::RAW
);
1425 // TODO: somehow show a warning to the user!
1426 return $handler->makeEmptyContent();
1429 if ( $content->getModel() !== $handler->getModelID() ) {
1430 $converted = $content->convert( $handler->getModelID() );
1432 if ( !$converted ) {
1433 // TODO: somehow show a warning to the user!
1434 wfDebug( "Attempt to preload incompatible content: " .
1435 "can't convert " . $content->getModel() .
1436 " to " . $handler->getModelID() );
1438 return $handler->makeEmptyContent();
1441 $content = $converted;
1444 return $content->preloadTransform( $title, $parserOptions, $params );
1448 * Make sure the form isn't faking a user's credentials.
1450 * @param WebRequest &$request
1454 public function tokenOk( &$request ) {
1455 $token = $request->getVal( 'wpEditToken' );
1456 $user = $this->context
->getUser();
1457 $this->mTokenOk
= $user->matchEditToken( $token );
1458 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1459 return $this->mTokenOk
;
1463 * Sets post-edit cookie indicating the user just saved a particular revision.
1465 * This uses a temporary cookie for each revision ID so separate saves will never
1466 * interfere with each other.
1468 * Article::view deletes the cookie on server-side after the redirect and
1469 * converts the value to the global JavaScript variable wgPostEdit.
1471 * If the variable were set on the server, it would be cached, which is unwanted
1472 * since the post-edit state should only apply to the load right after the save.
1474 * @param int $statusValue The status value (to check for new article status)
1476 protected function setPostEditCookie( $statusValue ) {
1477 $revisionId = $this->page
->getLatest();
1478 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1481 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1483 } elseif ( $this->oldid
) {
1487 $response = $this->context
->getRequest()->response();
1488 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1492 * Attempt submission
1493 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1494 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1495 * @return Status The resulting status object.
1497 public function attemptSave( &$resultDetails = false ) {
1498 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1499 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1500 // This is needed since PageUpdater no longer checks these rights!
1502 // Allow bots to exempt some edits from bot flagging
1503 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1504 $status = $this->internalAttemptSave( $resultDetails, $bot );
1506 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1512 * Log when a page was successfully saved after the edit conflict view
1514 private function incrementResolvedConflicts() {
1515 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1519 $this->getEditConflictHelper()->incrementResolvedStats();
1523 * Handle status, such as after attempt save
1525 * @param Status $status
1526 * @param array|bool $resultDetails
1528 * @throws ErrorPageError
1529 * @return bool False, if output is done, true if rest of the form should be displayed
1531 private function handleStatus( Status
$status, $resultDetails ) {
1533 * @todo FIXME: once the interface for internalAttemptSave() is made
1534 * nicer, this should use the message in $status
1536 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1537 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1539 $this->incrementResolvedConflicts();
1541 $this->didSave
= true;
1542 if ( !$resultDetails['nullEdit'] ) {
1543 $this->setPostEditCookie( $status->value
);
1547 $out = $this->context
->getOutput();
1549 // "wpExtraQueryRedirect" is a hidden input to modify
1550 // after save URL and is not used by actual edit form
1551 $request = $this->context
->getRequest();
1552 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1554 switch ( $status->value
) {
1555 case self
::AS_HOOK_ERROR_EXPECTED
:
1556 case self
::AS_CONTENT_TOO_BIG
:
1557 case self
::AS_ARTICLE_WAS_DELETED
:
1558 case self
::AS_CONFLICT_DETECTED
:
1559 case self
::AS_SUMMARY_NEEDED
:
1560 case self
::AS_TEXTBOX_EMPTY
:
1561 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1563 case self
::AS_BLANK_ARTICLE
:
1564 case self
::AS_SELF_REDIRECT
:
1567 case self
::AS_HOOK_ERROR
:
1570 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1571 case self
::AS_PARSE_ERROR
:
1572 case self
::AS_UNICODE_NOT_SUPPORTED
:
1573 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1576 case self
::AS_SUCCESS_NEW_ARTICLE
:
1577 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1578 if ( $extraQueryRedirect ) {
1579 if ( $query === '' ) {
1580 $query = $extraQueryRedirect;
1582 $query = $query . '&' . $extraQueryRedirect;
1585 $anchor = $resultDetails['sectionanchor'] ??
'';
1586 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1589 case self
::AS_SUCCESS_UPDATE
:
1591 $sectionanchor = $resultDetails['sectionanchor'];
1593 // Give extensions a chance to modify URL query on update
1595 'ArticleUpdateBeforeRedirect',
1596 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1599 if ( $resultDetails['redirect'] ) {
1600 if ( $extraQuery == '' ) {
1601 $extraQuery = 'redirect=no';
1603 $extraQuery = 'redirect=no&' . $extraQuery;
1606 if ( $extraQueryRedirect ) {
1607 if ( $extraQuery === '' ) {
1608 $extraQuery = $extraQueryRedirect;
1610 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1614 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1617 case self
::AS_SPAM_ERROR
:
1618 $this->spamPageWithContent( $resultDetails['spam'] );
1621 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1622 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1624 case self
::AS_IMAGE_REDIRECT_ANON
:
1625 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1626 throw new PermissionsError( 'upload' );
1628 case self
::AS_READ_ONLY_PAGE_ANON
:
1629 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1630 throw new PermissionsError( 'edit' );
1632 case self
::AS_READ_ONLY_PAGE
:
1633 throw new ReadOnlyError
;
1635 case self
::AS_RATE_LIMITED
:
1636 throw new ThrottledError();
1638 case self
::AS_NO_CREATE_PERMISSION
:
1639 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1640 throw new PermissionsError( $permission );
1642 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1643 throw new PermissionsError( 'editcontentmodel' );
1646 // We don't recognize $status->value. The only way that can happen
1647 // is if an extension hook aborted from inside ArticleSave.
1648 // Render the status object into $this->hookError
1649 // FIXME this sucks, we should just use the Status object throughout
1650 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1657 * Run hooks that can filter edits just before they get saved.
1659 * @param Content $content The Content to filter.
1660 * @param Status $status For reporting the outcome to the caller
1661 * @param User $user The user performing the edit
1665 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1666 // Run old style post-section-merge edit filter
1667 if ( $this->hookError
!= '' ) {
1668 # ...or the hook could be expecting us to produce an error
1669 $status->fatal( 'hookaborted' );
1670 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1674 // Run new style post-section-merge edit filter
1675 if ( !Hooks
::run( 'EditFilterMergedContent',
1676 [ $this->context
, $content, $status, $this->summary
,
1677 $user, $this->minoredit
] )
1679 # Error messages etc. could be handled within the hook...
1680 if ( $status->isGood() ) {
1681 $status->fatal( 'hookaborted' );
1682 // Not setting $this->hookError here is a hack to allow the hook
1683 // to cause a return to the edit page without $this->hookError
1684 // being set. This is used by ConfirmEdit to display a captcha
1685 // without any error message cruft.
1687 $this->hookError
= $this->formatStatusErrors( $status );
1689 // Use the existing $status->value if the hook set it
1690 if ( !$status->value
) {
1691 $status->value
= self
::AS_HOOK_ERROR
;
1694 } elseif ( !$status->isOK() ) {
1695 # ...or the hook could be expecting us to produce an error
1696 // FIXME this sucks, we should just use the Status object throughout
1697 $this->hookError
= $this->formatStatusErrors( $status );
1698 $status->fatal( 'hookaborted' );
1699 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1707 * Wrap status errors in an errorbox for increased visibility
1709 * @param Status $status
1710 * @return string Wikitext
1712 private function formatStatusErrors( Status
$status ) {
1713 $errmsg = $status->getWikiText(
1716 $this->context
->getLanguage()
1719 <div class="errorbox">
1727 * Return the summary to be used for a new section.
1729 * @param string $sectionanchor Set to the section anchor text
1732 private function newSectionSummary( &$sectionanchor = null ) {
1735 if ( $this->sectiontitle
!== '' ) {
1736 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1737 // If no edit summary was specified, create one automatically from the section
1738 // title and have it link to the new section. Otherwise, respect the summary as
1740 if ( $this->summary
=== '' ) {
1741 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1742 return $this->context
->msg( 'newsectionsummary' )
1743 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1745 } elseif ( $this->summary
!== '' ) {
1746 $sectionanchor = $this->guessSectionName( $this->summary
);
1747 # This is a new section, so create a link to the new section
1748 # in the revision summary.
1749 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1750 return $this->context
->msg( 'newsectionsummary' )
1751 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1753 return $this->summary
;
1757 * Attempt submission (no UI)
1759 * @param array &$result Array to add statuses to, currently with the
1761 * - spam (string): Spam string from content if any spam is detected by
1763 * - sectionanchor (string): Section anchor for a section save.
1764 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1766 * - redirect (bool): Set if doEditContent is OK. True if resulting
1767 * revision is a redirect.
1768 * @param bool $bot True if edit is being made under the bot right.
1770 * @return Status Status object, possibly with a message, but always with
1771 * one of the AS_* constants in $status->value,
1773 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1774 * various error display idiosyncrasies. There are also lots of cases
1775 * where error metadata is set in the object and retrieved later instead
1776 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1777 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1780 public function internalAttemptSave( &$result, $bot = false ) {
1781 $status = Status
::newGood();
1782 $user = $this->context
->getUser();
1784 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1785 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1786 $status->fatal( 'hookaborted' );
1787 $status->value
= self
::AS_HOOK_ERROR
;
1791 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1792 $status->fatal( 'unicode-support-fail' );
1793 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1797 $request = $this->context
->getRequest();
1798 $spam = $request->getText( 'wpAntispam' );
1799 if ( $spam !== '' ) {
1804 $this->mTitle
->getPrefixedText() .
1805 '" submitted bogus field "' .
1809 $status->fatal( 'spamprotectionmatch', false );
1810 $status->value
= self
::AS_SPAM_ERROR
;
1815 # Construct Content object
1816 $textbox_content = $this->toEditContent( $this->textbox1
);
1817 } catch ( MWContentSerializationException
$ex ) {
1819 'content-failed-to-parse',
1820 $this->contentModel
,
1821 $this->contentFormat
,
1824 $status->value
= self
::AS_PARSE_ERROR
;
1828 # Check image redirect
1829 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1830 $textbox_content->isRedirect() &&
1831 !$user->isAllowed( 'upload' )
1833 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1834 $status->setResult( false, $code );
1840 $match = self
::matchSummarySpamRegex( $this->summary
);
1841 if ( $match === false && $this->section
== 'new' ) {
1842 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1843 # regular summaries, it is added to the actual wikitext.
1844 if ( $this->sectiontitle
!== '' ) {
1845 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1846 $match = self
::matchSpamRegex( $this->sectiontitle
);
1848 # This branch is taken when the "Add Topic" user interface is used, or the API
1849 # is used with the 'summary' parameter.
1850 $match = self
::matchSpamRegex( $this->summary
);
1853 if ( $match === false ) {
1854 $match = self
::matchSpamRegex( $this->textbox1
);
1856 if ( $match !== false ) {
1857 $result['spam'] = $match;
1858 $ip = $request->getIP();
1859 $pdbk = $this->mTitle
->getPrefixedDBkey();
1860 $match = str_replace( "\n", '', $match );
1861 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1862 $status->fatal( 'spamprotectionmatch', $match );
1863 $status->value
= self
::AS_SPAM_ERROR
;
1868 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1870 # Error messages etc. could be handled within the hook...
1871 $status->fatal( 'hookaborted' );
1872 $status->value
= self
::AS_HOOK_ERROR
;
1874 } elseif ( $this->hookError
!= '' ) {
1875 # ...or the hook could be expecting us to produce an error
1876 $status->fatal( 'hookaborted' );
1877 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1881 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1882 // Auto-block user's IP if the account was "hard" blocked
1883 if ( !wfReadOnly() ) {
1884 $user->spreadAnyEditBlock();
1886 # Check block state against master, thus 'false'.
1887 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1891 $this->contentLength
= strlen( $this->textbox1
);
1892 $config = $this->context
->getConfig();
1893 $maxArticleSize = $config->get( 'MaxArticleSize' );
1894 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1895 // Error will be displayed by showEditForm()
1896 $this->tooBig
= true;
1897 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1901 if ( !$user->isAllowed( 'edit' ) ) {
1902 if ( $user->isAnon() ) {
1903 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1906 $status->fatal( 'readonlytext' );
1907 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1912 $changingContentModel = false;
1913 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1914 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1915 $status->fatal( 'editpage-cannot-use-custom-model' );
1916 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1918 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1919 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1922 // Make sure the user can edit the page under the new content model too
1923 $titleWithNewContentModel = clone $this->mTitle
;
1924 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1925 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1926 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1928 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1932 $changingContentModel = true;
1933 $oldContentModel = $this->mTitle
->getContentModel();
1936 if ( $this->changeTags
) {
1937 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1938 $this->changeTags
, $user );
1939 if ( !$changeTagsStatus->isOK() ) {
1940 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1941 return $changeTagsStatus;
1945 if ( wfReadOnly() ) {
1946 $status->fatal( 'readonlytext' );
1947 $status->value
= self
::AS_READ_ONLY_PAGE
;
1950 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1951 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1953 $status->fatal( 'actionthrottledtext' );
1954 $status->value
= self
::AS_RATE_LIMITED
;
1958 # If the article has been deleted while editing, don't save it without
1960 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1961 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1965 # Load the page data from the master. If anything changes in the meantime,
1966 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1967 $this->page
->loadPageData( 'fromdbmaster' );
1968 $new = !$this->page
->exists();
1971 // Late check for create permission, just in case *PARANOIA*
1972 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1973 $status->fatal( 'nocreatetext' );
1974 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1975 wfDebug( __METHOD__
. ": no create permission\n" );
1979 // Don't save a new page if it's blank or if it's a MediaWiki:
1980 // message with content equivalent to default (allow empty pages
1981 // in this case to disable messages, see T52124)
1982 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1983 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1984 $defaultText = $defaultMessageText;
1989 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1990 $this->blankArticle
= true;
1991 $status->fatal( 'blankarticle' );
1992 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1996 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2000 $content = $textbox_content;
2002 $result['sectionanchor'] = '';
2003 if ( $this->section
== 'new' ) {
2004 if ( $this->sectiontitle
!== '' ) {
2005 // Insert the section title above the content.
2006 $content = $content->addSectionHeader( $this->sectiontitle
);
2007 } elseif ( $this->summary
!== '' ) {
2008 // Insert the section title above the content.
2009 $content = $content->addSectionHeader( $this->summary
);
2011 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2014 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2018 # Article exists. Check for edit conflict.
2020 $this->page
->clear(); # Force reload of dates, etc.
2021 $timestamp = $this->page
->getTimestamp();
2022 $latest = $this->page
->getLatest();
2024 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2026 // Check editRevId if set, which handles same-second timestamp collisions
2027 if ( $timestamp != $this->edittime
2028 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2030 $this->isConflict
= true;
2031 if ( $this->section
== 'new' ) {
2032 if ( $this->page
->getUserText() == $user->getName() &&
2033 $this->page
->getComment() == $this->newSectionSummary()
2035 // Probably a duplicate submission of a new comment.
2036 // This can happen when CDN resends a request after
2037 // a timeout but the first one actually went through.
2039 . ": duplicate new section submission; trigger edit conflict!\n" );
2041 // New comment; suppress conflict.
2042 $this->isConflict
= false;
2043 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2045 } elseif ( $this->section
== ''
2046 && Revision
::userWasLastToEdit(
2047 DB_MASTER
, $this->mTitle
->getArticleID(),
2048 $user->getId(), $this->edittime
2051 # Suppress edit conflict with self, except for section edits where merging is required.
2052 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2053 $this->isConflict
= false;
2057 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2058 if ( $this->sectiontitle
!== '' ) {
2059 $sectionTitle = $this->sectiontitle
;
2061 $sectionTitle = $this->summary
;
2066 if ( $this->isConflict
) {
2068 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2069 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2070 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2071 // ...or disable section editing for non-current revisions (not exposed anyway).
2072 if ( $this->editRevId
!== null ) {
2073 $content = $this->page
->replaceSectionAtRev(
2080 $content = $this->page
->replaceSectionContent(
2088 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2089 $content = $this->page
->replaceSectionContent(
2096 if ( is_null( $content ) ) {
2097 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2098 $this->isConflict
= true;
2099 $content = $textbox_content; // do not try to merge here!
2100 } elseif ( $this->isConflict
) {
2102 if ( $this->mergeChangesIntoContent( $content ) ) {
2103 // Successful merge! Maybe we should tell the user the good news?
2104 $this->isConflict
= false;
2105 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2107 $this->section
= '';
2108 $this->textbox1
= ContentHandler
::getContentText( $content );
2109 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2113 if ( $this->isConflict
) {
2114 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2118 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2122 if ( $this->section
== 'new' ) {
2123 // Handle the user preference to force summaries here
2124 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2125 $this->missingSummary
= true;
2126 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2127 $status->value
= self
::AS_SUMMARY_NEEDED
;
2131 // Do not allow the user to post an empty comment
2132 if ( $this->textbox1
== '' ) {
2133 $this->missingComment
= true;
2134 $status->fatal( 'missingcommenttext' );
2135 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2138 } elseif ( !$this->allowBlankSummary
2139 && !$content->equals( $this->getOriginalContent( $user ) )
2140 && !$content->isRedirect()
2141 && md5( $this->summary
) == $this->autoSumm
2143 $this->missingSummary
= true;
2144 $status->fatal( 'missingsummary' );
2145 $status->value
= self
::AS_SUMMARY_NEEDED
;
2150 $sectionanchor = '';
2151 if ( $this->section
== 'new' ) {
2152 $this->summary
= $this->newSectionSummary( $sectionanchor );
2153 } elseif ( $this->section
!= '' ) {
2154 # Try to get a section anchor from the section source, redirect
2155 # to edited section if header found.
2156 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2157 # for duplicate heading checking and maybe parsing.
2158 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2159 # We can't deal with anchors, includes, html etc in the header for now,
2160 # headline would need to be parsed to improve this.
2161 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2162 $sectionanchor = $this->guessSectionName( $matches[2] );
2165 $result['sectionanchor'] = $sectionanchor;
2167 // Save errors may fall down to the edit form, but we've now
2168 // merged the section into full text. Clear the section field
2169 // so that later submission of conflict forms won't try to
2170 // replace that into a duplicated mess.
2171 $this->textbox1
= $this->toEditText( $content );
2172 $this->section
= '';
2174 $status->value
= self
::AS_SUCCESS_UPDATE
;
2177 if ( !$this->allowSelfRedirect
2178 && $content->isRedirect()
2179 && $content->getRedirectTarget()->equals( $this->getTitle() )
2181 // If the page already redirects to itself, don't warn.
2182 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2183 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2184 $this->selfRedirect
= true;
2185 $status->fatal( 'selfredirect' );
2186 $status->value
= self
::AS_SELF_REDIRECT
;
2191 // Check for length errors again now that the section is merged in
2192 $this->contentLength
= strlen( $this->toEditText( $content ) );
2193 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2194 $this->tooBig
= true;
2195 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2199 $flags = EDIT_AUTOSUMMARY |
2200 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2201 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2202 ( $bot ? EDIT_FORCE_BOT
: 0 );
2204 $doEditStatus = $this->page
->doEditContent(
2210 $content->getDefaultFormat(),
2215 if ( !$doEditStatus->isOK() ) {
2216 // Failure from doEdit()
2217 // Show the edit conflict page for certain recognized errors from doEdit(),
2218 // but don't show it for errors from extension hooks
2219 $errors = $doEditStatus->getErrorsArray();
2220 if ( in_array( $errors[0][0],
2221 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2223 $this->isConflict
= true;
2224 // Destroys data doEdit() put in $status->value but who cares
2225 $doEditStatus->value
= self
::AS_END
;
2227 return $doEditStatus;
2230 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2231 if ( $result['nullEdit'] ) {
2232 // We don't know if it was a null edit until now, so increment here
2233 $user->pingLimiter( 'linkpurge' );
2235 $result['redirect'] = $content->isRedirect();
2237 $this->updateWatchlist();
2239 // If the content model changed, add a log entry
2240 if ( $changingContentModel ) {
2241 $this->addContentModelChangeLogEntry(
2243 $new ?
false : $oldContentModel,
2244 $this->contentModel
,
2254 * @param string|false $oldModel false if the page is being newly created
2255 * @param string $newModel
2256 * @param string $reason
2258 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2259 $new = $oldModel === false;
2260 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2261 $log->setPerformer( $user );
2262 $log->setTarget( $this->mTitle
);
2263 $log->setComment( $reason );
2264 $log->setParameters( [
2265 '4::oldmodel' => $oldModel,
2266 '5::newmodel' => $newModel
2268 $logid = $log->insert();
2269 $log->publish( $logid );
2273 * Register the change of watch status
2275 protected function updateWatchlist() {
2276 $user = $this->context
->getUser();
2277 if ( !$user->isLoggedIn() ) {
2281 $title = $this->mTitle
;
2282 $watch = $this->watchthis
;
2283 // Do this in its own transaction to reduce contention...
2284 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2285 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2286 return; // nothing to change
2288 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2293 * Attempts to do 3-way merge of edit content with a base revision
2294 * and current content, in case of edit conflict, in whichever way appropriate
2295 * for the content type.
2299 * @param Content $editContent
2303 private function mergeChangesIntoContent( &$editContent ) {
2304 $db = wfGetDB( DB_MASTER
);
2306 // This is the revision the editor started from
2307 $baseRevision = $this->getBaseRevision();
2308 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2310 if ( is_null( $baseContent ) ) {
2314 // The current state, we want to merge updates into it
2315 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2316 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2318 if ( is_null( $currentContent ) ) {
2322 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2324 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2327 $editContent = $result;
2328 // Update parentRevId to what we just merged.
2329 $this->parentRevId
= $currentRevision->getId();
2337 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2338 * one might think of X as the "base revision", which is NOT what this returns.
2339 * @return Revision|null Current version when the edit was started
2341 public function getBaseRevision() {
2342 if ( !$this->mBaseRevision
) {
2343 $db = wfGetDB( DB_MASTER
);
2344 $this->mBaseRevision
= $this->editRevId
2345 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2346 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2348 return $this->mBaseRevision
;
2352 * Check given input text against $wgSpamRegex, and return the text of the first match.
2354 * @param string $text
2356 * @return string|bool Matching string or false
2358 public static function matchSpamRegex( $text ) {
2359 global $wgSpamRegex;
2360 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2361 $regexes = (array)$wgSpamRegex;
2362 return self
::matchSpamRegexInternal( $text, $regexes );
2366 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2368 * @param string $text
2370 * @return string|bool Matching string or false
2372 public static function matchSummarySpamRegex( $text ) {
2373 global $wgSummarySpamRegex;
2374 $regexes = (array)$wgSummarySpamRegex;
2375 return self
::matchSpamRegexInternal( $text, $regexes );
2379 * @param string $text
2380 * @param array $regexes
2381 * @return bool|string
2383 protected static function matchSpamRegexInternal( $text, $regexes ) {
2384 foreach ( $regexes as $regex ) {
2386 if ( preg_match( $regex, $text, $matches ) ) {
2393 public function setHeaders() {
2394 $out = $this->context
->getOutput();
2396 $out->addModules( 'mediawiki.action.edit' );
2397 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2398 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2400 $user = $this->context
->getUser();
2401 if ( $user->getOption( 'showtoolbar' ) ) {
2402 // The addition of default buttons is handled by getEditToolbar() which
2403 // has its own dependency on this module. The call here ensures the module
2404 // is loaded in time (it has position "top") for other modules to register
2405 // buttons (e.g. extensions, gadgets, user scripts).
2406 $out->addModules( 'mediawiki.toolbar' );
2409 if ( $user->getOption( 'uselivepreview' ) ) {
2410 $out->addModules( 'mediawiki.action.edit.preview' );
2413 if ( $user->getOption( 'useeditwarning' ) ) {
2414 $out->addModules( 'mediawiki.action.edit.editWarning' );
2417 # Enabled article-related sidebar, toplinks, etc.
2418 $out->setArticleRelated( true );
2420 $contextTitle = $this->getContextTitle();
2421 if ( $this->isConflict
) {
2422 $msg = 'editconflict';
2423 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2424 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2426 $msg = $contextTitle->exists()
2427 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2428 && $contextTitle->getDefaultMessageText() !== false
2434 # Use the title defined by DISPLAYTITLE magic word when present
2435 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2436 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2437 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2438 if ( $displayTitle === false ) {
2439 $displayTitle = $contextTitle->getPrefixedText();
2441 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2443 $config = $this->context
->getConfig();
2445 # Transmit the name of the message to JavaScript for live preview
2446 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2447 $out->addJsConfigVars( [
2448 'wgEditMessage' => $msg,
2449 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2452 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2454 $out->addJsConfigVars(
2455 'wgEditSubmitButtonLabelPublish',
2456 $config->get( 'EditSubmitButtonLabelPublish' )
2461 * Show all applicable editing introductions
2463 protected function showIntro() {
2464 if ( $this->suppressIntro
) {
2468 $out = $this->context
->getOutput();
2469 $namespace = $this->mTitle
->getNamespace();
2471 if ( $namespace == NS_MEDIAWIKI
) {
2472 # Show a warning if editing an interface message
2473 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2474 # If this is a default message (but not css, json, or js),
2475 # show a hint that it is translatable on translatewiki.net
2477 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2478 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2479 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2481 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2482 if ( $defaultMessageText !== false ) {
2483 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2484 'translateinterface' );
2487 } elseif ( $namespace == NS_FILE
) {
2488 # Show a hint to shared repo
2489 $file = wfFindFile( $this->mTitle
);
2490 if ( $file && !$file->isLocal() ) {
2491 $descUrl = $file->getDescriptionUrl();
2492 # there must be a description url to show a hint to shared repo
2494 if ( !$this->mTitle
->exists() ) {
2495 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2496 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2499 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2500 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2507 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2508 # Show log extract when the user is currently blocked
2509 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2510 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2511 $user = User
::newFromName( $username, false /* allow IP users */ );
2512 $ip = User
::isIP( $username );
2513 $block = Block
::newFromTarget( $user, $user );
2514 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2515 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2516 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2517 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2518 # Show log extract if the user is currently blocked
2519 LogEventsList
::showLogExtract(
2522 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2526 'showIfEmpty' => false,
2528 'blocked-notice-logextract',
2529 $user->getName() # Support GENDER in notice
2535 # Try to add a custom edit intro, or use the standard one if this is not possible.
2536 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2537 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2538 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2540 if ( $this->context
->getUser()->isLoggedIn() ) {
2542 // Suppress the external link icon, consider the help url an internal one
2543 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2551 // Suppress the external link icon, consider the help url an internal one
2552 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2554 'newarticletextanon',
2560 # Give a notice if the user is editing a deleted/moved page...
2561 if ( !$this->mTitle
->exists() ) {
2562 $dbr = wfGetDB( DB_REPLICA
);
2564 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2568 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2569 'showIfEmpty' => false,
2570 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2577 * Attempt to show a custom editing introduction, if supplied
2581 protected function showCustomIntro() {
2582 if ( $this->editintro
) {
2583 $title = Title
::newFromText( $this->editintro
);
2584 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2585 // Added using template syntax, to take <noinclude>'s into account.
2586 $this->context
->getOutput()->addWikiTextTitleTidy(
2587 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2597 * Gets an editable textual representation of $content.
2598 * The textual representation can be turned by into a Content object by the
2599 * toEditContent() method.
2601 * If $content is null or false or a string, $content is returned unchanged.
2603 * If the given Content object is not of a type that can be edited using
2604 * the text base EditPage, an exception will be raised. Set
2605 * $this->allowNonTextContent to true to allow editing of non-textual
2608 * @param Content|null|bool|string $content
2609 * @return string The editable text form of the content.
2611 * @throws MWException If $content is not an instance of TextContent and
2612 * $this->allowNonTextContent is not true.
2614 protected function toEditText( $content ) {
2615 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2619 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2620 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2623 return $content->serialize( $this->contentFormat
);
2627 * Turns the given text into a Content object by unserializing it.
2629 * If the resulting Content object is not of a type that can be edited using
2630 * the text base EditPage, an exception will be raised. Set
2631 * $this->allowNonTextContent to true to allow editing of non-textual
2634 * @param string|null|bool $text Text to unserialize
2635 * @return Content|bool|null The content object created from $text. If $text was false
2636 * or null, false resp. null will be returned instead.
2638 * @throws MWException If unserializing the text results in a Content
2639 * object that is not an instance of TextContent and
2640 * $this->allowNonTextContent is not true.
2642 protected function toEditContent( $text ) {
2643 if ( $text === false ||
$text === null ) {
2647 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2648 $this->contentModel
, $this->contentFormat
);
2650 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2651 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2658 * Send the edit form and related headers to OutputPage
2659 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2660 * during form output near the top, for captchas and the like.
2662 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2663 * use the EditPage::showEditForm:fields hook instead.
2665 public function showEditForm( $formCallback = null ) {
2666 # need to parse the preview early so that we know which templates are used,
2667 # otherwise users with "show preview after edit box" will get a blank list
2668 # we parse this near the beginning so that setHeaders can do the title
2669 # setting work instead of leaving it in getPreviewText
2670 $previewOutput = '';
2671 if ( $this->formtype
== 'preview' ) {
2672 $previewOutput = $this->getPreviewText();
2675 $out = $this->context
->getOutput();
2677 // Avoid PHP 7.1 warning of passing $this by reference
2679 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2681 $this->setHeaders();
2683 $this->addTalkPageText();
2684 $this->addEditNotices();
2686 if ( !$this->isConflict
&&
2687 $this->section
!= '' &&
2688 !$this->isSectionEditSupported() ) {
2689 // We use $this->section to much before this and getVal('wgSection') directly in other places
2690 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2691 // Someone is welcome to try refactoring though
2692 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2696 $this->showHeader();
2698 $out->addHTML( $this->editFormPageTop
);
2700 $user = $this->context
->getUser();
2701 if ( $user->getOption( 'previewontop' ) ) {
2702 $this->displayPreviewArea( $previewOutput, true );
2705 $out->addHTML( $this->editFormTextTop
);
2707 $showToolbar = true;
2708 if ( $this->wasDeletedSinceLastEdit() ) {
2709 if ( $this->formtype
== 'save' ) {
2710 // Hide the toolbar and edit area, user can click preview to get it back
2711 // Add an confirmation checkbox and explanation.
2712 $showToolbar = false;
2714 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2715 'deletedwhileediting' );
2719 // @todo add EditForm plugin interface and use it here!
2720 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2721 $out->addHTML( Html
::openElement(
2724 'class' => 'mw-editform',
2725 'id' => self
::EDITFORM_ID
,
2726 'name' => self
::EDITFORM_ID
,
2728 'action' => $this->getActionURL( $this->getContextTitle() ),
2729 'enctype' => 'multipart/form-data'
2733 if ( is_callable( $formCallback ) ) {
2734 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2735 call_user_func_array( $formCallback, [ &$out ] );
2738 // Add a check for Unicode support
2739 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2741 // Add an empty field to trip up spambots
2743 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2746 [ 'for' => 'wpAntispam' ],
2747 $this->context
->msg( 'simpleantispam-label' )->parse()
2753 'name' => 'wpAntispam',
2754 'id' => 'wpAntispam',
2758 . Xml
::closeElement( 'div' )
2761 // Avoid PHP 7.1 warning of passing $this by reference
2763 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2765 // Put these up at the top to ensure they aren't lost on early form submission
2766 $this->showFormBeforeText();
2768 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2769 $username = $this->lastDelete
->user_name
;
2770 $comment = CommentStore
::getStore()
2771 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2773 // It is better to not parse the comment at all than to have templates expanded in the middle
2774 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2775 $key = $comment === ''
2776 ?
'confirmrecreate-noreason'
2777 : 'confirmrecreate';
2779 '<div class="mw-confirm-recreate">' .
2780 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2781 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2782 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2788 # When the summary is hidden, also hide them on preview/show changes
2789 if ( $this->nosummary
) {
2790 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2793 # If a blank edit summary was previously provided, and the appropriate
2794 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2795 # user being bounced back more than once in the event that a summary
2798 # For a bit more sophisticated detection of blank summaries, hash the
2799 # automatic one and pass that in the hidden field wpAutoSummary.
2800 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2801 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2804 if ( $this->undidRev
) {
2805 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2808 if ( $this->selfRedirect
) {
2809 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2812 if ( $this->hasPresetSummary
) {
2813 // If a summary has been preset using &summary= we don't want to prompt for
2814 // a different summary. Only prompt for a summary if the summary is blanked.
2816 $this->autoSumm
= md5( '' );
2819 $autosumm = $this->autoSumm ?
: md5( $this->summary
);
2820 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2822 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2823 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2825 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2826 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2830 if ( $this->section
== 'new' ) {
2831 $this->showSummaryInput( true, $this->summary
);
2832 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2835 $out->addHTML( $this->editFormTextBeforeContent
);
2836 if ( $this->isConflict
) {
2837 // In an edit conflict, we turn textbox2 into the user's text,
2838 // and textbox1 into the stored version
2839 $this->textbox2
= $this->textbox1
;
2841 $content = $this->getCurrentContent();
2842 $this->textbox1
= $this->toEditText( $content );
2844 $editConflictHelper = $this->getEditConflictHelper();
2845 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2846 $editConflictHelper->setContentModel( $this->contentModel
);
2847 $editConflictHelper->setContentFormat( $this->contentFormat
);
2848 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2851 if ( !$this->mTitle
->isUserConfigPage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2852 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2855 if ( $this->blankArticle
) {
2856 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2859 if ( $this->isConflict
) {
2860 // In an edit conflict bypass the overridable content form method
2861 // and fallback to the raw wpTextbox1 since editconflicts can't be
2862 // resolved between page source edits and custom ui edits using the
2864 $conflictTextBoxAttribs = [];
2865 if ( $this->wasDeletedSinceLastEdit() ) {
2866 $conflictTextBoxAttribs['style'] = 'display:none;';
2867 } elseif ( $this->isOldRev
) {
2868 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2871 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2872 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2874 $this->showContentForm();
2877 $out->addHTML( $this->editFormTextAfterContent
);
2879 $this->showStandardInputs();
2881 $this->showFormAfterText();
2883 $this->showTosSummary();
2885 $this->showEditTools();
2887 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2889 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2891 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2892 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2894 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2895 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2897 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2899 if ( $this->isConflict
) {
2901 $this->showConflict();
2902 } catch ( MWContentSerializationException
$ex ) {
2903 // this can't really happen, but be nice if it does.
2904 $msg = $this->context
->msg(
2905 'content-failed-to-parse',
2906 $this->contentModel
,
2907 $this->contentFormat
,
2910 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2914 // Set a hidden field so JS knows what edit form mode we are in
2915 if ( $this->isConflict
) {
2917 } elseif ( $this->preview
) {
2919 } elseif ( $this->diff
) {
2924 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2926 // Marker for detecting truncated form data. This must be the last
2927 // parameter sent in order to be of use, so do not move me.
2928 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2929 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2931 if ( !$user->getOption( 'previewontop' ) ) {
2932 $this->displayPreviewArea( $previewOutput, false );
2937 * Wrapper around TemplatesOnThisPageFormatter to make
2938 * a "templates on this page" list.
2940 * @param Title[] $templates
2941 * @return string HTML
2943 public function makeTemplatesOnThisPageList( array $templates ) {
2944 $templateListFormatter = new TemplatesOnThisPageFormatter(
2945 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2948 // preview if preview, else section if section, else false
2950 if ( $this->preview
) {
2952 } elseif ( $this->section
!= '' ) {
2956 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2957 $templateListFormatter->format( $templates, $type )
2962 * Extract the section title from current section text, if any.
2964 * @param string $text
2965 * @return string|bool String or false
2967 public static function extractSectionTitle( $text ) {
2968 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2969 if ( !empty( $matches[2] ) ) {
2971 return $wgParser->stripSectionName( trim( $matches[2] ) );
2977 protected function showHeader() {
2978 $out = $this->context
->getOutput();
2979 $user = $this->context
->getUser();
2980 if ( $this->isConflict
) {
2981 $this->addExplainConflictHeader( $out );
2982 $this->editRevId
= $this->page
->getLatest();
2984 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2985 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2986 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2987 if ( $sectionTitle !== false ) {
2988 $this->summary
= "/* $sectionTitle */ ";
2993 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
2995 if ( $this->missingComment
) {
2996 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2999 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
3001 "<div id='mw-missingsummary'>\n$1\n</div>",
3002 [ 'missingsummary', $buttonLabel ]
3006 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3008 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3009 [ 'missingcommentheader', $buttonLabel ]
3013 if ( $this->blankArticle
) {
3015 "<div id='mw-blankarticle'>\n$1\n</div>",
3016 [ 'blankarticle', $buttonLabel ]
3020 if ( $this->selfRedirect
) {
3022 "<div id='mw-selfredirect'>\n$1\n</div>",
3023 [ 'selfredirect', $buttonLabel ]
3027 if ( $this->hookError
!== '' ) {
3028 $out->addWikiText( $this->hookError
);
3031 if ( $this->section
!= 'new' ) {
3032 $revision = $this->mArticle
->getRevisionFetched();
3034 // Let sysop know that this will make private content public if saved
3036 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3038 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3039 'rev-deleted-text-permission'
3041 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3043 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3044 'rev-deleted-text-view'
3048 if ( !$revision->isCurrent() ) {
3049 $this->mArticle
->setOldSubtitle( $revision->getId() );
3050 $out->addWikiMsg( 'editingold' );
3051 $this->isOldRev
= true;
3053 } elseif ( $this->mTitle
->exists() ) {
3054 // Something went wrong
3056 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3057 [ 'missing-revision', $this->oldid
] );
3062 if ( wfReadOnly() ) {
3064 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3065 [ 'readonlywarning', wfReadOnlyReason() ]
3067 } elseif ( $user->isAnon() ) {
3068 if ( $this->formtype
!= 'preview' ) {
3070 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3071 [ 'anoneditwarning',
3073 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3074 'returnto' => $this->getTitle()->getPrefixedDBkey()
3077 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3078 'returnto' => $this->getTitle()->getPrefixedDBkey()
3083 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3084 'anonpreviewwarning'
3088 if ( $this->mTitle
->isUserConfigPage() ) {
3089 # Check the skin exists
3090 if ( $this->isWrongCaseUserConfigPage() ) {
3092 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3093 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3096 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3097 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3098 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3099 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3101 $warning = $isUserCssConfig
3103 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3105 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3107 if ( $this->formtype
!== 'preview' ) {
3108 $config = $this->context
->getConfig();
3109 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3111 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3112 [ 'usercssyoucanpreview' ]
3114 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3116 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3117 [ 'userjsonyoucanpreview' ]
3119 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3121 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3122 [ 'userjsyoucanpreview' ]
3130 $this->addPageProtectionWarningHeaders();
3132 $this->addLongPageWarningHeader();
3134 # Add header copyright warning
3135 $this->showHeaderCopyrightWarning();
3139 * Helper function for summary input functions, which returns the neccessary
3140 * attributes for the input.
3142 * @param array|null $inputAttrs Array of attrs to use on the input
3145 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3146 $conf = $this->context
->getConfig();
3147 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
3148 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3149 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3150 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
3151 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3152 'id' => 'wpSummary',
3153 'name' => 'wpSummary',
3154 'maxlength' => $oldCommentSchema ?
200 : CommentStore
::COMMENT_CHARACTER_LIMIT
,
3157 'spellcheck' => 'true',
3162 * Builds a standard summary input with a label.
3164 * @param string $summary The value of the summary input
3165 * @param string $labelText The html to place inside the label
3166 * @param array $inputAttrs Array of attrs to use on the input
3168 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3170 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3171 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3172 $this->getSummaryInputAttributes( $inputAttrs )
3175 'title' => Linker
::titleAttrib( 'summary' ),
3176 'accessKey' => Linker
::accesskey( 'summary' ),
3179 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3180 $inputAttrs['inputId'] = $inputAttrs['id'];
3181 $inputAttrs['id'] = 'wpSummaryWidget';
3183 return new OOUI\
FieldLayout(
3184 new OOUI\
TextInputWidget( [
3185 'value' => $summary,
3186 'infusable' => true,
3189 'label' => new OOUI\
HtmlSnippet( $labelText ),
3191 'id' => 'wpSummaryLabel',
3192 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3198 * @param bool $isSubjectPreview True if this is the section subject/title
3199 * up top, or false if this is the comment summary
3200 * down below the textarea
3201 * @param string $summary The text of the summary to display
3203 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3204 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3205 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3206 if ( $isSubjectPreview ) {
3207 if ( $this->nosummary
) {
3211 if ( !$this->mShowSummaryField
) {
3216 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3217 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3220 [ 'class' => $summaryClass ]
3225 * @param bool $isSubjectPreview True if this is the section subject/title
3226 * up top, or false if this is the comment summary
3227 * down below the textarea
3228 * @param string $summary The text of the summary to display
3231 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3232 // avoid spaces in preview, gets always trimmed on save
3233 $summary = trim( $summary );
3234 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3240 if ( $isSubjectPreview ) {
3241 $summary = $this->context
->msg( 'newsectionsummary' )
3242 ->rawParams( $wgParser->stripSectionName( $summary ) )
3243 ->inContentLanguage()->text();
3246 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3248 $summary = $this->context
->msg( $message )->parse()
3249 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3250 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3253 protected function showFormBeforeText() {
3254 $out = $this->context
->getOutput();
3255 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3256 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3257 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3258 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3259 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3262 protected function showFormAfterText() {
3264 * To make it harder for someone to slip a user a page
3265 * which submits an edit form to the wiki without their
3266 * knowledge, a random token is associated with the login
3267 * session. If it's not passed back with the submission,
3268 * we won't save the page, or render user JavaScript and
3271 * For anon editors, who may not have a session, we just
3272 * include the constant suffix to prevent editing from
3273 * broken text-mangling proxies.
3275 $this->context
->getOutput()->addHTML(
3277 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3283 * Subpage overridable method for printing the form for page content editing
3284 * By default this simply outputs wpTextbox1
3285 * Subclasses can override this to provide a custom UI for editing;
3286 * be it a form, or simply wpTextbox1 with a modified content that will be
3287 * reverse modified when extracted from the post data.
3288 * Note that this is basically the inverse for importContentFormData
3290 protected function showContentForm() {
3291 $this->showTextbox1();
3295 * Method to output wpTextbox1
3296 * The $textoverride method can be used by subclasses overriding showContentForm
3297 * to pass back to this method.
3299 * @param array $customAttribs Array of html attributes to use in the textarea
3300 * @param string $textoverride Optional text to override $this->textarea1 with
3302 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3303 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3304 $attribs = [ 'style' => 'display:none;' ];
3306 $builder = new TextboxBuilder();
3307 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3309 # Is an old revision being edited?
3310 if ( $this->isOldRev
) {
3311 $classes[] = 'mw-textarea-oldrev';
3314 $attribs = [ 'tabindex' => 1 ];
3316 if ( is_array( $customAttribs ) ) {
3317 $attribs +
= $customAttribs;
3320 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3324 $textoverride !== null ?
$textoverride : $this->textbox1
,
3330 protected function showTextbox2() {
3331 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3334 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3335 $builder = new TextboxBuilder();
3336 $attribs = $builder->buildTextboxAttribs(
3339 $this->context
->getUser(),
3343 $this->context
->getOutput()->addHTML(
3344 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3348 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3351 $classes[] = 'ontop';
3354 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3356 if ( $this->formtype
!= 'preview' ) {
3357 $attribs['style'] = 'display: none;';
3360 $out = $this->context
->getOutput();
3361 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3363 if ( $this->formtype
== 'preview' ) {
3364 $this->showPreview( $previewOutput );
3366 // Empty content container for LivePreview
3367 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3368 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3369 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3370 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3373 $out->addHTML( '</div>' );
3375 if ( $this->formtype
== 'diff' ) {
3378 } catch ( MWContentSerializationException
$ex ) {
3379 $msg = $this->context
->msg(
3380 'content-failed-to-parse',
3381 $this->contentModel
,
3382 $this->contentFormat
,
3385 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3391 * Append preview output to OutputPage.
3392 * Includes category rendering if this is a category page.
3394 * @param string $text The HTML to be output for the preview.
3396 protected function showPreview( $text ) {
3397 if ( $this->mArticle
instanceof CategoryPage
) {
3398 $this->mArticle
->openShowCategory();
3400 # This hook seems slightly odd here, but makes things more
3401 # consistent for extensions.
3402 $out = $this->context
->getOutput();
3403 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3404 $out->addHTML( $text );
3405 if ( $this->mArticle
instanceof CategoryPage
) {
3406 $this->mArticle
->closeShowCategory();
3411 * Get a diff between the current contents of the edit box and the
3412 * version of the page we're editing from.
3414 * If this is a section edit, we'll replace the section as for final
3415 * save and then make a comparison.
3417 public function showDiff() {
3420 $oldtitlemsg = 'currentrev';
3421 # if message does not exist, show diff against the preloaded default
3422 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3423 $oldtext = $this->mTitle
->getDefaultMessageText();
3424 if ( $oldtext !== false ) {
3425 $oldtitlemsg = 'defaultmessagetext';
3426 $oldContent = $this->toEditContent( $oldtext );
3431 $oldContent = $this->getCurrentContent();
3434 $textboxContent = $this->toEditContent( $this->textbox1
);
3435 if ( $this->editRevId
!== null ) {
3436 $newContent = $this->page
->replaceSectionAtRev(
3437 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3440 $newContent = $this->page
->replaceSectionContent(
3441 $this->section
, $textboxContent, $this->summary
, $this->edittime
3445 if ( $newContent ) {
3446 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3448 $user = $this->context
->getUser();
3449 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
3450 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3453 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3454 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3455 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3457 if ( !$oldContent ) {
3458 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3461 if ( !$newContent ) {
3462 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3465 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3466 $de->setContent( $oldContent, $newContent );
3468 $difftext = $de->getDiff( $oldtitle, $newtitle );
3469 $de->showDiffStyle();
3474 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3478 * Show the header copyright warning.
3480 protected function showHeaderCopyrightWarning() {
3481 $msg = 'editpage-head-copy-warn';
3482 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3483 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3484 'editpage-head-copy-warn' );
3489 * Give a chance for site and per-namespace customizations of
3490 * terms of service summary link that might exist separately
3491 * from the copyright notice.
3493 * This will display between the save button and the edit tools,
3494 * so should remain short!
3496 protected function showTosSummary() {
3497 $msg = 'editpage-tos-summary';
3498 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3499 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3500 $out = $this->context
->getOutput();
3501 $out->addHTML( '<div class="mw-tos-summary">' );
3502 $out->addWikiMsg( $msg );
3503 $out->addHTML( '</div>' );
3508 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3509 * characters not present on most keyboards for copying/pasting.
3511 protected function showEditTools() {
3512 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3513 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3518 * Get the copyright warning
3520 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3523 protected function getCopywarn() {
3524 return self
::getCopyrightWarning( $this->mTitle
);
3528 * Get the copyright warning, by default returns wikitext
3530 * @param Title $title
3531 * @param string $format Output format, valid values are any function of a Message object
3532 * @param Language|string|null $langcode Language code or Language object.
3535 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3536 global $wgRightsText;
3537 if ( $wgRightsText ) {
3538 $copywarnMsg = [ 'copyrightwarning',
3539 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3542 $copywarnMsg = [ 'copyrightwarning2',
3543 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3545 // Allow for site and per-namespace customization of contribution/copyright notice.
3546 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3548 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3550 $msg->inLanguage( $langcode );
3552 return "<div id=\"editpage-copywarn\">\n" .
3553 $msg->$format() . "\n</div>";
3557 * Get the Limit report for page previews
3560 * @param ParserOutput $output ParserOutput object from the parse
3561 * @return string HTML
3563 public static function getPreviewLimitReport( $output ) {
3566 if ( !$output ||
!$output->getLimitReportData() ) {
3570 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3571 wfMessage( 'limitreport-title' )->parseAsBlock()
3574 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3575 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3577 $limitReport .= Html
::openElement( 'table', [
3578 'class' => 'preview-limit-report wikitable'
3580 Html
::openElement( 'tbody' );
3582 foreach ( $output->getLimitReportData() as $key => $value ) {
3583 if ( Hooks
::run( 'ParserLimitReportFormat',
3584 [ $key, &$value, &$limitReport, true, true ]
3586 $keyMsg = wfMessage( $key );
3587 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3588 if ( !$valueMsg->exists() ) {
3589 $valueMsg = new RawMessage( '$1' );
3591 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3592 $limitReport .= Html
::openElement( 'tr' ) .
3593 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3594 Html
::rawElement( 'td', null,
3595 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3597 Html
::closeElement( 'tr' );
3602 $limitReport .= Html
::closeElement( 'tbody' ) .
3603 Html
::closeElement( 'table' ) .
3604 Html
::closeElement( 'div' );
3606 return $limitReport;
3609 protected function showStandardInputs( &$tabindex = 2 ) {
3610 $out = $this->context
->getOutput();
3611 $out->addHTML( "<div class='editOptions'>\n" );
3613 if ( $this->section
!= 'new' ) {
3614 $this->showSummaryInput( false, $this->summary
);
3615 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3618 $checkboxes = $this->getCheckboxesWidget(
3620 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3622 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3624 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3626 // Show copyright warning.
3627 $out->addWikiText( $this->getCopywarn() );
3628 $out->addHTML( $this->editFormTextAfterWarn
);
3630 $out->addHTML( "<div class='editButtons'>\n" );
3631 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3633 $cancel = $this->getCancelLink();
3635 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3636 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3639 $this->context
->msg( 'edithelp' )->text(),
3640 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3643 $this->context
->msg( 'word-separator' )->escaped() .
3644 $this->context
->msg( 'newwindow' )->parse();
3646 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3647 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3648 $out->addHTML( "</div><!-- editButtons -->\n" );
3650 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3652 $out->addHTML( "</div><!-- editOptions -->\n" );
3656 * Show an edit conflict. textbox1 is already shown in showEditForm().
3657 * If you want to use another entry point to this function, be careful.
3659 protected function showConflict() {
3660 $out = $this->context
->getOutput();
3661 // Avoid PHP 7.1 warning of passing $this by reference
3663 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3664 $this->incrementConflictStats();
3666 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3670 protected function incrementConflictStats() {
3671 $this->getEditConflictHelper()->incrementConflictStats();
3677 public function getCancelLink() {
3679 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3680 $cancelParams['oldid'] = $this->oldid
;
3681 } elseif ( $this->getContextTitle()->isRedirect() ) {
3682 $cancelParams['redirect'] = 'no';
3685 return new OOUI\
ButtonWidget( [
3686 'id' => 'mw-editform-cancel',
3687 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3688 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3690 'infusable' => true,
3691 'flags' => 'destructive',
3696 * Returns the URL to use in the form's action attribute.
3697 * This is used by EditPage subclasses when simply customizing the action
3698 * variable in the constructor is not enough. This can be used when the
3699 * EditPage lives inside of a Special page rather than a custom page action.
3701 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3704 protected function getActionURL( Title
$title ) {
3705 return $title->getLocalURL( [ 'action' => $this->action
] );
3709 * Check if a page was deleted while the user was editing it, before submit.
3710 * Note that we rely on the logging table, which hasn't been always there,
3711 * but that doesn't matter, because this only applies to brand new
3715 protected function wasDeletedSinceLastEdit() {
3716 if ( $this->deletedSinceEdit
!== null ) {
3717 return $this->deletedSinceEdit
;
3720 $this->deletedSinceEdit
= false;
3722 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3723 $this->lastDelete
= $this->getLastDelete();
3724 if ( $this->lastDelete
) {
3725 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3726 if ( $deleteTime > $this->starttime
) {
3727 $this->deletedSinceEdit
= true;
3732 return $this->deletedSinceEdit
;
3736 * @return bool|stdClass
3738 protected function getLastDelete() {
3739 $dbr = wfGetDB( DB_REPLICA
);
3740 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3741 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3742 $data = $dbr->selectRow(
3743 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3753 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3755 'log_namespace' => $this->mTitle
->getNamespace(),
3756 'log_title' => $this->mTitle
->getDBkey(),
3757 'log_type' => 'delete',
3758 'log_action' => 'delete',
3761 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3763 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3764 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3766 // Quick paranoid permission checks...
3767 if ( is_object( $data ) ) {
3768 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3769 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3772 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3773 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3774 $data->log_comment_data
= null;
3782 * Get the rendered text for previewing.
3783 * @throws MWException
3786 public function getPreviewText() {
3787 $out = $this->context
->getOutput();
3788 $config = $this->context
->getConfig();
3790 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3791 // Could be an offsite preview attempt. This is very unsafe if
3792 // HTML is enabled, as it could be an attack.
3794 if ( $this->textbox1
!== '' ) {
3795 // Do not put big scary notice, if previewing the empty
3796 // string, which happens when you initially edit
3797 // a category page, due to automatic preview-on-open.
3798 $parsedNote = $out->parse( "<div class='previewnote'>" .
3799 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3800 true, /* interface */true );
3802 $this->incrementEditFailureStats( 'session_loss' );
3809 $content = $this->toEditContent( $this->textbox1
);
3813 'AlternateEditPreview',
3814 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3816 return $previewHTML;
3819 # provide a anchor link to the editform
3820 $continueEditing = '<span class="mw-continue-editing">' .
3821 '[[#' . self
::EDITFORM_ID
. '|' .
3822 $this->context
->getLanguage()->getArrow() . ' ' .
3823 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3824 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3825 if ( $this->mTokenOkExceptSuffix
) {
3826 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3827 $this->incrementEditFailureStats( 'bad_token' );
3829 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3830 $this->incrementEditFailureStats( 'session_loss' );
3832 } elseif ( $this->incompleteForm
) {
3833 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3834 if ( $this->mTriedSave
) {
3835 $this->incrementEditFailureStats( 'incomplete_form' );
3838 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3841 # don't parse non-wikitext pages, show message about preview
3842 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3843 if ( $this->mTitle
->isUserConfigPage() ) {
3845 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3851 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3853 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3856 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3858 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3861 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3863 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3870 # Used messages to make sure grep find them:
3871 # Messages: usercsspreview, userjsonpreview, userjspreview,
3872 # sitecsspreview, sitejsonpreview, sitejspreview
3873 if ( $level && $format ) {
3874 $note = "<div id='mw-{$level}{$format}preview'>" .
3875 $this->context
->msg( "{$level}{$format}preview" )->text() .
3876 ' ' . $continueEditing . "</div>";
3880 # If we're adding a comment, we need to show the
3881 # summary as the headline
3882 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3883 $content = $content->addSectionHeader( $this->summary
);
3886 $hook_args = [ $this, &$content ];
3887 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3889 $parserResult = $this->doPreviewParse( $content );
3890 $parserOutput = $parserResult['parserOutput'];
3891 $previewHTML = $parserResult['html'];
3892 $this->mParserOutput
= $parserOutput;
3893 $out->addParserOutputMetadata( $parserOutput );
3894 if ( $out->userCanPreview() ) {
3895 $out->addContentOverride( $this->getTitle(), $content );
3898 if ( count( $parserOutput->getWarnings() ) ) {
3899 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3902 } catch ( MWContentSerializationException
$ex ) {
3903 $m = $this->context
->msg(
3904 'content-failed-to-parse',
3905 $this->contentModel
,
3906 $this->contentFormat
,
3909 $note .= "\n\n" . $m->parse();
3913 if ( $this->isConflict
) {
3914 $conflict = '<h2 id="mw-previewconflict">'
3915 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3917 $conflict = '<hr />';
3920 $previewhead = "<div class='previewnote'>\n" .
3921 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3922 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3924 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3925 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3926 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3927 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3929 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3932 private function incrementEditFailureStats( $failureType ) {
3933 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3934 $stats->increment( 'edit.failures.' . $failureType );
3938 * Get parser options for a preview
3939 * @return ParserOptions
3941 protected function getPreviewParserOptions() {
3942 $parserOptions = $this->page
->makeParserOptions( $this->context
);
3943 $parserOptions->setIsPreview( true );
3944 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3945 $parserOptions->enableLimitReport();
3946 return $parserOptions;
3950 * Parse the page for a preview. Subclasses may override this class, in order
3951 * to parse with different options, or to otherwise modify the preview HTML.
3953 * @param Content $content The page content
3954 * @return array with keys:
3955 * - parserOutput: The ParserOutput object
3956 * - html: The HTML to be displayed
3958 protected function doPreviewParse( Content
$content ) {
3959 $user = $this->context
->getUser();
3960 $parserOptions = $this->getPreviewParserOptions();
3961 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
3962 $scopedCallback = $parserOptions->setupFakeRevision(
3963 $this->mTitle
, $pstContent, $user );
3964 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3965 ScopedCallback
::consume( $scopedCallback );
3967 'parserOutput' => $parserOutput,
3968 'html' => $parserOutput->getText( [
3969 'enableSectionEditLinks' => false
3977 public function getTemplates() {
3978 if ( $this->preview ||
$this->section
!= '' ) {
3980 if ( !isset( $this->mParserOutput
) ) {
3983 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3984 foreach ( array_keys( $template ) as $dbk ) {
3985 $templates[] = Title
::makeTitle( $ns, $dbk );
3990 return $this->mTitle
->getTemplateLinksFrom();
3995 * Shows a bulletin board style toolbar for common editing functions.
3996 * It can be disabled in the user preferences.
3998 * @param Title $title Title object for the page being edited (optional)
4001 public static function getEditToolbar( $title = null ) {
4002 global $wgContLang, $wgOut;
4003 global $wgEnableUploads, $wgForeignFileRepos;
4005 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
4006 $showSignature = true;
4008 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4012 * $toolarray is an array of arrays each of which includes the
4013 * opening tag, the closing tag, optionally a sample text that is
4014 * inserted between the two when no selection is highlighted
4015 * and. The tip text is shown when the user moves the mouse
4018 * Images are defined in ResourceLoaderEditToolbarModule.
4022 'id' => 'mw-editbutton-bold',
4024 'close' => '\'\'\'',
4025 'sample' => wfMessage( 'bold_sample' )->text(),
4026 'tip' => wfMessage( 'bold_tip' )->text(),
4029 'id' => 'mw-editbutton-italic',
4032 'sample' => wfMessage( 'italic_sample' )->text(),
4033 'tip' => wfMessage( 'italic_tip' )->text(),
4036 'id' => 'mw-editbutton-link',
4039 'sample' => wfMessage( 'link_sample' )->text(),
4040 'tip' => wfMessage( 'link_tip' )->text(),
4043 'id' => 'mw-editbutton-extlink',
4046 'sample' => wfMessage( 'extlink_sample' )->text(),
4047 'tip' => wfMessage( 'extlink_tip' )->text(),
4050 'id' => 'mw-editbutton-headline',
4053 'sample' => wfMessage( 'headline_sample' )->text(),
4054 'tip' => wfMessage( 'headline_tip' )->text(),
4056 $imagesAvailable ?
[
4057 'id' => 'mw-editbutton-image',
4058 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4060 'sample' => wfMessage( 'image_sample' )->text(),
4061 'tip' => wfMessage( 'image_tip' )->text(),
4063 $imagesAvailable ?
[
4064 'id' => 'mw-editbutton-media',
4065 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4067 'sample' => wfMessage( 'media_sample' )->text(),
4068 'tip' => wfMessage( 'media_tip' )->text(),
4071 'id' => 'mw-editbutton-nowiki',
4072 'open' => "<nowiki>",
4073 'close' => "</nowiki>",
4074 'sample' => wfMessage( 'nowiki_sample' )->text(),
4075 'tip' => wfMessage( 'nowiki_tip' )->text(),
4078 'id' => 'mw-editbutton-signature',
4079 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4082 'tip' => wfMessage( 'sig_tip' )->text(),
4085 'id' => 'mw-editbutton-hr',
4086 'open' => "\n----\n",
4089 'tip' => wfMessage( 'hr_tip' )->text(),
4093 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4094 foreach ( $toolarray as $tool ) {
4100 // Images are defined in ResourceLoaderEditToolbarModule
4102 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4103 // Older browsers show a "speedtip" type message only for ALT.
4104 // Ideally these should be different, realistically they
4105 // probably don't need to be.
4113 $script .= Xml
::encodeJsCall(
4114 'mw.toolbar.addButton',
4116 ResourceLoader
::inDebugMode()
4122 $toolbar = '<div id="toolbar"></div>';
4124 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4125 // Only add the old toolbar cruft to the page payload if the toolbar has not
4126 // been over-written by a hook caller
4127 $nonce = $wgOut->getCSPNonce();
4128 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script, $nonce ) );
4135 * Return an array of checkbox definitions.
4137 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4139 * Array values are associative arrays with the following keys:
4140 * - 'label-message' (required): message for label text
4141 * - 'id' (required): 'id' attribute for the `<input>`
4142 * - 'default' (required): default checkedness (true or false)
4143 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4144 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4145 * from messages like 'tooltip-foo', 'accesskey-foo'
4146 * - 'label-id' (optional): 'id' attribute for the `<label>`
4147 * - 'legacy-name' (optional): short name for backwards-compatibility
4148 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4149 * where bool indicates the checked status of the checkbox
4152 public function getCheckboxesDefinition( $checked ) {
4155 $user = $this->context
->getUser();
4156 // don't show the minor edit checkbox if it's a new page or section
4157 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4158 $checkboxes['wpMinoredit'] = [
4159 'id' => 'wpMinoredit',
4160 'label-message' => 'minoredit',
4161 // Uses messages: tooltip-minoredit, accesskey-minoredit
4162 'tooltip' => 'minoredit',
4163 'label-id' => 'mw-editpage-minoredit',
4164 'legacy-name' => 'minor',
4165 'default' => $checked['minor'],
4169 if ( $user->isLoggedIn() ) {
4170 $checkboxes['wpWatchthis'] = [
4171 'id' => 'wpWatchthis',
4172 'label-message' => 'watchthis',
4173 // Uses messages: tooltip-watch, accesskey-watch
4174 'tooltip' => 'watch',
4175 'label-id' => 'mw-editpage-watch',
4176 'legacy-name' => 'watch',
4177 'default' => $checked['watch'],
4182 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4188 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4189 * any other added by extensions.
4191 * @param int &$tabindex Current tabindex
4192 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4193 * status of the checkbox
4195 * @return array Associative array of string keys to OOUI\FieldLayout instances
4197 public function getCheckboxesWidget( &$tabindex, $checked ) {
4199 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4201 foreach ( $checkboxesDef as $name => $options ) {
4202 $legacyName = $options['legacy-name'] ??
$name;
4206 if ( isset( $options['tooltip'] ) ) {
4207 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4208 $title = Linker
::titleAttrib( $options['tooltip'] );
4210 if ( isset( $options['title-message'] ) ) {
4211 $title = $this->context
->msg( $options['title-message'] )->text();
4214 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4215 new OOUI\
CheckboxInputWidget( [
4216 'tabIndex' => ++
$tabindex,
4217 'accessKey' => $accesskey,
4218 'id' => $options['id'] . 'Widget',
4219 'inputId' => $options['id'],
4221 'selected' => $options['default'],
4222 'infusable' => true,
4225 'align' => 'inline',
4226 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4228 'id' => $options['label-id'] ??
null,
4237 * Get the message key of the label for the button to save the page
4242 protected function getSubmitButtonLabel() {
4244 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4246 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4247 $newPage = !$this->mTitle
->exists();
4249 if ( $labelAsPublish ) {
4250 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4252 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4255 return $buttonLabelKey;
4259 * Returns an array of html code of the following buttons:
4260 * save, diff and preview
4262 * @param int &$tabindex Current tabindex
4266 public function getEditButtons( &$tabindex ) {
4270 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4272 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4273 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4275 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4277 'tabIndex' => ++
$tabindex,
4278 'id' => 'wpSaveWidget',
4279 'inputId' => 'wpSave',
4280 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4281 'useInputTag' => true,
4282 'flags' => [ 'progressive', 'primary' ],
4283 'label' => $buttonLabel,
4284 'infusable' => true,
4286 // Messages used: tooltip-save, tooltip-publish
4287 'title' => Linker
::titleAttrib( $buttonTooltip ),
4288 // Messages used: accesskey-save, accesskey-publish
4289 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4292 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4293 'name' => 'wpPreview',
4294 'tabIndex' => ++
$tabindex,
4295 'id' => 'wpPreviewWidget',
4296 'inputId' => 'wpPreview',
4297 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4298 'useInputTag' => true,
4299 'label' => $this->context
->msg( 'showpreview' )->text(),
4300 'infusable' => true,
4302 // Message used: tooltip-preview
4303 'title' => Linker
::titleAttrib( 'preview' ),
4304 // Message used: accesskey-preview
4305 'accessKey' => Linker
::accesskey( 'preview' ),
4308 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4310 'tabIndex' => ++
$tabindex,
4311 'id' => 'wpDiffWidget',
4312 'inputId' => 'wpDiff',
4313 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4314 'useInputTag' => true,
4315 'label' => $this->context
->msg( 'showdiff' )->text(),
4316 'infusable' => true,
4318 // Message used: tooltip-diff
4319 'title' => Linker
::titleAttrib( 'diff' ),
4320 // Message used: accesskey-diff
4321 'accessKey' => Linker
::accesskey( 'diff' ),
4324 // Avoid PHP 7.1 warning of passing $this by reference
4326 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4332 * Creates a basic error page which informs the user that
4333 * they have attempted to edit a nonexistent section.
4335 public function noSuchSectionPage() {
4336 $out = $this->context
->getOutput();
4337 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4339 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4341 // Avoid PHP 7.1 warning of passing $this by reference
4343 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4344 $out->addHTML( $res );
4346 $out->returnToMain( false, $this->mTitle
);
4350 * Show "your edit contains spam" page with your diff and text
4352 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4354 public function spamPageWithContent( $match = false ) {
4355 $this->textbox2
= $this->textbox1
;
4357 if ( is_array( $match ) ) {
4358 $match = $this->context
->getLanguage()->listToText( $match );
4360 $out = $this->context
->getOutput();
4361 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4363 $out->addHTML( '<div id="spamprotected">' );
4364 $out->addWikiMsg( 'spamprotectiontext' );
4366 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4368 $out->addHTML( '</div>' );
4370 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4373 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4374 $this->showTextbox2();
4376 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4380 * Filter an input field through a Unicode de-armoring process if it
4381 * came from an old browser with known broken Unicode editing issues.
4383 * @deprecated since 1.30, does nothing
4385 * @param WebRequest $request
4386 * @param string $field
4389 protected function safeUnicodeInput( $request, $field ) {
4390 return rtrim( $request->getText( $field ) );
4394 * Filter an output field through a Unicode armoring process if it is
4395 * going to an old browser with known broken Unicode editing issues.
4397 * @deprecated since 1.30, does nothing
4399 * @param string $text
4402 protected function safeUnicodeOutput( $text ) {
4409 protected function addEditNotices() {
4410 $out = $this->context
->getOutput();
4411 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4412 if ( count( $editNotices ) ) {
4413 $out->addHTML( implode( "\n", $editNotices ) );
4415 $msg = $this->context
->msg( 'editnotice-notext' );
4416 if ( !$msg->isDisabled() ) {
4418 '<div class="mw-editnotice-notext">'
4419 . $msg->parseAsBlock()
4429 protected function addTalkPageText() {
4430 if ( $this->mTitle
->isTalkPage() ) {
4431 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4438 protected function addLongPageWarningHeader() {
4439 if ( $this->contentLength
=== false ) {
4440 $this->contentLength
= strlen( $this->textbox1
);
4443 $out = $this->context
->getOutput();
4444 $lang = $this->context
->getLanguage();
4445 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4446 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4447 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4450 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4451 $lang->formatNum( $maxArticleSize )
4455 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4456 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4459 $lang->formatSize( strlen( $this->textbox1
) ),
4460 strlen( $this->textbox1
)
4470 protected function addPageProtectionWarningHeaders() {
4471 $out = $this->context
->getOutput();
4472 if ( $this->mTitle
->isProtected( 'edit' ) &&
4473 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4475 # Is the title semi-protected?
4476 if ( $this->mTitle
->isSemiProtected() ) {
4477 $noticeMsg = 'semiprotectedpagewarning';
4479 # Then it must be protected based on static groups (regular)
4480 $noticeMsg = 'protectedpagewarning';
4482 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4483 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4485 if ( $this->mTitle
->isCascadeProtected() ) {
4486 # Is this page under cascading protection from some source pages?
4487 /** @var Title[] $cascadeSources */
4488 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4489 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4490 $cascadeSourcesCount = count( $cascadeSources );
4491 if ( $cascadeSourcesCount > 0 ) {
4492 # Explain, and list the titles responsible
4493 foreach ( $cascadeSources as $page ) {
4494 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4497 $notice .= '</div>';
4498 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4500 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4501 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4503 'showIfEmpty' => false,
4504 'msgKey' => [ 'titleprotectedwarning' ],
4505 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4510 * @param OutputPage $out
4513 protected function addExplainConflictHeader( OutputPage
$out ) {
4515 $this->getEditConflictHelper()->getExplainHeader()
4520 * @param string $name
4521 * @param mixed[] $customAttribs
4526 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4527 return ( new TextboxBuilder() )->buildTextboxAttribs(
4528 $name, $customAttribs, $user, $this->mTitle
4533 * @param string $wikitext
4537 protected function addNewLineAtEnd( $wikitext ) {
4538 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4542 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4543 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4544 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4545 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4546 * spread the new style links more efficiently.
4548 * @param string $text
4551 private function guessSectionName( $text ) {
4554 // Detect Microsoft browsers
4555 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4556 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4557 // ...and redirect them to legacy encoding, if available
4558 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4560 // Meanwhile, real browsers get real anchors
4561 return $wgParser->guessSectionNameFromWikiText( $text );
4565 * Set a factory function to create an EditConflictHelper
4567 * @param callable $factory Factory function
4570 public function setEditConflictHelperFactory( callable
$factory ) {
4571 $this->editConflictHelperFactory
= $factory;
4572 $this->editConflictHelper
= null;
4576 * @return TextConflictHelper
4578 private function getEditConflictHelper() {
4579 if ( !$this->editConflictHelper
) {
4580 $this->editConflictHelper
= call_user_func(
4581 $this->editConflictHelperFactory
,
4582 $this->getSubmitButtonLabel()
4586 return $this->editConflictHelper
;
4590 * @param string $submitButtonLabel
4591 * @return TextConflictHelper
4593 private function newTextConflictHelper( $submitButtonLabel ) {
4594 return new TextConflictHelper(
4596 $this->getContext()->getOutput(),
4597 MediaWikiServices
::getInstance()->getStatsdDataFactory(),