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() {
526 * Returns if the given content model is editable.
528 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
530 * @throws MWException If $modelId has no known handler
532 public function isSupportedContentModel( $modelId ) {
533 return $this->enableApiEditOverride
=== true ||
534 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
538 * Allow editing of content that supports API direct editing, but not general
539 * direct editing. Set to false by default.
541 * @param bool $enableOverride
543 public function setApiEditOverride( $enableOverride ) {
544 $this->enableApiEditOverride
= $enableOverride;
548 * @deprecated since 1.29, call edit directly
550 public function submit() {
551 wfDeprecated( __METHOD__
, '1.29' );
556 * This is the function that gets called for "action=edit". It
557 * sets up various member variables, then passes execution to
558 * another function, usually showEditForm()
560 * The edit form is self-submitting, so that when things like
561 * preview and edit conflicts occur, we get the same form back
562 * with the extra stuff added. Only when the final submission
563 * is made and all is well do we actually save and redirect to
564 * the newly-edited page.
566 public function edit() {
567 // Allow extensions to modify/prevent this form or submission
568 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
572 wfDebug( __METHOD__
. ": enter\n" );
574 $request = $this->context
->getRequest();
575 // If they used redlink=1 and the page exists, redirect to the main article
576 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
577 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
581 $this->importFormData( $request );
582 $this->firsttime
= false;
584 if ( wfReadOnly() && $this->save
) {
587 $this->preview
= true;
591 $this->formtype
= 'save';
592 } elseif ( $this->preview
) {
593 $this->formtype
= 'preview';
594 } elseif ( $this->diff
) {
595 $this->formtype
= 'diff';
596 } else { # First time through
597 $this->firsttime
= true;
598 if ( $this->previewOnOpen() ) {
599 $this->formtype
= 'preview';
601 $this->formtype
= 'initial';
605 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
607 wfDebug( __METHOD__
. ": User can't edit\n" );
608 // Auto-block user's IP if the account was "hard" blocked
609 if ( !wfReadOnly() ) {
610 DeferredUpdates
::addCallableUpdate( function () {
611 $this->context
->getUser()->spreadAnyEditBlock();
614 $this->displayPermissionsError( $permErrors );
619 $revision = $this->mArticle
->getRevisionFetched();
620 // Disallow editing revisions with content models different from the current one
621 // Undo edits being an exception in order to allow reverting content model changes.
623 && $revision->getContentModel() !== $this->contentModel
626 if ( $this->undidRev
) {
627 $undidRevObj = Revision
::newFromId( $this->undidRev
);
628 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
630 if ( !$this->undidRev
632 ||
$prevRev->getContentModel() !== $this->contentModel
634 $this->displayViewSourcePage(
635 $this->getContentObject(),
637 'contentmodelediterror',
638 $revision->getContentModel(),
646 $this->isConflict
= false;
647 // css / js subpages of user pages get a special treatment
648 // The following member variables are deprecated since 1.30,
649 // the functions should be used instead.
650 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
651 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
652 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
653 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
655 # Show applicable editing introductions
656 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
660 # Attempt submission here. This will check for edit conflicts,
661 # and redundantly check for locked database, blocked IPs, etc.
662 # that edit() already checked just in case someone tries to sneak
663 # in the back door with a hand-edited submission URL.
665 if ( 'save' == $this->formtype
) {
666 $resultDetails = null;
667 $status = $this->attemptSave( $resultDetails );
668 if ( !$this->handleStatus( $status, $resultDetails ) ) {
673 # First time through: get contents, set time for conflict
675 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
676 if ( $this->initialiseForm() === false ) {
677 $this->noSuchSectionPage();
681 if ( !$this->mTitle
->getArticleID() ) {
682 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
684 Hooks
::run( 'EditFormInitialText', [ $this ] );
689 $this->showEditForm();
693 * @param string $rigor Same format as Title::getUserPermissionErrors()
696 protected function getEditPermissionErrors( $rigor = 'secure' ) {
697 $user = $this->context
->getUser();
698 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
699 # Can this title be created?
700 if ( !$this->mTitle
->exists() ) {
701 $permErrors = array_merge(
704 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
709 # Ignore some permissions errors when a user is just previewing/viewing diffs
711 foreach ( $permErrors as $error ) {
712 if ( ( $this->preview ||
$this->diff
)
714 $error[0] == 'blockedtext' ||
715 $error[0] == 'autoblockedtext' ||
716 $error[0] == 'systemblockedtext'
722 $permErrors = wfArrayDiff2( $permErrors, $remove );
728 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
729 * but with the following differences:
730 * - If redlink=1, the user will be redirected to the page
731 * - If there is content to display or the error occurs while either saving,
732 * previewing or showing the difference, it will be a
733 * "View source for ..." page displaying the source code after the error message.
736 * @param array $permErrors Array of permissions errors, as returned by
737 * Title::getUserPermissionsErrors().
738 * @throws PermissionsError
740 protected function displayPermissionsError( array $permErrors ) {
741 $out = $this->context
->getOutput();
742 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
743 // The edit page was reached via a red link.
744 // Redirect to the article page and let them click the edit tab if
745 // they really want a permission error.
746 $out->redirect( $this->mTitle
->getFullURL() );
750 $content = $this->getContentObject();
752 # Use the normal message if there's nothing to display
753 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
754 $action = $this->mTitle
->exists() ?
'edit' :
755 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
756 throw new PermissionsError( $action, $permErrors );
759 $this->displayViewSourcePage(
761 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
766 * Display a read-only View Source page
767 * @param Content $content content object
768 * @param string $errorMessage additional wikitext error message to display
770 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
771 $out = $this->context
->getOutput();
772 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
774 $out->setRobotPolicy( 'noindex,nofollow' );
775 $out->setPageTitle( $this->context
->msg(
777 $this->getContextTitle()->getPrefixedText()
779 $out->addBacklinkSubtitle( $this->getContextTitle() );
780 $out->addHTML( $this->editFormPageTop
);
781 $out->addHTML( $this->editFormTextTop
);
783 if ( $errorMessage !== '' ) {
784 $out->addWikiText( $errorMessage );
785 $out->addHTML( "<hr />\n" );
788 # If the user made changes, preserve them when showing the markup
789 # (This happens when a user is blocked during edit, for instance)
790 if ( !$this->firsttime
) {
791 $text = $this->textbox1
;
792 $out->addWikiMsg( 'viewyourtext' );
795 $text = $this->toEditText( $content );
796 } catch ( MWException
$e ) {
797 # Serialize using the default format if the content model is not supported
798 # (e.g. for an old revision with a different model)
799 $text = $content->serialize();
801 $out->addWikiMsg( 'viewsourcetext' );
804 $out->addHTML( $this->editFormTextBeforeContent
);
805 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
806 $out->addHTML( $this->editFormTextAfterContent
);
808 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
810 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
812 $out->addHTML( $this->editFormTextBottom
);
813 if ( $this->mTitle
->exists() ) {
814 $out->returnToMain( null, $this->mTitle
);
819 * Should we show a preview when the edit form is first shown?
823 protected function previewOnOpen() {
824 $config = $this->context
->getConfig();
825 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
826 $request = $this->context
->getRequest();
827 if ( $config->get( 'RawHtml' ) ) {
828 // If raw HTML is enabled, disable preview on open
829 // since it has to be posted with a token for
833 if ( $request->getVal( 'preview' ) == 'yes' ) {
834 // Explicit override from request
836 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
837 // Explicit override from request
839 } elseif ( $this->section
== 'new' ) {
840 // Nothing *to* preview for new sections
842 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
843 && $this->context
->getUser()->getOption( 'previewonfirst' )
845 // Standard preference behavior
847 } elseif ( !$this->mTitle
->exists()
848 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
849 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
851 // Categories are special
859 * Checks whether the user entered a skin name in uppercase,
860 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
864 protected function isWrongCaseCssJsPage() {
865 if ( $this->mTitle
->isCssJsSubpage() ) {
866 $name = $this->mTitle
->getSkinFromCssJsSubpage();
867 $skins = array_merge(
868 array_keys( Skin
::getSkinNames() ),
871 return !in_array( $name, $skins )
872 && in_array( strtolower( $name ), $skins );
879 * Returns whether section editing is supported for the current page.
880 * Subclasses may override this to replace the default behavior, which is
881 * to check ContentHandler::supportsSections.
883 * @return bool True if this edit page supports sections, false otherwise.
885 protected function isSectionEditSupported() {
886 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
887 return $contentHandler->supportsSections();
891 * This function collects the form data and uses it to populate various member variables.
892 * @param WebRequest &$request
893 * @throws ErrorPageError
895 public function importFormData( &$request ) {
896 # Section edit can come from either the form or a link
897 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
899 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
900 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
903 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
905 if ( $request->wasPosted() ) {
906 # These fields need to be checked for encoding.
907 # Also remove trailing whitespace, but don't remove _initial_
908 # whitespace from the text boxes. This may be significant formatting.
909 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
910 if ( !$request->getCheck( 'wpTextbox2' ) ) {
911 // Skip this if wpTextbox2 has input, it indicates that we came
912 // from a conflict page with raw page text, not a custom form
913 // modified by subclasses
914 $textbox1 = $this->importContentFormData( $request );
915 if ( $textbox1 !== null ) {
916 $this->textbox1
= $textbox1;
920 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
922 $this->summary
= $request->getText( 'wpSummary' );
924 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
925 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
927 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
929 # Treat sectiontitle the same way as summary.
930 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
931 # currently doing double duty as both edit summary and section title. Right now this
932 # is just to allow API edits to work around this limitation, but this should be
933 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
934 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
935 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
937 $this->edittime
= $request->getVal( 'wpEdittime' );
938 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
939 $this->starttime
= $request->getVal( 'wpStarttime' );
941 $undidRev = $request->getInt( 'wpUndidRevision' );
943 $this->undidRev
= $undidRev;
946 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
948 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
949 // wpTextbox1 field is missing, possibly due to being "too big"
950 // according to some filter rules such as Suhosin's setting for
951 // suhosin.request.max_value_length (d'oh)
952 $this->incompleteForm
= true;
954 // If we receive the last parameter of the request, we can fairly
955 // claim the POST request has not been truncated.
957 // TODO: softened the check for cutover. Once we determine
958 // that it is safe, we should complete the transition by
959 // removing the "edittime" clause.
960 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
961 && is_null( $this->edittime
) );
963 if ( $this->incompleteForm
) {
964 # If the form is incomplete, force to preview.
965 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
966 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
967 $this->preview
= true;
969 $this->preview
= $request->getCheck( 'wpPreview' );
970 $this->diff
= $request->getCheck( 'wpDiff' );
972 // Remember whether a save was requested, so we can indicate
973 // if we forced preview due to session failure.
974 $this->mTriedSave
= !$this->preview
;
976 if ( $this->tokenOk( $request ) ) {
977 # Some browsers will not report any submit button
978 # if the user hits enter in the comment box.
979 # The unmarked state will be assumed to be a save,
980 # if the form seems otherwise complete.
981 wfDebug( __METHOD__
. ": Passed token check.\n" );
982 } elseif ( $this->diff
) {
983 # Failed token check, but only requested "Show Changes".
984 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
986 # Page might be a hack attempt posted from
987 # an external site. Preview instead of saving.
988 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
989 $this->preview
= true;
992 $this->save
= !$this->preview
&& !$this->diff
;
993 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
994 $this->edittime
= null;
997 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
998 $this->starttime
= null;
1001 $this->recreate
= $request->getCheck( 'wpRecreate' );
1003 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
1004 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
1006 $user = $this->context
->getUser();
1007 # Don't force edit summaries when a user is editing their own user or talk page
1008 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
1009 && $this->mTitle
->getText() == $user->getName()
1011 $this->allowBlankSummary
= true;
1013 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1014 ||
!$user->getOption( 'forceeditsummary' );
1017 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1019 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1020 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1022 $changeTags = $request->getVal( 'wpChangeTags' );
1023 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1024 $this->changeTags
= [];
1026 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1030 # Not a posted form? Start with nothing.
1031 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1032 $this->textbox1
= '';
1033 $this->summary
= '';
1034 $this->sectiontitle
= '';
1035 $this->edittime
= '';
1036 $this->editRevId
= null;
1037 $this->starttime
= wfTimestampNow();
1038 $this->edit
= false;
1039 $this->preview
= false;
1040 $this->save
= false;
1041 $this->diff
= false;
1042 $this->minoredit
= false;
1043 // Watch may be overridden by request parameters
1044 $this->watchthis
= $request->getBool( 'watchthis', false );
1045 $this->recreate
= false;
1047 // When creating a new section, we can preload a section title by passing it as the
1048 // preloadtitle parameter in the URL (T15100)
1049 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1050 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1051 // Once wpSummary isn't being use for setting section titles, we should delete this.
1052 $this->summary
= $request->getVal( 'preloadtitle' );
1053 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1054 $this->summary
= $request->getText( 'summary' );
1055 if ( $this->summary
!== '' ) {
1056 $this->hasPresetSummary
= true;
1060 if ( $request->getVal( 'minor' ) ) {
1061 $this->minoredit
= true;
1065 $this->oldid
= $request->getInt( 'oldid' );
1066 $this->parentRevId
= $request->getInt( 'parentRevId' );
1068 $this->bot
= $request->getBool( 'bot', true );
1069 $this->nosummary
= $request->getBool( 'nosummary' );
1071 // May be overridden by revision.
1072 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1073 // May be overridden by revision.
1074 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1077 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1078 } catch ( MWUnknownContentModelException
$e ) {
1079 throw new ErrorPageError(
1080 'editpage-invalidcontentmodel-title',
1081 'editpage-invalidcontentmodel-text',
1082 [ wfEscapeWikiText( $this->contentModel
) ]
1086 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1087 throw new ErrorPageError(
1088 'editpage-notsupportedcontentformat-title',
1089 'editpage-notsupportedcontentformat-text',
1091 wfEscapeWikiText( $this->contentFormat
),
1092 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1098 * @todo Check if the desired model is allowed in this namespace, and if
1099 * a transition from the page's current model to the new model is
1103 $this->editintro
= $request->getText( 'editintro',
1104 // Custom edit intro for new sections
1105 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1107 // Allow extensions to modify form data
1108 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1112 * Subpage overridable method for extracting the page content data from the
1113 * posted form to be placed in $this->textbox1, if using customized input
1114 * this method should be overridden and return the page text that will be used
1115 * for saving, preview parsing and so on...
1117 * @param WebRequest &$request
1118 * @return string|null
1120 protected function importContentFormData( &$request ) {
1121 return; // Don't do anything, EditPage already extracted wpTextbox1
1125 * Initialise form fields in the object
1126 * Called on the first invocation, e.g. when a user clicks an edit link
1127 * @return bool If the requested section is valid
1129 public function initialiseForm() {
1130 $this->edittime
= $this->page
->getTimestamp();
1131 $this->editRevId
= $this->page
->getLatest();
1133 $content = $this->getContentObject( false ); # TODO: track content object?!
1134 if ( $content === false ) {
1137 $this->textbox1
= $this->toEditText( $content );
1139 $user = $this->context
->getUser();
1140 // activate checkboxes if user wants them to be always active
1141 # Sort out the "watch" checkbox
1142 if ( $user->getOption( 'watchdefault' ) ) {
1144 $this->watchthis
= true;
1145 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1147 $this->watchthis
= true;
1148 } elseif ( $user->isWatched( $this->mTitle
) ) {
1150 $this->watchthis
= true;
1152 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1153 $this->minoredit
= true;
1155 if ( $this->textbox1
=== false ) {
1162 * @param Content|null $def_content The default value to return
1164 * @return Content|null Content on success, $def_content for invalid sections
1168 protected function getContentObject( $def_content = null ) {
1173 $user = $this->context
->getUser();
1174 $request = $this->context
->getRequest();
1175 // For message page not locally set, use the i18n message.
1176 // For other non-existent articles, use preload text if any.
1177 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1178 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1179 # If this is a system message, get the default text.
1180 $msg = $this->mTitle
->getDefaultMessageText();
1182 $content = $this->toEditContent( $msg );
1184 if ( $content === false ) {
1185 # If requested, preload some text.
1186 $preload = $request->getVal( 'preload',
1187 // Custom preload text for new sections
1188 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1189 $params = $request->getArray( 'preloadparams', [] );
1191 $content = $this->getPreloadedContent( $preload, $params );
1193 // For existing pages, get text based on "undo" or section parameters.
1195 if ( $this->section
!= '' ) {
1196 // Get section edit text (returns $def_text for invalid sections)
1197 $orig = $this->getOriginalContent( $user );
1198 $content = $orig ?
$orig->getSection( $this->section
) : null;
1201 $content = $def_content;
1204 $undoafter = $request->getInt( 'undoafter' );
1205 $undo = $request->getInt( 'undo' );
1207 if ( $undo > 0 && $undoafter > 0 ) {
1208 $undorev = Revision
::newFromId( $undo );
1209 $oldrev = Revision
::newFromId( $undoafter );
1211 # Sanity check, make sure it's the right page,
1212 # the revisions exist and they were not deleted.
1213 # Otherwise, $content will be left as-is.
1214 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1215 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1216 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1218 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1220 if ( $content === false ) {
1221 # Warn the user that something went wrong
1222 $undoMsg = 'failure';
1224 $oldContent = $this->page
->getContent( Revision
::RAW
);
1225 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1226 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1227 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1228 // The undo may change content
1229 // model if its reverting the top
1230 // edit. This can result in
1231 // mismatched content model/format.
1232 $this->contentModel
= $newContent->getModel();
1233 $this->contentFormat
= $oldrev->getContentFormat();
1236 if ( $newContent->equals( $oldContent ) ) {
1237 # Tell the user that the undo results in no change,
1238 # i.e. the revisions were already undone.
1239 $undoMsg = 'nochange';
1242 # Inform the user of our success and set an automatic edit summary
1243 $undoMsg = 'success';
1245 # If we just undid one rev, use an autosummary
1246 $firstrev = $oldrev->getNext();
1247 if ( $firstrev && $firstrev->getId() == $undo ) {
1248 $userText = $undorev->getUserText();
1249 if ( $userText === '' ) {
1250 $undoSummary = $this->context
->msg(
1251 'undo-summary-username-hidden',
1253 )->inContentLanguage()->text();
1255 $undoSummary = $this->context
->msg(
1259 )->inContentLanguage()->text();
1261 if ( $this->summary
=== '' ) {
1262 $this->summary
= $undoSummary;
1264 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1265 ->inContentLanguage()->text() . $this->summary
;
1267 $this->undidRev
= $undo;
1269 $this->formtype
= 'diff';
1273 // Failed basic sanity checks.
1274 // Older revisions may have been removed since the link
1275 // was created, or we may simply have got bogus input.
1279 $out = $this->context
->getOutput();
1280 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1281 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1282 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1283 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1286 if ( $content === false ) {
1287 $content = $this->getOriginalContent( $user );
1296 * Get the content of the wanted revision, without section extraction.
1298 * The result of this function can be used to compare user's input with
1299 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1300 * to the original text of the edit.
1302 * This differs from Article::getContent() that when a missing revision is
1303 * encountered the result will be null and not the
1304 * 'missing-revision' message.
1307 * @param User $user The user to get the revision for
1308 * @return Content|null
1310 private function getOriginalContent( User
$user ) {
1311 if ( $this->section
== 'new' ) {
1312 return $this->getCurrentContent();
1314 $revision = $this->mArticle
->getRevisionFetched();
1315 if ( $revision === null ) {
1316 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1317 return $handler->makeEmptyContent();
1319 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1324 * Get the edit's parent revision ID
1326 * The "parent" revision is the ancestor that should be recorded in this
1327 * page's revision history. It is either the revision ID of the in-memory
1328 * article content, or in the case of a 3-way merge in order to rebase
1329 * across a recoverable edit conflict, the ID of the newer revision to
1330 * which we have rebased this page.
1333 * @return int Revision ID
1335 public function getParentRevId() {
1336 if ( $this->parentRevId
) {
1337 return $this->parentRevId
;
1339 return $this->mArticle
->getRevIdFetched();
1344 * Get the current content of the page. This is basically similar to
1345 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1346 * content object is returned instead of null.
1351 protected function getCurrentContent() {
1352 $rev = $this->page
->getRevision();
1353 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1355 if ( $content === false ||
$content === null ) {
1356 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1357 return $handler->makeEmptyContent();
1358 } elseif ( !$this->undidRev
) {
1359 // Content models should always be the same since we error
1360 // out if they are different before this point (in ->edit()).
1361 // The exception being, during an undo, the current revision might
1362 // differ from the prior revision.
1363 $logger = LoggerFactory
::getInstance( 'editpage' );
1364 if ( $this->contentModel
!== $rev->getContentModel() ) {
1365 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1366 'prev' => $this->contentModel
,
1367 'new' => $rev->getContentModel(),
1368 'title' => $this->getTitle()->getPrefixedDBkey(),
1369 'method' => __METHOD__
1371 $this->contentModel
= $rev->getContentModel();
1374 // Given that the content models should match, the current selected
1375 // format should be supported.
1376 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1377 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1379 'prev' => $this->contentFormat
,
1380 'new' => $rev->getContentFormat(),
1381 'title' => $this->getTitle()->getPrefixedDBkey(),
1382 'method' => __METHOD__
1384 $this->contentFormat
= $rev->getContentFormat();
1391 * Use this method before edit() to preload some content into the edit box
1393 * @param Content $content
1397 public function setPreloadedContent( Content
$content ) {
1398 $this->mPreloadContent
= $content;
1402 * Get the contents to be preloaded into the box, either set by
1403 * an earlier setPreloadText() or by loading the given page.
1405 * @param string $preload Representing the title to preload from.
1406 * @param array $params Parameters to use (interface-message style) in the preloaded text
1412 protected function getPreloadedContent( $preload, $params = [] ) {
1413 if ( !empty( $this->mPreloadContent
) ) {
1414 return $this->mPreloadContent
;
1417 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1419 if ( $preload === '' ) {
1420 return $handler->makeEmptyContent();
1423 $user = $this->context
->getUser();
1424 $title = Title
::newFromText( $preload );
1425 # Check for existence to avoid getting MediaWiki:Noarticletext
1426 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1427 // TODO: somehow show a warning to the user!
1428 return $handler->makeEmptyContent();
1431 $page = WikiPage
::factory( $title );
1432 if ( $page->isRedirect() ) {
1433 $title = $page->getRedirectTarget();
1435 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1436 // TODO: somehow show a warning to the user!
1437 return $handler->makeEmptyContent();
1439 $page = WikiPage
::factory( $title );
1442 $parserOptions = ParserOptions
::newFromUser( $user );
1443 $content = $page->getContent( Revision
::RAW
);
1446 // TODO: somehow show a warning to the user!
1447 return $handler->makeEmptyContent();
1450 if ( $content->getModel() !== $handler->getModelID() ) {
1451 $converted = $content->convert( $handler->getModelID() );
1453 if ( !$converted ) {
1454 // TODO: somehow show a warning to the user!
1455 wfDebug( "Attempt to preload incompatible content: " .
1456 "can't convert " . $content->getModel() .
1457 " to " . $handler->getModelID() );
1459 return $handler->makeEmptyContent();
1462 $content = $converted;
1465 return $content->preloadTransform( $title, $parserOptions, $params );
1469 * Make sure the form isn't faking a user's credentials.
1471 * @param WebRequest &$request
1475 public function tokenOk( &$request ) {
1476 $token = $request->getVal( 'wpEditToken' );
1477 $user = $this->context
->getUser();
1478 $this->mTokenOk
= $user->matchEditToken( $token );
1479 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1480 return $this->mTokenOk
;
1484 * Sets post-edit cookie indicating the user just saved a particular revision.
1486 * This uses a temporary cookie for each revision ID so separate saves will never
1487 * interfere with each other.
1489 * Article::view deletes the cookie on server-side after the redirect and
1490 * converts the value to the global JavaScript variable wgPostEdit.
1492 * If the variable were set on the server, it would be cached, which is unwanted
1493 * since the post-edit state should only apply to the load right after the save.
1495 * @param int $statusValue The status value (to check for new article status)
1497 protected function setPostEditCookie( $statusValue ) {
1498 $revisionId = $this->page
->getLatest();
1499 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1502 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1504 } elseif ( $this->oldid
) {
1508 $response = $this->context
->getRequest()->response();
1509 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1513 * Attempt submission
1514 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1515 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1516 * @return Status The resulting status object.
1518 public function attemptSave( &$resultDetails = false ) {
1519 # Allow bots to exempt some edits from bot flagging
1520 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1521 $status = $this->internalAttemptSave( $resultDetails, $bot );
1523 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1529 * Log when a page was successfully saved after the edit conflict view
1531 private function incrementResolvedConflicts() {
1532 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1536 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1537 $stats->increment( 'edit.failures.conflict.resolved' );
1541 * Handle status, such as after attempt save
1543 * @param Status $status
1544 * @param array|bool $resultDetails
1546 * @throws ErrorPageError
1547 * @return bool False, if output is done, true if rest of the form should be displayed
1549 private function handleStatus( Status
$status, $resultDetails ) {
1551 * @todo FIXME: once the interface for internalAttemptSave() is made
1552 * nicer, this should use the message in $status
1554 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1555 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1557 $this->incrementResolvedConflicts();
1559 $this->didSave
= true;
1560 if ( !$resultDetails['nullEdit'] ) {
1561 $this->setPostEditCookie( $status->value
);
1565 $out = $this->context
->getOutput();
1567 // "wpExtraQueryRedirect" is a hidden input to modify
1568 // after save URL and is not used by actual edit form
1569 $request = $this->context
->getRequest();
1570 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1572 switch ( $status->value
) {
1573 case self
::AS_HOOK_ERROR_EXPECTED
:
1574 case self
::AS_CONTENT_TOO_BIG
:
1575 case self
::AS_ARTICLE_WAS_DELETED
:
1576 case self
::AS_CONFLICT_DETECTED
:
1577 case self
::AS_SUMMARY_NEEDED
:
1578 case self
::AS_TEXTBOX_EMPTY
:
1579 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1581 case self
::AS_BLANK_ARTICLE
:
1582 case self
::AS_SELF_REDIRECT
:
1585 case self
::AS_HOOK_ERROR
:
1588 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1589 case self
::AS_PARSE_ERROR
:
1590 case self
::AS_UNICODE_NOT_SUPPORTED
:
1591 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1594 case self
::AS_SUCCESS_NEW_ARTICLE
:
1595 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1596 if ( $extraQueryRedirect ) {
1597 if ( $query === '' ) {
1598 $query = $extraQueryRedirect;
1600 $query = $query . '&' . $extraQueryRedirect;
1603 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1604 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1607 case self
::AS_SUCCESS_UPDATE
:
1609 $sectionanchor = $resultDetails['sectionanchor'];
1611 // Give extensions a chance to modify URL query on update
1613 'ArticleUpdateBeforeRedirect',
1614 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1617 if ( $resultDetails['redirect'] ) {
1618 if ( $extraQuery == '' ) {
1619 $extraQuery = 'redirect=no';
1621 $extraQuery = 'redirect=no&' . $extraQuery;
1624 if ( $extraQueryRedirect ) {
1625 if ( $extraQuery === '' ) {
1626 $extraQuery = $extraQueryRedirect;
1628 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1632 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1635 case self
::AS_SPAM_ERROR
:
1636 $this->spamPageWithContent( $resultDetails['spam'] );
1639 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1640 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1642 case self
::AS_IMAGE_REDIRECT_ANON
:
1643 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1644 throw new PermissionsError( 'upload' );
1646 case self
::AS_READ_ONLY_PAGE_ANON
:
1647 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1648 throw new PermissionsError( 'edit' );
1650 case self
::AS_READ_ONLY_PAGE
:
1651 throw new ReadOnlyError
;
1653 case self
::AS_RATE_LIMITED
:
1654 throw new ThrottledError();
1656 case self
::AS_NO_CREATE_PERMISSION
:
1657 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1658 throw new PermissionsError( $permission );
1660 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1661 throw new PermissionsError( 'editcontentmodel' );
1664 // We don't recognize $status->value. The only way that can happen
1665 // is if an extension hook aborted from inside ArticleSave.
1666 // Render the status object into $this->hookError
1667 // FIXME this sucks, we should just use the Status object throughout
1668 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1675 * Run hooks that can filter edits just before they get saved.
1677 * @param Content $content The Content to filter.
1678 * @param Status $status For reporting the outcome to the caller
1679 * @param User $user The user performing the edit
1683 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1684 // Run old style post-section-merge edit filter
1685 if ( $this->hookError
!= '' ) {
1686 # ...or the hook could be expecting us to produce an error
1687 $status->fatal( 'hookaborted' );
1688 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1692 // Run new style post-section-merge edit filter
1693 if ( !Hooks
::run( 'EditFilterMergedContent',
1694 [ $this->context
, $content, $status, $this->summary
,
1695 $user, $this->minoredit
] )
1697 # Error messages etc. could be handled within the hook...
1698 if ( $status->isGood() ) {
1699 $status->fatal( 'hookaborted' );
1700 // Not setting $this->hookError here is a hack to allow the hook
1701 // to cause a return to the edit page without $this->hookError
1702 // being set. This is used by ConfirmEdit to display a captcha
1703 // without any error message cruft.
1705 $this->hookError
= $status->getWikiText();
1707 // Use the existing $status->value if the hook set it
1708 if ( !$status->value
) {
1709 $status->value
= self
::AS_HOOK_ERROR
;
1712 } elseif ( !$status->isOK() ) {
1713 # ...or the hook could be expecting us to produce an error
1714 // FIXME this sucks, we should just use the Status object throughout
1715 $this->hookError
= $status->getWikiText();
1716 $status->fatal( 'hookaborted' );
1717 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1725 * Return the summary to be used for a new section.
1727 * @param string $sectionanchor Set to the section anchor text
1730 private function newSectionSummary( &$sectionanchor = null ) {
1733 if ( $this->sectiontitle
!== '' ) {
1734 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1735 // If no edit summary was specified, create one automatically from the section
1736 // title and have it link to the new section. Otherwise, respect the summary as
1738 if ( $this->summary
=== '' ) {
1739 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1740 return $this->context
->msg( 'newsectionsummary' )
1741 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1743 } elseif ( $this->summary
!== '' ) {
1744 $sectionanchor = $this->guessSectionName( $this->summary
);
1745 # This is a new section, so create a link to the new section
1746 # in the revision summary.
1747 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1748 return $this->context
->msg( 'newsectionsummary' )
1749 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1751 return $this->summary
;
1755 * Attempt submission (no UI)
1757 * @param array &$result Array to add statuses to, currently with the
1759 * - spam (string): Spam string from content if any spam is detected by
1761 * - sectionanchor (string): Section anchor for a section save.
1762 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1764 * - redirect (bool): Set if doEditContent is OK. True if resulting
1765 * revision is a redirect.
1766 * @param bool $bot True if edit is being made under the bot right.
1768 * @return Status Status object, possibly with a message, but always with
1769 * one of the AS_* constants in $status->value,
1771 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1772 * various error display idiosyncrasies. There are also lots of cases
1773 * where error metadata is set in the object and retrieved later instead
1774 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1775 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1778 public function internalAttemptSave( &$result, $bot = false ) {
1779 $status = Status
::newGood();
1780 $user = $this->context
->getUser();
1782 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1783 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1784 $status->fatal( 'hookaborted' );
1785 $status->value
= self
::AS_HOOK_ERROR
;
1789 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1790 $status->fatal( 'unicode-support-fail' );
1791 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1795 $request = $this->context
->getRequest();
1796 $spam = $request->getText( 'wpAntispam' );
1797 if ( $spam !== '' ) {
1802 $this->mTitle
->getPrefixedText() .
1803 '" submitted bogus field "' .
1807 $status->fatal( 'spamprotectionmatch', false );
1808 $status->value
= self
::AS_SPAM_ERROR
;
1813 # Construct Content object
1814 $textbox_content = $this->toEditContent( $this->textbox1
);
1815 } catch ( MWContentSerializationException
$ex ) {
1817 'content-failed-to-parse',
1818 $this->contentModel
,
1819 $this->contentFormat
,
1822 $status->value
= self
::AS_PARSE_ERROR
;
1826 # Check image redirect
1827 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1828 $textbox_content->isRedirect() &&
1829 !$user->isAllowed( 'upload' )
1831 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1832 $status->setResult( false, $code );
1838 $match = self
::matchSummarySpamRegex( $this->summary
);
1839 if ( $match === false && $this->section
== 'new' ) {
1840 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1841 # regular summaries, it is added to the actual wikitext.
1842 if ( $this->sectiontitle
!== '' ) {
1843 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1844 $match = self
::matchSpamRegex( $this->sectiontitle
);
1846 # This branch is taken when the "Add Topic" user interface is used, or the API
1847 # is used with the 'summary' parameter.
1848 $match = self
::matchSpamRegex( $this->summary
);
1851 if ( $match === false ) {
1852 $match = self
::matchSpamRegex( $this->textbox1
);
1854 if ( $match !== false ) {
1855 $result['spam'] = $match;
1856 $ip = $request->getIP();
1857 $pdbk = $this->mTitle
->getPrefixedDBkey();
1858 $match = str_replace( "\n", '', $match );
1859 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1860 $status->fatal( 'spamprotectionmatch', $match );
1861 $status->value
= self
::AS_SPAM_ERROR
;
1866 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1868 # Error messages etc. could be handled within the hook...
1869 $status->fatal( 'hookaborted' );
1870 $status->value
= self
::AS_HOOK_ERROR
;
1872 } elseif ( $this->hookError
!= '' ) {
1873 # ...or the hook could be expecting us to produce an error
1874 $status->fatal( 'hookaborted' );
1875 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1879 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1880 // Auto-block user's IP if the account was "hard" blocked
1881 if ( !wfReadOnly() ) {
1882 $user->spreadAnyEditBlock();
1884 # Check block state against master, thus 'false'.
1885 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1889 $this->contentLength
= strlen( $this->textbox1
);
1890 $config = $this->context
->getConfig();
1891 $maxArticleSize = $config->get( 'MaxArticleSize' );
1892 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1893 // Error will be displayed by showEditForm()
1894 $this->tooBig
= true;
1895 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1899 if ( !$user->isAllowed( 'edit' ) ) {
1900 if ( $user->isAnon() ) {
1901 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1904 $status->fatal( 'readonlytext' );
1905 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1910 $changingContentModel = false;
1911 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1912 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1913 $status->fatal( 'editpage-cannot-use-custom-model' );
1914 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1916 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1917 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1920 // Make sure the user can edit the page under the new content model too
1921 $titleWithNewContentModel = clone $this->mTitle
;
1922 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1923 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1924 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1926 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1930 $changingContentModel = true;
1931 $oldContentModel = $this->mTitle
->getContentModel();
1934 if ( $this->changeTags
) {
1935 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1936 $this->changeTags
, $user );
1937 if ( !$changeTagsStatus->isOK() ) {
1938 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1939 return $changeTagsStatus;
1943 if ( wfReadOnly() ) {
1944 $status->fatal( 'readonlytext' );
1945 $status->value
= self
::AS_READ_ONLY_PAGE
;
1948 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1949 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1951 $status->fatal( 'actionthrottledtext' );
1952 $status->value
= self
::AS_RATE_LIMITED
;
1956 # If the article has been deleted while editing, don't save it without
1958 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1959 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1963 # Load the page data from the master. If anything changes in the meantime,
1964 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1965 $this->page
->loadPageData( 'fromdbmaster' );
1966 $new = !$this->page
->exists();
1969 // Late check for create permission, just in case *PARANOIA*
1970 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1971 $status->fatal( 'nocreatetext' );
1972 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1973 wfDebug( __METHOD__
. ": no create permission\n" );
1977 // Don't save a new page if it's blank or if it's a MediaWiki:
1978 // message with content equivalent to default (allow empty pages
1979 // in this case to disable messages, see T52124)
1980 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1981 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1982 $defaultText = $defaultMessageText;
1987 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1988 $this->blankArticle
= true;
1989 $status->fatal( 'blankarticle' );
1990 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1994 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
1998 $content = $textbox_content;
2000 $result['sectionanchor'] = '';
2001 if ( $this->section
== 'new' ) {
2002 if ( $this->sectiontitle
!== '' ) {
2003 // Insert the section title above the content.
2004 $content = $content->addSectionHeader( $this->sectiontitle
);
2005 } elseif ( $this->summary
!== '' ) {
2006 // Insert the section title above the content.
2007 $content = $content->addSectionHeader( $this->summary
);
2009 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2012 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2016 # Article exists. Check for edit conflict.
2018 $this->page
->clear(); # Force reload of dates, etc.
2019 $timestamp = $this->page
->getTimestamp();
2020 $latest = $this->page
->getLatest();
2022 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2024 // Check editRevId if set, which handles same-second timestamp collisions
2025 if ( $timestamp != $this->edittime
2026 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2028 $this->isConflict
= true;
2029 if ( $this->section
== 'new' ) {
2030 if ( $this->page
->getUserText() == $user->getName() &&
2031 $this->page
->getComment() == $this->newSectionSummary()
2033 // Probably a duplicate submission of a new comment.
2034 // This can happen when CDN resends a request after
2035 // a timeout but the first one actually went through.
2037 . ": duplicate new section submission; trigger edit conflict!\n" );
2039 // New comment; suppress conflict.
2040 $this->isConflict
= false;
2041 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2043 } elseif ( $this->section
== ''
2044 && Revision
::userWasLastToEdit(
2045 DB_MASTER
, $this->mTitle
->getArticleID(),
2046 $user->getId(), $this->edittime
2049 # Suppress edit conflict with self, except for section edits where merging is required.
2050 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2051 $this->isConflict
= false;
2055 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2056 if ( $this->sectiontitle
!== '' ) {
2057 $sectionTitle = $this->sectiontitle
;
2059 $sectionTitle = $this->summary
;
2064 if ( $this->isConflict
) {
2066 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2067 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2068 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2069 // ...or disable section editing for non-current revisions (not exposed anyway).
2070 if ( $this->editRevId
!== null ) {
2071 $content = $this->page
->replaceSectionAtRev(
2078 $content = $this->page
->replaceSectionContent(
2086 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2087 $content = $this->page
->replaceSectionContent(
2094 if ( is_null( $content ) ) {
2095 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2096 $this->isConflict
= true;
2097 $content = $textbox_content; // do not try to merge here!
2098 } elseif ( $this->isConflict
) {
2100 if ( $this->mergeChangesIntoContent( $content ) ) {
2101 // Successful merge! Maybe we should tell the user the good news?
2102 $this->isConflict
= false;
2103 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2105 $this->section
= '';
2106 $this->textbox1
= ContentHandler
::getContentText( $content );
2107 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2111 if ( $this->isConflict
) {
2112 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2116 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2120 if ( $this->section
== 'new' ) {
2121 // Handle the user preference to force summaries here
2122 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2123 $this->missingSummary
= true;
2124 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2125 $status->value
= self
::AS_SUMMARY_NEEDED
;
2129 // Do not allow the user to post an empty comment
2130 if ( $this->textbox1
== '' ) {
2131 $this->missingComment
= true;
2132 $status->fatal( 'missingcommenttext' );
2133 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2136 } elseif ( !$this->allowBlankSummary
2137 && !$content->equals( $this->getOriginalContent( $user ) )
2138 && !$content->isRedirect()
2139 && md5( $this->summary
) == $this->autoSumm
2141 $this->missingSummary
= true;
2142 $status->fatal( 'missingsummary' );
2143 $status->value
= self
::AS_SUMMARY_NEEDED
;
2148 $sectionanchor = '';
2149 if ( $this->section
== 'new' ) {
2150 $this->summary
= $this->newSectionSummary( $sectionanchor );
2151 } elseif ( $this->section
!= '' ) {
2152 # Try to get a section anchor from the section source, redirect
2153 # to edited section if header found.
2154 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2155 # for duplicate heading checking and maybe parsing.
2156 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2157 # We can't deal with anchors, includes, html etc in the header for now,
2158 # headline would need to be parsed to improve this.
2159 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2160 $sectionanchor = $this->guessSectionName( $matches[2] );
2163 $result['sectionanchor'] = $sectionanchor;
2165 // Save errors may fall down to the edit form, but we've now
2166 // merged the section into full text. Clear the section field
2167 // so that later submission of conflict forms won't try to
2168 // replace that into a duplicated mess.
2169 $this->textbox1
= $this->toEditText( $content );
2170 $this->section
= '';
2172 $status->value
= self
::AS_SUCCESS_UPDATE
;
2175 if ( !$this->allowSelfRedirect
2176 && $content->isRedirect()
2177 && $content->getRedirectTarget()->equals( $this->getTitle() )
2179 // If the page already redirects to itself, don't warn.
2180 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2181 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2182 $this->selfRedirect
= true;
2183 $status->fatal( 'selfredirect' );
2184 $status->value
= self
::AS_SELF_REDIRECT
;
2189 // Check for length errors again now that the section is merged in
2190 $this->contentLength
= strlen( $this->toEditText( $content ) );
2191 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2192 $this->tooBig
= true;
2193 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2197 $flags = EDIT_AUTOSUMMARY |
2198 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2199 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2200 ( $bot ? EDIT_FORCE_BOT
: 0 );
2202 $doEditStatus = $this->page
->doEditContent(
2208 $content->getDefaultFormat(),
2213 if ( !$doEditStatus->isOK() ) {
2214 // Failure from doEdit()
2215 // Show the edit conflict page for certain recognized errors from doEdit(),
2216 // but don't show it for errors from extension hooks
2217 $errors = $doEditStatus->getErrorsArray();
2218 if ( in_array( $errors[0][0],
2219 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2221 $this->isConflict
= true;
2222 // Destroys data doEdit() put in $status->value but who cares
2223 $doEditStatus->value
= self
::AS_END
;
2225 return $doEditStatus;
2228 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2229 if ( $result['nullEdit'] ) {
2230 // We don't know if it was a null edit until now, so increment here
2231 $user->pingLimiter( 'linkpurge' );
2233 $result['redirect'] = $content->isRedirect();
2235 $this->updateWatchlist();
2237 // If the content model changed, add a log entry
2238 if ( $changingContentModel ) {
2239 $this->addContentModelChangeLogEntry(
2241 $new ?
false : $oldContentModel,
2242 $this->contentModel
,
2252 * @param string|false $oldModel false if the page is being newly created
2253 * @param string $newModel
2254 * @param string $reason
2256 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2257 $new = $oldModel === false;
2258 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2259 $log->setPerformer( $user );
2260 $log->setTarget( $this->mTitle
);
2261 $log->setComment( $reason );
2262 $log->setParameters( [
2263 '4::oldmodel' => $oldModel,
2264 '5::newmodel' => $newModel
2266 $logid = $log->insert();
2267 $log->publish( $logid );
2271 * Register the change of watch status
2273 protected function updateWatchlist() {
2274 $user = $this->context
->getUser();
2275 if ( !$user->isLoggedIn() ) {
2279 $title = $this->mTitle
;
2280 $watch = $this->watchthis
;
2281 // Do this in its own transaction to reduce contention...
2282 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2283 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2284 return; // nothing to change
2286 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2291 * Attempts to do 3-way merge of edit content with a base revision
2292 * and current content, in case of edit conflict, in whichever way appropriate
2293 * for the content type.
2297 * @param Content $editContent
2301 private function mergeChangesIntoContent( &$editContent ) {
2302 $db = wfGetDB( DB_MASTER
);
2304 // This is the revision the editor started from
2305 $baseRevision = $this->getBaseRevision();
2306 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2308 if ( is_null( $baseContent ) ) {
2312 // The current state, we want to merge updates into it
2313 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2314 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2316 if ( is_null( $currentContent ) ) {
2320 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2322 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2325 $editContent = $result;
2326 // Update parentRevId to what we just merged.
2327 $this->parentRevId
= $currentRevision->getId();
2335 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2336 * one might think of X as the "base revision", which is NOT what this returns.
2337 * @return Revision Current version when the edit was started
2339 public function getBaseRevision() {
2340 if ( !$this->mBaseRevision
) {
2341 $db = wfGetDB( DB_MASTER
);
2342 $this->mBaseRevision
= $this->editRevId
2343 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2344 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2346 return $this->mBaseRevision
;
2350 * Check given input text against $wgSpamRegex, and return the text of the first match.
2352 * @param string $text
2354 * @return string|bool Matching string or false
2356 public static function matchSpamRegex( $text ) {
2357 global $wgSpamRegex;
2358 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2359 $regexes = (array)$wgSpamRegex;
2360 return self
::matchSpamRegexInternal( $text, $regexes );
2364 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2366 * @param string $text
2368 * @return string|bool Matching string or false
2370 public static function matchSummarySpamRegex( $text ) {
2371 global $wgSummarySpamRegex;
2372 $regexes = (array)$wgSummarySpamRegex;
2373 return self
::matchSpamRegexInternal( $text, $regexes );
2377 * @param string $text
2378 * @param array $regexes
2379 * @return bool|string
2381 protected static function matchSpamRegexInternal( $text, $regexes ) {
2382 foreach ( $regexes as $regex ) {
2384 if ( preg_match( $regex, $text, $matches ) ) {
2391 public function setHeaders() {
2392 $out = $this->context
->getOutput();
2394 $out->addModules( 'mediawiki.action.edit' );
2395 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2397 $user = $this->context
->getUser();
2398 if ( $user->getOption( 'showtoolbar' ) ) {
2399 // The addition of default buttons is handled by getEditToolbar() which
2400 // has its own dependency on this module. The call here ensures the module
2401 // is loaded in time (it has position "top") for other modules to register
2402 // buttons (e.g. extensions, gadgets, user scripts).
2403 $out->addModules( 'mediawiki.toolbar' );
2406 if ( $user->getOption( 'uselivepreview' ) ) {
2407 $out->addModules( 'mediawiki.action.edit.preview' );
2410 if ( $user->getOption( 'useeditwarning' ) ) {
2411 $out->addModules( 'mediawiki.action.edit.editWarning' );
2414 # Enabled article-related sidebar, toplinks, etc.
2415 $out->setArticleRelated( true );
2417 $contextTitle = $this->getContextTitle();
2418 if ( $this->isConflict
) {
2419 $msg = 'editconflict';
2420 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2421 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2423 $msg = $contextTitle->exists()
2424 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2425 && $contextTitle->getDefaultMessageText() !== false
2431 # Use the title defined by DISPLAYTITLE magic word when present
2432 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2433 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2434 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2435 if ( $displayTitle === false ) {
2436 $displayTitle = $contextTitle->getPrefixedText();
2438 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2439 # Transmit the name of the message to JavaScript for live preview
2440 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2441 $out->addJsConfigVars( [
2442 'wgEditMessage' => $msg,
2443 'wgAjaxEditStash' => $this->context
->getConfig()->get( 'AjaxEditStash' ),
2448 * Show all applicable editing introductions
2450 protected function showIntro() {
2451 if ( $this->suppressIntro
) {
2455 $out = $this->context
->getOutput();
2456 $namespace = $this->mTitle
->getNamespace();
2458 if ( $namespace == NS_MEDIAWIKI
) {
2459 # Show a warning if editing an interface message
2460 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2461 # If this is a default message (but not css or js),
2462 # show a hint that it is translatable on translatewiki.net
2463 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2464 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2466 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2467 if ( $defaultMessageText !== false ) {
2468 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2469 'translateinterface' );
2472 } elseif ( $namespace == NS_FILE
) {
2473 # Show a hint to shared repo
2474 $file = wfFindFile( $this->mTitle
);
2475 if ( $file && !$file->isLocal() ) {
2476 $descUrl = $file->getDescriptionUrl();
2477 # there must be a description url to show a hint to shared repo
2479 if ( !$this->mTitle
->exists() ) {
2480 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2481 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2484 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2485 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2492 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2493 # Show log extract when the user is currently blocked
2494 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2495 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2496 $user = User
::newFromName( $username, false /* allow IP users */ );
2497 $ip = User
::isIP( $username );
2498 $block = Block
::newFromTarget( $user, $user );
2499 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2500 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2501 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2502 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2503 # Show log extract if the user is currently blocked
2504 LogEventsList
::showLogExtract(
2507 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2511 'showIfEmpty' => false,
2513 'blocked-notice-logextract',
2514 $user->getName() # Support GENDER in notice
2520 # Try to add a custom edit intro, or use the standard one if this is not possible.
2521 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2522 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2523 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2525 if ( $this->context
->getUser()->isLoggedIn() ) {
2527 // Suppress the external link icon, consider the help url an internal one
2528 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2536 // Suppress the external link icon, consider the help url an internal one
2537 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2539 'newarticletextanon',
2545 # Give a notice if the user is editing a deleted/moved page...
2546 if ( !$this->mTitle
->exists() ) {
2547 $dbr = wfGetDB( DB_REPLICA
);
2549 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2553 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2554 'showIfEmpty' => false,
2555 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2562 * Attempt to show a custom editing introduction, if supplied
2566 protected function showCustomIntro() {
2567 if ( $this->editintro
) {
2568 $title = Title
::newFromText( $this->editintro
);
2569 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2570 // Added using template syntax, to take <noinclude>'s into account.
2571 $this->context
->getOutput()->addWikiTextTitleTidy(
2572 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2582 * Gets an editable textual representation of $content.
2583 * The textual representation can be turned by into a Content object by the
2584 * toEditContent() method.
2586 * If $content is null or false or a string, $content is returned unchanged.
2588 * If the given Content object is not of a type that can be edited using
2589 * the text base EditPage, an exception will be raised. Set
2590 * $this->allowNonTextContent to true to allow editing of non-textual
2593 * @param Content|null|bool|string $content
2594 * @return string The editable text form of the content.
2596 * @throws MWException If $content is not an instance of TextContent and
2597 * $this->allowNonTextContent is not true.
2599 protected function toEditText( $content ) {
2600 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2604 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2605 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2608 return $content->serialize( $this->contentFormat
);
2612 * Turns the given text into a Content object by unserializing it.
2614 * If the resulting Content object is not of a type that can be edited using
2615 * the text base EditPage, an exception will be raised. Set
2616 * $this->allowNonTextContent to true to allow editing of non-textual
2619 * @param string|null|bool $text Text to unserialize
2620 * @return Content|bool|null The content object created from $text. If $text was false
2621 * or null, false resp. null will be returned instead.
2623 * @throws MWException If unserializing the text results in a Content
2624 * object that is not an instance of TextContent and
2625 * $this->allowNonTextContent is not true.
2627 protected function toEditContent( $text ) {
2628 if ( $text === false ||
$text === null ) {
2632 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2633 $this->contentModel
, $this->contentFormat
);
2635 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2636 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2643 * Send the edit form and related headers to OutputPage
2644 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2645 * during form output near the top, for captchas and the like.
2647 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2648 * use the EditPage::showEditForm:fields hook instead.
2650 public function showEditForm( $formCallback = null ) {
2651 # need to parse the preview early so that we know which templates are used,
2652 # otherwise users with "show preview after edit box" will get a blank list
2653 # we parse this near the beginning so that setHeaders can do the title
2654 # setting work instead of leaving it in getPreviewText
2655 $previewOutput = '';
2656 if ( $this->formtype
== 'preview' ) {
2657 $previewOutput = $this->getPreviewText();
2660 $out = $this->context
->getOutput();
2662 // Avoid PHP 7.1 warning of passing $this by reference
2664 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2666 $this->setHeaders();
2668 $this->addTalkPageText();
2669 $this->addEditNotices();
2671 if ( !$this->isConflict
&&
2672 $this->section
!= '' &&
2673 !$this->isSectionEditSupported() ) {
2674 // We use $this->section to much before this and getVal('wgSection') directly in other places
2675 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2676 // Someone is welcome to try refactoring though
2677 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2681 $this->showHeader();
2683 $out->addHTML( $this->editFormPageTop
);
2685 $user = $this->context
->getUser();
2686 if ( $user->getOption( 'previewontop' ) ) {
2687 $this->displayPreviewArea( $previewOutput, true );
2690 $out->addHTML( $this->editFormTextTop
);
2692 $showToolbar = true;
2693 if ( $this->wasDeletedSinceLastEdit() ) {
2694 if ( $this->formtype
== 'save' ) {
2695 // Hide the toolbar and edit area, user can click preview to get it back
2696 // Add an confirmation checkbox and explanation.
2697 $showToolbar = false;
2699 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2700 'deletedwhileediting' );
2704 // @todo add EditForm plugin interface and use it here!
2705 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2706 $out->addHTML( Html
::openElement(
2709 'class' => 'mw-editform',
2710 'id' => self
::EDITFORM_ID
,
2711 'name' => self
::EDITFORM_ID
,
2713 'action' => $this->getActionURL( $this->getContextTitle() ),
2714 'enctype' => 'multipart/form-data'
2718 if ( is_callable( $formCallback ) ) {
2719 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2720 call_user_func_array( $formCallback, [ &$out ] );
2723 // Add a check for Unicode support
2724 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2726 // Add an empty field to trip up spambots
2728 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2731 [ 'for' => 'wpAntispam' ],
2732 $this->context
->msg( 'simpleantispam-label' )->parse()
2738 'name' => 'wpAntispam',
2739 'id' => 'wpAntispam',
2743 . Xml
::closeElement( 'div' )
2746 // Avoid PHP 7.1 warning of passing $this by reference
2748 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2750 // Put these up at the top to ensure they aren't lost on early form submission
2751 $this->showFormBeforeText();
2753 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2754 $username = $this->lastDelete
->user_name
;
2755 $comment = CommentStore
::newKey( 'log_comment' )->getComment( $this->lastDelete
)->text
;
2757 // It is better to not parse the comment at all than to have templates expanded in the middle
2758 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2759 $key = $comment === ''
2760 ?
'confirmrecreate-noreason'
2761 : 'confirmrecreate';
2763 '<div class="mw-confirm-recreate">' .
2764 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2765 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2766 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2772 # When the summary is hidden, also hide them on preview/show changes
2773 if ( $this->nosummary
) {
2774 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2777 # If a blank edit summary was previously provided, and the appropriate
2778 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2779 # user being bounced back more than once in the event that a summary
2782 # For a bit more sophisticated detection of blank summaries, hash the
2783 # automatic one and pass that in the hidden field wpAutoSummary.
2784 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2785 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2788 if ( $this->undidRev
) {
2789 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2792 if ( $this->selfRedirect
) {
2793 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2796 if ( $this->hasPresetSummary
) {
2797 // If a summary has been preset using &summary= we don't want to prompt for
2798 // a different summary. Only prompt for a summary if the summary is blanked.
2800 $this->autoSumm
= md5( '' );
2803 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2804 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2806 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2807 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2809 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2810 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2814 if ( $this->section
== 'new' ) {
2815 $this->showSummaryInput( true, $this->summary
);
2816 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2819 $out->addHTML( $this->editFormTextBeforeContent
);
2821 if ( !$this->mTitle
->isCssJsSubpage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2822 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2825 if ( $this->blankArticle
) {
2826 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2829 if ( $this->isConflict
) {
2830 // In an edit conflict bypass the overridable content form method
2831 // and fallback to the raw wpTextbox1 since editconflicts can't be
2832 // resolved between page source edits and custom ui edits using the
2834 $this->textbox2
= $this->textbox1
;
2836 $content = $this->getCurrentContent();
2837 $this->textbox1
= $this->toEditText( $content );
2839 $this->showTextbox1();
2841 $this->showContentForm();
2844 $out->addHTML( $this->editFormTextAfterContent
);
2846 $this->showStandardInputs();
2848 $this->showFormAfterText();
2850 $this->showTosSummary();
2852 $this->showEditTools();
2854 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2856 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2858 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2859 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2861 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2862 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2864 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2866 if ( $this->isConflict
) {
2868 $this->showConflict();
2869 } catch ( MWContentSerializationException
$ex ) {
2870 // this can't really happen, but be nice if it does.
2871 $msg = $this->context
->msg(
2872 'content-failed-to-parse',
2873 $this->contentModel
,
2874 $this->contentFormat
,
2877 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2881 // Set a hidden field so JS knows what edit form mode we are in
2882 if ( $this->isConflict
) {
2884 } elseif ( $this->preview
) {
2886 } elseif ( $this->diff
) {
2891 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2893 // Marker for detecting truncated form data. This must be the last
2894 // parameter sent in order to be of use, so do not move me.
2895 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2896 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2898 if ( !$user->getOption( 'previewontop' ) ) {
2899 $this->displayPreviewArea( $previewOutput, false );
2904 * Wrapper around TemplatesOnThisPageFormatter to make
2905 * a "templates on this page" list.
2907 * @param Title[] $templates
2908 * @return string HTML
2910 public function makeTemplatesOnThisPageList( array $templates ) {
2911 $templateListFormatter = new TemplatesOnThisPageFormatter(
2912 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2915 // preview if preview, else section if section, else false
2917 if ( $this->preview
) {
2919 } elseif ( $this->section
!= '' ) {
2923 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2924 $templateListFormatter->format( $templates, $type )
2929 * Extract the section title from current section text, if any.
2931 * @param string $text
2932 * @return string|bool String or false
2934 public static function extractSectionTitle( $text ) {
2935 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2936 if ( !empty( $matches[2] ) ) {
2938 return $wgParser->stripSectionName( trim( $matches[2] ) );
2944 protected function showHeader() {
2945 $out = $this->context
->getOutput();
2946 $user = $this->context
->getUser();
2947 if ( $this->isConflict
) {
2948 $this->addExplainConflictHeader( $out );
2949 $this->editRevId
= $this->page
->getLatest();
2951 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2952 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2953 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2954 if ( $sectionTitle !== false ) {
2955 $this->summary
= "/* $sectionTitle */ ";
2960 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
2962 if ( $this->missingComment
) {
2963 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2966 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2968 "<div id='mw-missingsummary'>\n$1\n</div>",
2969 [ 'missingsummary', $buttonLabel ]
2973 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2975 "<div id='mw-missingcommentheader'>\n$1\n</div>",
2976 [ 'missingcommentheader', $buttonLabel ]
2980 if ( $this->blankArticle
) {
2982 "<div id='mw-blankarticle'>\n$1\n</div>",
2983 [ 'blankarticle', $buttonLabel ]
2987 if ( $this->selfRedirect
) {
2989 "<div id='mw-selfredirect'>\n$1\n</div>",
2990 [ 'selfredirect', $buttonLabel ]
2994 if ( $this->hookError
!== '' ) {
2995 $out->addWikiText( $this->hookError
);
2998 if ( $this->section
!= 'new' ) {
2999 $revision = $this->mArticle
->getRevisionFetched();
3001 // Let sysop know that this will make private content public if saved
3003 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3005 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3006 'rev-deleted-text-permission'
3008 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3010 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3011 'rev-deleted-text-view'
3015 if ( !$revision->isCurrent() ) {
3016 $this->mArticle
->setOldSubtitle( $revision->getId() );
3017 $out->addWikiMsg( 'editingold' );
3018 $this->isOldRev
= true;
3020 } elseif ( $this->mTitle
->exists() ) {
3021 // Something went wrong
3023 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3024 [ 'missing-revision', $this->oldid
] );
3029 if ( wfReadOnly() ) {
3031 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3032 [ 'readonlywarning', wfReadOnlyReason() ]
3034 } elseif ( $user->isAnon() ) {
3035 if ( $this->formtype
!= 'preview' ) {
3037 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3038 [ 'anoneditwarning',
3040 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3041 'returnto' => $this->getTitle()->getPrefixedDBkey()
3044 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3045 'returnto' => $this->getTitle()->getPrefixedDBkey()
3050 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3051 'anonpreviewwarning'
3055 if ( $this->mTitle
->isCssJsSubpage() ) {
3056 # Check the skin exists
3057 if ( $this->isWrongCaseCssJsPage() ) {
3059 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
3060 [ 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ]
3063 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3064 $isCssSubpage = $this->mTitle
->isCssSubpage();
3065 $out->wrapWikiMsg( '<div class="mw-usercssjspublic">$1</div>',
3066 $isCssSubpage ?
'usercssispublic' : 'userjsispublic'
3068 if ( $this->formtype
!== 'preview' ) {
3069 $config = $this->context
->getConfig();
3070 if ( $isCssSubpage && $config->get( 'AllowUserCss' ) ) {
3072 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3073 [ 'usercssyoucanpreview' ]
3077 if ( $this->mTitle
->isJsSubpage() && $config->get( 'AllowUserJs' ) ) {
3079 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3080 [ 'userjsyoucanpreview' ]
3088 $this->addPageProtectionWarningHeaders();
3090 $this->addLongPageWarningHeader();
3092 # Add header copyright warning
3093 $this->showHeaderCopyrightWarning();
3097 * Helper function for summary input functions, which returns the neccessary
3098 * attributes for the input.
3100 * @param array|null $inputAttrs Array of attrs to use on the input
3103 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3104 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
3105 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3106 'id' => 'wpSummary',
3107 'name' => 'wpSummary',
3108 'maxlength' => '200',
3111 'spellcheck' => 'true',
3116 * Standard summary input and label (wgSummary), abstracted so EditPage
3117 * subclasses may reorganize the form.
3118 * Note that you do not need to worry about the label's for=, it will be
3119 * inferred by the id given to the input. You can remove them both by
3120 * passing [ 'id' => false ] to $userInputAttrs.
3122 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3123 * @param string $summary The value of the summary input
3124 * @param string $labelText The html to place inside the label
3125 * @param array $inputAttrs Array of attrs to use on the input
3126 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
3127 * @return array An array in the format [ $label, $input ]
3129 public function getSummaryInput( $summary = "", $labelText = null,
3130 $inputAttrs = null, $spanLabelAttrs = null
3132 wfDeprecated( __METHOD__
, '1.30' );
3133 $inputAttrs = $this->getSummaryInputAttributes( $inputAttrs );
3134 $inputAttrs +
= Linker
::tooltipAndAccesskeyAttribs( 'summary' );
3136 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : [] ) +
[
3137 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
3138 'id' => "wpSummaryLabel"
3145 $inputAttrs['id'] ?
[ 'for' => $inputAttrs['id'] ] : null,
3148 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
3151 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
3153 return [ $label, $input ];
3157 * Builds a standard summary input with a label.
3159 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3160 * @param string $summary The value of the summary input
3161 * @param string $labelText The html to place inside the label
3162 * @param array $inputAttrs Array of attrs to use on the input
3164 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3166 function getSummaryInputOOUI( $summary = "", $labelText = null, $inputAttrs = null ) {
3167 wfDeprecated( __METHOD__
, '1.30' );
3168 $this->getSummaryInputWidget( $summary, $labelText, $inputAttrs );
3172 * Builds a standard summary input with a label.
3174 * @param string $summary The value of the summary input
3175 * @param string $labelText The html to place inside the label
3176 * @param array $inputAttrs Array of attrs to use on the input
3178 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3180 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3181 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3182 $this->getSummaryInputAttributes( $inputAttrs )
3185 'title' => Linker
::titleAttrib( 'summary' ),
3186 'accessKey' => Linker
::accesskey( 'summary' ),
3189 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3190 $inputAttrs['inputId'] = $inputAttrs['id'];
3191 $inputAttrs['id'] = 'wpSummaryWidget';
3193 return new OOUI\
FieldLayout(
3194 new OOUI\
TextInputWidget( [
3195 'value' => $summary,
3196 'infusable' => true,
3199 'label' => new OOUI\
HtmlSnippet( $labelText ),
3201 'id' => 'wpSummaryLabel',
3202 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3208 * @param bool $isSubjectPreview True if this is the section subject/title
3209 * up top, or false if this is the comment summary
3210 * down below the textarea
3211 * @param string $summary The text of the summary to display
3213 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3214 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3215 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3216 if ( $isSubjectPreview ) {
3217 if ( $this->nosummary
) {
3221 if ( !$this->mShowSummaryField
) {
3226 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3227 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3230 [ 'class' => $summaryClass ]
3235 * @param bool $isSubjectPreview True if this is the section subject/title
3236 * up top, or false if this is the comment summary
3237 * down below the textarea
3238 * @param string $summary The text of the summary to display
3241 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3242 // avoid spaces in preview, gets always trimmed on save
3243 $summary = trim( $summary );
3244 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3250 if ( $isSubjectPreview ) {
3251 $summary = $this->context
->msg( 'newsectionsummary' )
3252 ->rawParams( $wgParser->stripSectionName( $summary ) )
3253 ->inContentLanguage()->text();
3256 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3258 $summary = $this->context
->msg( $message )->parse()
3259 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3260 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3263 protected function showFormBeforeText() {
3264 $out = $this->context
->getOutput();
3265 $out->addHTML( Html
::hidden( 'wpSection', htmlspecialchars( $this->section
) ) );
3266 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3267 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3268 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3269 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3272 protected function showFormAfterText() {
3274 * To make it harder for someone to slip a user a page
3275 * which submits an edit form to the wiki without their
3276 * knowledge, a random token is associated with the login
3277 * session. If it's not passed back with the submission,
3278 * we won't save the page, or render user JavaScript and
3281 * For anon editors, who may not have a session, we just
3282 * include the constant suffix to prevent editing from
3283 * broken text-mangling proxies.
3285 $this->context
->getOutput()->addHTML(
3287 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3293 * Subpage overridable method for printing the form for page content editing
3294 * By default this simply outputs wpTextbox1
3295 * Subclasses can override this to provide a custom UI for editing;
3296 * be it a form, or simply wpTextbox1 with a modified content that will be
3297 * reverse modified when extracted from the post data.
3298 * Note that this is basically the inverse for importContentFormData
3300 protected function showContentForm() {
3301 $this->showTextbox1();
3305 * Method to output wpTextbox1
3306 * The $textoverride method can be used by subclasses overriding showContentForm
3307 * to pass back to this method.
3309 * @param array $customAttribs Array of html attributes to use in the textarea
3310 * @param string $textoverride Optional text to override $this->textarea1 with
3312 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3313 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3314 $attribs = [ 'style' => 'display:none;' ];
3316 $classes = []; // Textarea CSS
3317 if ( $this->mTitle
->isProtected( 'edit' ) &&
3318 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
3320 # Is the title semi-protected?
3321 if ( $this->mTitle
->isSemiProtected() ) {
3322 $classes[] = 'mw-textarea-sprotected';
3324 # Then it must be protected based on static groups (regular)
3325 $classes[] = 'mw-textarea-protected';
3327 # Is the title cascade-protected?
3328 if ( $this->mTitle
->isCascadeProtected() ) {
3329 $classes[] = 'mw-textarea-cprotected';
3332 # Is an old revision being edited?
3333 if ( $this->isOldRev
) {
3334 $classes[] = 'mw-textarea-oldrev';
3337 $attribs = [ 'tabindex' => 1 ];
3339 if ( is_array( $customAttribs ) ) {
3340 $attribs +
= $customAttribs;
3343 if ( count( $classes ) ) {
3344 if ( isset( $attribs['class'] ) ) {
3345 $classes[] = $attribs['class'];
3347 $attribs['class'] = implode( ' ', $classes );
3352 $textoverride !== null ?
$textoverride : $this->textbox1
,
3358 protected function showTextbox2() {
3359 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3362 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3363 $wikitext = $this->addNewLineAtEnd( $text );
3365 $attribs = $this->buildTextboxAttribs( $name, $customAttribs, $this->context
->getUser() );
3367 $this->context
->getOutput()->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3370 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3373 $classes[] = 'ontop';
3376 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3378 if ( $this->formtype
!= 'preview' ) {
3379 $attribs['style'] = 'display: none;';
3382 $out = $this->context
->getOutput();
3383 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3385 if ( $this->formtype
== 'preview' ) {
3386 $this->showPreview( $previewOutput );
3388 // Empty content container for LivePreview
3389 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3390 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3391 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3392 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3395 $out->addHTML( '</div>' );
3397 if ( $this->formtype
== 'diff' ) {
3400 } catch ( MWContentSerializationException
$ex ) {
3401 $msg = $this->context
->msg(
3402 'content-failed-to-parse',
3403 $this->contentModel
,
3404 $this->contentFormat
,
3407 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3413 * Append preview output to OutputPage.
3414 * Includes category rendering if this is a category page.
3416 * @param string $text The HTML to be output for the preview.
3418 protected function showPreview( $text ) {
3419 if ( $this->mArticle
instanceof CategoryPage
) {
3420 $this->mArticle
->openShowCategory();
3422 # This hook seems slightly odd here, but makes things more
3423 # consistent for extensions.
3424 $out = $this->context
->getOutput();
3425 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3426 $out->addHTML( $text );
3427 if ( $this->mArticle
instanceof CategoryPage
) {
3428 $this->mArticle
->closeShowCategory();
3433 * Get a diff between the current contents of the edit box and the
3434 * version of the page we're editing from.
3436 * If this is a section edit, we'll replace the section as for final
3437 * save and then make a comparison.
3439 public function showDiff() {
3442 $oldtitlemsg = 'currentrev';
3443 # if message does not exist, show diff against the preloaded default
3444 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3445 $oldtext = $this->mTitle
->getDefaultMessageText();
3446 if ( $oldtext !== false ) {
3447 $oldtitlemsg = 'defaultmessagetext';
3448 $oldContent = $this->toEditContent( $oldtext );
3453 $oldContent = $this->getCurrentContent();
3456 $textboxContent = $this->toEditContent( $this->textbox1
);
3457 if ( $this->editRevId
!== null ) {
3458 $newContent = $this->page
->replaceSectionAtRev(
3459 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3462 $newContent = $this->page
->replaceSectionContent(
3463 $this->section
, $textboxContent, $this->summary
, $this->edittime
3467 if ( $newContent ) {
3468 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3470 $user = $this->context
->getUser();
3471 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
3472 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3475 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3476 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3477 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3479 if ( !$oldContent ) {
3480 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3483 if ( !$newContent ) {
3484 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3487 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3488 $de->setContent( $oldContent, $newContent );
3490 $difftext = $de->getDiff( $oldtitle, $newtitle );
3491 $de->showDiffStyle();
3496 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3500 * Show the header copyright warning.
3502 protected function showHeaderCopyrightWarning() {
3503 $msg = 'editpage-head-copy-warn';
3504 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3505 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3506 'editpage-head-copy-warn' );
3511 * Give a chance for site and per-namespace customizations of
3512 * terms of service summary link that might exist separately
3513 * from the copyright notice.
3515 * This will display between the save button and the edit tools,
3516 * so should remain short!
3518 protected function showTosSummary() {
3519 $msg = 'editpage-tos-summary';
3520 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3521 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3522 $out = $this->context
->getOutput();
3523 $out->addHTML( '<div class="mw-tos-summary">' );
3524 $out->addWikiMsg( $msg );
3525 $out->addHTML( '</div>' );
3530 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3531 * characters not present on most keyboards for copying/pasting.
3533 protected function showEditTools() {
3534 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3535 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3540 * Get the copyright warning
3542 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3545 protected function getCopywarn() {
3546 return self
::getCopyrightWarning( $this->mTitle
);
3550 * Get the copyright warning, by default returns wikitext
3552 * @param Title $title
3553 * @param string $format Output format, valid values are any function of a Message object
3554 * @param Language|string|null $langcode Language code or Language object.
3557 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3558 global $wgRightsText;
3559 if ( $wgRightsText ) {
3560 $copywarnMsg = [ 'copyrightwarning',
3561 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3564 $copywarnMsg = [ 'copyrightwarning2',
3565 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3567 // Allow for site and per-namespace customization of contribution/copyright notice.
3568 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3570 $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
3572 $msg->inLanguage( $langcode );
3574 return "<div id=\"editpage-copywarn\">\n" .
3575 $msg->$format() . "\n</div>";
3579 * Get the Limit report for page previews
3582 * @param ParserOutput $output ParserOutput object from the parse
3583 * @return string HTML
3585 public static function getPreviewLimitReport( $output ) {
3586 if ( !$output ||
!$output->getLimitReportData() ) {
3590 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3591 wfMessage( 'limitreport-title' )->parseAsBlock()
3594 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3595 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3597 $limitReport .= Html
::openElement( 'table', [
3598 'class' => 'preview-limit-report wikitable'
3600 Html
::openElement( 'tbody' );
3602 foreach ( $output->getLimitReportData() as $key => $value ) {
3603 if ( Hooks
::run( 'ParserLimitReportFormat',
3604 [ $key, &$value, &$limitReport, true, true ]
3606 $keyMsg = wfMessage( $key );
3607 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3608 if ( !$valueMsg->exists() ) {
3609 $valueMsg = new RawMessage( '$1' );
3611 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3612 $limitReport .= Html
::openElement( 'tr' ) .
3613 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3614 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3615 Html
::closeElement( 'tr' );
3620 $limitReport .= Html
::closeElement( 'tbody' ) .
3621 Html
::closeElement( 'table' ) .
3622 Html
::closeElement( 'div' );
3624 return $limitReport;
3627 protected function showStandardInputs( &$tabindex = 2 ) {
3628 $out = $this->context
->getOutput();
3629 $out->addHTML( "<div class='editOptions'>\n" );
3631 if ( $this->section
!= 'new' ) {
3632 $this->showSummaryInput( false, $this->summary
);
3633 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3636 $checkboxes = $this->getCheckboxesWidget(
3638 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3640 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3642 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3644 // Show copyright warning.
3645 $out->addWikiText( $this->getCopywarn() );
3646 $out->addHTML( $this->editFormTextAfterWarn
);
3648 $out->addHTML( "<div class='editButtons'>\n" );
3649 $out->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3651 $cancel = $this->getCancelLink();
3652 if ( $cancel !== '' ) {
3653 $cancel .= Html
::element( 'span',
3654 [ 'class' => 'mw-editButtons-pipe-separator' ],
3655 $this->context
->msg( 'pipe-separator' )->text() );
3658 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3659 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3662 $this->context
->msg( 'edithelp' )->text(),
3663 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3666 $this->context
->msg( 'word-separator' )->escaped() .
3667 $this->context
->msg( 'newwindow' )->parse();
3669 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3670 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3671 $out->addHTML( "</div><!-- editButtons -->\n" );
3673 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3675 $out->addHTML( "</div><!-- editOptions -->\n" );
3679 * Show an edit conflict. textbox1 is already shown in showEditForm().
3680 * If you want to use another entry point to this function, be careful.
3682 protected function showConflict() {
3683 $out = $this->context
->getOutput();
3684 // Avoid PHP 7.1 warning of passing $this by reference
3686 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3687 $this->incrementConflictStats();
3689 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3691 $content1 = $this->toEditContent( $this->textbox1
);
3692 $content2 = $this->toEditContent( $this->textbox2
);
3694 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3695 $de = $handler->createDifferenceEngine( $this->context
);
3696 $de->setContent( $content2, $content1 );
3698 $this->context
->msg( 'yourtext' )->parse(),
3699 $this->context
->msg( 'storedversion' )->text()
3702 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3703 $this->showTextbox2();
3707 protected function incrementConflictStats() {
3708 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3709 $stats->increment( 'edit.failures.conflict' );
3710 // Only include 'standard' namespaces to avoid creating unknown numbers of statsd metrics
3712 $this->mTitle
->getNamespace() >= NS_MAIN
&&
3713 $this->mTitle
->getNamespace() <= NS_CATEGORY_TALK
3715 $stats->increment( 'edit.failures.conflict.byNamespaceId.' . $this->mTitle
->getNamespace() );
3722 public function getCancelLink() {
3724 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3725 $cancelParams['oldid'] = $this->oldid
;
3726 } elseif ( $this->getContextTitle()->isRedirect() ) {
3727 $cancelParams['redirect'] = 'no';
3730 return new OOUI\
ButtonWidget( [
3731 'id' => 'mw-editform-cancel',
3732 'href' => $this->getContextTitle()->getLinkUrl( $cancelParams ),
3733 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3735 'infusable' => true,
3736 'flags' => 'destructive',
3741 * Returns the URL to use in the form's action attribute.
3742 * This is used by EditPage subclasses when simply customizing the action
3743 * variable in the constructor is not enough. This can be used when the
3744 * EditPage lives inside of a Special page rather than a custom page action.
3746 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3749 protected function getActionURL( Title
$title ) {
3750 return $title->getLocalURL( [ 'action' => $this->action
] );
3754 * Check if a page was deleted while the user was editing it, before submit.
3755 * Note that we rely on the logging table, which hasn't been always there,
3756 * but that doesn't matter, because this only applies to brand new
3760 protected function wasDeletedSinceLastEdit() {
3761 if ( $this->deletedSinceEdit
!== null ) {
3762 return $this->deletedSinceEdit
;
3765 $this->deletedSinceEdit
= false;
3767 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3768 $this->lastDelete
= $this->getLastDelete();
3769 if ( $this->lastDelete
) {
3770 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3771 if ( $deleteTime > $this->starttime
) {
3772 $this->deletedSinceEdit
= true;
3777 return $this->deletedSinceEdit
;
3781 * @return bool|stdClass
3783 protected function getLastDelete() {
3784 $dbr = wfGetDB( DB_REPLICA
);
3785 $commentQuery = CommentStore
::newKey( 'log_comment' )->getJoin();
3786 $data = $dbr->selectRow(
3787 [ 'logging', 'user' ] +
$commentQuery['tables'],
3798 ] +
$commentQuery['fields'], [
3799 'log_namespace' => $this->mTitle
->getNamespace(),
3800 'log_title' => $this->mTitle
->getDBkey(),
3801 'log_type' => 'delete',
3802 'log_action' => 'delete',
3806 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3808 'user' => [ 'JOIN', 'user_id=log_user' ],
3809 ] +
$commentQuery['joins']
3811 // Quick paranoid permission checks...
3812 if ( is_object( $data ) ) {
3813 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3814 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3817 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3818 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3819 $data->log_comment_data
= null;
3827 * Get the rendered text for previewing.
3828 * @throws MWException
3831 public function getPreviewText() {
3832 $out = $this->context
->getOutput();
3833 $config = $this->context
->getConfig();
3835 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3836 // Could be an offsite preview attempt. This is very unsafe if
3837 // HTML is enabled, as it could be an attack.
3839 if ( $this->textbox1
!== '' ) {
3840 // Do not put big scary notice, if previewing the empty
3841 // string, which happens when you initially edit
3842 // a category page, due to automatic preview-on-open.
3843 $parsedNote = $out->parse( "<div class='previewnote'>" .
3844 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3845 true, /* interface */true );
3847 $this->incrementEditFailureStats( 'session_loss' );
3854 $content = $this->toEditContent( $this->textbox1
);
3858 'AlternateEditPreview',
3859 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3861 return $previewHTML;
3864 # provide a anchor link to the editform
3865 $continueEditing = '<span class="mw-continue-editing">' .
3866 '[[#' . self
::EDITFORM_ID
. '|' .
3867 $this->context
->getLanguage()->getArrow() . ' ' .
3868 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3869 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3870 if ( $this->mTokenOkExceptSuffix
) {
3871 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3872 $this->incrementEditFailureStats( 'bad_token' );
3874 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3875 $this->incrementEditFailureStats( 'session_loss' );
3877 } elseif ( $this->incompleteForm
) {
3878 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3879 if ( $this->mTriedSave
) {
3880 $this->incrementEditFailureStats( 'incomplete_form' );
3883 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3886 # don't parse non-wikitext pages, show message about preview
3887 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3888 if ( $this->mTitle
->isCssJsSubpage() ) {
3890 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3896 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3898 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3901 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3903 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3910 # Used messages to make sure grep find them:
3911 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3912 if ( $level && $format ) {
3913 $note = "<div id='mw-{$level}{$format}preview'>" .
3914 $this->context
->msg( "{$level}{$format}preview" )->text() .
3915 ' ' . $continueEditing . "</div>";
3919 # If we're adding a comment, we need to show the
3920 # summary as the headline
3921 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3922 $content = $content->addSectionHeader( $this->summary
);
3925 $hook_args = [ $this, &$content ];
3926 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3928 $parserResult = $this->doPreviewParse( $content );
3929 $parserOutput = $parserResult['parserOutput'];
3930 $previewHTML = $parserResult['html'];
3931 $this->mParserOutput
= $parserOutput;
3932 $out->addParserOutputMetadata( $parserOutput );
3934 if ( count( $parserOutput->getWarnings() ) ) {
3935 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3938 } catch ( MWContentSerializationException
$ex ) {
3939 $m = $this->context
->msg(
3940 'content-failed-to-parse',
3941 $this->contentModel
,
3942 $this->contentFormat
,
3945 $note .= "\n\n" . $m->parse();
3949 if ( $this->isConflict
) {
3950 $conflict = '<h2 id="mw-previewconflict">'
3951 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3953 $conflict = '<hr />';
3956 $previewhead = "<div class='previewnote'>\n" .
3957 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3958 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3960 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3961 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3962 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3963 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3965 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3968 private function incrementEditFailureStats( $failureType ) {
3969 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3970 $stats->increment( 'edit.failures.' . $failureType );
3974 * Get parser options for a preview
3975 * @return ParserOptions
3977 protected function getPreviewParserOptions() {
3978 $parserOptions = $this->page
->makeParserOptions( $this->context
);
3979 $parserOptions->setIsPreview( true );
3980 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3981 $parserOptions->enableLimitReport();
3982 return $parserOptions;
3986 * Parse the page for a preview. Subclasses may override this class, in order
3987 * to parse with different options, or to otherwise modify the preview HTML.
3989 * @param Content $content The page content
3990 * @return array with keys:
3991 * - parserOutput: The ParserOutput object
3992 * - html: The HTML to be displayed
3994 protected function doPreviewParse( Content
$content ) {
3995 $user = $this->context
->getUser();
3996 $parserOptions = $this->getPreviewParserOptions();
3997 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
3998 $scopedCallback = $parserOptions->setupFakeRevision(
3999 $this->mTitle
, $pstContent, $user );
4000 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
4001 ScopedCallback
::consume( $scopedCallback );
4002 $parserOutput->setEditSectionTokens( false ); // no section edit links
4004 'parserOutput' => $parserOutput,
4005 'html' => $parserOutput->getText() ];
4011 public function getTemplates() {
4012 if ( $this->preview ||
$this->section
!= '' ) {
4014 if ( !isset( $this->mParserOutput
) ) {
4017 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
4018 foreach ( array_keys( $template ) as $dbk ) {
4019 $templates[] = Title
::makeTitle( $ns, $dbk );
4024 return $this->mTitle
->getTemplateLinksFrom();
4029 * Shows a bulletin board style toolbar for common editing functions.
4030 * It can be disabled in the user preferences.
4032 * @param Title $title Title object for the page being edited (optional)
4035 public static function getEditToolbar( $title = null ) {
4036 global $wgContLang, $wgOut;
4037 global $wgEnableUploads, $wgForeignFileRepos;
4039 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
4040 $showSignature = true;
4042 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4046 * $toolarray is an array of arrays each of which includes the
4047 * opening tag, the closing tag, optionally a sample text that is
4048 * inserted between the two when no selection is highlighted
4049 * and. The tip text is shown when the user moves the mouse
4052 * Images are defined in ResourceLoaderEditToolbarModule.
4056 'id' => 'mw-editbutton-bold',
4058 'close' => '\'\'\'',
4059 'sample' => wfMessage( 'bold_sample' )->text(),
4060 'tip' => wfMessage( 'bold_tip' )->text(),
4063 'id' => 'mw-editbutton-italic',
4066 'sample' => wfMessage( 'italic_sample' )->text(),
4067 'tip' => wfMessage( 'italic_tip' )->text(),
4070 'id' => 'mw-editbutton-link',
4073 'sample' => wfMessage( 'link_sample' )->text(),
4074 'tip' => wfMessage( 'link_tip' )->text(),
4077 'id' => 'mw-editbutton-extlink',
4080 'sample' => wfMessage( 'extlink_sample' )->text(),
4081 'tip' => wfMessage( 'extlink_tip' )->text(),
4084 'id' => 'mw-editbutton-headline',
4087 'sample' => wfMessage( 'headline_sample' )->text(),
4088 'tip' => wfMessage( 'headline_tip' )->text(),
4090 $imagesAvailable ?
[
4091 'id' => 'mw-editbutton-image',
4092 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4094 'sample' => wfMessage( 'image_sample' )->text(),
4095 'tip' => wfMessage( 'image_tip' )->text(),
4097 $imagesAvailable ?
[
4098 'id' => 'mw-editbutton-media',
4099 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4101 'sample' => wfMessage( 'media_sample' )->text(),
4102 'tip' => wfMessage( 'media_tip' )->text(),
4105 'id' => 'mw-editbutton-nowiki',
4106 'open' => "<nowiki>",
4107 'close' => "</nowiki>",
4108 'sample' => wfMessage( 'nowiki_sample' )->text(),
4109 'tip' => wfMessage( 'nowiki_tip' )->text(),
4112 'id' => 'mw-editbutton-signature',
4113 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4116 'tip' => wfMessage( 'sig_tip' )->text(),
4119 'id' => 'mw-editbutton-hr',
4120 'open' => "\n----\n",
4123 'tip' => wfMessage( 'hr_tip' )->text(),
4127 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4128 foreach ( $toolarray as $tool ) {
4134 // Images are defined in ResourceLoaderEditToolbarModule
4136 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4137 // Older browsers show a "speedtip" type message only for ALT.
4138 // Ideally these should be different, realistically they
4139 // probably don't need to be.
4147 $script .= Xml
::encodeJsCall(
4148 'mw.toolbar.addButton',
4150 ResourceLoader
::inDebugMode()
4156 $toolbar = '<div id="toolbar"></div>';
4158 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4159 // Only add the old toolbar cruft to the page payload if the toolbar has not
4160 // been over-written by a hook caller
4161 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
4168 * Return an array of checkbox definitions.
4170 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4172 * Array values are associative arrays with the following keys:
4173 * - 'label-message' (required): message for label text
4174 * - 'id' (required): 'id' attribute for the `<input>`
4175 * - 'default' (required): default checkedness (true or false)
4176 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4177 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4178 * from messages like 'tooltip-foo', 'accesskey-foo'
4179 * - 'label-id' (optional): 'id' attribute for the `<label>`
4180 * - 'legacy-name' (optional): short name for backwards-compatibility
4181 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4182 * where bool indicates the checked status of the checkbox
4185 public function getCheckboxesDefinition( $checked ) {
4188 $user = $this->context
->getUser();
4189 // don't show the minor edit checkbox if it's a new page or section
4190 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4191 $checkboxes['wpMinoredit'] = [
4192 'id' => 'wpMinoredit',
4193 'label-message' => 'minoredit',
4194 // Uses messages: tooltip-minoredit, accesskey-minoredit
4195 'tooltip' => 'minoredit',
4196 'label-id' => 'mw-editpage-minoredit',
4197 'legacy-name' => 'minor',
4198 'default' => $checked['minor'],
4202 if ( $user->isLoggedIn() ) {
4203 $checkboxes['wpWatchthis'] = [
4204 'id' => 'wpWatchthis',
4205 'label-message' => 'watchthis',
4206 // Uses messages: tooltip-watch, accesskey-watch
4207 'tooltip' => 'watch',
4208 'label-id' => 'mw-editpage-watch',
4209 'legacy-name' => 'watch',
4210 'default' => $checked['watch'],
4215 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4221 * Returns an array of html code of the following checkboxes old style:
4224 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4225 * @param int &$tabindex Current tabindex
4226 * @param array $checked See getCheckboxesDefinition()
4229 public function getCheckboxes( &$tabindex, $checked ) {
4231 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4233 // Backwards-compatibility for the EditPageBeforeEditChecks hook
4234 if ( !$this->isNew
) {
4235 $checkboxes['minor'] = '';
4237 $checkboxes['watch'] = '';
4239 foreach ( $checkboxesDef as $name => $options ) {
4240 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4241 $label = $this->context
->msg( $options['label-message'] )->parse();
4243 'tabindex' => ++
$tabindex,
4244 'id' => $options['id'],
4247 'for' => $options['id'],
4249 if ( isset( $options['tooltip'] ) ) {
4250 $attribs['accesskey'] = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4251 $labelAttribs['title'] = Linker
::titleAttrib( $options['tooltip'], 'withaccess' );
4253 if ( isset( $options['title-message'] ) ) {
4254 $labelAttribs['title'] = $this->context
->msg( $options['title-message'] )->text();
4256 if ( isset( $options['label-id'] ) ) {
4257 $labelAttribs['id'] = $options['label-id'];
4260 Xml
::check( $name, $options['default'], $attribs ) .
4262 Xml
::tags( 'label', $labelAttribs, $label );
4264 $checkboxes[ $legacyName ] = $checkboxHtml;
4267 // Avoid PHP 7.1 warning of passing $this by reference
4269 Hooks
::run( 'EditPageBeforeEditChecks', [ &$editPage, &$checkboxes, &$tabindex ], '1.29' );
4274 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4275 * any other added by extensions.
4277 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4278 * @param int &$tabindex Current tabindex
4279 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4280 * status of the checkbox
4282 * @return array Associative array of string keys to OOUI\FieldLayout instances
4284 public function getCheckboxesOOUI( &$tabindex, $checked ) {
4285 return $this->getCheckboxesWidget( $tabindex, $checked );
4289 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4290 * any other added by extensions.
4292 * @param int &$tabindex Current tabindex
4293 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4294 * status of the checkbox
4296 * @return array Associative array of string keys to OOUI\FieldLayout instances
4298 public function getCheckboxesWidget( &$tabindex, $checked ) {
4300 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4302 foreach ( $checkboxesDef as $name => $options ) {
4303 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4307 if ( isset( $options['tooltip'] ) ) {
4308 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4309 $title = Linker
::titleAttrib( $options['tooltip'] );
4311 if ( isset( $options['title-message'] ) ) {
4312 $title = $this->context
->msg( $options['title-message'] )->text();
4315 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4316 new OOUI\
CheckboxInputWidget( [
4317 'tabIndex' => ++
$tabindex,
4318 'accessKey' => $accesskey,
4319 'id' => $options['id'] . 'Widget',
4320 'inputId' => $options['id'],
4322 'selected' => $options['default'],
4323 'infusable' => true,
4326 'align' => 'inline',
4327 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4329 'id' => isset( $options['label-id'] ) ?
$options['label-id'] : null,
4334 // Backwards-compatibility hack to run the EditPageBeforeEditChecks hook. It's important,
4335 // people have used it for the weirdest things completely unrelated to checkboxes...
4336 // And if we're gonna run it, might as well allow its legacy checkboxes to be shown.
4337 $legacyCheckboxes = [];
4338 if ( !$this->isNew
) {
4339 $legacyCheckboxes['minor'] = '';
4341 $legacyCheckboxes['watch'] = '';
4342 // Copy new-style checkboxes into an old-style structure
4343 foreach ( $checkboxes as $name => $oouiLayout ) {
4344 $legacyCheckboxes[$name] = (string)$oouiLayout;
4346 // Avoid PHP 7.1 warning of passing $this by reference
4348 Hooks
::run( 'EditPageBeforeEditChecks', [ &$ep, &$legacyCheckboxes, &$tabindex ], '1.29' );
4349 // Copy back any additional old-style checkboxes into the new-style structure
4350 foreach ( $legacyCheckboxes as $name => $html ) {
4351 if ( $html && !isset( $checkboxes[$name] ) ) {
4352 $checkboxes[$name] = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $html ) ] );
4360 * Get the message key of the label for the button to save the page
4365 protected function getSubmitButtonLabel() {
4367 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4369 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4370 $newPage = !$this->mTitle
->exists();
4372 if ( $labelAsPublish ) {
4373 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4375 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4378 return $buttonLabelKey;
4382 * Returns an array of html code of the following buttons:
4383 * save, diff and preview
4385 * @param int &$tabindex Current tabindex
4389 public function getEditButtons( &$tabindex ) {
4392 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4396 'tabindex' => ++
$tabindex,
4399 $saveConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4400 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4401 'id' => 'wpSaveWidget',
4402 'inputId' => 'wpSave',
4403 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4404 'useInputTag' => true,
4405 'flags' => [ 'constructive', 'primary' ],
4406 'label' => $buttonLabel,
4407 'infusable' => true,
4409 'title' => Linker
::titleAttrib( 'save' ),
4410 'accessKey' => Linker
::accesskey( 'save' ),
4414 'name' => 'wpPreview',
4415 'tabindex' => ++
$tabindex,
4418 $previewConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4419 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4420 'id' => 'wpPreviewWidget',
4421 'inputId' => 'wpPreview',
4422 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4423 'useInputTag' => true,
4424 'label' => $this->context
->msg( 'showpreview' )->text(),
4425 'infusable' => true,
4427 'title' => Linker
::titleAttrib( 'preview' ),
4428 'accessKey' => Linker
::accesskey( 'preview' ),
4429 ] +
$previewConfig );
4433 'tabindex' => ++
$tabindex,
4436 $diffConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4437 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4438 'id' => 'wpDiffWidget',
4439 'inputId' => 'wpDiff',
4440 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4441 'useInputTag' => true,
4442 'label' => $this->context
->msg( 'showdiff' )->text(),
4443 'infusable' => true,
4445 'title' => Linker
::titleAttrib( 'diff' ),
4446 'accessKey' => Linker
::accesskey( 'diff' ),
4449 // Avoid PHP 7.1 warning of passing $this by reference
4451 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4457 * Creates a basic error page which informs the user that
4458 * they have attempted to edit a nonexistent section.
4460 public function noSuchSectionPage() {
4461 $out = $this->context
->getOutput();
4462 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4464 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4466 // Avoid PHP 7.1 warning of passing $this by reference
4468 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4469 $out->addHTML( $res );
4471 $out->returnToMain( false, $this->mTitle
);
4475 * Show "your edit contains spam" page with your diff and text
4477 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4479 public function spamPageWithContent( $match = false ) {
4480 $this->textbox2
= $this->textbox1
;
4482 if ( is_array( $match ) ) {
4483 $match = $this->context
->getLanguage()->listToText( $match );
4485 $out = $this->context
->getOutput();
4486 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4488 $out->addHTML( '<div id="spamprotected">' );
4489 $out->addWikiMsg( 'spamprotectiontext' );
4491 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4493 $out->addHTML( '</div>' );
4495 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4498 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4499 $this->showTextbox2();
4501 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4505 * Filter an input field through a Unicode de-armoring process if it
4506 * came from an old browser with known broken Unicode editing issues.
4508 * @deprecated since 1.30, does nothing
4510 * @param WebRequest $request
4511 * @param string $field
4514 protected function safeUnicodeInput( $request, $field ) {
4515 return rtrim( $request->getText( $field ) );
4519 * Filter an output field through a Unicode armoring process if it is
4520 * going to an old browser with known broken Unicode editing issues.
4522 * @deprecated since 1.30, does nothing
4524 * @param string $text
4527 protected function safeUnicodeOutput( $text ) {
4534 protected function addEditNotices() {
4535 $out = $this->context
->getOutput();
4536 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4537 if ( count( $editNotices ) ) {
4538 $out->addHTML( implode( "\n", $editNotices ) );
4540 $msg = $this->context
->msg( 'editnotice-notext' );
4541 if ( !$msg->isDisabled() ) {
4543 '<div class="mw-editnotice-notext">'
4544 . $msg->parseAsBlock()
4554 protected function addTalkPageText() {
4555 if ( $this->mTitle
->isTalkPage() ) {
4556 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4563 protected function addLongPageWarningHeader() {
4564 if ( $this->contentLength
=== false ) {
4565 $this->contentLength
= strlen( $this->textbox1
);
4568 $out = $this->context
->getOutput();
4569 $lang = $this->context
->getLanguage();
4570 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4571 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4572 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4575 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4576 $lang->formatNum( $maxArticleSize )
4580 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4581 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4584 $lang->formatSize( strlen( $this->textbox1
) ),
4585 strlen( $this->textbox1
)
4595 protected function addPageProtectionWarningHeaders() {
4596 $out = $this->context
->getOutput();
4597 if ( $this->mTitle
->isProtected( 'edit' ) &&
4598 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4600 # Is the title semi-protected?
4601 if ( $this->mTitle
->isSemiProtected() ) {
4602 $noticeMsg = 'semiprotectedpagewarning';
4604 # Then it must be protected based on static groups (regular)
4605 $noticeMsg = 'protectedpagewarning';
4607 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4608 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4610 if ( $this->mTitle
->isCascadeProtected() ) {
4611 # Is this page under cascading protection from some source pages?
4612 /** @var Title[] $cascadeSources */
4613 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4614 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4615 $cascadeSourcesCount = count( $cascadeSources );
4616 if ( $cascadeSourcesCount > 0 ) {
4617 # Explain, and list the titles responsible
4618 foreach ( $cascadeSources as $page ) {
4619 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4622 $notice .= '</div>';
4623 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4625 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4626 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4628 'showIfEmpty' => false,
4629 'msgKey' => [ 'titleprotectedwarning' ],
4630 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4635 * @param OutputPage $out
4638 protected function addExplainConflictHeader( OutputPage
$out ) {
4640 "<div class='mw-explainconflict'>\n$1\n</div>",
4641 [ 'explainconflict', $this->context
->msg( $this->getSubmitButtonLabel() )->text() ]
4646 * @param string $name
4647 * @param mixed[] $customAttribs
4652 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4653 $attribs = $customAttribs +
[
4658 // Avoid PHP notices when appending preferences
4659 // (appending allows customAttribs['style'] to still work).
4663 // The following classes can be used here:
4664 // * mw-editfont-default
4665 // * mw-editfont-monospace
4666 // * mw-editfont-sans-serif
4667 // * mw-editfont-serif
4668 $class = 'mw-editfont-' . $user->getOption( 'editfont' );
4670 if ( isset( $attribs['class'] ) ) {
4671 if ( is_string( $attribs['class'] ) ) {
4672 $attribs['class'] .= ' ' . $class;
4673 } elseif ( is_array( $attribs['class'] ) ) {
4674 $attribs['class'][] = $class;
4677 $attribs['class'] = $class;
4680 $pageLang = $this->mTitle
->getPageLanguage();
4681 $attribs['lang'] = $pageLang->getHtmlCode();
4682 $attribs['dir'] = $pageLang->getDir();
4688 * @param string $wikitext
4692 protected function addNewLineAtEnd( $wikitext ) {
4693 if ( strval( $wikitext ) !== '' ) {
4694 // Ensure there's a newline at the end, otherwise adding lines
4696 // But don't add a newline if the text is empty, or Firefox in XHTML
4697 // mode will show an extra newline. A bit annoying.
4705 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4706 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4707 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4708 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4709 * spread the new style links more efficiently.
4711 * @param string $text
4714 private function guessSectionName( $text ) {
4717 // Detect Microsoft browsers
4718 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4719 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4720 // ...and redirect them to legacy encoding, if available
4721 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4723 // Meanwhile, real browsers get real anchors
4724 return $wgParser->guessSectionNameFromWikiText( $text );