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\Logger\LoggerFactory
;
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\ScopedCallback
;
28 * The edit page/HTML interface (split from Article)
29 * The actual database and text munging is still in Article,
30 * but it should get easier to call those from alternate
33 * EditPage cares about two distinct titles:
34 * $this->mContextTitle is the page that forms submit to, links point to,
35 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
36 * page in the database that is actually being edited. These are
37 * usually the same, but they are now allowed to be different.
39 * Surgeon General's Warning: prolonged exposure to this class is known to cause
40 * headaches, which may be fatal.
44 * Used for Unicode support checks
46 const UNICODE_CHECK
= 'β³π²β₯πππΎπΈβ΄πΉβ―';
49 * Status: Article successfully updated
51 const AS_SUCCESS_UPDATE
= 200;
54 * Status: Article successfully created
56 const AS_SUCCESS_NEW_ARTICLE
= 201;
59 * Status: Article update aborted by a hook function
61 const AS_HOOK_ERROR
= 210;
64 * Status: A hook function returned an error
66 const AS_HOOK_ERROR_EXPECTED
= 212;
69 * Status: User is blocked from editing this page
71 const AS_BLOCKED_PAGE_FOR_USER
= 215;
74 * Status: Content too big (> $wgMaxArticleSize)
76 const AS_CONTENT_TOO_BIG
= 216;
79 * Status: this anonymous user is not allowed to edit this page
81 const AS_READ_ONLY_PAGE_ANON
= 218;
84 * Status: this logged in user is not allowed to edit this page
86 const AS_READ_ONLY_PAGE_LOGGED
= 219;
89 * Status: wiki is in readonly mode (wfReadOnly() == true)
91 const AS_READ_ONLY_PAGE
= 220;
94 * Status: rate limiter for action 'edit' was tripped
96 const AS_RATE_LIMITED
= 221;
99 * Status: article was deleted while editing and param wpRecreate == false or form
102 const AS_ARTICLE_WAS_DELETED
= 222;
105 * Status: user tried to create this page, but is not allowed to do that
106 * ( Title->userCan('create') == false )
108 const AS_NO_CREATE_PERMISSION
= 223;
111 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
113 const AS_BLANK_ARTICLE
= 224;
116 * Status: (non-resolvable) edit conflict
118 const AS_CONFLICT_DETECTED
= 225;
121 * Status: no edit summary given and the user has forceeditsummary set and the user is not
122 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
124 const AS_SUMMARY_NEEDED
= 226;
127 * Status: user tried to create a new section without content
129 const AS_TEXTBOX_EMPTY
= 228;
132 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
134 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
137 * Status: WikiPage::doEdit() was unsuccessful
142 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
144 const AS_SPAM_ERROR
= 232;
147 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
149 const AS_IMAGE_REDIRECT_ANON
= 233;
152 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
154 const AS_IMAGE_REDIRECT_LOGGED
= 234;
157 * Status: user tried to modify the content model, but is not allowed to do that
158 * ( User::isAllowed('editcontentmodel') == false )
160 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
163 * Status: user tried to create self-redirect (redirect to the same article) and
164 * wpIgnoreSelfRedirect == false
166 const AS_SELF_REDIRECT
= 236;
169 * Status: an error relating to change tagging. Look at the message key for
172 const AS_CHANGE_TAG_ERROR
= 237;
175 * Status: can't parse content
177 const AS_PARSE_ERROR
= 240;
180 * Status: when changing the content model is disallowed due to
181 * $wgContentHandlerUseDB being false
183 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
186 * Status: edit rejected because browser doesn't support Unicode.
188 const AS_UNICODE_NOT_SUPPORTED
= 242;
191 * HTML id and name for the beginning of the edit form.
193 const EDITFORM_ID
= 'editform';
196 * Prefix of key for cookie used to pass post-edit state.
197 * The revision id edited is added after this
199 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
202 * Duration of PostEdit cookie, in seconds.
203 * The cookie will be removed instantly if the JavaScript runs.
205 * Otherwise, though, we don't want the cookies to accumulate.
206 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
207 * limit of only 20 cookies per domain. This still applies at least to some
208 * versions of IE without full updates:
209 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
211 * A value of 20 minutes should be enough to take into account slow loads and minor
212 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
214 const POST_EDIT_COOKIE_DURATION
= 1200;
217 * @deprecated for public usage since 1.30 use EditPage::getArticle()
225 * @deprecated for public usage since 1.30 use EditPage::getTitle()
230 /** @var null|Title */
231 private $mContextTitle = null;
234 public $action = 'submit';
237 public $isConflict = false;
240 * @deprecated since 1.30 use Title::isCssJsSubpage()
243 public $isCssJsSubpage = false;
246 * @deprecated since 1.30 use Title::isCssSubpage()
249 public $isCssSubpage = false;
252 * @deprecated since 1.30 use Title::isJsSubpage()
255 public $isJsSubpage = false;
258 * @deprecated since 1.30
261 public $isWrongCaseCssJsPage = false;
263 /** @var bool New page or new section */
264 public $isNew = false;
267 public $deletedSinceEdit;
275 /** @var bool|stdClass */
279 public $mTokenOk = false;
282 public $mTokenOkExceptSuffix = false;
285 public $mTriedSave = false;
288 public $incompleteForm = false;
291 public $tooBig = false;
294 public $missingComment = false;
297 public $missingSummary = false;
300 public $allowBlankSummary = false;
303 protected $blankArticle = false;
306 protected $allowBlankArticle = false;
309 protected $selfRedirect = false;
312 protected $allowSelfRedirect = false;
315 public $autoSumm = '';
318 public $hookError = '';
320 /** @var ParserOutput */
321 public $mParserOutput;
323 /** @var bool Has a summary been preset using GET parameter &summary= ? */
324 public $hasPresetSummary = false;
326 /** @var Revision|bool */
327 public $mBaseRevision = false;
330 public $mShowSummaryField = true;
335 public $save = false;
338 public $preview = false;
341 public $diff = false;
344 public $minoredit = false;
347 public $watchthis = false;
350 public $recreate = false;
353 public $textbox1 = '';
356 public $textbox2 = '';
359 public $summary = '';
362 public $nosummary = false;
365 public $edittime = '';
368 private $editRevId = null;
371 public $section = '';
374 public $sectiontitle = '';
377 public $starttime = '';
383 public $parentRevId = 0;
386 public $editintro = '';
389 public $scrolltop = null;
395 public $contentModel;
397 /** @var null|string */
398 public $contentFormat = null;
400 /** @var null|array */
401 private $changeTags = null;
403 # Placeholders for text injection by hooks (must be HTML)
404 # extensions should take care to _append_ to the present value
406 /** @var string Before even the preview */
407 public $editFormPageTop = '';
408 public $editFormTextTop = '';
409 public $editFormTextBeforeContent = '';
410 public $editFormTextAfterWarn = '';
411 public $editFormTextAfterTools = '';
412 public $editFormTextBottom = '';
413 public $editFormTextAfterContent = '';
414 public $previewTextAfterContent = '';
415 public $mPreloadContent = null;
417 /* $didSave should be set to true whenever an article was successfully altered. */
418 public $didSave = false;
419 public $undidRev = 0;
421 public $suppressIntro = false;
427 protected $contentLength = false;
430 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
432 private $enableApiEditOverride = false;
435 * @var IContextSource
440 * @var bool Whether an old revision is edited
442 private $isOldRev = false;
445 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
447 private $unicodeCheck;
450 * @param Article $article
452 public function __construct( Article
$article ) {
453 $this->mArticle
= $article;
454 $this->page
= $article->getPage(); // model object
455 $this->mTitle
= $article->getTitle();
456 $this->context
= $article->getContext();
458 $this->contentModel
= $this->mTitle
->getContentModel();
460 $handler = ContentHandler
::getForModelID( $this->contentModel
);
461 $this->contentFormat
= $handler->getDefaultFormat();
467 public function getArticle() {
468 return $this->mArticle
;
473 * @return IContextSource
475 public function getContext() {
476 return $this->context
;
483 public function getTitle() {
484 return $this->mTitle
;
488 * Set the context Title object
490 * @param Title|null $title Title object or null
492 public function setContextTitle( $title ) {
493 $this->mContextTitle
= $title;
497 * Get the context title object.
498 * If not set, $wgTitle will be returned. This behavior might change in
499 * the future to return $this->mTitle instead.
503 public function getContextTitle() {
504 if ( is_null( $this->mContextTitle
) ) {
507 __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.'
512 return $this->mContextTitle
;
517 * Check if the edit page is using OOUI controls
518 * @return bool Always true
519 * @deprecated since 1.30
521 public function isOouiEnabled() {
522 wfDeprecated( __METHOD__
, '1.30' );
527 * Returns if the given content model is editable.
529 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
531 * @throws MWException If $modelId has no known handler
533 public function isSupportedContentModel( $modelId ) {
534 return $this->enableApiEditOverride
=== true ||
535 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
539 * Allow editing of content that supports API direct editing, but not general
540 * direct editing. Set to false by default.
542 * @param bool $enableOverride
544 public function setApiEditOverride( $enableOverride ) {
545 $this->enableApiEditOverride
= $enableOverride;
549 * @deprecated since 1.29, call edit directly
551 public function submit() {
552 wfDeprecated( __METHOD__
, '1.29' );
557 * This is the function that gets called for "action=edit". It
558 * sets up various member variables, then passes execution to
559 * another function, usually showEditForm()
561 * The edit form is self-submitting, so that when things like
562 * preview and edit conflicts occur, we get the same form back
563 * with the extra stuff added. Only when the final submission
564 * is made and all is well do we actually save and redirect to
565 * the newly-edited page.
567 public function edit() {
568 // Allow extensions to modify/prevent this form or submission
569 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
573 wfDebug( __METHOD__
. ": enter\n" );
575 $request = $this->context
->getRequest();
576 // If they used redlink=1 and the page exists, redirect to the main article
577 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
578 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
582 $this->importFormData( $request );
583 $this->firsttime
= false;
585 if ( wfReadOnly() && $this->save
) {
588 $this->preview
= true;
592 $this->formtype
= 'save';
593 } elseif ( $this->preview
) {
594 $this->formtype
= 'preview';
595 } elseif ( $this->diff
) {
596 $this->formtype
= 'diff';
597 } else { # First time through
598 $this->firsttime
= true;
599 if ( $this->previewOnOpen() ) {
600 $this->formtype
= 'preview';
602 $this->formtype
= 'initial';
606 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
608 wfDebug( __METHOD__
. ": User can't edit\n" );
609 // Auto-block user's IP if the account was "hard" blocked
610 if ( !wfReadOnly() ) {
611 DeferredUpdates
::addCallableUpdate( function () {
612 $this->context
->getUser()->spreadAnyEditBlock();
615 $this->displayPermissionsError( $permErrors );
620 $revision = $this->mArticle
->getRevisionFetched();
621 // Disallow editing revisions with content models different from the current one
622 // Undo edits being an exception in order to allow reverting content model changes.
624 && $revision->getContentModel() !== $this->contentModel
627 if ( $this->undidRev
) {
628 $undidRevObj = Revision
::newFromId( $this->undidRev
);
629 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
631 if ( !$this->undidRev
633 ||
$prevRev->getContentModel() !== $this->contentModel
635 $this->displayViewSourcePage(
636 $this->getContentObject(),
638 'contentmodelediterror',
639 $revision->getContentModel(),
647 $this->isConflict
= false;
648 // css / js subpages of user pages get a special treatment
649 // The following member variables are deprecated since 1.30,
650 // the functions should be used instead.
651 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
652 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
653 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
654 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
656 # Show applicable editing introductions
657 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
661 # Attempt submission here. This will check for edit conflicts,
662 # and redundantly check for locked database, blocked IPs, etc.
663 # that edit() already checked just in case someone tries to sneak
664 # in the back door with a hand-edited submission URL.
666 if ( 'save' == $this->formtype
) {
667 $resultDetails = null;
668 $status = $this->attemptSave( $resultDetails );
669 if ( !$this->handleStatus( $status, $resultDetails ) ) {
674 # First time through: get contents, set time for conflict
676 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
677 if ( $this->initialiseForm() === false ) {
678 $this->noSuchSectionPage();
682 if ( !$this->mTitle
->getArticleID() ) {
683 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
685 Hooks
::run( 'EditFormInitialText', [ $this ] );
690 $this->showEditForm();
694 * @param string $rigor Same format as Title::getUserPermissionErrors()
697 protected function getEditPermissionErrors( $rigor = 'secure' ) {
698 $user = $this->context
->getUser();
699 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
700 # Can this title be created?
701 if ( !$this->mTitle
->exists() ) {
702 $permErrors = array_merge(
705 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
710 # Ignore some permissions errors when a user is just previewing/viewing diffs
712 foreach ( $permErrors as $error ) {
713 if ( ( $this->preview ||
$this->diff
)
715 $error[0] == 'blockedtext' ||
716 $error[0] == 'autoblockedtext' ||
717 $error[0] == 'systemblockedtext'
723 $permErrors = wfArrayDiff2( $permErrors, $remove );
729 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
730 * but with the following differences:
731 * - If redlink=1, the user will be redirected to the page
732 * - If there is content to display or the error occurs while either saving,
733 * previewing or showing the difference, it will be a
734 * "View source for ..." page displaying the source code after the error message.
737 * @param array $permErrors Array of permissions errors, as returned by
738 * Title::getUserPermissionsErrors().
739 * @throws PermissionsError
741 protected function displayPermissionsError( array $permErrors ) {
742 $out = $this->context
->getOutput();
743 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
744 // The edit page was reached via a red link.
745 // Redirect to the article page and let them click the edit tab if
746 // they really want a permission error.
747 $out->redirect( $this->mTitle
->getFullURL() );
751 $content = $this->getContentObject();
753 # Use the normal message if there's nothing to display
754 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
755 $action = $this->mTitle
->exists() ?
'edit' :
756 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
757 throw new PermissionsError( $action, $permErrors );
760 $this->displayViewSourcePage(
762 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
767 * Display a read-only View Source page
768 * @param Content $content content object
769 * @param string $errorMessage additional wikitext error message to display
771 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
772 $out = $this->context
->getOutput();
773 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
775 $out->setRobotPolicy( 'noindex,nofollow' );
776 $out->setPageTitle( $this->context
->msg(
778 $this->getContextTitle()->getPrefixedText()
780 $out->addBacklinkSubtitle( $this->getContextTitle() );
781 $out->addHTML( $this->editFormPageTop
);
782 $out->addHTML( $this->editFormTextTop
);
784 if ( $errorMessage !== '' ) {
785 $out->addWikiText( $errorMessage );
786 $out->addHTML( "<hr />\n" );
789 # If the user made changes, preserve them when showing the markup
790 # (This happens when a user is blocked during edit, for instance)
791 if ( !$this->firsttime
) {
792 $text = $this->textbox1
;
793 $out->addWikiMsg( 'viewyourtext' );
796 $text = $this->toEditText( $content );
797 } catch ( MWException
$e ) {
798 # Serialize using the default format if the content model is not supported
799 # (e.g. for an old revision with a different model)
800 $text = $content->serialize();
802 $out->addWikiMsg( 'viewsourcetext' );
805 $out->addHTML( $this->editFormTextBeforeContent
);
806 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
807 $out->addHTML( $this->editFormTextAfterContent
);
809 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
811 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
813 $out->addHTML( $this->editFormTextBottom
);
814 if ( $this->mTitle
->exists() ) {
815 $out->returnToMain( null, $this->mTitle
);
820 * Should we show a preview when the edit form is first shown?
824 protected function previewOnOpen() {
825 $previewOnOpenNamespaces = $this->context
->getConfig()->get( 'PreviewOnOpenNamespaces' );
826 $request = $this->context
->getRequest();
827 if ( $request->getVal( 'preview' ) == 'yes' ) {
828 // Explicit override from request
830 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
831 // Explicit override from request
833 } elseif ( $this->section
== 'new' ) {
834 // Nothing *to* preview for new sections
836 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
837 && $this->context
->getUser()->getOption( 'previewonfirst' )
839 // Standard preference behavior
841 } elseif ( !$this->mTitle
->exists()
842 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
843 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
845 // Categories are special
853 * Checks whether the user entered a skin name in uppercase,
854 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
858 protected function isWrongCaseCssJsPage() {
859 if ( $this->mTitle
->isCssJsSubpage() ) {
860 $name = $this->mTitle
->getSkinFromCssJsSubpage();
861 $skins = array_merge(
862 array_keys( Skin
::getSkinNames() ),
865 return !in_array( $name, $skins )
866 && in_array( strtolower( $name ), $skins );
873 * Returns whether section editing is supported for the current page.
874 * Subclasses may override this to replace the default behavior, which is
875 * to check ContentHandler::supportsSections.
877 * @return bool True if this edit page supports sections, false otherwise.
879 protected function isSectionEditSupported() {
880 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
881 return $contentHandler->supportsSections();
885 * This function collects the form data and uses it to populate various member variables.
886 * @param WebRequest &$request
887 * @throws ErrorPageError
889 public function importFormData( &$request ) {
890 # Section edit can come from either the form or a link
891 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
893 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
894 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
897 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
899 if ( $request->wasPosted() ) {
900 # These fields need to be checked for encoding.
901 # Also remove trailing whitespace, but don't remove _initial_
902 # whitespace from the text boxes. This may be significant formatting.
903 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
904 if ( !$request->getCheck( 'wpTextbox2' ) ) {
905 // Skip this if wpTextbox2 has input, it indicates that we came
906 // from a conflict page with raw page text, not a custom form
907 // modified by subclasses
908 $textbox1 = $this->importContentFormData( $request );
909 if ( $textbox1 !== null ) {
910 $this->textbox1
= $textbox1;
914 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
916 $this->summary
= $request->getText( 'wpSummary' );
918 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
919 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
921 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
923 # Treat sectiontitle the same way as summary.
924 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
925 # currently doing double duty as both edit summary and section title. Right now this
926 # is just to allow API edits to work around this limitation, but this should be
927 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
928 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
929 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
931 $this->edittime
= $request->getVal( 'wpEdittime' );
932 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
933 $this->starttime
= $request->getVal( 'wpStarttime' );
935 $undidRev = $request->getInt( 'wpUndidRevision' );
937 $this->undidRev
= $undidRev;
940 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
942 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
943 // wpTextbox1 field is missing, possibly due to being "too big"
944 // according to some filter rules such as Suhosin's setting for
945 // suhosin.request.max_value_length (d'oh)
946 $this->incompleteForm
= true;
948 // If we receive the last parameter of the request, we can fairly
949 // claim the POST request has not been truncated.
951 // TODO: softened the check for cutover. Once we determine
952 // that it is safe, we should complete the transition by
953 // removing the "edittime" clause.
954 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
955 && is_null( $this->edittime
) );
957 if ( $this->incompleteForm
) {
958 # If the form is incomplete, force to preview.
959 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
960 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
961 $this->preview
= true;
963 $this->preview
= $request->getCheck( 'wpPreview' );
964 $this->diff
= $request->getCheck( 'wpDiff' );
966 // Remember whether a save was requested, so we can indicate
967 // if we forced preview due to session failure.
968 $this->mTriedSave
= !$this->preview
;
970 if ( $this->tokenOk( $request ) ) {
971 # Some browsers will not report any submit button
972 # if the user hits enter in the comment box.
973 # The unmarked state will be assumed to be a save,
974 # if the form seems otherwise complete.
975 wfDebug( __METHOD__
. ": Passed token check.\n" );
976 } elseif ( $this->diff
) {
977 # Failed token check, but only requested "Show Changes".
978 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
980 # Page might be a hack attempt posted from
981 # an external site. Preview instead of saving.
982 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
983 $this->preview
= true;
986 $this->save
= !$this->preview
&& !$this->diff
;
987 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
988 $this->edittime
= null;
991 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
992 $this->starttime
= null;
995 $this->recreate
= $request->getCheck( 'wpRecreate' );
997 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
998 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
1000 $user = $this->context
->getUser();
1001 # Don't force edit summaries when a user is editing their own user or talk page
1002 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
1003 && $this->mTitle
->getText() == $user->getName()
1005 $this->allowBlankSummary
= true;
1007 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1008 ||
!$user->getOption( 'forceeditsummary' );
1011 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1013 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1014 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1016 $changeTags = $request->getVal( 'wpChangeTags' );
1017 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1018 $this->changeTags
= [];
1020 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1024 # Not a posted form? Start with nothing.
1025 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1026 $this->textbox1
= '';
1027 $this->summary
= '';
1028 $this->sectiontitle
= '';
1029 $this->edittime
= '';
1030 $this->editRevId
= null;
1031 $this->starttime
= wfTimestampNow();
1032 $this->edit
= false;
1033 $this->preview
= false;
1034 $this->save
= false;
1035 $this->diff
= false;
1036 $this->minoredit
= false;
1037 // Watch may be overridden by request parameters
1038 $this->watchthis
= $request->getBool( 'watchthis', false );
1039 $this->recreate
= false;
1041 // When creating a new section, we can preload a section title by passing it as the
1042 // preloadtitle parameter in the URL (T15100)
1043 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1044 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1045 // Once wpSummary isn't being use for setting section titles, we should delete this.
1046 $this->summary
= $request->getVal( 'preloadtitle' );
1047 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1048 $this->summary
= $request->getText( 'summary' );
1049 if ( $this->summary
!== '' ) {
1050 $this->hasPresetSummary
= true;
1054 if ( $request->getVal( 'minor' ) ) {
1055 $this->minoredit
= true;
1059 $this->oldid
= $request->getInt( 'oldid' );
1060 $this->parentRevId
= $request->getInt( 'parentRevId' );
1062 $this->bot
= $request->getBool( 'bot', true );
1063 $this->nosummary
= $request->getBool( 'nosummary' );
1065 // May be overridden by revision.
1066 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1067 // May be overridden by revision.
1068 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1071 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1072 } catch ( MWUnknownContentModelException
$e ) {
1073 throw new ErrorPageError(
1074 'editpage-invalidcontentmodel-title',
1075 'editpage-invalidcontentmodel-text',
1076 [ wfEscapeWikiText( $this->contentModel
) ]
1080 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1081 throw new ErrorPageError(
1082 'editpage-notsupportedcontentformat-title',
1083 'editpage-notsupportedcontentformat-text',
1085 wfEscapeWikiText( $this->contentFormat
),
1086 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1092 * @todo Check if the desired model is allowed in this namespace, and if
1093 * a transition from the page's current model to the new model is
1097 $this->editintro
= $request->getText( 'editintro',
1098 // Custom edit intro for new sections
1099 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1101 // Allow extensions to modify form data
1102 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1106 * Subpage overridable method for extracting the page content data from the
1107 * posted form to be placed in $this->textbox1, if using customized input
1108 * this method should be overridden and return the page text that will be used
1109 * for saving, preview parsing and so on...
1111 * @param WebRequest &$request
1112 * @return string|null
1114 protected function importContentFormData( &$request ) {
1115 return; // Don't do anything, EditPage already extracted wpTextbox1
1119 * Initialise form fields in the object
1120 * Called on the first invocation, e.g. when a user clicks an edit link
1121 * @return bool If the requested section is valid
1123 public function initialiseForm() {
1124 $this->edittime
= $this->page
->getTimestamp();
1125 $this->editRevId
= $this->page
->getLatest();
1127 $content = $this->getContentObject( false ); # TODO: track content object?!
1128 if ( $content === false ) {
1131 $this->textbox1
= $this->toEditText( $content );
1133 $user = $this->context
->getUser();
1134 // activate checkboxes if user wants them to be always active
1135 # Sort out the "watch" checkbox
1136 if ( $user->getOption( 'watchdefault' ) ) {
1138 $this->watchthis
= true;
1139 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1141 $this->watchthis
= true;
1142 } elseif ( $user->isWatched( $this->mTitle
) ) {
1144 $this->watchthis
= true;
1146 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1147 $this->minoredit
= true;
1149 if ( $this->textbox1
=== false ) {
1156 * @param Content|null $def_content The default value to return
1158 * @return Content|null Content on success, $def_content for invalid sections
1162 protected function getContentObject( $def_content = null ) {
1167 $user = $this->context
->getUser();
1168 $request = $this->context
->getRequest();
1169 // For message page not locally set, use the i18n message.
1170 // For other non-existent articles, use preload text if any.
1171 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1172 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1173 # If this is a system message, get the default text.
1174 $msg = $this->mTitle
->getDefaultMessageText();
1176 $content = $this->toEditContent( $msg );
1178 if ( $content === false ) {
1179 # If requested, preload some text.
1180 $preload = $request->getVal( 'preload',
1181 // Custom preload text for new sections
1182 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1183 $params = $request->getArray( 'preloadparams', [] );
1185 $content = $this->getPreloadedContent( $preload, $params );
1187 // For existing pages, get text based on "undo" or section parameters.
1189 if ( $this->section
!= '' ) {
1190 // Get section edit text (returns $def_text for invalid sections)
1191 $orig = $this->getOriginalContent( $user );
1192 $content = $orig ?
$orig->getSection( $this->section
) : null;
1195 $content = $def_content;
1198 $undoafter = $request->getInt( 'undoafter' );
1199 $undo = $request->getInt( 'undo' );
1201 if ( $undo > 0 && $undoafter > 0 ) {
1202 $undorev = Revision
::newFromId( $undo );
1203 $oldrev = Revision
::newFromId( $undoafter );
1205 # Sanity check, make sure it's the right page,
1206 # the revisions exist and they were not deleted.
1207 # Otherwise, $content will be left as-is.
1208 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1209 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1210 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1212 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1214 if ( $content === false ) {
1215 # Warn the user that something went wrong
1216 $undoMsg = 'failure';
1218 $oldContent = $this->page
->getContent( Revision
::RAW
);
1219 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1220 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1221 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1222 // The undo may change content
1223 // model if its reverting the top
1224 // edit. This can result in
1225 // mismatched content model/format.
1226 $this->contentModel
= $newContent->getModel();
1227 $this->contentFormat
= $oldrev->getContentFormat();
1230 if ( $newContent->equals( $oldContent ) ) {
1231 # Tell the user that the undo results in no change,
1232 # i.e. the revisions were already undone.
1233 $undoMsg = 'nochange';
1236 # Inform the user of our success and set an automatic edit summary
1237 $undoMsg = 'success';
1239 # If we just undid one rev, use an autosummary
1240 $firstrev = $oldrev->getNext();
1241 if ( $firstrev && $firstrev->getId() == $undo ) {
1242 $userText = $undorev->getUserText();
1243 if ( $userText === '' ) {
1244 $undoSummary = $this->context
->msg(
1245 'undo-summary-username-hidden',
1247 )->inContentLanguage()->text();
1249 $undoSummary = $this->context
->msg(
1253 )->inContentLanguage()->text();
1255 if ( $this->summary
=== '' ) {
1256 $this->summary
= $undoSummary;
1258 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1259 ->inContentLanguage()->text() . $this->summary
;
1261 $this->undidRev
= $undo;
1263 $this->formtype
= 'diff';
1267 // Failed basic sanity checks.
1268 // Older revisions may have been removed since the link
1269 // was created, or we may simply have got bogus input.
1273 $out = $this->context
->getOutput();
1274 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1275 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1276 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1277 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1280 if ( $content === false ) {
1281 $content = $this->getOriginalContent( $user );
1290 * Get the content of the wanted revision, without section extraction.
1292 * The result of this function can be used to compare user's input with
1293 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1294 * to the original text of the edit.
1296 * This differs from Article::getContent() that when a missing revision is
1297 * encountered the result will be null and not the
1298 * 'missing-revision' message.
1301 * @param User $user The user to get the revision for
1302 * @return Content|null
1304 private function getOriginalContent( User
$user ) {
1305 if ( $this->section
== 'new' ) {
1306 return $this->getCurrentContent();
1308 $revision = $this->mArticle
->getRevisionFetched();
1309 if ( $revision === null ) {
1310 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1311 return $handler->makeEmptyContent();
1313 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1318 * Get the edit's parent revision ID
1320 * The "parent" revision is the ancestor that should be recorded in this
1321 * page's revision history. It is either the revision ID of the in-memory
1322 * article content, or in the case of a 3-way merge in order to rebase
1323 * across a recoverable edit conflict, the ID of the newer revision to
1324 * which we have rebased this page.
1327 * @return int Revision ID
1329 public function getParentRevId() {
1330 if ( $this->parentRevId
) {
1331 return $this->parentRevId
;
1333 return $this->mArticle
->getRevIdFetched();
1338 * Get the current content of the page. This is basically similar to
1339 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1340 * content object is returned instead of null.
1345 protected function getCurrentContent() {
1346 $rev = $this->page
->getRevision();
1347 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1349 if ( $content === false ||
$content === null ) {
1350 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1351 return $handler->makeEmptyContent();
1352 } elseif ( !$this->undidRev
) {
1353 // Content models should always be the same since we error
1354 // out if they are different before this point (in ->edit()).
1355 // The exception being, during an undo, the current revision might
1356 // differ from the prior revision.
1357 $logger = LoggerFactory
::getInstance( 'editpage' );
1358 if ( $this->contentModel
!== $rev->getContentModel() ) {
1359 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1360 'prev' => $this->contentModel
,
1361 'new' => $rev->getContentModel(),
1362 'title' => $this->getTitle()->getPrefixedDBkey(),
1363 'method' => __METHOD__
1365 $this->contentModel
= $rev->getContentModel();
1368 // Given that the content models should match, the current selected
1369 // format should be supported.
1370 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1371 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1373 'prev' => $this->contentFormat
,
1374 'new' => $rev->getContentFormat(),
1375 'title' => $this->getTitle()->getPrefixedDBkey(),
1376 'method' => __METHOD__
1378 $this->contentFormat
= $rev->getContentFormat();
1385 * Use this method before edit() to preload some content into the edit box
1387 * @param Content $content
1391 public function setPreloadedContent( Content
$content ) {
1392 $this->mPreloadContent
= $content;
1396 * Get the contents to be preloaded into the box, either set by
1397 * an earlier setPreloadText() or by loading the given page.
1399 * @param string $preload Representing the title to preload from.
1400 * @param array $params Parameters to use (interface-message style) in the preloaded text
1406 protected function getPreloadedContent( $preload, $params = [] ) {
1407 if ( !empty( $this->mPreloadContent
) ) {
1408 return $this->mPreloadContent
;
1411 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1413 if ( $preload === '' ) {
1414 return $handler->makeEmptyContent();
1417 $user = $this->context
->getUser();
1418 $title = Title
::newFromText( $preload );
1419 # Check for existence to avoid getting MediaWiki:Noarticletext
1420 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1421 // TODO: somehow show a warning to the user!
1422 return $handler->makeEmptyContent();
1425 $page = WikiPage
::factory( $title );
1426 if ( $page->isRedirect() ) {
1427 $title = $page->getRedirectTarget();
1429 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1430 // TODO: somehow show a warning to the user!
1431 return $handler->makeEmptyContent();
1433 $page = WikiPage
::factory( $title );
1436 $parserOptions = ParserOptions
::newFromUser( $user );
1437 $content = $page->getContent( Revision
::RAW
);
1440 // TODO: somehow show a warning to the user!
1441 return $handler->makeEmptyContent();
1444 if ( $content->getModel() !== $handler->getModelID() ) {
1445 $converted = $content->convert( $handler->getModelID() );
1447 if ( !$converted ) {
1448 // TODO: somehow show a warning to the user!
1449 wfDebug( "Attempt to preload incompatible content: " .
1450 "can't convert " . $content->getModel() .
1451 " to " . $handler->getModelID() );
1453 return $handler->makeEmptyContent();
1456 $content = $converted;
1459 return $content->preloadTransform( $title, $parserOptions, $params );
1463 * Make sure the form isn't faking a user's credentials.
1465 * @param WebRequest &$request
1469 public function tokenOk( &$request ) {
1470 $token = $request->getVal( 'wpEditToken' );
1471 $user = $this->context
->getUser();
1472 $this->mTokenOk
= $user->matchEditToken( $token );
1473 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1474 return $this->mTokenOk
;
1478 * Sets post-edit cookie indicating the user just saved a particular revision.
1480 * This uses a temporary cookie for each revision ID so separate saves will never
1481 * interfere with each other.
1483 * Article::view deletes the cookie on server-side after the redirect and
1484 * converts the value to the global JavaScript variable wgPostEdit.
1486 * If the variable were set on the server, it would be cached, which is unwanted
1487 * since the post-edit state should only apply to the load right after the save.
1489 * @param int $statusValue The status value (to check for new article status)
1491 protected function setPostEditCookie( $statusValue ) {
1492 $revisionId = $this->page
->getLatest();
1493 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1496 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1498 } elseif ( $this->oldid
) {
1502 $response = $this->context
->getRequest()->response();
1503 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1507 * Attempt submission
1508 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1509 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1510 * @return Status The resulting status object.
1512 public function attemptSave( &$resultDetails = false ) {
1513 # Allow bots to exempt some edits from bot flagging
1514 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1515 $status = $this->internalAttemptSave( $resultDetails, $bot );
1517 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1523 * Log when a page was successfully saved after the edit conflict view
1525 private function incrementResolvedConflicts() {
1526 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1530 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1531 $stats->increment( 'edit.failures.conflict.resolved' );
1535 * Handle status, such as after attempt save
1537 * @param Status $status
1538 * @param array|bool $resultDetails
1540 * @throws ErrorPageError
1541 * @return bool False, if output is done, true if rest of the form should be displayed
1543 private function handleStatus( Status
$status, $resultDetails ) {
1545 * @todo FIXME: once the interface for internalAttemptSave() is made
1546 * nicer, this should use the message in $status
1548 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1549 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1551 $this->incrementResolvedConflicts();
1553 $this->didSave
= true;
1554 if ( !$resultDetails['nullEdit'] ) {
1555 $this->setPostEditCookie( $status->value
);
1559 $out = $this->context
->getOutput();
1561 // "wpExtraQueryRedirect" is a hidden input to modify
1562 // after save URL and is not used by actual edit form
1563 $request = $this->context
->getRequest();
1564 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1566 switch ( $status->value
) {
1567 case self
::AS_HOOK_ERROR_EXPECTED
:
1568 case self
::AS_CONTENT_TOO_BIG
:
1569 case self
::AS_ARTICLE_WAS_DELETED
:
1570 case self
::AS_CONFLICT_DETECTED
:
1571 case self
::AS_SUMMARY_NEEDED
:
1572 case self
::AS_TEXTBOX_EMPTY
:
1573 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1575 case self
::AS_BLANK_ARTICLE
:
1576 case self
::AS_SELF_REDIRECT
:
1579 case self
::AS_HOOK_ERROR
:
1582 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1583 case self
::AS_PARSE_ERROR
:
1584 case self
::AS_UNICODE_NOT_SUPPORTED
:
1585 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1588 case self
::AS_SUCCESS_NEW_ARTICLE
:
1589 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1590 if ( $extraQueryRedirect ) {
1591 if ( $query === '' ) {
1592 $query = $extraQueryRedirect;
1594 $query = $query . '&' . $extraQueryRedirect;
1597 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1598 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1601 case self
::AS_SUCCESS_UPDATE
:
1603 $sectionanchor = $resultDetails['sectionanchor'];
1605 // Give extensions a chance to modify URL query on update
1607 'ArticleUpdateBeforeRedirect',
1608 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1611 if ( $resultDetails['redirect'] ) {
1612 if ( $extraQuery == '' ) {
1613 $extraQuery = 'redirect=no';
1615 $extraQuery = 'redirect=no&' . $extraQuery;
1618 if ( $extraQueryRedirect ) {
1619 if ( $extraQuery === '' ) {
1620 $extraQuery = $extraQueryRedirect;
1622 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1626 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1629 case self
::AS_SPAM_ERROR
:
1630 $this->spamPageWithContent( $resultDetails['spam'] );
1633 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1634 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1636 case self
::AS_IMAGE_REDIRECT_ANON
:
1637 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1638 throw new PermissionsError( 'upload' );
1640 case self
::AS_READ_ONLY_PAGE_ANON
:
1641 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1642 throw new PermissionsError( 'edit' );
1644 case self
::AS_READ_ONLY_PAGE
:
1645 throw new ReadOnlyError
;
1647 case self
::AS_RATE_LIMITED
:
1648 throw new ThrottledError();
1650 case self
::AS_NO_CREATE_PERMISSION
:
1651 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1652 throw new PermissionsError( $permission );
1654 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1655 throw new PermissionsError( 'editcontentmodel' );
1658 // We don't recognize $status->value. The only way that can happen
1659 // is if an extension hook aborted from inside ArticleSave.
1660 // Render the status object into $this->hookError
1661 // FIXME this sucks, we should just use the Status object throughout
1662 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1669 * Run hooks that can filter edits just before they get saved.
1671 * @param Content $content The Content to filter.
1672 * @param Status $status For reporting the outcome to the caller
1673 * @param User $user The user performing the edit
1677 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1678 // Run old style post-section-merge edit filter
1679 if ( $this->hookError
!= '' ) {
1680 # ...or the hook could be expecting us to produce an error
1681 $status->fatal( 'hookaborted' );
1682 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1686 // Run new style post-section-merge edit filter
1687 if ( !Hooks
::run( 'EditFilterMergedContent',
1688 [ $this->context
, $content, $status, $this->summary
,
1689 $user, $this->minoredit
] )
1691 # Error messages etc. could be handled within the hook...
1692 if ( $status->isGood() ) {
1693 $status->fatal( 'hookaborted' );
1694 // Not setting $this->hookError here is a hack to allow the hook
1695 // to cause a return to the edit page without $this->hookError
1696 // being set. This is used by ConfirmEdit to display a captcha
1697 // without any error message cruft.
1699 $this->hookError
= $status->getWikiText();
1701 // Use the existing $status->value if the hook set it
1702 if ( !$status->value
) {
1703 $status->value
= self
::AS_HOOK_ERROR
;
1706 } elseif ( !$status->isOK() ) {
1707 # ...or the hook could be expecting us to produce an error
1708 // FIXME this sucks, we should just use the Status object throughout
1709 $this->hookError
= $status->getWikiText();
1710 $status->fatal( 'hookaborted' );
1711 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1719 * Return the summary to be used for a new section.
1721 * @param string $sectionanchor Set to the section anchor text
1724 private function newSectionSummary( &$sectionanchor = null ) {
1727 if ( $this->sectiontitle
!== '' ) {
1728 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1729 // If no edit summary was specified, create one automatically from the section
1730 // title and have it link to the new section. Otherwise, respect the summary as
1732 if ( $this->summary
=== '' ) {
1733 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1734 return $this->context
->msg( 'newsectionsummary' )
1735 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1737 } elseif ( $this->summary
!== '' ) {
1738 $sectionanchor = $this->guessSectionName( $this->summary
);
1739 # This is a new section, so create a link to the new section
1740 # in the revision summary.
1741 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1742 return $this->context
->msg( 'newsectionsummary' )
1743 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1745 return $this->summary
;
1749 * Attempt submission (no UI)
1751 * @param array &$result Array to add statuses to, currently with the
1753 * - spam (string): Spam string from content if any spam is detected by
1755 * - sectionanchor (string): Section anchor for a section save.
1756 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1758 * - redirect (bool): Set if doEditContent is OK. True if resulting
1759 * revision is a redirect.
1760 * @param bool $bot True if edit is being made under the bot right.
1762 * @return Status Status object, possibly with a message, but always with
1763 * one of the AS_* constants in $status->value,
1765 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1766 * various error display idiosyncrasies. There are also lots of cases
1767 * where error metadata is set in the object and retrieved later instead
1768 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1769 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1772 public function internalAttemptSave( &$result, $bot = false ) {
1773 $status = Status
::newGood();
1774 $user = $this->context
->getUser();
1776 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1777 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1778 $status->fatal( 'hookaborted' );
1779 $status->value
= self
::AS_HOOK_ERROR
;
1783 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1784 $status->fatal( 'unicode-support-fail' );
1785 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1789 $request = $this->context
->getRequest();
1790 $spam = $request->getText( 'wpAntispam' );
1791 if ( $spam !== '' ) {
1796 $this->mTitle
->getPrefixedText() .
1797 '" submitted bogus field "' .
1801 $status->fatal( 'spamprotectionmatch', false );
1802 $status->value
= self
::AS_SPAM_ERROR
;
1807 # Construct Content object
1808 $textbox_content = $this->toEditContent( $this->textbox1
);
1809 } catch ( MWContentSerializationException
$ex ) {
1811 'content-failed-to-parse',
1812 $this->contentModel
,
1813 $this->contentFormat
,
1816 $status->value
= self
::AS_PARSE_ERROR
;
1820 # Check image redirect
1821 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1822 $textbox_content->isRedirect() &&
1823 !$user->isAllowed( 'upload' )
1825 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1826 $status->setResult( false, $code );
1832 $match = self
::matchSummarySpamRegex( $this->summary
);
1833 if ( $match === false && $this->section
== 'new' ) {
1834 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1835 # regular summaries, it is added to the actual wikitext.
1836 if ( $this->sectiontitle
!== '' ) {
1837 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1838 $match = self
::matchSpamRegex( $this->sectiontitle
);
1840 # This branch is taken when the "Add Topic" user interface is used, or the API
1841 # is used with the 'summary' parameter.
1842 $match = self
::matchSpamRegex( $this->summary
);
1845 if ( $match === false ) {
1846 $match = self
::matchSpamRegex( $this->textbox1
);
1848 if ( $match !== false ) {
1849 $result['spam'] = $match;
1850 $ip = $request->getIP();
1851 $pdbk = $this->mTitle
->getPrefixedDBkey();
1852 $match = str_replace( "\n", '', $match );
1853 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1854 $status->fatal( 'spamprotectionmatch', $match );
1855 $status->value
= self
::AS_SPAM_ERROR
;
1860 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1862 # Error messages etc. could be handled within the hook...
1863 $status->fatal( 'hookaborted' );
1864 $status->value
= self
::AS_HOOK_ERROR
;
1866 } elseif ( $this->hookError
!= '' ) {
1867 # ...or the hook could be expecting us to produce an error
1868 $status->fatal( 'hookaborted' );
1869 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1873 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1874 // Auto-block user's IP if the account was "hard" blocked
1875 if ( !wfReadOnly() ) {
1876 $user->spreadAnyEditBlock();
1878 # Check block state against master, thus 'false'.
1879 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1883 $this->contentLength
= strlen( $this->textbox1
);
1884 $config = $this->context
->getConfig();
1885 $maxArticleSize = $config->get( 'MaxArticleSize' );
1886 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1887 // Error will be displayed by showEditForm()
1888 $this->tooBig
= true;
1889 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1893 if ( !$user->isAllowed( 'edit' ) ) {
1894 if ( $user->isAnon() ) {
1895 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1898 $status->fatal( 'readonlytext' );
1899 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1904 $changingContentModel = false;
1905 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1906 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1907 $status->fatal( 'editpage-cannot-use-custom-model' );
1908 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1910 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1911 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1914 // Make sure the user can edit the page under the new content model too
1915 $titleWithNewContentModel = clone $this->mTitle
;
1916 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1917 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1918 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1920 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1924 $changingContentModel = true;
1925 $oldContentModel = $this->mTitle
->getContentModel();
1928 if ( $this->changeTags
) {
1929 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1930 $this->changeTags
, $user );
1931 if ( !$changeTagsStatus->isOK() ) {
1932 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1933 return $changeTagsStatus;
1937 if ( wfReadOnly() ) {
1938 $status->fatal( 'readonlytext' );
1939 $status->value
= self
::AS_READ_ONLY_PAGE
;
1942 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1943 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1945 $status->fatal( 'actionthrottledtext' );
1946 $status->value
= self
::AS_RATE_LIMITED
;
1950 # If the article has been deleted while editing, don't save it without
1952 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1953 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1957 # Load the page data from the master. If anything changes in the meantime,
1958 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1959 $this->page
->loadPageData( 'fromdbmaster' );
1960 $new = !$this->page
->exists();
1963 // Late check for create permission, just in case *PARANOIA*
1964 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1965 $status->fatal( 'nocreatetext' );
1966 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1967 wfDebug( __METHOD__
. ": no create permission\n" );
1971 // Don't save a new page if it's blank or if it's a MediaWiki:
1972 // message with content equivalent to default (allow empty pages
1973 // in this case to disable messages, see T52124)
1974 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1975 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1976 $defaultText = $defaultMessageText;
1981 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1982 $this->blankArticle
= true;
1983 $status->fatal( 'blankarticle' );
1984 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1988 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
1992 $content = $textbox_content;
1994 $result['sectionanchor'] = '';
1995 if ( $this->section
== 'new' ) {
1996 if ( $this->sectiontitle
!== '' ) {
1997 // Insert the section title above the content.
1998 $content = $content->addSectionHeader( $this->sectiontitle
);
1999 } elseif ( $this->summary
!== '' ) {
2000 // Insert the section title above the content.
2001 $content = $content->addSectionHeader( $this->summary
);
2003 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2006 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2010 # Article exists. Check for edit conflict.
2012 $this->page
->clear(); # Force reload of dates, etc.
2013 $timestamp = $this->page
->getTimestamp();
2014 $latest = $this->page
->getLatest();
2016 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2018 // Check editRevId if set, which handles same-second timestamp collisions
2019 if ( $timestamp != $this->edittime
2020 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2022 $this->isConflict
= true;
2023 if ( $this->section
== 'new' ) {
2024 if ( $this->page
->getUserText() == $user->getName() &&
2025 $this->page
->getComment() == $this->newSectionSummary()
2027 // Probably a duplicate submission of a new comment.
2028 // This can happen when CDN resends a request after
2029 // a timeout but the first one actually went through.
2031 . ": duplicate new section submission; trigger edit conflict!\n" );
2033 // New comment; suppress conflict.
2034 $this->isConflict
= false;
2035 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2037 } elseif ( $this->section
== ''
2038 && Revision
::userWasLastToEdit(
2039 DB_MASTER
, $this->mTitle
->getArticleID(),
2040 $user->getId(), $this->edittime
2043 # Suppress edit conflict with self, except for section edits where merging is required.
2044 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2045 $this->isConflict
= false;
2049 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2050 if ( $this->sectiontitle
!== '' ) {
2051 $sectionTitle = $this->sectiontitle
;
2053 $sectionTitle = $this->summary
;
2058 if ( $this->isConflict
) {
2060 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2061 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2062 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2063 // ...or disable section editing for non-current revisions (not exposed anyway).
2064 if ( $this->editRevId
!== null ) {
2065 $content = $this->page
->replaceSectionAtRev(
2072 $content = $this->page
->replaceSectionContent(
2080 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2081 $content = $this->page
->replaceSectionContent(
2088 if ( is_null( $content ) ) {
2089 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2090 $this->isConflict
= true;
2091 $content = $textbox_content; // do not try to merge here!
2092 } elseif ( $this->isConflict
) {
2094 if ( $this->mergeChangesIntoContent( $content ) ) {
2095 // Successful merge! Maybe we should tell the user the good news?
2096 $this->isConflict
= false;
2097 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2099 $this->section
= '';
2100 $this->textbox1
= ContentHandler
::getContentText( $content );
2101 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2105 if ( $this->isConflict
) {
2106 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2110 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2114 if ( $this->section
== 'new' ) {
2115 // Handle the user preference to force summaries here
2116 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2117 $this->missingSummary
= true;
2118 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2119 $status->value
= self
::AS_SUMMARY_NEEDED
;
2123 // Do not allow the user to post an empty comment
2124 if ( $this->textbox1
== '' ) {
2125 $this->missingComment
= true;
2126 $status->fatal( 'missingcommenttext' );
2127 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2130 } elseif ( !$this->allowBlankSummary
2131 && !$content->equals( $this->getOriginalContent( $user ) )
2132 && !$content->isRedirect()
2133 && md5( $this->summary
) == $this->autoSumm
2135 $this->missingSummary
= true;
2136 $status->fatal( 'missingsummary' );
2137 $status->value
= self
::AS_SUMMARY_NEEDED
;
2142 $sectionanchor = '';
2143 if ( $this->section
== 'new' ) {
2144 $this->summary
= $this->newSectionSummary( $sectionanchor );
2145 } elseif ( $this->section
!= '' ) {
2146 # Try to get a section anchor from the section source, redirect
2147 # to edited section if header found.
2148 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2149 # for duplicate heading checking and maybe parsing.
2150 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2151 # We can't deal with anchors, includes, html etc in the header for now,
2152 # headline would need to be parsed to improve this.
2153 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2154 $sectionanchor = $this->guessSectionName( $matches[2] );
2157 $result['sectionanchor'] = $sectionanchor;
2159 // Save errors may fall down to the edit form, but we've now
2160 // merged the section into full text. Clear the section field
2161 // so that later submission of conflict forms won't try to
2162 // replace that into a duplicated mess.
2163 $this->textbox1
= $this->toEditText( $content );
2164 $this->section
= '';
2166 $status->value
= self
::AS_SUCCESS_UPDATE
;
2169 if ( !$this->allowSelfRedirect
2170 && $content->isRedirect()
2171 && $content->getRedirectTarget()->equals( $this->getTitle() )
2173 // If the page already redirects to itself, don't warn.
2174 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2175 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2176 $this->selfRedirect
= true;
2177 $status->fatal( 'selfredirect' );
2178 $status->value
= self
::AS_SELF_REDIRECT
;
2183 // Check for length errors again now that the section is merged in
2184 $this->contentLength
= strlen( $this->toEditText( $content ) );
2185 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2186 $this->tooBig
= true;
2187 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2191 $flags = EDIT_AUTOSUMMARY |
2192 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2193 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2194 ( $bot ? EDIT_FORCE_BOT
: 0 );
2196 $doEditStatus = $this->page
->doEditContent(
2202 $content->getDefaultFormat(),
2207 if ( !$doEditStatus->isOK() ) {
2208 // Failure from doEdit()
2209 // Show the edit conflict page for certain recognized errors from doEdit(),
2210 // but don't show it for errors from extension hooks
2211 $errors = $doEditStatus->getErrorsArray();
2212 if ( in_array( $errors[0][0],
2213 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2215 $this->isConflict
= true;
2216 // Destroys data doEdit() put in $status->value but who cares
2217 $doEditStatus->value
= self
::AS_END
;
2219 return $doEditStatus;
2222 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2223 if ( $result['nullEdit'] ) {
2224 // We don't know if it was a null edit until now, so increment here
2225 $user->pingLimiter( 'linkpurge' );
2227 $result['redirect'] = $content->isRedirect();
2229 $this->updateWatchlist();
2231 // If the content model changed, add a log entry
2232 if ( $changingContentModel ) {
2233 $this->addContentModelChangeLogEntry(
2235 $new ?
false : $oldContentModel,
2236 $this->contentModel
,
2246 * @param string|false $oldModel false if the page is being newly created
2247 * @param string $newModel
2248 * @param string $reason
2250 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2251 $new = $oldModel === false;
2252 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2253 $log->setPerformer( $user );
2254 $log->setTarget( $this->mTitle
);
2255 $log->setComment( $reason );
2256 $log->setParameters( [
2257 '4::oldmodel' => $oldModel,
2258 '5::newmodel' => $newModel
2260 $logid = $log->insert();
2261 $log->publish( $logid );
2265 * Register the change of watch status
2267 protected function updateWatchlist() {
2268 $user = $this->context
->getUser();
2269 if ( !$user->isLoggedIn() ) {
2273 $title = $this->mTitle
;
2274 $watch = $this->watchthis
;
2275 // Do this in its own transaction to reduce contention...
2276 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2277 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2278 return; // nothing to change
2280 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2285 * Attempts to do 3-way merge of edit content with a base revision
2286 * and current content, in case of edit conflict, in whichever way appropriate
2287 * for the content type.
2291 * @param Content $editContent
2295 private function mergeChangesIntoContent( &$editContent ) {
2296 $db = wfGetDB( DB_MASTER
);
2298 // This is the revision the editor started from
2299 $baseRevision = $this->getBaseRevision();
2300 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2302 if ( is_null( $baseContent ) ) {
2306 // The current state, we want to merge updates into it
2307 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2308 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2310 if ( is_null( $currentContent ) ) {
2314 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2316 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2319 $editContent = $result;
2320 // Update parentRevId to what we just merged.
2321 $this->parentRevId
= $currentRevision->getId();
2329 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2330 * one might think of X as the "base revision", which is NOT what this returns.
2331 * @return Revision Current version when the edit was started
2333 public function getBaseRevision() {
2334 if ( !$this->mBaseRevision
) {
2335 $db = wfGetDB( DB_MASTER
);
2336 $this->mBaseRevision
= $this->editRevId
2337 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2338 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2340 return $this->mBaseRevision
;
2344 * Check given input text against $wgSpamRegex, and return the text of the first match.
2346 * @param string $text
2348 * @return string|bool Matching string or false
2350 public static function matchSpamRegex( $text ) {
2351 global $wgSpamRegex;
2352 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2353 $regexes = (array)$wgSpamRegex;
2354 return self
::matchSpamRegexInternal( $text, $regexes );
2358 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2360 * @param string $text
2362 * @return string|bool Matching string or false
2364 public static function matchSummarySpamRegex( $text ) {
2365 global $wgSummarySpamRegex;
2366 $regexes = (array)$wgSummarySpamRegex;
2367 return self
::matchSpamRegexInternal( $text, $regexes );
2371 * @param string $text
2372 * @param array $regexes
2373 * @return bool|string
2375 protected static function matchSpamRegexInternal( $text, $regexes ) {
2376 foreach ( $regexes as $regex ) {
2378 if ( preg_match( $regex, $text, $matches ) ) {
2385 public function setHeaders() {
2386 $out = $this->context
->getOutput();
2388 $out->addModules( 'mediawiki.action.edit' );
2389 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2391 $user = $this->context
->getUser();
2392 if ( $user->getOption( 'showtoolbar' ) ) {
2393 // The addition of default buttons is handled by getEditToolbar() which
2394 // has its own dependency on this module. The call here ensures the module
2395 // is loaded in time (it has position "top") for other modules to register
2396 // buttons (e.g. extensions, gadgets, user scripts).
2397 $out->addModules( 'mediawiki.toolbar' );
2400 if ( $user->getOption( 'uselivepreview' ) ) {
2401 $out->addModules( 'mediawiki.action.edit.preview' );
2404 if ( $user->getOption( 'useeditwarning' ) ) {
2405 $out->addModules( 'mediawiki.action.edit.editWarning' );
2408 # Enabled article-related sidebar, toplinks, etc.
2409 $out->setArticleRelated( true );
2411 $contextTitle = $this->getContextTitle();
2412 if ( $this->isConflict
) {
2413 $msg = 'editconflict';
2414 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2415 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2417 $msg = $contextTitle->exists()
2418 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2419 && $contextTitle->getDefaultMessageText() !== false
2425 # Use the title defined by DISPLAYTITLE magic word when present
2426 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2427 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2428 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2429 if ( $displayTitle === false ) {
2430 $displayTitle = $contextTitle->getPrefixedText();
2432 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2433 # Transmit the name of the message to JavaScript for live preview
2434 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2435 $out->addJsConfigVars( [
2436 'wgEditMessage' => $msg,
2437 'wgAjaxEditStash' => $this->context
->getConfig()->get( 'AjaxEditStash' ),
2442 * Show all applicable editing introductions
2444 protected function showIntro() {
2445 if ( $this->suppressIntro
) {
2449 $out = $this->context
->getOutput();
2450 $namespace = $this->mTitle
->getNamespace();
2452 if ( $namespace == NS_MEDIAWIKI
) {
2453 # Show a warning if editing an interface message
2454 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2455 # If this is a default message (but not css or js),
2456 # show a hint that it is translatable on translatewiki.net
2457 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2458 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2460 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2461 if ( $defaultMessageText !== false ) {
2462 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2463 'translateinterface' );
2466 } elseif ( $namespace == NS_FILE
) {
2467 # Show a hint to shared repo
2468 $file = wfFindFile( $this->mTitle
);
2469 if ( $file && !$file->isLocal() ) {
2470 $descUrl = $file->getDescriptionUrl();
2471 # there must be a description url to show a hint to shared repo
2473 if ( !$this->mTitle
->exists() ) {
2474 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2475 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2478 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2479 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2486 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2487 # Show log extract when the user is currently blocked
2488 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2489 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2490 $user = User
::newFromName( $username, false /* allow IP users */ );
2491 $ip = User
::isIP( $username );
2492 $block = Block
::newFromTarget( $user, $user );
2493 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2494 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2495 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2496 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2497 # Show log extract if the user is currently blocked
2498 LogEventsList
::showLogExtract(
2501 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2505 'showIfEmpty' => false,
2507 'blocked-notice-logextract',
2508 $user->getName() # Support GENDER in notice
2514 # Try to add a custom edit intro, or use the standard one if this is not possible.
2515 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2516 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2517 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2519 if ( $this->context
->getUser()->isLoggedIn() ) {
2521 // Suppress the external link icon, consider the help url an internal one
2522 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2530 // Suppress the external link icon, consider the help url an internal one
2531 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2533 'newarticletextanon',
2539 # Give a notice if the user is editing a deleted/moved page...
2540 if ( !$this->mTitle
->exists() ) {
2541 $dbr = wfGetDB( DB_REPLICA
);
2543 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2547 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2548 'showIfEmpty' => false,
2549 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2556 * Attempt to show a custom editing introduction, if supplied
2560 protected function showCustomIntro() {
2561 if ( $this->editintro
) {
2562 $title = Title
::newFromText( $this->editintro
);
2563 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2564 // Added using template syntax, to take <noinclude>'s into account.
2565 $this->context
->getOutput()->addWikiTextTitleTidy(
2566 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2576 * Gets an editable textual representation of $content.
2577 * The textual representation can be turned by into a Content object by the
2578 * toEditContent() method.
2580 * If $content is null or false or a string, $content is returned unchanged.
2582 * If the given Content object is not of a type that can be edited using
2583 * the text base EditPage, an exception will be raised. Set
2584 * $this->allowNonTextContent to true to allow editing of non-textual
2587 * @param Content|null|bool|string $content
2588 * @return string The editable text form of the content.
2590 * @throws MWException If $content is not an instance of TextContent and
2591 * $this->allowNonTextContent is not true.
2593 protected function toEditText( $content ) {
2594 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2598 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2599 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2602 return $content->serialize( $this->contentFormat
);
2606 * Turns the given text into a Content object by unserializing it.
2608 * If the resulting Content object is not of a type that can be edited using
2609 * the text base EditPage, an exception will be raised. Set
2610 * $this->allowNonTextContent to true to allow editing of non-textual
2613 * @param string|null|bool $text Text to unserialize
2614 * @return Content|bool|null The content object created from $text. If $text was false
2615 * or null, false resp. null will be returned instead.
2617 * @throws MWException If unserializing the text results in a Content
2618 * object that is not an instance of TextContent and
2619 * $this->allowNonTextContent is not true.
2621 protected function toEditContent( $text ) {
2622 if ( $text === false ||
$text === null ) {
2626 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2627 $this->contentModel
, $this->contentFormat
);
2629 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2630 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2637 * Send the edit form and related headers to OutputPage
2638 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2639 * during form output near the top, for captchas and the like.
2641 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2642 * use the EditPage::showEditForm:fields hook instead.
2644 public function showEditForm( $formCallback = null ) {
2645 # need to parse the preview early so that we know which templates are used,
2646 # otherwise users with "show preview after edit box" will get a blank list
2647 # we parse this near the beginning so that setHeaders can do the title
2648 # setting work instead of leaving it in getPreviewText
2649 $previewOutput = '';
2650 if ( $this->formtype
== 'preview' ) {
2651 $previewOutput = $this->getPreviewText();
2654 $out = $this->context
->getOutput();
2656 // Avoid PHP 7.1 warning of passing $this by reference
2658 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2660 $this->setHeaders();
2662 $this->addTalkPageText();
2663 $this->addEditNotices();
2665 if ( !$this->isConflict
&&
2666 $this->section
!= '' &&
2667 !$this->isSectionEditSupported() ) {
2668 // We use $this->section to much before this and getVal('wgSection') directly in other places
2669 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2670 // Someone is welcome to try refactoring though
2671 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2675 $this->showHeader();
2677 $out->addHTML( $this->editFormPageTop
);
2679 $user = $this->context
->getUser();
2680 if ( $user->getOption( 'previewontop' ) ) {
2681 $this->displayPreviewArea( $previewOutput, true );
2684 $out->addHTML( $this->editFormTextTop
);
2686 $showToolbar = true;
2687 if ( $this->wasDeletedSinceLastEdit() ) {
2688 if ( $this->formtype
== 'save' ) {
2689 // Hide the toolbar and edit area, user can click preview to get it back
2690 // Add an confirmation checkbox and explanation.
2691 $showToolbar = false;
2693 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2694 'deletedwhileediting' );
2698 // @todo add EditForm plugin interface and use it here!
2699 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2700 $out->addHTML( Html
::openElement(
2703 'class' => 'mw-editform',
2704 'id' => self
::EDITFORM_ID
,
2705 'name' => self
::EDITFORM_ID
,
2707 'action' => $this->getActionURL( $this->getContextTitle() ),
2708 'enctype' => 'multipart/form-data'
2712 if ( is_callable( $formCallback ) ) {
2713 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2714 call_user_func_array( $formCallback, [ &$out ] );
2717 // Add a check for Unicode support
2718 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2720 // Add an empty field to trip up spambots
2722 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2725 [ 'for' => 'wpAntispam' ],
2726 $this->context
->msg( 'simpleantispam-label' )->parse()
2732 'name' => 'wpAntispam',
2733 'id' => 'wpAntispam',
2737 . Xml
::closeElement( 'div' )
2740 // Avoid PHP 7.1 warning of passing $this by reference
2742 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2744 // Put these up at the top to ensure they aren't lost on early form submission
2745 $this->showFormBeforeText();
2747 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2748 $username = $this->lastDelete
->user_name
;
2749 $comment = CommentStore
::newKey( 'log_comment' )->getComment( $this->lastDelete
)->text
;
2751 // It is better to not parse the comment at all than to have templates expanded in the middle
2752 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2753 $key = $comment === ''
2754 ?
'confirmrecreate-noreason'
2755 : 'confirmrecreate';
2757 '<div class="mw-confirm-recreate">' .
2758 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2759 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2760 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2766 # When the summary is hidden, also hide them on preview/show changes
2767 if ( $this->nosummary
) {
2768 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2771 # If a blank edit summary was previously provided, and the appropriate
2772 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2773 # user being bounced back more than once in the event that a summary
2776 # For a bit more sophisticated detection of blank summaries, hash the
2777 # automatic one and pass that in the hidden field wpAutoSummary.
2778 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2779 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2782 if ( $this->undidRev
) {
2783 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2786 if ( $this->selfRedirect
) {
2787 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2790 if ( $this->hasPresetSummary
) {
2791 // If a summary has been preset using &summary= we don't want to prompt for
2792 // a different summary. Only prompt for a summary if the summary is blanked.
2794 $this->autoSumm
= md5( '' );
2797 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2798 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2800 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2801 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2803 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2804 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2808 if ( $this->section
== 'new' ) {
2809 $this->showSummaryInput( true, $this->summary
);
2810 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2813 $out->addHTML( $this->editFormTextBeforeContent
);
2815 if ( !$this->mTitle
->isCssJsSubpage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2816 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2819 if ( $this->blankArticle
) {
2820 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2823 if ( $this->isConflict
) {
2824 // In an edit conflict bypass the overridable content form method
2825 // and fallback to the raw wpTextbox1 since editconflicts can't be
2826 // resolved between page source edits and custom ui edits using the
2828 $this->textbox2
= $this->textbox1
;
2830 $content = $this->getCurrentContent();
2831 $this->textbox1
= $this->toEditText( $content );
2833 $this->showTextbox1();
2835 $this->showContentForm();
2838 $out->addHTML( $this->editFormTextAfterContent
);
2840 $this->showStandardInputs();
2842 $this->showFormAfterText();
2844 $this->showTosSummary();
2846 $this->showEditTools();
2848 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2850 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2852 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2853 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2855 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2856 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2858 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2860 if ( $this->isConflict
) {
2862 $this->showConflict();
2863 } catch ( MWContentSerializationException
$ex ) {
2864 // this can't really happen, but be nice if it does.
2865 $msg = $this->context
->msg(
2866 'content-failed-to-parse',
2867 $this->contentModel
,
2868 $this->contentFormat
,
2871 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2875 // Set a hidden field so JS knows what edit form mode we are in
2876 if ( $this->isConflict
) {
2878 } elseif ( $this->preview
) {
2880 } elseif ( $this->diff
) {
2885 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2887 // Marker for detecting truncated form data. This must be the last
2888 // parameter sent in order to be of use, so do not move me.
2889 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2890 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2892 if ( !$user->getOption( 'previewontop' ) ) {
2893 $this->displayPreviewArea( $previewOutput, false );
2898 * Wrapper around TemplatesOnThisPageFormatter to make
2899 * a "templates on this page" list.
2901 * @param Title[] $templates
2902 * @return string HTML
2904 public function makeTemplatesOnThisPageList( array $templates ) {
2905 $templateListFormatter = new TemplatesOnThisPageFormatter(
2906 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2909 // preview if preview, else section if section, else false
2911 if ( $this->preview
) {
2913 } elseif ( $this->section
!= '' ) {
2917 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2918 $templateListFormatter->format( $templates, $type )
2923 * Extract the section title from current section text, if any.
2925 * @param string $text
2926 * @return string|bool String or false
2928 public static function extractSectionTitle( $text ) {
2929 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2930 if ( !empty( $matches[2] ) ) {
2932 return $wgParser->stripSectionName( trim( $matches[2] ) );
2938 protected function showHeader() {
2939 $out = $this->context
->getOutput();
2940 $user = $this->context
->getUser();
2941 if ( $this->isConflict
) {
2942 $this->addExplainConflictHeader( $out );
2943 $this->editRevId
= $this->page
->getLatest();
2945 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2946 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2947 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2948 if ( $sectionTitle !== false ) {
2949 $this->summary
= "/* $sectionTitle */ ";
2954 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
2956 if ( $this->missingComment
) {
2957 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2960 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2962 "<div id='mw-missingsummary'>\n$1\n</div>",
2963 [ 'missingsummary', $buttonLabel ]
2967 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2969 "<div id='mw-missingcommentheader'>\n$1\n</div>",
2970 [ 'missingcommentheader', $buttonLabel ]
2974 if ( $this->blankArticle
) {
2976 "<div id='mw-blankarticle'>\n$1\n</div>",
2977 [ 'blankarticle', $buttonLabel ]
2981 if ( $this->selfRedirect
) {
2983 "<div id='mw-selfredirect'>\n$1\n</div>",
2984 [ 'selfredirect', $buttonLabel ]
2988 if ( $this->hookError
!== '' ) {
2989 $out->addWikiText( $this->hookError
);
2992 if ( $this->section
!= 'new' ) {
2993 $revision = $this->mArticle
->getRevisionFetched();
2995 // Let sysop know that this will make private content public if saved
2997 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
2999 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3000 'rev-deleted-text-permission'
3002 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3004 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3005 'rev-deleted-text-view'
3009 if ( !$revision->isCurrent() ) {
3010 $this->mArticle
->setOldSubtitle( $revision->getId() );
3011 $out->addWikiMsg( 'editingold' );
3012 $this->isOldRev
= true;
3014 } elseif ( $this->mTitle
->exists() ) {
3015 // Something went wrong
3017 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3018 [ 'missing-revision', $this->oldid
] );
3023 if ( wfReadOnly() ) {
3025 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3026 [ 'readonlywarning', wfReadOnlyReason() ]
3028 } elseif ( $user->isAnon() ) {
3029 if ( $this->formtype
!= 'preview' ) {
3031 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3032 [ 'anoneditwarning',
3034 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3035 'returnto' => $this->getTitle()->getPrefixedDBkey()
3038 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3039 'returnto' => $this->getTitle()->getPrefixedDBkey()
3044 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3045 'anonpreviewwarning'
3049 if ( $this->mTitle
->isCssJsSubpage() ) {
3050 # Check the skin exists
3051 if ( $this->isWrongCaseCssJsPage() ) {
3053 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
3054 [ 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ]
3057 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3058 $isCssSubpage = $this->mTitle
->isCssSubpage();
3059 $out->wrapWikiMsg( '<div class="mw-usercssjspublic">$1</div>',
3060 $isCssSubpage ?
'usercssispublic' : 'userjsispublic'
3062 if ( $this->formtype
!== 'preview' ) {
3063 $config = $this->context
->getConfig();
3064 if ( $isCssSubpage && $config->get( 'AllowUserCss' ) ) {
3066 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3067 [ 'usercssyoucanpreview' ]
3071 if ( $this->mTitle
->isJsSubpage() && $config->get( 'AllowUserJs' ) ) {
3073 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3074 [ 'userjsyoucanpreview' ]
3082 $this->addPageProtectionWarningHeaders();
3084 $this->addLongPageWarningHeader();
3086 # Add header copyright warning
3087 $this->showHeaderCopyrightWarning();
3091 * Helper function for summary input functions, which returns the neccessary
3092 * attributes for the input.
3094 * @param array|null $inputAttrs Array of attrs to use on the input
3097 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3098 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
3099 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3100 'id' => 'wpSummary',
3101 'name' => 'wpSummary',
3102 'maxlength' => '200',
3105 'spellcheck' => 'true',
3110 * Standard summary input and label (wgSummary), abstracted so EditPage
3111 * subclasses may reorganize the form.
3112 * Note that you do not need to worry about the label's for=, it will be
3113 * inferred by the id given to the input. You can remove them both by
3114 * passing [ 'id' => false ] to $userInputAttrs.
3116 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3117 * @param string $summary The value of the summary input
3118 * @param string $labelText The html to place inside the label
3119 * @param array $inputAttrs Array of attrs to use on the input
3120 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
3121 * @return array An array in the format [ $label, $input ]
3123 public function getSummaryInput( $summary = "", $labelText = null,
3124 $inputAttrs = null, $spanLabelAttrs = null
3126 wfDeprecated( __METHOD__
, '1.30' );
3127 $inputAttrs = $this->getSummaryInputAttributes( $inputAttrs );
3128 $inputAttrs +
= Linker
::tooltipAndAccesskeyAttribs( 'summary' );
3130 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : [] ) +
[
3131 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
3132 'id' => "wpSummaryLabel"
3139 $inputAttrs['id'] ?
[ 'for' => $inputAttrs['id'] ] : null,
3142 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
3145 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
3147 return [ $label, $input ];
3151 * Builds a standard summary input with a label.
3153 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3154 * @param string $summary The value of the summary input
3155 * @param string $labelText The html to place inside the label
3156 * @param array $inputAttrs Array of attrs to use on the input
3158 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3160 function getSummaryInputOOUI( $summary = "", $labelText = null, $inputAttrs = null ) {
3161 wfDeprecated( __METHOD__
, '1.30' );
3162 $this->getSummaryInputWidget( $summary, $labelText, $inputAttrs );
3166 * Builds a standard summary input with a label.
3168 * @param string $summary The value of the summary input
3169 * @param string $labelText The html to place inside the label
3170 * @param array $inputAttrs Array of attrs to use on the input
3172 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3174 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3175 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3176 $this->getSummaryInputAttributes( $inputAttrs )
3179 'title' => Linker
::titleAttrib( 'summary' ),
3180 'accessKey' => Linker
::accesskey( 'summary' ),
3183 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3184 $inputAttrs['inputId'] = $inputAttrs['id'];
3185 $inputAttrs['id'] = 'wpSummaryWidget';
3187 return new OOUI\
FieldLayout(
3188 new OOUI\
TextInputWidget( [
3189 'value' => $summary,
3190 'infusable' => true,
3193 'label' => new OOUI\
HtmlSnippet( $labelText ),
3195 'id' => 'wpSummaryLabel',
3196 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3202 * @param bool $isSubjectPreview True if this is the section subject/title
3203 * up top, or false if this is the comment summary
3204 * down below the textarea
3205 * @param string $summary The text of the summary to display
3207 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3208 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3209 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3210 if ( $isSubjectPreview ) {
3211 if ( $this->nosummary
) {
3215 if ( !$this->mShowSummaryField
) {
3220 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3221 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3224 [ 'class' => $summaryClass ]
3229 * @param bool $isSubjectPreview True if this is the section subject/title
3230 * up top, or false if this is the comment summary
3231 * down below the textarea
3232 * @param string $summary The text of the summary to display
3235 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3236 // avoid spaces in preview, gets always trimmed on save
3237 $summary = trim( $summary );
3238 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3244 if ( $isSubjectPreview ) {
3245 $summary = $this->context
->msg( 'newsectionsummary' )
3246 ->rawParams( $wgParser->stripSectionName( $summary ) )
3247 ->inContentLanguage()->text();
3250 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3252 $summary = $this->context
->msg( $message )->parse()
3253 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3254 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3257 protected function showFormBeforeText() {
3258 $out = $this->context
->getOutput();
3259 $out->addHTML( Html
::hidden( 'wpSection', htmlspecialchars( $this->section
) ) );
3260 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3261 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3262 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3263 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3266 protected function showFormAfterText() {
3268 * To make it harder for someone to slip a user a page
3269 * which submits an edit form to the wiki without their
3270 * knowledge, a random token is associated with the login
3271 * session. If it's not passed back with the submission,
3272 * we won't save the page, or render user JavaScript and
3275 * For anon editors, who may not have a session, we just
3276 * include the constant suffix to prevent editing from
3277 * broken text-mangling proxies.
3279 $this->context
->getOutput()->addHTML(
3281 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3287 * Subpage overridable method for printing the form for page content editing
3288 * By default this simply outputs wpTextbox1
3289 * Subclasses can override this to provide a custom UI for editing;
3290 * be it a form, or simply wpTextbox1 with a modified content that will be
3291 * reverse modified when extracted from the post data.
3292 * Note that this is basically the inverse for importContentFormData
3294 protected function showContentForm() {
3295 $this->showTextbox1();
3299 * Method to output wpTextbox1
3300 * The $textoverride method can be used by subclasses overriding showContentForm
3301 * to pass back to this method.
3303 * @param array $customAttribs Array of html attributes to use in the textarea
3304 * @param string $textoverride Optional text to override $this->textarea1 with
3306 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3307 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3308 $attribs = [ 'style' => 'display:none;' ];
3310 $classes = []; // Textarea CSS
3311 if ( $this->mTitle
->isProtected( 'edit' ) &&
3312 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
3314 # Is the title semi-protected?
3315 if ( $this->mTitle
->isSemiProtected() ) {
3316 $classes[] = 'mw-textarea-sprotected';
3318 # Then it must be protected based on static groups (regular)
3319 $classes[] = 'mw-textarea-protected';
3321 # Is the title cascade-protected?
3322 if ( $this->mTitle
->isCascadeProtected() ) {
3323 $classes[] = 'mw-textarea-cprotected';
3326 # Is an old revision being edited?
3327 if ( $this->isOldRev
) {
3328 $classes[] = 'mw-textarea-oldrev';
3331 $attribs = [ 'tabindex' => 1 ];
3333 if ( is_array( $customAttribs ) ) {
3334 $attribs +
= $customAttribs;
3337 if ( count( $classes ) ) {
3338 if ( isset( $attribs['class'] ) ) {
3339 $classes[] = $attribs['class'];
3341 $attribs['class'] = implode( ' ', $classes );
3346 $textoverride !== null ?
$textoverride : $this->textbox1
,
3352 protected function showTextbox2() {
3353 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3356 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3357 $wikitext = $this->addNewLineAtEnd( $text );
3359 $attribs = $this->buildTextboxAttribs( $name, $customAttribs, $this->context
->getUser() );
3361 $this->context
->getOutput()->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3364 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3367 $classes[] = 'ontop';
3370 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3372 if ( $this->formtype
!= 'preview' ) {
3373 $attribs['style'] = 'display: none;';
3376 $out = $this->context
->getOutput();
3377 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3379 if ( $this->formtype
== 'preview' ) {
3380 $this->showPreview( $previewOutput );
3382 // Empty content container for LivePreview
3383 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3384 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3385 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3386 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3389 $out->addHTML( '</div>' );
3391 if ( $this->formtype
== 'diff' ) {
3394 } catch ( MWContentSerializationException
$ex ) {
3395 $msg = $this->context
->msg(
3396 'content-failed-to-parse',
3397 $this->contentModel
,
3398 $this->contentFormat
,
3401 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3407 * Append preview output to OutputPage.
3408 * Includes category rendering if this is a category page.
3410 * @param string $text The HTML to be output for the preview.
3412 protected function showPreview( $text ) {
3413 if ( $this->mArticle
instanceof CategoryPage
) {
3414 $this->mArticle
->openShowCategory();
3416 # This hook seems slightly odd here, but makes things more
3417 # consistent for extensions.
3418 $out = $this->context
->getOutput();
3419 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3420 $out->addHTML( $text );
3421 if ( $this->mArticle
instanceof CategoryPage
) {
3422 $this->mArticle
->closeShowCategory();
3427 * Get a diff between the current contents of the edit box and the
3428 * version of the page we're editing from.
3430 * If this is a section edit, we'll replace the section as for final
3431 * save and then make a comparison.
3433 public function showDiff() {
3436 $oldtitlemsg = 'currentrev';
3437 # if message does not exist, show diff against the preloaded default
3438 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3439 $oldtext = $this->mTitle
->getDefaultMessageText();
3440 if ( $oldtext !== false ) {
3441 $oldtitlemsg = 'defaultmessagetext';
3442 $oldContent = $this->toEditContent( $oldtext );
3447 $oldContent = $this->getCurrentContent();
3450 $textboxContent = $this->toEditContent( $this->textbox1
);
3451 if ( $this->editRevId
!== null ) {
3452 $newContent = $this->page
->replaceSectionAtRev(
3453 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3456 $newContent = $this->page
->replaceSectionContent(
3457 $this->section
, $textboxContent, $this->summary
, $this->edittime
3461 if ( $newContent ) {
3462 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3464 $user = $this->context
->getUser();
3465 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
3466 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3469 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3470 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3471 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3473 if ( !$oldContent ) {
3474 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3477 if ( !$newContent ) {
3478 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3481 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3482 $de->setContent( $oldContent, $newContent );
3484 $difftext = $de->getDiff( $oldtitle, $newtitle );
3485 $de->showDiffStyle();
3490 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3494 * Show the header copyright warning.
3496 protected function showHeaderCopyrightWarning() {
3497 $msg = 'editpage-head-copy-warn';
3498 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3499 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3500 'editpage-head-copy-warn' );
3505 * Give a chance for site and per-namespace customizations of
3506 * terms of service summary link that might exist separately
3507 * from the copyright notice.
3509 * This will display between the save button and the edit tools,
3510 * so should remain short!
3512 protected function showTosSummary() {
3513 $msg = 'editpage-tos-summary';
3514 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3515 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3516 $out = $this->context
->getOutput();
3517 $out->addHTML( '<div class="mw-tos-summary">' );
3518 $out->addWikiMsg( $msg );
3519 $out->addHTML( '</div>' );
3524 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3525 * characters not present on most keyboards for copying/pasting.
3527 protected function showEditTools() {
3528 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3529 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3534 * Get the copyright warning
3536 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3539 protected function getCopywarn() {
3540 return self
::getCopyrightWarning( $this->mTitle
);
3544 * Get the copyright warning, by default returns wikitext
3546 * @param Title $title
3547 * @param string $format Output format, valid values are any function of a Message object
3548 * @param Language|string|null $langcode Language code or Language object.
3551 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3552 global $wgRightsText;
3553 if ( $wgRightsText ) {
3554 $copywarnMsg = [ 'copyrightwarning',
3555 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3558 $copywarnMsg = [ 'copyrightwarning2',
3559 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3561 // Allow for site and per-namespace customization of contribution/copyright notice.
3562 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3564 $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
3566 $msg->inLanguage( $langcode );
3568 return "<div id=\"editpage-copywarn\">\n" .
3569 $msg->$format() . "\n</div>";
3573 * Get the Limit report for page previews
3576 * @param ParserOutput $output ParserOutput object from the parse
3577 * @return string HTML
3579 public static function getPreviewLimitReport( $output ) {
3580 if ( !$output ||
!$output->getLimitReportData() ) {
3584 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3585 wfMessage( 'limitreport-title' )->parseAsBlock()
3588 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3589 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3591 $limitReport .= Html
::openElement( 'table', [
3592 'class' => 'preview-limit-report wikitable'
3594 Html
::openElement( 'tbody' );
3596 foreach ( $output->getLimitReportData() as $key => $value ) {
3597 if ( Hooks
::run( 'ParserLimitReportFormat',
3598 [ $key, &$value, &$limitReport, true, true ]
3600 $keyMsg = wfMessage( $key );
3601 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3602 if ( !$valueMsg->exists() ) {
3603 $valueMsg = new RawMessage( '$1' );
3605 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3606 $limitReport .= Html
::openElement( 'tr' ) .
3607 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3608 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3609 Html
::closeElement( 'tr' );
3614 $limitReport .= Html
::closeElement( 'tbody' ) .
3615 Html
::closeElement( 'table' ) .
3616 Html
::closeElement( 'div' );
3618 return $limitReport;
3621 protected function showStandardInputs( &$tabindex = 2 ) {
3622 $out = $this->context
->getOutput();
3623 $out->addHTML( "<div class='editOptions'>\n" );
3625 if ( $this->section
!= 'new' ) {
3626 $this->showSummaryInput( false, $this->summary
);
3627 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3630 $checkboxes = $this->getCheckboxesWidget(
3632 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3634 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3636 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3638 // Show copyright warning.
3639 $out->addWikiText( $this->getCopywarn() );
3640 $out->addHTML( $this->editFormTextAfterWarn
);
3642 $out->addHTML( "<div class='editButtons'>\n" );
3643 $out->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3645 $cancel = $this->getCancelLink();
3646 if ( $cancel !== '' ) {
3647 $cancel .= Html
::element( 'span',
3648 [ 'class' => 'mw-editButtons-pipe-separator' ],
3649 $this->context
->msg( 'pipe-separator' )->text() );
3652 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3653 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3656 $this->context
->msg( 'edithelp' )->text(),
3657 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3660 $this->context
->msg( 'word-separator' )->escaped() .
3661 $this->context
->msg( 'newwindow' )->parse();
3663 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3664 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3665 $out->addHTML( "</div><!-- editButtons -->\n" );
3667 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3669 $out->addHTML( "</div><!-- editOptions -->\n" );
3673 * Show an edit conflict. textbox1 is already shown in showEditForm().
3674 * If you want to use another entry point to this function, be careful.
3676 protected function showConflict() {
3677 $out = $this->context
->getOutput();
3678 // Avoid PHP 7.1 warning of passing $this by reference
3680 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3681 $this->incrementConflictStats();
3683 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3685 $content1 = $this->toEditContent( $this->textbox1
);
3686 $content2 = $this->toEditContent( $this->textbox2
);
3688 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3689 $de = $handler->createDifferenceEngine( $this->context
);
3690 $de->setContent( $content2, $content1 );
3692 $this->context
->msg( 'yourtext' )->parse(),
3693 $this->context
->msg( 'storedversion' )->text()
3696 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3697 $this->showTextbox2();
3701 protected function incrementConflictStats() {
3702 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3703 $stats->increment( 'edit.failures.conflict' );
3704 // Only include 'standard' namespaces to avoid creating unknown numbers of statsd metrics
3706 $this->mTitle
->getNamespace() >= NS_MAIN
&&
3707 $this->mTitle
->getNamespace() <= NS_CATEGORY_TALK
3709 $stats->increment( 'edit.failures.conflict.byNamespaceId.' . $this->mTitle
->getNamespace() );
3716 public function getCancelLink() {
3718 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3719 $cancelParams['oldid'] = $this->oldid
;
3720 } elseif ( $this->getContextTitle()->isRedirect() ) {
3721 $cancelParams['redirect'] = 'no';
3724 return new OOUI\
ButtonWidget( [
3725 'id' => 'mw-editform-cancel',
3726 'href' => $this->getContextTitle()->getLinkUrl( $cancelParams ),
3727 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3729 'infusable' => true,
3730 'flags' => 'destructive',
3735 * Returns the URL to use in the form's action attribute.
3736 * This is used by EditPage subclasses when simply customizing the action
3737 * variable in the constructor is not enough. This can be used when the
3738 * EditPage lives inside of a Special page rather than a custom page action.
3740 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3743 protected function getActionURL( Title
$title ) {
3744 return $title->getLocalURL( [ 'action' => $this->action
] );
3748 * Check if a page was deleted while the user was editing it, before submit.
3749 * Note that we rely on the logging table, which hasn't been always there,
3750 * but that doesn't matter, because this only applies to brand new
3754 protected function wasDeletedSinceLastEdit() {
3755 if ( $this->deletedSinceEdit
!== null ) {
3756 return $this->deletedSinceEdit
;
3759 $this->deletedSinceEdit
= false;
3761 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3762 $this->lastDelete
= $this->getLastDelete();
3763 if ( $this->lastDelete
) {
3764 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3765 if ( $deleteTime > $this->starttime
) {
3766 $this->deletedSinceEdit
= true;
3771 return $this->deletedSinceEdit
;
3775 * @return bool|stdClass
3777 protected function getLastDelete() {
3778 $dbr = wfGetDB( DB_REPLICA
);
3779 $commentQuery = CommentStore
::newKey( 'log_comment' )->getJoin();
3780 $data = $dbr->selectRow(
3781 [ 'logging', 'user' ] +
$commentQuery['tables'],
3792 ] +
$commentQuery['fields'], [
3793 'log_namespace' => $this->mTitle
->getNamespace(),
3794 'log_title' => $this->mTitle
->getDBkey(),
3795 'log_type' => 'delete',
3796 'log_action' => 'delete',
3800 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3802 'user' => [ 'JOIN', 'user_id=log_user' ],
3803 ] +
$commentQuery['joins']
3805 // Quick paranoid permission checks...
3806 if ( is_object( $data ) ) {
3807 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3808 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3811 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3812 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3813 $data->log_comment_data
= null;
3821 * Get the rendered text for previewing.
3822 * @throws MWException
3825 public function getPreviewText() {
3826 $out = $this->context
->getOutput();
3827 $config = $this->context
->getConfig();
3829 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3830 // Could be an offsite preview attempt. This is very unsafe if
3831 // HTML is enabled, as it could be an attack.
3833 if ( $this->textbox1
!== '' ) {
3834 // Do not put big scary notice, if previewing the empty
3835 // string, which happens when you initially edit
3836 // a category page, due to automatic preview-on-open.
3837 $parsedNote = $out->parse( "<div class='previewnote'>" .
3838 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3839 true, /* interface */true );
3841 $this->incrementEditFailureStats( 'session_loss' );
3848 $content = $this->toEditContent( $this->textbox1
);
3852 'AlternateEditPreview',
3853 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3855 return $previewHTML;
3858 # provide a anchor link to the editform
3859 $continueEditing = '<span class="mw-continue-editing">' .
3860 '[[#' . self
::EDITFORM_ID
. '|' .
3861 $this->context
->getLanguage()->getArrow() . ' ' .
3862 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3863 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3864 if ( $this->mTokenOkExceptSuffix
) {
3865 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3866 $this->incrementEditFailureStats( 'bad_token' );
3868 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3869 $this->incrementEditFailureStats( 'session_loss' );
3871 } elseif ( $this->incompleteForm
) {
3872 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3873 if ( $this->mTriedSave
) {
3874 $this->incrementEditFailureStats( 'incomplete_form' );
3877 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3880 # don't parse non-wikitext pages, show message about preview
3881 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3882 if ( $this->mTitle
->isCssJsSubpage() ) {
3884 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3890 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3892 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3895 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3897 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3904 # Used messages to make sure grep find them:
3905 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3906 if ( $level && $format ) {
3907 $note = "<div id='mw-{$level}{$format}preview'>" .
3908 $this->context
->msg( "{$level}{$format}preview" )->text() .
3909 ' ' . $continueEditing . "</div>";
3913 # If we're adding a comment, we need to show the
3914 # summary as the headline
3915 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3916 $content = $content->addSectionHeader( $this->summary
);
3919 $hook_args = [ $this, &$content ];
3920 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3922 $parserResult = $this->doPreviewParse( $content );
3923 $parserOutput = $parserResult['parserOutput'];
3924 $previewHTML = $parserResult['html'];
3925 $this->mParserOutput
= $parserOutput;
3926 $out->addParserOutputMetadata( $parserOutput );
3928 if ( count( $parserOutput->getWarnings() ) ) {
3929 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3932 } catch ( MWContentSerializationException
$ex ) {
3933 $m = $this->context
->msg(
3934 'content-failed-to-parse',
3935 $this->contentModel
,
3936 $this->contentFormat
,
3939 $note .= "\n\n" . $m->parse();
3943 if ( $this->isConflict
) {
3944 $conflict = '<h2 id="mw-previewconflict">'
3945 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3947 $conflict = '<hr />';
3950 $previewhead = "<div class='previewnote'>\n" .
3951 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3952 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3954 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3955 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3956 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3957 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3959 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3962 private function incrementEditFailureStats( $failureType ) {
3963 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3964 $stats->increment( 'edit.failures.' . $failureType );
3968 * Get parser options for a preview
3969 * @return ParserOptions
3971 protected function getPreviewParserOptions() {
3972 $parserOptions = $this->page
->makeParserOptions( $this->context
);
3973 $parserOptions->setIsPreview( true );
3974 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3975 $parserOptions->enableLimitReport();
3976 return $parserOptions;
3980 * Parse the page for a preview. Subclasses may override this class, in order
3981 * to parse with different options, or to otherwise modify the preview HTML.
3983 * @param Content $content The page content
3984 * @return array with keys:
3985 * - parserOutput: The ParserOutput object
3986 * - html: The HTML to be displayed
3988 protected function doPreviewParse( Content
$content ) {
3989 $user = $this->context
->getUser();
3990 $parserOptions = $this->getPreviewParserOptions();
3991 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
3992 $scopedCallback = $parserOptions->setupFakeRevision(
3993 $this->mTitle
, $pstContent, $user );
3994 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3995 ScopedCallback
::consume( $scopedCallback );
3996 $parserOutput->setEditSectionTokens( false ); // no section edit links
3998 'parserOutput' => $parserOutput,
3999 'html' => $parserOutput->getText() ];
4005 public function getTemplates() {
4006 if ( $this->preview ||
$this->section
!= '' ) {
4008 if ( !isset( $this->mParserOutput
) ) {
4011 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
4012 foreach ( array_keys( $template ) as $dbk ) {
4013 $templates[] = Title
::makeTitle( $ns, $dbk );
4018 return $this->mTitle
->getTemplateLinksFrom();
4023 * Shows a bulletin board style toolbar for common editing functions.
4024 * It can be disabled in the user preferences.
4026 * @param Title $title Title object for the page being edited (optional)
4029 public static function getEditToolbar( $title = null ) {
4030 global $wgContLang, $wgOut;
4031 global $wgEnableUploads, $wgForeignFileRepos;
4033 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
4034 $showSignature = true;
4036 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4040 * $toolarray is an array of arrays each of which includes the
4041 * opening tag, the closing tag, optionally a sample text that is
4042 * inserted between the two when no selection is highlighted
4043 * and. The tip text is shown when the user moves the mouse
4046 * Images are defined in ResourceLoaderEditToolbarModule.
4050 'id' => 'mw-editbutton-bold',
4052 'close' => '\'\'\'',
4053 'sample' => wfMessage( 'bold_sample' )->text(),
4054 'tip' => wfMessage( 'bold_tip' )->text(),
4057 'id' => 'mw-editbutton-italic',
4060 'sample' => wfMessage( 'italic_sample' )->text(),
4061 'tip' => wfMessage( 'italic_tip' )->text(),
4064 'id' => 'mw-editbutton-link',
4067 'sample' => wfMessage( 'link_sample' )->text(),
4068 'tip' => wfMessage( 'link_tip' )->text(),
4071 'id' => 'mw-editbutton-extlink',
4074 'sample' => wfMessage( 'extlink_sample' )->text(),
4075 'tip' => wfMessage( 'extlink_tip' )->text(),
4078 'id' => 'mw-editbutton-headline',
4081 'sample' => wfMessage( 'headline_sample' )->text(),
4082 'tip' => wfMessage( 'headline_tip' )->text(),
4084 $imagesAvailable ?
[
4085 'id' => 'mw-editbutton-image',
4086 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4088 'sample' => wfMessage( 'image_sample' )->text(),
4089 'tip' => wfMessage( 'image_tip' )->text(),
4091 $imagesAvailable ?
[
4092 'id' => 'mw-editbutton-media',
4093 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4095 'sample' => wfMessage( 'media_sample' )->text(),
4096 'tip' => wfMessage( 'media_tip' )->text(),
4099 'id' => 'mw-editbutton-nowiki',
4100 'open' => "<nowiki>",
4101 'close' => "</nowiki>",
4102 'sample' => wfMessage( 'nowiki_sample' )->text(),
4103 'tip' => wfMessage( 'nowiki_tip' )->text(),
4106 'id' => 'mw-editbutton-signature',
4107 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4110 'tip' => wfMessage( 'sig_tip' )->text(),
4113 'id' => 'mw-editbutton-hr',
4114 'open' => "\n----\n",
4117 'tip' => wfMessage( 'hr_tip' )->text(),
4121 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4122 foreach ( $toolarray as $tool ) {
4128 // Images are defined in ResourceLoaderEditToolbarModule
4130 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4131 // Older browsers show a "speedtip" type message only for ALT.
4132 // Ideally these should be different, realistically they
4133 // probably don't need to be.
4141 $script .= Xml
::encodeJsCall(
4142 'mw.toolbar.addButton',
4144 ResourceLoader
::inDebugMode()
4150 $toolbar = '<div id="toolbar"></div>';
4152 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4153 // Only add the old toolbar cruft to the page payload if the toolbar has not
4154 // been over-written by a hook caller
4155 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
4162 * Return an array of checkbox definitions.
4164 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4166 * Array values are associative arrays with the following keys:
4167 * - 'label-message' (required): message for label text
4168 * - 'id' (required): 'id' attribute for the `<input>`
4169 * - 'default' (required): default checkedness (true or false)
4170 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4171 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4172 * from messages like 'tooltip-foo', 'accesskey-foo'
4173 * - 'label-id' (optional): 'id' attribute for the `<label>`
4174 * - 'legacy-name' (optional): short name for backwards-compatibility
4175 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4176 * where bool indicates the checked status of the checkbox
4179 public function getCheckboxesDefinition( $checked ) {
4182 $user = $this->context
->getUser();
4183 // don't show the minor edit checkbox if it's a new page or section
4184 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4185 $checkboxes['wpMinoredit'] = [
4186 'id' => 'wpMinoredit',
4187 'label-message' => 'minoredit',
4188 // Uses messages: tooltip-minoredit, accesskey-minoredit
4189 'tooltip' => 'minoredit',
4190 'label-id' => 'mw-editpage-minoredit',
4191 'legacy-name' => 'minor',
4192 'default' => $checked['minor'],
4196 if ( $user->isLoggedIn() ) {
4197 $checkboxes['wpWatchthis'] = [
4198 'id' => 'wpWatchthis',
4199 'label-message' => 'watchthis',
4200 // Uses messages: tooltip-watch, accesskey-watch
4201 'tooltip' => 'watch',
4202 'label-id' => 'mw-editpage-watch',
4203 'legacy-name' => 'watch',
4204 'default' => $checked['watch'],
4209 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4215 * Returns an array of html code of the following checkboxes old style:
4218 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4219 * @param int &$tabindex Current tabindex
4220 * @param array $checked See getCheckboxesDefinition()
4223 public function getCheckboxes( &$tabindex, $checked ) {
4224 wfDeprecated( __METHOD__
, '1.30' );
4226 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4228 // Backwards-compatibility for the EditPageBeforeEditChecks hook
4229 if ( !$this->isNew
) {
4230 $checkboxes['minor'] = '';
4232 $checkboxes['watch'] = '';
4234 foreach ( $checkboxesDef as $name => $options ) {
4235 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4236 $label = $this->context
->msg( $options['label-message'] )->parse();
4238 'tabindex' => ++
$tabindex,
4239 'id' => $options['id'],
4242 'for' => $options['id'],
4244 if ( isset( $options['tooltip'] ) ) {
4245 $attribs['accesskey'] = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4246 $labelAttribs['title'] = Linker
::titleAttrib( $options['tooltip'], 'withaccess' );
4248 if ( isset( $options['title-message'] ) ) {
4249 $labelAttribs['title'] = $this->context
->msg( $options['title-message'] )->text();
4251 if ( isset( $options['label-id'] ) ) {
4252 $labelAttribs['id'] = $options['label-id'];
4255 Xml
::check( $name, $options['default'], $attribs ) .
4257 Xml
::tags( 'label', $labelAttribs, $label );
4259 $checkboxes[ $legacyName ] = $checkboxHtml;
4262 // Avoid PHP 7.1 warning of passing $this by reference
4264 Hooks
::run( 'EditPageBeforeEditChecks', [ &$editPage, &$checkboxes, &$tabindex ], '1.29' );
4269 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4270 * any other added by extensions.
4272 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4273 * @param int &$tabindex Current tabindex
4274 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4275 * status of the checkbox
4277 * @return array Associative array of string keys to OOUI\FieldLayout instances
4279 public function getCheckboxesOOUI( &$tabindex, $checked ) {
4280 wfDeprecated( __METHOD__
, '1.30' );
4281 return $this->getCheckboxesWidget( $tabindex, $checked );
4285 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4286 * any other added by extensions.
4288 * @param int &$tabindex Current tabindex
4289 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4290 * status of the checkbox
4292 * @return array Associative array of string keys to OOUI\FieldLayout instances
4294 public function getCheckboxesWidget( &$tabindex, $checked ) {
4296 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4298 foreach ( $checkboxesDef as $name => $options ) {
4299 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4303 if ( isset( $options['tooltip'] ) ) {
4304 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4305 $title = Linker
::titleAttrib( $options['tooltip'] );
4307 if ( isset( $options['title-message'] ) ) {
4308 $title = $this->context
->msg( $options['title-message'] )->text();
4311 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4312 new OOUI\
CheckboxInputWidget( [
4313 'tabIndex' => ++
$tabindex,
4314 'accessKey' => $accesskey,
4315 'id' => $options['id'] . 'Widget',
4316 'inputId' => $options['id'],
4318 'selected' => $options['default'],
4319 'infusable' => true,
4322 'align' => 'inline',
4323 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4325 'id' => isset( $options['label-id'] ) ?
$options['label-id'] : null,
4330 // Backwards-compatibility hack to run the EditPageBeforeEditChecks hook. It's important,
4331 // people have used it for the weirdest things completely unrelated to checkboxes...
4332 // And if we're gonna run it, might as well allow its legacy checkboxes to be shown.
4333 $legacyCheckboxes = [];
4334 if ( !$this->isNew
) {
4335 $legacyCheckboxes['minor'] = '';
4337 $legacyCheckboxes['watch'] = '';
4338 // Copy new-style checkboxes into an old-style structure
4339 foreach ( $checkboxes as $name => $oouiLayout ) {
4340 $legacyCheckboxes[$name] = (string)$oouiLayout;
4342 // Avoid PHP 7.1 warning of passing $this by reference
4344 Hooks
::run( 'EditPageBeforeEditChecks', [ &$ep, &$legacyCheckboxes, &$tabindex ], '1.29' );
4345 // Copy back any additional old-style checkboxes into the new-style structure
4346 foreach ( $legacyCheckboxes as $name => $html ) {
4347 if ( $html && !isset( $checkboxes[$name] ) ) {
4348 $checkboxes[$name] = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $html ) ] );
4356 * Get the message key of the label for the button to save the page
4361 protected function getSubmitButtonLabel() {
4363 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4365 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4366 $newPage = !$this->mTitle
->exists();
4368 if ( $labelAsPublish ) {
4369 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4371 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4374 return $buttonLabelKey;
4378 * Returns an array of html code of the following buttons:
4379 * save, diff and preview
4381 * @param int &$tabindex Current tabindex
4385 public function getEditButtons( &$tabindex ) {
4388 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4392 'tabindex' => ++
$tabindex,
4395 $saveConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4396 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4397 'id' => 'wpSaveWidget',
4398 'inputId' => 'wpSave',
4399 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4400 'useInputTag' => true,
4401 'flags' => [ 'constructive', 'primary' ],
4402 'label' => $buttonLabel,
4403 'infusable' => true,
4405 'title' => Linker
::titleAttrib( 'save' ),
4406 'accessKey' => Linker
::accesskey( 'save' ),
4410 'name' => 'wpPreview',
4411 'tabindex' => ++
$tabindex,
4414 $previewConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4415 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4416 'id' => 'wpPreviewWidget',
4417 'inputId' => 'wpPreview',
4418 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4419 'useInputTag' => true,
4420 'label' => $this->context
->msg( 'showpreview' )->text(),
4421 'infusable' => true,
4423 'title' => Linker
::titleAttrib( 'preview' ),
4424 'accessKey' => Linker
::accesskey( 'preview' ),
4425 ] +
$previewConfig );
4429 'tabindex' => ++
$tabindex,
4432 $diffConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4433 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4434 'id' => 'wpDiffWidget',
4435 'inputId' => 'wpDiff',
4436 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4437 'useInputTag' => true,
4438 'label' => $this->context
->msg( 'showdiff' )->text(),
4439 'infusable' => true,
4441 'title' => Linker
::titleAttrib( 'diff' ),
4442 'accessKey' => Linker
::accesskey( 'diff' ),
4445 // Avoid PHP 7.1 warning of passing $this by reference
4447 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4453 * Creates a basic error page which informs the user that
4454 * they have attempted to edit a nonexistent section.
4456 public function noSuchSectionPage() {
4457 $out = $this->context
->getOutput();
4458 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4460 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4462 // Avoid PHP 7.1 warning of passing $this by reference
4464 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4465 $out->addHTML( $res );
4467 $out->returnToMain( false, $this->mTitle
);
4471 * Show "your edit contains spam" page with your diff and text
4473 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4475 public function spamPageWithContent( $match = false ) {
4476 $this->textbox2
= $this->textbox1
;
4478 if ( is_array( $match ) ) {
4479 $match = $this->context
->getLanguage()->listToText( $match );
4481 $out = $this->context
->getOutput();
4482 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4484 $out->addHTML( '<div id="spamprotected">' );
4485 $out->addWikiMsg( 'spamprotectiontext' );
4487 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4489 $out->addHTML( '</div>' );
4491 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4494 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4495 $this->showTextbox2();
4497 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4501 * Filter an input field through a Unicode de-armoring process if it
4502 * came from an old browser with known broken Unicode editing issues.
4504 * @deprecated since 1.30, does nothing
4506 * @param WebRequest $request
4507 * @param string $field
4510 protected function safeUnicodeInput( $request, $field ) {
4511 return rtrim( $request->getText( $field ) );
4515 * Filter an output field through a Unicode armoring process if it is
4516 * going to an old browser with known broken Unicode editing issues.
4518 * @deprecated since 1.30, does nothing
4520 * @param string $text
4523 protected function safeUnicodeOutput( $text ) {
4530 protected function addEditNotices() {
4531 $out = $this->context
->getOutput();
4532 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4533 if ( count( $editNotices ) ) {
4534 $out->addHTML( implode( "\n", $editNotices ) );
4536 $msg = $this->context
->msg( 'editnotice-notext' );
4537 if ( !$msg->isDisabled() ) {
4539 '<div class="mw-editnotice-notext">'
4540 . $msg->parseAsBlock()
4550 protected function addTalkPageText() {
4551 if ( $this->mTitle
->isTalkPage() ) {
4552 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4559 protected function addLongPageWarningHeader() {
4560 if ( $this->contentLength
=== false ) {
4561 $this->contentLength
= strlen( $this->textbox1
);
4564 $out = $this->context
->getOutput();
4565 $lang = $this->context
->getLanguage();
4566 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4567 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4568 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4571 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4572 $lang->formatNum( $maxArticleSize )
4576 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4577 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4580 $lang->formatSize( strlen( $this->textbox1
) ),
4581 strlen( $this->textbox1
)
4591 protected function addPageProtectionWarningHeaders() {
4592 $out = $this->context
->getOutput();
4593 if ( $this->mTitle
->isProtected( 'edit' ) &&
4594 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4596 # Is the title semi-protected?
4597 if ( $this->mTitle
->isSemiProtected() ) {
4598 $noticeMsg = 'semiprotectedpagewarning';
4600 # Then it must be protected based on static groups (regular)
4601 $noticeMsg = 'protectedpagewarning';
4603 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4604 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4606 if ( $this->mTitle
->isCascadeProtected() ) {
4607 # Is this page under cascading protection from some source pages?
4608 /** @var Title[] $cascadeSources */
4609 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4610 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4611 $cascadeSourcesCount = count( $cascadeSources );
4612 if ( $cascadeSourcesCount > 0 ) {
4613 # Explain, and list the titles responsible
4614 foreach ( $cascadeSources as $page ) {
4615 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4618 $notice .= '</div>';
4619 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4621 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4622 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4624 'showIfEmpty' => false,
4625 'msgKey' => [ 'titleprotectedwarning' ],
4626 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4631 * @param OutputPage $out
4634 protected function addExplainConflictHeader( OutputPage
$out ) {
4636 "<div class='mw-explainconflict'>\n$1\n</div>",
4637 [ 'explainconflict', $this->context
->msg( $this->getSubmitButtonLabel() )->text() ]
4642 * @param string $name
4643 * @param mixed[] $customAttribs
4648 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4649 $attribs = $customAttribs +
[
4654 // Avoid PHP notices when appending preferences
4655 // (appending allows customAttribs['style'] to still work).
4659 // The following classes can be used here:
4660 // * mw-editfont-default
4661 // * mw-editfont-monospace
4662 // * mw-editfont-sans-serif
4663 // * mw-editfont-serif
4664 $class = 'mw-editfont-' . $user->getOption( 'editfont' );
4666 if ( isset( $attribs['class'] ) ) {
4667 if ( is_string( $attribs['class'] ) ) {
4668 $attribs['class'] .= ' ' . $class;
4669 } elseif ( is_array( $attribs['class'] ) ) {
4670 $attribs['class'][] = $class;
4673 $attribs['class'] = $class;
4676 $pageLang = $this->mTitle
->getPageLanguage();
4677 $attribs['lang'] = $pageLang->getHtmlCode();
4678 $attribs['dir'] = $pageLang->getDir();
4684 * @param string $wikitext
4688 protected function addNewLineAtEnd( $wikitext ) {
4689 if ( strval( $wikitext ) !== '' ) {
4690 // Ensure there's a newline at the end, otherwise adding lines
4692 // But don't add a newline if the text is empty, or Firefox in XHTML
4693 // mode will show an extra newline. A bit annoying.
4701 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4702 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4703 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4704 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4705 * spread the new style links more efficiently.
4707 * @param string $text
4710 private function guessSectionName( $text ) {
4713 // Detect Microsoft browsers
4714 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4715 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4716 // ...and redirect them to legacy encoding, if available
4717 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4719 // Meanwhile, real browsers get real anchors
4720 return $wgParser->guessSectionNameFromWikiText( $text );