3 * User interface for page editing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\EditPage\TextboxBuilder
;
24 use MediaWiki\EditPage\TextConflictHelper
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\ScopedCallback
;
30 * The edit page/HTML interface (split from Article)
31 * The actual database and text munging is still in Article,
32 * but it should get easier to call those from alternate
35 * EditPage cares about two distinct titles:
36 * $this->mContextTitle is the page that forms submit to, links point to,
37 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
38 * page in the database that is actually being edited. These are
39 * usually the same, but they are now allowed to be different.
41 * Surgeon General's Warning: prolonged exposure to this class is known to cause
42 * headaches, which may be fatal.
46 * Used for Unicode support checks
48 const UNICODE_CHECK
= 'β³π²β₯πππΎπΈβ΄πΉβ―';
51 * Status: Article successfully updated
53 const AS_SUCCESS_UPDATE
= 200;
56 * Status: Article successfully created
58 const AS_SUCCESS_NEW_ARTICLE
= 201;
61 * Status: Article update aborted by a hook function
63 const AS_HOOK_ERROR
= 210;
66 * Status: A hook function returned an error
68 const AS_HOOK_ERROR_EXPECTED
= 212;
71 * Status: User is blocked from editing this page
73 const AS_BLOCKED_PAGE_FOR_USER
= 215;
76 * Status: Content too big (> $wgMaxArticleSize)
78 const AS_CONTENT_TOO_BIG
= 216;
81 * Status: this anonymous user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_ANON
= 218;
86 * Status: this logged in user is not allowed to edit this page
88 const AS_READ_ONLY_PAGE_LOGGED
= 219;
91 * Status: wiki is in readonly mode (wfReadOnly() == true)
93 const AS_READ_ONLY_PAGE
= 220;
96 * Status: rate limiter for action 'edit' was tripped
98 const AS_RATE_LIMITED
= 221;
101 * Status: article was deleted while editing and param wpRecreate == false or form
104 const AS_ARTICLE_WAS_DELETED
= 222;
107 * Status: user tried to create this page, but is not allowed to do that
108 * ( Title->userCan('create') == false )
110 const AS_NO_CREATE_PERMISSION
= 223;
113 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
115 const AS_BLANK_ARTICLE
= 224;
118 * Status: (non-resolvable) edit conflict
120 const AS_CONFLICT_DETECTED
= 225;
123 * Status: no edit summary given and the user has forceeditsummary set and the user is not
124 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
126 const AS_SUMMARY_NEEDED
= 226;
129 * Status: user tried to create a new section without content
131 const AS_TEXTBOX_EMPTY
= 228;
134 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
136 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
139 * Status: WikiPage::doEdit() was unsuccessful
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
146 const AS_SPAM_ERROR
= 232;
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
151 const AS_IMAGE_REDIRECT_ANON
= 233;
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
156 const AS_IMAGE_REDIRECT_LOGGED
= 234;
159 * Status: user tried to modify the content model, but is not allowed to do that
160 * ( User::isAllowed('editcontentmodel') == false )
162 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
165 * Status: user tried to create self-redirect (redirect to the same article) and
166 * wpIgnoreSelfRedirect == false
168 const AS_SELF_REDIRECT
= 236;
171 * Status: an error relating to change tagging. Look at the message key for
174 const AS_CHANGE_TAG_ERROR
= 237;
177 * Status: can't parse content
179 const AS_PARSE_ERROR
= 240;
182 * Status: when changing the content model is disallowed due to
183 * $wgContentHandlerUseDB being false
185 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
188 * Status: edit rejected because browser doesn't support Unicode.
190 const AS_UNICODE_NOT_SUPPORTED
= 242;
193 * HTML id and name for the beginning of the edit form.
195 const EDITFORM_ID
= 'editform';
198 * Prefix of key for cookie used to pass post-edit state.
199 * The revision id edited is added after this
201 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
204 * Duration of PostEdit cookie, in seconds.
205 * The cookie will be removed instantly if the JavaScript runs.
207 * Otherwise, though, we don't want the cookies to accumulate.
208 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
209 * limit of only 20 cookies per domain. This still applies at least to some
210 * versions of IE without full updates:
211 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
213 * A value of 20 minutes should be enough to take into account slow loads and minor
214 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
216 const POST_EDIT_COOKIE_DURATION
= 1200;
219 * @deprecated for public usage since 1.30 use EditPage::getArticle()
227 * @deprecated for public usage since 1.30 use EditPage::getTitle()
232 /** @var null|Title */
233 private $mContextTitle = null;
236 public $action = 'submit';
238 /** @var bool Whether an edit conflict needs to be resolved. Detected based on whether
239 * $editRevId is different from the current revision. When a conflict has successfully
240 * been resolved by a 3-way-merge, this field is set to false.
242 public $isConflict = false;
244 /** @var bool New page or new section */
245 public $isNew = false;
248 public $deletedSinceEdit;
256 /** @var bool|stdClass */
260 public $mTokenOk = false;
263 public $mTokenOkExceptSuffix = false;
266 public $mTriedSave = false;
269 public $incompleteForm = false;
272 public $tooBig = false;
275 public $missingComment = false;
278 public $missingSummary = false;
281 public $allowBlankSummary = false;
284 protected $blankArticle = false;
287 protected $allowBlankArticle = false;
290 protected $selfRedirect = false;
293 protected $allowSelfRedirect = false;
296 public $autoSumm = '';
299 public $hookError = '';
301 /** @var ParserOutput */
302 public $mParserOutput;
304 /** @var bool Has a summary been preset using GET parameter &summary= ? */
305 public $hasPresetSummary = false;
307 /** @var Revision|bool|null A revision object corresponding to $this->editRevId. */
308 public $mBaseRevision = false;
311 public $mShowSummaryField = true;
316 public $save = false;
319 public $preview = false;
322 public $diff = false;
325 public $minoredit = false;
328 public $watchthis = false;
331 public $recreate = false;
334 public $textbox1 = '';
337 public $textbox2 = '';
340 public $summary = '';
343 public $nosummary = false;
346 public $edittime = '';
348 /** @var int ID of the current revision at the time editing was initiated on the client.
349 * This is used to detect and resolve edit conflicts.
351 * @note 0 if the page did not exist at that time.
352 * @note When starting an edit from an old revision, this still records the current
353 * revision at the time , not the one the edit is based on.
356 * @see getBaseRevision()
358 private $editRevId = null;
361 public $section = '';
364 public $sectiontitle = '';
367 public $starttime = '';
369 /** @var int Revision ID the edit is based on, or 0 if it's the current revision.
374 /** @var int Revision ID the edit is based on, adjusted when an edit conflict is resolved.
377 * @see getparentRevId()
379 public $parentRevId = 0;
382 public $editintro = '';
385 public $scrolltop = null;
391 public $contentModel;
393 /** @var null|string */
394 public $contentFormat = null;
396 /** @var null|array */
397 private $changeTags = null;
399 # Placeholders for text injection by hooks (must be HTML)
400 # extensions should take care to _append_ to the present value
402 /** @var string Before even the preview */
403 public $editFormPageTop = '';
404 public $editFormTextTop = '';
405 public $editFormTextBeforeContent = '';
406 public $editFormTextAfterWarn = '';
407 public $editFormTextAfterTools = '';
408 public $editFormTextBottom = '';
409 public $editFormTextAfterContent = '';
410 public $previewTextAfterContent = '';
411 public $mPreloadContent = null;
413 /* $didSave should be set to true whenever an article was successfully altered. */
414 public $didSave = false;
415 public $undidRev = 0;
417 public $suppressIntro = false;
423 protected $contentLength = false;
426 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
428 private $enableApiEditOverride = false;
431 * @var IContextSource
436 * @var bool Whether an old revision is edited
438 private $isOldRev = false;
441 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
443 private $unicodeCheck;
446 * Factory function to create an edit conflict helper
450 private $editConflictHelperFactory;
453 * @var TextConflictHelper|null
455 private $editConflictHelper;
458 * @param Article $article
460 public function __construct( Article
$article ) {
461 $this->mArticle
= $article;
462 $this->page
= $article->getPage(); // model object
463 $this->mTitle
= $article->getTitle();
464 $this->context
= $article->getContext();
466 $this->contentModel
= $this->mTitle
->getContentModel();
468 $handler = ContentHandler
::getForModelID( $this->contentModel
);
469 $this->contentFormat
= $handler->getDefaultFormat();
470 $this->editConflictHelperFactory
= [ $this, 'newTextConflictHelper' ];
476 public function getArticle() {
477 return $this->mArticle
;
482 * @return IContextSource
484 public function getContext() {
485 return $this->context
;
492 public function getTitle() {
493 return $this->mTitle
;
497 * Set the context Title object
499 * @param Title|null $title Title object or null
501 public function setContextTitle( $title ) {
502 $this->mContextTitle
= $title;
506 * Get the context title object.
508 * If not set, $wgTitle will be returned, but this is deprecated. This will
509 * throw an exception.
513 public function getContextTitle() {
514 if ( is_null( $this->mContextTitle
) ) {
515 wfDeprecated( __METHOD__
. ' called with no title set', '1.32' );
519 return $this->mContextTitle
;
524 * Returns if the given content model is editable.
526 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
528 * @throws MWException If $modelId has no known handler
530 public function isSupportedContentModel( $modelId ) {
531 return $this->enableApiEditOverride
=== true ||
532 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
536 * Allow editing of content that supports API direct editing, but not general
537 * direct editing. Set to false by default.
539 * @param bool $enableOverride
541 public function setApiEditOverride( $enableOverride ) {
542 $this->enableApiEditOverride
= $enableOverride;
546 * @deprecated since 1.29, call edit directly
548 public function submit() {
549 wfDeprecated( __METHOD__
, '1.29' );
554 * This is the function that gets called for "action=edit". It
555 * sets up various member variables, then passes execution to
556 * another function, usually showEditForm()
558 * The edit form is self-submitting, so that when things like
559 * preview and edit conflicts occur, we get the same form back
560 * with the extra stuff added. Only when the final submission
561 * is made and all is well do we actually save and redirect to
562 * the newly-edited page.
564 public function edit() {
565 // Allow extensions to modify/prevent this form or submission
566 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
570 wfDebug( __METHOD__
. ": enter\n" );
572 $request = $this->context
->getRequest();
573 // If they used redlink=1 and the page exists, redirect to the main article
574 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
575 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
579 $this->importFormData( $request );
580 $this->firsttime
= false;
582 if ( wfReadOnly() && $this->save
) {
585 $this->preview
= true;
589 $this->formtype
= 'save';
590 } elseif ( $this->preview
) {
591 $this->formtype
= 'preview';
592 } elseif ( $this->diff
) {
593 $this->formtype
= 'diff';
594 } else { # First time through
595 $this->firsttime
= true;
596 if ( $this->previewOnOpen() ) {
597 $this->formtype
= 'preview';
599 $this->formtype
= 'initial';
603 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
605 wfDebug( __METHOD__
. ": User can't edit\n" );
607 // track block with a cookie if it doesn't exists already
608 $this->context
->getUser()->trackBlockWithCookie();
610 // Auto-block user's IP if the account was "hard" blocked
611 if ( !wfReadOnly() ) {
612 DeferredUpdates
::addCallableUpdate( function () {
613 $this->context
->getUser()->spreadAnyEditBlock();
616 $this->displayPermissionsError( $permErrors );
621 $revision = $this->mArticle
->getRevisionFetched();
622 // Disallow editing revisions with content models different from the current one
623 // Undo edits being an exception in order to allow reverting content model changes.
625 && $revision->getContentModel() !== $this->contentModel
628 if ( $this->undidRev
) {
629 $undidRevObj = Revision
::newFromId( $this->undidRev
);
630 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
632 if ( !$this->undidRev
634 ||
$prevRev->getContentModel() !== $this->contentModel
636 $this->displayViewSourcePage(
637 $this->getContentObject(),
639 'contentmodelediterror',
640 $revision->getContentModel(),
648 $this->isConflict
= false;
650 # Show applicable editing introductions
651 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
655 # Attempt submission here. This will check for edit conflicts,
656 # and redundantly check for locked database, blocked IPs, etc.
657 # that edit() already checked just in case someone tries to sneak
658 # in the back door with a hand-edited submission URL.
660 if ( 'save' == $this->formtype
) {
661 $resultDetails = null;
662 $status = $this->attemptSave( $resultDetails );
663 if ( !$this->handleStatus( $status, $resultDetails ) ) {
668 # First time through: get contents, set time for conflict
670 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
671 if ( $this->initialiseForm() === false ) {
672 $this->noSuchSectionPage();
676 if ( !$this->mTitle
->getArticleID() ) {
677 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
679 Hooks
::run( 'EditFormInitialText', [ $this ] );
684 $this->showEditForm();
688 * @param string $rigor Same format as Title::getUserPermissionErrors()
691 protected function getEditPermissionErrors( $rigor = 'secure' ) {
692 $user = $this->context
->getUser();
693 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
694 # Can this title be created?
695 if ( !$this->mTitle
->exists() ) {
696 $permErrors = array_merge(
699 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
704 # Ignore some permissions errors when a user is just previewing/viewing diffs
706 foreach ( $permErrors as $error ) {
707 if ( ( $this->preview ||
$this->diff
)
709 $error[0] == 'blockedtext' ||
710 $error[0] == 'autoblockedtext' ||
711 $error[0] == 'systemblockedtext'
717 $permErrors = wfArrayDiff2( $permErrors, $remove );
723 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
724 * but with the following differences:
725 * - If redlink=1, the user will be redirected to the page
726 * - If there is content to display or the error occurs while either saving,
727 * previewing or showing the difference, it will be a
728 * "View source for ..." page displaying the source code after the error message.
731 * @param array $permErrors Array of permissions errors, as returned by
732 * Title::getUserPermissionsErrors().
733 * @throws PermissionsError
735 protected function displayPermissionsError( array $permErrors ) {
736 $out = $this->context
->getOutput();
737 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
738 // The edit page was reached via a red link.
739 // Redirect to the article page and let them click the edit tab if
740 // they really want a permission error.
741 $out->redirect( $this->mTitle
->getFullURL() );
745 $content = $this->getContentObject();
747 # Use the normal message if there's nothing to display
748 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
749 $action = $this->mTitle
->exists() ?
'edit' :
750 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
751 throw new PermissionsError( $action, $permErrors );
754 $this->displayViewSourcePage(
756 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
761 * Display a read-only View Source page
762 * @param Content $content
763 * @param string $errorMessage additional wikitext error message to display
765 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
766 $out = $this->context
->getOutput();
767 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
769 $out->setRobotPolicy( 'noindex,nofollow' );
770 $out->setPageTitle( $this->context
->msg(
772 $this->getContextTitle()->getPrefixedText()
774 $out->addBacklinkSubtitle( $this->getContextTitle() );
775 $out->addHTML( $this->editFormPageTop
);
776 $out->addHTML( $this->editFormTextTop
);
778 if ( $errorMessage !== '' ) {
779 $out->addWikiText( $errorMessage );
780 $out->addHTML( "<hr />\n" );
783 # If the user made changes, preserve them when showing the markup
784 # (This happens when a user is blocked during edit, for instance)
785 if ( !$this->firsttime
) {
786 $text = $this->textbox1
;
787 $out->addWikiMsg( 'viewyourtext' );
790 $text = $this->toEditText( $content );
791 } catch ( MWException
$e ) {
792 # Serialize using the default format if the content model is not supported
793 # (e.g. for an old revision with a different model)
794 $text = $content->serialize();
796 $out->addWikiMsg( 'viewsourcetext' );
799 $out->addHTML( $this->editFormTextBeforeContent
);
800 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
801 $out->addHTML( $this->editFormTextAfterContent
);
803 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
805 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
807 $out->addHTML( $this->editFormTextBottom
);
808 if ( $this->mTitle
->exists() ) {
809 $out->returnToMain( null, $this->mTitle
);
814 * Should we show a preview when the edit form is first shown?
818 protected function previewOnOpen() {
819 $config = $this->context
->getConfig();
820 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
821 $request = $this->context
->getRequest();
822 if ( $config->get( 'RawHtml' ) ) {
823 // If raw HTML is enabled, disable preview on open
824 // since it has to be posted with a token for
828 if ( $request->getVal( 'preview' ) == 'yes' ) {
829 // Explicit override from request
831 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
832 // Explicit override from request
834 } elseif ( $this->section
== 'new' ) {
835 // Nothing *to* preview for new sections
837 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
838 && $this->context
->getUser()->getOption( 'previewonfirst' )
840 // Standard preference behavior
842 } elseif ( !$this->mTitle
->exists()
843 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
844 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
846 // Categories are special
854 * Checks whether the user entered a skin name in uppercase,
855 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
859 protected function isWrongCaseUserConfigPage() {
860 if ( $this->mTitle
->isUserConfigPage() ) {
861 $name = $this->mTitle
->getSkinFromConfigSubpage();
862 $skins = array_merge(
863 array_keys( Skin
::getSkinNames() ),
866 return !in_array( $name, $skins )
867 && in_array( strtolower( $name ), $skins );
874 * Returns whether section editing is supported for the current page.
875 * Subclasses may override this to replace the default behavior, which is
876 * to check ContentHandler::supportsSections.
878 * @return bool True if this edit page supports sections, false otherwise.
880 protected function isSectionEditSupported() {
881 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
882 return $contentHandler->supportsSections();
886 * This function collects the form data and uses it to populate various member variables.
887 * @param WebRequest &$request
888 * @throws ErrorPageError
890 public function importFormData( &$request ) {
891 # Section edit can come from either the form or a link
892 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
894 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
895 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
898 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
900 if ( $request->wasPosted() ) {
901 # These fields need to be checked for encoding.
902 # Also remove trailing whitespace, but don't remove _initial_
903 # whitespace from the text boxes. This may be significant formatting.
904 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
905 if ( !$request->getCheck( 'wpTextbox2' ) ) {
906 // Skip this if wpTextbox2 has input, it indicates that we came
907 // from a conflict page with raw page text, not a custom form
908 // modified by subclasses
909 $textbox1 = $this->importContentFormData( $request );
910 if ( $textbox1 !== null ) {
911 $this->textbox1
= $textbox1;
915 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
917 $this->summary
= $request->getText( 'wpSummary' );
919 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
920 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
922 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
924 # Treat sectiontitle the same way as summary.
925 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
926 # currently doing double duty as both edit summary and section title. Right now this
927 # is just to allow API edits to work around this limitation, but this should be
928 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
929 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
930 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
932 $this->edittime
= $request->getVal( 'wpEdittime' );
933 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
934 $this->starttime
= $request->getVal( 'wpStarttime' );
936 $undidRev = $request->getInt( 'wpUndidRevision' );
938 $this->undidRev
= $undidRev;
941 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
943 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
944 // wpTextbox1 field is missing, possibly due to being "too big"
945 // according to some filter rules such as Suhosin's setting for
946 // suhosin.request.max_value_length (d'oh)
947 $this->incompleteForm
= true;
949 // If we receive the last parameter of the request, we can fairly
950 // claim the POST request has not been truncated.
952 // TODO: softened the check for cutover. Once we determine
953 // that it is safe, we should complete the transition by
954 // removing the "edittime" clause.
955 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
956 && is_null( $this->edittime
) );
958 if ( $this->incompleteForm
) {
959 # If the form is incomplete, force to preview.
960 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
961 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
962 $this->preview
= true;
964 $this->preview
= $request->getCheck( 'wpPreview' );
965 $this->diff
= $request->getCheck( 'wpDiff' );
967 // Remember whether a save was requested, so we can indicate
968 // if we forced preview due to session failure.
969 $this->mTriedSave
= !$this->preview
;
971 if ( $this->tokenOk( $request ) ) {
972 # Some browsers will not report any submit button
973 # if the user hits enter in the comment box.
974 # The unmarked state will be assumed to be a save,
975 # if the form seems otherwise complete.
976 wfDebug( __METHOD__
. ": Passed token check.\n" );
977 } elseif ( $this->diff
) {
978 # Failed token check, but only requested "Show Changes".
979 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
981 # Page might be a hack attempt posted from
982 # an external site. Preview instead of saving.
983 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
984 $this->preview
= true;
987 $this->save
= !$this->preview
&& !$this->diff
;
988 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
989 $this->edittime
= null;
992 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
993 $this->starttime
= null;
996 $this->recreate
= $request->getCheck( 'wpRecreate' );
998 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
999 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
1001 $user = $this->context
->getUser();
1002 # Don't force edit summaries when a user is editing their own user or talk page
1003 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
1004 && $this->mTitle
->getText() == $user->getName()
1006 $this->allowBlankSummary
= true;
1008 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1009 ||
!$user->getOption( 'forceeditsummary' );
1012 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1014 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1015 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1017 $changeTags = $request->getVal( 'wpChangeTags' );
1018 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1019 $this->changeTags
= [];
1021 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1025 # Not a posted form? Start with nothing.
1026 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1027 $this->textbox1
= '';
1028 $this->summary
= '';
1029 $this->sectiontitle
= '';
1030 $this->edittime
= '';
1031 $this->editRevId
= null;
1032 $this->starttime
= wfTimestampNow();
1033 $this->edit
= false;
1034 $this->preview
= false;
1035 $this->save
= false;
1036 $this->diff
= false;
1037 $this->minoredit
= false;
1038 // Watch may be overridden by request parameters
1039 $this->watchthis
= $request->getBool( 'watchthis', false );
1040 $this->recreate
= false;
1042 // When creating a new section, we can preload a section title by passing it as the
1043 // preloadtitle parameter in the URL (T15100)
1044 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1045 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1046 // Once wpSummary isn't being use for setting section titles, we should delete this.
1047 $this->summary
= $request->getVal( 'preloadtitle' );
1048 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1049 $this->summary
= $request->getText( 'summary' );
1050 if ( $this->summary
!== '' ) {
1051 $this->hasPresetSummary
= true;
1055 if ( $request->getVal( 'minor' ) ) {
1056 $this->minoredit
= true;
1060 $this->oldid
= $request->getInt( 'oldid' );
1061 $this->parentRevId
= $request->getInt( 'parentRevId' );
1063 $this->bot
= $request->getBool( 'bot', true );
1064 $this->nosummary
= $request->getBool( 'nosummary' );
1066 // May be overridden by revision.
1067 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1068 // May be overridden by revision.
1069 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1072 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1073 } catch ( MWUnknownContentModelException
$e ) {
1074 throw new ErrorPageError(
1075 'editpage-invalidcontentmodel-title',
1076 'editpage-invalidcontentmodel-text',
1077 [ wfEscapeWikiText( $this->contentModel
) ]
1081 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1082 throw new ErrorPageError(
1083 'editpage-notsupportedcontentformat-title',
1084 'editpage-notsupportedcontentformat-text',
1086 wfEscapeWikiText( $this->contentFormat
),
1087 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1093 * @todo Check if the desired model is allowed in this namespace, and if
1094 * a transition from the page's current model to the new model is
1098 $this->editintro
= $request->getText( 'editintro',
1099 // Custom edit intro for new sections
1100 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1102 // Allow extensions to modify form data
1103 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1107 * Subpage overridable method for extracting the page content data from the
1108 * posted form to be placed in $this->textbox1, if using customized input
1109 * this method should be overridden and return the page text that will be used
1110 * for saving, preview parsing and so on...
1112 * @param WebRequest &$request
1113 * @return string|null
1115 protected function importContentFormData( &$request ) {
1116 return; // Don't do anything, EditPage already extracted wpTextbox1
1120 * Initialise form fields in the object
1121 * Called on the first invocation, e.g. when a user clicks an edit link
1122 * @return bool If the requested section is valid
1124 public function initialiseForm() {
1125 $this->edittime
= $this->page
->getTimestamp();
1126 $this->editRevId
= $this->page
->getLatest();
1128 $content = $this->getContentObject( false ); # TODO: track content object?!
1129 if ( $content === false ) {
1132 $this->textbox1
= $this->toEditText( $content );
1134 $user = $this->context
->getUser();
1135 // activate checkboxes if user wants them to be always active
1136 # Sort out the "watch" checkbox
1137 if ( $user->getOption( 'watchdefault' ) ) {
1139 $this->watchthis
= true;
1140 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1142 $this->watchthis
= true;
1143 } elseif ( $user->isWatched( $this->mTitle
) ) {
1145 $this->watchthis
= true;
1147 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1148 $this->minoredit
= true;
1150 if ( $this->textbox1
=== false ) {
1157 * @param Content|null $def_content The default value to return
1159 * @return Content|null Content on success, $def_content for invalid sections
1163 protected function getContentObject( $def_content = null ) {
1168 $user = $this->context
->getUser();
1169 $request = $this->context
->getRequest();
1170 // For message page not locally set, use the i18n message.
1171 // For other non-existent articles, use preload text if any.
1172 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1173 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1174 # If this is a system message, get the default text.
1175 $msg = $this->mTitle
->getDefaultMessageText();
1177 $content = $this->toEditContent( $msg );
1179 if ( $content === false ) {
1180 # If requested, preload some text.
1181 $preload = $request->getVal( 'preload',
1182 // Custom preload text for new sections
1183 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1184 $params = $request->getArray( 'preloadparams', [] );
1186 $content = $this->getPreloadedContent( $preload, $params );
1188 // For existing pages, get text based on "undo" or section parameters.
1190 if ( $this->section
!= '' ) {
1191 // Get section edit text (returns $def_text for invalid sections)
1192 $orig = $this->getOriginalContent( $user );
1193 $content = $orig ?
$orig->getSection( $this->section
) : null;
1196 $content = $def_content;
1199 $undoafter = $request->getInt( 'undoafter' );
1200 $undo = $request->getInt( 'undo' );
1202 if ( $undo > 0 && $undoafter > 0 ) {
1203 $undorev = Revision
::newFromId( $undo );
1204 $oldrev = Revision
::newFromId( $undoafter );
1207 # Sanity check, make sure it's the right page,
1208 # the revisions exist and they were not deleted.
1209 # Otherwise, $content will be left as-is.
1210 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1211 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1212 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1214 if ( WikiPage
::hasDifferencesOutsideMainSlot( $undorev, $oldrev ) ) {
1215 // Cannot yet undo edits that involve anything other the main slot.
1216 $undoMsg = 'main-slot-only';
1218 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1220 if ( $content === false ) {
1221 # Warn the user that something went wrong
1222 $undoMsg = 'failure';
1226 if ( $undoMsg === null ) {
1227 $oldContent = $this->page
->getContent( Revision
::RAW
);
1228 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1229 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1230 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1231 // The undo may change content
1232 // model if its reverting the top
1233 // edit. This can result in
1234 // mismatched content model/format.
1235 $this->contentModel
= $newContent->getModel();
1236 $this->contentFormat
= $oldrev->getContentFormat();
1239 if ( $newContent->equals( $oldContent ) ) {
1240 # Tell the user that the undo results in no change,
1241 # i.e. the revisions were already undone.
1242 $undoMsg = 'nochange';
1245 # Inform the user of our success and set an automatic edit summary
1246 $undoMsg = 'success';
1248 # If we just undid one rev, use an autosummary
1249 $firstrev = $oldrev->getNext();
1250 if ( $firstrev && $firstrev->getId() == $undo ) {
1251 $userText = $undorev->getUserText();
1252 if ( $userText === '' ) {
1253 $undoSummary = $this->context
->msg(
1254 'undo-summary-username-hidden',
1256 )->inContentLanguage()->text();
1258 $undoSummary = $this->context
->msg(
1262 )->inContentLanguage()->text();
1264 if ( $this->summary
=== '' ) {
1265 $this->summary
= $undoSummary;
1267 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1268 ->inContentLanguage()->text() . $this->summary
;
1270 $this->undidRev
= $undo;
1272 $this->formtype
= 'diff';
1276 // Failed basic sanity checks.
1277 // Older revisions may have been removed since the link
1278 // was created, or we may simply have got bogus input.
1282 $out = $this->context
->getOutput();
1283 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1285 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1286 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1287 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1290 if ( $content === false ) {
1291 $content = $this->getOriginalContent( $user );
1300 * Get the content of the wanted revision, without section extraction.
1302 * The result of this function can be used to compare user's input with
1303 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1304 * to the original text of the edit.
1306 * This differs from Article::getContent() that when a missing revision is
1307 * encountered the result will be null and not the
1308 * 'missing-revision' message.
1311 * @param User $user The user to get the revision for
1312 * @return Content|null
1314 private function getOriginalContent( User
$user ) {
1315 if ( $this->section
== 'new' ) {
1316 return $this->getCurrentContent();
1318 $revision = $this->mArticle
->getRevisionFetched();
1319 if ( $revision === null ) {
1320 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1321 return $handler->makeEmptyContent();
1323 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1328 * Get the edit's parent revision ID
1330 * The "parent" revision is the ancestor that should be recorded in this
1331 * page's revision history. It is either the revision ID of the in-memory
1332 * article content, or in the case of a 3-way merge in order to rebase
1333 * across a recoverable edit conflict, the ID of the newer revision to
1334 * which we have rebased this page.
1337 * @return int Revision ID
1339 public function getParentRevId() {
1340 if ( $this->parentRevId
) {
1341 return $this->parentRevId
;
1343 return $this->mArticle
->getRevIdFetched();
1348 * Get the current content of the page. This is basically similar to
1349 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1350 * content object is returned instead of null.
1355 protected function getCurrentContent() {
1356 $rev = $this->page
->getRevision();
1357 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1359 if ( $content === false ||
$content === null ) {
1360 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1361 return $handler->makeEmptyContent();
1362 } elseif ( !$this->undidRev
) {
1363 // Content models should always be the same since we error
1364 // out if they are different before this point (in ->edit()).
1365 // The exception being, during an undo, the current revision might
1366 // differ from the prior revision.
1367 $logger = LoggerFactory
::getInstance( 'editpage' );
1368 if ( $this->contentModel
!== $rev->getContentModel() ) {
1369 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1370 'prev' => $this->contentModel
,
1371 'new' => $rev->getContentModel(),
1372 'title' => $this->getTitle()->getPrefixedDBkey(),
1373 'method' => __METHOD__
1375 $this->contentModel
= $rev->getContentModel();
1378 // Given that the content models should match, the current selected
1379 // format should be supported.
1380 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1381 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1383 'prev' => $this->contentFormat
,
1384 'new' => $rev->getContentFormat(),
1385 'title' => $this->getTitle()->getPrefixedDBkey(),
1386 'method' => __METHOD__
1388 $this->contentFormat
= $rev->getContentFormat();
1395 * Use this method before edit() to preload some content into the edit box
1397 * @param Content $content
1401 public function setPreloadedContent( Content
$content ) {
1402 $this->mPreloadContent
= $content;
1406 * Get the contents to be preloaded into the box, either set by
1407 * an earlier setPreloadText() or by loading the given page.
1409 * @param string $preload Representing the title to preload from.
1410 * @param array $params Parameters to use (interface-message style) in the preloaded text
1416 protected function getPreloadedContent( $preload, $params = [] ) {
1417 if ( !empty( $this->mPreloadContent
) ) {
1418 return $this->mPreloadContent
;
1421 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1423 if ( $preload === '' ) {
1424 return $handler->makeEmptyContent();
1427 $user = $this->context
->getUser();
1428 $title = Title
::newFromText( $preload );
1429 # Check for existence to avoid getting MediaWiki:Noarticletext
1430 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1431 // TODO: somehow show a warning to the user!
1432 return $handler->makeEmptyContent();
1435 $page = WikiPage
::factory( $title );
1436 if ( $page->isRedirect() ) {
1437 $title = $page->getRedirectTarget();
1439 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1440 // TODO: somehow show a warning to the user!
1441 return $handler->makeEmptyContent();
1443 $page = WikiPage
::factory( $title );
1446 $parserOptions = ParserOptions
::newFromUser( $user );
1447 $content = $page->getContent( Revision
::RAW
);
1450 // TODO: somehow show a warning to the user!
1451 return $handler->makeEmptyContent();
1454 if ( $content->getModel() !== $handler->getModelID() ) {
1455 $converted = $content->convert( $handler->getModelID() );
1457 if ( !$converted ) {
1458 // TODO: somehow show a warning to the user!
1459 wfDebug( "Attempt to preload incompatible content: " .
1460 "can't convert " . $content->getModel() .
1461 " to " . $handler->getModelID() );
1463 return $handler->makeEmptyContent();
1466 $content = $converted;
1469 return $content->preloadTransform( $title, $parserOptions, $params );
1473 * Make sure the form isn't faking a user's credentials.
1475 * @param WebRequest &$request
1479 public function tokenOk( &$request ) {
1480 $token = $request->getVal( 'wpEditToken' );
1481 $user = $this->context
->getUser();
1482 $this->mTokenOk
= $user->matchEditToken( $token );
1483 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1484 return $this->mTokenOk
;
1488 * Sets post-edit cookie indicating the user just saved a particular revision.
1490 * This uses a temporary cookie for each revision ID so separate saves will never
1491 * interfere with each other.
1493 * Article::view deletes the cookie on server-side after the redirect and
1494 * converts the value to the global JavaScript variable wgPostEdit.
1496 * If the variable were set on the server, it would be cached, which is unwanted
1497 * since the post-edit state should only apply to the load right after the save.
1499 * @param int $statusValue The status value (to check for new article status)
1501 protected function setPostEditCookie( $statusValue ) {
1502 $revisionId = $this->page
->getLatest();
1503 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1506 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1508 } elseif ( $this->oldid
) {
1512 $response = $this->context
->getRequest()->response();
1513 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1517 * Attempt submission
1518 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1519 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1520 * @return Status The resulting status object.
1522 public function attemptSave( &$resultDetails = false ) {
1523 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1524 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1525 // This is needed since PageUpdater no longer checks these rights!
1527 // Allow bots to exempt some edits from bot flagging
1528 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1529 $status = $this->internalAttemptSave( $resultDetails, $bot );
1531 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1537 * Log when a page was successfully saved after the edit conflict view
1539 private function incrementResolvedConflicts() {
1540 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1544 $this->getEditConflictHelper()->incrementResolvedStats();
1548 * Handle status, such as after attempt save
1550 * @param Status $status
1551 * @param array|bool $resultDetails
1553 * @throws ErrorPageError
1554 * @return bool False, if output is done, true if rest of the form should be displayed
1556 private function handleStatus( Status
$status, $resultDetails ) {
1558 * @todo FIXME: once the interface for internalAttemptSave() is made
1559 * nicer, this should use the message in $status
1561 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1562 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1564 $this->incrementResolvedConflicts();
1566 $this->didSave
= true;
1567 if ( !$resultDetails['nullEdit'] ) {
1568 $this->setPostEditCookie( $status->value
);
1572 $out = $this->context
->getOutput();
1574 // "wpExtraQueryRedirect" is a hidden input to modify
1575 // after save URL and is not used by actual edit form
1576 $request = $this->context
->getRequest();
1577 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1579 switch ( $status->value
) {
1580 case self
::AS_HOOK_ERROR_EXPECTED
:
1581 case self
::AS_CONTENT_TOO_BIG
:
1582 case self
::AS_ARTICLE_WAS_DELETED
:
1583 case self
::AS_CONFLICT_DETECTED
:
1584 case self
::AS_SUMMARY_NEEDED
:
1585 case self
::AS_TEXTBOX_EMPTY
:
1586 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1588 case self
::AS_BLANK_ARTICLE
:
1589 case self
::AS_SELF_REDIRECT
:
1592 case self
::AS_HOOK_ERROR
:
1595 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1596 case self
::AS_PARSE_ERROR
:
1597 case self
::AS_UNICODE_NOT_SUPPORTED
:
1598 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1601 case self
::AS_SUCCESS_NEW_ARTICLE
:
1602 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1603 if ( $extraQueryRedirect ) {
1604 if ( $query === '' ) {
1605 $query = $extraQueryRedirect;
1607 $query = $query . '&' . $extraQueryRedirect;
1610 $anchor = $resultDetails['sectionanchor'] ??
'';
1611 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1614 case self
::AS_SUCCESS_UPDATE
:
1616 $sectionanchor = $resultDetails['sectionanchor'];
1618 // Give extensions a chance to modify URL query on update
1620 'ArticleUpdateBeforeRedirect',
1621 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1624 if ( $resultDetails['redirect'] ) {
1625 if ( $extraQuery == '' ) {
1626 $extraQuery = 'redirect=no';
1628 $extraQuery = 'redirect=no&' . $extraQuery;
1631 if ( $extraQueryRedirect ) {
1632 if ( $extraQuery === '' ) {
1633 $extraQuery = $extraQueryRedirect;
1635 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1639 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1642 case self
::AS_SPAM_ERROR
:
1643 $this->spamPageWithContent( $resultDetails['spam'] );
1646 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1647 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1649 case self
::AS_IMAGE_REDIRECT_ANON
:
1650 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1651 throw new PermissionsError( 'upload' );
1653 case self
::AS_READ_ONLY_PAGE_ANON
:
1654 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1655 throw new PermissionsError( 'edit' );
1657 case self
::AS_READ_ONLY_PAGE
:
1658 throw new ReadOnlyError
;
1660 case self
::AS_RATE_LIMITED
:
1661 throw new ThrottledError();
1663 case self
::AS_NO_CREATE_PERMISSION
:
1664 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1665 throw new PermissionsError( $permission );
1667 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1668 throw new PermissionsError( 'editcontentmodel' );
1671 // We don't recognize $status->value. The only way that can happen
1672 // is if an extension hook aborted from inside ArticleSave.
1673 // Render the status object into $this->hookError
1674 // FIXME this sucks, we should just use the Status object throughout
1675 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1682 * Run hooks that can filter edits just before they get saved.
1684 * @param Content $content The Content to filter.
1685 * @param Status $status For reporting the outcome to the caller
1686 * @param User $user The user performing the edit
1690 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1691 // Run old style post-section-merge edit filter
1692 if ( $this->hookError
!= '' ) {
1693 # ...or the hook could be expecting us to produce an error
1694 $status->fatal( 'hookaborted' );
1695 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1699 // Run new style post-section-merge edit filter
1700 if ( !Hooks
::run( 'EditFilterMergedContent',
1701 [ $this->context
, $content, $status, $this->summary
,
1702 $user, $this->minoredit
] )
1704 # Error messages etc. could be handled within the hook...
1705 if ( $status->isGood() ) {
1706 $status->fatal( 'hookaborted' );
1707 // Not setting $this->hookError here is a hack to allow the hook
1708 // to cause a return to the edit page without $this->hookError
1709 // being set. This is used by ConfirmEdit to display a captcha
1710 // without any error message cruft.
1712 $this->hookError
= $this->formatStatusErrors( $status );
1714 // Use the existing $status->value if the hook set it
1715 if ( !$status->value
) {
1716 $status->value
= self
::AS_HOOK_ERROR
;
1719 } elseif ( !$status->isOK() ) {
1720 # ...or the hook could be expecting us to produce an error
1721 // FIXME this sucks, we should just use the Status object throughout
1722 $this->hookError
= $this->formatStatusErrors( $status );
1723 $status->fatal( 'hookaborted' );
1724 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1732 * Wrap status errors in an errorbox for increased visibility
1734 * @param Status $status
1735 * @return string Wikitext
1737 private function formatStatusErrors( Status
$status ) {
1738 $errmsg = $status->getWikiText(
1741 $this->context
->getLanguage()
1744 <div class="errorbox">
1752 * Return the summary to be used for a new section.
1754 * @param string $sectionanchor Set to the section anchor text
1757 private function newSectionSummary( &$sectionanchor = null ) {
1760 if ( $this->sectiontitle
!== '' ) {
1761 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1762 // If no edit summary was specified, create one automatically from the section
1763 // title and have it link to the new section. Otherwise, respect the summary as
1765 if ( $this->summary
=== '' ) {
1766 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1767 return $this->context
->msg( 'newsectionsummary' )
1768 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1770 } elseif ( $this->summary
!== '' ) {
1771 $sectionanchor = $this->guessSectionName( $this->summary
);
1772 # This is a new section, so create a link to the new section
1773 # in the revision summary.
1774 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1775 return $this->context
->msg( 'newsectionsummary' )
1776 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1778 return $this->summary
;
1782 * Attempt submission (no UI)
1784 * @param array &$result Array to add statuses to, currently with the
1786 * - spam (string): Spam string from content if any spam is detected by
1788 * - sectionanchor (string): Section anchor for a section save.
1789 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1791 * - redirect (bool): Set if doEditContent is OK. True if resulting
1792 * revision is a redirect.
1793 * @param bool $bot True if edit is being made under the bot right.
1795 * @return Status Status object, possibly with a message, but always with
1796 * one of the AS_* constants in $status->value,
1798 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1799 * various error display idiosyncrasies. There are also lots of cases
1800 * where error metadata is set in the object and retrieved later instead
1801 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1802 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1805 public function internalAttemptSave( &$result, $bot = false ) {
1806 $status = Status
::newGood();
1807 $user = $this->context
->getUser();
1809 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1810 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1811 $status->fatal( 'hookaborted' );
1812 $status->value
= self
::AS_HOOK_ERROR
;
1816 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1817 $status->fatal( 'unicode-support-fail' );
1818 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1822 $request = $this->context
->getRequest();
1823 $spam = $request->getText( 'wpAntispam' );
1824 if ( $spam !== '' ) {
1829 $this->mTitle
->getPrefixedText() .
1830 '" submitted bogus field "' .
1834 $status->fatal( 'spamprotectionmatch', false );
1835 $status->value
= self
::AS_SPAM_ERROR
;
1840 # Construct Content object
1841 $textbox_content = $this->toEditContent( $this->textbox1
);
1842 } catch ( MWContentSerializationException
$ex ) {
1844 'content-failed-to-parse',
1845 $this->contentModel
,
1846 $this->contentFormat
,
1849 $status->value
= self
::AS_PARSE_ERROR
;
1853 # Check image redirect
1854 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1855 $textbox_content->isRedirect() &&
1856 !$user->isAllowed( 'upload' )
1858 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1859 $status->setResult( false, $code );
1865 $match = self
::matchSummarySpamRegex( $this->summary
);
1866 if ( $match === false && $this->section
== 'new' ) {
1867 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1868 # regular summaries, it is added to the actual wikitext.
1869 if ( $this->sectiontitle
!== '' ) {
1870 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1871 $match = self
::matchSpamRegex( $this->sectiontitle
);
1873 # This branch is taken when the "Add Topic" user interface is used, or the API
1874 # is used with the 'summary' parameter.
1875 $match = self
::matchSpamRegex( $this->summary
);
1878 if ( $match === false ) {
1879 $match = self
::matchSpamRegex( $this->textbox1
);
1881 if ( $match !== false ) {
1882 $result['spam'] = $match;
1883 $ip = $request->getIP();
1884 $pdbk = $this->mTitle
->getPrefixedDBkey();
1885 $match = str_replace( "\n", '', $match );
1886 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1887 $status->fatal( 'spamprotectionmatch', $match );
1888 $status->value
= self
::AS_SPAM_ERROR
;
1893 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1895 # Error messages etc. could be handled within the hook...
1896 $status->fatal( 'hookaborted' );
1897 $status->value
= self
::AS_HOOK_ERROR
;
1899 } elseif ( $this->hookError
!= '' ) {
1900 # ...or the hook could be expecting us to produce an error
1901 $status->fatal( 'hookaborted' );
1902 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1906 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1907 // Auto-block user's IP if the account was "hard" blocked
1908 if ( !wfReadOnly() ) {
1909 $user->spreadAnyEditBlock();
1911 # Check block state against master, thus 'false'.
1912 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1916 $this->contentLength
= strlen( $this->textbox1
);
1917 $config = $this->context
->getConfig();
1918 $maxArticleSize = $config->get( 'MaxArticleSize' );
1919 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1920 // Error will be displayed by showEditForm()
1921 $this->tooBig
= true;
1922 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1926 if ( !$user->isAllowed( 'edit' ) ) {
1927 if ( $user->isAnon() ) {
1928 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1931 $status->fatal( 'readonlytext' );
1932 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1937 $changingContentModel = false;
1938 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1939 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1940 $status->fatal( 'editpage-cannot-use-custom-model' );
1941 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1943 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1944 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1947 // Make sure the user can edit the page under the new content model too
1948 $titleWithNewContentModel = clone $this->mTitle
;
1949 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1950 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1951 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1953 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1957 $changingContentModel = true;
1958 $oldContentModel = $this->mTitle
->getContentModel();
1961 if ( $this->changeTags
) {
1962 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1963 $this->changeTags
, $user );
1964 if ( !$changeTagsStatus->isOK() ) {
1965 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1966 return $changeTagsStatus;
1970 if ( wfReadOnly() ) {
1971 $status->fatal( 'readonlytext' );
1972 $status->value
= self
::AS_READ_ONLY_PAGE
;
1975 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1976 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1978 $status->fatal( 'actionthrottledtext' );
1979 $status->value
= self
::AS_RATE_LIMITED
;
1983 # If the article has been deleted while editing, don't save it without
1985 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1986 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1990 # Load the page data from the master. If anything changes in the meantime,
1991 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1992 $this->page
->loadPageData( 'fromdbmaster' );
1993 $new = !$this->page
->exists();
1996 // Late check for create permission, just in case *PARANOIA*
1997 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1998 $status->fatal( 'nocreatetext' );
1999 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
2000 wfDebug( __METHOD__
. ": no create permission\n" );
2004 // Don't save a new page if it's blank or if it's a MediaWiki:
2005 // message with content equivalent to default (allow empty pages
2006 // in this case to disable messages, see T52124)
2007 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2008 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
2009 $defaultText = $defaultMessageText;
2014 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
2015 $this->blankArticle
= true;
2016 $status->fatal( 'blankarticle' );
2017 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
2021 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2025 $content = $textbox_content;
2027 $result['sectionanchor'] = '';
2028 if ( $this->section
== 'new' ) {
2029 if ( $this->sectiontitle
!== '' ) {
2030 // Insert the section title above the content.
2031 $content = $content->addSectionHeader( $this->sectiontitle
);
2032 } elseif ( $this->summary
!== '' ) {
2033 // Insert the section title above the content.
2034 $content = $content->addSectionHeader( $this->summary
);
2036 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2039 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2043 # Article exists. Check for edit conflict.
2045 $this->page
->clear(); # Force reload of dates, etc.
2046 $timestamp = $this->page
->getTimestamp();
2047 $latest = $this->page
->getLatest();
2049 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2051 // An edit conflict is detected if the current revision is different from the
2052 // revision that was current when editing was initiated on the client.
2053 // This is checked based on the timestamp and revision ID.
2054 // TODO: the timestamp based check can probably go away now.
2055 if ( $timestamp != $this->edittime
2056 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2058 $this->isConflict
= true;
2059 if ( $this->section
== 'new' ) {
2060 if ( $this->page
->getUserText() == $user->getName() &&
2061 $this->page
->getComment() == $this->newSectionSummary()
2063 // Probably a duplicate submission of a new comment.
2064 // This can happen when CDN resends a request after
2065 // a timeout but the first one actually went through.
2067 . ": duplicate new section submission; trigger edit conflict!\n" );
2069 // New comment; suppress conflict.
2070 $this->isConflict
= false;
2071 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2073 } elseif ( $this->section
== ''
2074 && Revision
::userWasLastToEdit(
2075 DB_MASTER
, $this->mTitle
->getArticleID(),
2076 $user->getId(), $this->edittime
2079 # Suppress edit conflict with self, except for section edits where merging is required.
2080 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2081 $this->isConflict
= false;
2085 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2086 if ( $this->sectiontitle
!== '' ) {
2087 $sectionTitle = $this->sectiontitle
;
2089 $sectionTitle = $this->summary
;
2094 if ( $this->isConflict
) {
2096 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2097 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2098 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2099 // ...or disable section editing for non-current revisions (not exposed anyway).
2100 if ( $this->editRevId
!== null ) {
2101 $content = $this->page
->replaceSectionAtRev(
2108 $content = $this->page
->replaceSectionContent(
2116 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2117 $content = $this->page
->replaceSectionContent(
2124 if ( is_null( $content ) ) {
2125 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2126 $this->isConflict
= true;
2127 $content = $textbox_content; // do not try to merge here!
2128 } elseif ( $this->isConflict
) {
2130 if ( $this->mergeChangesIntoContent( $content ) ) {
2131 // Successful merge! Maybe we should tell the user the good news?
2132 $this->isConflict
= false;
2133 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2135 $this->section
= '';
2136 $this->textbox1
= ContentHandler
::getContentText( $content );
2137 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2141 if ( $this->isConflict
) {
2142 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2146 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2150 if ( $this->section
== 'new' ) {
2151 // Handle the user preference to force summaries here
2152 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2153 $this->missingSummary
= true;
2154 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2155 $status->value
= self
::AS_SUMMARY_NEEDED
;
2159 // Do not allow the user to post an empty comment
2160 if ( $this->textbox1
== '' ) {
2161 $this->missingComment
= true;
2162 $status->fatal( 'missingcommenttext' );
2163 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2166 } elseif ( !$this->allowBlankSummary
2167 && !$content->equals( $this->getOriginalContent( $user ) )
2168 && !$content->isRedirect()
2169 && md5( $this->summary
) == $this->autoSumm
2171 $this->missingSummary
= true;
2172 $status->fatal( 'missingsummary' );
2173 $status->value
= self
::AS_SUMMARY_NEEDED
;
2178 $sectionanchor = '';
2179 if ( $this->section
== 'new' ) {
2180 $this->summary
= $this->newSectionSummary( $sectionanchor );
2181 } elseif ( $this->section
!= '' ) {
2182 # Try to get a section anchor from the section source, redirect
2183 # to edited section if header found.
2184 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2185 # for duplicate heading checking and maybe parsing.
2186 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2187 # We can't deal with anchors, includes, html etc in the header for now,
2188 # headline would need to be parsed to improve this.
2189 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2190 $sectionanchor = $this->guessSectionName( $matches[2] );
2193 $result['sectionanchor'] = $sectionanchor;
2195 // Save errors may fall down to the edit form, but we've now
2196 // merged the section into full text. Clear the section field
2197 // so that later submission of conflict forms won't try to
2198 // replace that into a duplicated mess.
2199 $this->textbox1
= $this->toEditText( $content );
2200 $this->section
= '';
2202 $status->value
= self
::AS_SUCCESS_UPDATE
;
2205 if ( !$this->allowSelfRedirect
2206 && $content->isRedirect()
2207 && $content->getRedirectTarget()->equals( $this->getTitle() )
2209 // If the page already redirects to itself, don't warn.
2210 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2211 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2212 $this->selfRedirect
= true;
2213 $status->fatal( 'selfredirect' );
2214 $status->value
= self
::AS_SELF_REDIRECT
;
2219 // Check for length errors again now that the section is merged in
2220 $this->contentLength
= strlen( $this->toEditText( $content ) );
2221 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2222 $this->tooBig
= true;
2223 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2227 $flags = EDIT_AUTOSUMMARY |
2228 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2229 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2230 ( $bot ? EDIT_FORCE_BOT
: 0 );
2232 $doEditStatus = $this->page
->doEditContent(
2238 $content->getDefaultFormat(),
2243 if ( !$doEditStatus->isOK() ) {
2244 // Failure from doEdit()
2245 // Show the edit conflict page for certain recognized errors from doEdit(),
2246 // but don't show it for errors from extension hooks
2247 $errors = $doEditStatus->getErrorsArray();
2248 if ( in_array( $errors[0][0],
2249 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2251 $this->isConflict
= true;
2252 // Destroys data doEdit() put in $status->value but who cares
2253 $doEditStatus->value
= self
::AS_END
;
2255 return $doEditStatus;
2258 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2259 if ( $result['nullEdit'] ) {
2260 // We don't know if it was a null edit until now, so increment here
2261 $user->pingLimiter( 'linkpurge' );
2263 $result['redirect'] = $content->isRedirect();
2265 $this->updateWatchlist();
2267 // If the content model changed, add a log entry
2268 if ( $changingContentModel ) {
2269 $this->addContentModelChangeLogEntry(
2271 $new ?
false : $oldContentModel,
2272 $this->contentModel
,
2282 * @param string|false $oldModel false if the page is being newly created
2283 * @param string $newModel
2284 * @param string $reason
2286 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2287 $new = $oldModel === false;
2288 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2289 $log->setPerformer( $user );
2290 $log->setTarget( $this->mTitle
);
2291 $log->setComment( $reason );
2292 $log->setParameters( [
2293 '4::oldmodel' => $oldModel,
2294 '5::newmodel' => $newModel
2296 $logid = $log->insert();
2297 $log->publish( $logid );
2301 * Register the change of watch status
2303 protected function updateWatchlist() {
2304 $user = $this->context
->getUser();
2305 if ( !$user->isLoggedIn() ) {
2309 $title = $this->mTitle
;
2310 $watch = $this->watchthis
;
2311 // Do this in its own transaction to reduce contention...
2312 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2313 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2314 return; // nothing to change
2316 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2321 * Attempts to do 3-way merge of edit content with a base revision
2322 * and current content, in case of edit conflict, in whichever way appropriate
2323 * for the content type.
2327 * @param Content $editContent
2331 private function mergeChangesIntoContent( &$editContent ) {
2332 $db = wfGetDB( DB_MASTER
);
2334 // This is the revision that was current at the time editing was initiated on the client,
2335 // even if the edit was based on an old revision.
2336 $baseRevision = $this->getBaseRevision();
2337 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2339 if ( is_null( $baseContent ) ) {
2343 // The current state, we want to merge updates into it
2344 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2345 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2347 if ( is_null( $currentContent ) ) {
2351 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2353 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2356 $editContent = $result;
2357 // Update parentRevId to what we just merged.
2358 $this->parentRevId
= $currentRevision->getId();
2366 * Returns the revision that was current at the time editing was initiated on the client,
2367 * even if the edit was based on an old revision.
2369 * @warning: this method is very poorly named. If the user opened the form with ?oldid=X,
2370 * one might think of X as the "base revision", which is NOT what this returns,
2371 * see oldid for that. One might further assume that this corresponds to the $baseRevId
2372 * parameter of WikiPage::doEditContent, which is not the case either.
2373 * getExpectedParentRevision() would perhaps be a better name.
2375 * @return Revision|null Current version when editing was initiated on the client
2377 public function getBaseRevision() {
2378 if ( !$this->mBaseRevision
) {
2379 $db = wfGetDB( DB_MASTER
);
2380 $this->mBaseRevision
= $this->editRevId
2381 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2382 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2384 return $this->mBaseRevision
;
2388 * Check given input text against $wgSpamRegex, and return the text of the first match.
2390 * @param string $text
2392 * @return string|bool Matching string or false
2394 public static function matchSpamRegex( $text ) {
2395 global $wgSpamRegex;
2396 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2397 $regexes = (array)$wgSpamRegex;
2398 return self
::matchSpamRegexInternal( $text, $regexes );
2402 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2404 * @param string $text
2406 * @return string|bool Matching string or false
2408 public static function matchSummarySpamRegex( $text ) {
2409 global $wgSummarySpamRegex;
2410 $regexes = (array)$wgSummarySpamRegex;
2411 return self
::matchSpamRegexInternal( $text, $regexes );
2415 * @param string $text
2416 * @param array $regexes
2417 * @return bool|string
2419 protected static function matchSpamRegexInternal( $text, $regexes ) {
2420 foreach ( $regexes as $regex ) {
2422 if ( preg_match( $regex, $text, $matches ) ) {
2429 public function setHeaders() {
2430 $out = $this->context
->getOutput();
2432 $out->addModules( 'mediawiki.action.edit' );
2433 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2434 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2436 $user = $this->context
->getUser();
2437 if ( $user->getOption( 'showtoolbar' ) ) {
2438 // The addition of default buttons is handled by getEditToolbar() which
2439 // has its own dependency on this module. The call here ensures the module
2440 // is loaded in time (it has position "top") for other modules to register
2441 // buttons (e.g. extensions, gadgets, user scripts).
2442 $out->addModules( 'mediawiki.toolbar' );
2445 if ( $user->getOption( 'uselivepreview' ) ) {
2446 $out->addModules( 'mediawiki.action.edit.preview' );
2449 if ( $user->getOption( 'useeditwarning' ) ) {
2450 $out->addModules( 'mediawiki.action.edit.editWarning' );
2453 # Enabled article-related sidebar, toplinks, etc.
2454 $out->setArticleRelated( true );
2456 $contextTitle = $this->getContextTitle();
2457 if ( $this->isConflict
) {
2458 $msg = 'editconflict';
2459 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2460 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2462 $msg = $contextTitle->exists()
2463 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2464 && $contextTitle->getDefaultMessageText() !== false
2470 # Use the title defined by DISPLAYTITLE magic word when present
2471 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2472 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2473 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2474 if ( $displayTitle === false ) {
2475 $displayTitle = $contextTitle->getPrefixedText();
2477 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2479 $config = $this->context
->getConfig();
2481 # Transmit the name of the message to JavaScript for live preview
2482 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2483 $out->addJsConfigVars( [
2484 'wgEditMessage' => $msg,
2485 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2488 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2490 $out->addJsConfigVars(
2491 'wgEditSubmitButtonLabelPublish',
2492 $config->get( 'EditSubmitButtonLabelPublish' )
2497 * Show all applicable editing introductions
2499 protected function showIntro() {
2500 if ( $this->suppressIntro
) {
2504 $out = $this->context
->getOutput();
2505 $namespace = $this->mTitle
->getNamespace();
2507 if ( $namespace == NS_MEDIAWIKI
) {
2508 # Show a warning if editing an interface message
2509 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2510 # If this is a default message (but not css, json, or js),
2511 # show a hint that it is translatable on translatewiki.net
2513 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2514 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2515 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2517 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2518 if ( $defaultMessageText !== false ) {
2519 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2520 'translateinterface' );
2523 } elseif ( $namespace == NS_FILE
) {
2524 # Show a hint to shared repo
2525 $file = wfFindFile( $this->mTitle
);
2526 if ( $file && !$file->isLocal() ) {
2527 $descUrl = $file->getDescriptionUrl();
2528 # there must be a description url to show a hint to shared repo
2530 if ( !$this->mTitle
->exists() ) {
2531 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2532 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2535 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2536 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2543 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2544 # Show log extract when the user is currently blocked
2545 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2546 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2547 $user = User
::newFromName( $username, false /* allow IP users */ );
2548 $ip = User
::isIP( $username );
2549 $block = Block
::newFromTarget( $user, $user );
2550 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2551 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2552 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2553 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2554 # Show log extract if the user is currently blocked
2555 LogEventsList
::showLogExtract(
2558 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2562 'showIfEmpty' => false,
2564 'blocked-notice-logextract',
2565 $user->getName() # Support GENDER in notice
2571 # Try to add a custom edit intro, or use the standard one if this is not possible.
2572 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2573 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2574 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2576 if ( $this->context
->getUser()->isLoggedIn() ) {
2578 // Suppress the external link icon, consider the help url an internal one
2579 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2587 // Suppress the external link icon, consider the help url an internal one
2588 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2590 'newarticletextanon',
2596 # Give a notice if the user is editing a deleted/moved page...
2597 if ( !$this->mTitle
->exists() ) {
2598 $dbr = wfGetDB( DB_REPLICA
);
2600 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2604 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2605 'showIfEmpty' => false,
2606 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2613 * Attempt to show a custom editing introduction, if supplied
2617 protected function showCustomIntro() {
2618 if ( $this->editintro
) {
2619 $title = Title
::newFromText( $this->editintro
);
2620 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2621 // Added using template syntax, to take <noinclude>'s into account.
2622 $this->context
->getOutput()->addWikiTextTitleTidy(
2623 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2633 * Gets an editable textual representation of $content.
2634 * The textual representation can be turned by into a Content object by the
2635 * toEditContent() method.
2637 * If $content is null or false or a string, $content is returned unchanged.
2639 * If the given Content object is not of a type that can be edited using
2640 * the text base EditPage, an exception will be raised. Set
2641 * $this->allowNonTextContent to true to allow editing of non-textual
2644 * @param Content|null|bool|string $content
2645 * @return string The editable text form of the content.
2647 * @throws MWException If $content is not an instance of TextContent and
2648 * $this->allowNonTextContent is not true.
2650 protected function toEditText( $content ) {
2651 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2655 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2656 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2659 return $content->serialize( $this->contentFormat
);
2663 * Turns the given text into a Content object by unserializing it.
2665 * If the resulting Content object is not of a type that can be edited using
2666 * the text base EditPage, an exception will be raised. Set
2667 * $this->allowNonTextContent to true to allow editing of non-textual
2670 * @param string|null|bool $text Text to unserialize
2671 * @return Content|bool|null The content object created from $text. If $text was false
2672 * or null, false resp. null will be returned instead.
2674 * @throws MWException If unserializing the text results in a Content
2675 * object that is not an instance of TextContent and
2676 * $this->allowNonTextContent is not true.
2678 protected function toEditContent( $text ) {
2679 if ( $text === false ||
$text === null ) {
2683 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2684 $this->contentModel
, $this->contentFormat
);
2686 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2687 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2694 * Send the edit form and related headers to OutputPage
2695 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2696 * during form output near the top, for captchas and the like.
2698 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2699 * use the EditPage::showEditForm:fields hook instead.
2701 public function showEditForm( $formCallback = null ) {
2702 # need to parse the preview early so that we know which templates are used,
2703 # otherwise users with "show preview after edit box" will get a blank list
2704 # we parse this near the beginning so that setHeaders can do the title
2705 # setting work instead of leaving it in getPreviewText
2706 $previewOutput = '';
2707 if ( $this->formtype
== 'preview' ) {
2708 $previewOutput = $this->getPreviewText();
2711 $out = $this->context
->getOutput();
2713 // Avoid PHP 7.1 warning of passing $this by reference
2715 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2717 $this->setHeaders();
2719 $this->addTalkPageText();
2720 $this->addEditNotices();
2722 if ( !$this->isConflict
&&
2723 $this->section
!= '' &&
2724 !$this->isSectionEditSupported() ) {
2725 // We use $this->section to much before this and getVal('wgSection') directly in other places
2726 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2727 // Someone is welcome to try refactoring though
2728 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2732 $this->showHeader();
2734 $out->addHTML( $this->editFormPageTop
);
2736 $user = $this->context
->getUser();
2737 if ( $user->getOption( 'previewontop' ) ) {
2738 $this->displayPreviewArea( $previewOutput, true );
2741 $out->addHTML( $this->editFormTextTop
);
2743 $showToolbar = true;
2744 if ( $this->wasDeletedSinceLastEdit() ) {
2745 if ( $this->formtype
== 'save' ) {
2746 // Hide the toolbar and edit area, user can click preview to get it back
2747 // Add an confirmation checkbox and explanation.
2748 $showToolbar = false;
2750 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2751 'deletedwhileediting' );
2755 // @todo add EditForm plugin interface and use it here!
2756 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2757 $out->addHTML( Html
::openElement(
2760 'class' => 'mw-editform',
2761 'id' => self
::EDITFORM_ID
,
2762 'name' => self
::EDITFORM_ID
,
2764 'action' => $this->getActionURL( $this->getContextTitle() ),
2765 'enctype' => 'multipart/form-data'
2769 if ( is_callable( $formCallback ) ) {
2770 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2771 call_user_func_array( $formCallback, [ &$out ] );
2774 // Add a check for Unicode support
2775 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2777 // Add an empty field to trip up spambots
2779 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2782 [ 'for' => 'wpAntispam' ],
2783 $this->context
->msg( 'simpleantispam-label' )->parse()
2789 'name' => 'wpAntispam',
2790 'id' => 'wpAntispam',
2794 . Xml
::closeElement( 'div' )
2797 // Avoid PHP 7.1 warning of passing $this by reference
2799 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2801 // Put these up at the top to ensure they aren't lost on early form submission
2802 $this->showFormBeforeText();
2804 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2805 $username = $this->lastDelete
->user_name
;
2806 $comment = CommentStore
::getStore()
2807 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2809 // It is better to not parse the comment at all than to have templates expanded in the middle
2810 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2811 $key = $comment === ''
2812 ?
'confirmrecreate-noreason'
2813 : 'confirmrecreate';
2815 '<div class="mw-confirm-recreate">' .
2816 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2817 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2818 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2824 # When the summary is hidden, also hide them on preview/show changes
2825 if ( $this->nosummary
) {
2826 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2829 # If a blank edit summary was previously provided, and the appropriate
2830 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2831 # user being bounced back more than once in the event that a summary
2834 # For a bit more sophisticated detection of blank summaries, hash the
2835 # automatic one and pass that in the hidden field wpAutoSummary.
2836 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2837 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2840 if ( $this->undidRev
) {
2841 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2844 if ( $this->selfRedirect
) {
2845 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2848 if ( $this->hasPresetSummary
) {
2849 // If a summary has been preset using &summary= we don't want to prompt for
2850 // a different summary. Only prompt for a summary if the summary is blanked.
2852 $this->autoSumm
= md5( '' );
2855 $autosumm = $this->autoSumm ?
: md5( $this->summary
);
2856 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2858 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2859 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2861 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2862 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2866 if ( $this->section
== 'new' ) {
2867 $this->showSummaryInput( true, $this->summary
);
2868 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2871 $out->addHTML( $this->editFormTextBeforeContent
);
2872 if ( $this->isConflict
) {
2873 // In an edit conflict, we turn textbox2 into the user's text,
2874 // and textbox1 into the stored version
2875 $this->textbox2
= $this->textbox1
;
2877 $content = $this->getCurrentContent();
2878 $this->textbox1
= $this->toEditText( $content );
2880 $editConflictHelper = $this->getEditConflictHelper();
2881 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2882 $editConflictHelper->setContentModel( $this->contentModel
);
2883 $editConflictHelper->setContentFormat( $this->contentFormat
);
2884 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2887 if ( !$this->mTitle
->isUserConfigPage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2888 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2891 if ( $this->blankArticle
) {
2892 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2895 if ( $this->isConflict
) {
2896 // In an edit conflict bypass the overridable content form method
2897 // and fallback to the raw wpTextbox1 since editconflicts can't be
2898 // resolved between page source edits and custom ui edits using the
2900 $conflictTextBoxAttribs = [];
2901 if ( $this->wasDeletedSinceLastEdit() ) {
2902 $conflictTextBoxAttribs['style'] = 'display:none;';
2903 } elseif ( $this->isOldRev
) {
2904 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2907 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2908 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2910 $this->showContentForm();
2913 $out->addHTML( $this->editFormTextAfterContent
);
2915 $this->showStandardInputs();
2917 $this->showFormAfterText();
2919 $this->showTosSummary();
2921 $this->showEditTools();
2923 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2925 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2927 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2928 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2930 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2931 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2933 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2935 if ( $this->isConflict
) {
2937 $this->showConflict();
2938 } catch ( MWContentSerializationException
$ex ) {
2939 // this can't really happen, but be nice if it does.
2940 $msg = $this->context
->msg(
2941 'content-failed-to-parse',
2942 $this->contentModel
,
2943 $this->contentFormat
,
2946 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2950 // Set a hidden field so JS knows what edit form mode we are in
2951 if ( $this->isConflict
) {
2953 } elseif ( $this->preview
) {
2955 } elseif ( $this->diff
) {
2960 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2962 // Marker for detecting truncated form data. This must be the last
2963 // parameter sent in order to be of use, so do not move me.
2964 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2965 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2967 if ( !$user->getOption( 'previewontop' ) ) {
2968 $this->displayPreviewArea( $previewOutput, false );
2973 * Wrapper around TemplatesOnThisPageFormatter to make
2974 * a "templates on this page" list.
2976 * @param Title[] $templates
2977 * @return string HTML
2979 public function makeTemplatesOnThisPageList( array $templates ) {
2980 $templateListFormatter = new TemplatesOnThisPageFormatter(
2981 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2984 // preview if preview, else section if section, else false
2986 if ( $this->preview
) {
2988 } elseif ( $this->section
!= '' ) {
2992 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2993 $templateListFormatter->format( $templates, $type )
2998 * Extract the section title from current section text, if any.
3000 * @param string $text
3001 * @return string|bool String or false
3003 public static function extractSectionTitle( $text ) {
3004 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
3005 if ( !empty( $matches[2] ) ) {
3007 return $wgParser->stripSectionName( trim( $matches[2] ) );
3013 protected function showHeader() {
3014 $out = $this->context
->getOutput();
3015 $user = $this->context
->getUser();
3016 if ( $this->isConflict
) {
3017 $this->addExplainConflictHeader( $out );
3018 $this->editRevId
= $this->page
->getLatest();
3020 if ( $this->section
!= '' && $this->section
!= 'new' ) {
3021 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
3022 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
3023 if ( $sectionTitle !== false ) {
3024 $this->summary
= "/* $sectionTitle */ ";
3029 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
3031 if ( $this->missingComment
) {
3032 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3035 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
3037 "<div id='mw-missingsummary'>\n$1\n</div>",
3038 [ 'missingsummary', $buttonLabel ]
3042 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3044 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3045 [ 'missingcommentheader', $buttonLabel ]
3049 if ( $this->blankArticle
) {
3051 "<div id='mw-blankarticle'>\n$1\n</div>",
3052 [ 'blankarticle', $buttonLabel ]
3056 if ( $this->selfRedirect
) {
3058 "<div id='mw-selfredirect'>\n$1\n</div>",
3059 [ 'selfredirect', $buttonLabel ]
3063 if ( $this->hookError
!== '' ) {
3064 $out->addWikiText( $this->hookError
);
3067 if ( $this->section
!= 'new' ) {
3068 $revision = $this->mArticle
->getRevisionFetched();
3070 // Let sysop know that this will make private content public if saved
3072 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3074 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3075 'rev-deleted-text-permission'
3077 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3079 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3080 'rev-deleted-text-view'
3084 if ( !$revision->isCurrent() ) {
3085 $this->mArticle
->setOldSubtitle( $revision->getId() );
3086 $out->addWikiMsg( 'editingold' );
3087 $this->isOldRev
= true;
3089 } elseif ( $this->mTitle
->exists() ) {
3090 // Something went wrong
3092 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3093 [ 'missing-revision', $this->oldid
] );
3098 if ( wfReadOnly() ) {
3100 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3101 [ 'readonlywarning', wfReadOnlyReason() ]
3103 } elseif ( $user->isAnon() ) {
3104 if ( $this->formtype
!= 'preview' ) {
3106 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3107 [ 'anoneditwarning',
3109 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3110 'returnto' => $this->getTitle()->getPrefixedDBkey()
3113 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3114 'returnto' => $this->getTitle()->getPrefixedDBkey()
3119 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3120 'anonpreviewwarning'
3124 if ( $this->mTitle
->isUserConfigPage() ) {
3125 # Check the skin exists
3126 if ( $this->isWrongCaseUserConfigPage() ) {
3128 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3129 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3132 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3133 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3134 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3135 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3137 $warning = $isUserCssConfig
3139 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3141 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3143 if ( $this->formtype
!== 'preview' ) {
3144 $config = $this->context
->getConfig();
3145 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3147 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3148 [ 'usercssyoucanpreview' ]
3150 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3152 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3153 [ 'userjsonyoucanpreview' ]
3155 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3157 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3158 [ 'userjsyoucanpreview' ]
3166 $this->addPageProtectionWarningHeaders();
3168 $this->addLongPageWarningHeader();
3170 # Add header copyright warning
3171 $this->showHeaderCopyrightWarning();
3175 * Helper function for summary input functions, which returns the neccessary
3176 * attributes for the input.
3178 * @param array|null $inputAttrs Array of attrs to use on the input
3181 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3182 $conf = $this->context
->getConfig();
3183 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
3184 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3185 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3186 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
3187 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3188 'id' => 'wpSummary',
3189 'name' => 'wpSummary',
3190 'maxlength' => $oldCommentSchema ?
200 : CommentStore
::COMMENT_CHARACTER_LIMIT
,
3193 'spellcheck' => 'true',
3198 * Builds a standard summary input with a label.
3200 * @param string $summary The value of the summary input
3201 * @param string $labelText The html to place inside the label
3202 * @param array $inputAttrs Array of attrs to use on the input
3204 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3206 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3207 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3208 $this->getSummaryInputAttributes( $inputAttrs )
3211 'title' => Linker
::titleAttrib( 'summary' ),
3212 'accessKey' => Linker
::accesskey( 'summary' ),
3215 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3216 $inputAttrs['inputId'] = $inputAttrs['id'];
3217 $inputAttrs['id'] = 'wpSummaryWidget';
3219 return new OOUI\
FieldLayout(
3220 new OOUI\
TextInputWidget( [
3221 'value' => $summary,
3222 'infusable' => true,
3225 'label' => new OOUI\
HtmlSnippet( $labelText ),
3227 'id' => 'wpSummaryLabel',
3228 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3234 * @param bool $isSubjectPreview True if this is the section subject/title
3235 * up top, or false if this is the comment summary
3236 * down below the textarea
3237 * @param string $summary The text of the summary to display
3239 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3240 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3241 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3242 if ( $isSubjectPreview ) {
3243 if ( $this->nosummary
) {
3247 if ( !$this->mShowSummaryField
) {
3252 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3253 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3256 [ 'class' => $summaryClass ]
3261 * @param bool $isSubjectPreview True if this is the section subject/title
3262 * up top, or false if this is the comment summary
3263 * down below the textarea
3264 * @param string $summary The text of the summary to display
3267 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3268 // avoid spaces in preview, gets always trimmed on save
3269 $summary = trim( $summary );
3270 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3276 if ( $isSubjectPreview ) {
3277 $summary = $this->context
->msg( 'newsectionsummary' )
3278 ->rawParams( $wgParser->stripSectionName( $summary ) )
3279 ->inContentLanguage()->text();
3282 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3284 $summary = $this->context
->msg( $message )->parse()
3285 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3286 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3289 protected function showFormBeforeText() {
3290 $out = $this->context
->getOutput();
3291 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3292 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3293 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3294 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3295 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3298 protected function showFormAfterText() {
3300 * To make it harder for someone to slip a user a page
3301 * which submits an edit form to the wiki without their
3302 * knowledge, a random token is associated with the login
3303 * session. If it's not passed back with the submission,
3304 * we won't save the page, or render user JavaScript and
3307 * For anon editors, who may not have a session, we just
3308 * include the constant suffix to prevent editing from
3309 * broken text-mangling proxies.
3311 $this->context
->getOutput()->addHTML(
3313 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3319 * Subpage overridable method for printing the form for page content editing
3320 * By default this simply outputs wpTextbox1
3321 * Subclasses can override this to provide a custom UI for editing;
3322 * be it a form, or simply wpTextbox1 with a modified content that will be
3323 * reverse modified when extracted from the post data.
3324 * Note that this is basically the inverse for importContentFormData
3326 protected function showContentForm() {
3327 $this->showTextbox1();
3331 * Method to output wpTextbox1
3332 * The $textoverride method can be used by subclasses overriding showContentForm
3333 * to pass back to this method.
3335 * @param array $customAttribs Array of html attributes to use in the textarea
3336 * @param string $textoverride Optional text to override $this->textarea1 with
3338 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3339 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3340 $attribs = [ 'style' => 'display:none;' ];
3342 $builder = new TextboxBuilder();
3343 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3345 # Is an old revision being edited?
3346 if ( $this->isOldRev
) {
3347 $classes[] = 'mw-textarea-oldrev';
3350 $attribs = [ 'tabindex' => 1 ];
3352 if ( is_array( $customAttribs ) ) {
3353 $attribs +
= $customAttribs;
3356 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3360 $textoverride !== null ?
$textoverride : $this->textbox1
,
3366 protected function showTextbox2() {
3367 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3370 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3371 $builder = new TextboxBuilder();
3372 $attribs = $builder->buildTextboxAttribs(
3375 $this->context
->getUser(),
3379 $this->context
->getOutput()->addHTML(
3380 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3384 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3387 $classes[] = 'ontop';
3390 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3392 if ( $this->formtype
!= 'preview' ) {
3393 $attribs['style'] = 'display: none;';
3396 $out = $this->context
->getOutput();
3397 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3399 if ( $this->formtype
== 'preview' ) {
3400 $this->showPreview( $previewOutput );
3402 // Empty content container for LivePreview
3403 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3404 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3405 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3406 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3409 $out->addHTML( '</div>' );
3411 if ( $this->formtype
== 'diff' ) {
3414 } catch ( MWContentSerializationException
$ex ) {
3415 $msg = $this->context
->msg(
3416 'content-failed-to-parse',
3417 $this->contentModel
,
3418 $this->contentFormat
,
3421 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3427 * Append preview output to OutputPage.
3428 * Includes category rendering if this is a category page.
3430 * @param string $text The HTML to be output for the preview.
3432 protected function showPreview( $text ) {
3433 if ( $this->mArticle
instanceof CategoryPage
) {
3434 $this->mArticle
->openShowCategory();
3436 # This hook seems slightly odd here, but makes things more
3437 # consistent for extensions.
3438 $out = $this->context
->getOutput();
3439 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3440 $out->addHTML( $text );
3441 if ( $this->mArticle
instanceof CategoryPage
) {
3442 $this->mArticle
->closeShowCategory();
3447 * Get a diff between the current contents of the edit box and the
3448 * version of the page we're editing from.
3450 * If this is a section edit, we'll replace the section as for final
3451 * save and then make a comparison.
3453 public function showDiff() {
3456 $oldtitlemsg = 'currentrev';
3457 # if message does not exist, show diff against the preloaded default
3458 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3459 $oldtext = $this->mTitle
->getDefaultMessageText();
3460 if ( $oldtext !== false ) {
3461 $oldtitlemsg = 'defaultmessagetext';
3462 $oldContent = $this->toEditContent( $oldtext );
3467 $oldContent = $this->getCurrentContent();
3470 $textboxContent = $this->toEditContent( $this->textbox1
);
3471 if ( $this->editRevId
!== null ) {
3472 $newContent = $this->page
->replaceSectionAtRev(
3473 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3476 $newContent = $this->page
->replaceSectionContent(
3477 $this->section
, $textboxContent, $this->summary
, $this->edittime
3481 if ( $newContent ) {
3482 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3484 $user = $this->context
->getUser();
3485 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
3486 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3489 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3490 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3491 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3493 if ( !$oldContent ) {
3494 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3497 if ( !$newContent ) {
3498 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3501 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3502 $de->setContent( $oldContent, $newContent );
3504 $difftext = $de->getDiff( $oldtitle, $newtitle );
3505 $de->showDiffStyle();
3510 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3514 * Show the header copyright warning.
3516 protected function showHeaderCopyrightWarning() {
3517 $msg = 'editpage-head-copy-warn';
3518 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3519 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3520 'editpage-head-copy-warn' );
3525 * Give a chance for site and per-namespace customizations of
3526 * terms of service summary link that might exist separately
3527 * from the copyright notice.
3529 * This will display between the save button and the edit tools,
3530 * so should remain short!
3532 protected function showTosSummary() {
3533 $msg = 'editpage-tos-summary';
3534 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3535 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3536 $out = $this->context
->getOutput();
3537 $out->addHTML( '<div class="mw-tos-summary">' );
3538 $out->addWikiMsg( $msg );
3539 $out->addHTML( '</div>' );
3544 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3545 * characters not present on most keyboards for copying/pasting.
3547 protected function showEditTools() {
3548 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3549 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3554 * Get the copyright warning
3556 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3559 protected function getCopywarn() {
3560 return self
::getCopyrightWarning( $this->mTitle
);
3564 * Get the copyright warning, by default returns wikitext
3566 * @param Title $title
3567 * @param string $format Output format, valid values are any function of a Message object
3568 * @param Language|string|null $langcode Language code or Language object.
3571 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3572 global $wgRightsText;
3573 if ( $wgRightsText ) {
3574 $copywarnMsg = [ 'copyrightwarning',
3575 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3578 $copywarnMsg = [ 'copyrightwarning2',
3579 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3581 // Allow for site and per-namespace customization of contribution/copyright notice.
3582 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3584 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3586 $msg->inLanguage( $langcode );
3588 return "<div id=\"editpage-copywarn\">\n" .
3589 $msg->$format() . "\n</div>";
3593 * Get the Limit report for page previews
3596 * @param ParserOutput $output ParserOutput object from the parse
3597 * @return string HTML
3599 public static function getPreviewLimitReport( $output ) {
3602 if ( !$output ||
!$output->getLimitReportData() ) {
3606 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3607 wfMessage( 'limitreport-title' )->parseAsBlock()
3610 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3611 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3613 $limitReport .= Html
::openElement( 'table', [
3614 'class' => 'preview-limit-report wikitable'
3616 Html
::openElement( 'tbody' );
3618 foreach ( $output->getLimitReportData() as $key => $value ) {
3619 if ( Hooks
::run( 'ParserLimitReportFormat',
3620 [ $key, &$value, &$limitReport, true, true ]
3622 $keyMsg = wfMessage( $key );
3623 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3624 if ( !$valueMsg->exists() ) {
3625 $valueMsg = new RawMessage( '$1' );
3627 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3628 $limitReport .= Html
::openElement( 'tr' ) .
3629 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3630 Html
::rawElement( 'td', null,
3631 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3633 Html
::closeElement( 'tr' );
3638 $limitReport .= Html
::closeElement( 'tbody' ) .
3639 Html
::closeElement( 'table' ) .
3640 Html
::closeElement( 'div' );
3642 return $limitReport;
3645 protected function showStandardInputs( &$tabindex = 2 ) {
3646 $out = $this->context
->getOutput();
3647 $out->addHTML( "<div class='editOptions'>\n" );
3649 if ( $this->section
!= 'new' ) {
3650 $this->showSummaryInput( false, $this->summary
);
3651 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3654 $checkboxes = $this->getCheckboxesWidget(
3656 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3658 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3660 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3662 // Show copyright warning.
3663 $out->addWikiText( $this->getCopywarn() );
3664 $out->addHTML( $this->editFormTextAfterWarn
);
3666 $out->addHTML( "<div class='editButtons'>\n" );
3667 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3669 $cancel = $this->getCancelLink();
3671 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3672 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3675 $this->context
->msg( 'edithelp' )->text(),
3676 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3679 $this->context
->msg( 'word-separator' )->escaped() .
3680 $this->context
->msg( 'newwindow' )->parse();
3682 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3683 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3684 $out->addHTML( "</div><!-- editButtons -->\n" );
3686 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3688 $out->addHTML( "</div><!-- editOptions -->\n" );
3692 * Show an edit conflict. textbox1 is already shown in showEditForm().
3693 * If you want to use another entry point to this function, be careful.
3695 protected function showConflict() {
3696 $out = $this->context
->getOutput();
3697 // Avoid PHP 7.1 warning of passing $this by reference
3699 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3700 $this->incrementConflictStats();
3702 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3706 protected function incrementConflictStats() {
3707 $this->getEditConflictHelper()->incrementConflictStats();
3713 public function getCancelLink() {
3715 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3716 $cancelParams['oldid'] = $this->oldid
;
3717 } elseif ( $this->getContextTitle()->isRedirect() ) {
3718 $cancelParams['redirect'] = 'no';
3721 return new OOUI\
ButtonWidget( [
3722 'id' => 'mw-editform-cancel',
3723 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3724 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3726 'infusable' => true,
3727 'flags' => 'destructive',
3732 * Returns the URL to use in the form's action attribute.
3733 * This is used by EditPage subclasses when simply customizing the action
3734 * variable in the constructor is not enough. This can be used when the
3735 * EditPage lives inside of a Special page rather than a custom page action.
3737 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3740 protected function getActionURL( Title
$title ) {
3741 return $title->getLocalURL( [ 'action' => $this->action
] );
3745 * Check if a page was deleted while the user was editing it, before submit.
3746 * Note that we rely on the logging table, which hasn't been always there,
3747 * but that doesn't matter, because this only applies to brand new
3751 protected function wasDeletedSinceLastEdit() {
3752 if ( $this->deletedSinceEdit
!== null ) {
3753 return $this->deletedSinceEdit
;
3756 $this->deletedSinceEdit
= false;
3758 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3759 $this->lastDelete
= $this->getLastDelete();
3760 if ( $this->lastDelete
) {
3761 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3762 if ( $deleteTime > $this->starttime
) {
3763 $this->deletedSinceEdit
= true;
3768 return $this->deletedSinceEdit
;
3772 * @return bool|stdClass
3774 protected function getLastDelete() {
3775 $dbr = wfGetDB( DB_REPLICA
);
3776 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3777 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3778 $data = $dbr->selectRow(
3779 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3789 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3791 'log_namespace' => $this->mTitle
->getNamespace(),
3792 'log_title' => $this->mTitle
->getDBkey(),
3793 'log_type' => 'delete',
3794 'log_action' => 'delete',
3797 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3799 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3800 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3802 // Quick paranoid permission checks...
3803 if ( is_object( $data ) ) {
3804 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3805 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3808 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3809 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3810 $data->log_comment_data
= null;
3818 * Get the rendered text for previewing.
3819 * @throws MWException
3822 public function getPreviewText() {
3823 $out = $this->context
->getOutput();
3824 $config = $this->context
->getConfig();
3826 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3827 // Could be an offsite preview attempt. This is very unsafe if
3828 // HTML is enabled, as it could be an attack.
3830 if ( $this->textbox1
!== '' ) {
3831 // Do not put big scary notice, if previewing the empty
3832 // string, which happens when you initially edit
3833 // a category page, due to automatic preview-on-open.
3834 $parsedNote = $out->parse( "<div class='previewnote'>" .
3835 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3836 true, /* interface */true );
3838 $this->incrementEditFailureStats( 'session_loss' );
3845 $content = $this->toEditContent( $this->textbox1
);
3849 'AlternateEditPreview',
3850 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3852 return $previewHTML;
3855 # provide a anchor link to the editform
3856 $continueEditing = '<span class="mw-continue-editing">' .
3857 '[[#' . self
::EDITFORM_ID
. '|' .
3858 $this->context
->getLanguage()->getArrow() . ' ' .
3859 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3860 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3861 if ( $this->mTokenOkExceptSuffix
) {
3862 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3863 $this->incrementEditFailureStats( 'bad_token' );
3865 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3866 $this->incrementEditFailureStats( 'session_loss' );
3868 } elseif ( $this->incompleteForm
) {
3869 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3870 if ( $this->mTriedSave
) {
3871 $this->incrementEditFailureStats( 'incomplete_form' );
3874 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3877 # don't parse non-wikitext pages, show message about preview
3878 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3879 if ( $this->mTitle
->isUserConfigPage() ) {
3881 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3887 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3889 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3892 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3894 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3897 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3899 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3906 # Used messages to make sure grep find them:
3907 # Messages: usercsspreview, userjsonpreview, userjspreview,
3908 # sitecsspreview, sitejsonpreview, sitejspreview
3909 if ( $level && $format ) {
3910 $note = "<div id='mw-{$level}{$format}preview'>" .
3911 $this->context
->msg( "{$level}{$format}preview" )->text() .
3912 ' ' . $continueEditing . "</div>";
3916 # If we're adding a comment, we need to show the
3917 # summary as the headline
3918 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3919 $content = $content->addSectionHeader( $this->summary
);
3922 $hook_args = [ $this, &$content ];
3923 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3925 $parserResult = $this->doPreviewParse( $content );
3926 $parserOutput = $parserResult['parserOutput'];
3927 $previewHTML = $parserResult['html'];
3928 $this->mParserOutput
= $parserOutput;
3929 $out->addParserOutputMetadata( $parserOutput );
3930 if ( $out->userCanPreview() ) {
3931 $out->addContentOverride( $this->getTitle(), $content );
3934 if ( count( $parserOutput->getWarnings() ) ) {
3935 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3938 } catch ( MWContentSerializationException
$ex ) {
3939 $m = $this->context
->msg(
3940 'content-failed-to-parse',
3941 $this->contentModel
,
3942 $this->contentFormat
,
3945 $note .= "\n\n" . $m->parse();
3949 if ( $this->isConflict
) {
3950 $conflict = '<h2 id="mw-previewconflict">'
3951 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3953 $conflict = '<hr />';
3956 $previewhead = "<div class='previewnote'>\n" .
3957 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3958 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3960 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3961 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3962 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3963 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3965 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3968 private function incrementEditFailureStats( $failureType ) {
3969 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3970 $stats->increment( 'edit.failures.' . $failureType );
3974 * Get parser options for a preview
3975 * @return ParserOptions
3977 protected function getPreviewParserOptions() {
3978 $parserOptions = $this->page
->makeParserOptions( $this->context
);
3979 $parserOptions->setIsPreview( true );
3980 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3981 $parserOptions->enableLimitReport();
3982 return $parserOptions;
3986 * Parse the page for a preview. Subclasses may override this class, in order
3987 * to parse with different options, or to otherwise modify the preview HTML.
3989 * @param Content $content The page content
3990 * @return array with keys:
3991 * - parserOutput: The ParserOutput object
3992 * - html: The HTML to be displayed
3994 protected function doPreviewParse( Content
$content ) {
3995 $user = $this->context
->getUser();
3996 $parserOptions = $this->getPreviewParserOptions();
3997 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
3998 $scopedCallback = $parserOptions->setupFakeRevision(
3999 $this->mTitle
, $pstContent, $user );
4000 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
4001 ScopedCallback
::consume( $scopedCallback );
4003 'parserOutput' => $parserOutput,
4004 'html' => $parserOutput->getText( [
4005 'enableSectionEditLinks' => false
4013 public function getTemplates() {
4014 if ( $this->preview ||
$this->section
!= '' ) {
4016 if ( !isset( $this->mParserOutput
) ) {
4019 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
4020 foreach ( array_keys( $template ) as $dbk ) {
4021 $templates[] = Title
::makeTitle( $ns, $dbk );
4026 return $this->mTitle
->getTemplateLinksFrom();
4031 * Shows a bulletin board style toolbar for common editing functions.
4032 * It can be disabled in the user preferences.
4034 * @param Title $title Title object for the page being edited (optional)
4037 public static function getEditToolbar( $title = null ) {
4038 global $wgContLang, $wgOut;
4039 global $wgEnableUploads, $wgForeignFileRepos;
4041 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
4042 $showSignature = true;
4044 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4048 * $toolarray is an array of arrays each of which includes the
4049 * opening tag, the closing tag, optionally a sample text that is
4050 * inserted between the two when no selection is highlighted
4051 * and. The tip text is shown when the user moves the mouse
4054 * Images are defined in ResourceLoaderEditToolbarModule.
4058 'id' => 'mw-editbutton-bold',
4060 'close' => '\'\'\'',
4061 'sample' => wfMessage( 'bold_sample' )->text(),
4062 'tip' => wfMessage( 'bold_tip' )->text(),
4065 'id' => 'mw-editbutton-italic',
4068 'sample' => wfMessage( 'italic_sample' )->text(),
4069 'tip' => wfMessage( 'italic_tip' )->text(),
4072 'id' => 'mw-editbutton-link',
4075 'sample' => wfMessage( 'link_sample' )->text(),
4076 'tip' => wfMessage( 'link_tip' )->text(),
4079 'id' => 'mw-editbutton-extlink',
4082 'sample' => wfMessage( 'extlink_sample' )->text(),
4083 'tip' => wfMessage( 'extlink_tip' )->text(),
4086 'id' => 'mw-editbutton-headline',
4089 'sample' => wfMessage( 'headline_sample' )->text(),
4090 'tip' => wfMessage( 'headline_tip' )->text(),
4092 $imagesAvailable ?
[
4093 'id' => 'mw-editbutton-image',
4094 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4096 'sample' => wfMessage( 'image_sample' )->text(),
4097 'tip' => wfMessage( 'image_tip' )->text(),
4099 $imagesAvailable ?
[
4100 'id' => 'mw-editbutton-media',
4101 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4103 'sample' => wfMessage( 'media_sample' )->text(),
4104 'tip' => wfMessage( 'media_tip' )->text(),
4107 'id' => 'mw-editbutton-nowiki',
4108 'open' => "<nowiki>",
4109 'close' => "</nowiki>",
4110 'sample' => wfMessage( 'nowiki_sample' )->text(),
4111 'tip' => wfMessage( 'nowiki_tip' )->text(),
4114 'id' => 'mw-editbutton-signature',
4115 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4118 'tip' => wfMessage( 'sig_tip' )->text(),
4121 'id' => 'mw-editbutton-hr',
4122 'open' => "\n----\n",
4125 'tip' => wfMessage( 'hr_tip' )->text(),
4129 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4130 foreach ( $toolarray as $tool ) {
4136 // Images are defined in ResourceLoaderEditToolbarModule
4138 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4139 // Older browsers show a "speedtip" type message only for ALT.
4140 // Ideally these should be different, realistically they
4141 // probably don't need to be.
4149 $script .= Xml
::encodeJsCall(
4150 'mw.toolbar.addButton',
4152 ResourceLoader
::inDebugMode()
4158 $toolbar = '<div id="toolbar"></div>';
4160 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4161 // Only add the old toolbar cruft to the page payload if the toolbar has not
4162 // been over-written by a hook caller
4163 $nonce = $wgOut->getCSPNonce();
4164 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script, $nonce ) );
4171 * Return an array of checkbox definitions.
4173 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4175 * Array values are associative arrays with the following keys:
4176 * - 'label-message' (required): message for label text
4177 * - 'id' (required): 'id' attribute for the `<input>`
4178 * - 'default' (required): default checkedness (true or false)
4179 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4180 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4181 * from messages like 'tooltip-foo', 'accesskey-foo'
4182 * - 'label-id' (optional): 'id' attribute for the `<label>`
4183 * - 'legacy-name' (optional): short name for backwards-compatibility
4184 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4185 * where bool indicates the checked status of the checkbox
4188 public function getCheckboxesDefinition( $checked ) {
4191 $user = $this->context
->getUser();
4192 // don't show the minor edit checkbox if it's a new page or section
4193 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4194 $checkboxes['wpMinoredit'] = [
4195 'id' => 'wpMinoredit',
4196 'label-message' => 'minoredit',
4197 // Uses messages: tooltip-minoredit, accesskey-minoredit
4198 'tooltip' => 'minoredit',
4199 'label-id' => 'mw-editpage-minoredit',
4200 'legacy-name' => 'minor',
4201 'default' => $checked['minor'],
4205 if ( $user->isLoggedIn() ) {
4206 $checkboxes['wpWatchthis'] = [
4207 'id' => 'wpWatchthis',
4208 'label-message' => 'watchthis',
4209 // Uses messages: tooltip-watch, accesskey-watch
4210 'tooltip' => 'watch',
4211 'label-id' => 'mw-editpage-watch',
4212 'legacy-name' => 'watch',
4213 'default' => $checked['watch'],
4218 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4224 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4225 * any other added by extensions.
4227 * @param int &$tabindex Current tabindex
4228 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4229 * status of the checkbox
4231 * @return array Associative array of string keys to OOUI\FieldLayout instances
4233 public function getCheckboxesWidget( &$tabindex, $checked ) {
4235 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4237 foreach ( $checkboxesDef as $name => $options ) {
4238 $legacyName = $options['legacy-name'] ??
$name;
4242 if ( isset( $options['tooltip'] ) ) {
4243 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4244 $title = Linker
::titleAttrib( $options['tooltip'] );
4246 if ( isset( $options['title-message'] ) ) {
4247 $title = $this->context
->msg( $options['title-message'] )->text();
4250 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4251 new OOUI\
CheckboxInputWidget( [
4252 'tabIndex' => ++
$tabindex,
4253 'accessKey' => $accesskey,
4254 'id' => $options['id'] . 'Widget',
4255 'inputId' => $options['id'],
4257 'selected' => $options['default'],
4258 'infusable' => true,
4261 'align' => 'inline',
4262 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4264 'id' => $options['label-id'] ??
null,
4273 * Get the message key of the label for the button to save the page
4278 protected function getSubmitButtonLabel() {
4280 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4282 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4283 $newPage = !$this->mTitle
->exists();
4285 if ( $labelAsPublish ) {
4286 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4288 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4291 return $buttonLabelKey;
4295 * Returns an array of html code of the following buttons:
4296 * save, diff and preview
4298 * @param int &$tabindex Current tabindex
4302 public function getEditButtons( &$tabindex ) {
4306 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4308 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4309 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4311 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4313 'tabIndex' => ++
$tabindex,
4314 'id' => 'wpSaveWidget',
4315 'inputId' => 'wpSave',
4316 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4317 'useInputTag' => true,
4318 'flags' => [ 'progressive', 'primary' ],
4319 'label' => $buttonLabel,
4320 'infusable' => true,
4322 // Messages used: tooltip-save, tooltip-publish
4323 'title' => Linker
::titleAttrib( $buttonTooltip ),
4324 // Messages used: accesskey-save, accesskey-publish
4325 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4328 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4329 'name' => 'wpPreview',
4330 'tabIndex' => ++
$tabindex,
4331 'id' => 'wpPreviewWidget',
4332 'inputId' => 'wpPreview',
4333 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4334 'useInputTag' => true,
4335 'label' => $this->context
->msg( 'showpreview' )->text(),
4336 'infusable' => true,
4338 // Message used: tooltip-preview
4339 'title' => Linker
::titleAttrib( 'preview' ),
4340 // Message used: accesskey-preview
4341 'accessKey' => Linker
::accesskey( 'preview' ),
4344 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4346 'tabIndex' => ++
$tabindex,
4347 'id' => 'wpDiffWidget',
4348 'inputId' => 'wpDiff',
4349 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4350 'useInputTag' => true,
4351 'label' => $this->context
->msg( 'showdiff' )->text(),
4352 'infusable' => true,
4354 // Message used: tooltip-diff
4355 'title' => Linker
::titleAttrib( 'diff' ),
4356 // Message used: accesskey-diff
4357 'accessKey' => Linker
::accesskey( 'diff' ),
4360 // Avoid PHP 7.1 warning of passing $this by reference
4362 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4368 * Creates a basic error page which informs the user that
4369 * they have attempted to edit a nonexistent section.
4371 public function noSuchSectionPage() {
4372 $out = $this->context
->getOutput();
4373 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4375 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4377 // Avoid PHP 7.1 warning of passing $this by reference
4379 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4380 $out->addHTML( $res );
4382 $out->returnToMain( false, $this->mTitle
);
4386 * Show "your edit contains spam" page with your diff and text
4388 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4390 public function spamPageWithContent( $match = false ) {
4391 $this->textbox2
= $this->textbox1
;
4393 if ( is_array( $match ) ) {
4394 $match = $this->context
->getLanguage()->listToText( $match );
4396 $out = $this->context
->getOutput();
4397 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4399 $out->addHTML( '<div id="spamprotected">' );
4400 $out->addWikiMsg( 'spamprotectiontext' );
4402 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4404 $out->addHTML( '</div>' );
4406 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4409 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4410 $this->showTextbox2();
4412 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4416 * Filter an input field through a Unicode de-armoring process if it
4417 * came from an old browser with known broken Unicode editing issues.
4419 * @deprecated since 1.30, does nothing
4421 * @param WebRequest $request
4422 * @param string $field
4425 protected function safeUnicodeInput( $request, $field ) {
4426 return rtrim( $request->getText( $field ) );
4430 * Filter an output field through a Unicode armoring process if it is
4431 * going to an old browser with known broken Unicode editing issues.
4433 * @deprecated since 1.30, does nothing
4435 * @param string $text
4438 protected function safeUnicodeOutput( $text ) {
4445 protected function addEditNotices() {
4446 $out = $this->context
->getOutput();
4447 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4448 if ( count( $editNotices ) ) {
4449 $out->addHTML( implode( "\n", $editNotices ) );
4451 $msg = $this->context
->msg( 'editnotice-notext' );
4452 if ( !$msg->isDisabled() ) {
4454 '<div class="mw-editnotice-notext">'
4455 . $msg->parseAsBlock()
4465 protected function addTalkPageText() {
4466 if ( $this->mTitle
->isTalkPage() ) {
4467 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4474 protected function addLongPageWarningHeader() {
4475 if ( $this->contentLength
=== false ) {
4476 $this->contentLength
= strlen( $this->textbox1
);
4479 $out = $this->context
->getOutput();
4480 $lang = $this->context
->getLanguage();
4481 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4482 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4483 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4486 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4487 $lang->formatNum( $maxArticleSize )
4491 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4492 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4495 $lang->formatSize( strlen( $this->textbox1
) ),
4496 strlen( $this->textbox1
)
4506 protected function addPageProtectionWarningHeaders() {
4507 $out = $this->context
->getOutput();
4508 if ( $this->mTitle
->isProtected( 'edit' ) &&
4509 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4511 # Is the title semi-protected?
4512 if ( $this->mTitle
->isSemiProtected() ) {
4513 $noticeMsg = 'semiprotectedpagewarning';
4515 # Then it must be protected based on static groups (regular)
4516 $noticeMsg = 'protectedpagewarning';
4518 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4519 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4521 if ( $this->mTitle
->isCascadeProtected() ) {
4522 # Is this page under cascading protection from some source pages?
4523 /** @var Title[] $cascadeSources */
4524 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4525 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4526 $cascadeSourcesCount = count( $cascadeSources );
4527 if ( $cascadeSourcesCount > 0 ) {
4528 # Explain, and list the titles responsible
4529 foreach ( $cascadeSources as $page ) {
4530 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4533 $notice .= '</div>';
4534 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4536 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4537 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4539 'showIfEmpty' => false,
4540 'msgKey' => [ 'titleprotectedwarning' ],
4541 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4546 * @param OutputPage $out
4549 protected function addExplainConflictHeader( OutputPage
$out ) {
4551 $this->getEditConflictHelper()->getExplainHeader()
4556 * @param string $name
4557 * @param mixed[] $customAttribs
4562 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4563 return ( new TextboxBuilder() )->buildTextboxAttribs(
4564 $name, $customAttribs, $user, $this->mTitle
4569 * @param string $wikitext
4573 protected function addNewLineAtEnd( $wikitext ) {
4574 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4578 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4579 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4580 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4581 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4582 * spread the new style links more efficiently.
4584 * @param string $text
4587 private function guessSectionName( $text ) {
4590 // Detect Microsoft browsers
4591 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4592 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4593 // ...and redirect them to legacy encoding, if available
4594 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4596 // Meanwhile, real browsers get real anchors
4597 return $wgParser->guessSectionNameFromWikiText( $text );
4601 * Set a factory function to create an EditConflictHelper
4603 * @param callable $factory Factory function
4606 public function setEditConflictHelperFactory( callable
$factory ) {
4607 $this->editConflictHelperFactory
= $factory;
4608 $this->editConflictHelper
= null;
4612 * @return TextConflictHelper
4614 private function getEditConflictHelper() {
4615 if ( !$this->editConflictHelper
) {
4616 $this->editConflictHelper
= call_user_func(
4617 $this->editConflictHelperFactory
,
4618 $this->getSubmitButtonLabel()
4622 return $this->editConflictHelper
;
4626 * @param string $submitButtonLabel
4627 * @return TextConflictHelper
4629 private function newTextConflictHelper( $submitButtonLabel ) {
4630 return new TextConflictHelper(
4632 $this->getContext()->getOutput(),
4633 MediaWikiServices
::getInstance()->getStatsdDataFactory(),