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" );
590 // Auto-block user's IP if the account was "hard" blocked
591 if ( !wfReadOnly() ) {
592 DeferredUpdates
::addCallableUpdate( function () {
593 $this->context
->getUser()->spreadAnyEditBlock();
596 $this->displayPermissionsError( $permErrors );
601 $revision = $this->mArticle
->getRevisionFetched();
602 // Disallow editing revisions with content models different from the current one
603 // Undo edits being an exception in order to allow reverting content model changes.
605 && $revision->getContentModel() !== $this->contentModel
608 if ( $this->undidRev
) {
609 $undidRevObj = Revision
::newFromId( $this->undidRev
);
610 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
612 if ( !$this->undidRev
614 ||
$prevRev->getContentModel() !== $this->contentModel
616 $this->displayViewSourcePage(
617 $this->getContentObject(),
619 'contentmodelediterror',
620 $revision->getContentModel(),
628 $this->isConflict
= false;
630 # Show applicable editing introductions
631 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
635 # Attempt submission here. This will check for edit conflicts,
636 # and redundantly check for locked database, blocked IPs, etc.
637 # that edit() already checked just in case someone tries to sneak
638 # in the back door with a hand-edited submission URL.
640 if ( 'save' == $this->formtype
) {
641 $resultDetails = null;
642 $status = $this->attemptSave( $resultDetails );
643 if ( !$this->handleStatus( $status, $resultDetails ) ) {
648 # First time through: get contents, set time for conflict
650 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
651 if ( $this->initialiseForm() === false ) {
652 $this->noSuchSectionPage();
656 if ( !$this->mTitle
->getArticleID() ) {
657 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
659 Hooks
::run( 'EditFormInitialText', [ $this ] );
664 $this->showEditForm();
668 * @param string $rigor Same format as Title::getUserPermissionErrors()
671 protected function getEditPermissionErrors( $rigor = 'secure' ) {
672 $user = $this->context
->getUser();
673 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
674 # Can this title be created?
675 if ( !$this->mTitle
->exists() ) {
676 $permErrors = array_merge(
679 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
684 # Ignore some permissions errors when a user is just previewing/viewing diffs
686 foreach ( $permErrors as $error ) {
687 if ( ( $this->preview ||
$this->diff
)
689 $error[0] == 'blockedtext' ||
690 $error[0] == 'autoblockedtext' ||
691 $error[0] == 'systemblockedtext'
697 $permErrors = wfArrayDiff2( $permErrors, $remove );
703 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
704 * but with the following differences:
705 * - If redlink=1, the user will be redirected to the page
706 * - If there is content to display or the error occurs while either saving,
707 * previewing or showing the difference, it will be a
708 * "View source for ..." page displaying the source code after the error message.
711 * @param array $permErrors Array of permissions errors, as returned by
712 * Title::getUserPermissionsErrors().
713 * @throws PermissionsError
715 protected function displayPermissionsError( array $permErrors ) {
716 $out = $this->context
->getOutput();
717 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
718 // The edit page was reached via a red link.
719 // Redirect to the article page and let them click the edit tab if
720 // they really want a permission error.
721 $out->redirect( $this->mTitle
->getFullURL() );
725 $content = $this->getContentObject();
727 # Use the normal message if there's nothing to display
728 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
729 $action = $this->mTitle
->exists() ?
'edit' :
730 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
731 throw new PermissionsError( $action, $permErrors );
734 $this->displayViewSourcePage(
736 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
741 * Display a read-only View Source page
742 * @param Content $content
743 * @param string $errorMessage additional wikitext error message to display
745 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
746 $out = $this->context
->getOutput();
747 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
749 $out->setRobotPolicy( 'noindex,nofollow' );
750 $out->setPageTitle( $this->context
->msg(
752 $this->getContextTitle()->getPrefixedText()
754 $out->addBacklinkSubtitle( $this->getContextTitle() );
755 $out->addHTML( $this->editFormPageTop
);
756 $out->addHTML( $this->editFormTextTop
);
758 if ( $errorMessage !== '' ) {
759 $out->addWikiText( $errorMessage );
760 $out->addHTML( "<hr />\n" );
763 # If the user made changes, preserve them when showing the markup
764 # (This happens when a user is blocked during edit, for instance)
765 if ( !$this->firsttime
) {
766 $text = $this->textbox1
;
767 $out->addWikiMsg( 'viewyourtext' );
770 $text = $this->toEditText( $content );
771 } catch ( MWException
$e ) {
772 # Serialize using the default format if the content model is not supported
773 # (e.g. for an old revision with a different model)
774 $text = $content->serialize();
776 $out->addWikiMsg( 'viewsourcetext' );
779 $out->addHTML( $this->editFormTextBeforeContent
);
780 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
781 $out->addHTML( $this->editFormTextAfterContent
);
783 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
785 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
787 $out->addHTML( $this->editFormTextBottom
);
788 if ( $this->mTitle
->exists() ) {
789 $out->returnToMain( null, $this->mTitle
);
794 * Should we show a preview when the edit form is first shown?
798 protected function previewOnOpen() {
799 $config = $this->context
->getConfig();
800 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
801 $request = $this->context
->getRequest();
802 if ( $config->get( 'RawHtml' ) ) {
803 // If raw HTML is enabled, disable preview on open
804 // since it has to be posted with a token for
808 if ( $request->getVal( 'preview' ) == 'yes' ) {
809 // Explicit override from request
811 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
812 // Explicit override from request
814 } elseif ( $this->section
== 'new' ) {
815 // Nothing *to* preview for new sections
817 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
818 && $this->context
->getUser()->getOption( 'previewonfirst' )
820 // Standard preference behavior
822 } elseif ( !$this->mTitle
->exists()
823 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
824 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
826 // Categories are special
834 * Checks whether the user entered a skin name in uppercase,
835 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
839 protected function isWrongCaseUserConfigPage() {
840 if ( $this->mTitle
->isUserConfigPage() ) {
841 $name = $this->mTitle
->getSkinFromConfigSubpage();
842 $skins = array_merge(
843 array_keys( Skin
::getSkinNames() ),
846 return !in_array( $name, $skins )
847 && in_array( strtolower( $name ), $skins );
854 * Returns whether section editing is supported for the current page.
855 * Subclasses may override this to replace the default behavior, which is
856 * to check ContentHandler::supportsSections.
858 * @return bool True if this edit page supports sections, false otherwise.
860 protected function isSectionEditSupported() {
861 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
862 return $contentHandler->supportsSections();
866 * This function collects the form data and uses it to populate various member variables.
867 * @param WebRequest &$request
868 * @throws ErrorPageError
870 public function importFormData( &$request ) {
871 # Section edit can come from either the form or a link
872 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
874 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
875 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
878 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
880 if ( $request->wasPosted() ) {
881 # These fields need to be checked for encoding.
882 # Also remove trailing whitespace, but don't remove _initial_
883 # whitespace from the text boxes. This may be significant formatting.
884 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
885 if ( !$request->getCheck( 'wpTextbox2' ) ) {
886 // Skip this if wpTextbox2 has input, it indicates that we came
887 // from a conflict page with raw page text, not a custom form
888 // modified by subclasses
889 $textbox1 = $this->importContentFormData( $request );
890 if ( $textbox1 !== null ) {
891 $this->textbox1
= $textbox1;
895 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
897 $this->summary
= $request->getText( 'wpSummary' );
899 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
900 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
902 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
904 # Treat sectiontitle the same way as summary.
905 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
906 # currently doing double duty as both edit summary and section title. Right now this
907 # is just to allow API edits to work around this limitation, but this should be
908 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
909 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
910 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
912 $this->edittime
= $request->getVal( 'wpEdittime' );
913 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
914 $this->starttime
= $request->getVal( 'wpStarttime' );
916 $undidRev = $request->getInt( 'wpUndidRevision' );
918 $this->undidRev
= $undidRev;
921 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
923 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
924 // wpTextbox1 field is missing, possibly due to being "too big"
925 // according to some filter rules such as Suhosin's setting for
926 // suhosin.request.max_value_length (d'oh)
927 $this->incompleteForm
= true;
929 // If we receive the last parameter of the request, we can fairly
930 // claim the POST request has not been truncated.
932 // TODO: softened the check for cutover. Once we determine
933 // that it is safe, we should complete the transition by
934 // removing the "edittime" clause.
935 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
936 && is_null( $this->edittime
) );
938 if ( $this->incompleteForm
) {
939 # If the form is incomplete, force to preview.
940 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
941 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
942 $this->preview
= true;
944 $this->preview
= $request->getCheck( 'wpPreview' );
945 $this->diff
= $request->getCheck( 'wpDiff' );
947 // Remember whether a save was requested, so we can indicate
948 // if we forced preview due to session failure.
949 $this->mTriedSave
= !$this->preview
;
951 if ( $this->tokenOk( $request ) ) {
952 # Some browsers will not report any submit button
953 # if the user hits enter in the comment box.
954 # The unmarked state will be assumed to be a save,
955 # if the form seems otherwise complete.
956 wfDebug( __METHOD__
. ": Passed token check.\n" );
957 } elseif ( $this->diff
) {
958 # Failed token check, but only requested "Show Changes".
959 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
961 # Page might be a hack attempt posted from
962 # an external site. Preview instead of saving.
963 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
964 $this->preview
= true;
967 $this->save
= !$this->preview
&& !$this->diff
;
968 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
969 $this->edittime
= null;
972 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
973 $this->starttime
= null;
976 $this->recreate
= $request->getCheck( 'wpRecreate' );
978 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
979 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
981 $user = $this->context
->getUser();
982 # Don't force edit summaries when a user is editing their own user or talk page
983 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
984 && $this->mTitle
->getText() == $user->getName()
986 $this->allowBlankSummary
= true;
988 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
989 ||
!$user->getOption( 'forceeditsummary' );
992 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
994 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
995 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
997 $changeTags = $request->getVal( 'wpChangeTags' );
998 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
999 $this->changeTags
= [];
1001 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1005 # Not a posted form? Start with nothing.
1006 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1007 $this->textbox1
= '';
1008 $this->summary
= '';
1009 $this->sectiontitle
= '';
1010 $this->edittime
= '';
1011 $this->editRevId
= null;
1012 $this->starttime
= wfTimestampNow();
1013 $this->edit
= false;
1014 $this->preview
= false;
1015 $this->save
= false;
1016 $this->diff
= false;
1017 $this->minoredit
= false;
1018 // Watch may be overridden by request parameters
1019 $this->watchthis
= $request->getBool( 'watchthis', false );
1020 $this->recreate
= false;
1022 // When creating a new section, we can preload a section title by passing it as the
1023 // preloadtitle parameter in the URL (T15100)
1024 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1025 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1026 // Once wpSummary isn't being use for setting section titles, we should delete this.
1027 $this->summary
= $request->getVal( 'preloadtitle' );
1028 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1029 $this->summary
= $request->getText( 'summary' );
1030 if ( $this->summary
!== '' ) {
1031 $this->hasPresetSummary
= true;
1035 if ( $request->getVal( 'minor' ) ) {
1036 $this->minoredit
= true;
1040 $this->oldid
= $request->getInt( 'oldid' );
1041 $this->parentRevId
= $request->getInt( 'parentRevId' );
1043 $this->bot
= $request->getBool( 'bot', true );
1044 $this->nosummary
= $request->getBool( 'nosummary' );
1046 // May be overridden by revision.
1047 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1048 // May be overridden by revision.
1049 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1052 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1053 } catch ( MWUnknownContentModelException
$e ) {
1054 throw new ErrorPageError(
1055 'editpage-invalidcontentmodel-title',
1056 'editpage-invalidcontentmodel-text',
1057 [ wfEscapeWikiText( $this->contentModel
) ]
1061 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1062 throw new ErrorPageError(
1063 'editpage-notsupportedcontentformat-title',
1064 'editpage-notsupportedcontentformat-text',
1066 wfEscapeWikiText( $this->contentFormat
),
1067 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1073 * @todo Check if the desired model is allowed in this namespace, and if
1074 * a transition from the page's current model to the new model is
1078 $this->editintro
= $request->getText( 'editintro',
1079 // Custom edit intro for new sections
1080 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1082 // Allow extensions to modify form data
1083 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1087 * Subpage overridable method for extracting the page content data from the
1088 * posted form to be placed in $this->textbox1, if using customized input
1089 * this method should be overridden and return the page text that will be used
1090 * for saving, preview parsing and so on...
1092 * @param WebRequest &$request
1093 * @return string|null
1095 protected function importContentFormData( &$request ) {
1096 return; // Don't do anything, EditPage already extracted wpTextbox1
1100 * Initialise form fields in the object
1101 * Called on the first invocation, e.g. when a user clicks an edit link
1102 * @return bool If the requested section is valid
1104 public function initialiseForm() {
1105 $this->edittime
= $this->page
->getTimestamp();
1106 $this->editRevId
= $this->page
->getLatest();
1108 $content = $this->getContentObject( false ); # TODO: track content object?!
1109 if ( $content === false ) {
1112 $this->textbox1
= $this->toEditText( $content );
1114 $user = $this->context
->getUser();
1115 // activate checkboxes if user wants them to be always active
1116 # Sort out the "watch" checkbox
1117 if ( $user->getOption( 'watchdefault' ) ) {
1119 $this->watchthis
= true;
1120 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1122 $this->watchthis
= true;
1123 } elseif ( $user->isWatched( $this->mTitle
) ) {
1125 $this->watchthis
= true;
1127 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1128 $this->minoredit
= true;
1130 if ( $this->textbox1
=== false ) {
1137 * @param Content|null $def_content The default value to return
1139 * @return Content|null Content on success, $def_content for invalid sections
1143 protected function getContentObject( $def_content = null ) {
1148 $user = $this->context
->getUser();
1149 $request = $this->context
->getRequest();
1150 // For message page not locally set, use the i18n message.
1151 // For other non-existent articles, use preload text if any.
1152 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1153 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1154 # If this is a system message, get the default text.
1155 $msg = $this->mTitle
->getDefaultMessageText();
1157 $content = $this->toEditContent( $msg );
1159 if ( $content === false ) {
1160 # If requested, preload some text.
1161 $preload = $request->getVal( 'preload',
1162 // Custom preload text for new sections
1163 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1164 $params = $request->getArray( 'preloadparams', [] );
1166 $content = $this->getPreloadedContent( $preload, $params );
1168 // For existing pages, get text based on "undo" or section parameters.
1170 if ( $this->section
!= '' ) {
1171 // Get section edit text (returns $def_text for invalid sections)
1172 $orig = $this->getOriginalContent( $user );
1173 $content = $orig ?
$orig->getSection( $this->section
) : null;
1176 $content = $def_content;
1179 $undoafter = $request->getInt( 'undoafter' );
1180 $undo = $request->getInt( 'undo' );
1182 if ( $undo > 0 && $undoafter > 0 ) {
1183 $undorev = Revision
::newFromId( $undo );
1184 $oldrev = Revision
::newFromId( $undoafter );
1186 # Sanity check, make sure it's the right page,
1187 # the revisions exist and they were not deleted.
1188 # Otherwise, $content will be left as-is.
1189 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1190 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1191 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1193 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1195 if ( $content === false ) {
1196 # Warn the user that something went wrong
1197 $undoMsg = 'failure';
1199 $oldContent = $this->page
->getContent( Revision
::RAW
);
1200 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1201 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1202 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1203 // The undo may change content
1204 // model if its reverting the top
1205 // edit. This can result in
1206 // mismatched content model/format.
1207 $this->contentModel
= $newContent->getModel();
1208 $this->contentFormat
= $oldrev->getContentFormat();
1211 if ( $newContent->equals( $oldContent ) ) {
1212 # Tell the user that the undo results in no change,
1213 # i.e. the revisions were already undone.
1214 $undoMsg = 'nochange';
1217 # Inform the user of our success and set an automatic edit summary
1218 $undoMsg = 'success';
1220 # If we just undid one rev, use an autosummary
1221 $firstrev = $oldrev->getNext();
1222 if ( $firstrev && $firstrev->getId() == $undo ) {
1223 $userText = $undorev->getUserText();
1224 if ( $userText === '' ) {
1225 $undoSummary = $this->context
->msg(
1226 'undo-summary-username-hidden',
1228 )->inContentLanguage()->text();
1230 $undoSummary = $this->context
->msg(
1234 )->inContentLanguage()->text();
1236 if ( $this->summary
=== '' ) {
1237 $this->summary
= $undoSummary;
1239 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1240 ->inContentLanguage()->text() . $this->summary
;
1242 $this->undidRev
= $undo;
1244 $this->formtype
= 'diff';
1248 // Failed basic sanity checks.
1249 // Older revisions may have been removed since the link
1250 // was created, or we may simply have got bogus input.
1254 $out = $this->context
->getOutput();
1255 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1256 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1257 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1258 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1261 if ( $content === false ) {
1262 $content = $this->getOriginalContent( $user );
1271 * Get the content of the wanted revision, without section extraction.
1273 * The result of this function can be used to compare user's input with
1274 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1275 * to the original text of the edit.
1277 * This differs from Article::getContent() that when a missing revision is
1278 * encountered the result will be null and not the
1279 * 'missing-revision' message.
1282 * @param User $user The user to get the revision for
1283 * @return Content|null
1285 private function getOriginalContent( User
$user ) {
1286 if ( $this->section
== 'new' ) {
1287 return $this->getCurrentContent();
1289 $revision = $this->mArticle
->getRevisionFetched();
1290 if ( $revision === null ) {
1291 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1292 return $handler->makeEmptyContent();
1294 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1299 * Get the edit's parent revision ID
1301 * The "parent" revision is the ancestor that should be recorded in this
1302 * page's revision history. It is either the revision ID of the in-memory
1303 * article content, or in the case of a 3-way merge in order to rebase
1304 * across a recoverable edit conflict, the ID of the newer revision to
1305 * which we have rebased this page.
1308 * @return int Revision ID
1310 public function getParentRevId() {
1311 if ( $this->parentRevId
) {
1312 return $this->parentRevId
;
1314 return $this->mArticle
->getRevIdFetched();
1319 * Get the current content of the page. This is basically similar to
1320 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1321 * content object is returned instead of null.
1326 protected function getCurrentContent() {
1327 $rev = $this->page
->getRevision();
1328 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1330 if ( $content === false ||
$content === null ) {
1331 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1332 return $handler->makeEmptyContent();
1333 } elseif ( !$this->undidRev
) {
1334 // Content models should always be the same since we error
1335 // out if they are different before this point (in ->edit()).
1336 // The exception being, during an undo, the current revision might
1337 // differ from the prior revision.
1338 $logger = LoggerFactory
::getInstance( 'editpage' );
1339 if ( $this->contentModel
!== $rev->getContentModel() ) {
1340 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1341 'prev' => $this->contentModel
,
1342 'new' => $rev->getContentModel(),
1343 'title' => $this->getTitle()->getPrefixedDBkey(),
1344 'method' => __METHOD__
1346 $this->contentModel
= $rev->getContentModel();
1349 // Given that the content models should match, the current selected
1350 // format should be supported.
1351 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1352 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1354 'prev' => $this->contentFormat
,
1355 'new' => $rev->getContentFormat(),
1356 'title' => $this->getTitle()->getPrefixedDBkey(),
1357 'method' => __METHOD__
1359 $this->contentFormat
= $rev->getContentFormat();
1366 * Use this method before edit() to preload some content into the edit box
1368 * @param Content $content
1372 public function setPreloadedContent( Content
$content ) {
1373 $this->mPreloadContent
= $content;
1377 * Get the contents to be preloaded into the box, either set by
1378 * an earlier setPreloadText() or by loading the given page.
1380 * @param string $preload Representing the title to preload from.
1381 * @param array $params Parameters to use (interface-message style) in the preloaded text
1387 protected function getPreloadedContent( $preload, $params = [] ) {
1388 if ( !empty( $this->mPreloadContent
) ) {
1389 return $this->mPreloadContent
;
1392 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1394 if ( $preload === '' ) {
1395 return $handler->makeEmptyContent();
1398 $user = $this->context
->getUser();
1399 $title = Title
::newFromText( $preload );
1400 # Check for existence to avoid getting MediaWiki:Noarticletext
1401 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1402 // TODO: somehow show a warning to the user!
1403 return $handler->makeEmptyContent();
1406 $page = WikiPage
::factory( $title );
1407 if ( $page->isRedirect() ) {
1408 $title = $page->getRedirectTarget();
1410 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1411 // TODO: somehow show a warning to the user!
1412 return $handler->makeEmptyContent();
1414 $page = WikiPage
::factory( $title );
1417 $parserOptions = ParserOptions
::newFromUser( $user );
1418 $content = $page->getContent( Revision
::RAW
);
1421 // TODO: somehow show a warning to the user!
1422 return $handler->makeEmptyContent();
1425 if ( $content->getModel() !== $handler->getModelID() ) {
1426 $converted = $content->convert( $handler->getModelID() );
1428 if ( !$converted ) {
1429 // TODO: somehow show a warning to the user!
1430 wfDebug( "Attempt to preload incompatible content: " .
1431 "can't convert " . $content->getModel() .
1432 " to " . $handler->getModelID() );
1434 return $handler->makeEmptyContent();
1437 $content = $converted;
1440 return $content->preloadTransform( $title, $parserOptions, $params );
1444 * Make sure the form isn't faking a user's credentials.
1446 * @param WebRequest &$request
1450 public function tokenOk( &$request ) {
1451 $token = $request->getVal( 'wpEditToken' );
1452 $user = $this->context
->getUser();
1453 $this->mTokenOk
= $user->matchEditToken( $token );
1454 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1455 return $this->mTokenOk
;
1459 * Sets post-edit cookie indicating the user just saved a particular revision.
1461 * This uses a temporary cookie for each revision ID so separate saves will never
1462 * interfere with each other.
1464 * Article::view deletes the cookie on server-side after the redirect and
1465 * converts the value to the global JavaScript variable wgPostEdit.
1467 * If the variable were set on the server, it would be cached, which is unwanted
1468 * since the post-edit state should only apply to the load right after the save.
1470 * @param int $statusValue The status value (to check for new article status)
1472 protected function setPostEditCookie( $statusValue ) {
1473 $revisionId = $this->page
->getLatest();
1474 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1477 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1479 } elseif ( $this->oldid
) {
1483 $response = $this->context
->getRequest()->response();
1484 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1488 * Attempt submission
1489 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1490 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1491 * @return Status The resulting status object.
1493 public function attemptSave( &$resultDetails = false ) {
1494 # Allow bots to exempt some edits from bot flagging
1495 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1496 $status = $this->internalAttemptSave( $resultDetails, $bot );
1498 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1504 * Log when a page was successfully saved after the edit conflict view
1506 private function incrementResolvedConflicts() {
1507 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1511 $this->getEditConflictHelper()->incrementResolvedStats();
1515 * Handle status, such as after attempt save
1517 * @param Status $status
1518 * @param array|bool $resultDetails
1520 * @throws ErrorPageError
1521 * @return bool False, if output is done, true if rest of the form should be displayed
1523 private function handleStatus( Status
$status, $resultDetails ) {
1525 * @todo FIXME: once the interface for internalAttemptSave() is made
1526 * nicer, this should use the message in $status
1528 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1529 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1531 $this->incrementResolvedConflicts();
1533 $this->didSave
= true;
1534 if ( !$resultDetails['nullEdit'] ) {
1535 $this->setPostEditCookie( $status->value
);
1539 $out = $this->context
->getOutput();
1541 // "wpExtraQueryRedirect" is a hidden input to modify
1542 // after save URL and is not used by actual edit form
1543 $request = $this->context
->getRequest();
1544 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1546 switch ( $status->value
) {
1547 case self
::AS_HOOK_ERROR_EXPECTED
:
1548 case self
::AS_CONTENT_TOO_BIG
:
1549 case self
::AS_ARTICLE_WAS_DELETED
:
1550 case self
::AS_CONFLICT_DETECTED
:
1551 case self
::AS_SUMMARY_NEEDED
:
1552 case self
::AS_TEXTBOX_EMPTY
:
1553 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1555 case self
::AS_BLANK_ARTICLE
:
1556 case self
::AS_SELF_REDIRECT
:
1559 case self
::AS_HOOK_ERROR
:
1562 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1563 case self
::AS_PARSE_ERROR
:
1564 case self
::AS_UNICODE_NOT_SUPPORTED
:
1565 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1568 case self
::AS_SUCCESS_NEW_ARTICLE
:
1569 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1570 if ( $extraQueryRedirect ) {
1571 if ( $query === '' ) {
1572 $query = $extraQueryRedirect;
1574 $query = $query . '&' . $extraQueryRedirect;
1577 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1578 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1581 case self
::AS_SUCCESS_UPDATE
:
1583 $sectionanchor = $resultDetails['sectionanchor'];
1585 // Give extensions a chance to modify URL query on update
1587 'ArticleUpdateBeforeRedirect',
1588 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1591 if ( $resultDetails['redirect'] ) {
1592 if ( $extraQuery == '' ) {
1593 $extraQuery = 'redirect=no';
1595 $extraQuery = 'redirect=no&' . $extraQuery;
1598 if ( $extraQueryRedirect ) {
1599 if ( $extraQuery === '' ) {
1600 $extraQuery = $extraQueryRedirect;
1602 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1606 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1609 case self
::AS_SPAM_ERROR
:
1610 $this->spamPageWithContent( $resultDetails['spam'] );
1613 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1614 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1616 case self
::AS_IMAGE_REDIRECT_ANON
:
1617 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1618 throw new PermissionsError( 'upload' );
1620 case self
::AS_READ_ONLY_PAGE_ANON
:
1621 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1622 throw new PermissionsError( 'edit' );
1624 case self
::AS_READ_ONLY_PAGE
:
1625 throw new ReadOnlyError
;
1627 case self
::AS_RATE_LIMITED
:
1628 throw new ThrottledError();
1630 case self
::AS_NO_CREATE_PERMISSION
:
1631 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1632 throw new PermissionsError( $permission );
1634 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1635 throw new PermissionsError( 'editcontentmodel' );
1638 // We don't recognize $status->value. The only way that can happen
1639 // is if an extension hook aborted from inside ArticleSave.
1640 // Render the status object into $this->hookError
1641 // FIXME this sucks, we should just use the Status object throughout
1642 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1649 * Run hooks that can filter edits just before they get saved.
1651 * @param Content $content The Content to filter.
1652 * @param Status $status For reporting the outcome to the caller
1653 * @param User $user The user performing the edit
1657 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1658 // Run old style post-section-merge edit filter
1659 if ( $this->hookError
!= '' ) {
1660 # ...or the hook could be expecting us to produce an error
1661 $status->fatal( 'hookaborted' );
1662 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1666 // Run new style post-section-merge edit filter
1667 if ( !Hooks
::run( 'EditFilterMergedContent',
1668 [ $this->context
, $content, $status, $this->summary
,
1669 $user, $this->minoredit
] )
1671 # Error messages etc. could be handled within the hook...
1672 if ( $status->isGood() ) {
1673 $status->fatal( 'hookaborted' );
1674 // Not setting $this->hookError here is a hack to allow the hook
1675 // to cause a return to the edit page without $this->hookError
1676 // being set. This is used by ConfirmEdit to display a captcha
1677 // without any error message cruft.
1679 $this->hookError
= $this->formatStatusErrors( $status );
1681 // Use the existing $status->value if the hook set it
1682 if ( !$status->value
) {
1683 $status->value
= self
::AS_HOOK_ERROR
;
1686 } elseif ( !$status->isOK() ) {
1687 # ...or the hook could be expecting us to produce an error
1688 // FIXME this sucks, we should just use the Status object throughout
1689 $this->hookError
= $this->formatStatusErrors( $status );
1690 $status->fatal( 'hookaborted' );
1691 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1699 * Wrap status errors in an errorbox for increased visibility
1701 * @param Status $status
1702 * @return string Wikitext
1704 private function formatStatusErrors( Status
$status ) {
1705 $errmsg = $status->getWikiText(
1708 $this->context
->getLanguage()
1711 <div class="errorbox">
1719 * Return the summary to be used for a new section.
1721 * @param string $sectionanchor Set to the section anchor text
1724 private function newSectionSummary( &$sectionanchor = null ) {
1727 if ( $this->sectiontitle
!== '' ) {
1728 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1729 // If no edit summary was specified, create one automatically from the section
1730 // title and have it link to the new section. Otherwise, respect the summary as
1732 if ( $this->summary
=== '' ) {
1733 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1734 return $this->context
->msg( 'newsectionsummary' )
1735 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1737 } elseif ( $this->summary
!== '' ) {
1738 $sectionanchor = $this->guessSectionName( $this->summary
);
1739 # This is a new section, so create a link to the new section
1740 # in the revision summary.
1741 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1742 return $this->context
->msg( 'newsectionsummary' )
1743 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1745 return $this->summary
;
1749 * Attempt submission (no UI)
1751 * @param array &$result Array to add statuses to, currently with the
1753 * - spam (string): Spam string from content if any spam is detected by
1755 * - sectionanchor (string): Section anchor for a section save.
1756 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1758 * - redirect (bool): Set if doEditContent is OK. True if resulting
1759 * revision is a redirect.
1760 * @param bool $bot True if edit is being made under the bot right.
1762 * @return Status Status object, possibly with a message, but always with
1763 * one of the AS_* constants in $status->value,
1765 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1766 * various error display idiosyncrasies. There are also lots of cases
1767 * where error metadata is set in the object and retrieved later instead
1768 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1769 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1772 public function internalAttemptSave( &$result, $bot = false ) {
1773 $status = Status
::newGood();
1774 $user = $this->context
->getUser();
1776 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1777 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1778 $status->fatal( 'hookaborted' );
1779 $status->value
= self
::AS_HOOK_ERROR
;
1783 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1784 $status->fatal( 'unicode-support-fail' );
1785 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1789 $request = $this->context
->getRequest();
1790 $spam = $request->getText( 'wpAntispam' );
1791 if ( $spam !== '' ) {
1796 $this->mTitle
->getPrefixedText() .
1797 '" submitted bogus field "' .
1801 $status->fatal( 'spamprotectionmatch', false );
1802 $status->value
= self
::AS_SPAM_ERROR
;
1807 # Construct Content object
1808 $textbox_content = $this->toEditContent( $this->textbox1
);
1809 } catch ( MWContentSerializationException
$ex ) {
1811 'content-failed-to-parse',
1812 $this->contentModel
,
1813 $this->contentFormat
,
1816 $status->value
= self
::AS_PARSE_ERROR
;
1820 # Check image redirect
1821 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1822 $textbox_content->isRedirect() &&
1823 !$user->isAllowed( 'upload' )
1825 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1826 $status->setResult( false, $code );
1832 $match = self
::matchSummarySpamRegex( $this->summary
);
1833 if ( $match === false && $this->section
== 'new' ) {
1834 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1835 # regular summaries, it is added to the actual wikitext.
1836 if ( $this->sectiontitle
!== '' ) {
1837 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1838 $match = self
::matchSpamRegex( $this->sectiontitle
);
1840 # This branch is taken when the "Add Topic" user interface is used, or the API
1841 # is used with the 'summary' parameter.
1842 $match = self
::matchSpamRegex( $this->summary
);
1845 if ( $match === false ) {
1846 $match = self
::matchSpamRegex( $this->textbox1
);
1848 if ( $match !== false ) {
1849 $result['spam'] = $match;
1850 $ip = $request->getIP();
1851 $pdbk = $this->mTitle
->getPrefixedDBkey();
1852 $match = str_replace( "\n", '', $match );
1853 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1854 $status->fatal( 'spamprotectionmatch', $match );
1855 $status->value
= self
::AS_SPAM_ERROR
;
1860 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1862 # Error messages etc. could be handled within the hook...
1863 $status->fatal( 'hookaborted' );
1864 $status->value
= self
::AS_HOOK_ERROR
;
1866 } elseif ( $this->hookError
!= '' ) {
1867 # ...or the hook could be expecting us to produce an error
1868 $status->fatal( 'hookaborted' );
1869 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1873 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1874 // Auto-block user's IP if the account was "hard" blocked
1875 if ( !wfReadOnly() ) {
1876 $user->spreadAnyEditBlock();
1878 # Check block state against master, thus 'false'.
1879 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1883 $this->contentLength
= strlen( $this->textbox1
);
1884 $config = $this->context
->getConfig();
1885 $maxArticleSize = $config->get( 'MaxArticleSize' );
1886 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1887 // Error will be displayed by showEditForm()
1888 $this->tooBig
= true;
1889 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1893 if ( !$user->isAllowed( 'edit' ) ) {
1894 if ( $user->isAnon() ) {
1895 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1898 $status->fatal( 'readonlytext' );
1899 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1904 $changingContentModel = false;
1905 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1906 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1907 $status->fatal( 'editpage-cannot-use-custom-model' );
1908 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1910 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1911 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1914 // Make sure the user can edit the page under the new content model too
1915 $titleWithNewContentModel = clone $this->mTitle
;
1916 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1917 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1918 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1920 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1924 $changingContentModel = true;
1925 $oldContentModel = $this->mTitle
->getContentModel();
1928 if ( $this->changeTags
) {
1929 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1930 $this->changeTags
, $user );
1931 if ( !$changeTagsStatus->isOK() ) {
1932 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1933 return $changeTagsStatus;
1937 if ( wfReadOnly() ) {
1938 $status->fatal( 'readonlytext' );
1939 $status->value
= self
::AS_READ_ONLY_PAGE
;
1942 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1943 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1945 $status->fatal( 'actionthrottledtext' );
1946 $status->value
= self
::AS_RATE_LIMITED
;
1950 # If the article has been deleted while editing, don't save it without
1952 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1953 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1957 # Load the page data from the master. If anything changes in the meantime,
1958 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1959 $this->page
->loadPageData( 'fromdbmaster' );
1960 $new = !$this->page
->exists();
1963 // Late check for create permission, just in case *PARANOIA*
1964 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1965 $status->fatal( 'nocreatetext' );
1966 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1967 wfDebug( __METHOD__
. ": no create permission\n" );
1971 // Don't save a new page if it's blank or if it's a MediaWiki:
1972 // message with content equivalent to default (allow empty pages
1973 // in this case to disable messages, see T52124)
1974 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1975 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1976 $defaultText = $defaultMessageText;
1981 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1982 $this->blankArticle
= true;
1983 $status->fatal( 'blankarticle' );
1984 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1988 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
1992 $content = $textbox_content;
1994 $result['sectionanchor'] = '';
1995 if ( $this->section
== 'new' ) {
1996 if ( $this->sectiontitle
!== '' ) {
1997 // Insert the section title above the content.
1998 $content = $content->addSectionHeader( $this->sectiontitle
);
1999 } elseif ( $this->summary
!== '' ) {
2000 // Insert the section title above the content.
2001 $content = $content->addSectionHeader( $this->summary
);
2003 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2006 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2010 # Article exists. Check for edit conflict.
2012 $this->page
->clear(); # Force reload of dates, etc.
2013 $timestamp = $this->page
->getTimestamp();
2014 $latest = $this->page
->getLatest();
2016 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2018 // Check editRevId if set, which handles same-second timestamp collisions
2019 if ( $timestamp != $this->edittime
2020 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2022 $this->isConflict
= true;
2023 if ( $this->section
== 'new' ) {
2024 if ( $this->page
->getUserText() == $user->getName() &&
2025 $this->page
->getComment() == $this->newSectionSummary()
2027 // Probably a duplicate submission of a new comment.
2028 // This can happen when CDN resends a request after
2029 // a timeout but the first one actually went through.
2031 . ": duplicate new section submission; trigger edit conflict!\n" );
2033 // New comment; suppress conflict.
2034 $this->isConflict
= false;
2035 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2037 } elseif ( $this->section
== ''
2038 && Revision
::userWasLastToEdit(
2039 DB_MASTER
, $this->mTitle
->getArticleID(),
2040 $user->getId(), $this->edittime
2043 # Suppress edit conflict with self, except for section edits where merging is required.
2044 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2045 $this->isConflict
= false;
2049 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2050 if ( $this->sectiontitle
!== '' ) {
2051 $sectionTitle = $this->sectiontitle
;
2053 $sectionTitle = $this->summary
;
2058 if ( $this->isConflict
) {
2060 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2061 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2062 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2063 // ...or disable section editing for non-current revisions (not exposed anyway).
2064 if ( $this->editRevId
!== null ) {
2065 $content = $this->page
->replaceSectionAtRev(
2072 $content = $this->page
->replaceSectionContent(
2080 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2081 $content = $this->page
->replaceSectionContent(
2088 if ( is_null( $content ) ) {
2089 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2090 $this->isConflict
= true;
2091 $content = $textbox_content; // do not try to merge here!
2092 } elseif ( $this->isConflict
) {
2094 if ( $this->mergeChangesIntoContent( $content ) ) {
2095 // Successful merge! Maybe we should tell the user the good news?
2096 $this->isConflict
= false;
2097 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2099 $this->section
= '';
2100 $this->textbox1
= ContentHandler
::getContentText( $content );
2101 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2105 if ( $this->isConflict
) {
2106 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2110 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2114 if ( $this->section
== 'new' ) {
2115 // Handle the user preference to force summaries here
2116 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2117 $this->missingSummary
= true;
2118 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2119 $status->value
= self
::AS_SUMMARY_NEEDED
;
2123 // Do not allow the user to post an empty comment
2124 if ( $this->textbox1
== '' ) {
2125 $this->missingComment
= true;
2126 $status->fatal( 'missingcommenttext' );
2127 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2130 } elseif ( !$this->allowBlankSummary
2131 && !$content->equals( $this->getOriginalContent( $user ) )
2132 && !$content->isRedirect()
2133 && md5( $this->summary
) == $this->autoSumm
2135 $this->missingSummary
= true;
2136 $status->fatal( 'missingsummary' );
2137 $status->value
= self
::AS_SUMMARY_NEEDED
;
2142 $sectionanchor = '';
2143 if ( $this->section
== 'new' ) {
2144 $this->summary
= $this->newSectionSummary( $sectionanchor );
2145 } elseif ( $this->section
!= '' ) {
2146 # Try to get a section anchor from the section source, redirect
2147 # to edited section if header found.
2148 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2149 # for duplicate heading checking and maybe parsing.
2150 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2151 # We can't deal with anchors, includes, html etc in the header for now,
2152 # headline would need to be parsed to improve this.
2153 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2154 $sectionanchor = $this->guessSectionName( $matches[2] );
2157 $result['sectionanchor'] = $sectionanchor;
2159 // Save errors may fall down to the edit form, but we've now
2160 // merged the section into full text. Clear the section field
2161 // so that later submission of conflict forms won't try to
2162 // replace that into a duplicated mess.
2163 $this->textbox1
= $this->toEditText( $content );
2164 $this->section
= '';
2166 $status->value
= self
::AS_SUCCESS_UPDATE
;
2169 if ( !$this->allowSelfRedirect
2170 && $content->isRedirect()
2171 && $content->getRedirectTarget()->equals( $this->getTitle() )
2173 // If the page already redirects to itself, don't warn.
2174 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2175 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2176 $this->selfRedirect
= true;
2177 $status->fatal( 'selfredirect' );
2178 $status->value
= self
::AS_SELF_REDIRECT
;
2183 // Check for length errors again now that the section is merged in
2184 $this->contentLength
= strlen( $this->toEditText( $content ) );
2185 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2186 $this->tooBig
= true;
2187 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2191 $flags = EDIT_AUTOSUMMARY |
2192 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2193 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2194 ( $bot ? EDIT_FORCE_BOT
: 0 );
2196 $doEditStatus = $this->page
->doEditContent(
2202 $content->getDefaultFormat(),
2207 if ( !$doEditStatus->isOK() ) {
2208 // Failure from doEdit()
2209 // Show the edit conflict page for certain recognized errors from doEdit(),
2210 // but don't show it for errors from extension hooks
2211 $errors = $doEditStatus->getErrorsArray();
2212 if ( in_array( $errors[0][0],
2213 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2215 $this->isConflict
= true;
2216 // Destroys data doEdit() put in $status->value but who cares
2217 $doEditStatus->value
= self
::AS_END
;
2219 return $doEditStatus;
2222 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2223 if ( $result['nullEdit'] ) {
2224 // We don't know if it was a null edit until now, so increment here
2225 $user->pingLimiter( 'linkpurge' );
2227 $result['redirect'] = $content->isRedirect();
2229 $this->updateWatchlist();
2231 // If the content model changed, add a log entry
2232 if ( $changingContentModel ) {
2233 $this->addContentModelChangeLogEntry(
2235 $new ?
false : $oldContentModel,
2236 $this->contentModel
,
2246 * @param string|false $oldModel false if the page is being newly created
2247 * @param string $newModel
2248 * @param string $reason
2250 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2251 $new = $oldModel === false;
2252 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2253 $log->setPerformer( $user );
2254 $log->setTarget( $this->mTitle
);
2255 $log->setComment( $reason );
2256 $log->setParameters( [
2257 '4::oldmodel' => $oldModel,
2258 '5::newmodel' => $newModel
2260 $logid = $log->insert();
2261 $log->publish( $logid );
2265 * Register the change of watch status
2267 protected function updateWatchlist() {
2268 $user = $this->context
->getUser();
2269 if ( !$user->isLoggedIn() ) {
2273 $title = $this->mTitle
;
2274 $watch = $this->watchthis
;
2275 // Do this in its own transaction to reduce contention...
2276 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2277 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2278 return; // nothing to change
2280 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2285 * Attempts to do 3-way merge of edit content with a base revision
2286 * and current content, in case of edit conflict, in whichever way appropriate
2287 * for the content type.
2291 * @param Content $editContent
2295 private function mergeChangesIntoContent( &$editContent ) {
2296 $db = wfGetDB( DB_MASTER
);
2298 // This is the revision the editor started from
2299 $baseRevision = $this->getBaseRevision();
2300 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2302 if ( is_null( $baseContent ) ) {
2306 // The current state, we want to merge updates into it
2307 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2308 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2310 if ( is_null( $currentContent ) ) {
2314 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2316 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2319 $editContent = $result;
2320 // Update parentRevId to what we just merged.
2321 $this->parentRevId
= $currentRevision->getId();
2329 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2330 * one might think of X as the "base revision", which is NOT what this returns.
2331 * @return Revision|null Current version when the edit was started
2333 public function getBaseRevision() {
2334 if ( !$this->mBaseRevision
) {
2335 $db = wfGetDB( DB_MASTER
);
2336 $this->mBaseRevision
= $this->editRevId
2337 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2338 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2340 return $this->mBaseRevision
;
2344 * Check given input text against $wgSpamRegex, and return the text of the first match.
2346 * @param string $text
2348 * @return string|bool Matching string or false
2350 public static function matchSpamRegex( $text ) {
2351 global $wgSpamRegex;
2352 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2353 $regexes = (array)$wgSpamRegex;
2354 return self
::matchSpamRegexInternal( $text, $regexes );
2358 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2360 * @param string $text
2362 * @return string|bool Matching string or false
2364 public static function matchSummarySpamRegex( $text ) {
2365 global $wgSummarySpamRegex;
2366 $regexes = (array)$wgSummarySpamRegex;
2367 return self
::matchSpamRegexInternal( $text, $regexes );
2371 * @param string $text
2372 * @param array $regexes
2373 * @return bool|string
2375 protected static function matchSpamRegexInternal( $text, $regexes ) {
2376 foreach ( $regexes as $regex ) {
2378 if ( preg_match( $regex, $text, $matches ) ) {
2385 public function setHeaders() {
2386 $out = $this->context
->getOutput();
2388 $out->addModules( 'mediawiki.action.edit' );
2389 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2390 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2392 $user = $this->context
->getUser();
2393 if ( $user->getOption( 'showtoolbar' ) ) {
2394 // The addition of default buttons is handled by getEditToolbar() which
2395 // has its own dependency on this module. The call here ensures the module
2396 // is loaded in time (it has position "top") for other modules to register
2397 // buttons (e.g. extensions, gadgets, user scripts).
2398 $out->addModules( 'mediawiki.toolbar' );
2401 if ( $user->getOption( 'uselivepreview' ) ) {
2402 $out->addModules( 'mediawiki.action.edit.preview' );
2405 if ( $user->getOption( 'useeditwarning' ) ) {
2406 $out->addModules( 'mediawiki.action.edit.editWarning' );
2409 # Enabled article-related sidebar, toplinks, etc.
2410 $out->setArticleRelated( true );
2412 $contextTitle = $this->getContextTitle();
2413 if ( $this->isConflict
) {
2414 $msg = 'editconflict';
2415 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2416 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2418 $msg = $contextTitle->exists()
2419 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2420 && $contextTitle->getDefaultMessageText() !== false
2426 # Use the title defined by DISPLAYTITLE magic word when present
2427 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2428 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2429 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2430 if ( $displayTitle === false ) {
2431 $displayTitle = $contextTitle->getPrefixedText();
2433 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2435 $config = $this->context
->getConfig();
2437 # Transmit the name of the message to JavaScript for live preview
2438 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2439 $out->addJsConfigVars( [
2440 'wgEditMessage' => $msg,
2441 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2444 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2446 $out->addJsConfigVars(
2447 'wgEditSubmitButtonLabelPublish',
2448 $config->get( 'EditSubmitButtonLabelPublish' )
2453 * Show all applicable editing introductions
2455 protected function showIntro() {
2456 if ( $this->suppressIntro
) {
2460 $out = $this->context
->getOutput();
2461 $namespace = $this->mTitle
->getNamespace();
2463 if ( $namespace == NS_MEDIAWIKI
) {
2464 # Show a warning if editing an interface message
2465 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2466 # If this is a default message (but not css, json, or js),
2467 # show a hint that it is translatable on translatewiki.net
2469 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2470 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2471 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2473 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2474 if ( $defaultMessageText !== false ) {
2475 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2476 'translateinterface' );
2479 } elseif ( $namespace == NS_FILE
) {
2480 # Show a hint to shared repo
2481 $file = wfFindFile( $this->mTitle
);
2482 if ( $file && !$file->isLocal() ) {
2483 $descUrl = $file->getDescriptionUrl();
2484 # there must be a description url to show a hint to shared repo
2486 if ( !$this->mTitle
->exists() ) {
2487 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2488 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2491 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2492 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2499 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2500 # Show log extract when the user is currently blocked
2501 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2502 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2503 $user = User
::newFromName( $username, false /* allow IP users */ );
2504 $ip = User
::isIP( $username );
2505 $block = Block
::newFromTarget( $user, $user );
2506 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2507 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2508 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2509 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2510 # Show log extract if the user is currently blocked
2511 LogEventsList
::showLogExtract(
2514 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2518 'showIfEmpty' => false,
2520 'blocked-notice-logextract',
2521 $user->getName() # Support GENDER in notice
2527 # Try to add a custom edit intro, or use the standard one if this is not possible.
2528 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2529 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2530 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2532 if ( $this->context
->getUser()->isLoggedIn() ) {
2534 // Suppress the external link icon, consider the help url an internal one
2535 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2543 // Suppress the external link icon, consider the help url an internal one
2544 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2546 'newarticletextanon',
2552 # Give a notice if the user is editing a deleted/moved page...
2553 if ( !$this->mTitle
->exists() ) {
2554 $dbr = wfGetDB( DB_REPLICA
);
2556 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2560 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2561 'showIfEmpty' => false,
2562 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2569 * Attempt to show a custom editing introduction, if supplied
2573 protected function showCustomIntro() {
2574 if ( $this->editintro
) {
2575 $title = Title
::newFromText( $this->editintro
);
2576 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2577 // Added using template syntax, to take <noinclude>'s into account.
2578 $this->context
->getOutput()->addWikiTextTitleTidy(
2579 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2589 * Gets an editable textual representation of $content.
2590 * The textual representation can be turned by into a Content object by the
2591 * toEditContent() method.
2593 * If $content is null or false or a string, $content is returned unchanged.
2595 * If the given Content object is not of a type that can be edited using
2596 * the text base EditPage, an exception will be raised. Set
2597 * $this->allowNonTextContent to true to allow editing of non-textual
2600 * @param Content|null|bool|string $content
2601 * @return string The editable text form of the content.
2603 * @throws MWException If $content is not an instance of TextContent and
2604 * $this->allowNonTextContent is not true.
2606 protected function toEditText( $content ) {
2607 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2611 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2612 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2615 return $content->serialize( $this->contentFormat
);
2619 * Turns the given text into a Content object by unserializing it.
2621 * If the resulting Content object is not of a type that can be edited using
2622 * the text base EditPage, an exception will be raised. Set
2623 * $this->allowNonTextContent to true to allow editing of non-textual
2626 * @param string|null|bool $text Text to unserialize
2627 * @return Content|bool|null The content object created from $text. If $text was false
2628 * or null, false resp. null will be returned instead.
2630 * @throws MWException If unserializing the text results in a Content
2631 * object that is not an instance of TextContent and
2632 * $this->allowNonTextContent is not true.
2634 protected function toEditContent( $text ) {
2635 if ( $text === false ||
$text === null ) {
2639 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2640 $this->contentModel
, $this->contentFormat
);
2642 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2643 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2650 * Send the edit form and related headers to OutputPage
2651 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2652 * during form output near the top, for captchas and the like.
2654 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2655 * use the EditPage::showEditForm:fields hook instead.
2657 public function showEditForm( $formCallback = null ) {
2658 # need to parse the preview early so that we know which templates are used,
2659 # otherwise users with "show preview after edit box" will get a blank list
2660 # we parse this near the beginning so that setHeaders can do the title
2661 # setting work instead of leaving it in getPreviewText
2662 $previewOutput = '';
2663 if ( $this->formtype
== 'preview' ) {
2664 $previewOutput = $this->getPreviewText();
2667 $out = $this->context
->getOutput();
2669 // Avoid PHP 7.1 warning of passing $this by reference
2671 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2673 $this->setHeaders();
2675 $this->addTalkPageText();
2676 $this->addEditNotices();
2678 if ( !$this->isConflict
&&
2679 $this->section
!= '' &&
2680 !$this->isSectionEditSupported() ) {
2681 // We use $this->section to much before this and getVal('wgSection') directly in other places
2682 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2683 // Someone is welcome to try refactoring though
2684 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2688 $this->showHeader();
2690 $out->addHTML( $this->editFormPageTop
);
2692 $user = $this->context
->getUser();
2693 if ( $user->getOption( 'previewontop' ) ) {
2694 $this->displayPreviewArea( $previewOutput, true );
2697 $out->addHTML( $this->editFormTextTop
);
2699 $showToolbar = true;
2700 if ( $this->wasDeletedSinceLastEdit() ) {
2701 if ( $this->formtype
== 'save' ) {
2702 // Hide the toolbar and edit area, user can click preview to get it back
2703 // Add an confirmation checkbox and explanation.
2704 $showToolbar = false;
2706 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2707 'deletedwhileediting' );
2711 // @todo add EditForm plugin interface and use it here!
2712 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2713 $out->addHTML( Html
::openElement(
2716 'class' => 'mw-editform',
2717 'id' => self
::EDITFORM_ID
,
2718 'name' => self
::EDITFORM_ID
,
2720 'action' => $this->getActionURL( $this->getContextTitle() ),
2721 'enctype' => 'multipart/form-data'
2725 if ( is_callable( $formCallback ) ) {
2726 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2727 call_user_func_array( $formCallback, [ &$out ] );
2730 // Add a check for Unicode support
2731 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2733 // Add an empty field to trip up spambots
2735 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2738 [ 'for' => 'wpAntispam' ],
2739 $this->context
->msg( 'simpleantispam-label' )->parse()
2745 'name' => 'wpAntispam',
2746 'id' => 'wpAntispam',
2750 . Xml
::closeElement( 'div' )
2753 // Avoid PHP 7.1 warning of passing $this by reference
2755 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2757 // Put these up at the top to ensure they aren't lost on early form submission
2758 $this->showFormBeforeText();
2760 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2761 $username = $this->lastDelete
->user_name
;
2762 $comment = CommentStore
::getStore()
2763 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2765 // It is better to not parse the comment at all than to have templates expanded in the middle
2766 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2767 $key = $comment === ''
2768 ?
'confirmrecreate-noreason'
2769 : 'confirmrecreate';
2771 '<div class="mw-confirm-recreate">' .
2772 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2773 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2774 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2780 # When the summary is hidden, also hide them on preview/show changes
2781 if ( $this->nosummary
) {
2782 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2785 # If a blank edit summary was previously provided, and the appropriate
2786 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2787 # user being bounced back more than once in the event that a summary
2790 # For a bit more sophisticated detection of blank summaries, hash the
2791 # automatic one and pass that in the hidden field wpAutoSummary.
2792 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2793 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2796 if ( $this->undidRev
) {
2797 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2800 if ( $this->selfRedirect
) {
2801 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2804 if ( $this->hasPresetSummary
) {
2805 // If a summary has been preset using &summary= we don't want to prompt for
2806 // a different summary. Only prompt for a summary if the summary is blanked.
2808 $this->autoSumm
= md5( '' );
2811 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2812 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2814 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2815 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2817 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2818 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2822 if ( $this->section
== 'new' ) {
2823 $this->showSummaryInput( true, $this->summary
);
2824 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2827 $out->addHTML( $this->editFormTextBeforeContent
);
2828 if ( $this->isConflict
) {
2829 // In an edit conflict, we turn textbox2 into the user's text,
2830 // and textbox1 into the stored version
2831 $this->textbox2
= $this->textbox1
;
2833 $content = $this->getCurrentContent();
2834 $this->textbox1
= $this->toEditText( $content );
2836 $editConflictHelper = $this->getEditConflictHelper();
2837 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2838 $editConflictHelper->setContentModel( $this->contentModel
);
2839 $editConflictHelper->setContentFormat( $this->contentFormat
);
2840 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2843 if ( !$this->mTitle
->isUserConfigPage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2844 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2847 if ( $this->blankArticle
) {
2848 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2851 if ( $this->isConflict
) {
2852 // In an edit conflict bypass the overridable content form method
2853 // and fallback to the raw wpTextbox1 since editconflicts can't be
2854 // resolved between page source edits and custom ui edits using the
2856 $conflictTextBoxAttribs = [];
2857 if ( $this->wasDeletedSinceLastEdit() ) {
2858 $conflictTextBoxAttribs['style'] = 'display:none;';
2859 } elseif ( $this->isOldRev
) {
2860 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2863 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2864 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2866 $this->showContentForm();
2869 $out->addHTML( $this->editFormTextAfterContent
);
2871 $this->showStandardInputs();
2873 $this->showFormAfterText();
2875 $this->showTosSummary();
2877 $this->showEditTools();
2879 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2881 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2883 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2884 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2886 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2887 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2889 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2891 if ( $this->isConflict
) {
2893 $this->showConflict();
2894 } catch ( MWContentSerializationException
$ex ) {
2895 // this can't really happen, but be nice if it does.
2896 $msg = $this->context
->msg(
2897 'content-failed-to-parse',
2898 $this->contentModel
,
2899 $this->contentFormat
,
2902 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2906 // Set a hidden field so JS knows what edit form mode we are in
2907 if ( $this->isConflict
) {
2909 } elseif ( $this->preview
) {
2911 } elseif ( $this->diff
) {
2916 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2918 // Marker for detecting truncated form data. This must be the last
2919 // parameter sent in order to be of use, so do not move me.
2920 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2921 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2923 if ( !$user->getOption( 'previewontop' ) ) {
2924 $this->displayPreviewArea( $previewOutput, false );
2929 * Wrapper around TemplatesOnThisPageFormatter to make
2930 * a "templates on this page" list.
2932 * @param Title[] $templates
2933 * @return string HTML
2935 public function makeTemplatesOnThisPageList( array $templates ) {
2936 $templateListFormatter = new TemplatesOnThisPageFormatter(
2937 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2940 // preview if preview, else section if section, else false
2942 if ( $this->preview
) {
2944 } elseif ( $this->section
!= '' ) {
2948 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2949 $templateListFormatter->format( $templates, $type )
2954 * Extract the section title from current section text, if any.
2956 * @param string $text
2957 * @return string|bool String or false
2959 public static function extractSectionTitle( $text ) {
2960 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2961 if ( !empty( $matches[2] ) ) {
2963 return $wgParser->stripSectionName( trim( $matches[2] ) );
2969 protected function showHeader() {
2970 $out = $this->context
->getOutput();
2971 $user = $this->context
->getUser();
2972 if ( $this->isConflict
) {
2973 $this->addExplainConflictHeader( $out );
2974 $this->editRevId
= $this->page
->getLatest();
2976 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2977 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2978 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2979 if ( $sectionTitle !== false ) {
2980 $this->summary
= "/* $sectionTitle */ ";
2985 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
2987 if ( $this->missingComment
) {
2988 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2991 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2993 "<div id='mw-missingsummary'>\n$1\n</div>",
2994 [ 'missingsummary', $buttonLabel ]
2998 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3000 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3001 [ 'missingcommentheader', $buttonLabel ]
3005 if ( $this->blankArticle
) {
3007 "<div id='mw-blankarticle'>\n$1\n</div>",
3008 [ 'blankarticle', $buttonLabel ]
3012 if ( $this->selfRedirect
) {
3014 "<div id='mw-selfredirect'>\n$1\n</div>",
3015 [ 'selfredirect', $buttonLabel ]
3019 if ( $this->hookError
!== '' ) {
3020 $out->addWikiText( $this->hookError
);
3023 if ( $this->section
!= 'new' ) {
3024 $revision = $this->mArticle
->getRevisionFetched();
3026 // Let sysop know that this will make private content public if saved
3028 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3030 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3031 'rev-deleted-text-permission'
3033 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3035 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3036 'rev-deleted-text-view'
3040 if ( !$revision->isCurrent() ) {
3041 $this->mArticle
->setOldSubtitle( $revision->getId() );
3042 $out->addWikiMsg( 'editingold' );
3043 $this->isOldRev
= true;
3045 } elseif ( $this->mTitle
->exists() ) {
3046 // Something went wrong
3048 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3049 [ 'missing-revision', $this->oldid
] );
3054 if ( wfReadOnly() ) {
3056 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3057 [ 'readonlywarning', wfReadOnlyReason() ]
3059 } elseif ( $user->isAnon() ) {
3060 if ( $this->formtype
!= 'preview' ) {
3062 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3063 [ 'anoneditwarning',
3065 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3066 'returnto' => $this->getTitle()->getPrefixedDBkey()
3069 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3070 'returnto' => $this->getTitle()->getPrefixedDBkey()
3075 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3076 'anonpreviewwarning'
3080 if ( $this->mTitle
->isUserConfigPage() ) {
3081 # Check the skin exists
3082 if ( $this->isWrongCaseUserConfigPage() ) {
3084 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3085 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3088 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3089 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3090 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3091 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3093 $warning = $isUserCssConfig
3095 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3097 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3099 if ( $this->formtype
!== 'preview' ) {
3100 $config = $this->context
->getConfig();
3101 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3103 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3104 [ 'usercssyoucanpreview' ]
3106 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3108 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3109 [ 'userjsonyoucanpreview' ]
3111 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3113 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3114 [ 'userjsyoucanpreview' ]
3122 $this->addPageProtectionWarningHeaders();
3124 $this->addLongPageWarningHeader();
3126 # Add header copyright warning
3127 $this->showHeaderCopyrightWarning();
3131 * Helper function for summary input functions, which returns the neccessary
3132 * attributes for the input.
3134 * @param array|null $inputAttrs Array of attrs to use on the input
3137 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3138 $conf = $this->context
->getConfig();
3139 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
3140 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3141 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3142 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
3143 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3144 'id' => 'wpSummary',
3145 'name' => 'wpSummary',
3146 'maxlength' => $oldCommentSchema ?
200 : CommentStore
::COMMENT_CHARACTER_LIMIT
,
3149 'spellcheck' => 'true',
3154 * Builds a standard summary input with a label.
3156 * @param string $summary The value of the summary input
3157 * @param string $labelText The html to place inside the label
3158 * @param array $inputAttrs Array of attrs to use on the input
3160 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3162 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3163 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3164 $this->getSummaryInputAttributes( $inputAttrs )
3167 'title' => Linker
::titleAttrib( 'summary' ),
3168 'accessKey' => Linker
::accesskey( 'summary' ),
3171 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3172 $inputAttrs['inputId'] = $inputAttrs['id'];
3173 $inputAttrs['id'] = 'wpSummaryWidget';
3175 return new OOUI\
FieldLayout(
3176 new OOUI\
TextInputWidget( [
3177 'value' => $summary,
3178 'infusable' => true,
3181 'label' => new OOUI\
HtmlSnippet( $labelText ),
3183 'id' => 'wpSummaryLabel',
3184 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3190 * @param bool $isSubjectPreview True if this is the section subject/title
3191 * up top, or false if this is the comment summary
3192 * down below the textarea
3193 * @param string $summary The text of the summary to display
3195 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3196 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3197 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3198 if ( $isSubjectPreview ) {
3199 if ( $this->nosummary
) {
3203 if ( !$this->mShowSummaryField
) {
3208 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3209 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3212 [ 'class' => $summaryClass ]
3217 * @param bool $isSubjectPreview True if this is the section subject/title
3218 * up top, or false if this is the comment summary
3219 * down below the textarea
3220 * @param string $summary The text of the summary to display
3223 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3224 // avoid spaces in preview, gets always trimmed on save
3225 $summary = trim( $summary );
3226 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3232 if ( $isSubjectPreview ) {
3233 $summary = $this->context
->msg( 'newsectionsummary' )
3234 ->rawParams( $wgParser->stripSectionName( $summary ) )
3235 ->inContentLanguage()->text();
3238 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3240 $summary = $this->context
->msg( $message )->parse()
3241 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3242 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3245 protected function showFormBeforeText() {
3246 $out = $this->context
->getOutput();
3247 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3248 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3249 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3250 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3251 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3254 protected function showFormAfterText() {
3256 * To make it harder for someone to slip a user a page
3257 * which submits an edit form to the wiki without their
3258 * knowledge, a random token is associated with the login
3259 * session. If it's not passed back with the submission,
3260 * we won't save the page, or render user JavaScript and
3263 * For anon editors, who may not have a session, we just
3264 * include the constant suffix to prevent editing from
3265 * broken text-mangling proxies.
3267 $this->context
->getOutput()->addHTML(
3269 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3275 * Subpage overridable method for printing the form for page content editing
3276 * By default this simply outputs wpTextbox1
3277 * Subclasses can override this to provide a custom UI for editing;
3278 * be it a form, or simply wpTextbox1 with a modified content that will be
3279 * reverse modified when extracted from the post data.
3280 * Note that this is basically the inverse for importContentFormData
3282 protected function showContentForm() {
3283 $this->showTextbox1();
3287 * Method to output wpTextbox1
3288 * The $textoverride method can be used by subclasses overriding showContentForm
3289 * to pass back to this method.
3291 * @param array $customAttribs Array of html attributes to use in the textarea
3292 * @param string $textoverride Optional text to override $this->textarea1 with
3294 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3295 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3296 $attribs = [ 'style' => 'display:none;' ];
3298 $builder = new TextboxBuilder();
3299 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3301 # Is an old revision being edited?
3302 if ( $this->isOldRev
) {
3303 $classes[] = 'mw-textarea-oldrev';
3306 $attribs = [ 'tabindex' => 1 ];
3308 if ( is_array( $customAttribs ) ) {
3309 $attribs +
= $customAttribs;
3312 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3316 $textoverride !== null ?
$textoverride : $this->textbox1
,
3322 protected function showTextbox2() {
3323 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3326 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3327 $builder = new TextboxBuilder();
3328 $attribs = $builder->buildTextboxAttribs(
3331 $this->context
->getUser(),
3335 $this->context
->getOutput()->addHTML(
3336 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3340 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3343 $classes[] = 'ontop';
3346 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3348 if ( $this->formtype
!= 'preview' ) {
3349 $attribs['style'] = 'display: none;';
3352 $out = $this->context
->getOutput();
3353 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3355 if ( $this->formtype
== 'preview' ) {
3356 $this->showPreview( $previewOutput );
3358 // Empty content container for LivePreview
3359 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3360 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3361 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3362 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3365 $out->addHTML( '</div>' );
3367 if ( $this->formtype
== 'diff' ) {
3370 } catch ( MWContentSerializationException
$ex ) {
3371 $msg = $this->context
->msg(
3372 'content-failed-to-parse',
3373 $this->contentModel
,
3374 $this->contentFormat
,
3377 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3383 * Append preview output to OutputPage.
3384 * Includes category rendering if this is a category page.
3386 * @param string $text The HTML to be output for the preview.
3388 protected function showPreview( $text ) {
3389 if ( $this->mArticle
instanceof CategoryPage
) {
3390 $this->mArticle
->openShowCategory();
3392 # This hook seems slightly odd here, but makes things more
3393 # consistent for extensions.
3394 $out = $this->context
->getOutput();
3395 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3396 $out->addHTML( $text );
3397 if ( $this->mArticle
instanceof CategoryPage
) {
3398 $this->mArticle
->closeShowCategory();
3403 * Get a diff between the current contents of the edit box and the
3404 * version of the page we're editing from.
3406 * If this is a section edit, we'll replace the section as for final
3407 * save and then make a comparison.
3409 public function showDiff() {
3412 $oldtitlemsg = 'currentrev';
3413 # if message does not exist, show diff against the preloaded default
3414 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3415 $oldtext = $this->mTitle
->getDefaultMessageText();
3416 if ( $oldtext !== false ) {
3417 $oldtitlemsg = 'defaultmessagetext';
3418 $oldContent = $this->toEditContent( $oldtext );
3423 $oldContent = $this->getCurrentContent();
3426 $textboxContent = $this->toEditContent( $this->textbox1
);
3427 if ( $this->editRevId
!== null ) {
3428 $newContent = $this->page
->replaceSectionAtRev(
3429 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3432 $newContent = $this->page
->replaceSectionContent(
3433 $this->section
, $textboxContent, $this->summary
, $this->edittime
3437 if ( $newContent ) {
3438 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3440 $user = $this->context
->getUser();
3441 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
3442 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3445 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3446 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3447 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3449 if ( !$oldContent ) {
3450 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3453 if ( !$newContent ) {
3454 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3457 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3458 $de->setContent( $oldContent, $newContent );
3460 $difftext = $de->getDiff( $oldtitle, $newtitle );
3461 $de->showDiffStyle();
3466 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3470 * Show the header copyright warning.
3472 protected function showHeaderCopyrightWarning() {
3473 $msg = 'editpage-head-copy-warn';
3474 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3475 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3476 'editpage-head-copy-warn' );
3481 * Give a chance for site and per-namespace customizations of
3482 * terms of service summary link that might exist separately
3483 * from the copyright notice.
3485 * This will display between the save button and the edit tools,
3486 * so should remain short!
3488 protected function showTosSummary() {
3489 $msg = 'editpage-tos-summary';
3490 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3491 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3492 $out = $this->context
->getOutput();
3493 $out->addHTML( '<div class="mw-tos-summary">' );
3494 $out->addWikiMsg( $msg );
3495 $out->addHTML( '</div>' );
3500 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3501 * characters not present on most keyboards for copying/pasting.
3503 protected function showEditTools() {
3504 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3505 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3510 * Get the copyright warning
3512 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3515 protected function getCopywarn() {
3516 return self
::getCopyrightWarning( $this->mTitle
);
3520 * Get the copyright warning, by default returns wikitext
3522 * @param Title $title
3523 * @param string $format Output format, valid values are any function of a Message object
3524 * @param Language|string|null $langcode Language code or Language object.
3527 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3528 global $wgRightsText;
3529 if ( $wgRightsText ) {
3530 $copywarnMsg = [ 'copyrightwarning',
3531 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3534 $copywarnMsg = [ 'copyrightwarning2',
3535 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3537 // Allow for site and per-namespace customization of contribution/copyright notice.
3538 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3540 $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
3542 $msg->inLanguage( $langcode );
3544 return "<div id=\"editpage-copywarn\">\n" .
3545 $msg->$format() . "\n</div>";
3549 * Get the Limit report for page previews
3552 * @param ParserOutput $output ParserOutput object from the parse
3553 * @return string HTML
3555 public static function getPreviewLimitReport( $output ) {
3558 if ( !$output ||
!$output->getLimitReportData() ) {
3562 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3563 wfMessage( 'limitreport-title' )->parseAsBlock()
3566 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3567 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3569 $limitReport .= Html
::openElement( 'table', [
3570 'class' => 'preview-limit-report wikitable'
3572 Html
::openElement( 'tbody' );
3574 foreach ( $output->getLimitReportData() as $key => $value ) {
3575 if ( Hooks
::run( 'ParserLimitReportFormat',
3576 [ $key, &$value, &$limitReport, true, true ]
3578 $keyMsg = wfMessage( $key );
3579 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3580 if ( !$valueMsg->exists() ) {
3581 $valueMsg = new RawMessage( '$1' );
3583 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3584 $limitReport .= Html
::openElement( 'tr' ) .
3585 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3586 Html
::rawElement( 'td', null,
3587 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3589 Html
::closeElement( 'tr' );
3594 $limitReport .= Html
::closeElement( 'tbody' ) .
3595 Html
::closeElement( 'table' ) .
3596 Html
::closeElement( 'div' );
3598 return $limitReport;
3601 protected function showStandardInputs( &$tabindex = 2 ) {
3602 $out = $this->context
->getOutput();
3603 $out->addHTML( "<div class='editOptions'>\n" );
3605 if ( $this->section
!= 'new' ) {
3606 $this->showSummaryInput( false, $this->summary
);
3607 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3610 $checkboxes = $this->getCheckboxesWidget(
3612 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3614 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3616 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3618 // Show copyright warning.
3619 $out->addWikiText( $this->getCopywarn() );
3620 $out->addHTML( $this->editFormTextAfterWarn
);
3622 $out->addHTML( "<div class='editButtons'>\n" );
3623 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3625 $cancel = $this->getCancelLink();
3627 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3628 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3631 $this->context
->msg( 'edithelp' )->text(),
3632 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3635 $this->context
->msg( 'word-separator' )->escaped() .
3636 $this->context
->msg( 'newwindow' )->parse();
3638 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3639 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3640 $out->addHTML( "</div><!-- editButtons -->\n" );
3642 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3644 $out->addHTML( "</div><!-- editOptions -->\n" );
3648 * Show an edit conflict. textbox1 is already shown in showEditForm().
3649 * If you want to use another entry point to this function, be careful.
3651 protected function showConflict() {
3652 $out = $this->context
->getOutput();
3653 // Avoid PHP 7.1 warning of passing $this by reference
3655 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3656 $this->incrementConflictStats();
3658 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3662 protected function incrementConflictStats() {
3663 $this->getEditConflictHelper()->incrementConflictStats();
3669 public function getCancelLink() {
3671 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3672 $cancelParams['oldid'] = $this->oldid
;
3673 } elseif ( $this->getContextTitle()->isRedirect() ) {
3674 $cancelParams['redirect'] = 'no';
3677 return new OOUI\
ButtonWidget( [
3678 'id' => 'mw-editform-cancel',
3679 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3680 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3682 'infusable' => true,
3683 'flags' => 'destructive',
3688 * Returns the URL to use in the form's action attribute.
3689 * This is used by EditPage subclasses when simply customizing the action
3690 * variable in the constructor is not enough. This can be used when the
3691 * EditPage lives inside of a Special page rather than a custom page action.
3693 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3696 protected function getActionURL( Title
$title ) {
3697 return $title->getLocalURL( [ 'action' => $this->action
] );
3701 * Check if a page was deleted while the user was editing it, before submit.
3702 * Note that we rely on the logging table, which hasn't been always there,
3703 * but that doesn't matter, because this only applies to brand new
3707 protected function wasDeletedSinceLastEdit() {
3708 if ( $this->deletedSinceEdit
!== null ) {
3709 return $this->deletedSinceEdit
;
3712 $this->deletedSinceEdit
= false;
3714 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3715 $this->lastDelete
= $this->getLastDelete();
3716 if ( $this->lastDelete
) {
3717 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3718 if ( $deleteTime > $this->starttime
) {
3719 $this->deletedSinceEdit
= true;
3724 return $this->deletedSinceEdit
;
3728 * @return bool|stdClass
3730 protected function getLastDelete() {
3731 $dbr = wfGetDB( DB_REPLICA
);
3732 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3733 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3734 $data = $dbr->selectRow(
3735 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3745 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3747 'log_namespace' => $this->mTitle
->getNamespace(),
3748 'log_title' => $this->mTitle
->getDBkey(),
3749 'log_type' => 'delete',
3750 'log_action' => 'delete',
3753 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3755 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3756 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3758 // Quick paranoid permission checks...
3759 if ( is_object( $data ) ) {
3760 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3761 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3764 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3765 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3766 $data->log_comment_data
= null;
3774 * Get the rendered text for previewing.
3775 * @throws MWException
3778 public function getPreviewText() {
3779 $out = $this->context
->getOutput();
3780 $config = $this->context
->getConfig();
3782 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3783 // Could be an offsite preview attempt. This is very unsafe if
3784 // HTML is enabled, as it could be an attack.
3786 if ( $this->textbox1
!== '' ) {
3787 // Do not put big scary notice, if previewing the empty
3788 // string, which happens when you initially edit
3789 // a category page, due to automatic preview-on-open.
3790 $parsedNote = $out->parse( "<div class='previewnote'>" .
3791 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3792 true, /* interface */true );
3794 $this->incrementEditFailureStats( 'session_loss' );
3801 $content = $this->toEditContent( $this->textbox1
);
3805 'AlternateEditPreview',
3806 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3808 return $previewHTML;
3811 # provide a anchor link to the editform
3812 $continueEditing = '<span class="mw-continue-editing">' .
3813 '[[#' . self
::EDITFORM_ID
. '|' .
3814 $this->context
->getLanguage()->getArrow() . ' ' .
3815 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3816 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3817 if ( $this->mTokenOkExceptSuffix
) {
3818 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3819 $this->incrementEditFailureStats( 'bad_token' );
3821 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3822 $this->incrementEditFailureStats( 'session_loss' );
3824 } elseif ( $this->incompleteForm
) {
3825 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3826 if ( $this->mTriedSave
) {
3827 $this->incrementEditFailureStats( 'incomplete_form' );
3830 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3833 # don't parse non-wikitext pages, show message about preview
3834 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3835 if ( $this->mTitle
->isUserConfigPage() ) {
3837 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3843 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3845 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3848 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3850 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3853 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3855 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3862 # Used messages to make sure grep find them:
3863 # Messages: usercsspreview, userjsonpreview, userjspreview,
3864 # sitecsspreview, sitejsonpreview, sitejspreview
3865 if ( $level && $format ) {
3866 $note = "<div id='mw-{$level}{$format}preview'>" .
3867 $this->context
->msg( "{$level}{$format}preview" )->text() .
3868 ' ' . $continueEditing . "</div>";
3872 # If we're adding a comment, we need to show the
3873 # summary as the headline
3874 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3875 $content = $content->addSectionHeader( $this->summary
);
3878 $hook_args = [ $this, &$content ];
3879 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3881 $parserResult = $this->doPreviewParse( $content );
3882 $parserOutput = $parserResult['parserOutput'];
3883 $previewHTML = $parserResult['html'];
3884 $this->mParserOutput
= $parserOutput;
3885 $out->addParserOutputMetadata( $parserOutput );
3886 if ( $out->userCanPreview() ) {
3887 $out->addContentOverride( $this->getTitle(), $content );
3890 if ( count( $parserOutput->getWarnings() ) ) {
3891 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3894 } catch ( MWContentSerializationException
$ex ) {
3895 $m = $this->context
->msg(
3896 'content-failed-to-parse',
3897 $this->contentModel
,
3898 $this->contentFormat
,
3901 $note .= "\n\n" . $m->parse();
3905 if ( $this->isConflict
) {
3906 $conflict = '<h2 id="mw-previewconflict">'
3907 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3909 $conflict = '<hr />';
3912 $previewhead = "<div class='previewnote'>\n" .
3913 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3914 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3916 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3917 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3918 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3919 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3921 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3924 private function incrementEditFailureStats( $failureType ) {
3925 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3926 $stats->increment( 'edit.failures.' . $failureType );
3930 * Get parser options for a preview
3931 * @return ParserOptions
3933 protected function getPreviewParserOptions() {
3934 $parserOptions = $this->page
->makeParserOptions( $this->context
);
3935 $parserOptions->setIsPreview( true );
3936 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3937 $parserOptions->enableLimitReport();
3938 return $parserOptions;
3942 * Parse the page for a preview. Subclasses may override this class, in order
3943 * to parse with different options, or to otherwise modify the preview HTML.
3945 * @param Content $content The page content
3946 * @return array with keys:
3947 * - parserOutput: The ParserOutput object
3948 * - html: The HTML to be displayed
3950 protected function doPreviewParse( Content
$content ) {
3951 $user = $this->context
->getUser();
3952 $parserOptions = $this->getPreviewParserOptions();
3953 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
3954 $scopedCallback = $parserOptions->setupFakeRevision(
3955 $this->mTitle
, $pstContent, $user );
3956 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3957 ScopedCallback
::consume( $scopedCallback );
3959 'parserOutput' => $parserOutput,
3960 'html' => $parserOutput->getText( [
3961 'enableSectionEditLinks' => false
3969 public function getTemplates() {
3970 if ( $this->preview ||
$this->section
!= '' ) {
3972 if ( !isset( $this->mParserOutput
) ) {
3975 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3976 foreach ( array_keys( $template ) as $dbk ) {
3977 $templates[] = Title
::makeTitle( $ns, $dbk );
3982 return $this->mTitle
->getTemplateLinksFrom();
3987 * Shows a bulletin board style toolbar for common editing functions.
3988 * It can be disabled in the user preferences.
3990 * @param Title $title Title object for the page being edited (optional)
3993 public static function getEditToolbar( $title = null ) {
3994 global $wgContLang, $wgOut;
3995 global $wgEnableUploads, $wgForeignFileRepos;
3997 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3998 $showSignature = true;
4000 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4004 * $toolarray is an array of arrays each of which includes the
4005 * opening tag, the closing tag, optionally a sample text that is
4006 * inserted between the two when no selection is highlighted
4007 * and. The tip text is shown when the user moves the mouse
4010 * Images are defined in ResourceLoaderEditToolbarModule.
4014 'id' => 'mw-editbutton-bold',
4016 'close' => '\'\'\'',
4017 'sample' => wfMessage( 'bold_sample' )->text(),
4018 'tip' => wfMessage( 'bold_tip' )->text(),
4021 'id' => 'mw-editbutton-italic',
4024 'sample' => wfMessage( 'italic_sample' )->text(),
4025 'tip' => wfMessage( 'italic_tip' )->text(),
4028 'id' => 'mw-editbutton-link',
4031 'sample' => wfMessage( 'link_sample' )->text(),
4032 'tip' => wfMessage( 'link_tip' )->text(),
4035 'id' => 'mw-editbutton-extlink',
4038 'sample' => wfMessage( 'extlink_sample' )->text(),
4039 'tip' => wfMessage( 'extlink_tip' )->text(),
4042 'id' => 'mw-editbutton-headline',
4045 'sample' => wfMessage( 'headline_sample' )->text(),
4046 'tip' => wfMessage( 'headline_tip' )->text(),
4048 $imagesAvailable ?
[
4049 'id' => 'mw-editbutton-image',
4050 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4052 'sample' => wfMessage( 'image_sample' )->text(),
4053 'tip' => wfMessage( 'image_tip' )->text(),
4055 $imagesAvailable ?
[
4056 'id' => 'mw-editbutton-media',
4057 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4059 'sample' => wfMessage( 'media_sample' )->text(),
4060 'tip' => wfMessage( 'media_tip' )->text(),
4063 'id' => 'mw-editbutton-nowiki',
4064 'open' => "<nowiki>",
4065 'close' => "</nowiki>",
4066 'sample' => wfMessage( 'nowiki_sample' )->text(),
4067 'tip' => wfMessage( 'nowiki_tip' )->text(),
4070 'id' => 'mw-editbutton-signature',
4071 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4074 'tip' => wfMessage( 'sig_tip' )->text(),
4077 'id' => 'mw-editbutton-hr',
4078 'open' => "\n----\n",
4081 'tip' => wfMessage( 'hr_tip' )->text(),
4085 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4086 foreach ( $toolarray as $tool ) {
4092 // Images are defined in ResourceLoaderEditToolbarModule
4094 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4095 // Older browsers show a "speedtip" type message only for ALT.
4096 // Ideally these should be different, realistically they
4097 // probably don't need to be.
4105 $script .= Xml
::encodeJsCall(
4106 'mw.toolbar.addButton',
4108 ResourceLoader
::inDebugMode()
4114 $toolbar = '<div id="toolbar"></div>';
4116 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4117 // Only add the old toolbar cruft to the page payload if the toolbar has not
4118 // been over-written by a hook caller
4119 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
4126 * Return an array of checkbox definitions.
4128 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4130 * Array values are associative arrays with the following keys:
4131 * - 'label-message' (required): message for label text
4132 * - 'id' (required): 'id' attribute for the `<input>`
4133 * - 'default' (required): default checkedness (true or false)
4134 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4135 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4136 * from messages like 'tooltip-foo', 'accesskey-foo'
4137 * - 'label-id' (optional): 'id' attribute for the `<label>`
4138 * - 'legacy-name' (optional): short name for backwards-compatibility
4139 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4140 * where bool indicates the checked status of the checkbox
4143 public function getCheckboxesDefinition( $checked ) {
4146 $user = $this->context
->getUser();
4147 // don't show the minor edit checkbox if it's a new page or section
4148 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4149 $checkboxes['wpMinoredit'] = [
4150 'id' => 'wpMinoredit',
4151 'label-message' => 'minoredit',
4152 // Uses messages: tooltip-minoredit, accesskey-minoredit
4153 'tooltip' => 'minoredit',
4154 'label-id' => 'mw-editpage-minoredit',
4155 'legacy-name' => 'minor',
4156 'default' => $checked['minor'],
4160 if ( $user->isLoggedIn() ) {
4161 $checkboxes['wpWatchthis'] = [
4162 'id' => 'wpWatchthis',
4163 'label-message' => 'watchthis',
4164 // Uses messages: tooltip-watch, accesskey-watch
4165 'tooltip' => 'watch',
4166 'label-id' => 'mw-editpage-watch',
4167 'legacy-name' => 'watch',
4168 'default' => $checked['watch'],
4173 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4179 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4180 * any other added by extensions.
4182 * @param int &$tabindex Current tabindex
4183 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4184 * status of the checkbox
4186 * @return array Associative array of string keys to OOUI\FieldLayout instances
4188 public function getCheckboxesWidget( &$tabindex, $checked ) {
4190 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4192 foreach ( $checkboxesDef as $name => $options ) {
4193 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4197 if ( isset( $options['tooltip'] ) ) {
4198 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4199 $title = Linker
::titleAttrib( $options['tooltip'] );
4201 if ( isset( $options['title-message'] ) ) {
4202 $title = $this->context
->msg( $options['title-message'] )->text();
4205 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4206 new OOUI\
CheckboxInputWidget( [
4207 'tabIndex' => ++
$tabindex,
4208 'accessKey' => $accesskey,
4209 'id' => $options['id'] . 'Widget',
4210 'inputId' => $options['id'],
4212 'selected' => $options['default'],
4213 'infusable' => true,
4216 'align' => 'inline',
4217 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4219 'id' => isset( $options['label-id'] ) ?
$options['label-id'] : null,
4224 // Backwards-compatibility hack to run the EditPageBeforeEditChecks hook. It's important,
4225 // people have used it for the weirdest things completely unrelated to checkboxes...
4226 // And if we're gonna run it, might as well allow its legacy checkboxes to be shown.
4227 $legacyCheckboxes = [];
4228 if ( !$this->isNew
) {
4229 $legacyCheckboxes['minor'] = '';
4231 $legacyCheckboxes['watch'] = '';
4232 // Copy new-style checkboxes into an old-style structure
4233 foreach ( $checkboxes as $name => $oouiLayout ) {
4234 $legacyCheckboxes[$name] = (string)$oouiLayout;
4236 // Avoid PHP 7.1 warning of passing $this by reference
4238 Hooks
::run( 'EditPageBeforeEditChecks', [ &$ep, &$legacyCheckboxes, &$tabindex ], '1.29' );
4239 // Copy back any additional old-style checkboxes into the new-style structure
4240 foreach ( $legacyCheckboxes as $name => $html ) {
4241 if ( $html && !isset( $checkboxes[$name] ) ) {
4242 $checkboxes[$name] = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $html ) ] );
4250 * Get the message key of the label for the button to save the page
4255 protected function getSubmitButtonLabel() {
4257 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4259 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4260 $newPage = !$this->mTitle
->exists();
4262 if ( $labelAsPublish ) {
4263 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4265 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4268 return $buttonLabelKey;
4272 * Returns an array of html code of the following buttons:
4273 * save, diff and preview
4275 * @param int &$tabindex Current tabindex
4279 public function getEditButtons( &$tabindex ) {
4283 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4285 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4286 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4288 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4290 'tabIndex' => ++
$tabindex,
4291 'id' => 'wpSaveWidget',
4292 'inputId' => 'wpSave',
4293 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4294 'useInputTag' => true,
4295 'flags' => [ 'progressive', 'primary' ],
4296 'label' => $buttonLabel,
4297 'infusable' => true,
4299 // Messages used: tooltip-save, tooltip-publish
4300 'title' => Linker
::titleAttrib( $buttonTooltip ),
4301 // Messages used: accesskey-save, accesskey-publish
4302 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4305 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4306 'name' => 'wpPreview',
4307 'tabIndex' => ++
$tabindex,
4308 'id' => 'wpPreviewWidget',
4309 'inputId' => 'wpPreview',
4310 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4311 'useInputTag' => true,
4312 'label' => $this->context
->msg( 'showpreview' )->text(),
4313 'infusable' => true,
4315 // Message used: tooltip-preview
4316 'title' => Linker
::titleAttrib( 'preview' ),
4317 // Message used: accesskey-preview
4318 'accessKey' => Linker
::accesskey( 'preview' ),
4321 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4323 'tabIndex' => ++
$tabindex,
4324 'id' => 'wpDiffWidget',
4325 'inputId' => 'wpDiff',
4326 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4327 'useInputTag' => true,
4328 'label' => $this->context
->msg( 'showdiff' )->text(),
4329 'infusable' => true,
4331 // Message used: tooltip-diff
4332 'title' => Linker
::titleAttrib( 'diff' ),
4333 // Message used: accesskey-diff
4334 'accessKey' => Linker
::accesskey( 'diff' ),
4337 // Avoid PHP 7.1 warning of passing $this by reference
4339 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4345 * Creates a basic error page which informs the user that
4346 * they have attempted to edit a nonexistent section.
4348 public function noSuchSectionPage() {
4349 $out = $this->context
->getOutput();
4350 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4352 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4354 // Avoid PHP 7.1 warning of passing $this by reference
4356 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4357 $out->addHTML( $res );
4359 $out->returnToMain( false, $this->mTitle
);
4363 * Show "your edit contains spam" page with your diff and text
4365 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4367 public function spamPageWithContent( $match = false ) {
4368 $this->textbox2
= $this->textbox1
;
4370 if ( is_array( $match ) ) {
4371 $match = $this->context
->getLanguage()->listToText( $match );
4373 $out = $this->context
->getOutput();
4374 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4376 $out->addHTML( '<div id="spamprotected">' );
4377 $out->addWikiMsg( 'spamprotectiontext' );
4379 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4381 $out->addHTML( '</div>' );
4383 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4386 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4387 $this->showTextbox2();
4389 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4393 * Filter an input field through a Unicode de-armoring process if it
4394 * came from an old browser with known broken Unicode editing issues.
4396 * @deprecated since 1.30, does nothing
4398 * @param WebRequest $request
4399 * @param string $field
4402 protected function safeUnicodeInput( $request, $field ) {
4403 return rtrim( $request->getText( $field ) );
4407 * Filter an output field through a Unicode armoring process if it is
4408 * going to an old browser with known broken Unicode editing issues.
4410 * @deprecated since 1.30, does nothing
4412 * @param string $text
4415 protected function safeUnicodeOutput( $text ) {
4422 protected function addEditNotices() {
4423 $out = $this->context
->getOutput();
4424 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4425 if ( count( $editNotices ) ) {
4426 $out->addHTML( implode( "\n", $editNotices ) );
4428 $msg = $this->context
->msg( 'editnotice-notext' );
4429 if ( !$msg->isDisabled() ) {
4431 '<div class="mw-editnotice-notext">'
4432 . $msg->parseAsBlock()
4442 protected function addTalkPageText() {
4443 if ( $this->mTitle
->isTalkPage() ) {
4444 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4451 protected function addLongPageWarningHeader() {
4452 if ( $this->contentLength
=== false ) {
4453 $this->contentLength
= strlen( $this->textbox1
);
4456 $out = $this->context
->getOutput();
4457 $lang = $this->context
->getLanguage();
4458 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4459 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4460 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4463 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4464 $lang->formatNum( $maxArticleSize )
4468 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4469 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4472 $lang->formatSize( strlen( $this->textbox1
) ),
4473 strlen( $this->textbox1
)
4483 protected function addPageProtectionWarningHeaders() {
4484 $out = $this->context
->getOutput();
4485 if ( $this->mTitle
->isProtected( 'edit' ) &&
4486 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4488 # Is the title semi-protected?
4489 if ( $this->mTitle
->isSemiProtected() ) {
4490 $noticeMsg = 'semiprotectedpagewarning';
4492 # Then it must be protected based on static groups (regular)
4493 $noticeMsg = 'protectedpagewarning';
4495 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4496 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4498 if ( $this->mTitle
->isCascadeProtected() ) {
4499 # Is this page under cascading protection from some source pages?
4500 /** @var Title[] $cascadeSources */
4501 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4502 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4503 $cascadeSourcesCount = count( $cascadeSources );
4504 if ( $cascadeSourcesCount > 0 ) {
4505 # Explain, and list the titles responsible
4506 foreach ( $cascadeSources as $page ) {
4507 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4510 $notice .= '</div>';
4511 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4513 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4514 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4516 'showIfEmpty' => false,
4517 'msgKey' => [ 'titleprotectedwarning' ],
4518 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4523 * @param OutputPage $out
4526 protected function addExplainConflictHeader( OutputPage
$out ) {
4528 $this->getEditConflictHelper()->getExplainHeader()
4533 * @param string $name
4534 * @param mixed[] $customAttribs
4539 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4540 return ( new TextboxBuilder() )->buildTextboxAttribs(
4541 $name, $customAttribs, $user, $this->mTitle
4546 * @param string $wikitext
4550 protected function addNewLineAtEnd( $wikitext ) {
4551 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4555 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4556 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4557 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4558 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4559 * spread the new style links more efficiently.
4561 * @param string $text
4564 private function guessSectionName( $text ) {
4567 // Detect Microsoft browsers
4568 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4569 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4570 // ...and redirect them to legacy encoding, if available
4571 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4573 // Meanwhile, real browsers get real anchors
4574 return $wgParser->guessSectionNameFromWikiText( $text );
4578 * Set a factory function to create an EditConflictHelper
4580 * @param callable $factory Factory function
4583 public function setEditConflictHelperFactory( callable
$factory ) {
4584 $this->editConflictHelperFactory
= $factory;
4585 $this->editConflictHelper
= null;
4589 * @return TextConflictHelper
4591 private function getEditConflictHelper() {
4592 if ( !$this->editConflictHelper
) {
4593 $this->editConflictHelper
= call_user_func(
4594 $this->editConflictHelperFactory
,
4595 $this->getSubmitButtonLabel()
4599 return $this->editConflictHelper
;
4603 * @param string $submitButtonLabel
4604 * @return TextConflictHelper
4606 private function newTextConflictHelper( $submitButtonLabel ) {
4607 return new TextConflictHelper(
4609 $this->getContext()->getOutput(),
4610 MediaWikiServices
::getInstance()->getStatsdDataFactory(),