3 * User interface for page editing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\EditPage\TextboxBuilder
;
24 use MediaWiki\EditPage\TextConflictHelper
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\ScopedCallback
;
30 * The edit page/HTML interface (split from Article)
31 * The actual database and text munging is still in Article,
32 * but it should get easier to call those from alternate
35 * EditPage cares about two distinct titles:
36 * $this->mContextTitle is the page that forms submit to, links point to,
37 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
38 * page in the database that is actually being edited. These are
39 * usually the same, but they are now allowed to be different.
41 * Surgeon General's Warning: prolonged exposure to this class is known to cause
42 * headaches, which may be fatal.
46 * Used for Unicode support checks
48 const UNICODE_CHECK
= 'β³π²β₯πππΎπΈβ΄πΉβ―';
51 * Status: Article successfully updated
53 const AS_SUCCESS_UPDATE
= 200;
56 * Status: Article successfully created
58 const AS_SUCCESS_NEW_ARTICLE
= 201;
61 * Status: Article update aborted by a hook function
63 const AS_HOOK_ERROR
= 210;
66 * Status: A hook function returned an error
68 const AS_HOOK_ERROR_EXPECTED
= 212;
71 * Status: User is blocked from editing this page
73 const AS_BLOCKED_PAGE_FOR_USER
= 215;
76 * Status: Content too big (> $wgMaxArticleSize)
78 const AS_CONTENT_TOO_BIG
= 216;
81 * Status: this anonymous user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_ANON
= 218;
86 * Status: this logged in user is not allowed to edit this page
88 const AS_READ_ONLY_PAGE_LOGGED
= 219;
91 * Status: wiki is in readonly mode (wfReadOnly() == true)
93 const AS_READ_ONLY_PAGE
= 220;
96 * Status: rate limiter for action 'edit' was tripped
98 const AS_RATE_LIMITED
= 221;
101 * Status: article was deleted while editing and param wpRecreate == false or form
104 const AS_ARTICLE_WAS_DELETED
= 222;
107 * Status: user tried to create this page, but is not allowed to do that
108 * ( Title->userCan('create') == false )
110 const AS_NO_CREATE_PERMISSION
= 223;
113 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
115 const AS_BLANK_ARTICLE
= 224;
118 * Status: (non-resolvable) edit conflict
120 const AS_CONFLICT_DETECTED
= 225;
123 * Status: no edit summary given and the user has forceeditsummary set and the user is not
124 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
126 const AS_SUMMARY_NEEDED
= 226;
129 * Status: user tried to create a new section without content
131 const AS_TEXTBOX_EMPTY
= 228;
134 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
136 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
139 * Status: WikiPage::doEdit() was unsuccessful
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
146 const AS_SPAM_ERROR
= 232;
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
151 const AS_IMAGE_REDIRECT_ANON
= 233;
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
156 const AS_IMAGE_REDIRECT_LOGGED
= 234;
159 * Status: user tried to modify the content model, but is not allowed to do that
160 * ( User::isAllowed('editcontentmodel') == false )
162 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
165 * Status: user tried to create self-redirect (redirect to the same article) and
166 * wpIgnoreSelfRedirect == false
168 const AS_SELF_REDIRECT
= 236;
171 * Status: an error relating to change tagging. Look at the message key for
174 const AS_CHANGE_TAG_ERROR
= 237;
177 * Status: can't parse content
179 const AS_PARSE_ERROR
= 240;
182 * Status: when changing the content model is disallowed due to
183 * $wgContentHandlerUseDB being false
185 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
188 * Status: edit rejected because browser doesn't support Unicode.
190 const AS_UNICODE_NOT_SUPPORTED
= 242;
193 * HTML id and name for the beginning of the edit form.
195 const EDITFORM_ID
= 'editform';
198 * Prefix of key for cookie used to pass post-edit state.
199 * The revision id edited is added after this
201 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
204 * Duration of PostEdit cookie, in seconds.
205 * The cookie will be removed instantly if the JavaScript runs.
207 * Otherwise, though, we don't want the cookies to accumulate.
208 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
209 * limit of only 20 cookies per domain. This still applies at least to some
210 * versions of IE without full updates:
211 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
213 * A value of 20 minutes should be enough to take into account slow loads and minor
214 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
216 const POST_EDIT_COOKIE_DURATION
= 1200;
219 * @deprecated for public usage since 1.30 use EditPage::getArticle()
227 * @deprecated for public usage since 1.30 use EditPage::getTitle()
232 /** @var null|Title */
233 private $mContextTitle = null;
236 public $action = 'submit';
238 /** @var bool Whether an edit conflict needs to be resolved. Detected based on whether
239 * $editRevId is different than the latest revision. When a conflict has successfully
240 * been resolved by a 3-way-merge, this field is set to false.
242 public $isConflict = false;
244 /** @var bool New page or new section */
245 public $isNew = false;
248 public $deletedSinceEdit;
254 * True the first time the edit form is rendered, false after re-rendering
255 * with diff, save prompts, etc.
259 /** @var bool|stdClass */
263 public $mTokenOk = false;
266 public $mTokenOkExceptSuffix = false;
269 public $mTriedSave = false;
272 public $incompleteForm = false;
275 public $tooBig = false;
278 public $missingComment = false;
281 public $missingSummary = false;
284 public $allowBlankSummary = false;
287 protected $blankArticle = false;
290 protected $allowBlankArticle = false;
293 protected $selfRedirect = false;
296 protected $allowSelfRedirect = false;
299 public $autoSumm = '';
302 public $hookError = '';
304 /** @var ParserOutput */
305 public $mParserOutput;
307 /** @var bool Has a summary been preset using GET parameter &summary= ? */
308 public $hasPresetSummary = false;
310 /** @var Revision|bool|null A revision object corresponding to $this->editRevId. */
311 public $mBaseRevision = false;
314 public $mShowSummaryField = true;
319 public $save = false;
322 public $preview = false;
325 public $diff = false;
328 public $minoredit = false;
331 public $watchthis = false;
334 public $recreate = false;
337 * Page content input field.
339 public $textbox1 = '';
342 public $textbox2 = '';
345 public $summary = '';
348 * If true, hide the summary field.
350 public $nosummary = false;
353 * Timestamp of the latest revision of the page when editing was initiated
356 public $edittime = '';
358 /** @var int Revision ID of the latest revision of the page when editing
359 * was initiated on the client. This is used to detect and resolve edit
362 * @note 0 if the page did not exist at that time.
363 * @note When starting an edit from an old revision, this still records the current
364 * revision at the time, not the one the edit is based on.
367 * @see getBaseRevision()
369 private $editRevId = null;
372 public $section = '';
375 public $sectiontitle = '';
378 * Timestamp from the first time the edit form was rendered.
380 public $starttime = '';
382 /** @var int Revision ID the edit is based on, or 0 if it's the current revision.
383 * FIXME: This isn't used in conflict resolution--provide a better
384 * justification or merge with parentRevId.
389 /** @var int Revision ID the edit is based on, adjusted when an edit conflict is resolved.
392 * @see getparentRevId()
394 public $parentRevId = 0;
397 public $editintro = '';
400 public $scrolltop = null;
406 public $contentModel;
408 /** @var null|string */
409 public $contentFormat = null;
411 /** @var null|array */
412 private $changeTags = null;
414 # Placeholders for text injection by hooks (must be HTML)
415 # extensions should take care to _append_ to the present value
417 /** @var string Before even the preview */
418 public $editFormPageTop = '';
419 public $editFormTextTop = '';
420 public $editFormTextBeforeContent = '';
421 public $editFormTextAfterWarn = '';
422 public $editFormTextAfterTools = '';
423 public $editFormTextBottom = '';
424 public $editFormTextAfterContent = '';
425 public $previewTextAfterContent = '';
426 public $mPreloadContent = null;
428 /* $didSave should be set to true whenever an article was successfully altered. */
429 public $didSave = false;
430 public $undidRev = 0;
432 public $suppressIntro = false;
438 protected $contentLength = false;
441 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
443 private $enableApiEditOverride = false;
446 * @var IContextSource
451 * @var bool Whether an old revision is edited
453 private $isOldRev = false;
456 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
458 private $unicodeCheck;
461 * Factory function to create an edit conflict helper
465 private $editConflictHelperFactory;
468 * @var TextConflictHelper|null
470 private $editConflictHelper;
473 * @param Article $article
475 public function __construct( Article
$article ) {
476 $this->mArticle
= $article;
477 $this->page
= $article->getPage(); // model object
478 $this->mTitle
= $article->getTitle();
479 $this->context
= $article->getContext();
481 $this->contentModel
= $this->mTitle
->getContentModel();
483 $handler = ContentHandler
::getForModelID( $this->contentModel
);
484 $this->contentFormat
= $handler->getDefaultFormat();
485 $this->editConflictHelperFactory
= [ $this, 'newTextConflictHelper' ];
491 public function getArticle() {
492 return $this->mArticle
;
497 * @return IContextSource
499 public function getContext() {
500 return $this->context
;
507 public function getTitle() {
508 return $this->mTitle
;
512 * Set the context Title object
514 * @param Title|null $title Title object or null
516 public function setContextTitle( $title ) {
517 $this->mContextTitle
= $title;
521 * Get the context title object.
523 * If not set, $wgTitle will be returned, but this is deprecated. This will
524 * throw an exception.
528 public function getContextTitle() {
529 if ( is_null( $this->mContextTitle
) ) {
530 wfDeprecated( __METHOD__
. ' called with no title set', '1.32' );
534 return $this->mContextTitle
;
539 * Returns if the given content model is editable.
541 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
543 * @throws MWException If $modelId has no known handler
545 public function isSupportedContentModel( $modelId ) {
546 return $this->enableApiEditOverride
=== true ||
547 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
551 * Allow editing of content that supports API direct editing, but not general
552 * direct editing. Set to false by default.
554 * @param bool $enableOverride
556 public function setApiEditOverride( $enableOverride ) {
557 $this->enableApiEditOverride
= $enableOverride;
561 * @deprecated since 1.29, call edit directly
563 public function submit() {
564 wfDeprecated( __METHOD__
, '1.29' );
569 * This is the function that gets called for "action=edit". It
570 * sets up various member variables, then passes execution to
571 * another function, usually showEditForm()
573 * The edit form is self-submitting, so that when things like
574 * preview and edit conflicts occur, we get the same form back
575 * with the extra stuff added. Only when the final submission
576 * is made and all is well do we actually save and redirect to
577 * the newly-edited page.
579 public function edit() {
580 // Allow extensions to modify/prevent this form or submission
581 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
585 wfDebug( __METHOD__
. ": enter\n" );
587 $request = $this->context
->getRequest();
588 // If they used redlink=1 and the page exists, redirect to the main article
589 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
590 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
594 $this->importFormData( $request );
595 $this->firsttime
= false;
597 if ( wfReadOnly() && $this->save
) {
600 $this->preview
= true;
604 $this->formtype
= 'save';
605 } elseif ( $this->preview
) {
606 $this->formtype
= 'preview';
607 } elseif ( $this->diff
) {
608 $this->formtype
= 'diff';
609 } else { # First time through
610 $this->firsttime
= true;
611 if ( $this->previewOnOpen() ) {
612 $this->formtype
= 'preview';
614 $this->formtype
= 'initial';
618 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
620 wfDebug( __METHOD__
. ": User can't edit\n" );
622 // track block with a cookie if it doesn't exists already
623 $this->context
->getUser()->trackBlockWithCookie();
625 // Auto-block user's IP if the account was "hard" blocked
626 if ( !wfReadOnly() ) {
627 DeferredUpdates
::addCallableUpdate( function () {
628 $this->context
->getUser()->spreadAnyEditBlock();
631 $this->displayPermissionsError( $permErrors );
636 $revision = $this->mArticle
->getRevisionFetched();
637 // Disallow editing revisions with content models different from the current one
638 // Undo edits being an exception in order to allow reverting content model changes.
640 && $revision->getContentModel() !== $this->contentModel
643 if ( $this->undidRev
) {
644 $undidRevObj = Revision
::newFromId( $this->undidRev
);
645 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
647 if ( !$this->undidRev
649 ||
$prevRev->getContentModel() !== $this->contentModel
651 $this->displayViewSourcePage(
652 $this->getContentObject(),
654 'contentmodelediterror',
655 $revision->getContentModel(),
663 $this->isConflict
= false;
665 # Show applicable editing introductions
666 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
670 # Attempt submission here. This will check for edit conflicts,
671 # and redundantly check for locked database, blocked IPs, etc.
672 # that edit() already checked just in case someone tries to sneak
673 # in the back door with a hand-edited submission URL.
675 if ( 'save' == $this->formtype
) {
676 $resultDetails = null;
677 $status = $this->attemptSave( $resultDetails );
678 if ( !$this->handleStatus( $status, $resultDetails ) ) {
683 # First time through: get contents, set time for conflict
685 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
686 if ( $this->initialiseForm() === false ) {
687 $out = $this->context
->getOutput();
688 if ( $out->getRedirect() === '' ) { // mcrundo hack redirects, don't override it
689 $this->noSuchSectionPage();
694 if ( !$this->mTitle
->getArticleID() ) {
695 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
697 Hooks
::run( 'EditFormInitialText', [ $this ] );
702 $this->showEditForm();
706 * @param string $rigor Same format as Title::getUserPermissionErrors()
709 protected function getEditPermissionErrors( $rigor = 'secure' ) {
710 $user = $this->context
->getUser();
711 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
712 # Can this title be created?
713 if ( !$this->mTitle
->exists() ) {
714 $permErrors = array_merge(
717 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
722 # Ignore some permissions errors when a user is just previewing/viewing diffs
724 foreach ( $permErrors as $error ) {
725 if ( ( $this->preview ||
$this->diff
)
727 $error[0] == 'blockedtext' ||
728 $error[0] == 'autoblockedtext' ||
729 $error[0] == 'systemblockedtext'
735 $permErrors = wfArrayDiff2( $permErrors, $remove );
741 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
742 * but with the following differences:
743 * - If redlink=1, the user will be redirected to the page
744 * - If there is content to display or the error occurs while either saving,
745 * previewing or showing the difference, it will be a
746 * "View source for ..." page displaying the source code after the error message.
749 * @param array $permErrors Array of permissions errors, as returned by
750 * Title::getUserPermissionsErrors().
751 * @throws PermissionsError
753 protected function displayPermissionsError( array $permErrors ) {
754 $out = $this->context
->getOutput();
755 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
756 // The edit page was reached via a red link.
757 // Redirect to the article page and let them click the edit tab if
758 // they really want a permission error.
759 $out->redirect( $this->mTitle
->getFullURL() );
763 $content = $this->getContentObject();
765 # Use the normal message if there's nothing to display
766 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
767 $action = $this->mTitle
->exists() ?
'edit' :
768 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
769 throw new PermissionsError( $action, $permErrors );
772 $this->displayViewSourcePage(
774 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
779 * Display a read-only View Source page
780 * @param Content $content
781 * @param string $errorMessage additional wikitext error message to display
783 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
784 $out = $this->context
->getOutput();
785 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
787 $out->setRobotPolicy( 'noindex,nofollow' );
788 $out->setPageTitle( $this->context
->msg(
790 $this->getContextTitle()->getPrefixedText()
792 $out->addBacklinkSubtitle( $this->getContextTitle() );
793 $out->addHTML( $this->editFormPageTop
);
794 $out->addHTML( $this->editFormTextTop
);
796 if ( $errorMessage !== '' ) {
797 $out->addWikiText( $errorMessage );
798 $out->addHTML( "<hr />\n" );
801 # If the user made changes, preserve them when showing the markup
802 # (This happens when a user is blocked during edit, for instance)
803 if ( !$this->firsttime
) {
804 $text = $this->textbox1
;
805 $out->addWikiMsg( 'viewyourtext' );
808 $text = $this->toEditText( $content );
809 } catch ( MWException
$e ) {
810 # Serialize using the default format if the content model is not supported
811 # (e.g. for an old revision with a different model)
812 $text = $content->serialize();
814 $out->addWikiMsg( 'viewsourcetext' );
817 $out->addHTML( $this->editFormTextBeforeContent
);
818 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
819 $out->addHTML( $this->editFormTextAfterContent
);
821 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
823 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
825 $out->addHTML( $this->editFormTextBottom
);
826 if ( $this->mTitle
->exists() ) {
827 $out->returnToMain( null, $this->mTitle
);
832 * Should we show a preview when the edit form is first shown?
836 protected function previewOnOpen() {
837 $config = $this->context
->getConfig();
838 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
839 $request = $this->context
->getRequest();
840 if ( $config->get( 'RawHtml' ) ) {
841 // If raw HTML is enabled, disable preview on open
842 // since it has to be posted with a token for
846 if ( $request->getVal( 'preview' ) == 'yes' ) {
847 // Explicit override from request
849 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
850 // Explicit override from request
852 } elseif ( $this->section
== 'new' ) {
853 // Nothing *to* preview for new sections
855 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
856 && $this->context
->getUser()->getOption( 'previewonfirst' )
858 // Standard preference behavior
860 } elseif ( !$this->mTitle
->exists()
861 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
862 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
864 // Categories are special
872 * Checks whether the user entered a skin name in uppercase,
873 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
877 protected function isWrongCaseUserConfigPage() {
878 if ( $this->mTitle
->isUserConfigPage() ) {
879 $name = $this->mTitle
->getSkinFromConfigSubpage();
880 $skins = array_merge(
881 array_keys( Skin
::getSkinNames() ),
884 return !in_array( $name, $skins )
885 && in_array( strtolower( $name ), $skins );
892 * Returns whether section editing is supported for the current page.
893 * Subclasses may override this to replace the default behavior, which is
894 * to check ContentHandler::supportsSections.
896 * @return bool True if this edit page supports sections, false otherwise.
898 protected function isSectionEditSupported() {
899 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
900 return $contentHandler->supportsSections();
904 * This function collects the form data and uses it to populate various member variables.
905 * @param WebRequest &$request
906 * @throws ErrorPageError
908 public function importFormData( &$request ) {
909 # Section edit can come from either the form or a link
910 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
912 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
913 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
916 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
918 if ( $request->wasPosted() ) {
919 # These fields need to be checked for encoding.
920 # Also remove trailing whitespace, but don't remove _initial_
921 # whitespace from the text boxes. This may be significant formatting.
922 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
923 if ( !$request->getCheck( 'wpTextbox2' ) ) {
924 // Skip this if wpTextbox2 has input, it indicates that we came
925 // from a conflict page with raw page text, not a custom form
926 // modified by subclasses
927 $textbox1 = $this->importContentFormData( $request );
928 if ( $textbox1 !== null ) {
929 $this->textbox1
= $textbox1;
933 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
935 $this->summary
= $request->getText( 'wpSummary' );
937 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
938 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
940 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
942 # Treat sectiontitle the same way as summary.
943 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
944 # currently doing double duty as both edit summary and section title. Right now this
945 # is just to allow API edits to work around this limitation, but this should be
946 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
947 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
948 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
950 $this->edittime
= $request->getVal( 'wpEdittime' );
951 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
952 $this->starttime
= $request->getVal( 'wpStarttime' );
954 $undidRev = $request->getInt( 'wpUndidRevision' );
956 $this->undidRev
= $undidRev;
959 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
961 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
962 // wpTextbox1 field is missing, possibly due to being "too big"
963 // according to some filter rules such as Suhosin's setting for
964 // suhosin.request.max_value_length (d'oh)
965 $this->incompleteForm
= true;
967 // If we receive the last parameter of the request, we can fairly
968 // claim the POST request has not been truncated.
969 $this->incompleteForm
= !$request->getVal( 'wpUltimateParam' );
971 if ( $this->incompleteForm
) {
972 # If the form is incomplete, force to preview.
973 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
974 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
975 $this->preview
= true;
977 $this->preview
= $request->getCheck( 'wpPreview' );
978 $this->diff
= $request->getCheck( 'wpDiff' );
980 // Remember whether a save was requested, so we can indicate
981 // if we forced preview due to session failure.
982 $this->mTriedSave
= !$this->preview
;
984 if ( $this->tokenOk( $request ) ) {
985 # Some browsers will not report any submit button
986 # if the user hits enter in the comment box.
987 # The unmarked state will be assumed to be a save,
988 # if the form seems otherwise complete.
989 wfDebug( __METHOD__
. ": Passed token check.\n" );
990 } elseif ( $this->diff
) {
991 # Failed token check, but only requested "Show Changes".
992 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
994 # Page might be a hack attempt posted from
995 # an external site. Preview instead of saving.
996 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
997 $this->preview
= true;
1000 $this->save
= !$this->preview
&& !$this->diff
;
1001 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
1002 $this->edittime
= null;
1005 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
1006 $this->starttime
= null;
1009 $this->recreate
= $request->getCheck( 'wpRecreate' );
1011 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
1012 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
1014 $user = $this->context
->getUser();
1015 # Don't force edit summaries when a user is editing their own user or talk page
1016 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
1017 && $this->mTitle
->getText() == $user->getName()
1019 $this->allowBlankSummary
= true;
1021 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1022 ||
!$user->getOption( 'forceeditsummary' );
1025 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1027 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1028 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1030 $changeTags = $request->getVal( 'wpChangeTags' );
1031 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1032 $this->changeTags
= [];
1034 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1038 # Not a posted form? Start with nothing.
1039 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1040 $this->textbox1
= '';
1041 $this->summary
= '';
1042 $this->sectiontitle
= '';
1043 $this->edittime
= '';
1044 $this->editRevId
= null;
1045 $this->starttime
= wfTimestampNow();
1046 $this->edit
= false;
1047 $this->preview
= false;
1048 $this->save
= false;
1049 $this->diff
= false;
1050 $this->minoredit
= false;
1051 // Watch may be overridden by request parameters
1052 $this->watchthis
= $request->getBool( 'watchthis', false );
1053 $this->recreate
= false;
1055 // When creating a new section, we can preload a section title by passing it as the
1056 // preloadtitle parameter in the URL (T15100)
1057 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1058 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1059 // Once wpSummary isn't being use for setting section titles, we should delete this.
1060 $this->summary
= $request->getVal( 'preloadtitle' );
1061 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) !== '' ) {
1062 $this->summary
= $request->getText( 'summary' );
1063 if ( $this->summary
!== '' ) {
1064 $this->hasPresetSummary
= true;
1068 if ( $request->getVal( 'minor' ) ) {
1069 $this->minoredit
= true;
1073 $this->oldid
= $request->getInt( 'oldid' );
1074 $this->parentRevId
= $request->getInt( 'parentRevId' );
1076 $this->bot
= $request->getBool( 'bot', true );
1077 $this->nosummary
= $request->getBool( 'nosummary' );
1079 // May be overridden by revision.
1080 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1081 // May be overridden by revision.
1082 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1085 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1086 } catch ( MWUnknownContentModelException
$e ) {
1087 throw new ErrorPageError(
1088 'editpage-invalidcontentmodel-title',
1089 'editpage-invalidcontentmodel-text',
1090 [ wfEscapeWikiText( $this->contentModel
) ]
1094 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1095 throw new ErrorPageError(
1096 'editpage-notsupportedcontentformat-title',
1097 'editpage-notsupportedcontentformat-text',
1099 wfEscapeWikiText( $this->contentFormat
),
1100 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1106 * @todo Check if the desired model is allowed in this namespace, and if
1107 * a transition from the page's current model to the new model is
1111 $this->editintro
= $request->getText( 'editintro',
1112 // Custom edit intro for new sections
1113 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1115 // Allow extensions to modify form data
1116 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1120 * Subpage overridable method for extracting the page content data from the
1121 * posted form to be placed in $this->textbox1, if using customized input
1122 * this method should be overridden and return the page text that will be used
1123 * for saving, preview parsing and so on...
1125 * @param WebRequest &$request
1126 * @return string|null
1128 protected function importContentFormData( &$request ) {
1129 return; // Don't do anything, EditPage already extracted wpTextbox1
1133 * Initialise form fields in the object
1134 * Called on the first invocation, e.g. when a user clicks an edit link
1135 * @return bool If the requested section is valid
1137 public function initialiseForm() {
1138 $this->edittime
= $this->page
->getTimestamp();
1139 $this->editRevId
= $this->page
->getLatest();
1141 $content = $this->getContentObject( false ); # TODO: track content object?!
1142 if ( $content === false ) {
1145 $this->textbox1
= $this->toEditText( $content );
1147 $user = $this->context
->getUser();
1148 // activate checkboxes if user wants them to be always active
1149 # Sort out the "watch" checkbox
1150 if ( $user->getOption( 'watchdefault' ) ) {
1152 $this->watchthis
= true;
1153 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1155 $this->watchthis
= true;
1156 } elseif ( $user->isWatched( $this->mTitle
) ) {
1158 $this->watchthis
= true;
1160 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1161 $this->minoredit
= true;
1163 if ( $this->textbox1
=== false ) {
1170 * @param Content|null $def_content The default value to return
1172 * @return Content|null Content on success, $def_content for invalid sections
1176 protected function getContentObject( $def_content = null ) {
1179 $user = $this->context
->getUser();
1180 $request = $this->context
->getRequest();
1181 // For message page not locally set, use the i18n message.
1182 // For other non-existent articles, use preload text if any.
1183 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1184 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1185 # If this is a system message, get the default text.
1186 $msg = $this->mTitle
->getDefaultMessageText();
1188 $content = $this->toEditContent( $msg );
1190 if ( $content === false ) {
1191 # If requested, preload some text.
1192 $preload = $request->getVal( 'preload',
1193 // Custom preload text for new sections
1194 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1195 $params = $request->getArray( 'preloadparams', [] );
1197 $content = $this->getPreloadedContent( $preload, $params );
1199 // For existing pages, get text based on "undo" or section parameters.
1201 if ( $this->section
!= '' ) {
1202 // Get section edit text (returns $def_text for invalid sections)
1203 $orig = $this->getOriginalContent( $user );
1204 $content = $orig ?
$orig->getSection( $this->section
) : null;
1207 $content = $def_content;
1210 $undoafter = $request->getInt( 'undoafter' );
1211 $undo = $request->getInt( 'undo' );
1213 if ( $undo > 0 && $undoafter > 0 ) {
1214 $undorev = Revision
::newFromId( $undo );
1215 $oldrev = Revision
::newFromId( $undoafter );
1218 # Sanity check, make sure it's the right page,
1219 # the revisions exist and they were not deleted.
1220 # Otherwise, $content will be left as-is.
1221 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1222 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1223 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1225 if ( WikiPage
::hasDifferencesOutsideMainSlot( $undorev, $oldrev )
1226 ||
!$this->isSupportedContentModel( $oldrev->getContentModel() )
1228 // Hack for undo while EditPage can't handle multi-slot editing
1229 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL( [
1230 'action' => 'mcrundo',
1232 'undoafter' => $undoafter,
1236 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1238 if ( $content === false ) {
1239 # Warn the user that something went wrong
1240 $undoMsg = 'failure';
1244 if ( $undoMsg === null ) {
1245 $oldContent = $this->page
->getContent( Revision
::RAW
);
1246 $popts = ParserOptions
::newFromUserAndLang(
1247 $user, MediaWikiServices
::getInstance()->getContentLanguage() );
1248 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1249 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1250 // The undo may change content
1251 // model if its reverting the top
1252 // edit. This can result in
1253 // mismatched content model/format.
1254 $this->contentModel
= $newContent->getModel();
1255 $this->contentFormat
= $oldrev->getContentFormat();
1258 if ( $newContent->equals( $oldContent ) ) {
1259 # Tell the user that the undo results in no change,
1260 # i.e. the revisions were already undone.
1261 $undoMsg = 'nochange';
1264 # Inform the user of our success and set an automatic edit summary
1265 $undoMsg = 'success';
1267 # If we just undid one rev, use an autosummary
1268 $firstrev = $oldrev->getNext();
1269 if ( $firstrev && $firstrev->getId() == $undo ) {
1270 $userText = $undorev->getUserText();
1271 if ( $userText === '' ) {
1272 $undoSummary = $this->context
->msg(
1273 'undo-summary-username-hidden',
1275 )->inContentLanguage()->text();
1277 $undoSummary = $this->context
->msg(
1281 )->inContentLanguage()->text();
1283 if ( $this->summary
=== '' ) {
1284 $this->summary
= $undoSummary;
1286 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1287 ->inContentLanguage()->text() . $this->summary
;
1289 $this->undidRev
= $undo;
1291 $this->formtype
= 'diff';
1295 // Failed basic sanity checks.
1296 // Older revisions may have been removed since the link
1297 // was created, or we may simply have got bogus input.
1301 $out = $this->context
->getOutput();
1302 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1304 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1305 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1306 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1309 if ( $content === false ) {
1310 // Hack for restoring old revisions while EditPage
1311 // can't handle multi-slot editing.
1313 $curRevision = $this->page
->getRevision();
1314 $oldRevision = $this->mArticle
->getRevisionFetched();
1318 && $curRevision->getId() !== $oldRevision->getId()
1319 && ( WikiPage
::hasDifferencesOutsideMainSlot( $oldRevision, $curRevision )
1320 ||
!$this->isSupportedContentModel( $oldRevision->getContentModel() ) )
1322 $this->context
->getOutput()->redirect(
1323 $this->mTitle
->getFullURL(
1325 'action' => 'mcrrestore',
1326 'restore' => $oldRevision->getId(),
1335 if ( $content === false ) {
1336 $content = $this->getOriginalContent( $user );
1345 * Get the content of the wanted revision, without section extraction.
1347 * The result of this function can be used to compare user's input with
1348 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1349 * to the original text of the edit.
1351 * This differs from Article::getContent() that when a missing revision is
1352 * encountered the result will be null and not the
1353 * 'missing-revision' message.
1356 * @param User $user The user to get the revision for
1357 * @return Content|null
1359 private function getOriginalContent( User
$user ) {
1360 if ( $this->section
== 'new' ) {
1361 return $this->getCurrentContent();
1363 $revision = $this->mArticle
->getRevisionFetched();
1364 if ( $revision === null ) {
1365 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1366 return $handler->makeEmptyContent();
1368 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1373 * Get the edit's parent revision ID
1375 * The "parent" revision is the ancestor that should be recorded in this
1376 * page's revision history. It is either the revision ID of the in-memory
1377 * article content, or in the case of a 3-way merge in order to rebase
1378 * across a recoverable edit conflict, the ID of the newer revision to
1379 * which we have rebased this page.
1382 * @return int Revision ID
1384 public function getParentRevId() {
1385 if ( $this->parentRevId
) {
1386 return $this->parentRevId
;
1388 return $this->mArticle
->getRevIdFetched();
1393 * Get the current content of the page. This is basically similar to
1394 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1395 * content object is returned instead of null.
1400 protected function getCurrentContent() {
1401 $rev = $this->page
->getRevision();
1402 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1404 if ( $content === false ||
$content === null ) {
1405 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1406 return $handler->makeEmptyContent();
1407 } elseif ( !$this->undidRev
) {
1408 // Content models should always be the same since we error
1409 // out if they are different before this point (in ->edit()).
1410 // The exception being, during an undo, the current revision might
1411 // differ from the prior revision.
1412 $logger = LoggerFactory
::getInstance( 'editpage' );
1413 if ( $this->contentModel
!== $rev->getContentModel() ) {
1414 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1415 'prev' => $this->contentModel
,
1416 'new' => $rev->getContentModel(),
1417 'title' => $this->getTitle()->getPrefixedDBkey(),
1418 'method' => __METHOD__
1420 $this->contentModel
= $rev->getContentModel();
1423 // Given that the content models should match, the current selected
1424 // format should be supported.
1425 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1426 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1428 'prev' => $this->contentFormat
,
1429 'new' => $rev->getContentFormat(),
1430 'title' => $this->getTitle()->getPrefixedDBkey(),
1431 'method' => __METHOD__
1433 $this->contentFormat
= $rev->getContentFormat();
1440 * Use this method before edit() to preload some content into the edit box
1442 * @param Content $content
1446 public function setPreloadedContent( Content
$content ) {
1447 $this->mPreloadContent
= $content;
1451 * Get the contents to be preloaded into the box, either set by
1452 * an earlier setPreloadText() or by loading the given page.
1454 * @param string $preload Representing the title to preload from.
1455 * @param array $params Parameters to use (interface-message style) in the preloaded text
1461 protected function getPreloadedContent( $preload, $params = [] ) {
1462 if ( !empty( $this->mPreloadContent
) ) {
1463 return $this->mPreloadContent
;
1466 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1468 if ( $preload === '' ) {
1469 return $handler->makeEmptyContent();
1472 $user = $this->context
->getUser();
1473 $title = Title
::newFromText( $preload );
1474 # Check for existence to avoid getting MediaWiki:Noarticletext
1475 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1476 // TODO: somehow show a warning to the user!
1477 return $handler->makeEmptyContent();
1480 $page = WikiPage
::factory( $title );
1481 if ( $page->isRedirect() ) {
1482 $title = $page->getRedirectTarget();
1484 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1485 // TODO: somehow show a warning to the user!
1486 return $handler->makeEmptyContent();
1488 $page = WikiPage
::factory( $title );
1491 $parserOptions = ParserOptions
::newFromUser( $user );
1492 $content = $page->getContent( Revision
::RAW
);
1495 // TODO: somehow show a warning to the user!
1496 return $handler->makeEmptyContent();
1499 if ( $content->getModel() !== $handler->getModelID() ) {
1500 $converted = $content->convert( $handler->getModelID() );
1502 if ( !$converted ) {
1503 // TODO: somehow show a warning to the user!
1504 wfDebug( "Attempt to preload incompatible content: " .
1505 "can't convert " . $content->getModel() .
1506 " to " . $handler->getModelID() );
1508 return $handler->makeEmptyContent();
1511 $content = $converted;
1514 return $content->preloadTransform( $title, $parserOptions, $params );
1518 * Make sure the form isn't faking a user's credentials.
1520 * @param WebRequest &$request
1524 public function tokenOk( &$request ) {
1525 $token = $request->getVal( 'wpEditToken' );
1526 $user = $this->context
->getUser();
1527 $this->mTokenOk
= $user->matchEditToken( $token );
1528 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1529 return $this->mTokenOk
;
1533 * Sets post-edit cookie indicating the user just saved a particular revision.
1535 * This uses a temporary cookie for each revision ID so separate saves will never
1536 * interfere with each other.
1538 * Article::view deletes the cookie on server-side after the redirect and
1539 * converts the value to the global JavaScript variable wgPostEdit.
1541 * If the variable were set on the server, it would be cached, which is unwanted
1542 * since the post-edit state should only apply to the load right after the save.
1544 * @param int $statusValue The status value (to check for new article status)
1546 protected function setPostEditCookie( $statusValue ) {
1547 $revisionId = $this->page
->getLatest();
1548 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1551 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1553 } elseif ( $this->oldid
) {
1557 $response = $this->context
->getRequest()->response();
1558 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1562 * Attempt submission
1563 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1564 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1565 * @return Status The resulting status object.
1567 public function attemptSave( &$resultDetails = false ) {
1568 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1569 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1570 // This is needed since PageUpdater no longer checks these rights!
1572 // Allow bots to exempt some edits from bot flagging
1573 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1574 $status = $this->internalAttemptSave( $resultDetails, $bot );
1576 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1582 * Log when a page was successfully saved after the edit conflict view
1584 private function incrementResolvedConflicts() {
1585 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1589 $this->getEditConflictHelper()->incrementResolvedStats();
1593 * Handle status, such as after attempt save
1595 * @param Status $status
1596 * @param array|bool $resultDetails
1598 * @throws ErrorPageError
1599 * @return bool False, if output is done, true if rest of the form should be displayed
1601 private function handleStatus( Status
$status, $resultDetails ) {
1603 * @todo FIXME: once the interface for internalAttemptSave() is made
1604 * nicer, this should use the message in $status
1606 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1607 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1609 $this->incrementResolvedConflicts();
1611 $this->didSave
= true;
1612 if ( !$resultDetails['nullEdit'] ) {
1613 $this->setPostEditCookie( $status->value
);
1617 $out = $this->context
->getOutput();
1619 // "wpExtraQueryRedirect" is a hidden input to modify
1620 // after save URL and is not used by actual edit form
1621 $request = $this->context
->getRequest();
1622 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1624 switch ( $status->value
) {
1625 case self
::AS_HOOK_ERROR_EXPECTED
:
1626 case self
::AS_CONTENT_TOO_BIG
:
1627 case self
::AS_ARTICLE_WAS_DELETED
:
1628 case self
::AS_CONFLICT_DETECTED
:
1629 case self
::AS_SUMMARY_NEEDED
:
1630 case self
::AS_TEXTBOX_EMPTY
:
1631 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1633 case self
::AS_BLANK_ARTICLE
:
1634 case self
::AS_SELF_REDIRECT
:
1637 case self
::AS_HOOK_ERROR
:
1640 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1641 case self
::AS_PARSE_ERROR
:
1642 case self
::AS_UNICODE_NOT_SUPPORTED
:
1643 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1646 case self
::AS_SUCCESS_NEW_ARTICLE
:
1647 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1648 if ( $extraQueryRedirect ) {
1649 if ( $query === '' ) {
1650 $query = $extraQueryRedirect;
1652 $query = $query . '&' . $extraQueryRedirect;
1655 $anchor = $resultDetails['sectionanchor'] ??
'';
1656 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1659 case self
::AS_SUCCESS_UPDATE
:
1661 $sectionanchor = $resultDetails['sectionanchor'];
1663 // Give extensions a chance to modify URL query on update
1665 'ArticleUpdateBeforeRedirect',
1666 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1669 if ( $resultDetails['redirect'] ) {
1670 if ( $extraQuery == '' ) {
1671 $extraQuery = 'redirect=no';
1673 $extraQuery = 'redirect=no&' . $extraQuery;
1676 if ( $extraQueryRedirect ) {
1677 if ( $extraQuery === '' ) {
1678 $extraQuery = $extraQueryRedirect;
1680 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1684 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1687 case self
::AS_SPAM_ERROR
:
1688 $this->spamPageWithContent( $resultDetails['spam'] );
1691 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1692 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1694 case self
::AS_IMAGE_REDIRECT_ANON
:
1695 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1696 throw new PermissionsError( 'upload' );
1698 case self
::AS_READ_ONLY_PAGE_ANON
:
1699 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1700 throw new PermissionsError( 'edit' );
1702 case self
::AS_READ_ONLY_PAGE
:
1703 throw new ReadOnlyError
;
1705 case self
::AS_RATE_LIMITED
:
1706 throw new ThrottledError();
1708 case self
::AS_NO_CREATE_PERMISSION
:
1709 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1710 throw new PermissionsError( $permission );
1712 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1713 throw new PermissionsError( 'editcontentmodel' );
1716 // We don't recognize $status->value. The only way that can happen
1717 // is if an extension hook aborted from inside ArticleSave.
1718 // Render the status object into $this->hookError
1719 // FIXME this sucks, we should just use the Status object throughout
1720 $this->hookError
= '<div class="error">' . "\n" . $status->getWikiText() .
1727 * Run hooks that can filter edits just before they get saved.
1729 * @param Content $content The Content to filter.
1730 * @param Status $status For reporting the outcome to the caller
1731 * @param User $user The user performing the edit
1735 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1736 // Run old style post-section-merge edit filter
1737 if ( $this->hookError
!= '' ) {
1738 # ...or the hook could be expecting us to produce an error
1739 $status->fatal( 'hookaborted' );
1740 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1744 // Run new style post-section-merge edit filter
1745 if ( !Hooks
::run( 'EditFilterMergedContent',
1746 [ $this->context
, $content, $status, $this->summary
,
1747 $user, $this->minoredit
] )
1749 # Error messages etc. could be handled within the hook...
1750 if ( $status->isGood() ) {
1751 $status->fatal( 'hookaborted' );
1752 // Not setting $this->hookError here is a hack to allow the hook
1753 // to cause a return to the edit page without $this->hookError
1754 // being set. This is used by ConfirmEdit to display a captcha
1755 // without any error message cruft.
1757 $this->hookError
= $this->formatStatusErrors( $status );
1759 // Use the existing $status->value if the hook set it
1760 if ( !$status->value
) {
1761 $status->value
= self
::AS_HOOK_ERROR
;
1764 } elseif ( !$status->isOK() ) {
1765 # ...or the hook could be expecting us to produce an error
1766 // FIXME this sucks, we should just use the Status object throughout
1767 $this->hookError
= $this->formatStatusErrors( $status );
1768 $status->fatal( 'hookaborted' );
1769 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1777 * Wrap status errors in an errorbox for increased visibility
1779 * @param Status $status
1780 * @return string Wikitext
1782 private function formatStatusErrors( Status
$status ) {
1783 $errmsg = $status->getWikiText(
1786 $this->context
->getLanguage()
1789 <div class="errorbox">
1797 * Return the summary to be used for a new section.
1799 * @param string $sectionanchor Set to the section anchor text
1802 private function newSectionSummary( &$sectionanchor = null ) {
1805 if ( $this->sectiontitle
!== '' ) {
1806 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1807 // If no edit summary was specified, create one automatically from the section
1808 // title and have it link to the new section. Otherwise, respect the summary as
1810 if ( $this->summary
=== '' ) {
1811 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1812 return $this->context
->msg( 'newsectionsummary' )
1813 ->plaintextParams( $cleanSectionTitle )->inContentLanguage()->text();
1815 } elseif ( $this->summary
!== '' ) {
1816 $sectionanchor = $this->guessSectionName( $this->summary
);
1817 # This is a new section, so create a link to the new section
1818 # in the revision summary.
1819 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1820 return $this->context
->msg( 'newsectionsummary' )
1821 ->plaintextParams( $cleanSummary )->inContentLanguage()->text();
1823 return $this->summary
;
1827 * Attempt submission (no UI)
1829 * @param array &$result Array to add statuses to, currently with the
1831 * - spam (string): Spam string from content if any spam is detected by
1833 * - sectionanchor (string): Section anchor for a section save.
1834 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1836 * - redirect (bool): Set if doEditContent is OK. True if resulting
1837 * revision is a redirect.
1838 * @param bool $bot True if edit is being made under the bot right.
1840 * @return Status Status object, possibly with a message, but always with
1841 * one of the AS_* constants in $status->value,
1843 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1844 * various error display idiosyncrasies. There are also lots of cases
1845 * where error metadata is set in the object and retrieved later instead
1846 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1847 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1850 public function internalAttemptSave( &$result, $bot = false ) {
1851 $status = Status
::newGood();
1852 $user = $this->context
->getUser();
1854 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1855 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1856 $status->fatal( 'hookaborted' );
1857 $status->value
= self
::AS_HOOK_ERROR
;
1861 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1862 $status->fatal( 'unicode-support-fail' );
1863 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1867 $request = $this->context
->getRequest();
1868 $spam = $request->getText( 'wpAntispam' );
1869 if ( $spam !== '' ) {
1874 $this->mTitle
->getPrefixedText() .
1875 '" submitted bogus field "' .
1879 $status->fatal( 'spamprotectionmatch', false );
1880 $status->value
= self
::AS_SPAM_ERROR
;
1885 # Construct Content object
1886 $textbox_content = $this->toEditContent( $this->textbox1
);
1887 } catch ( MWContentSerializationException
$ex ) {
1889 'content-failed-to-parse',
1890 $this->contentModel
,
1891 $this->contentFormat
,
1894 $status->value
= self
::AS_PARSE_ERROR
;
1898 # Check image redirect
1899 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1900 $textbox_content->isRedirect() &&
1901 !$user->isAllowed( 'upload' )
1903 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1904 $status->setResult( false, $code );
1910 $match = self
::matchSummarySpamRegex( $this->summary
);
1911 if ( $match === false && $this->section
== 'new' ) {
1912 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1913 # regular summaries, it is added to the actual wikitext.
1914 if ( $this->sectiontitle
!== '' ) {
1915 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1916 $match = self
::matchSpamRegex( $this->sectiontitle
);
1918 # This branch is taken when the "Add Topic" user interface is used, or the API
1919 # is used with the 'summary' parameter.
1920 $match = self
::matchSpamRegex( $this->summary
);
1923 if ( $match === false ) {
1924 $match = self
::matchSpamRegex( $this->textbox1
);
1926 if ( $match !== false ) {
1927 $result['spam'] = $match;
1928 $ip = $request->getIP();
1929 $pdbk = $this->mTitle
->getPrefixedDBkey();
1930 $match = str_replace( "\n", '', $match );
1931 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1932 $status->fatal( 'spamprotectionmatch', $match );
1933 $status->value
= self
::AS_SPAM_ERROR
;
1938 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1940 # Error messages etc. could be handled within the hook...
1941 $status->fatal( 'hookaborted' );
1942 $status->value
= self
::AS_HOOK_ERROR
;
1944 } elseif ( $this->hookError
!= '' ) {
1945 # ...or the hook could be expecting us to produce an error
1946 $status->fatal( 'hookaborted' );
1947 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1951 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1952 // Auto-block user's IP if the account was "hard" blocked
1953 if ( !wfReadOnly() ) {
1954 $user->spreadAnyEditBlock();
1956 # Check block state against master, thus 'false'.
1957 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1961 $this->contentLength
= strlen( $this->textbox1
);
1962 $config = $this->context
->getConfig();
1963 $maxArticleSize = $config->get( 'MaxArticleSize' );
1964 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1965 // Error will be displayed by showEditForm()
1966 $this->tooBig
= true;
1967 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1971 if ( !$user->isAllowed( 'edit' ) ) {
1972 if ( $user->isAnon() ) {
1973 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1976 $status->fatal( 'readonlytext' );
1977 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1982 $changingContentModel = false;
1983 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1984 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1985 $status->fatal( 'editpage-cannot-use-custom-model' );
1986 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1988 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1989 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1992 // Make sure the user can edit the page under the new content model too
1993 $titleWithNewContentModel = clone $this->mTitle
;
1994 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1995 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1996 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1998 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
2002 $changingContentModel = true;
2003 $oldContentModel = $this->mTitle
->getContentModel();
2006 if ( $this->changeTags
) {
2007 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
2008 $this->changeTags
, $user );
2009 if ( !$changeTagsStatus->isOK() ) {
2010 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
2011 return $changeTagsStatus;
2015 if ( wfReadOnly() ) {
2016 $status->fatal( 'readonlytext' );
2017 $status->value
= self
::AS_READ_ONLY_PAGE
;
2020 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
2021 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
2023 $status->fatal( 'actionthrottledtext' );
2024 $status->value
= self
::AS_RATE_LIMITED
;
2028 # If the article has been deleted while editing, don't save it without
2030 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
2031 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
2035 # Load the page data from the master. If anything changes in the meantime,
2036 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
2037 $this->page
->loadPageData( 'fromdbmaster' );
2038 $new = !$this->page
->exists();
2041 // Late check for create permission, just in case *PARANOIA*
2042 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
2043 $status->fatal( 'nocreatetext' );
2044 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
2045 wfDebug( __METHOD__
. ": no create permission\n" );
2049 // Don't save a new page if it's blank or if it's a MediaWiki:
2050 // message with content equivalent to default (allow empty pages
2051 // in this case to disable messages, see T52124)
2052 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2053 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
2054 $defaultText = $defaultMessageText;
2059 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
2060 $this->blankArticle
= true;
2061 $status->fatal( 'blankarticle' );
2062 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
2066 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2070 $content = $textbox_content;
2072 $result['sectionanchor'] = '';
2073 if ( $this->section
== 'new' ) {
2074 if ( $this->sectiontitle
!== '' ) {
2075 // Insert the section title above the content.
2076 $content = $content->addSectionHeader( $this->sectiontitle
);
2077 } elseif ( $this->summary
!== '' ) {
2078 // Insert the section title above the content.
2079 $content = $content->addSectionHeader( $this->summary
);
2081 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2084 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2088 # Article exists. Check for edit conflict.
2090 $this->page
->clear(); # Force reload of dates, etc.
2091 $timestamp = $this->page
->getTimestamp();
2092 $latest = $this->page
->getLatest();
2094 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2096 // An edit conflict is detected if the current revision is different from the
2097 // revision that was current when editing was initiated on the client.
2098 // This is checked based on the timestamp and revision ID.
2099 // TODO: the timestamp based check can probably go away now.
2100 if ( $timestamp != $this->edittime
2101 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2103 $this->isConflict
= true;
2104 if ( $this->section
== 'new' ) {
2105 if ( $this->page
->getUserText() == $user->getName() &&
2106 $this->page
->getComment() == $this->newSectionSummary()
2108 // Probably a duplicate submission of a new comment.
2109 // This can happen when CDN resends a request after
2110 // a timeout but the first one actually went through.
2112 . ": duplicate new section submission; trigger edit conflict!\n" );
2114 // New comment; suppress conflict.
2115 $this->isConflict
= false;
2116 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2118 } elseif ( $this->section
== ''
2119 && Revision
::userWasLastToEdit(
2120 DB_MASTER
, $this->mTitle
->getArticleID(),
2121 $user->getId(), $this->edittime
2124 # Suppress edit conflict with self, except for section edits where merging is required.
2125 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2126 $this->isConflict
= false;
2130 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2131 if ( $this->sectiontitle
!== '' ) {
2132 $sectionTitle = $this->sectiontitle
;
2134 $sectionTitle = $this->summary
;
2139 if ( $this->isConflict
) {
2141 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2142 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2143 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2144 // ...or disable section editing for non-current revisions (not exposed anyway).
2145 if ( $this->editRevId
!== null ) {
2146 $content = $this->page
->replaceSectionAtRev(
2153 $content = $this->page
->replaceSectionContent(
2161 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2162 $content = $this->page
->replaceSectionContent(
2169 if ( is_null( $content ) ) {
2170 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2171 $this->isConflict
= true;
2172 $content = $textbox_content; // do not try to merge here!
2173 } elseif ( $this->isConflict
) {
2175 if ( $this->mergeChangesIntoContent( $content ) ) {
2176 // Successful merge! Maybe we should tell the user the good news?
2177 $this->isConflict
= false;
2178 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2180 $this->section
= '';
2181 $this->textbox1
= ContentHandler
::getContentText( $content );
2182 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2186 if ( $this->isConflict
) {
2187 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2191 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2195 if ( $this->section
== 'new' ) {
2196 // Handle the user preference to force summaries here
2197 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2198 $this->missingSummary
= true;
2199 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2200 $status->value
= self
::AS_SUMMARY_NEEDED
;
2204 // Do not allow the user to post an empty comment
2205 if ( $this->textbox1
== '' ) {
2206 $this->missingComment
= true;
2207 $status->fatal( 'missingcommenttext' );
2208 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2211 } elseif ( !$this->allowBlankSummary
2212 && !$content->equals( $this->getOriginalContent( $user ) )
2213 && !$content->isRedirect()
2214 && md5( $this->summary
) == $this->autoSumm
2216 $this->missingSummary
= true;
2217 $status->fatal( 'missingsummary' );
2218 $status->value
= self
::AS_SUMMARY_NEEDED
;
2223 $sectionanchor = '';
2224 if ( $this->section
== 'new' ) {
2225 $this->summary
= $this->newSectionSummary( $sectionanchor );
2226 } elseif ( $this->section
!= '' ) {
2227 # Try to get a section anchor from the section source, redirect
2228 # to edited section if header found.
2229 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2230 # for duplicate heading checking and maybe parsing.
2231 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2232 # We can't deal with anchors, includes, html etc in the header for now,
2233 # headline would need to be parsed to improve this.
2234 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2235 $sectionanchor = $this->guessSectionName( $matches[2] );
2238 $result['sectionanchor'] = $sectionanchor;
2240 // Save errors may fall down to the edit form, but we've now
2241 // merged the section into full text. Clear the section field
2242 // so that later submission of conflict forms won't try to
2243 // replace that into a duplicated mess.
2244 $this->textbox1
= $this->toEditText( $content );
2245 $this->section
= '';
2247 $status->value
= self
::AS_SUCCESS_UPDATE
;
2250 if ( !$this->allowSelfRedirect
2251 && $content->isRedirect()
2252 && $content->getRedirectTarget()->equals( $this->getTitle() )
2254 // If the page already redirects to itself, don't warn.
2255 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2256 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2257 $this->selfRedirect
= true;
2258 $status->fatal( 'selfredirect' );
2259 $status->value
= self
::AS_SELF_REDIRECT
;
2264 // Check for length errors again now that the section is merged in
2265 $this->contentLength
= strlen( $this->toEditText( $content ) );
2266 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2267 $this->tooBig
= true;
2268 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2272 $flags = EDIT_AUTOSUMMARY |
2273 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2274 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2275 ( $bot ? EDIT_FORCE_BOT
: 0 );
2277 $doEditStatus = $this->page
->doEditContent(
2283 $content->getDefaultFormat(),
2288 if ( !$doEditStatus->isOK() ) {
2289 // Failure from doEdit()
2290 // Show the edit conflict page for certain recognized errors from doEdit(),
2291 // but don't show it for errors from extension hooks
2292 $errors = $doEditStatus->getErrorsArray();
2293 if ( in_array( $errors[0][0],
2294 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2296 $this->isConflict
= true;
2297 // Destroys data doEdit() put in $status->value but who cares
2298 $doEditStatus->value
= self
::AS_END
;
2300 return $doEditStatus;
2303 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2304 if ( $result['nullEdit'] ) {
2305 // We don't know if it was a null edit until now, so increment here
2306 $user->pingLimiter( 'linkpurge' );
2308 $result['redirect'] = $content->isRedirect();
2310 $this->updateWatchlist();
2312 // If the content model changed, add a log entry
2313 if ( $changingContentModel ) {
2314 $this->addContentModelChangeLogEntry(
2316 $new ?
false : $oldContentModel,
2317 $this->contentModel
,
2327 * @param string|false $oldModel false if the page is being newly created
2328 * @param string $newModel
2329 * @param string $reason
2331 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2332 $new = $oldModel === false;
2333 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2334 $log->setPerformer( $user );
2335 $log->setTarget( $this->mTitle
);
2336 $log->setComment( $reason );
2337 $log->setParameters( [
2338 '4::oldmodel' => $oldModel,
2339 '5::newmodel' => $newModel
2341 $logid = $log->insert();
2342 $log->publish( $logid );
2346 * Register the change of watch status
2348 protected function updateWatchlist() {
2349 $user = $this->context
->getUser();
2350 if ( !$user->isLoggedIn() ) {
2354 $title = $this->mTitle
;
2355 $watch = $this->watchthis
;
2356 // Do this in its own transaction to reduce contention...
2357 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2358 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2359 return; // nothing to change
2361 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2366 * Attempts to do 3-way merge of edit content with a base revision
2367 * and current content, in case of edit conflict, in whichever way appropriate
2368 * for the content type.
2372 * @param Content $editContent
2376 private function mergeChangesIntoContent( &$editContent ) {
2377 $db = wfGetDB( DB_MASTER
);
2379 // This is the revision that was current at the time editing was initiated on the client,
2380 // even if the edit was based on an old revision.
2381 $baseRevision = $this->getBaseRevision();
2382 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2384 if ( is_null( $baseContent ) ) {
2388 // The current state, we want to merge updates into it
2389 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2390 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2392 if ( is_null( $currentContent ) ) {
2396 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2398 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2401 $editContent = $result;
2402 // Update parentRevId to what we just merged.
2403 $this->parentRevId
= $currentRevision->getId();
2411 * Returns the revision that was current at the time editing was initiated on the client,
2412 * even if the edit was based on an old revision.
2414 * @warning this method is very poorly named. If the user opened the form with ?oldid=X,
2415 * one might think of X as the "base revision", which is NOT what this returns,
2416 * see oldid for that. One might further assume that this corresponds to the $baseRevId
2417 * parameter of WikiPage::doEditContent, which is not the case either.
2418 * getExpectedParentRevision() would perhaps be a better name.
2420 * @return Revision|null Current version when editing was initiated on the client
2422 public function getBaseRevision() {
2423 if ( !$this->mBaseRevision
) {
2424 $db = wfGetDB( DB_MASTER
);
2425 $this->mBaseRevision
= $this->editRevId
2426 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2427 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2429 return $this->mBaseRevision
;
2433 * Check given input text against $wgSpamRegex, and return the text of the first match.
2435 * @param string $text
2437 * @return string|bool Matching string or false
2439 public static function matchSpamRegex( $text ) {
2440 global $wgSpamRegex;
2441 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2442 $regexes = (array)$wgSpamRegex;
2443 return self
::matchSpamRegexInternal( $text, $regexes );
2447 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2449 * @param string $text
2451 * @return string|bool Matching string or false
2453 public static function matchSummarySpamRegex( $text ) {
2454 global $wgSummarySpamRegex;
2455 $regexes = (array)$wgSummarySpamRegex;
2456 return self
::matchSpamRegexInternal( $text, $regexes );
2460 * @param string $text
2461 * @param array $regexes
2462 * @return bool|string
2464 protected static function matchSpamRegexInternal( $text, $regexes ) {
2465 foreach ( $regexes as $regex ) {
2467 if ( preg_match( $regex, $text, $matches ) ) {
2474 public function setHeaders() {
2475 $out = $this->context
->getOutput();
2477 $out->addModules( 'mediawiki.action.edit' );
2478 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2479 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2481 $user = $this->context
->getUser();
2482 if ( $user->getOption( 'showtoolbar' ) ) {
2483 // The addition of default buttons is handled by getEditToolbar() which
2484 // has its own dependency on this module. The call here ensures the module
2485 // is loaded in time (it has position "top") for other modules to register
2486 // buttons (e.g. extensions, gadgets, user scripts).
2487 $out->addModules( 'mediawiki.toolbar' );
2490 if ( $user->getOption( 'uselivepreview' ) ) {
2491 $out->addModules( 'mediawiki.action.edit.preview' );
2494 if ( $user->getOption( 'useeditwarning' ) ) {
2495 $out->addModules( 'mediawiki.action.edit.editWarning' );
2498 # Enabled article-related sidebar, toplinks, etc.
2499 $out->setArticleRelated( true );
2501 $contextTitle = $this->getContextTitle();
2502 if ( $this->isConflict
) {
2503 $msg = 'editconflict';
2504 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2505 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2507 $msg = $contextTitle->exists()
2508 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2509 && $contextTitle->getDefaultMessageText() !== false
2515 # Use the title defined by DISPLAYTITLE magic word when present
2516 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2517 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2518 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2519 if ( $displayTitle === false ) {
2520 $displayTitle = $contextTitle->getPrefixedText();
2522 $out->setDisplayTitle( $displayTitle );
2524 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2526 $config = $this->context
->getConfig();
2528 # Transmit the name of the message to JavaScript for live preview
2529 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2530 $out->addJsConfigVars( [
2531 'wgEditMessage' => $msg,
2532 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2535 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2537 $out->addJsConfigVars(
2538 'wgEditSubmitButtonLabelPublish',
2539 $config->get( 'EditSubmitButtonLabelPublish' )
2544 * Show all applicable editing introductions
2546 protected function showIntro() {
2547 if ( $this->suppressIntro
) {
2551 $out = $this->context
->getOutput();
2552 $namespace = $this->mTitle
->getNamespace();
2554 if ( $namespace == NS_MEDIAWIKI
) {
2555 # Show a warning if editing an interface message
2556 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2557 # If this is a default message (but not css, json, or js),
2558 # show a hint that it is translatable on translatewiki.net
2560 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2561 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2562 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2564 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2565 if ( $defaultMessageText !== false ) {
2566 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2567 'translateinterface' );
2570 } elseif ( $namespace == NS_FILE
) {
2571 # Show a hint to shared repo
2572 $file = wfFindFile( $this->mTitle
);
2573 if ( $file && !$file->isLocal() ) {
2574 $descUrl = $file->getDescriptionUrl();
2575 # there must be a description url to show a hint to shared repo
2577 if ( !$this->mTitle
->exists() ) {
2578 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2579 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2582 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2583 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2590 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2591 # Show log extract when the user is currently blocked
2592 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2593 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2594 $user = User
::newFromName( $username, false /* allow IP users */ );
2595 $ip = User
::isIP( $username );
2596 $block = Block
::newFromTarget( $user, $user );
2597 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2598 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2599 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2600 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2601 # Show log extract if the user is currently blocked
2602 LogEventsList
::showLogExtract(
2605 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2609 'showIfEmpty' => false,
2611 'blocked-notice-logextract',
2612 $user->getName() # Support GENDER in notice
2618 # Try to add a custom edit intro, or use the standard one if this is not possible.
2619 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2620 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2621 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2623 if ( $this->context
->getUser()->isLoggedIn() ) {
2625 // Suppress the external link icon, consider the help url an internal one
2626 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2634 // Suppress the external link icon, consider the help url an internal one
2635 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2637 'newarticletextanon',
2643 # Give a notice if the user is editing a deleted/moved page...
2644 if ( !$this->mTitle
->exists() ) {
2645 $dbr = wfGetDB( DB_REPLICA
);
2647 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2651 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2652 'showIfEmpty' => false,
2653 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2660 * Attempt to show a custom editing introduction, if supplied
2664 protected function showCustomIntro() {
2665 if ( $this->editintro
) {
2666 $title = Title
::newFromText( $this->editintro
);
2667 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2668 // Added using template syntax, to take <noinclude>'s into account.
2669 $this->context
->getOutput()->addWikiTextTitleTidy(
2670 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2680 * Gets an editable textual representation of $content.
2681 * The textual representation can be turned by into a Content object by the
2682 * toEditContent() method.
2684 * If $content is null or false or a string, $content is returned unchanged.
2686 * If the given Content object is not of a type that can be edited using
2687 * the text base EditPage, an exception will be raised. Set
2688 * $this->allowNonTextContent to true to allow editing of non-textual
2691 * @param Content|null|bool|string $content
2692 * @return string The editable text form of the content.
2694 * @throws MWException If $content is not an instance of TextContent and
2695 * $this->allowNonTextContent is not true.
2697 protected function toEditText( $content ) {
2698 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2702 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2703 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2706 return $content->serialize( $this->contentFormat
);
2710 * Turns the given text into a Content object by unserializing it.
2712 * If the resulting Content object is not of a type that can be edited using
2713 * the text base EditPage, an exception will be raised. Set
2714 * $this->allowNonTextContent to true to allow editing of non-textual
2717 * @param string|null|bool $text Text to unserialize
2718 * @return Content|bool|null The content object created from $text. If $text was false
2719 * or null, false resp. null will be returned instead.
2721 * @throws MWException If unserializing the text results in a Content
2722 * object that is not an instance of TextContent and
2723 * $this->allowNonTextContent is not true.
2725 protected function toEditContent( $text ) {
2726 if ( $text === false ||
$text === null ) {
2730 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2731 $this->contentModel
, $this->contentFormat
);
2733 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2734 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2741 * Send the edit form and related headers to OutputPage
2742 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2743 * during form output near the top, for captchas and the like.
2745 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2746 * use the EditPage::showEditForm:fields hook instead.
2748 public function showEditForm( $formCallback = null ) {
2749 # need to parse the preview early so that we know which templates are used,
2750 # otherwise users with "show preview after edit box" will get a blank list
2751 # we parse this near the beginning so that setHeaders can do the title
2752 # setting work instead of leaving it in getPreviewText
2753 $previewOutput = '';
2754 if ( $this->formtype
== 'preview' ) {
2755 $previewOutput = $this->getPreviewText();
2758 $out = $this->context
->getOutput();
2760 // Avoid PHP 7.1 warning of passing $this by reference
2762 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2764 $this->setHeaders();
2766 $this->addTalkPageText();
2767 $this->addEditNotices();
2769 if ( !$this->isConflict
&&
2770 $this->section
!= '' &&
2771 !$this->isSectionEditSupported() ) {
2772 // We use $this->section to much before this and getVal('wgSection') directly in other places
2773 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2774 // Someone is welcome to try refactoring though
2775 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2779 $this->showHeader();
2781 $out->addHTML( $this->editFormPageTop
);
2783 $user = $this->context
->getUser();
2784 if ( $user->getOption( 'previewontop' ) ) {
2785 $this->displayPreviewArea( $previewOutput, true );
2788 $out->addHTML( $this->editFormTextTop
);
2790 $showToolbar = true;
2791 if ( $this->wasDeletedSinceLastEdit() ) {
2792 if ( $this->formtype
== 'save' ) {
2793 // Hide the toolbar and edit area, user can click preview to get it back
2794 // Add an confirmation checkbox and explanation.
2795 $showToolbar = false;
2797 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2798 'deletedwhileediting' );
2802 // @todo add EditForm plugin interface and use it here!
2803 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2804 $out->addHTML( Html
::openElement(
2807 'class' => 'mw-editform',
2808 'id' => self
::EDITFORM_ID
,
2809 'name' => self
::EDITFORM_ID
,
2811 'action' => $this->getActionURL( $this->getContextTitle() ),
2812 'enctype' => 'multipart/form-data'
2816 if ( is_callable( $formCallback ) ) {
2817 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2818 call_user_func_array( $formCallback, [ &$out ] );
2821 // Add a check for Unicode support
2822 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2824 // Add an empty field to trip up spambots
2826 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2829 [ 'for' => 'wpAntispam' ],
2830 $this->context
->msg( 'simpleantispam-label' )->parse()
2836 'name' => 'wpAntispam',
2837 'id' => 'wpAntispam',
2841 . Xml
::closeElement( 'div' )
2844 // Avoid PHP 7.1 warning of passing $this by reference
2846 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2848 // Put these up at the top to ensure they aren't lost on early form submission
2849 $this->showFormBeforeText();
2851 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2852 $username = $this->lastDelete
->user_name
;
2853 $comment = CommentStore
::getStore()
2854 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2856 // It is better to not parse the comment at all than to have templates expanded in the middle
2857 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2858 $key = $comment === ''
2859 ?
'confirmrecreate-noreason'
2860 : 'confirmrecreate';
2862 '<div class="mw-confirm-recreate">' .
2863 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2864 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2865 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2871 # When the summary is hidden, also hide them on preview/show changes
2872 if ( $this->nosummary
) {
2873 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2876 # If a blank edit summary was previously provided, and the appropriate
2877 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2878 # user being bounced back more than once in the event that a summary
2881 # For a bit more sophisticated detection of blank summaries, hash the
2882 # automatic one and pass that in the hidden field wpAutoSummary.
2883 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2884 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2887 if ( $this->undidRev
) {
2888 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2891 if ( $this->selfRedirect
) {
2892 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2895 if ( $this->hasPresetSummary
) {
2896 // If a summary has been preset using &summary= we don't want to prompt for
2897 // a different summary. Only prompt for a summary if the summary is blanked.
2899 $this->autoSumm
= md5( '' );
2902 $autosumm = $this->autoSumm
!== '' ?
$this->autoSumm
: md5( $this->summary
);
2903 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2905 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2906 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2908 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2909 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2913 if ( $this->section
== 'new' ) {
2914 $this->showSummaryInput( true, $this->summary
);
2915 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2918 $out->addHTML( $this->editFormTextBeforeContent
);
2919 if ( $this->isConflict
) {
2920 // In an edit conflict, we turn textbox2 into the user's text,
2921 // and textbox1 into the stored version
2922 $this->textbox2
= $this->textbox1
;
2924 $content = $this->getCurrentContent();
2925 $this->textbox1
= $this->toEditText( $content );
2927 $editConflictHelper = $this->getEditConflictHelper();
2928 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2929 $editConflictHelper->setContentModel( $this->contentModel
);
2930 $editConflictHelper->setContentFormat( $this->contentFormat
);
2931 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2934 if ( !$this->mTitle
->isUserConfigPage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2935 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2938 if ( $this->blankArticle
) {
2939 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2942 if ( $this->isConflict
) {
2943 // In an edit conflict bypass the overridable content form method
2944 // and fallback to the raw wpTextbox1 since editconflicts can't be
2945 // resolved between page source edits and custom ui edits using the
2947 $conflictTextBoxAttribs = [];
2948 if ( $this->wasDeletedSinceLastEdit() ) {
2949 $conflictTextBoxAttribs['style'] = 'display:none;';
2950 } elseif ( $this->isOldRev
) {
2951 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2954 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2955 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2957 $this->showContentForm();
2960 $out->addHTML( $this->editFormTextAfterContent
);
2962 $this->showStandardInputs();
2964 $this->showFormAfterText();
2966 $this->showTosSummary();
2968 $this->showEditTools();
2970 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2972 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2974 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2975 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2977 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2978 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2980 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2982 if ( $this->isConflict
) {
2984 $this->showConflict();
2985 } catch ( MWContentSerializationException
$ex ) {
2986 // this can't really happen, but be nice if it does.
2987 $msg = $this->context
->msg(
2988 'content-failed-to-parse',
2989 $this->contentModel
,
2990 $this->contentFormat
,
2993 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2997 // Set a hidden field so JS knows what edit form mode we are in
2998 if ( $this->isConflict
) {
3000 } elseif ( $this->preview
) {
3002 } elseif ( $this->diff
) {
3007 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
3009 // Marker for detecting truncated form data. This must be the last
3010 // parameter sent in order to be of use, so do not move me.
3011 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
3012 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
3014 if ( !$user->getOption( 'previewontop' ) ) {
3015 $this->displayPreviewArea( $previewOutput, false );
3020 * Wrapper around TemplatesOnThisPageFormatter to make
3021 * a "templates on this page" list.
3023 * @param Title[] $templates
3024 * @return string HTML
3026 public function makeTemplatesOnThisPageList( array $templates ) {
3027 $templateListFormatter = new TemplatesOnThisPageFormatter(
3028 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
3031 // preview if preview, else section if section, else false
3033 if ( $this->preview
) {
3035 } elseif ( $this->section
!= '' ) {
3039 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
3040 $templateListFormatter->format( $templates, $type )
3045 * Extract the section title from current section text, if any.
3047 * @param string $text
3048 * @return string|bool String or false
3050 public static function extractSectionTitle( $text ) {
3051 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
3052 if ( !empty( $matches[2] ) ) {
3054 return $wgParser->stripSectionName( trim( $matches[2] ) );
3060 protected function showHeader() {
3061 $out = $this->context
->getOutput();
3062 $user = $this->context
->getUser();
3063 if ( $this->isConflict
) {
3064 $this->addExplainConflictHeader( $out );
3065 $this->editRevId
= $this->page
->getLatest();
3067 if ( $this->section
!= '' && $this->section
!= 'new' ) {
3068 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
3069 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
3070 if ( $sectionTitle !== false ) {
3071 $this->summary
= "/* $sectionTitle */ ";
3076 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
3078 if ( $this->missingComment
) {
3079 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3082 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
3084 "<div id='mw-missingsummary'>\n$1\n</div>",
3085 [ 'missingsummary', $buttonLabel ]
3089 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3091 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3092 [ 'missingcommentheader', $buttonLabel ]
3096 if ( $this->blankArticle
) {
3098 "<div id='mw-blankarticle'>\n$1\n</div>",
3099 [ 'blankarticle', $buttonLabel ]
3103 if ( $this->selfRedirect
) {
3105 "<div id='mw-selfredirect'>\n$1\n</div>",
3106 [ 'selfredirect', $buttonLabel ]
3110 if ( $this->hookError
!== '' ) {
3111 $out->addWikiText( $this->hookError
);
3114 if ( $this->section
!= 'new' ) {
3115 $revision = $this->mArticle
->getRevisionFetched();
3117 // Let sysop know that this will make private content public if saved
3119 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3121 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3122 'rev-deleted-text-permission'
3124 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3126 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3127 'rev-deleted-text-view'
3131 if ( !$revision->isCurrent() ) {
3132 $this->mArticle
->setOldSubtitle( $revision->getId() );
3133 $out->addWikiMsg( 'editingold' );
3134 $this->isOldRev
= true;
3136 } elseif ( $this->mTitle
->exists() ) {
3137 // Something went wrong
3139 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3140 [ 'missing-revision', $this->oldid
] );
3145 if ( wfReadOnly() ) {
3147 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3148 [ 'readonlywarning', wfReadOnlyReason() ]
3150 } elseif ( $user->isAnon() ) {
3151 if ( $this->formtype
!= 'preview' ) {
3153 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3154 [ 'anoneditwarning',
3156 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3157 'returnto' => $this->getTitle()->getPrefixedDBkey()
3160 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3161 'returnto' => $this->getTitle()->getPrefixedDBkey()
3166 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3167 'anonpreviewwarning'
3171 if ( $this->mTitle
->isUserConfigPage() ) {
3172 # Check the skin exists
3173 if ( $this->isWrongCaseUserConfigPage() ) {
3175 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3176 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3179 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3180 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3181 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3182 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3184 $warning = $isUserCssConfig
3186 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3188 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3190 if ( $this->formtype
!== 'preview' ) {
3191 $config = $this->context
->getConfig();
3192 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3194 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3195 [ 'usercssyoucanpreview' ]
3197 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3199 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3200 [ 'userjsonyoucanpreview' ]
3202 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3204 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3205 [ 'userjsyoucanpreview' ]
3213 $this->addPageProtectionWarningHeaders();
3215 $this->addLongPageWarningHeader();
3217 # Add header copyright warning
3218 $this->showHeaderCopyrightWarning();
3222 * Helper function for summary input functions, which returns the necessary
3223 * attributes for the input.
3225 * @param array|null $inputAttrs Array of attrs to use on the input
3228 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3229 $conf = $this->context
->getConfig();
3230 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
3231 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3232 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3233 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
3234 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3235 'id' => 'wpSummary',
3236 'name' => 'wpSummary',
3237 'maxlength' => $oldCommentSchema ?
200 : CommentStore
::COMMENT_CHARACTER_LIMIT
,
3240 'spellcheck' => 'true',
3245 * Builds a standard summary input with a label.
3247 * @param string $summary The value of the summary input
3248 * @param string|null $labelText The html to place inside the label
3249 * @param array|null $inputAttrs Array of attrs to use on the input
3251 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3253 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3254 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3255 $this->getSummaryInputAttributes( $inputAttrs )
3258 'title' => Linker
::titleAttrib( 'summary' ),
3259 'accessKey' => Linker
::accesskey( 'summary' ),
3262 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3263 $inputAttrs['inputId'] = $inputAttrs['id'];
3264 $inputAttrs['id'] = 'wpSummaryWidget';
3266 return new OOUI\
FieldLayout(
3267 new OOUI\
TextInputWidget( [
3268 'value' => $summary,
3269 'infusable' => true,
3272 'label' => new OOUI\
HtmlSnippet( $labelText ),
3274 'id' => 'wpSummaryLabel',
3275 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3281 * @param bool $isSubjectPreview True if this is the section subject/title
3282 * up top, or false if this is the comment summary
3283 * down below the textarea
3284 * @param string $summary The text of the summary to display
3286 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3287 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3288 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3289 if ( $isSubjectPreview ) {
3290 if ( $this->nosummary
) {
3294 if ( !$this->mShowSummaryField
) {
3299 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3300 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3303 [ 'class' => $summaryClass ]
3308 * @param bool $isSubjectPreview True if this is the section subject/title
3309 * up top, or false if this is the comment summary
3310 * down below the textarea
3311 * @param string $summary The text of the summary to display
3314 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3315 // avoid spaces in preview, gets always trimmed on save
3316 $summary = trim( $summary );
3317 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3323 if ( $isSubjectPreview ) {
3324 $summary = $this->context
->msg( 'newsectionsummary' )
3325 ->rawParams( $wgParser->stripSectionName( $summary ) )
3326 ->inContentLanguage()->text();
3329 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3331 $summary = $this->context
->msg( $message )->parse()
3332 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3333 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3336 protected function showFormBeforeText() {
3337 $out = $this->context
->getOutput();
3338 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3339 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3340 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3341 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3342 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3345 protected function showFormAfterText() {
3347 * To make it harder for someone to slip a user a page
3348 * which submits an edit form to the wiki without their
3349 * knowledge, a random token is associated with the login
3350 * session. If it's not passed back with the submission,
3351 * we won't save the page, or render user JavaScript and
3354 * For anon editors, who may not have a session, we just
3355 * include the constant suffix to prevent editing from
3356 * broken text-mangling proxies.
3358 $this->context
->getOutput()->addHTML(
3360 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3366 * Subpage overridable method for printing the form for page content editing
3367 * By default this simply outputs wpTextbox1
3368 * Subclasses can override this to provide a custom UI for editing;
3369 * be it a form, or simply wpTextbox1 with a modified content that will be
3370 * reverse modified when extracted from the post data.
3371 * Note that this is basically the inverse for importContentFormData
3373 protected function showContentForm() {
3374 $this->showTextbox1();
3378 * Method to output wpTextbox1
3379 * The $textoverride method can be used by subclasses overriding showContentForm
3380 * to pass back to this method.
3382 * @param array|null $customAttribs Array of html attributes to use in the textarea
3383 * @param string|null $textoverride Optional text to override $this->textarea1 with
3385 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3386 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3387 $attribs = [ 'style' => 'display:none;' ];
3389 $builder = new TextboxBuilder();
3390 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3392 # Is an old revision being edited?
3393 if ( $this->isOldRev
) {
3394 $classes[] = 'mw-textarea-oldrev';
3397 $attribs = [ 'tabindex' => 1 ];
3399 if ( is_array( $customAttribs ) ) {
3400 $attribs +
= $customAttribs;
3403 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3407 $textoverride ??
$this->textbox1
,
3413 protected function showTextbox2() {
3414 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3417 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3418 $builder = new TextboxBuilder();
3419 $attribs = $builder->buildTextboxAttribs(
3422 $this->context
->getUser(),
3426 $this->context
->getOutput()->addHTML(
3427 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3431 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3434 $classes[] = 'ontop';
3437 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3439 if ( $this->formtype
!= 'preview' ) {
3440 $attribs['style'] = 'display: none;';
3443 $out = $this->context
->getOutput();
3444 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3446 if ( $this->formtype
== 'preview' ) {
3447 $this->showPreview( $previewOutput );
3449 // Empty content container for LivePreview
3450 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3451 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3452 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3453 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3456 $out->addHTML( '</div>' );
3458 if ( $this->formtype
== 'diff' ) {
3461 } catch ( MWContentSerializationException
$ex ) {
3462 $msg = $this->context
->msg(
3463 'content-failed-to-parse',
3464 $this->contentModel
,
3465 $this->contentFormat
,
3468 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3474 * Append preview output to OutputPage.
3475 * Includes category rendering if this is a category page.
3477 * @param string $text The HTML to be output for the preview.
3479 protected function showPreview( $text ) {
3480 if ( $this->mArticle
instanceof CategoryPage
) {
3481 $this->mArticle
->openShowCategory();
3483 # This hook seems slightly odd here, but makes things more
3484 # consistent for extensions.
3485 $out = $this->context
->getOutput();
3486 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3487 $out->addHTML( $text );
3488 if ( $this->mArticle
instanceof CategoryPage
) {
3489 $this->mArticle
->closeShowCategory();
3494 * Get a diff between the current contents of the edit box and the
3495 * version of the page we're editing from.
3497 * If this is a section edit, we'll replace the section as for final
3498 * save and then make a comparison.
3500 public function showDiff() {
3501 $oldtitlemsg = 'currentrev';
3502 # if message does not exist, show diff against the preloaded default
3503 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3504 $oldtext = $this->mTitle
->getDefaultMessageText();
3505 if ( $oldtext !== false ) {
3506 $oldtitlemsg = 'defaultmessagetext';
3507 $oldContent = $this->toEditContent( $oldtext );
3512 $oldContent = $this->getCurrentContent();
3515 $textboxContent = $this->toEditContent( $this->textbox1
);
3516 if ( $this->editRevId
!== null ) {
3517 $newContent = $this->page
->replaceSectionAtRev(
3518 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3521 $newContent = $this->page
->replaceSectionContent(
3522 $this->section
, $textboxContent, $this->summary
, $this->edittime
3526 if ( $newContent ) {
3527 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3529 $user = $this->context
->getUser();
3530 $popts = ParserOptions
::newFromUserAndLang( $user,
3531 MediaWikiServices
::getInstance()->getContentLanguage() );
3532 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3535 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3536 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3537 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3539 if ( !$oldContent ) {
3540 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3543 if ( !$newContent ) {
3544 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3547 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3548 $de->setContent( $oldContent, $newContent );
3550 $difftext = $de->getDiff( $oldtitle, $newtitle );
3551 $de->showDiffStyle();
3556 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3560 * Show the header copyright warning.
3562 protected function showHeaderCopyrightWarning() {
3563 $msg = 'editpage-head-copy-warn';
3564 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3565 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3566 'editpage-head-copy-warn' );
3571 * Give a chance for site and per-namespace customizations of
3572 * terms of service summary link that might exist separately
3573 * from the copyright notice.
3575 * This will display between the save button and the edit tools,
3576 * so should remain short!
3578 protected function showTosSummary() {
3579 $msg = 'editpage-tos-summary';
3580 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3581 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3582 $out = $this->context
->getOutput();
3583 $out->addHTML( '<div class="mw-tos-summary">' );
3584 $out->addWikiMsg( $msg );
3585 $out->addHTML( '</div>' );
3590 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3591 * characters not present on most keyboards for copying/pasting.
3593 protected function showEditTools() {
3594 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3595 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3600 * Get the copyright warning
3602 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3605 protected function getCopywarn() {
3606 return self
::getCopyrightWarning( $this->mTitle
);
3610 * Get the copyright warning, by default returns wikitext
3612 * @param Title $title
3613 * @param string $format Output format, valid values are any function of a Message object
3614 * @param Language|string|null $langcode Language code or Language object.
3617 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3618 global $wgRightsText;
3619 if ( $wgRightsText ) {
3620 $copywarnMsg = [ 'copyrightwarning',
3621 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3624 $copywarnMsg = [ 'copyrightwarning2',
3625 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3627 // Allow for site and per-namespace customization of contribution/copyright notice.
3628 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3630 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3632 $msg->inLanguage( $langcode );
3634 return "<div id=\"editpage-copywarn\">\n" .
3635 $msg->$format() . "\n</div>";
3639 * Get the Limit report for page previews
3642 * @param ParserOutput|null $output ParserOutput object from the parse
3643 * @return string HTML
3645 public static function getPreviewLimitReport( ParserOutput
$output = null ) {
3648 if ( !$output ||
!$output->getLimitReportData() ) {
3652 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3653 wfMessage( 'limitreport-title' )->parseAsBlock()
3656 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3657 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3659 $limitReport .= Html
::openElement( 'table', [
3660 'class' => 'preview-limit-report wikitable'
3662 Html
::openElement( 'tbody' );
3664 foreach ( $output->getLimitReportData() as $key => $value ) {
3665 if ( Hooks
::run( 'ParserLimitReportFormat',
3666 [ $key, &$value, &$limitReport, true, true ]
3668 $keyMsg = wfMessage( $key );
3669 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3670 if ( !$valueMsg->exists() ) {
3671 $valueMsg = new RawMessage( '$1' );
3673 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3674 $limitReport .= Html
::openElement( 'tr' ) .
3675 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3676 Html
::rawElement( 'td', null,
3677 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3679 Html
::closeElement( 'tr' );
3684 $limitReport .= Html
::closeElement( 'tbody' ) .
3685 Html
::closeElement( 'table' ) .
3686 Html
::closeElement( 'div' );
3688 return $limitReport;
3691 protected function showStandardInputs( &$tabindex = 2 ) {
3692 $out = $this->context
->getOutput();
3693 $out->addHTML( "<div class='editOptions'>\n" );
3695 if ( $this->section
!= 'new' ) {
3696 $this->showSummaryInput( false, $this->summary
);
3697 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3700 $checkboxes = $this->getCheckboxesWidget(
3702 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3704 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3706 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3708 // Show copyright warning.
3709 $out->addWikiText( $this->getCopywarn() );
3710 $out->addHTML( $this->editFormTextAfterWarn
);
3712 $out->addHTML( "<div class='editButtons'>\n" );
3713 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3715 $cancel = $this->getCancelLink();
3717 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3718 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3721 $this->context
->msg( 'edithelp' )->text(),
3722 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3725 $this->context
->msg( 'word-separator' )->escaped() .
3726 $this->context
->msg( 'newwindow' )->parse();
3728 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3729 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3730 $out->addHTML( "</div><!-- editButtons -->\n" );
3732 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3734 $out->addHTML( "</div><!-- editOptions -->\n" );
3738 * Show an edit conflict. textbox1 is already shown in showEditForm().
3739 * If you want to use another entry point to this function, be careful.
3741 protected function showConflict() {
3742 $out = $this->context
->getOutput();
3743 // Avoid PHP 7.1 warning of passing $this by reference
3745 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3746 $this->incrementConflictStats();
3748 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3752 protected function incrementConflictStats() {
3753 $this->getEditConflictHelper()->incrementConflictStats();
3759 public function getCancelLink() {
3761 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3762 $cancelParams['oldid'] = $this->oldid
;
3763 } elseif ( $this->getContextTitle()->isRedirect() ) {
3764 $cancelParams['redirect'] = 'no';
3767 return new OOUI\
ButtonWidget( [
3768 'id' => 'mw-editform-cancel',
3769 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3770 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3772 'infusable' => true,
3773 'flags' => 'destructive',
3778 * Returns the URL to use in the form's action attribute.
3779 * This is used by EditPage subclasses when simply customizing the action
3780 * variable in the constructor is not enough. This can be used when the
3781 * EditPage lives inside of a Special page rather than a custom page action.
3783 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3786 protected function getActionURL( Title
$title ) {
3787 return $title->getLocalURL( [ 'action' => $this->action
] );
3791 * Check if a page was deleted while the user was editing it, before submit.
3792 * Note that we rely on the logging table, which hasn't been always there,
3793 * but that doesn't matter, because this only applies to brand new
3797 protected function wasDeletedSinceLastEdit() {
3798 if ( $this->deletedSinceEdit
!== null ) {
3799 return $this->deletedSinceEdit
;
3802 $this->deletedSinceEdit
= false;
3804 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3805 $this->lastDelete
= $this->getLastDelete();
3806 if ( $this->lastDelete
) {
3807 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3808 if ( $deleteTime > $this->starttime
) {
3809 $this->deletedSinceEdit
= true;
3814 return $this->deletedSinceEdit
;
3818 * Get the last log record of this page being deleted, if ever. This is
3819 * used to detect whether a delete occurred during editing.
3820 * @return bool|stdClass
3822 protected function getLastDelete() {
3823 $dbr = wfGetDB( DB_REPLICA
);
3824 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3825 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3826 $data = $dbr->selectRow(
3827 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3837 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3839 'log_namespace' => $this->mTitle
->getNamespace(),
3840 'log_title' => $this->mTitle
->getDBkey(),
3841 'log_type' => 'delete',
3842 'log_action' => 'delete',
3845 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3847 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3848 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3850 // Quick paranoid permission checks...
3851 if ( is_object( $data ) ) {
3852 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3853 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3856 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3857 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3858 $data->log_comment_data
= null;
3866 * Get the rendered text for previewing.
3867 * @throws MWException
3870 public function getPreviewText() {
3871 $out = $this->context
->getOutput();
3872 $config = $this->context
->getConfig();
3874 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3875 // Could be an offsite preview attempt. This is very unsafe if
3876 // HTML is enabled, as it could be an attack.
3878 if ( $this->textbox1
!== '' ) {
3879 // Do not put big scary notice, if previewing the empty
3880 // string, which happens when you initially edit
3881 // a category page, due to automatic preview-on-open.
3882 $parsedNote = $out->parse( "<div class='previewnote'>" .
3883 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3884 true, /* interface */true );
3886 $this->incrementEditFailureStats( 'session_loss' );
3893 $content = $this->toEditContent( $this->textbox1
);
3897 'AlternateEditPreview',
3898 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3900 return $previewHTML;
3903 # provide a anchor link to the editform
3904 $continueEditing = '<span class="mw-continue-editing">' .
3905 '[[#' . self
::EDITFORM_ID
. '|' .
3906 $this->context
->getLanguage()->getArrow() . ' ' .
3907 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3908 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3909 if ( $this->mTokenOkExceptSuffix
) {
3910 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3911 $this->incrementEditFailureStats( 'bad_token' );
3913 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3914 $this->incrementEditFailureStats( 'session_loss' );
3916 } elseif ( $this->incompleteForm
) {
3917 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3918 if ( $this->mTriedSave
) {
3919 $this->incrementEditFailureStats( 'incomplete_form' );
3922 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3925 # don't parse non-wikitext pages, show message about preview
3926 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3927 if ( $this->mTitle
->isUserConfigPage() ) {
3929 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3935 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3937 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3940 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3942 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3945 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3947 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3954 # Used messages to make sure grep find them:
3955 # Messages: usercsspreview, userjsonpreview, userjspreview,
3956 # sitecsspreview, sitejsonpreview, sitejspreview
3957 if ( $level && $format ) {
3958 $note = "<div id='mw-{$level}{$format}preview'>" .
3959 $this->context
->msg( "{$level}{$format}preview" )->text() .
3960 ' ' . $continueEditing . "</div>";
3964 # If we're adding a comment, we need to show the
3965 # summary as the headline
3966 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3967 $content = $content->addSectionHeader( $this->summary
);
3970 $hook_args = [ $this, &$content ];
3971 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3973 $parserResult = $this->doPreviewParse( $content );
3974 $parserOutput = $parserResult['parserOutput'];
3975 $previewHTML = $parserResult['html'];
3976 $this->mParserOutput
= $parserOutput;
3977 $out->addParserOutputMetadata( $parserOutput );
3978 if ( $out->userCanPreview() ) {
3979 $out->addContentOverride( $this->getTitle(), $content );
3982 if ( count( $parserOutput->getWarnings() ) ) {
3983 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3986 } catch ( MWContentSerializationException
$ex ) {
3987 $m = $this->context
->msg(
3988 'content-failed-to-parse',
3989 $this->contentModel
,
3990 $this->contentFormat
,
3993 $note .= "\n\n" . $m->parse();
3997 if ( $this->isConflict
) {
3998 $conflict = '<h2 id="mw-previewconflict">'
3999 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
4001 $conflict = '<hr />';
4004 $previewhead = "<div class='previewnote'>\n" .
4005 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
4006 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
4008 $pageViewLang = $this->mTitle
->getPageViewLanguage();
4009 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
4010 'class' => 'mw-content-' . $pageViewLang->getDir() ];
4011 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
4013 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
4016 private function incrementEditFailureStats( $failureType ) {
4017 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
4018 $stats->increment( 'edit.failures.' . $failureType );
4022 * Get parser options for a preview
4023 * @return ParserOptions
4025 protected function getPreviewParserOptions() {
4026 $parserOptions = $this->page
->makeParserOptions( $this->context
);
4027 $parserOptions->setIsPreview( true );
4028 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
4029 $parserOptions->enableLimitReport();
4031 // XXX: we could call $parserOptions->setCurrentRevisionCallback here to force the
4032 // current revision to be null during PST, until setupFakeRevision is called on
4033 // the ParserOptions. Currently, we rely on Parser::getRevisionObject() to ignore
4034 // existing revisions in preview mode.
4036 return $parserOptions;
4040 * Parse the page for a preview. Subclasses may override this class, in order
4041 * to parse with different options, or to otherwise modify the preview HTML.
4043 * @param Content $content The page content
4044 * @return array with keys:
4045 * - parserOutput: The ParserOutput object
4046 * - html: The HTML to be displayed
4048 protected function doPreviewParse( Content
$content ) {
4049 $user = $this->context
->getUser();
4050 $parserOptions = $this->getPreviewParserOptions();
4052 // NOTE: preSaveTransform doesn't have a fake revision to operate on.
4053 // Parser::getRevisionObject() will return null in preview mode,
4054 // causing the context user to be used for {{subst:REVISIONUSER}}.
4055 // XXX: Alternatively, we could also call setupFakeRevision() a second time:
4056 // once before PST with $content, and then after PST with $pstContent.
4057 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
4058 $scopedCallback = $parserOptions->setupFakeRevision( $this->mTitle
, $pstContent, $user );
4059 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
4060 ScopedCallback
::consume( $scopedCallback );
4062 'parserOutput' => $parserOutput,
4063 'html' => $parserOutput->getText( [
4064 'enableSectionEditLinks' => false
4072 public function getTemplates() {
4073 if ( $this->preview ||
$this->section
!= '' ) {
4075 if ( !isset( $this->mParserOutput
) ) {
4078 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
4079 foreach ( array_keys( $template ) as $dbk ) {
4080 $templates[] = Title
::makeTitle( $ns, $dbk );
4085 return $this->mTitle
->getTemplateLinksFrom();
4090 * Shows a bulletin board style toolbar for common editing functions.
4091 * It can be disabled in the user preferences.
4093 * @param Title|null $title Title object for the page being edited (optional)
4096 public static function getEditToolbar( $title = null ) {
4097 global $wgOut, $wgEnableUploads, $wgForeignFileRepos;
4099 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
4100 $showSignature = true;
4102 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4105 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4108 * $toolarray is an array of arrays each of which includes the
4109 * opening tag, the closing tag, optionally a sample text that is
4110 * inserted between the two when no selection is highlighted
4111 * and. The tip text is shown when the user moves the mouse
4114 * Images are defined in ResourceLoaderEditToolbarModule.
4118 'id' => 'mw-editbutton-bold',
4120 'close' => '\'\'\'',
4121 'sample' => wfMessage( 'bold_sample' )->text(),
4122 'tip' => wfMessage( 'bold_tip' )->text(),
4125 'id' => 'mw-editbutton-italic',
4128 'sample' => wfMessage( 'italic_sample' )->text(),
4129 'tip' => wfMessage( 'italic_tip' )->text(),
4132 'id' => 'mw-editbutton-link',
4135 'sample' => wfMessage( 'link_sample' )->text(),
4136 'tip' => wfMessage( 'link_tip' )->text(),
4139 'id' => 'mw-editbutton-extlink',
4142 'sample' => wfMessage( 'extlink_sample' )->text(),
4143 'tip' => wfMessage( 'extlink_tip' )->text(),
4146 'id' => 'mw-editbutton-headline',
4149 'sample' => wfMessage( 'headline_sample' )->text(),
4150 'tip' => wfMessage( 'headline_tip' )->text(),
4152 $imagesAvailable ?
[
4153 'id' => 'mw-editbutton-image',
4154 'open' => '[[' . $contLang->getNsText( NS_FILE
) . ':',
4156 'sample' => wfMessage( 'image_sample' )->text(),
4157 'tip' => wfMessage( 'image_tip' )->text(),
4159 $imagesAvailable ?
[
4160 'id' => 'mw-editbutton-media',
4161 'open' => '[[' . $contLang->getNsText( NS_MEDIA
) . ':',
4163 'sample' => wfMessage( 'media_sample' )->text(),
4164 'tip' => wfMessage( 'media_tip' )->text(),
4167 'id' => 'mw-editbutton-nowiki',
4168 'open' => "<nowiki>",
4169 'close' => "</nowiki>",
4170 'sample' => wfMessage( 'nowiki_sample' )->text(),
4171 'tip' => wfMessage( 'nowiki_tip' )->text(),
4174 'id' => 'mw-editbutton-signature',
4175 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4178 'tip' => wfMessage( 'sig_tip' )->text(),
4181 'id' => 'mw-editbutton-hr',
4182 'open' => "\n----\n",
4185 'tip' => wfMessage( 'hr_tip' )->text(),
4190 foreach ( $toolarray as $tool ) {
4196 // Images are defined in ResourceLoaderEditToolbarModule
4198 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4199 // Older browsers show a "speedtip" type message only for ALT.
4200 // Ideally these should be different, realistically they
4201 // probably don't need to be.
4209 $script .= Xml
::encodeJsCall(
4210 'mw.toolbar.addButton',
4212 ResourceLoader
::inDebugMode()
4216 $toolbar = '<div id="toolbar"></div>';
4218 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4219 // Only add the old toolbar cruft to the page payload if the toolbar has not
4220 // been over-written by a hook caller
4221 $nonce = $wgOut->getCSPNonce();
4222 $wgOut->addScript( Html
::inlineScript(
4223 ResourceLoader
::makeInlineCodeWithModule( 'mediawiki.toolbar', $script ),
4232 * Return an array of checkbox definitions.
4234 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4236 * Array values are associative arrays with the following keys:
4237 * - 'label-message' (required): message for label text
4238 * - 'id' (required): 'id' attribute for the `<input>`
4239 * - 'default' (required): default checkedness (true or false)
4240 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4241 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4242 * from messages like 'tooltip-foo', 'accesskey-foo'
4243 * - 'label-id' (optional): 'id' attribute for the `<label>`
4244 * - 'legacy-name' (optional): short name for backwards-compatibility
4245 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4246 * where bool indicates the checked status of the checkbox
4249 public function getCheckboxesDefinition( $checked ) {
4252 $user = $this->context
->getUser();
4253 // don't show the minor edit checkbox if it's a new page or section
4254 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4255 $checkboxes['wpMinoredit'] = [
4256 'id' => 'wpMinoredit',
4257 'label-message' => 'minoredit',
4258 // Uses messages: tooltip-minoredit, accesskey-minoredit
4259 'tooltip' => 'minoredit',
4260 'label-id' => 'mw-editpage-minoredit',
4261 'legacy-name' => 'minor',
4262 'default' => $checked['minor'],
4266 if ( $user->isLoggedIn() ) {
4267 $checkboxes['wpWatchthis'] = [
4268 'id' => 'wpWatchthis',
4269 'label-message' => 'watchthis',
4270 // Uses messages: tooltip-watch, accesskey-watch
4271 'tooltip' => 'watch',
4272 'label-id' => 'mw-editpage-watch',
4273 'legacy-name' => 'watch',
4274 'default' => $checked['watch'],
4279 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4285 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4286 * any other added by extensions.
4288 * @param int &$tabindex Current tabindex
4289 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4290 * status of the checkbox
4292 * @return array Associative array of string keys to OOUI\FieldLayout instances
4294 public function getCheckboxesWidget( &$tabindex, $checked ) {
4296 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4298 foreach ( $checkboxesDef as $name => $options ) {
4299 $legacyName = $options['legacy-name'] ??
$name;
4303 if ( isset( $options['tooltip'] ) ) {
4304 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4305 $title = Linker
::titleAttrib( $options['tooltip'] );
4307 if ( isset( $options['title-message'] ) ) {
4308 $title = $this->context
->msg( $options['title-message'] )->text();
4311 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4312 new OOUI\
CheckboxInputWidget( [
4313 'tabIndex' => ++
$tabindex,
4314 'accessKey' => $accesskey,
4315 'id' => $options['id'] . 'Widget',
4316 'inputId' => $options['id'],
4318 'selected' => $options['default'],
4319 'infusable' => true,
4322 'align' => 'inline',
4323 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4325 'id' => $options['label-id'] ??
null,
4334 * Get the message key of the label for the button to save the page
4339 protected function getSubmitButtonLabel() {
4341 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4343 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4344 $newPage = !$this->mTitle
->exists();
4346 if ( $labelAsPublish ) {
4347 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4349 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4352 return $buttonLabelKey;
4356 * Returns an array of html code of the following buttons:
4357 * save, diff and preview
4359 * @param int &$tabindex Current tabindex
4363 public function getEditButtons( &$tabindex ) {
4367 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4369 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4370 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4372 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4374 'tabIndex' => ++
$tabindex,
4375 'id' => 'wpSaveWidget',
4376 'inputId' => 'wpSave',
4377 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4378 'useInputTag' => true,
4379 'flags' => [ 'progressive', 'primary' ],
4380 'label' => $buttonLabel,
4381 'infusable' => true,
4383 // Messages used: tooltip-save, tooltip-publish
4384 'title' => Linker
::titleAttrib( $buttonTooltip ),
4385 // Messages used: accesskey-save, accesskey-publish
4386 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4389 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4390 'name' => 'wpPreview',
4391 'tabIndex' => ++
$tabindex,
4392 'id' => 'wpPreviewWidget',
4393 'inputId' => 'wpPreview',
4394 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4395 'useInputTag' => true,
4396 'label' => $this->context
->msg( 'showpreview' )->text(),
4397 'infusable' => true,
4399 // Message used: tooltip-preview
4400 'title' => Linker
::titleAttrib( 'preview' ),
4401 // Message used: accesskey-preview
4402 'accessKey' => Linker
::accesskey( 'preview' ),
4405 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4407 'tabIndex' => ++
$tabindex,
4408 'id' => 'wpDiffWidget',
4409 'inputId' => 'wpDiff',
4410 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4411 'useInputTag' => true,
4412 'label' => $this->context
->msg( 'showdiff' )->text(),
4413 'infusable' => true,
4415 // Message used: tooltip-diff
4416 'title' => Linker
::titleAttrib( 'diff' ),
4417 // Message used: accesskey-diff
4418 'accessKey' => Linker
::accesskey( 'diff' ),
4421 // Avoid PHP 7.1 warning of passing $this by reference
4423 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4429 * Creates a basic error page which informs the user that
4430 * they have attempted to edit a nonexistent section.
4432 public function noSuchSectionPage() {
4433 $out = $this->context
->getOutput();
4434 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4436 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4438 // Avoid PHP 7.1 warning of passing $this by reference
4440 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4441 $out->addHTML( $res );
4443 $out->returnToMain( false, $this->mTitle
);
4447 * Show "your edit contains spam" page with your diff and text
4449 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4451 public function spamPageWithContent( $match = false ) {
4452 $this->textbox2
= $this->textbox1
;
4454 if ( is_array( $match ) ) {
4455 $match = $this->context
->getLanguage()->listToText( $match );
4457 $out = $this->context
->getOutput();
4458 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4460 $out->addHTML( '<div id="spamprotected">' );
4461 $out->addWikiMsg( 'spamprotectiontext' );
4463 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4465 $out->addHTML( '</div>' );
4467 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4470 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4471 $this->showTextbox2();
4473 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4477 * Filter an input field through a Unicode de-armoring process if it
4478 * came from an old browser with known broken Unicode editing issues.
4480 * @deprecated since 1.30, does nothing
4482 * @param WebRequest $request
4483 * @param string $field
4486 protected function safeUnicodeInput( $request, $field ) {
4487 return rtrim( $request->getText( $field ) );
4491 * Filter an output field through a Unicode armoring process if it is
4492 * going to an old browser with known broken Unicode editing issues.
4494 * @deprecated since 1.30, does nothing
4496 * @param string $text
4499 protected function safeUnicodeOutput( $text ) {
4506 protected function addEditNotices() {
4507 $out = $this->context
->getOutput();
4508 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4509 if ( count( $editNotices ) ) {
4510 $out->addHTML( implode( "\n", $editNotices ) );
4512 $msg = $this->context
->msg( 'editnotice-notext' );
4513 if ( !$msg->isDisabled() ) {
4515 '<div class="mw-editnotice-notext">'
4516 . $msg->parseAsBlock()
4526 protected function addTalkPageText() {
4527 if ( $this->mTitle
->isTalkPage() ) {
4528 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4535 protected function addLongPageWarningHeader() {
4536 if ( $this->contentLength
=== false ) {
4537 $this->contentLength
= strlen( $this->textbox1
);
4540 $out = $this->context
->getOutput();
4541 $lang = $this->context
->getLanguage();
4542 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4543 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4544 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4547 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4548 $lang->formatNum( $maxArticleSize )
4552 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4553 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4556 $lang->formatSize( strlen( $this->textbox1
) ),
4557 strlen( $this->textbox1
)
4567 protected function addPageProtectionWarningHeaders() {
4568 $out = $this->context
->getOutput();
4569 if ( $this->mTitle
->isProtected( 'edit' ) &&
4570 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4572 # Is the title semi-protected?
4573 if ( $this->mTitle
->isSemiProtected() ) {
4574 $noticeMsg = 'semiprotectedpagewarning';
4576 # Then it must be protected based on static groups (regular)
4577 $noticeMsg = 'protectedpagewarning';
4579 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4580 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4582 if ( $this->mTitle
->isCascadeProtected() ) {
4583 # Is this page under cascading protection from some source pages?
4584 /** @var Title[] $cascadeSources */
4585 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4586 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4587 $cascadeSourcesCount = count( $cascadeSources );
4588 if ( $cascadeSourcesCount > 0 ) {
4589 # Explain, and list the titles responsible
4590 foreach ( $cascadeSources as $page ) {
4591 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4594 $notice .= '</div>';
4595 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4597 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4598 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4600 'showIfEmpty' => false,
4601 'msgKey' => [ 'titleprotectedwarning' ],
4602 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4607 * @param OutputPage $out
4610 protected function addExplainConflictHeader( OutputPage
$out ) {
4612 $this->getEditConflictHelper()->getExplainHeader()
4617 * @param string $name
4618 * @param mixed[] $customAttribs
4623 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4624 return ( new TextboxBuilder() )->buildTextboxAttribs(
4625 $name, $customAttribs, $user, $this->mTitle
4630 * @param string $wikitext
4634 protected function addNewLineAtEnd( $wikitext ) {
4635 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4639 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4640 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4641 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4642 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4643 * spread the new style links more efficiently.
4645 * @param string $text
4648 private function guessSectionName( $text ) {
4651 // Detect Microsoft browsers
4652 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4653 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4654 // ...and redirect them to legacy encoding, if available
4655 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4657 // Meanwhile, real browsers get real anchors
4658 return $wgParser->guessSectionNameFromWikiText( $text );
4662 * Set a factory function to create an EditConflictHelper
4664 * @param callable $factory Factory function
4667 public function setEditConflictHelperFactory( callable
$factory ) {
4668 $this->editConflictHelperFactory
= $factory;
4669 $this->editConflictHelper
= null;
4673 * @return TextConflictHelper
4675 private function getEditConflictHelper() {
4676 if ( !$this->editConflictHelper
) {
4677 $this->editConflictHelper
= call_user_func(
4678 $this->editConflictHelperFactory
,
4679 $this->getSubmitButtonLabel()
4683 return $this->editConflictHelper
;
4687 * @param string $submitButtonLabel
4688 * @return TextConflictHelper
4690 private function newTextConflictHelper( $submitButtonLabel ) {
4691 return new TextConflictHelper(
4693 $this->getContext()->getOutput(),
4694 MediaWikiServices
::getInstance()->getStatsdDataFactory(),