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;
224 /** @var null|Title */
225 private $mContextTitle = null;
228 public $action = 'submit';
231 public $isConflict = false;
234 * @deprecated since 1.30 use Title::isCssJsSubpage()
237 public $isCssJsSubpage = false;
240 * @deprecated since 1.30 use Title::isCssSubpage()
243 public $isCssSubpage = false;
246 * @deprecated since 1.30 use Title::isJsSubpage()
249 public $isJsSubpage = false;
252 * @deprecated since 1.30
255 public $isWrongCaseCssJsPage = false;
257 /** @var bool New page or new section */
258 public $isNew = false;
261 public $deletedSinceEdit;
269 /** @var bool|stdClass */
273 public $mTokenOk = false;
276 public $mTokenOkExceptSuffix = false;
279 public $mTriedSave = false;
282 public $incompleteForm = false;
285 public $tooBig = false;
288 public $missingComment = false;
291 public $missingSummary = false;
294 public $allowBlankSummary = false;
297 protected $blankArticle = false;
300 protected $allowBlankArticle = false;
303 protected $selfRedirect = false;
306 protected $allowSelfRedirect = false;
309 public $autoSumm = '';
312 public $hookError = '';
314 /** @var ParserOutput */
315 public $mParserOutput;
317 /** @var bool Has a summary been preset using GET parameter &summary= ? */
318 public $hasPresetSummary = false;
320 /** @var Revision|bool */
321 public $mBaseRevision = false;
324 public $mShowSummaryField = true;
329 public $save = false;
332 public $preview = false;
335 public $diff = false;
338 public $minoredit = false;
341 public $watchthis = false;
344 public $recreate = false;
347 public $textbox1 = '';
350 public $textbox2 = '';
353 public $summary = '';
356 public $nosummary = false;
359 public $edittime = '';
362 private $editRevId = null;
365 public $section = '';
368 public $sectiontitle = '';
371 public $starttime = '';
377 public $parentRevId = 0;
380 public $editintro = '';
383 public $scrolltop = null;
389 public $contentModel;
391 /** @var null|string */
392 public $contentFormat = null;
394 /** @var null|array */
395 private $changeTags = null;
397 # Placeholders for text injection by hooks (must be HTML)
398 # extensions should take care to _append_ to the present value
400 /** @var string Before even the preview */
401 public $editFormPageTop = '';
402 public $editFormTextTop = '';
403 public $editFormTextBeforeContent = '';
404 public $editFormTextAfterWarn = '';
405 public $editFormTextAfterTools = '';
406 public $editFormTextBottom = '';
407 public $editFormTextAfterContent = '';
408 public $previewTextAfterContent = '';
409 public $mPreloadContent = null;
411 /* $didSave should be set to true whenever an article was successfully altered. */
412 public $didSave = false;
413 public $undidRev = 0;
415 public $suppressIntro = false;
421 protected $contentLength = false;
424 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
426 private $enableApiEditOverride = false;
429 * @var IContextSource
434 * @var bool Whether an old revision is edited
436 private $isOldRev = false;
439 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
441 private $unicodeCheck;
444 * @param Article $article
446 public function __construct( Article
$article ) {
447 $this->mArticle
= $article;
448 $this->page
= $article->getPage(); // model object
449 $this->mTitle
= $article->getTitle();
450 $this->context
= $article->getContext();
452 $this->contentModel
= $this->mTitle
->getContentModel();
454 $handler = ContentHandler
::getForModelID( $this->contentModel
);
455 $this->contentFormat
= $handler->getDefaultFormat();
461 public function getArticle() {
462 return $this->mArticle
;
467 * @return IContextSource
469 public function getContext() {
470 return $this->context
;
477 public function getTitle() {
478 return $this->mTitle
;
482 * Set the context Title object
484 * @param Title|null $title Title object or null
486 public function setContextTitle( $title ) {
487 $this->mContextTitle
= $title;
491 * Get the context title object.
492 * If not set, $wgTitle will be returned. This behavior might change in
493 * the future to return $this->mTitle instead.
497 public function getContextTitle() {
498 if ( is_null( $this->mContextTitle
) ) {
501 __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.'
506 return $this->mContextTitle
;
511 * Check if the edit page is using OOUI controls
512 * @return bool Always true
513 * @deprecated since 1.30
515 public function isOouiEnabled() {
520 * Returns if the given content model is editable.
522 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
524 * @throws MWException If $modelId has no known handler
526 public function isSupportedContentModel( $modelId ) {
527 return $this->enableApiEditOverride
=== true ||
528 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
532 * Allow editing of content that supports API direct editing, but not general
533 * direct editing. Set to false by default.
535 * @param bool $enableOverride
537 public function setApiEditOverride( $enableOverride ) {
538 $this->enableApiEditOverride
= $enableOverride;
542 * @deprecated since 1.29, call edit directly
544 public function submit() {
545 wfDeprecated( __METHOD__
, '1.29' );
550 * This is the function that gets called for "action=edit". It
551 * sets up various member variables, then passes execution to
552 * another function, usually showEditForm()
554 * The edit form is self-submitting, so that when things like
555 * preview and edit conflicts occur, we get the same form back
556 * with the extra stuff added. Only when the final submission
557 * is made and all is well do we actually save and redirect to
558 * the newly-edited page.
560 public function edit() {
561 // Allow extensions to modify/prevent this form or submission
562 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
566 wfDebug( __METHOD__
. ": enter\n" );
568 $request = $this->context
->getRequest();
569 // If they used redlink=1 and the page exists, redirect to the main article
570 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
571 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
575 $this->importFormData( $request );
576 $this->firsttime
= false;
578 if ( wfReadOnly() && $this->save
) {
581 $this->preview
= true;
585 $this->formtype
= 'save';
586 } elseif ( $this->preview
) {
587 $this->formtype
= 'preview';
588 } elseif ( $this->diff
) {
589 $this->formtype
= 'diff';
590 } else { # First time through
591 $this->firsttime
= true;
592 if ( $this->previewOnOpen() ) {
593 $this->formtype
= 'preview';
595 $this->formtype
= 'initial';
599 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
601 wfDebug( __METHOD__
. ": User can't edit\n" );
602 // Auto-block user's IP if the account was "hard" blocked
603 if ( !wfReadOnly() ) {
604 DeferredUpdates
::addCallableUpdate( function () {
605 $this->context
->getUser()->spreadAnyEditBlock();
608 $this->displayPermissionsError( $permErrors );
613 $revision = $this->mArticle
->getRevisionFetched();
614 // Disallow editing revisions with content models different from the current one
615 // Undo edits being an exception in order to allow reverting content model changes.
617 && $revision->getContentModel() !== $this->contentModel
620 if ( $this->undidRev
) {
621 $undidRevObj = Revision
::newFromId( $this->undidRev
);
622 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
624 if ( !$this->undidRev
626 ||
$prevRev->getContentModel() !== $this->contentModel
628 $this->displayViewSourcePage(
629 $this->getContentObject(),
631 'contentmodelediterror',
632 $revision->getContentModel(),
640 $this->isConflict
= false;
641 // css / js subpages of user pages get a special treatment
642 // The following member variables are deprecated since 1.30,
643 // the functions should be used instead.
644 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
645 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
646 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
647 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
649 # Show applicable editing introductions
650 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
654 # Attempt submission here. This will check for edit conflicts,
655 # and redundantly check for locked database, blocked IPs, etc.
656 # that edit() already checked just in case someone tries to sneak
657 # in the back door with a hand-edited submission URL.
659 if ( 'save' == $this->formtype
) {
660 $resultDetails = null;
661 $status = $this->attemptSave( $resultDetails );
662 if ( !$this->handleStatus( $status, $resultDetails ) ) {
667 # First time through: get contents, set time for conflict
669 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
670 if ( $this->initialiseForm() === false ) {
671 $this->noSuchSectionPage();
675 if ( !$this->mTitle
->getArticleID() ) {
676 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
678 Hooks
::run( 'EditFormInitialText', [ $this ] );
683 $this->showEditForm();
687 * @param string $rigor Same format as Title::getUserPermissionErrors()
690 protected function getEditPermissionErrors( $rigor = 'secure' ) {
691 $user = $this->context
->getUser();
692 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
693 # Can this title be created?
694 if ( !$this->mTitle
->exists() ) {
695 $permErrors = array_merge(
698 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
703 # Ignore some permissions errors when a user is just previewing/viewing diffs
705 foreach ( $permErrors as $error ) {
706 if ( ( $this->preview ||
$this->diff
)
708 $error[0] == 'blockedtext' ||
709 $error[0] == 'autoblockedtext' ||
710 $error[0] == 'systemblockedtext'
716 $permErrors = wfArrayDiff2( $permErrors, $remove );
722 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
723 * but with the following differences:
724 * - If redlink=1, the user will be redirected to the page
725 * - If there is content to display or the error occurs while either saving,
726 * previewing or showing the difference, it will be a
727 * "View source for ..." page displaying the source code after the error message.
730 * @param array $permErrors Array of permissions errors, as returned by
731 * Title::getUserPermissionsErrors().
732 * @throws PermissionsError
734 protected function displayPermissionsError( array $permErrors ) {
735 $out = $this->context
->getOutput();
736 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
737 // The edit page was reached via a red link.
738 // Redirect to the article page and let them click the edit tab if
739 // they really want a permission error.
740 $out->redirect( $this->mTitle
->getFullURL() );
744 $content = $this->getContentObject();
746 # Use the normal message if there's nothing to display
747 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
748 $action = $this->mTitle
->exists() ?
'edit' :
749 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
750 throw new PermissionsError( $action, $permErrors );
753 $this->displayViewSourcePage(
755 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
760 * Display a read-only View Source page
761 * @param Content $content content object
762 * @param string $errorMessage additional wikitext error message to display
764 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
765 $out = $this->context
->getOutput();
766 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
768 $out->setRobotPolicy( 'noindex,nofollow' );
769 $out->setPageTitle( $this->context
->msg(
771 $this->getContextTitle()->getPrefixedText()
773 $out->addBacklinkSubtitle( $this->getContextTitle() );
774 $out->addHTML( $this->editFormPageTop
);
775 $out->addHTML( $this->editFormTextTop
);
777 if ( $errorMessage !== '' ) {
778 $out->addWikiText( $errorMessage );
779 $out->addHTML( "<hr />\n" );
782 # If the user made changes, preserve them when showing the markup
783 # (This happens when a user is blocked during edit, for instance)
784 if ( !$this->firsttime
) {
785 $text = $this->textbox1
;
786 $out->addWikiMsg( 'viewyourtext' );
789 $text = $this->toEditText( $content );
790 } catch ( MWException
$e ) {
791 # Serialize using the default format if the content model is not supported
792 # (e.g. for an old revision with a different model)
793 $text = $content->serialize();
795 $out->addWikiMsg( 'viewsourcetext' );
798 $out->addHTML( $this->editFormTextBeforeContent
);
799 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
800 $out->addHTML( $this->editFormTextAfterContent
);
802 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
804 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
806 $out->addHTML( $this->editFormTextBottom
);
807 if ( $this->mTitle
->exists() ) {
808 $out->returnToMain( null, $this->mTitle
);
813 * Should we show a preview when the edit form is first shown?
817 protected function previewOnOpen() {
818 global $wgPreviewOnOpenNamespaces;
819 $request = $this->context
->getRequest();
820 if ( $request->getVal( 'preview' ) == 'yes' ) {
821 // Explicit override from request
823 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
824 // Explicit override from request
826 } elseif ( $this->section
== 'new' ) {
827 // Nothing *to* preview for new sections
829 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
830 && $this->context
->getUser()->getOption( 'previewonfirst' )
832 // Standard preference behavior
834 } elseif ( !$this->mTitle
->exists()
835 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
836 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
838 // Categories are special
846 * Checks whether the user entered a skin name in uppercase,
847 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
851 protected function isWrongCaseCssJsPage() {
852 if ( $this->mTitle
->isCssJsSubpage() ) {
853 $name = $this->mTitle
->getSkinFromCssJsSubpage();
854 $skins = array_merge(
855 array_keys( Skin
::getSkinNames() ),
858 return !in_array( $name, $skins )
859 && in_array( strtolower( $name ), $skins );
866 * Returns whether section editing is supported for the current page.
867 * Subclasses may override this to replace the default behavior, which is
868 * to check ContentHandler::supportsSections.
870 * @return bool True if this edit page supports sections, false otherwise.
872 protected function isSectionEditSupported() {
873 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
874 return $contentHandler->supportsSections();
878 * This function collects the form data and uses it to populate various member variables.
879 * @param WebRequest &$request
880 * @throws ErrorPageError
882 public function importFormData( &$request ) {
883 # Section edit can come from either the form or a link
884 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
886 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
887 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
890 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
892 if ( $request->wasPosted() ) {
893 # These fields need to be checked for encoding.
894 # Also remove trailing whitespace, but don't remove _initial_
895 # whitespace from the text boxes. This may be significant formatting.
896 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
897 if ( !$request->getCheck( 'wpTextbox2' ) ) {
898 // Skip this if wpTextbox2 has input, it indicates that we came
899 // from a conflict page with raw page text, not a custom form
900 // modified by subclasses
901 $textbox1 = $this->importContentFormData( $request );
902 if ( $textbox1 !== null ) {
903 $this->textbox1
= $textbox1;
907 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
909 $this->summary
= $request->getText( 'wpSummary' );
911 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
912 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
914 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
916 # Treat sectiontitle the same way as summary.
917 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
918 # currently doing double duty as both edit summary and section title. Right now this
919 # is just to allow API edits to work around this limitation, but this should be
920 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
921 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
922 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
924 $this->edittime
= $request->getVal( 'wpEdittime' );
925 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
926 $this->starttime
= $request->getVal( 'wpStarttime' );
928 $undidRev = $request->getInt( 'wpUndidRevision' );
930 $this->undidRev
= $undidRev;
933 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
935 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
936 // wpTextbox1 field is missing, possibly due to being "too big"
937 // according to some filter rules such as Suhosin's setting for
938 // suhosin.request.max_value_length (d'oh)
939 $this->incompleteForm
= true;
941 // If we receive the last parameter of the request, we can fairly
942 // claim the POST request has not been truncated.
944 // TODO: softened the check for cutover. Once we determine
945 // that it is safe, we should complete the transition by
946 // removing the "edittime" clause.
947 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
948 && is_null( $this->edittime
) );
950 if ( $this->incompleteForm
) {
951 # If the form is incomplete, force to preview.
952 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
953 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
954 $this->preview
= true;
956 $this->preview
= $request->getCheck( 'wpPreview' );
957 $this->diff
= $request->getCheck( 'wpDiff' );
959 // Remember whether a save was requested, so we can indicate
960 // if we forced preview due to session failure.
961 $this->mTriedSave
= !$this->preview
;
963 if ( $this->tokenOk( $request ) ) {
964 # Some browsers will not report any submit button
965 # if the user hits enter in the comment box.
966 # The unmarked state will be assumed to be a save,
967 # if the form seems otherwise complete.
968 wfDebug( __METHOD__
. ": Passed token check.\n" );
969 } elseif ( $this->diff
) {
970 # Failed token check, but only requested "Show Changes".
971 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
973 # Page might be a hack attempt posted from
974 # an external site. Preview instead of saving.
975 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
976 $this->preview
= true;
979 $this->save
= !$this->preview
&& !$this->diff
;
980 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
981 $this->edittime
= null;
984 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
985 $this->starttime
= null;
988 $this->recreate
= $request->getCheck( 'wpRecreate' );
990 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
991 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
993 $user = $this->context
->getUser();
994 # Don't force edit summaries when a user is editing their own user or talk page
995 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
996 && $this->mTitle
->getText() == $user->getName()
998 $this->allowBlankSummary
= true;
1000 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1001 ||
!$user->getOption( 'forceeditsummary' );
1004 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1006 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1007 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1009 $changeTags = $request->getVal( 'wpChangeTags' );
1010 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1011 $this->changeTags
= [];
1013 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1017 # Not a posted form? Start with nothing.
1018 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1019 $this->textbox1
= '';
1020 $this->summary
= '';
1021 $this->sectiontitle
= '';
1022 $this->edittime
= '';
1023 $this->editRevId
= null;
1024 $this->starttime
= wfTimestampNow();
1025 $this->edit
= false;
1026 $this->preview
= false;
1027 $this->save
= false;
1028 $this->diff
= false;
1029 $this->minoredit
= false;
1030 // Watch may be overridden by request parameters
1031 $this->watchthis
= $request->getBool( 'watchthis', false );
1032 $this->recreate
= false;
1034 // When creating a new section, we can preload a section title by passing it as the
1035 // preloadtitle parameter in the URL (T15100)
1036 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1037 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1038 // Once wpSummary isn't being use for setting section titles, we should delete this.
1039 $this->summary
= $request->getVal( 'preloadtitle' );
1040 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1041 $this->summary
= $request->getText( 'summary' );
1042 if ( $this->summary
!== '' ) {
1043 $this->hasPresetSummary
= true;
1047 if ( $request->getVal( 'minor' ) ) {
1048 $this->minoredit
= true;
1052 $this->oldid
= $request->getInt( 'oldid' );
1053 $this->parentRevId
= $request->getInt( 'parentRevId' );
1055 $this->bot
= $request->getBool( 'bot', true );
1056 $this->nosummary
= $request->getBool( 'nosummary' );
1058 // May be overridden by revision.
1059 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1060 // May be overridden by revision.
1061 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1064 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1065 } catch ( MWUnknownContentModelException
$e ) {
1066 throw new ErrorPageError(
1067 'editpage-invalidcontentmodel-title',
1068 'editpage-invalidcontentmodel-text',
1069 [ wfEscapeWikiText( $this->contentModel
) ]
1073 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1074 throw new ErrorPageError(
1075 'editpage-notsupportedcontentformat-title',
1076 'editpage-notsupportedcontentformat-text',
1078 wfEscapeWikiText( $this->contentFormat
),
1079 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1085 * @todo Check if the desired model is allowed in this namespace, and if
1086 * a transition from the page's current model to the new model is
1090 $this->editintro
= $request->getText( 'editintro',
1091 // Custom edit intro for new sections
1092 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1094 // Allow extensions to modify form data
1095 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1099 * Subpage overridable method for extracting the page content data from the
1100 * posted form to be placed in $this->textbox1, if using customized input
1101 * this method should be overridden and return the page text that will be used
1102 * for saving, preview parsing and so on...
1104 * @param WebRequest &$request
1105 * @return string|null
1107 protected function importContentFormData( &$request ) {
1108 return; // Don't do anything, EditPage already extracted wpTextbox1
1112 * Initialise form fields in the object
1113 * Called on the first invocation, e.g. when a user clicks an edit link
1114 * @return bool If the requested section is valid
1116 public function initialiseForm() {
1117 $this->edittime
= $this->page
->getTimestamp();
1118 $this->editRevId
= $this->page
->getLatest();
1120 $content = $this->getContentObject( false ); # TODO: track content object?!
1121 if ( $content === false ) {
1124 $this->textbox1
= $this->toEditText( $content );
1126 $user = $this->context
->getUser();
1127 // activate checkboxes if user wants them to be always active
1128 # Sort out the "watch" checkbox
1129 if ( $user->getOption( 'watchdefault' ) ) {
1131 $this->watchthis
= true;
1132 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1134 $this->watchthis
= true;
1135 } elseif ( $user->isWatched( $this->mTitle
) ) {
1137 $this->watchthis
= true;
1139 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1140 $this->minoredit
= true;
1142 if ( $this->textbox1
=== false ) {
1149 * @param Content|null $def_content The default value to return
1151 * @return Content|null Content on success, $def_content for invalid sections
1155 protected function getContentObject( $def_content = null ) {
1160 $user = $this->context
->getUser();
1161 $request = $this->context
->getRequest();
1162 // For message page not locally set, use the i18n message.
1163 // For other non-existent articles, use preload text if any.
1164 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1165 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1166 # If this is a system message, get the default text.
1167 $msg = $this->mTitle
->getDefaultMessageText();
1169 $content = $this->toEditContent( $msg );
1171 if ( $content === false ) {
1172 # If requested, preload some text.
1173 $preload = $request->getVal( 'preload',
1174 // Custom preload text for new sections
1175 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1176 $params = $request->getArray( 'preloadparams', [] );
1178 $content = $this->getPreloadedContent( $preload, $params );
1180 // For existing pages, get text based on "undo" or section parameters.
1182 if ( $this->section
!= '' ) {
1183 // Get section edit text (returns $def_text for invalid sections)
1184 $orig = $this->getOriginalContent( $user );
1185 $content = $orig ?
$orig->getSection( $this->section
) : null;
1188 $content = $def_content;
1191 $undoafter = $request->getInt( 'undoafter' );
1192 $undo = $request->getInt( 'undo' );
1194 if ( $undo > 0 && $undoafter > 0 ) {
1195 $undorev = Revision
::newFromId( $undo );
1196 $oldrev = Revision
::newFromId( $undoafter );
1198 # Sanity check, make sure it's the right page,
1199 # the revisions exist and they were not deleted.
1200 # Otherwise, $content will be left as-is.
1201 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1202 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1203 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1205 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1207 if ( $content === false ) {
1208 # Warn the user that something went wrong
1209 $undoMsg = 'failure';
1211 $oldContent = $this->page
->getContent( Revision
::RAW
);
1212 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1213 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1214 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1215 // The undo may change content
1216 // model if its reverting the top
1217 // edit. This can result in
1218 // mismatched content model/format.
1219 $this->contentModel
= $newContent->getModel();
1220 $this->contentFormat
= $oldrev->getContentFormat();
1223 if ( $newContent->equals( $oldContent ) ) {
1224 # Tell the user that the undo results in no change,
1225 # i.e. the revisions were already undone.
1226 $undoMsg = 'nochange';
1229 # Inform the user of our success and set an automatic edit summary
1230 $undoMsg = 'success';
1232 # If we just undid one rev, use an autosummary
1233 $firstrev = $oldrev->getNext();
1234 if ( $firstrev && $firstrev->getId() == $undo ) {
1235 $userText = $undorev->getUserText();
1236 if ( $userText === '' ) {
1237 $undoSummary = $this->context
->msg(
1238 'undo-summary-username-hidden',
1240 )->inContentLanguage()->text();
1242 $undoSummary = $this->context
->msg(
1246 )->inContentLanguage()->text();
1248 if ( $this->summary
=== '' ) {
1249 $this->summary
= $undoSummary;
1251 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1252 ->inContentLanguage()->text() . $this->summary
;
1254 $this->undidRev
= $undo;
1256 $this->formtype
= 'diff';
1260 // Failed basic sanity checks.
1261 // Older revisions may have been removed since the link
1262 // was created, or we may simply have got bogus input.
1266 $out = $this->context
->getOutput();
1267 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1268 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1269 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1270 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1273 if ( $content === false ) {
1274 $content = $this->getOriginalContent( $user );
1283 * Get the content of the wanted revision, without section extraction.
1285 * The result of this function can be used to compare user's input with
1286 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1287 * to the original text of the edit.
1289 * This differs from Article::getContent() that when a missing revision is
1290 * encountered the result will be null and not the
1291 * 'missing-revision' message.
1294 * @param User $user The user to get the revision for
1295 * @return Content|null
1297 private function getOriginalContent( User
$user ) {
1298 if ( $this->section
== 'new' ) {
1299 return $this->getCurrentContent();
1301 $revision = $this->mArticle
->getRevisionFetched();
1302 if ( $revision === null ) {
1303 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1304 return $handler->makeEmptyContent();
1306 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1311 * Get the edit's parent revision ID
1313 * The "parent" revision is the ancestor that should be recorded in this
1314 * page's revision history. It is either the revision ID of the in-memory
1315 * article content, or in the case of a 3-way merge in order to rebase
1316 * across a recoverable edit conflict, the ID of the newer revision to
1317 * which we have rebased this page.
1320 * @return int Revision ID
1322 public function getParentRevId() {
1323 if ( $this->parentRevId
) {
1324 return $this->parentRevId
;
1326 return $this->mArticle
->getRevIdFetched();
1331 * Get the current content of the page. This is basically similar to
1332 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1333 * content object is returned instead of null.
1338 protected function getCurrentContent() {
1339 $rev = $this->page
->getRevision();
1340 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1342 if ( $content === false ||
$content === null ) {
1343 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1344 return $handler->makeEmptyContent();
1345 } elseif ( !$this->undidRev
) {
1346 // Content models should always be the same since we error
1347 // out if they are different before this point (in ->edit()).
1348 // The exception being, during an undo, the current revision might
1349 // differ from the prior revision.
1350 $logger = LoggerFactory
::getInstance( 'editpage' );
1351 if ( $this->contentModel
!== $rev->getContentModel() ) {
1352 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1353 'prev' => $this->contentModel
,
1354 'new' => $rev->getContentModel(),
1355 'title' => $this->getTitle()->getPrefixedDBkey(),
1356 'method' => __METHOD__
1358 $this->contentModel
= $rev->getContentModel();
1361 // Given that the content models should match, the current selected
1362 // format should be supported.
1363 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1364 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1366 'prev' => $this->contentFormat
,
1367 'new' => $rev->getContentFormat(),
1368 'title' => $this->getTitle()->getPrefixedDBkey(),
1369 'method' => __METHOD__
1371 $this->contentFormat
= $rev->getContentFormat();
1378 * Use this method before edit() to preload some content into the edit box
1380 * @param Content $content
1384 public function setPreloadedContent( Content
$content ) {
1385 $this->mPreloadContent
= $content;
1389 * Get the contents to be preloaded into the box, either set by
1390 * an earlier setPreloadText() or by loading the given page.
1392 * @param string $preload Representing the title to preload from.
1393 * @param array $params Parameters to use (interface-message style) in the preloaded text
1399 protected function getPreloadedContent( $preload, $params = [] ) {
1400 if ( !empty( $this->mPreloadContent
) ) {
1401 return $this->mPreloadContent
;
1404 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1406 if ( $preload === '' ) {
1407 return $handler->makeEmptyContent();
1410 $user = $this->context
->getUser();
1411 $title = Title
::newFromText( $preload );
1412 # Check for existence to avoid getting MediaWiki:Noarticletext
1413 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1414 // TODO: somehow show a warning to the user!
1415 return $handler->makeEmptyContent();
1418 $page = WikiPage
::factory( $title );
1419 if ( $page->isRedirect() ) {
1420 $title = $page->getRedirectTarget();
1422 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1423 // TODO: somehow show a warning to the user!
1424 return $handler->makeEmptyContent();
1426 $page = WikiPage
::factory( $title );
1429 $parserOptions = ParserOptions
::newFromUser( $user );
1430 $content = $page->getContent( Revision
::RAW
);
1433 // TODO: somehow show a warning to the user!
1434 return $handler->makeEmptyContent();
1437 if ( $content->getModel() !== $handler->getModelID() ) {
1438 $converted = $content->convert( $handler->getModelID() );
1440 if ( !$converted ) {
1441 // TODO: somehow show a warning to the user!
1442 wfDebug( "Attempt to preload incompatible content: " .
1443 "can't convert " . $content->getModel() .
1444 " to " . $handler->getModelID() );
1446 return $handler->makeEmptyContent();
1449 $content = $converted;
1452 return $content->preloadTransform( $title, $parserOptions, $params );
1456 * Make sure the form isn't faking a user's credentials.
1458 * @param WebRequest &$request
1462 public function tokenOk( &$request ) {
1463 $token = $request->getVal( 'wpEditToken' );
1464 $user = $this->context
->getUser();
1465 $this->mTokenOk
= $user->matchEditToken( $token );
1466 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1467 return $this->mTokenOk
;
1471 * Sets post-edit cookie indicating the user just saved a particular revision.
1473 * This uses a temporary cookie for each revision ID so separate saves will never
1474 * interfere with each other.
1476 * Article::view deletes the cookie on server-side after the redirect and
1477 * converts the value to the global JavaScript variable wgPostEdit.
1479 * If the variable were set on the server, it would be cached, which is unwanted
1480 * since the post-edit state should only apply to the load right after the save.
1482 * @param int $statusValue The status value (to check for new article status)
1484 protected function setPostEditCookie( $statusValue ) {
1485 $revisionId = $this->page
->getLatest();
1486 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1489 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1491 } elseif ( $this->oldid
) {
1495 $response = $this->context
->getRequest()->response();
1496 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1500 * Attempt submission
1501 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1502 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1503 * @return Status The resulting status object.
1505 public function attemptSave( &$resultDetails = false ) {
1506 # Allow bots to exempt some edits from bot flagging
1507 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1508 $status = $this->internalAttemptSave( $resultDetails, $bot );
1510 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1516 * Log when a page was successfully saved after the edit conflict view
1518 private function incrementResolvedConflicts() {
1519 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1523 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1524 $stats->increment( 'edit.failures.conflict.resolved' );
1528 * Handle status, such as after attempt save
1530 * @param Status $status
1531 * @param array|bool $resultDetails
1533 * @throws ErrorPageError
1534 * @return bool False, if output is done, true if rest of the form should be displayed
1536 private function handleStatus( Status
$status, $resultDetails ) {
1538 * @todo FIXME: once the interface for internalAttemptSave() is made
1539 * nicer, this should use the message in $status
1541 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1542 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1544 $this->incrementResolvedConflicts();
1546 $this->didSave
= true;
1547 if ( !$resultDetails['nullEdit'] ) {
1548 $this->setPostEditCookie( $status->value
);
1552 $out = $this->context
->getOutput();
1554 // "wpExtraQueryRedirect" is a hidden input to modify
1555 // after save URL and is not used by actual edit form
1556 $request = $this->context
->getRequest();
1557 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1559 switch ( $status->value
) {
1560 case self
::AS_HOOK_ERROR_EXPECTED
:
1561 case self
::AS_CONTENT_TOO_BIG
:
1562 case self
::AS_ARTICLE_WAS_DELETED
:
1563 case self
::AS_CONFLICT_DETECTED
:
1564 case self
::AS_SUMMARY_NEEDED
:
1565 case self
::AS_TEXTBOX_EMPTY
:
1566 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1568 case self
::AS_BLANK_ARTICLE
:
1569 case self
::AS_SELF_REDIRECT
:
1572 case self
::AS_HOOK_ERROR
:
1575 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1576 case self
::AS_PARSE_ERROR
:
1577 case self
::AS_UNICODE_NOT_SUPPORTED
:
1578 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1581 case self
::AS_SUCCESS_NEW_ARTICLE
:
1582 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1583 if ( $extraQueryRedirect ) {
1584 if ( $query === '' ) {
1585 $query = $extraQueryRedirect;
1587 $query = $query . '&' . $extraQueryRedirect;
1590 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1591 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1594 case self
::AS_SUCCESS_UPDATE
:
1596 $sectionanchor = $resultDetails['sectionanchor'];
1598 // Give extensions a chance to modify URL query on update
1600 'ArticleUpdateBeforeRedirect',
1601 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1604 if ( $resultDetails['redirect'] ) {
1605 if ( $extraQuery == '' ) {
1606 $extraQuery = 'redirect=no';
1608 $extraQuery = 'redirect=no&' . $extraQuery;
1611 if ( $extraQueryRedirect ) {
1612 if ( $extraQuery === '' ) {
1613 $extraQuery = $extraQueryRedirect;
1615 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1619 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1622 case self
::AS_SPAM_ERROR
:
1623 $this->spamPageWithContent( $resultDetails['spam'] );
1626 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1627 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1629 case self
::AS_IMAGE_REDIRECT_ANON
:
1630 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1631 throw new PermissionsError( 'upload' );
1633 case self
::AS_READ_ONLY_PAGE_ANON
:
1634 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1635 throw new PermissionsError( 'edit' );
1637 case self
::AS_READ_ONLY_PAGE
:
1638 throw new ReadOnlyError
;
1640 case self
::AS_RATE_LIMITED
:
1641 throw new ThrottledError();
1643 case self
::AS_NO_CREATE_PERMISSION
:
1644 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1645 throw new PermissionsError( $permission );
1647 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1648 throw new PermissionsError( 'editcontentmodel' );
1651 // We don't recognize $status->value. The only way that can happen
1652 // is if an extension hook aborted from inside ArticleSave.
1653 // Render the status object into $this->hookError
1654 // FIXME this sucks, we should just use the Status object throughout
1655 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1662 * Run hooks that can filter edits just before they get saved.
1664 * @param Content $content The Content to filter.
1665 * @param Status $status For reporting the outcome to the caller
1666 * @param User $user The user performing the edit
1670 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1671 // Run old style post-section-merge edit filter
1672 if ( $this->hookError
!= '' ) {
1673 # ...or the hook could be expecting us to produce an error
1674 $status->fatal( 'hookaborted' );
1675 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1679 // Run new style post-section-merge edit filter
1680 if ( !Hooks
::run( 'EditFilterMergedContent',
1681 [ $this->mArticle
->getContext(), $content, $status, $this->summary
,
1682 $user, $this->minoredit
] )
1684 # Error messages etc. could be handled within the hook...
1685 if ( $status->isGood() ) {
1686 $status->fatal( 'hookaborted' );
1687 // Not setting $this->hookError here is a hack to allow the hook
1688 // to cause a return to the edit page without $this->hookError
1689 // being set. This is used by ConfirmEdit to display a captcha
1690 // without any error message cruft.
1692 $this->hookError
= $status->getWikiText();
1694 // Use the existing $status->value if the hook set it
1695 if ( !$status->value
) {
1696 $status->value
= self
::AS_HOOK_ERROR
;
1699 } elseif ( !$status->isOK() ) {
1700 # ...or the hook could be expecting us to produce an error
1701 // FIXME this sucks, we should just use the Status object throughout
1702 $this->hookError
= $status->getWikiText();
1703 $status->fatal( 'hookaborted' );
1704 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1712 * Return the summary to be used for a new section.
1714 * @param string $sectionanchor Set to the section anchor text
1717 private function newSectionSummary( &$sectionanchor = null ) {
1720 if ( $this->sectiontitle
!== '' ) {
1721 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1722 // If no edit summary was specified, create one automatically from the section
1723 // title and have it link to the new section. Otherwise, respect the summary as
1725 if ( $this->summary
=== '' ) {
1726 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1727 return $this->context
->msg( 'newsectionsummary' )
1728 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1730 } elseif ( $this->summary
!== '' ) {
1731 $sectionanchor = $this->guessSectionName( $this->summary
);
1732 # This is a new section, so create a link to the new section
1733 # in the revision summary.
1734 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1735 return $this->context
->msg( 'newsectionsummary' )
1736 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1738 return $this->summary
;
1742 * Attempt submission (no UI)
1744 * @param array &$result Array to add statuses to, currently with the
1746 * - spam (string): Spam string from content if any spam is detected by
1748 * - sectionanchor (string): Section anchor for a section save.
1749 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1751 * - redirect (bool): Set if doEditContent is OK. True if resulting
1752 * revision is a redirect.
1753 * @param bool $bot True if edit is being made under the bot right.
1755 * @return Status Status object, possibly with a message, but always with
1756 * one of the AS_* constants in $status->value,
1758 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1759 * various error display idiosyncrasies. There are also lots of cases
1760 * where error metadata is set in the object and retrieved later instead
1761 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1762 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1765 public function internalAttemptSave( &$result, $bot = false ) {
1766 global $wgMaxArticleSize;
1767 global $wgContentHandlerUseDB;
1769 $status = Status
::newGood();
1770 $user = $this->context
->getUser();
1772 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1773 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1774 $status->fatal( 'hookaborted' );
1775 $status->value
= self
::AS_HOOK_ERROR
;
1779 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1780 $status->fatal( 'unicode-support-fail' );
1781 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1785 $request = $this->context
->getRequest();
1786 $spam = $request->getText( 'wpAntispam' );
1787 if ( $spam !== '' ) {
1792 $this->mTitle
->getPrefixedText() .
1793 '" submitted bogus field "' .
1797 $status->fatal( 'spamprotectionmatch', false );
1798 $status->value
= self
::AS_SPAM_ERROR
;
1803 # Construct Content object
1804 $textbox_content = $this->toEditContent( $this->textbox1
);
1805 } catch ( MWContentSerializationException
$ex ) {
1807 'content-failed-to-parse',
1808 $this->contentModel
,
1809 $this->contentFormat
,
1812 $status->value
= self
::AS_PARSE_ERROR
;
1816 # Check image redirect
1817 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1818 $textbox_content->isRedirect() &&
1819 !$user->isAllowed( 'upload' )
1821 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1822 $status->setResult( false, $code );
1828 $match = self
::matchSummarySpamRegex( $this->summary
);
1829 if ( $match === false && $this->section
== 'new' ) {
1830 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1831 # regular summaries, it is added to the actual wikitext.
1832 if ( $this->sectiontitle
!== '' ) {
1833 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1834 $match = self
::matchSpamRegex( $this->sectiontitle
);
1836 # This branch is taken when the "Add Topic" user interface is used, or the API
1837 # is used with the 'summary' parameter.
1838 $match = self
::matchSpamRegex( $this->summary
);
1841 if ( $match === false ) {
1842 $match = self
::matchSpamRegex( $this->textbox1
);
1844 if ( $match !== false ) {
1845 $result['spam'] = $match;
1846 $ip = $request->getIP();
1847 $pdbk = $this->mTitle
->getPrefixedDBkey();
1848 $match = str_replace( "\n", '', $match );
1849 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1850 $status->fatal( 'spamprotectionmatch', $match );
1851 $status->value
= self
::AS_SPAM_ERROR
;
1856 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1858 # Error messages etc. could be handled within the hook...
1859 $status->fatal( 'hookaborted' );
1860 $status->value
= self
::AS_HOOK_ERROR
;
1862 } elseif ( $this->hookError
!= '' ) {
1863 # ...or the hook could be expecting us to produce an error
1864 $status->fatal( 'hookaborted' );
1865 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1869 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1870 // Auto-block user's IP if the account was "hard" blocked
1871 if ( !wfReadOnly() ) {
1872 $user->spreadAnyEditBlock();
1874 # Check block state against master, thus 'false'.
1875 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1879 $this->contentLength
= strlen( $this->textbox1
);
1880 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
1881 // Error will be displayed by showEditForm()
1882 $this->tooBig
= true;
1883 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1887 if ( !$user->isAllowed( 'edit' ) ) {
1888 if ( $user->isAnon() ) {
1889 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1892 $status->fatal( 'readonlytext' );
1893 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1898 $changingContentModel = false;
1899 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1900 if ( !$wgContentHandlerUseDB ) {
1901 $status->fatal( 'editpage-cannot-use-custom-model' );
1902 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1904 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1905 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1908 // Make sure the user can edit the page under the new content model too
1909 $titleWithNewContentModel = clone $this->mTitle
;
1910 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1911 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1912 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1914 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1918 $changingContentModel = true;
1919 $oldContentModel = $this->mTitle
->getContentModel();
1922 if ( $this->changeTags
) {
1923 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1924 $this->changeTags
, $user );
1925 if ( !$changeTagsStatus->isOK() ) {
1926 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1927 return $changeTagsStatus;
1931 if ( wfReadOnly() ) {
1932 $status->fatal( 'readonlytext' );
1933 $status->value
= self
::AS_READ_ONLY_PAGE
;
1936 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1937 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1939 $status->fatal( 'actionthrottledtext' );
1940 $status->value
= self
::AS_RATE_LIMITED
;
1944 # If the article has been deleted while editing, don't save it without
1946 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1947 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1951 # Load the page data from the master. If anything changes in the meantime,
1952 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1953 $this->page
->loadPageData( 'fromdbmaster' );
1954 $new = !$this->page
->exists();
1957 // Late check for create permission, just in case *PARANOIA*
1958 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1959 $status->fatal( 'nocreatetext' );
1960 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1961 wfDebug( __METHOD__
. ": no create permission\n" );
1965 // Don't save a new page if it's blank or if it's a MediaWiki:
1966 // message with content equivalent to default (allow empty pages
1967 // in this case to disable messages, see T52124)
1968 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1969 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1970 $defaultText = $defaultMessageText;
1975 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1976 $this->blankArticle
= true;
1977 $status->fatal( 'blankarticle' );
1978 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1982 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
1986 $content = $textbox_content;
1988 $result['sectionanchor'] = '';
1989 if ( $this->section
== 'new' ) {
1990 if ( $this->sectiontitle
!== '' ) {
1991 // Insert the section title above the content.
1992 $content = $content->addSectionHeader( $this->sectiontitle
);
1993 } elseif ( $this->summary
!== '' ) {
1994 // Insert the section title above the content.
1995 $content = $content->addSectionHeader( $this->summary
);
1997 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2000 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2004 # Article exists. Check for edit conflict.
2006 $this->page
->clear(); # Force reload of dates, etc.
2007 $timestamp = $this->page
->getTimestamp();
2008 $latest = $this->page
->getLatest();
2010 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2012 // Check editRevId if set, which handles same-second timestamp collisions
2013 if ( $timestamp != $this->edittime
2014 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2016 $this->isConflict
= true;
2017 if ( $this->section
== 'new' ) {
2018 if ( $this->page
->getUserText() == $user->getName() &&
2019 $this->page
->getComment() == $this->newSectionSummary()
2021 // Probably a duplicate submission of a new comment.
2022 // This can happen when CDN resends a request after
2023 // a timeout but the first one actually went through.
2025 . ": duplicate new section submission; trigger edit conflict!\n" );
2027 // New comment; suppress conflict.
2028 $this->isConflict
= false;
2029 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2031 } elseif ( $this->section
== ''
2032 && Revision
::userWasLastToEdit(
2033 DB_MASTER
, $this->mTitle
->getArticleID(),
2034 $user->getId(), $this->edittime
2037 # Suppress edit conflict with self, except for section edits where merging is required.
2038 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2039 $this->isConflict
= false;
2043 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2044 if ( $this->sectiontitle
!== '' ) {
2045 $sectionTitle = $this->sectiontitle
;
2047 $sectionTitle = $this->summary
;
2052 if ( $this->isConflict
) {
2054 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2055 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2056 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2057 // ...or disable section editing for non-current revisions (not exposed anyway).
2058 if ( $this->editRevId
!== null ) {
2059 $content = $this->page
->replaceSectionAtRev(
2066 $content = $this->page
->replaceSectionContent(
2074 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2075 $content = $this->page
->replaceSectionContent(
2082 if ( is_null( $content ) ) {
2083 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2084 $this->isConflict
= true;
2085 $content = $textbox_content; // do not try to merge here!
2086 } elseif ( $this->isConflict
) {
2088 if ( $this->mergeChangesIntoContent( $content ) ) {
2089 // Successful merge! Maybe we should tell the user the good news?
2090 $this->isConflict
= false;
2091 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2093 $this->section
= '';
2094 $this->textbox1
= ContentHandler
::getContentText( $content );
2095 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2099 if ( $this->isConflict
) {
2100 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2104 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2108 if ( $this->section
== 'new' ) {
2109 // Handle the user preference to force summaries here
2110 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2111 $this->missingSummary
= true;
2112 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2113 $status->value
= self
::AS_SUMMARY_NEEDED
;
2117 // Do not allow the user to post an empty comment
2118 if ( $this->textbox1
== '' ) {
2119 $this->missingComment
= true;
2120 $status->fatal( 'missingcommenttext' );
2121 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2124 } elseif ( !$this->allowBlankSummary
2125 && !$content->equals( $this->getOriginalContent( $user ) )
2126 && !$content->isRedirect()
2127 && md5( $this->summary
) == $this->autoSumm
2129 $this->missingSummary
= true;
2130 $status->fatal( 'missingsummary' );
2131 $status->value
= self
::AS_SUMMARY_NEEDED
;
2136 $sectionanchor = '';
2137 if ( $this->section
== 'new' ) {
2138 $this->summary
= $this->newSectionSummary( $sectionanchor );
2139 } elseif ( $this->section
!= '' ) {
2140 # Try to get a section anchor from the section source, redirect
2141 # to edited section if header found.
2142 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2143 # for duplicate heading checking and maybe parsing.
2144 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2145 # We can't deal with anchors, includes, html etc in the header for now,
2146 # headline would need to be parsed to improve this.
2147 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2148 $sectionanchor = $this->guessSectionName( $matches[2] );
2151 $result['sectionanchor'] = $sectionanchor;
2153 // Save errors may fall down to the edit form, but we've now
2154 // merged the section into full text. Clear the section field
2155 // so that later submission of conflict forms won't try to
2156 // replace that into a duplicated mess.
2157 $this->textbox1
= $this->toEditText( $content );
2158 $this->section
= '';
2160 $status->value
= self
::AS_SUCCESS_UPDATE
;
2163 if ( !$this->allowSelfRedirect
2164 && $content->isRedirect()
2165 && $content->getRedirectTarget()->equals( $this->getTitle() )
2167 // If the page already redirects to itself, don't warn.
2168 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2169 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2170 $this->selfRedirect
= true;
2171 $status->fatal( 'selfredirect' );
2172 $status->value
= self
::AS_SELF_REDIRECT
;
2177 // Check for length errors again now that the section is merged in
2178 $this->contentLength
= strlen( $this->toEditText( $content ) );
2179 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
2180 $this->tooBig
= true;
2181 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2185 $flags = EDIT_AUTOSUMMARY |
2186 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2187 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2188 ( $bot ? EDIT_FORCE_BOT
: 0 );
2190 $doEditStatus = $this->page
->doEditContent(
2196 $content->getDefaultFormat(),
2201 if ( !$doEditStatus->isOK() ) {
2202 // Failure from doEdit()
2203 // Show the edit conflict page for certain recognized errors from doEdit(),
2204 // but don't show it for errors from extension hooks
2205 $errors = $doEditStatus->getErrorsArray();
2206 if ( in_array( $errors[0][0],
2207 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2209 $this->isConflict
= true;
2210 // Destroys data doEdit() put in $status->value but who cares
2211 $doEditStatus->value
= self
::AS_END
;
2213 return $doEditStatus;
2216 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2217 if ( $result['nullEdit'] ) {
2218 // We don't know if it was a null edit until now, so increment here
2219 $user->pingLimiter( 'linkpurge' );
2221 $result['redirect'] = $content->isRedirect();
2223 $this->updateWatchlist();
2225 // If the content model changed, add a log entry
2226 if ( $changingContentModel ) {
2227 $this->addContentModelChangeLogEntry(
2229 $new ?
false : $oldContentModel,
2230 $this->contentModel
,
2240 * @param string|false $oldModel false if the page is being newly created
2241 * @param string $newModel
2242 * @param string $reason
2244 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2245 $new = $oldModel === false;
2246 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2247 $log->setPerformer( $user );
2248 $log->setTarget( $this->mTitle
);
2249 $log->setComment( $reason );
2250 $log->setParameters( [
2251 '4::oldmodel' => $oldModel,
2252 '5::newmodel' => $newModel
2254 $logid = $log->insert();
2255 $log->publish( $logid );
2259 * Register the change of watch status
2261 protected function updateWatchlist() {
2262 $user = $this->context
->getUser();
2263 if ( !$user->isLoggedIn() ) {
2267 $title = $this->mTitle
;
2268 $watch = $this->watchthis
;
2269 // Do this in its own transaction to reduce contention...
2270 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2271 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2272 return; // nothing to change
2274 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2279 * Attempts to do 3-way merge of edit content with a base revision
2280 * and current content, in case of edit conflict, in whichever way appropriate
2281 * for the content type.
2285 * @param Content $editContent
2289 private function mergeChangesIntoContent( &$editContent ) {
2290 $db = wfGetDB( DB_MASTER
);
2292 // This is the revision the editor started from
2293 $baseRevision = $this->getBaseRevision();
2294 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2296 if ( is_null( $baseContent ) ) {
2300 // The current state, we want to merge updates into it
2301 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2302 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2304 if ( is_null( $currentContent ) ) {
2308 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2310 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2313 $editContent = $result;
2314 // Update parentRevId to what we just merged.
2315 $this->parentRevId
= $currentRevision->getId();
2323 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2324 * one might think of X as the "base revision", which is NOT what this returns.
2325 * @return Revision Current version when the edit was started
2327 public function getBaseRevision() {
2328 if ( !$this->mBaseRevision
) {
2329 $db = wfGetDB( DB_MASTER
);
2330 $this->mBaseRevision
= $this->editRevId
2331 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2332 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2334 return $this->mBaseRevision
;
2338 * Check given input text against $wgSpamRegex, and return the text of the first match.
2340 * @param string $text
2342 * @return string|bool Matching string or false
2344 public static function matchSpamRegex( $text ) {
2345 global $wgSpamRegex;
2346 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2347 $regexes = (array)$wgSpamRegex;
2348 return self
::matchSpamRegexInternal( $text, $regexes );
2352 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2354 * @param string $text
2356 * @return string|bool Matching string or false
2358 public static function matchSummarySpamRegex( $text ) {
2359 global $wgSummarySpamRegex;
2360 $regexes = (array)$wgSummarySpamRegex;
2361 return self
::matchSpamRegexInternal( $text, $regexes );
2365 * @param string $text
2366 * @param array $regexes
2367 * @return bool|string
2369 protected static function matchSpamRegexInternal( $text, $regexes ) {
2370 foreach ( $regexes as $regex ) {
2372 if ( preg_match( $regex, $text, $matches ) ) {
2379 public function setHeaders() {
2380 global $wgAjaxEditStash;
2382 $out = $this->context
->getOutput();
2384 $out->addModules( 'mediawiki.action.edit' );
2385 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2387 $user = $this->context
->getUser();
2388 if ( $user->getOption( 'showtoolbar' ) ) {
2389 // The addition of default buttons is handled by getEditToolbar() which
2390 // has its own dependency on this module. The call here ensures the module
2391 // is loaded in time (it has position "top") for other modules to register
2392 // buttons (e.g. extensions, gadgets, user scripts).
2393 $out->addModules( 'mediawiki.toolbar' );
2396 if ( $user->getOption( 'uselivepreview' ) ) {
2397 $out->addModules( 'mediawiki.action.edit.preview' );
2400 if ( $user->getOption( 'useeditwarning' ) ) {
2401 $out->addModules( 'mediawiki.action.edit.editWarning' );
2404 # Enabled article-related sidebar, toplinks, etc.
2405 $out->setArticleRelated( true );
2407 $contextTitle = $this->getContextTitle();
2408 if ( $this->isConflict
) {
2409 $msg = 'editconflict';
2410 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2411 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2413 $msg = $contextTitle->exists()
2414 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2415 && $contextTitle->getDefaultMessageText() !== false
2421 # Use the title defined by DISPLAYTITLE magic word when present
2422 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2423 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2424 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2425 if ( $displayTitle === false ) {
2426 $displayTitle = $contextTitle->getPrefixedText();
2428 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2429 # Transmit the name of the message to JavaScript for live preview
2430 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2431 $out->addJsConfigVars( [
2432 'wgEditMessage' => $msg,
2433 'wgAjaxEditStash' => $wgAjaxEditStash,
2438 * Show all applicable editing introductions
2440 protected function showIntro() {
2441 if ( $this->suppressIntro
) {
2445 $out = $this->context
->getOutput();
2446 $namespace = $this->mTitle
->getNamespace();
2448 if ( $namespace == NS_MEDIAWIKI
) {
2449 # Show a warning if editing an interface message
2450 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2451 # If this is a default message (but not css or js),
2452 # show a hint that it is translatable on translatewiki.net
2453 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2454 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2456 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2457 if ( $defaultMessageText !== false ) {
2458 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2459 'translateinterface' );
2462 } elseif ( $namespace == NS_FILE
) {
2463 # Show a hint to shared repo
2464 $file = wfFindFile( $this->mTitle
);
2465 if ( $file && !$file->isLocal() ) {
2466 $descUrl = $file->getDescriptionUrl();
2467 # there must be a description url to show a hint to shared repo
2469 if ( !$this->mTitle
->exists() ) {
2470 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2471 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2474 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2475 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2482 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2483 # Show log extract when the user is currently blocked
2484 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2485 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2486 $user = User
::newFromName( $username, false /* allow IP users */ );
2487 $ip = User
::isIP( $username );
2488 $block = Block
::newFromTarget( $user, $user );
2489 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2490 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2491 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2492 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2493 # Show log extract if the user is currently blocked
2494 LogEventsList
::showLogExtract(
2497 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2501 'showIfEmpty' => false,
2503 'blocked-notice-logextract',
2504 $user->getName() # Support GENDER in notice
2510 # Try to add a custom edit intro, or use the standard one if this is not possible.
2511 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2512 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2513 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2515 if ( $this->context
->getUser()->isLoggedIn() ) {
2517 // Suppress the external link icon, consider the help url an internal one
2518 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2526 // Suppress the external link icon, consider the help url an internal one
2527 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2529 'newarticletextanon',
2535 # Give a notice if the user is editing a deleted/moved page...
2536 if ( !$this->mTitle
->exists() ) {
2537 $dbr = wfGetDB( DB_REPLICA
);
2539 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2543 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2544 'showIfEmpty' => false,
2545 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2552 * Attempt to show a custom editing introduction, if supplied
2556 protected function showCustomIntro() {
2557 if ( $this->editintro
) {
2558 $title = Title
::newFromText( $this->editintro
);
2559 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2560 // Added using template syntax, to take <noinclude>'s into account.
2561 $this->context
->getOutput()->addWikiTextTitleTidy(
2562 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2572 * Gets an editable textual representation of $content.
2573 * The textual representation can be turned by into a Content object by the
2574 * toEditContent() method.
2576 * If $content is null or false or a string, $content is returned unchanged.
2578 * If the given Content object is not of a type that can be edited using
2579 * the text base EditPage, an exception will be raised. Set
2580 * $this->allowNonTextContent to true to allow editing of non-textual
2583 * @param Content|null|bool|string $content
2584 * @return string The editable text form of the content.
2586 * @throws MWException If $content is not an instance of TextContent and
2587 * $this->allowNonTextContent is not true.
2589 protected function toEditText( $content ) {
2590 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2594 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2595 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2598 return $content->serialize( $this->contentFormat
);
2602 * Turns the given text into a Content object by unserializing it.
2604 * If the resulting Content object is not of a type that can be edited using
2605 * the text base EditPage, an exception will be raised. Set
2606 * $this->allowNonTextContent to true to allow editing of non-textual
2609 * @param string|null|bool $text Text to unserialize
2610 * @return Content|bool|null The content object created from $text. If $text was false
2611 * or null, false resp. null will be returned instead.
2613 * @throws MWException If unserializing the text results in a Content
2614 * object that is not an instance of TextContent and
2615 * $this->allowNonTextContent is not true.
2617 protected function toEditContent( $text ) {
2618 if ( $text === false ||
$text === null ) {
2622 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2623 $this->contentModel
, $this->contentFormat
);
2625 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2626 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2633 * Send the edit form and related headers to OutputPage
2634 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2635 * during form output near the top, for captchas and the like.
2637 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2638 * use the EditPage::showEditForm:fields hook instead.
2640 public function showEditForm( $formCallback = null ) {
2641 # need to parse the preview early so that we know which templates are used,
2642 # otherwise users with "show preview after edit box" will get a blank list
2643 # we parse this near the beginning so that setHeaders can do the title
2644 # setting work instead of leaving it in getPreviewText
2645 $previewOutput = '';
2646 if ( $this->formtype
== 'preview' ) {
2647 $previewOutput = $this->getPreviewText();
2650 $out = $this->context
->getOutput();
2652 // Avoid PHP 7.1 warning of passing $this by reference
2654 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2656 $this->setHeaders();
2658 $this->addTalkPageText();
2659 $this->addEditNotices();
2661 if ( !$this->isConflict
&&
2662 $this->section
!= '' &&
2663 !$this->isSectionEditSupported() ) {
2664 // We use $this->section to much before this and getVal('wgSection') directly in other places
2665 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2666 // Someone is welcome to try refactoring though
2667 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2671 $this->showHeader();
2673 $out->addHTML( $this->editFormPageTop
);
2675 $user = $this->context
->getUser();
2676 if ( $user->getOption( 'previewontop' ) ) {
2677 $this->displayPreviewArea( $previewOutput, true );
2680 $out->addHTML( $this->editFormTextTop
);
2682 $showToolbar = true;
2683 if ( $this->wasDeletedSinceLastEdit() ) {
2684 if ( $this->formtype
== 'save' ) {
2685 // Hide the toolbar and edit area, user can click preview to get it back
2686 // Add an confirmation checkbox and explanation.
2687 $showToolbar = false;
2689 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2690 'deletedwhileediting' );
2694 // @todo add EditForm plugin interface and use it here!
2695 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2696 $out->addHTML( Html
::openElement(
2699 'class' => 'mw-editform',
2700 'id' => self
::EDITFORM_ID
,
2701 'name' => self
::EDITFORM_ID
,
2703 'action' => $this->getActionURL( $this->getContextTitle() ),
2704 'enctype' => 'multipart/form-data'
2708 if ( is_callable( $formCallback ) ) {
2709 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2710 call_user_func_array( $formCallback, [ &$out ] );
2713 // Add a check for Unicode support
2714 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2716 // Add an empty field to trip up spambots
2718 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2721 [ 'for' => 'wpAntispam' ],
2722 $this->context
->msg( 'simpleantispam-label' )->parse()
2728 'name' => 'wpAntispam',
2729 'id' => 'wpAntispam',
2733 . Xml
::closeElement( 'div' )
2736 // Avoid PHP 7.1 warning of passing $this by reference
2738 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2740 // Put these up at the top to ensure they aren't lost on early form submission
2741 $this->showFormBeforeText();
2743 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2744 $username = $this->lastDelete
->user_name
;
2745 $comment = CommentStore
::newKey( 'log_comment' )->getComment( $this->lastDelete
)->text
;
2747 // It is better to not parse the comment at all than to have templates expanded in the middle
2748 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2749 $key = $comment === ''
2750 ?
'confirmrecreate-noreason'
2751 : 'confirmrecreate';
2753 '<div class="mw-confirm-recreate">' .
2754 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2755 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2756 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2762 # When the summary is hidden, also hide them on preview/show changes
2763 if ( $this->nosummary
) {
2764 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2767 # If a blank edit summary was previously provided, and the appropriate
2768 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2769 # user being bounced back more than once in the event that a summary
2772 # For a bit more sophisticated detection of blank summaries, hash the
2773 # automatic one and pass that in the hidden field wpAutoSummary.
2774 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2775 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2778 if ( $this->undidRev
) {
2779 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2782 if ( $this->selfRedirect
) {
2783 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2786 if ( $this->hasPresetSummary
) {
2787 // If a summary has been preset using &summary= we don't want to prompt for
2788 // a different summary. Only prompt for a summary if the summary is blanked.
2790 $this->autoSumm
= md5( '' );
2793 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2794 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2796 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2797 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2799 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2800 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2804 if ( $this->section
== 'new' ) {
2805 $this->showSummaryInput( true, $this->summary
);
2806 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2809 $out->addHTML( $this->editFormTextBeforeContent
);
2811 if ( !$this->mTitle
->isCssJsSubpage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2812 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2815 if ( $this->blankArticle
) {
2816 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2819 if ( $this->isConflict
) {
2820 // In an edit conflict bypass the overridable content form method
2821 // and fallback to the raw wpTextbox1 since editconflicts can't be
2822 // resolved between page source edits and custom ui edits using the
2824 $this->textbox2
= $this->textbox1
;
2826 $content = $this->getCurrentContent();
2827 $this->textbox1
= $this->toEditText( $content );
2829 $this->showTextbox1();
2831 $this->showContentForm();
2834 $out->addHTML( $this->editFormTextAfterContent
);
2836 $this->showStandardInputs();
2838 $this->showFormAfterText();
2840 $this->showTosSummary();
2842 $this->showEditTools();
2844 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2846 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2848 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2849 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2851 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2852 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2854 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2856 if ( $this->isConflict
) {
2858 $this->showConflict();
2859 } catch ( MWContentSerializationException
$ex ) {
2860 // this can't really happen, but be nice if it does.
2861 $msg = $this->context
->msg(
2862 'content-failed-to-parse',
2863 $this->contentModel
,
2864 $this->contentFormat
,
2867 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2871 // Set a hidden field so JS knows what edit form mode we are in
2872 if ( $this->isConflict
) {
2874 } elseif ( $this->preview
) {
2876 } elseif ( $this->diff
) {
2881 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2883 // Marker for detecting truncated form data. This must be the last
2884 // parameter sent in order to be of use, so do not move me.
2885 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2886 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2888 if ( !$user->getOption( 'previewontop' ) ) {
2889 $this->displayPreviewArea( $previewOutput, false );
2894 * Wrapper around TemplatesOnThisPageFormatter to make
2895 * a "templates on this page" list.
2897 * @param Title[] $templates
2898 * @return string HTML
2900 public function makeTemplatesOnThisPageList( array $templates ) {
2901 $templateListFormatter = new TemplatesOnThisPageFormatter(
2902 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2905 // preview if preview, else section if section, else false
2907 if ( $this->preview
) {
2909 } elseif ( $this->section
!= '' ) {
2913 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2914 $templateListFormatter->format( $templates, $type )
2919 * Extract the section title from current section text, if any.
2921 * @param string $text
2922 * @return string|bool String or false
2924 public static function extractSectionTitle( $text ) {
2925 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2926 if ( !empty( $matches[2] ) ) {
2928 return $wgParser->stripSectionName( trim( $matches[2] ) );
2934 protected function showHeader() {
2935 global $wgAllowUserCss, $wgAllowUserJs;
2937 $out = $this->context
->getOutput();
2938 $user = $this->context
->getUser();
2939 if ( $this->isConflict
) {
2940 $this->addExplainConflictHeader( $out );
2941 $this->editRevId
= $this->page
->getLatest();
2943 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2944 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2945 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2946 if ( $sectionTitle !== false ) {
2947 $this->summary
= "/* $sectionTitle */ ";
2952 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
2954 if ( $this->missingComment
) {
2955 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2958 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2960 "<div id='mw-missingsummary'>\n$1\n</div>",
2961 [ 'missingsummary', $buttonLabel ]
2965 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2967 "<div id='mw-missingcommentheader'>\n$1\n</div>",
2968 [ 'missingcommentheader', $buttonLabel ]
2972 if ( $this->blankArticle
) {
2974 "<div id='mw-blankarticle'>\n$1\n</div>",
2975 [ 'blankarticle', $buttonLabel ]
2979 if ( $this->selfRedirect
) {
2981 "<div id='mw-selfredirect'>\n$1\n</div>",
2982 [ 'selfredirect', $buttonLabel ]
2986 if ( $this->hookError
!== '' ) {
2987 $out->addWikiText( $this->hookError
);
2990 if ( $this->section
!= 'new' ) {
2991 $revision = $this->mArticle
->getRevisionFetched();
2993 // Let sysop know that this will make private content public if saved
2995 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
2997 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2998 'rev-deleted-text-permission'
3000 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3002 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3003 'rev-deleted-text-view'
3007 if ( !$revision->isCurrent() ) {
3008 $this->mArticle
->setOldSubtitle( $revision->getId() );
3009 $out->addWikiMsg( 'editingold' );
3010 $this->isOldRev
= true;
3012 } elseif ( $this->mTitle
->exists() ) {
3013 // Something went wrong
3015 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3016 [ 'missing-revision', $this->oldid
] );
3021 if ( wfReadOnly() ) {
3023 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3024 [ 'readonlywarning', wfReadOnlyReason() ]
3026 } elseif ( $user->isAnon() ) {
3027 if ( $this->formtype
!= 'preview' ) {
3029 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3030 [ 'anoneditwarning',
3032 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3033 'returnto' => $this->getTitle()->getPrefixedDBkey()
3036 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3037 'returnto' => $this->getTitle()->getPrefixedDBkey()
3042 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3043 'anonpreviewwarning'
3047 if ( $this->mTitle
->isCssJsSubpage() ) {
3048 # Check the skin exists
3049 if ( $this->isWrongCaseCssJsPage() ) {
3051 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
3052 [ 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ]
3055 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3056 $isCssSubpage = $this->mTitle
->isCssSubpage();
3057 $out->wrapWikiMsg( '<div class="mw-usercssjspublic">$1</div>',
3058 $isCssSubpage ?
'usercssispublic' : 'userjsispublic'
3060 if ( $this->formtype
!== 'preview' ) {
3061 if ( $isCssSubpage && $wgAllowUserCss ) {
3063 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3064 [ 'usercssyoucanpreview' ]
3068 if ( $this->mTitle
->isJsSubpage() && $wgAllowUserJs ) {
3070 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3071 [ 'userjsyoucanpreview' ]
3079 $this->addPageProtectionWarningHeaders();
3081 $this->addLongPageWarningHeader();
3083 # Add header copyright warning
3084 $this->showHeaderCopyrightWarning();
3088 * Helper function for summary input functions, which returns the neccessary
3089 * attributes for the input.
3091 * @param array|null $inputAttrs Array of attrs to use on the input
3094 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3095 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
3096 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3097 'id' => 'wpSummary',
3098 'name' => 'wpSummary',
3099 'maxlength' => '200',
3102 'spellcheck' => 'true',
3107 * Standard summary input and label (wgSummary), abstracted so EditPage
3108 * subclasses may reorganize the form.
3109 * Note that you do not need to worry about the label's for=, it will be
3110 * inferred by the id given to the input. You can remove them both by
3111 * passing [ 'id' => false ] to $userInputAttrs.
3113 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3114 * @param string $summary The value of the summary input
3115 * @param string $labelText The html to place inside the label
3116 * @param array $inputAttrs Array of attrs to use on the input
3117 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
3118 * @return array An array in the format [ $label, $input ]
3120 public function getSummaryInput( $summary = "", $labelText = null,
3121 $inputAttrs = null, $spanLabelAttrs = null
3123 wfDeprecated( __METHOD__
, '1.30' );
3124 $inputAttrs = $this->getSummaryInputAttributes( $inputAttrs );
3125 $inputAttrs +
= Linker
::tooltipAndAccesskeyAttribs( 'summary' );
3127 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : [] ) +
[
3128 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
3129 'id' => "wpSummaryLabel"
3136 $inputAttrs['id'] ?
[ 'for' => $inputAttrs['id'] ] : null,
3139 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
3142 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
3144 return [ $label, $input ];
3148 * Builds a standard summary input with a label.
3150 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3151 * @param string $summary The value of the summary input
3152 * @param string $labelText The html to place inside the label
3153 * @param array $inputAttrs Array of attrs to use on the input
3155 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3157 function getSummaryInputOOUI( $summary = "", $labelText = null, $inputAttrs = null ) {
3158 wfDeprecated( __METHOD__
, '1.30' );
3159 $this->getSummaryInputWidget( $summary, $labelText, $inputAttrs );
3163 * Builds a standard summary input with a label.
3165 * @param string $summary The value of the summary input
3166 * @param string $labelText The html to place inside the label
3167 * @param array $inputAttrs Array of attrs to use on the input
3169 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3171 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3172 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3173 $this->getSummaryInputAttributes( $inputAttrs )
3176 'title' => Linker
::titleAttrib( 'summary' ),
3177 'accessKey' => Linker
::accesskey( 'summary' ),
3180 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3181 $inputAttrs['inputId'] = $inputAttrs['id'];
3182 $inputAttrs['id'] = 'wpSummaryWidget';
3184 return new OOUI\
FieldLayout(
3185 new OOUI\
TextInputWidget( [
3186 'value' => $summary,
3187 'infusable' => true,
3190 'label' => new OOUI\
HtmlSnippet( $labelText ),
3192 'id' => 'wpSummaryLabel',
3193 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3199 * @param bool $isSubjectPreview True if this is the section subject/title
3200 * up top, or false if this is the comment summary
3201 * down below the textarea
3202 * @param string $summary The text of the summary to display
3204 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3205 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3206 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3207 if ( $isSubjectPreview ) {
3208 if ( $this->nosummary
) {
3212 if ( !$this->mShowSummaryField
) {
3217 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3218 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3221 [ 'class' => $summaryClass ]
3226 * @param bool $isSubjectPreview True if this is the section subject/title
3227 * up top, or false if this is the comment summary
3228 * down below the textarea
3229 * @param string $summary The text of the summary to display
3232 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3233 // avoid spaces in preview, gets always trimmed on save
3234 $summary = trim( $summary );
3235 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3241 if ( $isSubjectPreview ) {
3242 $summary = $this->context
->msg( 'newsectionsummary' )
3243 ->rawParams( $wgParser->stripSectionName( $summary ) )
3244 ->inContentLanguage()->text();
3247 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3249 $summary = $this->context
->msg( $message )->parse()
3250 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3251 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3254 protected function showFormBeforeText() {
3255 $out = $this->context
->getOutput();
3256 $out->addHTML( Html
::hidden( 'wpSection', htmlspecialchars( $this->section
) ) );
3257 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3258 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3259 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3260 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3263 protected function showFormAfterText() {
3265 * To make it harder for someone to slip a user a page
3266 * which submits an edit form to the wiki without their
3267 * knowledge, a random token is associated with the login
3268 * session. If it's not passed back with the submission,
3269 * we won't save the page, or render user JavaScript and
3272 * For anon editors, who may not have a session, we just
3273 * include the constant suffix to prevent editing from
3274 * broken text-mangling proxies.
3276 $this->context
->getOutput()->addHTML(
3278 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3284 * Subpage overridable method for printing the form for page content editing
3285 * By default this simply outputs wpTextbox1
3286 * Subclasses can override this to provide a custom UI for editing;
3287 * be it a form, or simply wpTextbox1 with a modified content that will be
3288 * reverse modified when extracted from the post data.
3289 * Note that this is basically the inverse for importContentFormData
3291 protected function showContentForm() {
3292 $this->showTextbox1();
3296 * Method to output wpTextbox1
3297 * The $textoverride method can be used by subclasses overriding showContentForm
3298 * to pass back to this method.
3300 * @param array $customAttribs Array of html attributes to use in the textarea
3301 * @param string $textoverride Optional text to override $this->textarea1 with
3303 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3304 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3305 $attribs = [ 'style' => 'display:none;' ];
3307 $classes = []; // Textarea CSS
3308 if ( $this->mTitle
->isProtected( 'edit' ) &&
3309 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
3311 # Is the title semi-protected?
3312 if ( $this->mTitle
->isSemiProtected() ) {
3313 $classes[] = 'mw-textarea-sprotected';
3315 # Then it must be protected based on static groups (regular)
3316 $classes[] = 'mw-textarea-protected';
3318 # Is the title cascade-protected?
3319 if ( $this->mTitle
->isCascadeProtected() ) {
3320 $classes[] = 'mw-textarea-cprotected';
3323 # Is an old revision being edited?
3324 if ( $this->isOldRev
) {
3325 $classes[] = 'mw-textarea-oldrev';
3328 $attribs = [ 'tabindex' => 1 ];
3330 if ( is_array( $customAttribs ) ) {
3331 $attribs +
= $customAttribs;
3334 if ( count( $classes ) ) {
3335 if ( isset( $attribs['class'] ) ) {
3336 $classes[] = $attribs['class'];
3338 $attribs['class'] = implode( ' ', $classes );
3343 $textoverride !== null ?
$textoverride : $this->textbox1
,
3349 protected function showTextbox2() {
3350 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3353 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3354 $wikitext = $this->addNewLineAtEnd( $text );
3356 $attribs = $this->buildTextboxAttribs( $name, $customAttribs, $this->context
->getUser() );
3358 $this->context
->getOutput()->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3361 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3364 $classes[] = 'ontop';
3367 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3369 if ( $this->formtype
!= 'preview' ) {
3370 $attribs['style'] = 'display: none;';
3373 $out = $this->context
->getOutput();
3374 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3376 if ( $this->formtype
== 'preview' ) {
3377 $this->showPreview( $previewOutput );
3379 // Empty content container for LivePreview
3380 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3381 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3382 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3383 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3386 $out->addHTML( '</div>' );
3388 if ( $this->formtype
== 'diff' ) {
3391 } catch ( MWContentSerializationException
$ex ) {
3392 $msg = $this->context
->msg(
3393 'content-failed-to-parse',
3394 $this->contentModel
,
3395 $this->contentFormat
,
3398 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3404 * Append preview output to OutputPage.
3405 * Includes category rendering if this is a category page.
3407 * @param string $text The HTML to be output for the preview.
3409 protected function showPreview( $text ) {
3410 if ( $this->mArticle
instanceof CategoryPage
) {
3411 $this->mArticle
->openShowCategory();
3413 # This hook seems slightly odd here, but makes things more
3414 # consistent for extensions.
3415 $out = $this->context
->getOutput();
3416 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3417 $out->addHTML( $text );
3418 if ( $this->mArticle
instanceof CategoryPage
) {
3419 $this->mArticle
->closeShowCategory();
3424 * Get a diff between the current contents of the edit box and the
3425 * version of the page we're editing from.
3427 * If this is a section edit, we'll replace the section as for final
3428 * save and then make a comparison.
3430 public function showDiff() {
3433 $oldtitlemsg = 'currentrev';
3434 # if message does not exist, show diff against the preloaded default
3435 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3436 $oldtext = $this->mTitle
->getDefaultMessageText();
3437 if ( $oldtext !== false ) {
3438 $oldtitlemsg = 'defaultmessagetext';
3439 $oldContent = $this->toEditContent( $oldtext );
3444 $oldContent = $this->getCurrentContent();
3447 $textboxContent = $this->toEditContent( $this->textbox1
);
3448 if ( $this->editRevId
!== null ) {
3449 $newContent = $this->page
->replaceSectionAtRev(
3450 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3453 $newContent = $this->page
->replaceSectionContent(
3454 $this->section
, $textboxContent, $this->summary
, $this->edittime
3458 if ( $newContent ) {
3459 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3461 $user = $this->context
->getUser();
3462 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
3463 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3466 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3467 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3468 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3470 if ( !$oldContent ) {
3471 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3474 if ( !$newContent ) {
3475 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3478 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3479 $de->setContent( $oldContent, $newContent );
3481 $difftext = $de->getDiff( $oldtitle, $newtitle );
3482 $de->showDiffStyle();
3487 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3491 * Show the header copyright warning.
3493 protected function showHeaderCopyrightWarning() {
3494 $msg = 'editpage-head-copy-warn';
3495 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3496 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3497 'editpage-head-copy-warn' );
3502 * Give a chance for site and per-namespace customizations of
3503 * terms of service summary link that might exist separately
3504 * from the copyright notice.
3506 * This will display between the save button and the edit tools,
3507 * so should remain short!
3509 protected function showTosSummary() {
3510 $msg = 'editpage-tos-summary';
3511 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3512 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3513 $out = $this->context
->getOutput();
3514 $out->addHTML( '<div class="mw-tos-summary">' );
3515 $out->addWikiMsg( $msg );
3516 $out->addHTML( '</div>' );
3521 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3522 * characters not present on most keyboards for copying/pasting.
3524 protected function showEditTools() {
3525 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3526 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3531 * Get the copyright warning
3533 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3536 protected function getCopywarn() {
3537 return self
::getCopyrightWarning( $this->mTitle
);
3541 * Get the copyright warning, by default returns wikitext
3543 * @param Title $title
3544 * @param string $format Output format, valid values are any function of a Message object
3545 * @param Language|string|null $langcode Language code or Language object.
3548 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3549 global $wgRightsText;
3550 if ( $wgRightsText ) {
3551 $copywarnMsg = [ 'copyrightwarning',
3552 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3555 $copywarnMsg = [ 'copyrightwarning2',
3556 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3558 // Allow for site and per-namespace customization of contribution/copyright notice.
3559 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3561 $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
3563 $msg->inLanguage( $langcode );
3565 return "<div id=\"editpage-copywarn\">\n" .
3566 $msg->$format() . "\n</div>";
3570 * Get the Limit report for page previews
3573 * @param ParserOutput $output ParserOutput object from the parse
3574 * @return string HTML
3576 public static function getPreviewLimitReport( $output ) {
3577 if ( !$output ||
!$output->getLimitReportData() ) {
3581 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3582 wfMessage( 'limitreport-title' )->parseAsBlock()
3585 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3586 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3588 $limitReport .= Html
::openElement( 'table', [
3589 'class' => 'preview-limit-report wikitable'
3591 Html
::openElement( 'tbody' );
3593 foreach ( $output->getLimitReportData() as $key => $value ) {
3594 if ( Hooks
::run( 'ParserLimitReportFormat',
3595 [ $key, &$value, &$limitReport, true, true ]
3597 $keyMsg = wfMessage( $key );
3598 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3599 if ( !$valueMsg->exists() ) {
3600 $valueMsg = new RawMessage( '$1' );
3602 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3603 $limitReport .= Html
::openElement( 'tr' ) .
3604 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3605 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3606 Html
::closeElement( 'tr' );
3611 $limitReport .= Html
::closeElement( 'tbody' ) .
3612 Html
::closeElement( 'table' ) .
3613 Html
::closeElement( 'div' );
3615 return $limitReport;
3618 protected function showStandardInputs( &$tabindex = 2 ) {
3619 $out = $this->context
->getOutput();
3620 $out->addHTML( "<div class='editOptions'>\n" );
3622 if ( $this->section
!= 'new' ) {
3623 $this->showSummaryInput( false, $this->summary
);
3624 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3627 $checkboxes = $this->getCheckboxesWidget(
3629 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3631 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3633 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3635 // Show copyright warning.
3636 $out->addWikiText( $this->getCopywarn() );
3637 $out->addHTML( $this->editFormTextAfterWarn
);
3639 $out->addHTML( "<div class='editButtons'>\n" );
3640 $out->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3642 $cancel = $this->getCancelLink();
3643 if ( $cancel !== '' ) {
3644 $cancel .= Html
::element( 'span',
3645 [ 'class' => 'mw-editButtons-pipe-separator' ],
3646 $this->context
->msg( 'pipe-separator' )->text() );
3649 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3650 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3653 $this->context
->msg( 'edithelp' )->text(),
3654 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3657 $this->context
->msg( 'word-separator' )->escaped() .
3658 $this->context
->msg( 'newwindow' )->parse();
3660 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3661 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3662 $out->addHTML( "</div><!-- editButtons -->\n" );
3664 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3666 $out->addHTML( "</div><!-- editOptions -->\n" );
3670 * Show an edit conflict. textbox1 is already shown in showEditForm().
3671 * If you want to use another entry point to this function, be careful.
3673 protected function showConflict() {
3674 $out = $this->context
->getOutput();
3675 // Avoid PHP 7.1 warning of passing $this by reference
3677 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3678 $this->incrementConflictStats();
3680 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3682 $content1 = $this->toEditContent( $this->textbox1
);
3683 $content2 = $this->toEditContent( $this->textbox2
);
3685 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3686 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3687 $de->setContent( $content2, $content1 );
3689 $this->context
->msg( 'yourtext' )->parse(),
3690 $this->context
->msg( 'storedversion' )->text()
3693 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3694 $this->showTextbox2();
3698 protected function incrementConflictStats() {
3699 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3700 $stats->increment( 'edit.failures.conflict' );
3701 // Only include 'standard' namespaces to avoid creating unknown numbers of statsd metrics
3703 $this->mTitle
->getNamespace() >= NS_MAIN
&&
3704 $this->mTitle
->getNamespace() <= NS_CATEGORY_TALK
3706 $stats->increment( 'edit.failures.conflict.byNamespaceId.' . $this->mTitle
->getNamespace() );
3713 public function getCancelLink() {
3715 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3716 $cancelParams['oldid'] = $this->oldid
;
3717 } elseif ( $this->getContextTitle()->isRedirect() ) {
3718 $cancelParams['redirect'] = 'no';
3721 return new OOUI\
ButtonWidget( [
3722 'id' => 'mw-editform-cancel',
3723 'href' => $this->getContextTitle()->getLinkUrl( $cancelParams ),
3724 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3726 'infusable' => true,
3727 'flags' => 'destructive',
3732 * Returns the URL to use in the form's action attribute.
3733 * This is used by EditPage subclasses when simply customizing the action
3734 * variable in the constructor is not enough. This can be used when the
3735 * EditPage lives inside of a Special page rather than a custom page action.
3737 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3740 protected function getActionURL( Title
$title ) {
3741 return $title->getLocalURL( [ 'action' => $this->action
] );
3745 * Check if a page was deleted while the user was editing it, before submit.
3746 * Note that we rely on the logging table, which hasn't been always there,
3747 * but that doesn't matter, because this only applies to brand new
3751 protected function wasDeletedSinceLastEdit() {
3752 if ( $this->deletedSinceEdit
!== null ) {
3753 return $this->deletedSinceEdit
;
3756 $this->deletedSinceEdit
= false;
3758 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3759 $this->lastDelete
= $this->getLastDelete();
3760 if ( $this->lastDelete
) {
3761 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3762 if ( $deleteTime > $this->starttime
) {
3763 $this->deletedSinceEdit
= true;
3768 return $this->deletedSinceEdit
;
3772 * @return bool|stdClass
3774 protected function getLastDelete() {
3775 $dbr = wfGetDB( DB_REPLICA
);
3776 $commentQuery = CommentStore
::newKey( 'log_comment' )->getJoin();
3777 $data = $dbr->selectRow(
3778 [ 'logging', 'user' ] +
$commentQuery['tables'],
3789 ] +
$commentQuery['fields'], [
3790 'log_namespace' => $this->mTitle
->getNamespace(),
3791 'log_title' => $this->mTitle
->getDBkey(),
3792 'log_type' => 'delete',
3793 'log_action' => 'delete',
3797 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3799 'user' => [ 'JOIN', 'user_id=log_user' ],
3800 ] +
$commentQuery['joins']
3802 // Quick paranoid permission checks...
3803 if ( is_object( $data ) ) {
3804 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3805 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3808 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3809 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3810 $data->log_comment_data
= null;
3818 * Get the rendered text for previewing.
3819 * @throws MWException
3822 public function getPreviewText() {
3824 global $wgAllowUserCss, $wgAllowUserJs;
3826 $out = $this->context
->getOutput();
3828 if ( $wgRawHtml && !$this->mTokenOk
) {
3829 // Could be an offsite preview attempt. This is very unsafe if
3830 // HTML is enabled, as it could be an attack.
3832 if ( $this->textbox1
!== '' ) {
3833 // Do not put big scary notice, if previewing the empty
3834 // string, which happens when you initially edit
3835 // a category page, due to automatic preview-on-open.
3836 $parsedNote = $out->parse( "<div class='previewnote'>" .
3837 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3838 true, /* interface */true );
3840 $this->incrementEditFailureStats( 'session_loss' );
3847 $content = $this->toEditContent( $this->textbox1
);
3851 'AlternateEditPreview',
3852 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3854 return $previewHTML;
3857 # provide a anchor link to the editform
3858 $continueEditing = '<span class="mw-continue-editing">' .
3859 '[[#' . self
::EDITFORM_ID
. '|' .
3860 $this->context
->getLanguage()->getArrow() . ' ' .
3861 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3862 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3863 if ( $this->mTokenOkExceptSuffix
) {
3864 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3865 $this->incrementEditFailureStats( 'bad_token' );
3867 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3868 $this->incrementEditFailureStats( 'session_loss' );
3870 } elseif ( $this->incompleteForm
) {
3871 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3872 if ( $this->mTriedSave
) {
3873 $this->incrementEditFailureStats( 'incomplete_form' );
3876 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3879 # don't parse non-wikitext pages, show message about preview
3880 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3881 if ( $this->mTitle
->isCssJsSubpage() ) {
3883 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3889 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3891 if ( $level === 'user' && !$wgAllowUserCss ) {
3894 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3896 if ( $level === 'user' && !$wgAllowUserJs ) {
3903 # Used messages to make sure grep find them:
3904 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3905 if ( $level && $format ) {
3906 $note = "<div id='mw-{$level}{$format}preview'>" .
3907 $this->context
->msg( "{$level}{$format}preview" )->text() .
3908 ' ' . $continueEditing . "</div>";
3912 # If we're adding a comment, we need to show the
3913 # summary as the headline
3914 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3915 $content = $content->addSectionHeader( $this->summary
);
3918 $hook_args = [ $this, &$content ];
3919 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3921 $parserResult = $this->doPreviewParse( $content );
3922 $parserOutput = $parserResult['parserOutput'];
3923 $previewHTML = $parserResult['html'];
3924 $this->mParserOutput
= $parserOutput;
3925 $out->addParserOutputMetadata( $parserOutput );
3927 if ( count( $parserOutput->getWarnings() ) ) {
3928 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3931 } catch ( MWContentSerializationException
$ex ) {
3932 $m = $this->context
->msg(
3933 'content-failed-to-parse',
3934 $this->contentModel
,
3935 $this->contentFormat
,
3938 $note .= "\n\n" . $m->parse();
3942 if ( $this->isConflict
) {
3943 $conflict = '<h2 id="mw-previewconflict">'
3944 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3946 $conflict = '<hr />';
3949 $previewhead = "<div class='previewnote'>\n" .
3950 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3951 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3953 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3954 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3955 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3956 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3958 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3961 private function incrementEditFailureStats( $failureType ) {
3962 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3963 $stats->increment( 'edit.failures.' . $failureType );
3967 * Get parser options for a preview
3968 * @return ParserOptions
3970 protected function getPreviewParserOptions() {
3971 $parserOptions = $this->page
->makeParserOptions( $this->mArticle
->getContext() );
3972 $parserOptions->setIsPreview( true );
3973 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3974 $parserOptions->enableLimitReport();
3975 return $parserOptions;
3979 * Parse the page for a preview. Subclasses may override this class, in order
3980 * to parse with different options, or to otherwise modify the preview HTML.
3982 * @param Content $content The page content
3983 * @return array with keys:
3984 * - parserOutput: The ParserOutput object
3985 * - html: The HTML to be displayed
3987 protected function doPreviewParse( Content
$content ) {
3988 $user = $this->context
->getUser();
3989 $parserOptions = $this->getPreviewParserOptions();
3990 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
3991 $scopedCallback = $parserOptions->setupFakeRevision(
3992 $this->mTitle
, $pstContent, $user );
3993 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3994 ScopedCallback
::consume( $scopedCallback );
3995 $parserOutput->setEditSectionTokens( false ); // no section edit links
3997 'parserOutput' => $parserOutput,
3998 'html' => $parserOutput->getText() ];
4004 public function getTemplates() {
4005 if ( $this->preview ||
$this->section
!= '' ) {
4007 if ( !isset( $this->mParserOutput
) ) {
4010 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
4011 foreach ( array_keys( $template ) as $dbk ) {
4012 $templates[] = Title
::makeTitle( $ns, $dbk );
4017 return $this->mTitle
->getTemplateLinksFrom();
4022 * Shows a bulletin board style toolbar for common editing functions.
4023 * It can be disabled in the user preferences.
4025 * @param Title $title Title object for the page being edited (optional)
4028 public static function getEditToolbar( $title = null ) {
4029 global $wgContLang, $wgOut;
4030 global $wgEnableUploads, $wgForeignFileRepos;
4032 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
4033 $showSignature = true;
4035 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4039 * $toolarray is an array of arrays each of which includes the
4040 * opening tag, the closing tag, optionally a sample text that is
4041 * inserted between the two when no selection is highlighted
4042 * and. The tip text is shown when the user moves the mouse
4045 * Images are defined in ResourceLoaderEditToolbarModule.
4049 'id' => 'mw-editbutton-bold',
4051 'close' => '\'\'\'',
4052 'sample' => wfMessage( 'bold_sample' )->text(),
4053 'tip' => wfMessage( 'bold_tip' )->text(),
4056 'id' => 'mw-editbutton-italic',
4059 'sample' => wfMessage( 'italic_sample' )->text(),
4060 'tip' => wfMessage( 'italic_tip' )->text(),
4063 'id' => 'mw-editbutton-link',
4066 'sample' => wfMessage( 'link_sample' )->text(),
4067 'tip' => wfMessage( 'link_tip' )->text(),
4070 'id' => 'mw-editbutton-extlink',
4073 'sample' => wfMessage( 'extlink_sample' )->text(),
4074 'tip' => wfMessage( 'extlink_tip' )->text(),
4077 'id' => 'mw-editbutton-headline',
4080 'sample' => wfMessage( 'headline_sample' )->text(),
4081 'tip' => wfMessage( 'headline_tip' )->text(),
4083 $imagesAvailable ?
[
4084 'id' => 'mw-editbutton-image',
4085 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4087 'sample' => wfMessage( 'image_sample' )->text(),
4088 'tip' => wfMessage( 'image_tip' )->text(),
4090 $imagesAvailable ?
[
4091 'id' => 'mw-editbutton-media',
4092 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4094 'sample' => wfMessage( 'media_sample' )->text(),
4095 'tip' => wfMessage( 'media_tip' )->text(),
4098 'id' => 'mw-editbutton-nowiki',
4099 'open' => "<nowiki>",
4100 'close' => "</nowiki>",
4101 'sample' => wfMessage( 'nowiki_sample' )->text(),
4102 'tip' => wfMessage( 'nowiki_tip' )->text(),
4105 'id' => 'mw-editbutton-signature',
4106 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4109 'tip' => wfMessage( 'sig_tip' )->text(),
4112 'id' => 'mw-editbutton-hr',
4113 'open' => "\n----\n",
4116 'tip' => wfMessage( 'hr_tip' )->text(),
4120 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4121 foreach ( $toolarray as $tool ) {
4127 // Images are defined in ResourceLoaderEditToolbarModule
4129 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4130 // Older browsers show a "speedtip" type message only for ALT.
4131 // Ideally these should be different, realistically they
4132 // probably don't need to be.
4140 $script .= Xml
::encodeJsCall(
4141 'mw.toolbar.addButton',
4143 ResourceLoader
::inDebugMode()
4149 $toolbar = '<div id="toolbar"></div>';
4151 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4152 // Only add the old toolbar cruft to the page payload if the toolbar has not
4153 // been over-written by a hook caller
4154 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
4161 * Return an array of checkbox definitions.
4163 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4165 * Array values are associative arrays with the following keys:
4166 * - 'label-message' (required): message for label text
4167 * - 'id' (required): 'id' attribute for the `<input>`
4168 * - 'default' (required): default checkedness (true or false)
4169 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4170 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4171 * from messages like 'tooltip-foo', 'accesskey-foo'
4172 * - 'label-id' (optional): 'id' attribute for the `<label>`
4173 * - 'legacy-name' (optional): short name for backwards-compatibility
4174 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4175 * where bool indicates the checked status of the checkbox
4178 public function getCheckboxesDefinition( $checked ) {
4181 $user = $this->context
->getUser();
4182 // don't show the minor edit checkbox if it's a new page or section
4183 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4184 $checkboxes['wpMinoredit'] = [
4185 'id' => 'wpMinoredit',
4186 'label-message' => 'minoredit',
4187 // Uses messages: tooltip-minoredit, accesskey-minoredit
4188 'tooltip' => 'minoredit',
4189 'label-id' => 'mw-editpage-minoredit',
4190 'legacy-name' => 'minor',
4191 'default' => $checked['minor'],
4195 if ( $user->isLoggedIn() ) {
4196 $checkboxes['wpWatchthis'] = [
4197 'id' => 'wpWatchthis',
4198 'label-message' => 'watchthis',
4199 // Uses messages: tooltip-watch, accesskey-watch
4200 'tooltip' => 'watch',
4201 'label-id' => 'mw-editpage-watch',
4202 'legacy-name' => 'watch',
4203 'default' => $checked['watch'],
4208 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4214 * Returns an array of html code of the following checkboxes old style:
4217 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4218 * @param int &$tabindex Current tabindex
4219 * @param array $checked See getCheckboxesDefinition()
4222 public function getCheckboxes( &$tabindex, $checked ) {
4224 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4226 // Backwards-compatibility for the EditPageBeforeEditChecks hook
4227 if ( !$this->isNew
) {
4228 $checkboxes['minor'] = '';
4230 $checkboxes['watch'] = '';
4232 foreach ( $checkboxesDef as $name => $options ) {
4233 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4234 $label = $this->context
->msg( $options['label-message'] )->parse();
4236 'tabindex' => ++
$tabindex,
4237 'id' => $options['id'],
4240 'for' => $options['id'],
4242 if ( isset( $options['tooltip'] ) ) {
4243 $attribs['accesskey'] = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4244 $labelAttribs['title'] = Linker
::titleAttrib( $options['tooltip'], 'withaccess' );
4246 if ( isset( $options['title-message'] ) ) {
4247 $labelAttribs['title'] = $this->context
->msg( $options['title-message'] )->text();
4249 if ( isset( $options['label-id'] ) ) {
4250 $labelAttribs['id'] = $options['label-id'];
4253 Xml
::check( $name, $options['default'], $attribs ) .
4255 Xml
::tags( 'label', $labelAttribs, $label );
4257 $checkboxes[ $legacyName ] = $checkboxHtml;
4260 // Avoid PHP 7.1 warning of passing $this by reference
4262 Hooks
::run( 'EditPageBeforeEditChecks', [ &$editPage, &$checkboxes, &$tabindex ], '1.29' );
4267 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4268 * any other added by extensions.
4270 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4271 * @param int &$tabindex Current tabindex
4272 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4273 * status of the checkbox
4275 * @return array Associative array of string keys to OOUI\FieldLayout instances
4277 public function getCheckboxesOOUI( &$tabindex, $checked ) {
4278 return $this->getCheckboxesWidget( $tabindex, $checked );
4282 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4283 * any other added by extensions.
4285 * @param int &$tabindex Current tabindex
4286 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4287 * status of the checkbox
4289 * @return array Associative array of string keys to OOUI\FieldLayout instances
4291 public function getCheckboxesWidget( &$tabindex, $checked ) {
4293 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4295 foreach ( $checkboxesDef as $name => $options ) {
4296 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4300 if ( isset( $options['tooltip'] ) ) {
4301 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4302 $title = Linker
::titleAttrib( $options['tooltip'] );
4304 if ( isset( $options['title-message'] ) ) {
4305 $title = $this->context
->msg( $options['title-message'] )->text();
4308 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4309 new OOUI\
CheckboxInputWidget( [
4310 'tabIndex' => ++
$tabindex,
4311 'accessKey' => $accesskey,
4312 'id' => $options['id'] . 'Widget',
4313 'inputId' => $options['id'],
4315 'selected' => $options['default'],
4316 'infusable' => true,
4319 'align' => 'inline',
4320 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4322 'id' => isset( $options['label-id'] ) ?
$options['label-id'] : null,
4327 // Backwards-compatibility hack to run the EditPageBeforeEditChecks hook. It's important,
4328 // people have used it for the weirdest things completely unrelated to checkboxes...
4329 // And if we're gonna run it, might as well allow its legacy checkboxes to be shown.
4330 $legacyCheckboxes = [];
4331 if ( !$this->isNew
) {
4332 $legacyCheckboxes['minor'] = '';
4334 $legacyCheckboxes['watch'] = '';
4335 // Copy new-style checkboxes into an old-style structure
4336 foreach ( $checkboxes as $name => $oouiLayout ) {
4337 $legacyCheckboxes[$name] = (string)$oouiLayout;
4339 // Avoid PHP 7.1 warning of passing $this by reference
4341 Hooks
::run( 'EditPageBeforeEditChecks', [ &$ep, &$legacyCheckboxes, &$tabindex ], '1.29' );
4342 // Copy back any additional old-style checkboxes into the new-style structure
4343 foreach ( $legacyCheckboxes as $name => $html ) {
4344 if ( $html && !isset( $checkboxes[$name] ) ) {
4345 $checkboxes[$name] = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $html ) ] );
4353 * Get the message key of the label for the button to save the page
4357 protected function getSubmitButtonLabel() {
4359 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4361 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4362 $newPage = !$this->mTitle
->exists();
4364 if ( $labelAsPublish ) {
4365 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4367 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4370 return $buttonLabelKey;
4374 * Returns an array of html code of the following buttons:
4375 * save, diff and preview
4377 * @param int &$tabindex Current tabindex
4381 public function getEditButtons( &$tabindex ) {
4384 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4388 'tabindex' => ++
$tabindex,
4391 $saveConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4392 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4393 'id' => 'wpSaveWidget',
4394 'inputId' => 'wpSave',
4395 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4396 'useInputTag' => true,
4397 'flags' => [ 'constructive', 'primary' ],
4398 'label' => $buttonLabel,
4399 'infusable' => true,
4401 'title' => Linker
::titleAttrib( 'save' ),
4402 'accessKey' => Linker
::accesskey( 'save' ),
4406 'name' => 'wpPreview',
4407 'tabindex' => ++
$tabindex,
4410 $previewConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4411 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4412 'id' => 'wpPreviewWidget',
4413 'inputId' => 'wpPreview',
4414 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4415 'useInputTag' => true,
4416 'label' => $this->context
->msg( 'showpreview' )->text(),
4417 'infusable' => true,
4419 'title' => Linker
::titleAttrib( 'preview' ),
4420 'accessKey' => Linker
::accesskey( 'preview' ),
4421 ] +
$previewConfig );
4425 'tabindex' => ++
$tabindex,
4428 $diffConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4429 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4430 'id' => 'wpDiffWidget',
4431 'inputId' => 'wpDiff',
4432 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4433 'useInputTag' => true,
4434 'label' => $this->context
->msg( 'showdiff' )->text(),
4435 'infusable' => true,
4437 'title' => Linker
::titleAttrib( 'diff' ),
4438 'accessKey' => Linker
::accesskey( 'diff' ),
4441 // Avoid PHP 7.1 warning of passing $this by reference
4443 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4449 * Creates a basic error page which informs the user that
4450 * they have attempted to edit a nonexistent section.
4452 public function noSuchSectionPage() {
4453 $out = $this->context
->getOutput();
4454 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4456 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4458 // Avoid PHP 7.1 warning of passing $this by reference
4460 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4461 $out->addHTML( $res );
4463 $out->returnToMain( false, $this->mTitle
);
4467 * Show "your edit contains spam" page with your diff and text
4469 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4471 public function spamPageWithContent( $match = false ) {
4472 $this->textbox2
= $this->textbox1
;
4474 if ( is_array( $match ) ) {
4475 $match = $this->context
->getLanguage()->listToText( $match );
4477 $out = $this->context
->getOutput();
4478 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4480 $out->addHTML( '<div id="spamprotected">' );
4481 $out->addWikiMsg( 'spamprotectiontext' );
4483 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4485 $out->addHTML( '</div>' );
4487 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4490 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4491 $this->showTextbox2();
4493 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4497 * Filter an input field through a Unicode de-armoring process if it
4498 * came from an old browser with known broken Unicode editing issues.
4500 * @deprecated since 1.30, does nothing
4502 * @param WebRequest $request
4503 * @param string $field
4506 protected function safeUnicodeInput( $request, $field ) {
4507 return rtrim( $request->getText( $field ) );
4511 * Filter an output field through a Unicode armoring process if it is
4512 * going to an old browser with known broken Unicode editing issues.
4514 * @deprecated since 1.30, does nothing
4516 * @param string $text
4519 protected function safeUnicodeOutput( $text ) {
4526 protected function addEditNotices() {
4527 $out = $this->context
->getOutput();
4528 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4529 if ( count( $editNotices ) ) {
4530 $out->addHTML( implode( "\n", $editNotices ) );
4532 $msg = $this->context
->msg( 'editnotice-notext' );
4533 if ( !$msg->isDisabled() ) {
4535 '<div class="mw-editnotice-notext">'
4536 . $msg->parseAsBlock()
4546 protected function addTalkPageText() {
4547 if ( $this->mTitle
->isTalkPage() ) {
4548 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4555 protected function addLongPageWarningHeader() {
4556 global $wgMaxArticleSize;
4558 if ( $this->contentLength
=== false ) {
4559 $this->contentLength
= strlen( $this->textbox1
);
4562 $out = $this->context
->getOutput();
4563 $lang = $this->context
->getLanguage();
4564 if ( $this->tooBig ||
$this->contentLength
> $wgMaxArticleSize * 1024 ) {
4565 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4568 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4569 $lang->formatNum( $wgMaxArticleSize )
4573 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4574 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4577 $lang->formatSize( strlen( $this->textbox1
) ),
4578 strlen( $this->textbox1
)
4588 protected function addPageProtectionWarningHeaders() {
4589 $out = $this->context
->getOutput();
4590 if ( $this->mTitle
->isProtected( 'edit' ) &&
4591 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4593 # Is the title semi-protected?
4594 if ( $this->mTitle
->isSemiProtected() ) {
4595 $noticeMsg = 'semiprotectedpagewarning';
4597 # Then it must be protected based on static groups (regular)
4598 $noticeMsg = 'protectedpagewarning';
4600 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4601 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4603 if ( $this->mTitle
->isCascadeProtected() ) {
4604 # Is this page under cascading protection from some source pages?
4605 /** @var Title[] $cascadeSources */
4606 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4607 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4608 $cascadeSourcesCount = count( $cascadeSources );
4609 if ( $cascadeSourcesCount > 0 ) {
4610 # Explain, and list the titles responsible
4611 foreach ( $cascadeSources as $page ) {
4612 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4615 $notice .= '</div>';
4616 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4618 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4619 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4621 'showIfEmpty' => false,
4622 'msgKey' => [ 'titleprotectedwarning' ],
4623 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4628 * @param OutputPage $out
4631 protected function addExplainConflictHeader( OutputPage
$out ) {
4633 "<div class='mw-explainconflict'>\n$1\n</div>",
4634 [ 'explainconflict', $this->context
->msg( $this->getSubmitButtonLabel() )->text() ]
4639 * @param string $name
4640 * @param mixed[] $customAttribs
4645 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4646 $attribs = $customAttribs +
[
4651 // Avoid PHP notices when appending preferences
4652 // (appending allows customAttribs['style'] to still work).
4656 // The following classes can be used here:
4657 // * mw-editfont-default
4658 // * mw-editfont-monospace
4659 // * mw-editfont-sans-serif
4660 // * mw-editfont-serif
4661 $class = 'mw-editfont-' . $user->getOption( 'editfont' );
4663 if ( isset( $attribs['class'] ) ) {
4664 if ( is_string( $attribs['class'] ) ) {
4665 $attribs['class'] .= ' ' . $class;
4666 } elseif ( is_array( $attribs['class'] ) ) {
4667 $attribs['class'][] = $class;
4670 $attribs['class'] = $class;
4673 $pageLang = $this->mTitle
->getPageLanguage();
4674 $attribs['lang'] = $pageLang->getHtmlCode();
4675 $attribs['dir'] = $pageLang->getDir();
4681 * @param string $wikitext
4685 protected function addNewLineAtEnd( $wikitext ) {
4686 if ( strval( $wikitext ) !== '' ) {
4687 // Ensure there's a newline at the end, otherwise adding lines
4689 // But don't add a newline if the text is empty, or Firefox in XHTML
4690 // mode will show an extra newline. A bit annoying.
4698 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4699 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4700 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4701 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4702 * spread the new style links more efficiently.
4704 * @param string $text
4707 private function guessSectionName( $text ) {
4710 // Detect Microsoft browsers
4711 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4712 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4713 // ...and redirect them to legacy encoding, if available
4714 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4716 // Meanwhile, real browsers get real anchors
4717 return $wgParser->guessSectionNameFromWikiText( $text );