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 public $isCssJsSubpage = false;
237 public $isCssSubpage = false;
240 public $isJsSubpage = false;
243 public $isWrongCaseCssJsPage = false;
245 /** @var bool New page or new section */
246 public $isNew = false;
249 public $deletedSinceEdit;
257 /** @var bool|stdClass */
261 public $mTokenOk = false;
264 public $mTokenOkExceptSuffix = false;
267 public $mTriedSave = false;
270 public $incompleteForm = false;
273 public $tooBig = false;
276 public $missingComment = false;
279 public $missingSummary = false;
282 public $allowBlankSummary = false;
285 protected $blankArticle = false;
288 protected $allowBlankArticle = false;
291 protected $selfRedirect = false;
294 protected $allowSelfRedirect = false;
297 public $autoSumm = '';
300 public $hookError = '';
302 /** @var ParserOutput */
303 public $mParserOutput;
305 /** @var bool Has a summary been preset using GET parameter &summary= ? */
306 public $hasPresetSummary = false;
308 /** @var Revision|bool */
309 public $mBaseRevision = false;
312 public $mShowSummaryField = true;
317 public $save = false;
320 public $preview = false;
323 public $diff = false;
326 public $minoredit = false;
329 public $watchthis = false;
332 public $recreate = false;
335 public $textbox1 = '';
338 public $textbox2 = '';
341 public $summary = '';
344 public $nosummary = false;
347 public $edittime = '';
350 private $editRevId = null;
353 public $section = '';
356 public $sectiontitle = '';
359 public $starttime = '';
365 public $parentRevId = 0;
368 public $editintro = '';
371 public $scrolltop = null;
377 public $contentModel;
379 /** @var null|string */
380 public $contentFormat = null;
382 /** @var null|array */
383 private $changeTags = null;
385 # Placeholders for text injection by hooks (must be HTML)
386 # extensions should take care to _append_ to the present value
388 /** @var string Before even the preview */
389 public $editFormPageTop = '';
390 public $editFormTextTop = '';
391 public $editFormTextBeforeContent = '';
392 public $editFormTextAfterWarn = '';
393 public $editFormTextAfterTools = '';
394 public $editFormTextBottom = '';
395 public $editFormTextAfterContent = '';
396 public $previewTextAfterContent = '';
397 public $mPreloadContent = null;
399 /* $didSave should be set to true whenever an article was successfully altered. */
400 public $didSave = false;
401 public $undidRev = 0;
403 public $suppressIntro = false;
409 protected $contentLength = false;
412 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
414 private $enableApiEditOverride = false;
417 * @var IContextSource
422 * @var bool Whether an old revision is edited
424 private $isOldRev = false;
427 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
429 private $unicodeCheck;
432 * @param Article $article
434 public function __construct( Article
$article ) {
435 $this->mArticle
= $article;
436 $this->page
= $article->getPage(); // model object
437 $this->mTitle
= $article->getTitle();
438 $this->context
= $article->getContext();
440 $this->contentModel
= $this->mTitle
->getContentModel();
442 $handler = ContentHandler
::getForModelID( $this->contentModel
);
443 $this->contentFormat
= $handler->getDefaultFormat();
449 public function getArticle() {
450 return $this->mArticle
;
455 * @return IContextSource
457 public function getContext() {
458 return $this->context
;
465 public function getTitle() {
466 return $this->mTitle
;
470 * Set the context Title object
472 * @param Title|null $title Title object or null
474 public function setContextTitle( $title ) {
475 $this->mContextTitle
= $title;
479 * Get the context title object.
480 * If not set, $wgTitle will be returned. This behavior might change in
481 * the future to return $this->mTitle instead.
485 public function getContextTitle() {
486 if ( is_null( $this->mContextTitle
) ) {
489 __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.'
494 return $this->mContextTitle
;
499 * Check if the edit page is using OOUI controls
500 * @return bool Always true
501 * @deprecated since 1.30
503 public function isOouiEnabled() {
508 * Returns if the given content model is editable.
510 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
512 * @throws MWException If $modelId has no known handler
514 public function isSupportedContentModel( $modelId ) {
515 return $this->enableApiEditOverride
=== true ||
516 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
520 * Allow editing of content that supports API direct editing, but not general
521 * direct editing. Set to false by default.
523 * @param bool $enableOverride
525 public function setApiEditOverride( $enableOverride ) {
526 $this->enableApiEditOverride
= $enableOverride;
530 * @deprecated since 1.29, call edit directly
532 public function submit() {
533 wfDeprecated( __METHOD__
, '1.29' );
538 * This is the function that gets called for "action=edit". It
539 * sets up various member variables, then passes execution to
540 * another function, usually showEditForm()
542 * The edit form is self-submitting, so that when things like
543 * preview and edit conflicts occur, we get the same form back
544 * with the extra stuff added. Only when the final submission
545 * is made and all is well do we actually save and redirect to
546 * the newly-edited page.
548 public function edit() {
549 // Allow extensions to modify/prevent this form or submission
550 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
554 wfDebug( __METHOD__
. ": enter\n" );
556 $request = $this->context
->getRequest();
557 // If they used redlink=1 and the page exists, redirect to the main article
558 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
559 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
563 $this->importFormData( $request );
564 $this->firsttime
= false;
566 if ( wfReadOnly() && $this->save
) {
569 $this->preview
= true;
573 $this->formtype
= 'save';
574 } elseif ( $this->preview
) {
575 $this->formtype
= 'preview';
576 } elseif ( $this->diff
) {
577 $this->formtype
= 'diff';
578 } else { # First time through
579 $this->firsttime
= true;
580 if ( $this->previewOnOpen() ) {
581 $this->formtype
= 'preview';
583 $this->formtype
= 'initial';
587 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
589 wfDebug( __METHOD__
. ": User can't edit\n" );
590 // Auto-block user's IP if the account was "hard" blocked
591 if ( !wfReadOnly() ) {
592 DeferredUpdates
::addCallableUpdate( function () {
593 $this->context
->getUser()->spreadAnyEditBlock();
596 $this->displayPermissionsError( $permErrors );
601 $revision = $this->mArticle
->getRevisionFetched();
602 // Disallow editing revisions with content models different from the current one
603 // Undo edits being an exception in order to allow reverting content model changes.
605 && $revision->getContentModel() !== $this->contentModel
608 if ( $this->undidRev
) {
609 $undidRevObj = Revision
::newFromId( $this->undidRev
);
610 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
612 if ( !$this->undidRev
614 ||
$prevRev->getContentModel() !== $this->contentModel
616 $this->displayViewSourcePage(
617 $this->getContentObject(),
619 'contentmodelediterror',
620 $revision->getContentModel(),
628 $this->isConflict
= false;
629 // css / js subpages of user pages get a special treatment
630 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
631 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
632 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
633 // @todo FIXME: Silly assignment.
634 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
636 # Show applicable editing introductions
637 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
641 # Attempt submission here. This will check for edit conflicts,
642 # and redundantly check for locked database, blocked IPs, etc.
643 # that edit() already checked just in case someone tries to sneak
644 # in the back door with a hand-edited submission URL.
646 if ( 'save' == $this->formtype
) {
647 $resultDetails = null;
648 $status = $this->attemptSave( $resultDetails );
649 if ( !$this->handleStatus( $status, $resultDetails ) ) {
654 # First time through: get contents, set time for conflict
656 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
657 if ( $this->initialiseForm() === false ) {
658 $this->noSuchSectionPage();
662 if ( !$this->mTitle
->getArticleID() ) {
663 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
665 Hooks
::run( 'EditFormInitialText', [ $this ] );
670 $this->showEditForm();
674 * @param string $rigor Same format as Title::getUserPermissionErrors()
677 protected function getEditPermissionErrors( $rigor = 'secure' ) {
678 $user = $this->context
->getUser();
679 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
680 # Can this title be created?
681 if ( !$this->mTitle
->exists() ) {
682 $permErrors = array_merge(
685 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
690 # Ignore some permissions errors when a user is just previewing/viewing diffs
692 foreach ( $permErrors as $error ) {
693 if ( ( $this->preview ||
$this->diff
)
695 $error[0] == 'blockedtext' ||
696 $error[0] == 'autoblockedtext' ||
697 $error[0] == 'systemblockedtext'
703 $permErrors = wfArrayDiff2( $permErrors, $remove );
709 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
710 * but with the following differences:
711 * - If redlink=1, the user will be redirected to the page
712 * - If there is content to display or the error occurs while either saving,
713 * previewing or showing the difference, it will be a
714 * "View source for ..." page displaying the source code after the error message.
717 * @param array $permErrors Array of permissions errors, as returned by
718 * Title::getUserPermissionsErrors().
719 * @throws PermissionsError
721 protected function displayPermissionsError( array $permErrors ) {
722 $out = $this->context
->getOutput();
723 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
724 // The edit page was reached via a red link.
725 // Redirect to the article page and let them click the edit tab if
726 // they really want a permission error.
727 $out->redirect( $this->mTitle
->getFullURL() );
731 $content = $this->getContentObject();
733 # Use the normal message if there's nothing to display
734 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
735 $action = $this->mTitle
->exists() ?
'edit' :
736 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
737 throw new PermissionsError( $action, $permErrors );
740 $this->displayViewSourcePage(
742 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
747 * Display a read-only View Source page
748 * @param Content $content content object
749 * @param string $errorMessage additional wikitext error message to display
751 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
752 $out = $this->context
->getOutput();
753 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
755 $out->setRobotPolicy( 'noindex,nofollow' );
756 $out->setPageTitle( $this->context
->msg(
758 $this->getContextTitle()->getPrefixedText()
760 $out->addBacklinkSubtitle( $this->getContextTitle() );
761 $out->addHTML( $this->editFormPageTop
);
762 $out->addHTML( $this->editFormTextTop
);
764 if ( $errorMessage !== '' ) {
765 $out->addWikiText( $errorMessage );
766 $out->addHTML( "<hr />\n" );
769 # If the user made changes, preserve them when showing the markup
770 # (This happens when a user is blocked during edit, for instance)
771 if ( !$this->firsttime
) {
772 $text = $this->textbox1
;
773 $out->addWikiMsg( 'viewyourtext' );
776 $text = $this->toEditText( $content );
777 } catch ( MWException
$e ) {
778 # Serialize using the default format if the content model is not supported
779 # (e.g. for an old revision with a different model)
780 $text = $content->serialize();
782 $out->addWikiMsg( 'viewsourcetext' );
785 $out->addHTML( $this->editFormTextBeforeContent
);
786 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
787 $out->addHTML( $this->editFormTextAfterContent
);
789 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
791 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
793 $out->addHTML( $this->editFormTextBottom
);
794 if ( $this->mTitle
->exists() ) {
795 $out->returnToMain( null, $this->mTitle
);
800 * Should we show a preview when the edit form is first shown?
804 protected function previewOnOpen() {
805 global $wgPreviewOnOpenNamespaces;
806 $request = $this->context
->getRequest();
807 if ( $request->getVal( 'preview' ) == 'yes' ) {
808 // Explicit override from request
810 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
811 // Explicit override from request
813 } elseif ( $this->section
== 'new' ) {
814 // Nothing *to* preview for new sections
816 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
817 && $this->context
->getUser()->getOption( 'previewonfirst' )
819 // Standard preference behavior
821 } elseif ( !$this->mTitle
->exists()
822 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
823 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
825 // Categories are special
833 * Checks whether the user entered a skin name in uppercase,
834 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
838 protected function isWrongCaseCssJsPage() {
839 if ( $this->mTitle
->isCssJsSubpage() ) {
840 $name = $this->mTitle
->getSkinFromCssJsSubpage();
841 $skins = array_merge(
842 array_keys( Skin
::getSkinNames() ),
845 return !in_array( $name, $skins )
846 && in_array( strtolower( $name ), $skins );
853 * Returns whether section editing is supported for the current page.
854 * Subclasses may override this to replace the default behavior, which is
855 * to check ContentHandler::supportsSections.
857 * @return bool True if this edit page supports sections, false otherwise.
859 protected function isSectionEditSupported() {
860 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
861 return $contentHandler->supportsSections();
865 * This function collects the form data and uses it to populate various member variables.
866 * @param WebRequest &$request
867 * @throws ErrorPageError
869 public function importFormData( &$request ) {
870 # Section edit can come from either the form or a link
871 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
873 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
874 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
877 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
879 if ( $request->wasPosted() ) {
880 # These fields need to be checked for encoding.
881 # Also remove trailing whitespace, but don't remove _initial_
882 # whitespace from the text boxes. This may be significant formatting.
883 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
884 if ( !$request->getCheck( 'wpTextbox2' ) ) {
885 // Skip this if wpTextbox2 has input, it indicates that we came
886 // from a conflict page with raw page text, not a custom form
887 // modified by subclasses
888 $textbox1 = $this->importContentFormData( $request );
889 if ( $textbox1 !== null ) {
890 $this->textbox1
= $textbox1;
894 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
896 $this->summary
= $request->getText( 'wpSummary' );
898 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
899 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
901 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
903 # Treat sectiontitle the same way as summary.
904 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
905 # currently doing double duty as both edit summary and section title. Right now this
906 # is just to allow API edits to work around this limitation, but this should be
907 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
908 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
909 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
911 $this->edittime
= $request->getVal( 'wpEdittime' );
912 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
913 $this->starttime
= $request->getVal( 'wpStarttime' );
915 $undidRev = $request->getInt( 'wpUndidRevision' );
917 $this->undidRev
= $undidRev;
920 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
922 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
923 // wpTextbox1 field is missing, possibly due to being "too big"
924 // according to some filter rules such as Suhosin's setting for
925 // suhosin.request.max_value_length (d'oh)
926 $this->incompleteForm
= true;
928 // If we receive the last parameter of the request, we can fairly
929 // claim the POST request has not been truncated.
931 // TODO: softened the check for cutover. Once we determine
932 // that it is safe, we should complete the transition by
933 // removing the "edittime" clause.
934 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
935 && is_null( $this->edittime
) );
937 if ( $this->incompleteForm
) {
938 # If the form is incomplete, force to preview.
939 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
940 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
941 $this->preview
= true;
943 $this->preview
= $request->getCheck( 'wpPreview' );
944 $this->diff
= $request->getCheck( 'wpDiff' );
946 // Remember whether a save was requested, so we can indicate
947 // if we forced preview due to session failure.
948 $this->mTriedSave
= !$this->preview
;
950 if ( $this->tokenOk( $request ) ) {
951 # Some browsers will not report any submit button
952 # if the user hits enter in the comment box.
953 # The unmarked state will be assumed to be a save,
954 # if the form seems otherwise complete.
955 wfDebug( __METHOD__
. ": Passed token check.\n" );
956 } elseif ( $this->diff
) {
957 # Failed token check, but only requested "Show Changes".
958 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
960 # Page might be a hack attempt posted from
961 # an external site. Preview instead of saving.
962 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
963 $this->preview
= true;
966 $this->save
= !$this->preview
&& !$this->diff
;
967 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
968 $this->edittime
= null;
971 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
972 $this->starttime
= null;
975 $this->recreate
= $request->getCheck( 'wpRecreate' );
977 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
978 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
980 $user = $this->context
->getUser();
981 # Don't force edit summaries when a user is editing their own user or talk page
982 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
983 && $this->mTitle
->getText() == $user->getName()
985 $this->allowBlankSummary
= true;
987 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
988 ||
!$user->getOption( 'forceeditsummary' );
991 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
993 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
994 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
996 $changeTags = $request->getVal( 'wpChangeTags' );
997 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
998 $this->changeTags
= [];
1000 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1004 # Not a posted form? Start with nothing.
1005 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1006 $this->textbox1
= '';
1007 $this->summary
= '';
1008 $this->sectiontitle
= '';
1009 $this->edittime
= '';
1010 $this->editRevId
= null;
1011 $this->starttime
= wfTimestampNow();
1012 $this->edit
= false;
1013 $this->preview
= false;
1014 $this->save
= false;
1015 $this->diff
= false;
1016 $this->minoredit
= false;
1017 // Watch may be overridden by request parameters
1018 $this->watchthis
= $request->getBool( 'watchthis', false );
1019 $this->recreate
= false;
1021 // When creating a new section, we can preload a section title by passing it as the
1022 // preloadtitle parameter in the URL (T15100)
1023 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1024 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1025 // Once wpSummary isn't being use for setting section titles, we should delete this.
1026 $this->summary
= $request->getVal( 'preloadtitle' );
1027 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1028 $this->summary
= $request->getText( 'summary' );
1029 if ( $this->summary
!== '' ) {
1030 $this->hasPresetSummary
= true;
1034 if ( $request->getVal( 'minor' ) ) {
1035 $this->minoredit
= true;
1039 $this->oldid
= $request->getInt( 'oldid' );
1040 $this->parentRevId
= $request->getInt( 'parentRevId' );
1042 $this->bot
= $request->getBool( 'bot', true );
1043 $this->nosummary
= $request->getBool( 'nosummary' );
1045 // May be overridden by revision.
1046 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1047 // May be overridden by revision.
1048 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1051 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1052 } catch ( MWUnknownContentModelException
$e ) {
1053 throw new ErrorPageError(
1054 'editpage-invalidcontentmodel-title',
1055 'editpage-invalidcontentmodel-text',
1056 [ wfEscapeWikiText( $this->contentModel
) ]
1060 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1061 throw new ErrorPageError(
1062 'editpage-notsupportedcontentformat-title',
1063 'editpage-notsupportedcontentformat-text',
1065 wfEscapeWikiText( $this->contentFormat
),
1066 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1072 * @todo Check if the desired model is allowed in this namespace, and if
1073 * a transition from the page's current model to the new model is
1077 $this->editintro
= $request->getText( 'editintro',
1078 // Custom edit intro for new sections
1079 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1081 // Allow extensions to modify form data
1082 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1086 * Subpage overridable method for extracting the page content data from the
1087 * posted form to be placed in $this->textbox1, if using customized input
1088 * this method should be overridden and return the page text that will be used
1089 * for saving, preview parsing and so on...
1091 * @param WebRequest &$request
1092 * @return string|null
1094 protected function importContentFormData( &$request ) {
1095 return; // Don't do anything, EditPage already extracted wpTextbox1
1099 * Initialise form fields in the object
1100 * Called on the first invocation, e.g. when a user clicks an edit link
1101 * @return bool If the requested section is valid
1103 public function initialiseForm() {
1104 $this->edittime
= $this->page
->getTimestamp();
1105 $this->editRevId
= $this->page
->getLatest();
1107 $content = $this->getContentObject( false ); # TODO: track content object?!
1108 if ( $content === false ) {
1111 $this->textbox1
= $this->toEditText( $content );
1113 $user = $this->context
->getUser();
1114 // activate checkboxes if user wants them to be always active
1115 # Sort out the "watch" checkbox
1116 if ( $user->getOption( 'watchdefault' ) ) {
1118 $this->watchthis
= true;
1119 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1121 $this->watchthis
= true;
1122 } elseif ( $user->isWatched( $this->mTitle
) ) {
1124 $this->watchthis
= true;
1126 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1127 $this->minoredit
= true;
1129 if ( $this->textbox1
=== false ) {
1136 * @param Content|null $def_content The default value to return
1138 * @return Content|null Content on success, $def_content for invalid sections
1142 protected function getContentObject( $def_content = null ) {
1147 $user = $this->context
->getUser();
1148 $request = $this->context
->getRequest();
1149 // For message page not locally set, use the i18n message.
1150 // For other non-existent articles, use preload text if any.
1151 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1152 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1153 # If this is a system message, get the default text.
1154 $msg = $this->mTitle
->getDefaultMessageText();
1156 $content = $this->toEditContent( $msg );
1158 if ( $content === false ) {
1159 # If requested, preload some text.
1160 $preload = $request->getVal( 'preload',
1161 // Custom preload text for new sections
1162 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1163 $params = $request->getArray( 'preloadparams', [] );
1165 $content = $this->getPreloadedContent( $preload, $params );
1167 // For existing pages, get text based on "undo" or section parameters.
1169 if ( $this->section
!= '' ) {
1170 // Get section edit text (returns $def_text for invalid sections)
1171 $orig = $this->getOriginalContent( $user );
1172 $content = $orig ?
$orig->getSection( $this->section
) : null;
1175 $content = $def_content;
1178 $undoafter = $request->getInt( 'undoafter' );
1179 $undo = $request->getInt( 'undo' );
1181 if ( $undo > 0 && $undoafter > 0 ) {
1182 $undorev = Revision
::newFromId( $undo );
1183 $oldrev = Revision
::newFromId( $undoafter );
1185 # Sanity check, make sure it's the right page,
1186 # the revisions exist and they were not deleted.
1187 # Otherwise, $content will be left as-is.
1188 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1189 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1190 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1192 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1194 if ( $content === false ) {
1195 # Warn the user that something went wrong
1196 $undoMsg = 'failure';
1198 $oldContent = $this->page
->getContent( Revision
::RAW
);
1199 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1200 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1201 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1202 // The undo may change content
1203 // model if its reverting the top
1204 // edit. This can result in
1205 // mismatched content model/format.
1206 $this->contentModel
= $newContent->getModel();
1207 $this->contentFormat
= $oldrev->getContentFormat();
1210 if ( $newContent->equals( $oldContent ) ) {
1211 # Tell the user that the undo results in no change,
1212 # i.e. the revisions were already undone.
1213 $undoMsg = 'nochange';
1216 # Inform the user of our success and set an automatic edit summary
1217 $undoMsg = 'success';
1219 # If we just undid one rev, use an autosummary
1220 $firstrev = $oldrev->getNext();
1221 if ( $firstrev && $firstrev->getId() == $undo ) {
1222 $userText = $undorev->getUserText();
1223 if ( $userText === '' ) {
1224 $undoSummary = $this->context
->msg(
1225 'undo-summary-username-hidden',
1227 )->inContentLanguage()->text();
1229 $undoSummary = $this->context
->msg(
1233 )->inContentLanguage()->text();
1235 if ( $this->summary
=== '' ) {
1236 $this->summary
= $undoSummary;
1238 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1239 ->inContentLanguage()->text() . $this->summary
;
1241 $this->undidRev
= $undo;
1243 $this->formtype
= 'diff';
1247 // Failed basic sanity checks.
1248 // Older revisions may have been removed since the link
1249 // was created, or we may simply have got bogus input.
1253 $out = $this->context
->getOutput();
1254 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1255 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1256 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1257 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1260 if ( $content === false ) {
1261 $content = $this->getOriginalContent( $user );
1270 * Get the content of the wanted revision, without section extraction.
1272 * The result of this function can be used to compare user's input with
1273 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1274 * to the original text of the edit.
1276 * This differs from Article::getContent() that when a missing revision is
1277 * encountered the result will be null and not the
1278 * 'missing-revision' message.
1281 * @param User $user The user to get the revision for
1282 * @return Content|null
1284 private function getOriginalContent( User
$user ) {
1285 if ( $this->section
== 'new' ) {
1286 return $this->getCurrentContent();
1288 $revision = $this->mArticle
->getRevisionFetched();
1289 if ( $revision === null ) {
1290 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1291 return $handler->makeEmptyContent();
1293 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1298 * Get the edit's parent revision ID
1300 * The "parent" revision is the ancestor that should be recorded in this
1301 * page's revision history. It is either the revision ID of the in-memory
1302 * article content, or in the case of a 3-way merge in order to rebase
1303 * across a recoverable edit conflict, the ID of the newer revision to
1304 * which we have rebased this page.
1307 * @return int Revision ID
1309 public function getParentRevId() {
1310 if ( $this->parentRevId
) {
1311 return $this->parentRevId
;
1313 return $this->mArticle
->getRevIdFetched();
1318 * Get the current content of the page. This is basically similar to
1319 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1320 * content object is returned instead of null.
1325 protected function getCurrentContent() {
1326 $rev = $this->page
->getRevision();
1327 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1329 if ( $content === false ||
$content === null ) {
1330 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1331 return $handler->makeEmptyContent();
1332 } elseif ( !$this->undidRev
) {
1333 // Content models should always be the same since we error
1334 // out if they are different before this point (in ->edit()).
1335 // The exception being, during an undo, the current revision might
1336 // differ from the prior revision.
1337 $logger = LoggerFactory
::getInstance( 'editpage' );
1338 if ( $this->contentModel
!== $rev->getContentModel() ) {
1339 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1340 'prev' => $this->contentModel
,
1341 'new' => $rev->getContentModel(),
1342 'title' => $this->getTitle()->getPrefixedDBkey(),
1343 'method' => __METHOD__
1345 $this->contentModel
= $rev->getContentModel();
1348 // Given that the content models should match, the current selected
1349 // format should be supported.
1350 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1351 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1353 'prev' => $this->contentFormat
,
1354 'new' => $rev->getContentFormat(),
1355 'title' => $this->getTitle()->getPrefixedDBkey(),
1356 'method' => __METHOD__
1358 $this->contentFormat
= $rev->getContentFormat();
1365 * Use this method before edit() to preload some content into the edit box
1367 * @param Content $content
1371 public function setPreloadedContent( Content
$content ) {
1372 $this->mPreloadContent
= $content;
1376 * Get the contents to be preloaded into the box, either set by
1377 * an earlier setPreloadText() or by loading the given page.
1379 * @param string $preload Representing the title to preload from.
1380 * @param array $params Parameters to use (interface-message style) in the preloaded text
1386 protected function getPreloadedContent( $preload, $params = [] ) {
1387 if ( !empty( $this->mPreloadContent
) ) {
1388 return $this->mPreloadContent
;
1391 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1393 if ( $preload === '' ) {
1394 return $handler->makeEmptyContent();
1397 $user = $this->context
->getUser();
1398 $title = Title
::newFromText( $preload );
1399 # Check for existence to avoid getting MediaWiki:Noarticletext
1400 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1401 // TODO: somehow show a warning to the user!
1402 return $handler->makeEmptyContent();
1405 $page = WikiPage
::factory( $title );
1406 if ( $page->isRedirect() ) {
1407 $title = $page->getRedirectTarget();
1409 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1410 // TODO: somehow show a warning to the user!
1411 return $handler->makeEmptyContent();
1413 $page = WikiPage
::factory( $title );
1416 $parserOptions = ParserOptions
::newFromUser( $user );
1417 $content = $page->getContent( Revision
::RAW
);
1420 // TODO: somehow show a warning to the user!
1421 return $handler->makeEmptyContent();
1424 if ( $content->getModel() !== $handler->getModelID() ) {
1425 $converted = $content->convert( $handler->getModelID() );
1427 if ( !$converted ) {
1428 // TODO: somehow show a warning to the user!
1429 wfDebug( "Attempt to preload incompatible content: " .
1430 "can't convert " . $content->getModel() .
1431 " to " . $handler->getModelID() );
1433 return $handler->makeEmptyContent();
1436 $content = $converted;
1439 return $content->preloadTransform( $title, $parserOptions, $params );
1443 * Make sure the form isn't faking a user's credentials.
1445 * @param WebRequest &$request
1449 public function tokenOk( &$request ) {
1450 $token = $request->getVal( 'wpEditToken' );
1451 $user = $this->context
->getUser();
1452 $this->mTokenOk
= $user->matchEditToken( $token );
1453 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1454 return $this->mTokenOk
;
1458 * Sets post-edit cookie indicating the user just saved a particular revision.
1460 * This uses a temporary cookie for each revision ID so separate saves will never
1461 * interfere with each other.
1463 * Article::view deletes the cookie on server-side after the redirect and
1464 * converts the value to the global JavaScript variable wgPostEdit.
1466 * If the variable were set on the server, it would be cached, which is unwanted
1467 * since the post-edit state should only apply to the load right after the save.
1469 * @param int $statusValue The status value (to check for new article status)
1471 protected function setPostEditCookie( $statusValue ) {
1472 $revisionId = $this->page
->getLatest();
1473 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1476 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1478 } elseif ( $this->oldid
) {
1482 $response = $this->context
->getRequest()->response();
1483 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1487 * Attempt submission
1488 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1489 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1490 * @return Status The resulting status object.
1492 public function attemptSave( &$resultDetails = false ) {
1493 # Allow bots to exempt some edits from bot flagging
1494 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1495 $status = $this->internalAttemptSave( $resultDetails, $bot );
1497 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1503 * Log when a page was successfully saved after the edit conflict view
1505 private function incrementResolvedConflicts() {
1506 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1510 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1511 $stats->increment( 'edit.failures.conflict.resolved' );
1515 * Handle status, such as after attempt save
1517 * @param Status $status
1518 * @param array|bool $resultDetails
1520 * @throws ErrorPageError
1521 * @return bool False, if output is done, true if rest of the form should be displayed
1523 private function handleStatus( Status
$status, $resultDetails ) {
1525 * @todo FIXME: once the interface for internalAttemptSave() is made
1526 * nicer, this should use the message in $status
1528 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1529 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1531 $this->incrementResolvedConflicts();
1533 $this->didSave
= true;
1534 if ( !$resultDetails['nullEdit'] ) {
1535 $this->setPostEditCookie( $status->value
);
1539 $out = $this->context
->getOutput();
1541 // "wpExtraQueryRedirect" is a hidden input to modify
1542 // after save URL and is not used by actual edit form
1543 $request = $this->context
->getRequest();
1544 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1546 switch ( $status->value
) {
1547 case self
::AS_HOOK_ERROR_EXPECTED
:
1548 case self
::AS_CONTENT_TOO_BIG
:
1549 case self
::AS_ARTICLE_WAS_DELETED
:
1550 case self
::AS_CONFLICT_DETECTED
:
1551 case self
::AS_SUMMARY_NEEDED
:
1552 case self
::AS_TEXTBOX_EMPTY
:
1553 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1555 case self
::AS_BLANK_ARTICLE
:
1556 case self
::AS_SELF_REDIRECT
:
1559 case self
::AS_HOOK_ERROR
:
1562 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1563 case self
::AS_PARSE_ERROR
:
1564 case self
::AS_UNICODE_NOT_SUPPORTED
:
1565 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1568 case self
::AS_SUCCESS_NEW_ARTICLE
:
1569 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1570 if ( $extraQueryRedirect ) {
1571 if ( $query === '' ) {
1572 $query = $extraQueryRedirect;
1574 $query = $query . '&' . $extraQueryRedirect;
1577 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1578 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1581 case self
::AS_SUCCESS_UPDATE
:
1583 $sectionanchor = $resultDetails['sectionanchor'];
1585 // Give extensions a chance to modify URL query on update
1587 'ArticleUpdateBeforeRedirect',
1588 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1591 if ( $resultDetails['redirect'] ) {
1592 if ( $extraQuery == '' ) {
1593 $extraQuery = 'redirect=no';
1595 $extraQuery = 'redirect=no&' . $extraQuery;
1598 if ( $extraQueryRedirect ) {
1599 if ( $extraQuery === '' ) {
1600 $extraQuery = $extraQueryRedirect;
1602 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1606 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1609 case self
::AS_SPAM_ERROR
:
1610 $this->spamPageWithContent( $resultDetails['spam'] );
1613 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1614 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1616 case self
::AS_IMAGE_REDIRECT_ANON
:
1617 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1618 throw new PermissionsError( 'upload' );
1620 case self
::AS_READ_ONLY_PAGE_ANON
:
1621 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1622 throw new PermissionsError( 'edit' );
1624 case self
::AS_READ_ONLY_PAGE
:
1625 throw new ReadOnlyError
;
1627 case self
::AS_RATE_LIMITED
:
1628 throw new ThrottledError();
1630 case self
::AS_NO_CREATE_PERMISSION
:
1631 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1632 throw new PermissionsError( $permission );
1634 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1635 throw new PermissionsError( 'editcontentmodel' );
1638 // We don't recognize $status->value. The only way that can happen
1639 // is if an extension hook aborted from inside ArticleSave.
1640 // Render the status object into $this->hookError
1641 // FIXME this sucks, we should just use the Status object throughout
1642 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1649 * Run hooks that can filter edits just before they get saved.
1651 * @param Content $content The Content to filter.
1652 * @param Status $status For reporting the outcome to the caller
1653 * @param User $user The user performing the edit
1657 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1658 // Run old style post-section-merge edit filter
1659 if ( $this->hookError
!= '' ) {
1660 # ...or the hook could be expecting us to produce an error
1661 $status->fatal( 'hookaborted' );
1662 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1666 // Run new style post-section-merge edit filter
1667 if ( !Hooks
::run( 'EditFilterMergedContent',
1668 [ $this->mArticle
->getContext(), $content, $status, $this->summary
,
1669 $user, $this->minoredit
] )
1671 # Error messages etc. could be handled within the hook...
1672 if ( $status->isGood() ) {
1673 $status->fatal( 'hookaborted' );
1674 // Not setting $this->hookError here is a hack to allow the hook
1675 // to cause a return to the edit page without $this->hookError
1676 // being set. This is used by ConfirmEdit to display a captcha
1677 // without any error message cruft.
1679 $this->hookError
= $status->getWikiText();
1681 // Use the existing $status->value if the hook set it
1682 if ( !$status->value
) {
1683 $status->value
= self
::AS_HOOK_ERROR
;
1686 } elseif ( !$status->isOK() ) {
1687 # ...or the hook could be expecting us to produce an error
1688 // FIXME this sucks, we should just use the Status object throughout
1689 $this->hookError
= $status->getWikiText();
1690 $status->fatal( 'hookaborted' );
1691 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1699 * Return the summary to be used for a new section.
1701 * @param string $sectionanchor Set to the section anchor text
1704 private function newSectionSummary( &$sectionanchor = null ) {
1707 if ( $this->sectiontitle
!== '' ) {
1708 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1709 // If no edit summary was specified, create one automatically from the section
1710 // title and have it link to the new section. Otherwise, respect the summary as
1712 if ( $this->summary
=== '' ) {
1713 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1714 return $this->context
->msg( 'newsectionsummary' )
1715 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1717 } elseif ( $this->summary
!== '' ) {
1718 $sectionanchor = $this->guessSectionName( $this->summary
);
1719 # This is a new section, so create a link to the new section
1720 # in the revision summary.
1721 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1722 return $this->context
->msg( 'newsectionsummary' )
1723 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1725 return $this->summary
;
1729 * Attempt submission (no UI)
1731 * @param array &$result Array to add statuses to, currently with the
1733 * - spam (string): Spam string from content if any spam is detected by
1735 * - sectionanchor (string): Section anchor for a section save.
1736 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1738 * - redirect (bool): Set if doEditContent is OK. True if resulting
1739 * revision is a redirect.
1740 * @param bool $bot True if edit is being made under the bot right.
1742 * @return Status Status object, possibly with a message, but always with
1743 * one of the AS_* constants in $status->value,
1745 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1746 * various error display idiosyncrasies. There are also lots of cases
1747 * where error metadata is set in the object and retrieved later instead
1748 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1749 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1752 public function internalAttemptSave( &$result, $bot = false ) {
1753 global $wgMaxArticleSize;
1754 global $wgContentHandlerUseDB;
1756 $status = Status
::newGood();
1757 $user = $this->context
->getUser();
1759 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1760 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1761 $status->fatal( 'hookaborted' );
1762 $status->value
= self
::AS_HOOK_ERROR
;
1766 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1767 $status->fatal( 'unicode-support-fail' );
1768 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1772 $request = $this->context
->getRequest();
1773 $spam = $request->getText( 'wpAntispam' );
1774 if ( $spam !== '' ) {
1779 $this->mTitle
->getPrefixedText() .
1780 '" submitted bogus field "' .
1784 $status->fatal( 'spamprotectionmatch', false );
1785 $status->value
= self
::AS_SPAM_ERROR
;
1790 # Construct Content object
1791 $textbox_content = $this->toEditContent( $this->textbox1
);
1792 } catch ( MWContentSerializationException
$ex ) {
1794 'content-failed-to-parse',
1795 $this->contentModel
,
1796 $this->contentFormat
,
1799 $status->value
= self
::AS_PARSE_ERROR
;
1803 # Check image redirect
1804 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1805 $textbox_content->isRedirect() &&
1806 !$user->isAllowed( 'upload' )
1808 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1809 $status->setResult( false, $code );
1815 $match = self
::matchSummarySpamRegex( $this->summary
);
1816 if ( $match === false && $this->section
== 'new' ) {
1817 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1818 # regular summaries, it is added to the actual wikitext.
1819 if ( $this->sectiontitle
!== '' ) {
1820 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1821 $match = self
::matchSpamRegex( $this->sectiontitle
);
1823 # This branch is taken when the "Add Topic" user interface is used, or the API
1824 # is used with the 'summary' parameter.
1825 $match = self
::matchSpamRegex( $this->summary
);
1828 if ( $match === false ) {
1829 $match = self
::matchSpamRegex( $this->textbox1
);
1831 if ( $match !== false ) {
1832 $result['spam'] = $match;
1833 $ip = $request->getIP();
1834 $pdbk = $this->mTitle
->getPrefixedDBkey();
1835 $match = str_replace( "\n", '', $match );
1836 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1837 $status->fatal( 'spamprotectionmatch', $match );
1838 $status->value
= self
::AS_SPAM_ERROR
;
1843 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1845 # Error messages etc. could be handled within the hook...
1846 $status->fatal( 'hookaborted' );
1847 $status->value
= self
::AS_HOOK_ERROR
;
1849 } elseif ( $this->hookError
!= '' ) {
1850 # ...or the hook could be expecting us to produce an error
1851 $status->fatal( 'hookaborted' );
1852 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1856 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1857 // Auto-block user's IP if the account was "hard" blocked
1858 if ( !wfReadOnly() ) {
1859 $user->spreadAnyEditBlock();
1861 # Check block state against master, thus 'false'.
1862 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1866 $this->contentLength
= strlen( $this->textbox1
);
1867 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
1868 // Error will be displayed by showEditForm()
1869 $this->tooBig
= true;
1870 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1874 if ( !$user->isAllowed( 'edit' ) ) {
1875 if ( $user->isAnon() ) {
1876 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1879 $status->fatal( 'readonlytext' );
1880 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1885 $changingContentModel = false;
1886 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1887 if ( !$wgContentHandlerUseDB ) {
1888 $status->fatal( 'editpage-cannot-use-custom-model' );
1889 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1891 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1892 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1895 // Make sure the user can edit the page under the new content model too
1896 $titleWithNewContentModel = clone $this->mTitle
;
1897 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1898 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1899 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1901 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1905 $changingContentModel = true;
1906 $oldContentModel = $this->mTitle
->getContentModel();
1909 if ( $this->changeTags
) {
1910 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1911 $this->changeTags
, $user );
1912 if ( !$changeTagsStatus->isOK() ) {
1913 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1914 return $changeTagsStatus;
1918 if ( wfReadOnly() ) {
1919 $status->fatal( 'readonlytext' );
1920 $status->value
= self
::AS_READ_ONLY_PAGE
;
1923 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1924 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1926 $status->fatal( 'actionthrottledtext' );
1927 $status->value
= self
::AS_RATE_LIMITED
;
1931 # If the article has been deleted while editing, don't save it without
1933 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1934 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1938 # Load the page data from the master. If anything changes in the meantime,
1939 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1940 $this->page
->loadPageData( 'fromdbmaster' );
1941 $new = !$this->page
->exists();
1944 // Late check for create permission, just in case *PARANOIA*
1945 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1946 $status->fatal( 'nocreatetext' );
1947 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1948 wfDebug( __METHOD__
. ": no create permission\n" );
1952 // Don't save a new page if it's blank or if it's a MediaWiki:
1953 // message with content equivalent to default (allow empty pages
1954 // in this case to disable messages, see T52124)
1955 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1956 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1957 $defaultText = $defaultMessageText;
1962 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1963 $this->blankArticle
= true;
1964 $status->fatal( 'blankarticle' );
1965 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1969 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
1973 $content = $textbox_content;
1975 $result['sectionanchor'] = '';
1976 if ( $this->section
== 'new' ) {
1977 if ( $this->sectiontitle
!== '' ) {
1978 // Insert the section title above the content.
1979 $content = $content->addSectionHeader( $this->sectiontitle
);
1980 } elseif ( $this->summary
!== '' ) {
1981 // Insert the section title above the content.
1982 $content = $content->addSectionHeader( $this->summary
);
1984 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1987 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1991 # Article exists. Check for edit conflict.
1993 $this->page
->clear(); # Force reload of dates, etc.
1994 $timestamp = $this->page
->getTimestamp();
1995 $latest = $this->page
->getLatest();
1997 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1999 // Check editRevId if set, which handles same-second timestamp collisions
2000 if ( $timestamp != $this->edittime
2001 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2003 $this->isConflict
= true;
2004 if ( $this->section
== 'new' ) {
2005 if ( $this->page
->getUserText() == $user->getName() &&
2006 $this->page
->getComment() == $this->newSectionSummary()
2008 // Probably a duplicate submission of a new comment.
2009 // This can happen when CDN resends a request after
2010 // a timeout but the first one actually went through.
2012 . ": duplicate new section submission; trigger edit conflict!\n" );
2014 // New comment; suppress conflict.
2015 $this->isConflict
= false;
2016 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2018 } elseif ( $this->section
== ''
2019 && Revision
::userWasLastToEdit(
2020 DB_MASTER
, $this->mTitle
->getArticleID(),
2021 $user->getId(), $this->edittime
2024 # Suppress edit conflict with self, except for section edits where merging is required.
2025 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2026 $this->isConflict
= false;
2030 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2031 if ( $this->sectiontitle
!== '' ) {
2032 $sectionTitle = $this->sectiontitle
;
2034 $sectionTitle = $this->summary
;
2039 if ( $this->isConflict
) {
2041 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2042 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2043 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2044 // ...or disable section editing for non-current revisions (not exposed anyway).
2045 if ( $this->editRevId
!== null ) {
2046 $content = $this->page
->replaceSectionAtRev(
2053 $content = $this->page
->replaceSectionContent(
2061 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2062 $content = $this->page
->replaceSectionContent(
2069 if ( is_null( $content ) ) {
2070 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2071 $this->isConflict
= true;
2072 $content = $textbox_content; // do not try to merge here!
2073 } elseif ( $this->isConflict
) {
2075 if ( $this->mergeChangesIntoContent( $content ) ) {
2076 // Successful merge! Maybe we should tell the user the good news?
2077 $this->isConflict
= false;
2078 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2080 $this->section
= '';
2081 $this->textbox1
= ContentHandler
::getContentText( $content );
2082 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2086 if ( $this->isConflict
) {
2087 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2091 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2095 if ( $this->section
== 'new' ) {
2096 // Handle the user preference to force summaries here
2097 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2098 $this->missingSummary
= true;
2099 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2100 $status->value
= self
::AS_SUMMARY_NEEDED
;
2104 // Do not allow the user to post an empty comment
2105 if ( $this->textbox1
== '' ) {
2106 $this->missingComment
= true;
2107 $status->fatal( 'missingcommenttext' );
2108 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2111 } elseif ( !$this->allowBlankSummary
2112 && !$content->equals( $this->getOriginalContent( $user ) )
2113 && !$content->isRedirect()
2114 && md5( $this->summary
) == $this->autoSumm
2116 $this->missingSummary
= true;
2117 $status->fatal( 'missingsummary' );
2118 $status->value
= self
::AS_SUMMARY_NEEDED
;
2123 $sectionanchor = '';
2124 if ( $this->section
== 'new' ) {
2125 $this->summary
= $this->newSectionSummary( $sectionanchor );
2126 } elseif ( $this->section
!= '' ) {
2127 # Try to get a section anchor from the section source, redirect
2128 # to edited section if header found.
2129 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2130 # for duplicate heading checking and maybe parsing.
2131 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2132 # We can't deal with anchors, includes, html etc in the header for now,
2133 # headline would need to be parsed to improve this.
2134 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2135 $sectionanchor = $this->guessSectionName( $matches[2] );
2138 $result['sectionanchor'] = $sectionanchor;
2140 // Save errors may fall down to the edit form, but we've now
2141 // merged the section into full text. Clear the section field
2142 // so that later submission of conflict forms won't try to
2143 // replace that into a duplicated mess.
2144 $this->textbox1
= $this->toEditText( $content );
2145 $this->section
= '';
2147 $status->value
= self
::AS_SUCCESS_UPDATE
;
2150 if ( !$this->allowSelfRedirect
2151 && $content->isRedirect()
2152 && $content->getRedirectTarget()->equals( $this->getTitle() )
2154 // If the page already redirects to itself, don't warn.
2155 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2156 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2157 $this->selfRedirect
= true;
2158 $status->fatal( 'selfredirect' );
2159 $status->value
= self
::AS_SELF_REDIRECT
;
2164 // Check for length errors again now that the section is merged in
2165 $this->contentLength
= strlen( $this->toEditText( $content ) );
2166 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
2167 $this->tooBig
= true;
2168 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2172 $flags = EDIT_AUTOSUMMARY |
2173 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2174 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2175 ( $bot ? EDIT_FORCE_BOT
: 0 );
2177 $doEditStatus = $this->page
->doEditContent(
2183 $content->getDefaultFormat(),
2188 if ( !$doEditStatus->isOK() ) {
2189 // Failure from doEdit()
2190 // Show the edit conflict page for certain recognized errors from doEdit(),
2191 // but don't show it for errors from extension hooks
2192 $errors = $doEditStatus->getErrorsArray();
2193 if ( in_array( $errors[0][0],
2194 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2196 $this->isConflict
= true;
2197 // Destroys data doEdit() put in $status->value but who cares
2198 $doEditStatus->value
= self
::AS_END
;
2200 return $doEditStatus;
2203 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2204 if ( $result['nullEdit'] ) {
2205 // We don't know if it was a null edit until now, so increment here
2206 $user->pingLimiter( 'linkpurge' );
2208 $result['redirect'] = $content->isRedirect();
2210 $this->updateWatchlist();
2212 // If the content model changed, add a log entry
2213 if ( $changingContentModel ) {
2214 $this->addContentModelChangeLogEntry(
2216 $new ?
false : $oldContentModel,
2217 $this->contentModel
,
2227 * @param string|false $oldModel false if the page is being newly created
2228 * @param string $newModel
2229 * @param string $reason
2231 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2232 $new = $oldModel === false;
2233 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2234 $log->setPerformer( $user );
2235 $log->setTarget( $this->mTitle
);
2236 $log->setComment( $reason );
2237 $log->setParameters( [
2238 '4::oldmodel' => $oldModel,
2239 '5::newmodel' => $newModel
2241 $logid = $log->insert();
2242 $log->publish( $logid );
2246 * Register the change of watch status
2248 protected function updateWatchlist() {
2249 $user = $this->context
->getUser();
2250 if ( !$user->isLoggedIn() ) {
2254 $title = $this->mTitle
;
2255 $watch = $this->watchthis
;
2256 // Do this in its own transaction to reduce contention...
2257 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2258 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2259 return; // nothing to change
2261 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2266 * Attempts to do 3-way merge of edit content with a base revision
2267 * and current content, in case of edit conflict, in whichever way appropriate
2268 * for the content type.
2272 * @param Content $editContent
2276 private function mergeChangesIntoContent( &$editContent ) {
2277 $db = wfGetDB( DB_MASTER
);
2279 // This is the revision the editor started from
2280 $baseRevision = $this->getBaseRevision();
2281 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2283 if ( is_null( $baseContent ) ) {
2287 // The current state, we want to merge updates into it
2288 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2289 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2291 if ( is_null( $currentContent ) ) {
2295 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2297 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2300 $editContent = $result;
2301 // Update parentRevId to what we just merged.
2302 $this->parentRevId
= $currentRevision->getId();
2310 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2311 * one might think of X as the "base revision", which is NOT what this returns.
2312 * @return Revision Current version when the edit was started
2314 public function getBaseRevision() {
2315 if ( !$this->mBaseRevision
) {
2316 $db = wfGetDB( DB_MASTER
);
2317 $this->mBaseRevision
= $this->editRevId
2318 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2319 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2321 return $this->mBaseRevision
;
2325 * Check given input text against $wgSpamRegex, and return the text of the first match.
2327 * @param string $text
2329 * @return string|bool Matching string or false
2331 public static function matchSpamRegex( $text ) {
2332 global $wgSpamRegex;
2333 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2334 $regexes = (array)$wgSpamRegex;
2335 return self
::matchSpamRegexInternal( $text, $regexes );
2339 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2341 * @param string $text
2343 * @return string|bool Matching string or false
2345 public static function matchSummarySpamRegex( $text ) {
2346 global $wgSummarySpamRegex;
2347 $regexes = (array)$wgSummarySpamRegex;
2348 return self
::matchSpamRegexInternal( $text, $regexes );
2352 * @param string $text
2353 * @param array $regexes
2354 * @return bool|string
2356 protected static function matchSpamRegexInternal( $text, $regexes ) {
2357 foreach ( $regexes as $regex ) {
2359 if ( preg_match( $regex, $text, $matches ) ) {
2366 public function setHeaders() {
2367 global $wgAjaxEditStash;
2369 $out = $this->context
->getOutput();
2371 $out->addModules( 'mediawiki.action.edit' );
2372 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2374 $user = $this->context
->getUser();
2375 if ( $user->getOption( 'showtoolbar' ) ) {
2376 // The addition of default buttons is handled by getEditToolbar() which
2377 // has its own dependency on this module. The call here ensures the module
2378 // is loaded in time (it has position "top") for other modules to register
2379 // buttons (e.g. extensions, gadgets, user scripts).
2380 $out->addModules( 'mediawiki.toolbar' );
2383 if ( $user->getOption( 'uselivepreview' ) ) {
2384 $out->addModules( 'mediawiki.action.edit.preview' );
2387 if ( $user->getOption( 'useeditwarning' ) ) {
2388 $out->addModules( 'mediawiki.action.edit.editWarning' );
2391 # Enabled article-related sidebar, toplinks, etc.
2392 $out->setArticleRelated( true );
2394 $contextTitle = $this->getContextTitle();
2395 if ( $this->isConflict
) {
2396 $msg = 'editconflict';
2397 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2398 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2400 $msg = $contextTitle->exists()
2401 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2402 && $contextTitle->getDefaultMessageText() !== false
2408 # Use the title defined by DISPLAYTITLE magic word when present
2409 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2410 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2411 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2412 if ( $displayTitle === false ) {
2413 $displayTitle = $contextTitle->getPrefixedText();
2415 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2416 # Transmit the name of the message to JavaScript for live preview
2417 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2418 $out->addJsConfigVars( [
2419 'wgEditMessage' => $msg,
2420 'wgAjaxEditStash' => $wgAjaxEditStash,
2425 * Show all applicable editing introductions
2427 protected function showIntro() {
2428 if ( $this->suppressIntro
) {
2432 $out = $this->context
->getOutput();
2433 $namespace = $this->mTitle
->getNamespace();
2435 if ( $namespace == NS_MEDIAWIKI
) {
2436 # Show a warning if editing an interface message
2437 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2438 # If this is a default message (but not css or js),
2439 # show a hint that it is translatable on translatewiki.net
2440 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2441 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2443 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2444 if ( $defaultMessageText !== false ) {
2445 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2446 'translateinterface' );
2449 } elseif ( $namespace == NS_FILE
) {
2450 # Show a hint to shared repo
2451 $file = wfFindFile( $this->mTitle
);
2452 if ( $file && !$file->isLocal() ) {
2453 $descUrl = $file->getDescriptionUrl();
2454 # there must be a description url to show a hint to shared repo
2456 if ( !$this->mTitle
->exists() ) {
2457 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2458 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2461 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2462 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2469 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2470 # Show log extract when the user is currently blocked
2471 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2472 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2473 $user = User
::newFromName( $username, false /* allow IP users */ );
2474 $ip = User
::isIP( $username );
2475 $block = Block
::newFromTarget( $user, $user );
2476 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2477 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2478 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2479 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2480 # Show log extract if the user is currently blocked
2481 LogEventsList
::showLogExtract(
2484 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2488 'showIfEmpty' => false,
2490 'blocked-notice-logextract',
2491 $user->getName() # Support GENDER in notice
2497 # Try to add a custom edit intro, or use the standard one if this is not possible.
2498 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2499 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2500 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2502 if ( $this->context
->getUser()->isLoggedIn() ) {
2504 // Suppress the external link icon, consider the help url an internal one
2505 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2513 // Suppress the external link icon, consider the help url an internal one
2514 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2516 'newarticletextanon',
2522 # Give a notice if the user is editing a deleted/moved page...
2523 if ( !$this->mTitle
->exists() ) {
2524 $dbr = wfGetDB( DB_REPLICA
);
2526 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2530 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2531 'showIfEmpty' => false,
2532 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2539 * Attempt to show a custom editing introduction, if supplied
2543 protected function showCustomIntro() {
2544 if ( $this->editintro
) {
2545 $title = Title
::newFromText( $this->editintro
);
2546 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2547 // Added using template syntax, to take <noinclude>'s into account.
2548 $this->context
->getOutput()->addWikiTextTitleTidy(
2549 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2559 * Gets an editable textual representation of $content.
2560 * The textual representation can be turned by into a Content object by the
2561 * toEditContent() method.
2563 * If $content is null or false or a string, $content is returned unchanged.
2565 * If the given Content object is not of a type that can be edited using
2566 * the text base EditPage, an exception will be raised. Set
2567 * $this->allowNonTextContent to true to allow editing of non-textual
2570 * @param Content|null|bool|string $content
2571 * @return string The editable text form of the content.
2573 * @throws MWException If $content is not an instance of TextContent and
2574 * $this->allowNonTextContent is not true.
2576 protected function toEditText( $content ) {
2577 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2581 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2582 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2585 return $content->serialize( $this->contentFormat
);
2589 * Turns the given text into a Content object by unserializing it.
2591 * If the resulting Content object is not of a type that can be edited using
2592 * the text base EditPage, an exception will be raised. Set
2593 * $this->allowNonTextContent to true to allow editing of non-textual
2596 * @param string|null|bool $text Text to unserialize
2597 * @return Content|bool|null The content object created from $text. If $text was false
2598 * or null, false resp. null will be returned instead.
2600 * @throws MWException If unserializing the text results in a Content
2601 * object that is not an instance of TextContent and
2602 * $this->allowNonTextContent is not true.
2604 protected function toEditContent( $text ) {
2605 if ( $text === false ||
$text === null ) {
2609 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2610 $this->contentModel
, $this->contentFormat
);
2612 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2613 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2620 * Send the edit form and related headers to OutputPage
2621 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2622 * during form output near the top, for captchas and the like.
2624 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2625 * use the EditPage::showEditForm:fields hook instead.
2627 public function showEditForm( $formCallback = null ) {
2628 # need to parse the preview early so that we know which templates are used,
2629 # otherwise users with "show preview after edit box" will get a blank list
2630 # we parse this near the beginning so that setHeaders can do the title
2631 # setting work instead of leaving it in getPreviewText
2632 $previewOutput = '';
2633 if ( $this->formtype
== 'preview' ) {
2634 $previewOutput = $this->getPreviewText();
2637 $out = $this->context
->getOutput();
2639 // Avoid PHP 7.1 warning of passing $this by reference
2641 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2643 $this->setHeaders();
2645 $this->addTalkPageText();
2646 $this->addEditNotices();
2648 if ( !$this->isConflict
&&
2649 $this->section
!= '' &&
2650 !$this->isSectionEditSupported() ) {
2651 // We use $this->section to much before this and getVal('wgSection') directly in other places
2652 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2653 // Someone is welcome to try refactoring though
2654 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2658 $this->showHeader();
2660 $out->addHTML( $this->editFormPageTop
);
2662 $user = $this->context
->getUser();
2663 if ( $user->getOption( 'previewontop' ) ) {
2664 $this->displayPreviewArea( $previewOutput, true );
2667 $out->addHTML( $this->editFormTextTop
);
2669 $showToolbar = true;
2670 if ( $this->wasDeletedSinceLastEdit() ) {
2671 if ( $this->formtype
== 'save' ) {
2672 // Hide the toolbar and edit area, user can click preview to get it back
2673 // Add an confirmation checkbox and explanation.
2674 $showToolbar = false;
2676 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2677 'deletedwhileediting' );
2681 // @todo add EditForm plugin interface and use it here!
2682 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2683 $out->addHTML( Html
::openElement(
2686 'class' => 'mw-editform',
2687 'id' => self
::EDITFORM_ID
,
2688 'name' => self
::EDITFORM_ID
,
2690 'action' => $this->getActionURL( $this->getContextTitle() ),
2691 'enctype' => 'multipart/form-data'
2695 if ( is_callable( $formCallback ) ) {
2696 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2697 call_user_func_array( $formCallback, [ &$out ] );
2700 // Add a check for Unicode support
2701 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2703 // Add an empty field to trip up spambots
2705 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2708 [ 'for' => 'wpAntispam' ],
2709 $this->context
->msg( 'simpleantispam-label' )->parse()
2715 'name' => 'wpAntispam',
2716 'id' => 'wpAntispam',
2720 . Xml
::closeElement( 'div' )
2723 // Avoid PHP 7.1 warning of passing $this by reference
2725 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2727 // Put these up at the top to ensure they aren't lost on early form submission
2728 $this->showFormBeforeText();
2730 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2731 $username = $this->lastDelete
->user_name
;
2732 $comment = CommentStore
::newKey( 'log_comment' )->getComment( $this->lastDelete
)->text
;
2734 // It is better to not parse the comment at all than to have templates expanded in the middle
2735 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2736 $key = $comment === ''
2737 ?
'confirmrecreate-noreason'
2738 : 'confirmrecreate';
2740 '<div class="mw-confirm-recreate">' .
2741 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2742 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2743 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2749 # When the summary is hidden, also hide them on preview/show changes
2750 if ( $this->nosummary
) {
2751 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2754 # If a blank edit summary was previously provided, and the appropriate
2755 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2756 # user being bounced back more than once in the event that a summary
2759 # For a bit more sophisticated detection of blank summaries, hash the
2760 # automatic one and pass that in the hidden field wpAutoSummary.
2761 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2762 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2765 if ( $this->undidRev
) {
2766 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2769 if ( $this->selfRedirect
) {
2770 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2773 if ( $this->hasPresetSummary
) {
2774 // If a summary has been preset using &summary= we don't want to prompt for
2775 // a different summary. Only prompt for a summary if the summary is blanked.
2777 $this->autoSumm
= md5( '' );
2780 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2781 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2783 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2784 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2786 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2787 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2791 if ( $this->section
== 'new' ) {
2792 $this->showSummaryInput( true, $this->summary
);
2793 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2796 $out->addHTML( $this->editFormTextBeforeContent
);
2798 if ( !$this->isCssJsSubpage
&& $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2799 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2802 if ( $this->blankArticle
) {
2803 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2806 if ( $this->isConflict
) {
2807 // In an edit conflict bypass the overridable content form method
2808 // and fallback to the raw wpTextbox1 since editconflicts can't be
2809 // resolved between page source edits and custom ui edits using the
2811 $this->textbox2
= $this->textbox1
;
2813 $content = $this->getCurrentContent();
2814 $this->textbox1
= $this->toEditText( $content );
2816 $this->showTextbox1();
2818 $this->showContentForm();
2821 $out->addHTML( $this->editFormTextAfterContent
);
2823 $this->showStandardInputs();
2825 $this->showFormAfterText();
2827 $this->showTosSummary();
2829 $this->showEditTools();
2831 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2833 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2835 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2836 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2838 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2839 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2841 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2843 if ( $this->isConflict
) {
2845 $this->showConflict();
2846 } catch ( MWContentSerializationException
$ex ) {
2847 // this can't really happen, but be nice if it does.
2848 $msg = $this->context
->msg(
2849 'content-failed-to-parse',
2850 $this->contentModel
,
2851 $this->contentFormat
,
2854 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2858 // Set a hidden field so JS knows what edit form mode we are in
2859 if ( $this->isConflict
) {
2861 } elseif ( $this->preview
) {
2863 } elseif ( $this->diff
) {
2868 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2870 // Marker for detecting truncated form data. This must be the last
2871 // parameter sent in order to be of use, so do not move me.
2872 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2873 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2875 if ( !$user->getOption( 'previewontop' ) ) {
2876 $this->displayPreviewArea( $previewOutput, false );
2881 * Wrapper around TemplatesOnThisPageFormatter to make
2882 * a "templates on this page" list.
2884 * @param Title[] $templates
2885 * @return string HTML
2887 public function makeTemplatesOnThisPageList( array $templates ) {
2888 $templateListFormatter = new TemplatesOnThisPageFormatter(
2889 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2892 // preview if preview, else section if section, else false
2894 if ( $this->preview
) {
2896 } elseif ( $this->section
!= '' ) {
2900 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2901 $templateListFormatter->format( $templates, $type )
2906 * Extract the section title from current section text, if any.
2908 * @param string $text
2909 * @return string|bool String or false
2911 public static function extractSectionTitle( $text ) {
2912 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2913 if ( !empty( $matches[2] ) ) {
2915 return $wgParser->stripSectionName( trim( $matches[2] ) );
2921 protected function showHeader() {
2922 global $wgAllowUserCss, $wgAllowUserJs;
2924 $out = $this->context
->getOutput();
2925 $user = $this->context
->getUser();
2926 if ( $this->isConflict
) {
2927 $this->addExplainConflictHeader( $out );
2928 $this->editRevId
= $this->page
->getLatest();
2930 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2931 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2932 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2933 if ( $sectionTitle !== false ) {
2934 $this->summary
= "/* $sectionTitle */ ";
2939 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
2941 if ( $this->missingComment
) {
2942 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2945 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2947 "<div id='mw-missingsummary'>\n$1\n</div>",
2948 [ 'missingsummary', $buttonLabel ]
2952 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2954 "<div id='mw-missingcommentheader'>\n$1\n</div>",
2955 [ 'missingcommentheader', $buttonLabel ]
2959 if ( $this->blankArticle
) {
2961 "<div id='mw-blankarticle'>\n$1\n</div>",
2962 [ 'blankarticle', $buttonLabel ]
2966 if ( $this->selfRedirect
) {
2968 "<div id='mw-selfredirect'>\n$1\n</div>",
2969 [ 'selfredirect', $buttonLabel ]
2973 if ( $this->hookError
!== '' ) {
2974 $out->addWikiText( $this->hookError
);
2977 if ( $this->section
!= 'new' ) {
2978 $revision = $this->mArticle
->getRevisionFetched();
2980 // Let sysop know that this will make private content public if saved
2982 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
2984 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2985 'rev-deleted-text-permission'
2987 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2989 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2990 'rev-deleted-text-view'
2994 if ( !$revision->isCurrent() ) {
2995 $this->mArticle
->setOldSubtitle( $revision->getId() );
2996 $out->addWikiMsg( 'editingold' );
2997 $this->isOldRev
= true;
2999 } elseif ( $this->mTitle
->exists() ) {
3000 // Something went wrong
3002 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3003 [ 'missing-revision', $this->oldid
] );
3008 if ( wfReadOnly() ) {
3010 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3011 [ 'readonlywarning', wfReadOnlyReason() ]
3013 } elseif ( $user->isAnon() ) {
3014 if ( $this->formtype
!= 'preview' ) {
3016 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3017 [ 'anoneditwarning',
3019 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3020 'returnto' => $this->getTitle()->getPrefixedDBkey()
3023 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3024 'returnto' => $this->getTitle()->getPrefixedDBkey()
3029 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3030 'anonpreviewwarning'
3034 if ( $this->isCssJsSubpage
) {
3035 # Check the skin exists
3036 if ( $this->isWrongCaseCssJsPage
) {
3038 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
3039 [ 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ]
3042 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3043 $out->wrapWikiMsg( '<div class="mw-usercssjspublic">$1</div>',
3044 $this->isCssSubpage ?
'usercssispublic' : 'userjsispublic'
3046 if ( $this->formtype
!== 'preview' ) {
3047 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
3049 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3050 [ 'usercssyoucanpreview' ]
3054 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
3056 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3057 [ 'userjsyoucanpreview' ]
3065 $this->addPageProtectionWarningHeaders();
3067 $this->addLongPageWarningHeader();
3069 # Add header copyright warning
3070 $this->showHeaderCopyrightWarning();
3074 * Helper function for summary input functions, which returns the neccessary
3075 * attributes for the input.
3077 * @param array|null $inputAttrs Array of attrs to use on the input
3080 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3081 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
3082 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3083 'id' => 'wpSummary',
3084 'name' => 'wpSummary',
3085 'maxlength' => '200',
3088 'spellcheck' => 'true',
3093 * Standard summary input and label (wgSummary), abstracted so EditPage
3094 * subclasses may reorganize the form.
3095 * Note that you do not need to worry about the label's for=, it will be
3096 * inferred by the id given to the input. You can remove them both by
3097 * passing [ 'id' => false ] to $userInputAttrs.
3099 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3100 * @param string $summary The value of the summary input
3101 * @param string $labelText The html to place inside the label
3102 * @param array $inputAttrs Array of attrs to use on the input
3103 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
3104 * @return array An array in the format [ $label, $input ]
3106 public function getSummaryInput( $summary = "", $labelText = null,
3107 $inputAttrs = null, $spanLabelAttrs = null
3109 wfDeprecated( __METHOD__
, '1.30' );
3110 $inputAttrs = $this->getSummaryInputAttributes( $inputAttrs );
3111 $inputAttrs +
= Linker
::tooltipAndAccesskeyAttribs( 'summary' );
3113 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : [] ) +
[
3114 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
3115 'id' => "wpSummaryLabel"
3122 $inputAttrs['id'] ?
[ 'for' => $inputAttrs['id'] ] : null,
3125 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
3128 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
3130 return [ $label, $input ];
3134 * Builds a standard summary input with a label.
3136 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3137 * @param string $summary The value of the summary input
3138 * @param string $labelText The html to place inside the label
3139 * @param array $inputAttrs Array of attrs to use on the input
3141 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3143 function getSummaryInputOOUI( $summary = "", $labelText = null, $inputAttrs = null ) {
3144 wfDeprecated( __METHOD__
, '1.30' );
3145 $this->getSummaryInputWidget( $summary, $labelText, $inputAttrs );
3149 * Builds a standard summary input with a label.
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 getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3158 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3159 $this->getSummaryInputAttributes( $inputAttrs )
3162 'title' => Linker
::titleAttrib( 'summary' ),
3163 'accessKey' => Linker
::accesskey( 'summary' ),
3166 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3167 $inputAttrs['inputId'] = $inputAttrs['id'];
3168 $inputAttrs['id'] = 'wpSummaryWidget';
3170 return new OOUI\
FieldLayout(
3171 new OOUI\
TextInputWidget( [
3172 'value' => $summary,
3173 'infusable' => true,
3176 'label' => new OOUI\
HtmlSnippet( $labelText ),
3178 'id' => 'wpSummaryLabel',
3179 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3185 * @param bool $isSubjectPreview True if this is the section subject/title
3186 * up top, or false if this is the comment summary
3187 * down below the textarea
3188 * @param string $summary The text of the summary to display
3190 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3191 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3192 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3193 if ( $isSubjectPreview ) {
3194 if ( $this->nosummary
) {
3198 if ( !$this->mShowSummaryField
) {
3203 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3204 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3207 [ 'class' => $summaryClass ]
3212 * @param bool $isSubjectPreview True if this is the section subject/title
3213 * up top, or false if this is the comment summary
3214 * down below the textarea
3215 * @param string $summary The text of the summary to display
3218 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3219 // avoid spaces in preview, gets always trimmed on save
3220 $summary = trim( $summary );
3221 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3227 if ( $isSubjectPreview ) {
3228 $summary = $this->context
->msg( 'newsectionsummary' )
3229 ->rawParams( $wgParser->stripSectionName( $summary ) )
3230 ->inContentLanguage()->text();
3233 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3235 $summary = $this->context
->msg( $message )->parse()
3236 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3237 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3240 protected function showFormBeforeText() {
3241 $out = $this->context
->getOutput();
3242 $out->addHTML( Html
::hidden( 'wpSection', htmlspecialchars( $this->section
) ) );
3243 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3244 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3245 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3246 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3249 protected function showFormAfterText() {
3251 * To make it harder for someone to slip a user a page
3252 * which submits an edit form to the wiki without their
3253 * knowledge, a random token is associated with the login
3254 * session. If it's not passed back with the submission,
3255 * we won't save the page, or render user JavaScript and
3258 * For anon editors, who may not have a session, we just
3259 * include the constant suffix to prevent editing from
3260 * broken text-mangling proxies.
3262 $this->context
->getOutput()->addHTML(
3264 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3270 * Subpage overridable method for printing the form for page content editing
3271 * By default this simply outputs wpTextbox1
3272 * Subclasses can override this to provide a custom UI for editing;
3273 * be it a form, or simply wpTextbox1 with a modified content that will be
3274 * reverse modified when extracted from the post data.
3275 * Note that this is basically the inverse for importContentFormData
3277 protected function showContentForm() {
3278 $this->showTextbox1();
3282 * Method to output wpTextbox1
3283 * The $textoverride method can be used by subclasses overriding showContentForm
3284 * to pass back to this method.
3286 * @param array $customAttribs Array of html attributes to use in the textarea
3287 * @param string $textoverride Optional text to override $this->textarea1 with
3289 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3290 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3291 $attribs = [ 'style' => 'display:none;' ];
3293 $classes = []; // Textarea CSS
3294 if ( $this->mTitle
->isProtected( 'edit' ) &&
3295 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
3297 # Is the title semi-protected?
3298 if ( $this->mTitle
->isSemiProtected() ) {
3299 $classes[] = 'mw-textarea-sprotected';
3301 # Then it must be protected based on static groups (regular)
3302 $classes[] = 'mw-textarea-protected';
3304 # Is the title cascade-protected?
3305 if ( $this->mTitle
->isCascadeProtected() ) {
3306 $classes[] = 'mw-textarea-cprotected';
3309 # Is an old revision being edited?
3310 if ( $this->isOldRev
) {
3311 $classes[] = 'mw-textarea-oldrev';
3314 $attribs = [ 'tabindex' => 1 ];
3316 if ( is_array( $customAttribs ) ) {
3317 $attribs +
= $customAttribs;
3320 if ( count( $classes ) ) {
3321 if ( isset( $attribs['class'] ) ) {
3322 $classes[] = $attribs['class'];
3324 $attribs['class'] = implode( ' ', $classes );
3329 $textoverride !== null ?
$textoverride : $this->textbox1
,
3335 protected function showTextbox2() {
3336 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3339 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3340 $wikitext = $this->addNewLineAtEnd( $text );
3342 $attribs = $this->buildTextboxAttribs( $name, $customAttribs, $this->context
->getUser() );
3344 $this->context
->getOutput()->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3347 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3350 $classes[] = 'ontop';
3353 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3355 if ( $this->formtype
!= 'preview' ) {
3356 $attribs['style'] = 'display: none;';
3359 $out = $this->context
->getOutput();
3360 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3362 if ( $this->formtype
== 'preview' ) {
3363 $this->showPreview( $previewOutput );
3365 // Empty content container for LivePreview
3366 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3367 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3368 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3369 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3372 $out->addHTML( '</div>' );
3374 if ( $this->formtype
== 'diff' ) {
3377 } catch ( MWContentSerializationException
$ex ) {
3378 $msg = $this->context
->msg(
3379 'content-failed-to-parse',
3380 $this->contentModel
,
3381 $this->contentFormat
,
3384 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3390 * Append preview output to OutputPage.
3391 * Includes category rendering if this is a category page.
3393 * @param string $text The HTML to be output for the preview.
3395 protected function showPreview( $text ) {
3396 if ( $this->mArticle
instanceof CategoryPage
) {
3397 $this->mArticle
->openShowCategory();
3399 # This hook seems slightly odd here, but makes things more
3400 # consistent for extensions.
3401 $out = $this->context
->getOutput();
3402 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3403 $out->addHTML( $text );
3404 if ( $this->mArticle
instanceof CategoryPage
) {
3405 $this->mArticle
->closeShowCategory();
3410 * Get a diff between the current contents of the edit box and the
3411 * version of the page we're editing from.
3413 * If this is a section edit, we'll replace the section as for final
3414 * save and then make a comparison.
3416 public function showDiff() {
3419 $oldtitlemsg = 'currentrev';
3420 # if message does not exist, show diff against the preloaded default
3421 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3422 $oldtext = $this->mTitle
->getDefaultMessageText();
3423 if ( $oldtext !== false ) {
3424 $oldtitlemsg = 'defaultmessagetext';
3425 $oldContent = $this->toEditContent( $oldtext );
3430 $oldContent = $this->getCurrentContent();
3433 $textboxContent = $this->toEditContent( $this->textbox1
);
3434 if ( $this->editRevId
!== null ) {
3435 $newContent = $this->page
->replaceSectionAtRev(
3436 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3439 $newContent = $this->page
->replaceSectionContent(
3440 $this->section
, $textboxContent, $this->summary
, $this->edittime
3444 if ( $newContent ) {
3445 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3447 $user = $this->context
->getUser();
3448 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
3449 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3452 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3453 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3454 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3456 if ( !$oldContent ) {
3457 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3460 if ( !$newContent ) {
3461 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3464 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3465 $de->setContent( $oldContent, $newContent );
3467 $difftext = $de->getDiff( $oldtitle, $newtitle );
3468 $de->showDiffStyle();
3473 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3477 * Show the header copyright warning.
3479 protected function showHeaderCopyrightWarning() {
3480 $msg = 'editpage-head-copy-warn';
3481 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3482 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3483 'editpage-head-copy-warn' );
3488 * Give a chance for site and per-namespace customizations of
3489 * terms of service summary link that might exist separately
3490 * from the copyright notice.
3492 * This will display between the save button and the edit tools,
3493 * so should remain short!
3495 protected function showTosSummary() {
3496 $msg = 'editpage-tos-summary';
3497 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3498 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3499 $out = $this->context
->getOutput();
3500 $out->addHTML( '<div class="mw-tos-summary">' );
3501 $out->addWikiMsg( $msg );
3502 $out->addHTML( '</div>' );
3507 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3508 * characters not present on most keyboards for copying/pasting.
3510 protected function showEditTools() {
3511 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3512 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3517 * Get the copyright warning
3519 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3522 protected function getCopywarn() {
3523 return self
::getCopyrightWarning( $this->mTitle
);
3527 * Get the copyright warning, by default returns wikitext
3529 * @param Title $title
3530 * @param string $format Output format, valid values are any function of a Message object
3531 * @param Language|string|null $langcode Language code or Language object.
3534 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3535 global $wgRightsText;
3536 if ( $wgRightsText ) {
3537 $copywarnMsg = [ 'copyrightwarning',
3538 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3541 $copywarnMsg = [ 'copyrightwarning2',
3542 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3544 // Allow for site and per-namespace customization of contribution/copyright notice.
3545 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3547 $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
3549 $msg->inLanguage( $langcode );
3551 return "<div id=\"editpage-copywarn\">\n" .
3552 $msg->$format() . "\n</div>";
3556 * Get the Limit report for page previews
3559 * @param ParserOutput $output ParserOutput object from the parse
3560 * @return string HTML
3562 public static function getPreviewLimitReport( $output ) {
3563 if ( !$output ||
!$output->getLimitReportData() ) {
3567 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3568 wfMessage( 'limitreport-title' )->parseAsBlock()
3571 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3572 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3574 $limitReport .= Html
::openElement( 'table', [
3575 'class' => 'preview-limit-report wikitable'
3577 Html
::openElement( 'tbody' );
3579 foreach ( $output->getLimitReportData() as $key => $value ) {
3580 if ( Hooks
::run( 'ParserLimitReportFormat',
3581 [ $key, &$value, &$limitReport, true, true ]
3583 $keyMsg = wfMessage( $key );
3584 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3585 if ( !$valueMsg->exists() ) {
3586 $valueMsg = new RawMessage( '$1' );
3588 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3589 $limitReport .= Html
::openElement( 'tr' ) .
3590 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3591 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3592 Html
::closeElement( 'tr' );
3597 $limitReport .= Html
::closeElement( 'tbody' ) .
3598 Html
::closeElement( 'table' ) .
3599 Html
::closeElement( 'div' );
3601 return $limitReport;
3604 protected function showStandardInputs( &$tabindex = 2 ) {
3605 $out = $this->context
->getOutput();
3606 $out->addHTML( "<div class='editOptions'>\n" );
3608 if ( $this->section
!= 'new' ) {
3609 $this->showSummaryInput( false, $this->summary
);
3610 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3613 $checkboxes = $this->getCheckboxesWidget(
3615 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3617 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3619 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3621 // Show copyright warning.
3622 $out->addWikiText( $this->getCopywarn() );
3623 $out->addHTML( $this->editFormTextAfterWarn
);
3625 $out->addHTML( "<div class='editButtons'>\n" );
3626 $out->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3628 $cancel = $this->getCancelLink();
3629 if ( $cancel !== '' ) {
3630 $cancel .= Html
::element( 'span',
3631 [ 'class' => 'mw-editButtons-pipe-separator' ],
3632 $this->context
->msg( 'pipe-separator' )->text() );
3635 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3636 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3639 $this->context
->msg( 'edithelp' )->text(),
3640 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3643 $this->context
->msg( 'word-separator' )->escaped() .
3644 $this->context
->msg( 'newwindow' )->parse();
3646 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3647 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3648 $out->addHTML( "</div><!-- editButtons -->\n" );
3650 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3652 $out->addHTML( "</div><!-- editOptions -->\n" );
3656 * Show an edit conflict. textbox1 is already shown in showEditForm().
3657 * If you want to use another entry point to this function, be careful.
3659 protected function showConflict() {
3660 $out = $this->context
->getOutput();
3661 // Avoid PHP 7.1 warning of passing $this by reference
3663 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3664 $this->incrementConflictStats();
3666 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3668 $content1 = $this->toEditContent( $this->textbox1
);
3669 $content2 = $this->toEditContent( $this->textbox2
);
3671 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3672 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3673 $de->setContent( $content2, $content1 );
3675 $this->context
->msg( 'yourtext' )->parse(),
3676 $this->context
->msg( 'storedversion' )->text()
3679 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3680 $this->showTextbox2();
3684 protected function incrementConflictStats() {
3685 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3686 $stats->increment( 'edit.failures.conflict' );
3687 // Only include 'standard' namespaces to avoid creating unknown numbers of statsd metrics
3689 $this->mTitle
->getNamespace() >= NS_MAIN
&&
3690 $this->mTitle
->getNamespace() <= NS_CATEGORY_TALK
3692 $stats->increment( 'edit.failures.conflict.byNamespaceId.' . $this->mTitle
->getNamespace() );
3699 public function getCancelLink() {
3701 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3702 $cancelParams['oldid'] = $this->oldid
;
3703 } elseif ( $this->getContextTitle()->isRedirect() ) {
3704 $cancelParams['redirect'] = 'no';
3707 return new OOUI\
ButtonWidget( [
3708 'id' => 'mw-editform-cancel',
3709 'href' => $this->getContextTitle()->getLinkUrl( $cancelParams ),
3710 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3712 'infusable' => true,
3713 'flags' => 'destructive',
3718 * Returns the URL to use in the form's action attribute.
3719 * This is used by EditPage subclasses when simply customizing the action
3720 * variable in the constructor is not enough. This can be used when the
3721 * EditPage lives inside of a Special page rather than a custom page action.
3723 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3726 protected function getActionURL( Title
$title ) {
3727 return $title->getLocalURL( [ 'action' => $this->action
] );
3731 * Check if a page was deleted while the user was editing it, before submit.
3732 * Note that we rely on the logging table, which hasn't been always there,
3733 * but that doesn't matter, because this only applies to brand new
3737 protected function wasDeletedSinceLastEdit() {
3738 if ( $this->deletedSinceEdit
!== null ) {
3739 return $this->deletedSinceEdit
;
3742 $this->deletedSinceEdit
= false;
3744 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3745 $this->lastDelete
= $this->getLastDelete();
3746 if ( $this->lastDelete
) {
3747 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3748 if ( $deleteTime > $this->starttime
) {
3749 $this->deletedSinceEdit
= true;
3754 return $this->deletedSinceEdit
;
3758 * @return bool|stdClass
3760 protected function getLastDelete() {
3761 $dbr = wfGetDB( DB_REPLICA
);
3762 $commentQuery = CommentStore
::newKey( 'log_comment' )->getJoin();
3763 $data = $dbr->selectRow(
3764 [ 'logging', 'user' ] +
$commentQuery['tables'],
3775 ] +
$commentQuery['fields'], [
3776 'log_namespace' => $this->mTitle
->getNamespace(),
3777 'log_title' => $this->mTitle
->getDBkey(),
3778 'log_type' => 'delete',
3779 'log_action' => 'delete',
3783 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3785 'user' => [ 'JOIN', 'user_id=log_user' ],
3786 ] +
$commentQuery['joins']
3788 // Quick paranoid permission checks...
3789 if ( is_object( $data ) ) {
3790 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3791 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3794 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3795 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3796 $data->log_comment_data
= null;
3804 * Get the rendered text for previewing.
3805 * @throws MWException
3808 public function getPreviewText() {
3810 global $wgAllowUserCss, $wgAllowUserJs;
3812 $out = $this->context
->getOutput();
3814 if ( $wgRawHtml && !$this->mTokenOk
) {
3815 // Could be an offsite preview attempt. This is very unsafe if
3816 // HTML is enabled, as it could be an attack.
3818 if ( $this->textbox1
!== '' ) {
3819 // Do not put big scary notice, if previewing the empty
3820 // string, which happens when you initially edit
3821 // a category page, due to automatic preview-on-open.
3822 $parsedNote = $out->parse( "<div class='previewnote'>" .
3823 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3824 true, /* interface */true );
3826 $this->incrementEditFailureStats( 'session_loss' );
3833 $content = $this->toEditContent( $this->textbox1
);
3837 'AlternateEditPreview',
3838 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3840 return $previewHTML;
3843 # provide a anchor link to the editform
3844 $continueEditing = '<span class="mw-continue-editing">' .
3845 '[[#' . self
::EDITFORM_ID
. '|' .
3846 $this->context
->getLanguage()->getArrow() . ' ' .
3847 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3848 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3849 if ( $this->mTokenOkExceptSuffix
) {
3850 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3851 $this->incrementEditFailureStats( 'bad_token' );
3853 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3854 $this->incrementEditFailureStats( 'session_loss' );
3856 } elseif ( $this->incompleteForm
) {
3857 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3858 if ( $this->mTriedSave
) {
3859 $this->incrementEditFailureStats( 'incomplete_form' );
3862 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3865 # don't parse non-wikitext pages, show message about preview
3866 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3867 if ( $this->mTitle
->isCssJsSubpage() ) {
3869 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3875 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3877 if ( $level === 'user' && !$wgAllowUserCss ) {
3880 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3882 if ( $level === 'user' && !$wgAllowUserJs ) {
3889 # Used messages to make sure grep find them:
3890 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3891 if ( $level && $format ) {
3892 $note = "<div id='mw-{$level}{$format}preview'>" .
3893 $this->context
->msg( "{$level}{$format}preview" )->text() .
3894 ' ' . $continueEditing . "</div>";
3898 # If we're adding a comment, we need to show the
3899 # summary as the headline
3900 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3901 $content = $content->addSectionHeader( $this->summary
);
3904 $hook_args = [ $this, &$content ];
3905 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3907 $parserResult = $this->doPreviewParse( $content );
3908 $parserOutput = $parserResult['parserOutput'];
3909 $previewHTML = $parserResult['html'];
3910 $this->mParserOutput
= $parserOutput;
3911 $out->addParserOutputMetadata( $parserOutput );
3913 if ( count( $parserOutput->getWarnings() ) ) {
3914 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3917 } catch ( MWContentSerializationException
$ex ) {
3918 $m = $this->context
->msg(
3919 'content-failed-to-parse',
3920 $this->contentModel
,
3921 $this->contentFormat
,
3924 $note .= "\n\n" . $m->parse();
3928 if ( $this->isConflict
) {
3929 $conflict = '<h2 id="mw-previewconflict">'
3930 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3932 $conflict = '<hr />';
3935 $previewhead = "<div class='previewnote'>\n" .
3936 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3937 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3939 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3940 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3941 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3942 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3944 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3947 private function incrementEditFailureStats( $failureType ) {
3948 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3949 $stats->increment( 'edit.failures.' . $failureType );
3953 * Get parser options for a preview
3954 * @return ParserOptions
3956 protected function getPreviewParserOptions() {
3957 $parserOptions = $this->page
->makeParserOptions( $this->mArticle
->getContext() );
3958 $parserOptions->setIsPreview( true );
3959 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3960 $parserOptions->enableLimitReport();
3961 return $parserOptions;
3965 * Parse the page for a preview. Subclasses may override this class, in order
3966 * to parse with different options, or to otherwise modify the preview HTML.
3968 * @param Content $content The page content
3969 * @return array with keys:
3970 * - parserOutput: The ParserOutput object
3971 * - html: The HTML to be displayed
3973 protected function doPreviewParse( Content
$content ) {
3974 $user = $this->context
->getUser();
3975 $parserOptions = $this->getPreviewParserOptions();
3976 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
3977 $scopedCallback = $parserOptions->setupFakeRevision(
3978 $this->mTitle
, $pstContent, $user );
3979 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3980 ScopedCallback
::consume( $scopedCallback );
3981 $parserOutput->setEditSectionTokens( false ); // no section edit links
3983 'parserOutput' => $parserOutput,
3984 'html' => $parserOutput->getText() ];
3990 public function getTemplates() {
3991 if ( $this->preview ||
$this->section
!= '' ) {
3993 if ( !isset( $this->mParserOutput
) ) {
3996 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3997 foreach ( array_keys( $template ) as $dbk ) {
3998 $templates[] = Title
::makeTitle( $ns, $dbk );
4003 return $this->mTitle
->getTemplateLinksFrom();
4008 * Shows a bulletin board style toolbar for common editing functions.
4009 * It can be disabled in the user preferences.
4011 * @param Title $title Title object for the page being edited (optional)
4014 public static function getEditToolbar( $title = null ) {
4015 global $wgContLang, $wgOut;
4016 global $wgEnableUploads, $wgForeignFileRepos;
4018 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
4019 $showSignature = true;
4021 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4025 * $toolarray is an array of arrays each of which includes the
4026 * opening tag, the closing tag, optionally a sample text that is
4027 * inserted between the two when no selection is highlighted
4028 * and. The tip text is shown when the user moves the mouse
4031 * Images are defined in ResourceLoaderEditToolbarModule.
4035 'id' => 'mw-editbutton-bold',
4037 'close' => '\'\'\'',
4038 'sample' => wfMessage( 'bold_sample' )->text(),
4039 'tip' => wfMessage( 'bold_tip' )->text(),
4042 'id' => 'mw-editbutton-italic',
4045 'sample' => wfMessage( 'italic_sample' )->text(),
4046 'tip' => wfMessage( 'italic_tip' )->text(),
4049 'id' => 'mw-editbutton-link',
4052 'sample' => wfMessage( 'link_sample' )->text(),
4053 'tip' => wfMessage( 'link_tip' )->text(),
4056 'id' => 'mw-editbutton-extlink',
4059 'sample' => wfMessage( 'extlink_sample' )->text(),
4060 'tip' => wfMessage( 'extlink_tip' )->text(),
4063 'id' => 'mw-editbutton-headline',
4066 'sample' => wfMessage( 'headline_sample' )->text(),
4067 'tip' => wfMessage( 'headline_tip' )->text(),
4069 $imagesAvailable ?
[
4070 'id' => 'mw-editbutton-image',
4071 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4073 'sample' => wfMessage( 'image_sample' )->text(),
4074 'tip' => wfMessage( 'image_tip' )->text(),
4076 $imagesAvailable ?
[
4077 'id' => 'mw-editbutton-media',
4078 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4080 'sample' => wfMessage( 'media_sample' )->text(),
4081 'tip' => wfMessage( 'media_tip' )->text(),
4084 'id' => 'mw-editbutton-nowiki',
4085 'open' => "<nowiki>",
4086 'close' => "</nowiki>",
4087 'sample' => wfMessage( 'nowiki_sample' )->text(),
4088 'tip' => wfMessage( 'nowiki_tip' )->text(),
4091 'id' => 'mw-editbutton-signature',
4092 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4095 'tip' => wfMessage( 'sig_tip' )->text(),
4098 'id' => 'mw-editbutton-hr',
4099 'open' => "\n----\n",
4102 'tip' => wfMessage( 'hr_tip' )->text(),
4106 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4107 foreach ( $toolarray as $tool ) {
4113 // Images are defined in ResourceLoaderEditToolbarModule
4115 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4116 // Older browsers show a "speedtip" type message only for ALT.
4117 // Ideally these should be different, realistically they
4118 // probably don't need to be.
4126 $script .= Xml
::encodeJsCall(
4127 'mw.toolbar.addButton',
4129 ResourceLoader
::inDebugMode()
4135 $toolbar = '<div id="toolbar"></div>';
4137 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4138 // Only add the old toolbar cruft to the page payload if the toolbar has not
4139 // been over-written by a hook caller
4140 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
4147 * Return an array of checkbox definitions.
4149 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4151 * Array values are associative arrays with the following keys:
4152 * - 'label-message' (required): message for label text
4153 * - 'id' (required): 'id' attribute for the `<input>`
4154 * - 'default' (required): default checkedness (true or false)
4155 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4156 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4157 * from messages like 'tooltip-foo', 'accesskey-foo'
4158 * - 'label-id' (optional): 'id' attribute for the `<label>`
4159 * - 'legacy-name' (optional): short name for backwards-compatibility
4160 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4161 * where bool indicates the checked status of the checkbox
4164 public function getCheckboxesDefinition( $checked ) {
4167 $user = $this->context
->getUser();
4168 // don't show the minor edit checkbox if it's a new page or section
4169 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4170 $checkboxes['wpMinoredit'] = [
4171 'id' => 'wpMinoredit',
4172 'label-message' => 'minoredit',
4173 // Uses messages: tooltip-minoredit, accesskey-minoredit
4174 'tooltip' => 'minoredit',
4175 'label-id' => 'mw-editpage-minoredit',
4176 'legacy-name' => 'minor',
4177 'default' => $checked['minor'],
4181 if ( $user->isLoggedIn() ) {
4182 $checkboxes['wpWatchthis'] = [
4183 'id' => 'wpWatchthis',
4184 'label-message' => 'watchthis',
4185 // Uses messages: tooltip-watch, accesskey-watch
4186 'tooltip' => 'watch',
4187 'label-id' => 'mw-editpage-watch',
4188 'legacy-name' => 'watch',
4189 'default' => $checked['watch'],
4194 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4200 * Returns an array of html code of the following checkboxes old style:
4203 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4204 * @param int &$tabindex Current tabindex
4205 * @param array $checked See getCheckboxesDefinition()
4208 public function getCheckboxes( &$tabindex, $checked ) {
4210 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4212 // Backwards-compatibility for the EditPageBeforeEditChecks hook
4213 if ( !$this->isNew
) {
4214 $checkboxes['minor'] = '';
4216 $checkboxes['watch'] = '';
4218 foreach ( $checkboxesDef as $name => $options ) {
4219 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4220 $label = $this->context
->msg( $options['label-message'] )->parse();
4222 'tabindex' => ++
$tabindex,
4223 'id' => $options['id'],
4226 'for' => $options['id'],
4228 if ( isset( $options['tooltip'] ) ) {
4229 $attribs['accesskey'] = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4230 $labelAttribs['title'] = Linker
::titleAttrib( $options['tooltip'], 'withaccess' );
4232 if ( isset( $options['title-message'] ) ) {
4233 $labelAttribs['title'] = $this->context
->msg( $options['title-message'] )->text();
4235 if ( isset( $options['label-id'] ) ) {
4236 $labelAttribs['id'] = $options['label-id'];
4239 Xml
::check( $name, $options['default'], $attribs ) .
4241 Xml
::tags( 'label', $labelAttribs, $label );
4243 $checkboxes[ $legacyName ] = $checkboxHtml;
4246 // Avoid PHP 7.1 warning of passing $this by reference
4248 Hooks
::run( 'EditPageBeforeEditChecks', [ &$editPage, &$checkboxes, &$tabindex ], '1.29' );
4253 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4254 * any other added by extensions.
4256 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4257 * @param int &$tabindex Current tabindex
4258 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4259 * status of the checkbox
4261 * @return array Associative array of string keys to OOUI\FieldLayout instances
4263 public function getCheckboxesOOUI( &$tabindex, $checked ) {
4264 return $this->getCheckboxesWidget( $tabindex, $checked );
4268 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4269 * any other added by extensions.
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 getCheckboxesWidget( &$tabindex, $checked ) {
4279 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4281 foreach ( $checkboxesDef as $name => $options ) {
4282 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4286 if ( isset( $options['tooltip'] ) ) {
4287 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4288 $title = Linker
::titleAttrib( $options['tooltip'] );
4290 if ( isset( $options['title-message'] ) ) {
4291 $title = $this->context
->msg( $options['title-message'] )->text();
4294 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4295 new OOUI\
CheckboxInputWidget( [
4296 'tabIndex' => ++
$tabindex,
4297 'accessKey' => $accesskey,
4298 'id' => $options['id'] . 'Widget',
4299 'inputId' => $options['id'],
4301 'selected' => $options['default'],
4302 'infusable' => true,
4305 'align' => 'inline',
4306 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4308 'id' => isset( $options['label-id'] ) ?
$options['label-id'] : null,
4313 // Backwards-compatibility hack to run the EditPageBeforeEditChecks hook. It's important,
4314 // people have used it for the weirdest things completely unrelated to checkboxes...
4315 // And if we're gonna run it, might as well allow its legacy checkboxes to be shown.
4316 $legacyCheckboxes = [];
4317 if ( !$this->isNew
) {
4318 $legacyCheckboxes['minor'] = '';
4320 $legacyCheckboxes['watch'] = '';
4321 // Copy new-style checkboxes into an old-style structure
4322 foreach ( $checkboxes as $name => $oouiLayout ) {
4323 $legacyCheckboxes[$name] = (string)$oouiLayout;
4325 // Avoid PHP 7.1 warning of passing $this by reference
4327 Hooks
::run( 'EditPageBeforeEditChecks', [ &$ep, &$legacyCheckboxes, &$tabindex ], '1.29' );
4328 // Copy back any additional old-style checkboxes into the new-style structure
4329 foreach ( $legacyCheckboxes as $name => $html ) {
4330 if ( $html && !isset( $checkboxes[$name] ) ) {
4331 $checkboxes[$name] = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $html ) ] );
4339 * Get the message key of the label for the button to save the page
4343 protected function getSubmitButtonLabel() {
4345 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4347 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4348 $newPage = !$this->mTitle
->exists();
4350 if ( $labelAsPublish ) {
4351 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4353 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4356 return $buttonLabelKey;
4360 * Returns an array of html code of the following buttons:
4361 * save, diff and preview
4363 * @param int &$tabindex Current tabindex
4367 public function getEditButtons( &$tabindex ) {
4370 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4374 'tabindex' => ++
$tabindex,
4377 $saveConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4378 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4379 'id' => 'wpSaveWidget',
4380 'inputId' => 'wpSave',
4381 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4382 'useInputTag' => true,
4383 'flags' => [ 'constructive', 'primary' ],
4384 'label' => $buttonLabel,
4385 'infusable' => true,
4387 'title' => Linker
::titleAttrib( 'save' ),
4388 'accessKey' => Linker
::accesskey( 'save' ),
4392 'name' => 'wpPreview',
4393 'tabindex' => ++
$tabindex,
4396 $previewConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4397 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4398 'id' => 'wpPreviewWidget',
4399 'inputId' => 'wpPreview',
4400 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4401 'useInputTag' => true,
4402 'label' => $this->context
->msg( 'showpreview' )->text(),
4403 'infusable' => true,
4405 'title' => Linker
::titleAttrib( 'preview' ),
4406 'accessKey' => Linker
::accesskey( 'preview' ),
4407 ] +
$previewConfig );
4411 'tabindex' => ++
$tabindex,
4414 $diffConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4415 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4416 'id' => 'wpDiffWidget',
4417 'inputId' => 'wpDiff',
4418 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4419 'useInputTag' => true,
4420 'label' => $this->context
->msg( 'showdiff' )->text(),
4421 'infusable' => true,
4423 'title' => Linker
::titleAttrib( 'diff' ),
4424 'accessKey' => Linker
::accesskey( 'diff' ),
4427 // Avoid PHP 7.1 warning of passing $this by reference
4429 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4435 * Creates a basic error page which informs the user that
4436 * they have attempted to edit a nonexistent section.
4438 public function noSuchSectionPage() {
4439 $out = $this->context
->getOutput();
4440 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4442 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4444 // Avoid PHP 7.1 warning of passing $this by reference
4446 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4447 $out->addHTML( $res );
4449 $out->returnToMain( false, $this->mTitle
);
4453 * Show "your edit contains spam" page with your diff and text
4455 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4457 public function spamPageWithContent( $match = false ) {
4458 $this->textbox2
= $this->textbox1
;
4460 if ( is_array( $match ) ) {
4461 $match = $this->context
->getLanguage()->listToText( $match );
4463 $out = $this->context
->getOutput();
4464 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4466 $out->addHTML( '<div id="spamprotected">' );
4467 $out->addWikiMsg( 'spamprotectiontext' );
4469 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4471 $out->addHTML( '</div>' );
4473 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4476 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4477 $this->showTextbox2();
4479 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4483 * Filter an input field through a Unicode de-armoring process if it
4484 * came from an old browser with known broken Unicode editing issues.
4486 * @deprecated since 1.30, does nothing
4488 * @param WebRequest $request
4489 * @param string $field
4492 protected function safeUnicodeInput( $request, $field ) {
4493 return rtrim( $request->getText( $field ) );
4497 * Filter an output field through a Unicode armoring process if it is
4498 * going to an old browser with known broken Unicode editing issues.
4500 * @deprecated since 1.30, does nothing
4502 * @param string $text
4505 protected function safeUnicodeOutput( $text ) {
4512 protected function addEditNotices() {
4513 $out = $this->context
->getOutput();
4514 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4515 if ( count( $editNotices ) ) {
4516 $out->addHTML( implode( "\n", $editNotices ) );
4518 $msg = $this->context
->msg( 'editnotice-notext' );
4519 if ( !$msg->isDisabled() ) {
4521 '<div class="mw-editnotice-notext">'
4522 . $msg->parseAsBlock()
4532 protected function addTalkPageText() {
4533 if ( $this->mTitle
->isTalkPage() ) {
4534 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4541 protected function addLongPageWarningHeader() {
4542 global $wgMaxArticleSize;
4544 if ( $this->contentLength
=== false ) {
4545 $this->contentLength
= strlen( $this->textbox1
);
4548 $out = $this->context
->getOutput();
4549 $lang = $this->context
->getLanguage();
4550 if ( $this->tooBig ||
$this->contentLength
> $wgMaxArticleSize * 1024 ) {
4551 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4554 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4555 $lang->formatNum( $wgMaxArticleSize )
4559 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4560 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4563 $lang->formatSize( strlen( $this->textbox1
) ),
4564 strlen( $this->textbox1
)
4574 protected function addPageProtectionWarningHeaders() {
4575 $out = $this->context
->getOutput();
4576 if ( $this->mTitle
->isProtected( 'edit' ) &&
4577 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4579 # Is the title semi-protected?
4580 if ( $this->mTitle
->isSemiProtected() ) {
4581 $noticeMsg = 'semiprotectedpagewarning';
4583 # Then it must be protected based on static groups (regular)
4584 $noticeMsg = 'protectedpagewarning';
4586 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4587 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4589 if ( $this->mTitle
->isCascadeProtected() ) {
4590 # Is this page under cascading protection from some source pages?
4591 /** @var Title[] $cascadeSources */
4592 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4593 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4594 $cascadeSourcesCount = count( $cascadeSources );
4595 if ( $cascadeSourcesCount > 0 ) {
4596 # Explain, and list the titles responsible
4597 foreach ( $cascadeSources as $page ) {
4598 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4601 $notice .= '</div>';
4602 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4604 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4605 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4607 'showIfEmpty' => false,
4608 'msgKey' => [ 'titleprotectedwarning' ],
4609 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4614 * @param OutputPage $out
4617 protected function addExplainConflictHeader( OutputPage
$out ) {
4619 "<div class='mw-explainconflict'>\n$1\n</div>",
4620 [ 'explainconflict', $this->context
->msg( $this->getSubmitButtonLabel() )->text() ]
4625 * @param string $name
4626 * @param mixed[] $customAttribs
4631 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4632 $attribs = $customAttribs +
[
4637 // Avoid PHP notices when appending preferences
4638 // (appending allows customAttribs['style'] to still work).
4642 // The following classes can be used here:
4643 // * mw-editfont-default
4644 // * mw-editfont-monospace
4645 // * mw-editfont-sans-serif
4646 // * mw-editfont-serif
4647 $class = 'mw-editfont-' . $user->getOption( 'editfont' );
4649 if ( isset( $attribs['class'] ) ) {
4650 if ( is_string( $attribs['class'] ) ) {
4651 $attribs['class'] .= ' ' . $class;
4652 } elseif ( is_array( $attribs['class'] ) ) {
4653 $attribs['class'][] = $class;
4656 $attribs['class'] = $class;
4659 $pageLang = $this->mTitle
->getPageLanguage();
4660 $attribs['lang'] = $pageLang->getHtmlCode();
4661 $attribs['dir'] = $pageLang->getDir();
4667 * @param string $wikitext
4671 protected function addNewLineAtEnd( $wikitext ) {
4672 if ( strval( $wikitext ) !== '' ) {
4673 // Ensure there's a newline at the end, otherwise adding lines
4675 // But don't add a newline if the text is empty, or Firefox in XHTML
4676 // mode will show an extra newline. A bit annoying.
4684 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4685 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4686 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4687 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4688 * spread the new style links more efficiently.
4690 * @param string $text
4693 private function guessSectionName( $text ) {
4696 // Detect Microsoft browsers
4697 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4698 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4699 // ...and redirect them to legacy encoding, if available
4700 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4702 // Meanwhile, real browsers get real anchors
4703 return $wgParser->guessSectionNameFromWikiText( $text );