3 * User interface for page editing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\ScopedCallback
;
28 * The edit page/HTML interface (split from Article)
29 * The actual database and text munging is still in Article,
30 * but it should get easier to call those from alternate
33 * EditPage cares about two distinct titles:
34 * $this->mContextTitle is the page that forms submit to, links point to,
35 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
36 * page in the database that is actually being edited. These are
37 * usually the same, but they are now allowed to be different.
39 * Surgeon General's Warning: prolonged exposure to this class is known to cause
40 * headaches, which may be fatal.
44 * Status: Article successfully updated
46 const AS_SUCCESS_UPDATE
= 200;
49 * Status: Article successfully created
51 const AS_SUCCESS_NEW_ARTICLE
= 201;
54 * Status: Article update aborted by a hook function
56 const AS_HOOK_ERROR
= 210;
59 * Status: A hook function returned an error
61 const AS_HOOK_ERROR_EXPECTED
= 212;
64 * Status: User is blocked from editing this page
66 const AS_BLOCKED_PAGE_FOR_USER
= 215;
69 * Status: Content too big (> $wgMaxArticleSize)
71 const AS_CONTENT_TOO_BIG
= 216;
74 * Status: this anonymous user is not allowed to edit this page
76 const AS_READ_ONLY_PAGE_ANON
= 218;
79 * Status: this logged in user is not allowed to edit this page
81 const AS_READ_ONLY_PAGE_LOGGED
= 219;
84 * Status: wiki is in readonly mode (wfReadOnly() == true)
86 const AS_READ_ONLY_PAGE
= 220;
89 * Status: rate limiter for action 'edit' was tripped
91 const AS_RATE_LIMITED
= 221;
94 * Status: article was deleted while editing and param wpRecreate == false or form
97 const AS_ARTICLE_WAS_DELETED
= 222;
100 * Status: user tried to create this page, but is not allowed to do that
101 * ( Title->userCan('create') == false )
103 const AS_NO_CREATE_PERMISSION
= 223;
106 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
108 const AS_BLANK_ARTICLE
= 224;
111 * Status: (non-resolvable) edit conflict
113 const AS_CONFLICT_DETECTED
= 225;
116 * Status: no edit summary given and the user has forceeditsummary set and the user is not
117 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
119 const AS_SUMMARY_NEEDED
= 226;
122 * Status: user tried to create a new section without content
124 const AS_TEXTBOX_EMPTY
= 228;
127 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
129 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
132 * Status: WikiPage::doEdit() was unsuccessful
137 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
139 const AS_SPAM_ERROR
= 232;
142 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
144 const AS_IMAGE_REDIRECT_ANON
= 233;
147 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
149 const AS_IMAGE_REDIRECT_LOGGED
= 234;
152 * Status: user tried to modify the content model, but is not allowed to do that
153 * ( User::isAllowed('editcontentmodel') == false )
155 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
158 * Status: user tried to create self-redirect (redirect to the same article) and
159 * wpIgnoreSelfRedirect == false
161 const AS_SELF_REDIRECT
= 236;
164 * Status: an error relating to change tagging. Look at the message key for
167 const AS_CHANGE_TAG_ERROR
= 237;
170 * Status: can't parse content
172 const AS_PARSE_ERROR
= 240;
175 * Status: when changing the content model is disallowed due to
176 * $wgContentHandlerUseDB being false
178 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
181 * HTML id and name for the beginning of the edit form.
183 const EDITFORM_ID
= 'editform';
186 * Prefix of key for cookie used to pass post-edit state.
187 * The revision id edited is added after this
189 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
192 * Duration of PostEdit cookie, in seconds.
193 * The cookie will be removed instantly if the JavaScript runs.
195 * Otherwise, though, we don't want the cookies to accumulate.
196 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
197 * limit of only 20 cookies per domain. This still applies at least to some
198 * versions of IE without full updates:
199 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
201 * A value of 20 minutes should be enough to take into account slow loads and minor
202 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
204 const POST_EDIT_COOKIE_DURATION
= 1200;
214 /** @var null|Title */
215 private $mContextTitle = null;
218 public $action = 'submit';
221 public $isConflict = false;
224 public $isCssJsSubpage = false;
227 public $isCssSubpage = false;
230 public $isJsSubpage = false;
233 public $isWrongCaseCssJsPage = false;
235 /** @var bool New page or new section */
236 public $isNew = false;
239 public $deletedSinceEdit;
247 /** @var bool|stdClass */
251 public $mTokenOk = false;
254 public $mTokenOkExceptSuffix = false;
257 public $mTriedSave = false;
260 public $incompleteForm = false;
263 public $tooBig = false;
266 public $missingComment = false;
269 public $missingSummary = false;
272 public $allowBlankSummary = false;
275 protected $blankArticle = false;
278 protected $allowBlankArticle = false;
281 protected $selfRedirect = false;
284 protected $allowSelfRedirect = false;
287 public $autoSumm = '';
290 public $hookError = '';
292 /** @var ParserOutput */
293 public $mParserOutput;
295 /** @var bool Has a summary been preset using GET parameter &summary= ? */
296 public $hasPresetSummary = false;
298 /** @var Revision|bool */
299 public $mBaseRevision = false;
302 public $mShowSummaryField = true;
307 public $save = false;
310 public $preview = false;
313 public $diff = false;
316 public $minoredit = false;
319 public $watchthis = false;
322 public $recreate = false;
325 public $textbox1 = '';
328 public $textbox2 = '';
331 public $summary = '';
334 public $nosummary = false;
337 public $edittime = '';
340 private $editRevId = null;
343 public $section = '';
346 public $sectiontitle = '';
349 public $starttime = '';
355 public $parentRevId = 0;
358 public $editintro = '';
361 public $scrolltop = null;
367 public $contentModel;
369 /** @var null|string */
370 public $contentFormat = null;
372 /** @var null|array */
373 private $changeTags = null;
375 # Placeholders for text injection by hooks (must be HTML)
376 # extensions should take care to _append_ to the present value
378 /** @var string Before even the preview */
379 public $editFormPageTop = '';
380 public $editFormTextTop = '';
381 public $editFormTextBeforeContent = '';
382 public $editFormTextAfterWarn = '';
383 public $editFormTextAfterTools = '';
384 public $editFormTextBottom = '';
385 public $editFormTextAfterContent = '';
386 public $previewTextAfterContent = '';
387 public $mPreloadContent = null;
389 /* $didSave should be set to true whenever an article was successfully altered. */
390 public $didSave = false;
391 public $undidRev = 0;
393 public $suppressIntro = false;
399 protected $contentLength = false;
402 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
404 private $enableApiEditOverride = false;
407 * @var IContextSource
412 * @var bool Whether an old revision is edited
414 private $isOldRev = false;
417 * @param Article $article
419 public function __construct( Article
$article ) {
420 $this->mArticle
= $article;
421 $this->page
= $article->getPage(); // model object
422 $this->mTitle
= $article->getTitle();
423 $this->context
= $article->getContext();
425 $this->contentModel
= $this->mTitle
->getContentModel();
427 $handler = ContentHandler
::getForModelID( $this->contentModel
);
428 $this->contentFormat
= $handler->getDefaultFormat();
434 public function getArticle() {
435 return $this->mArticle
;
440 * @return IContextSource
442 public function getContext() {
443 return $this->context
;
450 public function getTitle() {
451 return $this->mTitle
;
455 * Set the context Title object
457 * @param Title|null $title Title object or null
459 public function setContextTitle( $title ) {
460 $this->mContextTitle
= $title;
464 * Get the context title object.
465 * If not set, $wgTitle will be returned. This behavior might change in
466 * the future to return $this->mTitle instead.
470 public function getContextTitle() {
471 if ( is_null( $this->mContextTitle
) ) {
475 return $this->mContextTitle
;
480 * Check if the edit page is using OOUI controls
481 * @return bool Always true
482 * @deprecated since 1.30
484 public function isOouiEnabled() {
489 * Returns if the given content model is editable.
491 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
493 * @throws MWException If $modelId has no known handler
495 public function isSupportedContentModel( $modelId ) {
496 return $this->enableApiEditOverride
=== true ||
497 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
501 * Allow editing of content that supports API direct editing, but not general
502 * direct editing. Set to false by default.
504 * @param bool $enableOverride
506 public function setApiEditOverride( $enableOverride ) {
507 $this->enableApiEditOverride
= $enableOverride;
511 * @deprecated since 1.29, call edit directly
513 public function submit() {
518 * This is the function that gets called for "action=edit". It
519 * sets up various member variables, then passes execution to
520 * another function, usually showEditForm()
522 * The edit form is self-submitting, so that when things like
523 * preview and edit conflicts occur, we get the same form back
524 * with the extra stuff added. Only when the final submission
525 * is made and all is well do we actually save and redirect to
526 * the newly-edited page.
528 public function edit() {
529 global $wgRequest, $wgUser;
530 // Allow extensions to modify/prevent this form or submission
531 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
535 wfDebug( __METHOD__
. ": enter\n" );
537 // If they used redlink=1 and the page exists, redirect to the main article
538 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
539 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
543 $this->importFormData( $wgRequest );
544 $this->firsttime
= false;
546 if ( wfReadOnly() && $this->save
) {
549 $this->preview
= true;
553 $this->formtype
= 'save';
554 } elseif ( $this->preview
) {
555 $this->formtype
= 'preview';
556 } elseif ( $this->diff
) {
557 $this->formtype
= 'diff';
558 } else { # First time through
559 $this->firsttime
= true;
560 if ( $this->previewOnOpen() ) {
561 $this->formtype
= 'preview';
563 $this->formtype
= 'initial';
567 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
569 wfDebug( __METHOD__
. ": User can't edit\n" );
570 // Auto-block user's IP if the account was "hard" blocked
571 if ( !wfReadOnly() ) {
573 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
574 $user->spreadAnyEditBlock();
577 $this->displayPermissionsError( $permErrors );
582 $revision = $this->mArticle
->getRevisionFetched();
583 // Disallow editing revisions with content models different from the current one
584 // Undo edits being an exception in order to allow reverting content model changes.
586 && $revision->getContentModel() !== $this->contentModel
589 if ( $this->undidRev
) {
590 $undidRevObj = Revision
::newFromId( $this->undidRev
);
591 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
593 if ( !$this->undidRev
595 ||
$prevRev->getContentModel() !== $this->contentModel
597 $this->displayViewSourcePage(
598 $this->getContentObject(),
600 'contentmodelediterror',
601 $revision->getContentModel(),
609 $this->isConflict
= false;
610 // css / js subpages of user pages get a special treatment
611 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
612 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
613 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
614 // @todo FIXME: Silly assignment.
615 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
617 # Show applicable editing introductions
618 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
622 # Attempt submission here. This will check for edit conflicts,
623 # and redundantly check for locked database, blocked IPs, etc.
624 # that edit() already checked just in case someone tries to sneak
625 # in the back door with a hand-edited submission URL.
627 if ( 'save' == $this->formtype
) {
628 $resultDetails = null;
629 $status = $this->attemptSave( $resultDetails );
630 if ( !$this->handleStatus( $status, $resultDetails ) ) {
635 # First time through: get contents, set time for conflict
637 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
638 if ( $this->initialiseForm() === false ) {
639 $this->noSuchSectionPage();
643 if ( !$this->mTitle
->getArticleID() ) {
644 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
646 Hooks
::run( 'EditFormInitialText', [ $this ] );
651 $this->showEditForm();
655 * @param string $rigor Same format as Title::getUserPermissionErrors()
658 protected function getEditPermissionErrors( $rigor = 'secure' ) {
661 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
662 # Can this title be created?
663 if ( !$this->mTitle
->exists() ) {
664 $permErrors = array_merge(
667 $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
672 # Ignore some permissions errors when a user is just previewing/viewing diffs
674 foreach ( $permErrors as $error ) {
675 if ( ( $this->preview ||
$this->diff
)
677 $error[0] == 'blockedtext' ||
678 $error[0] == 'autoblockedtext' ||
679 $error[0] == 'systemblockedtext'
685 $permErrors = wfArrayDiff2( $permErrors, $remove );
691 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
692 * but with the following differences:
693 * - If redlink=1, the user will be redirected to the page
694 * - If there is content to display or the error occurs while either saving,
695 * previewing or showing the difference, it will be a
696 * "View source for ..." page displaying the source code after the error message.
699 * @param array $permErrors Array of permissions errors, as returned by
700 * Title::getUserPermissionsErrors().
701 * @throws PermissionsError
703 protected function displayPermissionsError( array $permErrors ) {
706 $out = $this->context
->getOutput();
707 if ( $wgRequest->getBool( 'redlink' ) ) {
708 // The edit page was reached via a red link.
709 // Redirect to the article page and let them click the edit tab if
710 // they really want a permission error.
711 $out->redirect( $this->mTitle
->getFullURL() );
715 $content = $this->getContentObject();
717 # Use the normal message if there's nothing to display
718 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
719 $action = $this->mTitle
->exists() ?
'edit' :
720 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
721 throw new PermissionsError( $action, $permErrors );
724 $this->displayViewSourcePage(
726 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
731 * Display a read-only View Source page
732 * @param Content $content content object
733 * @param string $errorMessage additional wikitext error message to display
735 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
736 $out = $this->context
->getOutput();
737 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
739 $out->setRobotPolicy( 'noindex,nofollow' );
740 $out->setPageTitle( $this->context
->msg(
742 $this->getContextTitle()->getPrefixedText()
744 $out->addBacklinkSubtitle( $this->getContextTitle() );
745 $out->addHTML( $this->editFormPageTop
);
746 $out->addHTML( $this->editFormTextTop
);
748 if ( $errorMessage !== '' ) {
749 $out->addWikiText( $errorMessage );
750 $out->addHTML( "<hr />\n" );
753 # If the user made changes, preserve them when showing the markup
754 # (This happens when a user is blocked during edit, for instance)
755 if ( !$this->firsttime
) {
756 $text = $this->textbox1
;
757 $out->addWikiMsg( 'viewyourtext' );
760 $text = $this->toEditText( $content );
761 } catch ( MWException
$e ) {
762 # Serialize using the default format if the content model is not supported
763 # (e.g. for an old revision with a different model)
764 $text = $content->serialize();
766 $out->addWikiMsg( 'viewsourcetext' );
769 $out->addHTML( $this->editFormTextBeforeContent
);
770 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
771 $out->addHTML( $this->editFormTextAfterContent
);
773 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
775 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
777 $out->addHTML( $this->editFormTextBottom
);
778 if ( $this->mTitle
->exists() ) {
779 $out->returnToMain( null, $this->mTitle
);
784 * Should we show a preview when the edit form is first shown?
788 protected function previewOnOpen() {
789 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
790 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
791 // Explicit override from request
793 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
794 // Explicit override from request
796 } elseif ( $this->section
== 'new' ) {
797 // Nothing *to* preview for new sections
799 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
800 && $wgUser->getOption( 'previewonfirst' )
802 // Standard preference behavior
804 } elseif ( !$this->mTitle
->exists()
805 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
806 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
808 // Categories are special
816 * Checks whether the user entered a skin name in uppercase,
817 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
821 protected function isWrongCaseCssJsPage() {
822 if ( $this->mTitle
->isCssJsSubpage() ) {
823 $name = $this->mTitle
->getSkinFromCssJsSubpage();
824 $skins = array_merge(
825 array_keys( Skin
::getSkinNames() ),
828 return !in_array( $name, $skins )
829 && in_array( strtolower( $name ), $skins );
836 * Returns whether section editing is supported for the current page.
837 * Subclasses may override this to replace the default behavior, which is
838 * to check ContentHandler::supportsSections.
840 * @return bool True if this edit page supports sections, false otherwise.
842 protected function isSectionEditSupported() {
843 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
844 return $contentHandler->supportsSections();
848 * This function collects the form data and uses it to populate various member variables.
849 * @param WebRequest &$request
850 * @throws ErrorPageError
852 public function importFormData( &$request ) {
853 global $wgContLang, $wgUser;
855 # Section edit can come from either the form or a link
856 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
858 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
859 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
862 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
864 if ( $request->wasPosted() ) {
865 # These fields need to be checked for encoding.
866 # Also remove trailing whitespace, but don't remove _initial_
867 # whitespace from the text boxes. This may be significant formatting.
868 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
869 if ( !$request->getCheck( 'wpTextbox2' ) ) {
870 // Skip this if wpTextbox2 has input, it indicates that we came
871 // from a conflict page with raw page text, not a custom form
872 // modified by subclasses
873 $textbox1 = $this->importContentFormData( $request );
874 if ( $textbox1 !== null ) {
875 $this->textbox1
= $textbox1;
879 # Truncate for whole multibyte characters
880 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
882 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
883 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
885 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
887 # Treat sectiontitle the same way as summary.
888 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
889 # currently doing double duty as both edit summary and section title. Right now this
890 # is just to allow API edits to work around this limitation, but this should be
891 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
892 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
893 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
895 $this->edittime
= $request->getVal( 'wpEdittime' );
896 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
897 $this->starttime
= $request->getVal( 'wpStarttime' );
899 $undidRev = $request->getInt( 'wpUndidRevision' );
901 $this->undidRev
= $undidRev;
904 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
906 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
907 // wpTextbox1 field is missing, possibly due to being "too big"
908 // according to some filter rules such as Suhosin's setting for
909 // suhosin.request.max_value_length (d'oh)
910 $this->incompleteForm
= true;
912 // If we receive the last parameter of the request, we can fairly
913 // claim the POST request has not been truncated.
915 // TODO: softened the check for cutover. Once we determine
916 // that it is safe, we should complete the transition by
917 // removing the "edittime" clause.
918 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
919 && is_null( $this->edittime
) );
921 if ( $this->incompleteForm
) {
922 # If the form is incomplete, force to preview.
923 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
924 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
925 $this->preview
= true;
927 $this->preview
= $request->getCheck( 'wpPreview' );
928 $this->diff
= $request->getCheck( 'wpDiff' );
930 // Remember whether a save was requested, so we can indicate
931 // if we forced preview due to session failure.
932 $this->mTriedSave
= !$this->preview
;
934 if ( $this->tokenOk( $request ) ) {
935 # Some browsers will not report any submit button
936 # if the user hits enter in the comment box.
937 # The unmarked state will be assumed to be a save,
938 # if the form seems otherwise complete.
939 wfDebug( __METHOD__
. ": Passed token check.\n" );
940 } elseif ( $this->diff
) {
941 # Failed token check, but only requested "Show Changes".
942 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
944 # Page might be a hack attempt posted from
945 # an external site. Preview instead of saving.
946 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
947 $this->preview
= true;
950 $this->save
= !$this->preview
&& !$this->diff
;
951 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
952 $this->edittime
= null;
955 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
956 $this->starttime
= null;
959 $this->recreate
= $request->getCheck( 'wpRecreate' );
961 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
962 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
964 # Don't force edit summaries when a user is editing their own user or talk page
965 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
966 && $this->mTitle
->getText() == $wgUser->getName()
968 $this->allowBlankSummary
= true;
970 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
971 ||
!$wgUser->getOption( 'forceeditsummary' );
974 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
976 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
977 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
979 $changeTags = $request->getVal( 'wpChangeTags' );
980 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
981 $this->changeTags
= [];
983 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
987 # Not a posted form? Start with nothing.
988 wfDebug( __METHOD__
. ": Not a posted form.\n" );
989 $this->textbox1
= '';
991 $this->sectiontitle
= '';
992 $this->edittime
= '';
993 $this->editRevId
= null;
994 $this->starttime
= wfTimestampNow();
996 $this->preview
= false;
999 $this->minoredit
= false;
1000 // Watch may be overridden by request parameters
1001 $this->watchthis
= $request->getBool( 'watchthis', false );
1002 $this->recreate
= false;
1004 // When creating a new section, we can preload a section title by passing it as the
1005 // preloadtitle parameter in the URL (T15100)
1006 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1007 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1008 // Once wpSummary isn't being use for setting section titles, we should delete this.
1009 $this->summary
= $request->getVal( 'preloadtitle' );
1010 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1011 $this->summary
= $request->getText( 'summary' );
1012 if ( $this->summary
!== '' ) {
1013 $this->hasPresetSummary
= true;
1017 if ( $request->getVal( 'minor' ) ) {
1018 $this->minoredit
= true;
1022 $this->oldid
= $request->getInt( 'oldid' );
1023 $this->parentRevId
= $request->getInt( 'parentRevId' );
1025 $this->bot
= $request->getBool( 'bot', true );
1026 $this->nosummary
= $request->getBool( 'nosummary' );
1028 // May be overridden by revision.
1029 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1030 // May be overridden by revision.
1031 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1034 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1035 } catch ( MWUnknownContentModelException
$e ) {
1036 throw new ErrorPageError(
1037 'editpage-invalidcontentmodel-title',
1038 'editpage-invalidcontentmodel-text',
1039 [ wfEscapeWikiText( $this->contentModel
) ]
1043 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1044 throw new ErrorPageError(
1045 'editpage-notsupportedcontentformat-title',
1046 'editpage-notsupportedcontentformat-text',
1048 wfEscapeWikiText( $this->contentFormat
),
1049 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1055 * @todo Check if the desired model is allowed in this namespace, and if
1056 * a transition from the page's current model to the new model is
1060 $this->editintro
= $request->getText( 'editintro',
1061 // Custom edit intro for new sections
1062 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1064 // Allow extensions to modify form data
1065 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1069 * Subpage overridable method for extracting the page content data from the
1070 * posted form to be placed in $this->textbox1, if using customized input
1071 * this method should be overridden and return the page text that will be used
1072 * for saving, preview parsing and so on...
1074 * @param WebRequest &$request
1075 * @return string|null
1077 protected function importContentFormData( &$request ) {
1078 return; // Don't do anything, EditPage already extracted wpTextbox1
1082 * Initialise form fields in the object
1083 * Called on the first invocation, e.g. when a user clicks an edit link
1084 * @return bool If the requested section is valid
1086 public function initialiseForm() {
1088 $this->edittime
= $this->page
->getTimestamp();
1089 $this->editRevId
= $this->page
->getLatest();
1091 $content = $this->getContentObject( false ); # TODO: track content object?!
1092 if ( $content === false ) {
1095 $this->textbox1
= $this->toEditText( $content );
1097 // activate checkboxes if user wants them to be always active
1098 # Sort out the "watch" checkbox
1099 if ( $wgUser->getOption( 'watchdefault' ) ) {
1101 $this->watchthis
= true;
1102 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1104 $this->watchthis
= true;
1105 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
1107 $this->watchthis
= true;
1109 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
1110 $this->minoredit
= true;
1112 if ( $this->textbox1
=== false ) {
1119 * @param Content|null $def_content The default value to return
1121 * @return Content|null Content on success, $def_content for invalid sections
1125 protected function getContentObject( $def_content = null ) {
1126 global $wgRequest, $wgUser, $wgContLang;
1130 // For message page not locally set, use the i18n message.
1131 // For other non-existent articles, use preload text if any.
1132 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1133 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1134 # If this is a system message, get the default text.
1135 $msg = $this->mTitle
->getDefaultMessageText();
1137 $content = $this->toEditContent( $msg );
1139 if ( $content === false ) {
1140 # If requested, preload some text.
1141 $preload = $wgRequest->getVal( 'preload',
1142 // Custom preload text for new sections
1143 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1144 $params = $wgRequest->getArray( 'preloadparams', [] );
1146 $content = $this->getPreloadedContent( $preload, $params );
1148 // For existing pages, get text based on "undo" or section parameters.
1150 if ( $this->section
!= '' ) {
1151 // Get section edit text (returns $def_text for invalid sections)
1152 $orig = $this->getOriginalContent( $wgUser );
1153 $content = $orig ?
$orig->getSection( $this->section
) : null;
1156 $content = $def_content;
1159 $undoafter = $wgRequest->getInt( 'undoafter' );
1160 $undo = $wgRequest->getInt( 'undo' );
1162 if ( $undo > 0 && $undoafter > 0 ) {
1163 $undorev = Revision
::newFromId( $undo );
1164 $oldrev = Revision
::newFromId( $undoafter );
1166 # Sanity check, make sure it's the right page,
1167 # the revisions exist and they were not deleted.
1168 # Otherwise, $content will be left as-is.
1169 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1170 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1171 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1173 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1175 if ( $content === false ) {
1176 # Warn the user that something went wrong
1177 $undoMsg = 'failure';
1179 $oldContent = $this->page
->getContent( Revision
::RAW
);
1180 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
1181 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
1182 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1183 // The undo may change content
1184 // model if its reverting the top
1185 // edit. This can result in
1186 // mismatched content model/format.
1187 $this->contentModel
= $newContent->getModel();
1188 $this->contentFormat
= $oldrev->getContentFormat();
1191 if ( $newContent->equals( $oldContent ) ) {
1192 # Tell the user that the undo results in no change,
1193 # i.e. the revisions were already undone.
1194 $undoMsg = 'nochange';
1197 # Inform the user of our success and set an automatic edit summary
1198 $undoMsg = 'success';
1200 # If we just undid one rev, use an autosummary
1201 $firstrev = $oldrev->getNext();
1202 if ( $firstrev && $firstrev->getId() == $undo ) {
1203 $userText = $undorev->getUserText();
1204 if ( $userText === '' ) {
1205 $undoSummary = $this->context
->msg(
1206 'undo-summary-username-hidden',
1208 )->inContentLanguage()->text();
1210 $undoSummary = $this->context
->msg(
1214 )->inContentLanguage()->text();
1216 if ( $this->summary
=== '' ) {
1217 $this->summary
= $undoSummary;
1219 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1220 ->inContentLanguage()->text() . $this->summary
;
1222 $this->undidRev
= $undo;
1224 $this->formtype
= 'diff';
1228 // Failed basic sanity checks.
1229 // Older revisions may have been removed since the link
1230 // was created, or we may simply have got bogus input.
1234 $out = $this->context
->getOutput();
1235 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1236 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1237 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1238 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1241 if ( $content === false ) {
1242 $content = $this->getOriginalContent( $wgUser );
1251 * Get the content of the wanted revision, without section extraction.
1253 * The result of this function can be used to compare user's input with
1254 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1255 * to the original text of the edit.
1257 * This differs from Article::getContent() that when a missing revision is
1258 * encountered the result will be null and not the
1259 * 'missing-revision' message.
1262 * @param User $user The user to get the revision for
1263 * @return Content|null
1265 private function getOriginalContent( User
$user ) {
1266 if ( $this->section
== 'new' ) {
1267 return $this->getCurrentContent();
1269 $revision = $this->mArticle
->getRevisionFetched();
1270 if ( $revision === null ) {
1271 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1272 return $handler->makeEmptyContent();
1274 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1279 * Get the edit's parent revision ID
1281 * The "parent" revision is the ancestor that should be recorded in this
1282 * page's revision history. It is either the revision ID of the in-memory
1283 * article content, or in the case of a 3-way merge in order to rebase
1284 * across a recoverable edit conflict, the ID of the newer revision to
1285 * which we have rebased this page.
1288 * @return int Revision ID
1290 public function getParentRevId() {
1291 if ( $this->parentRevId
) {
1292 return $this->parentRevId
;
1294 return $this->mArticle
->getRevIdFetched();
1299 * Get the current content of the page. This is basically similar to
1300 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1301 * content object is returned instead of null.
1306 protected function getCurrentContent() {
1307 $rev = $this->page
->getRevision();
1308 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1310 if ( $content === false ||
$content === null ) {
1311 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1312 return $handler->makeEmptyContent();
1313 } elseif ( !$this->undidRev
) {
1314 // Content models should always be the same since we error
1315 // out if they are different before this point (in ->edit()).
1316 // The exception being, during an undo, the current revision might
1317 // differ from the prior revision.
1318 $logger = LoggerFactory
::getInstance( 'editpage' );
1319 if ( $this->contentModel
!== $rev->getContentModel() ) {
1320 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1321 'prev' => $this->contentModel
,
1322 'new' => $rev->getContentModel(),
1323 'title' => $this->getTitle()->getPrefixedDBkey(),
1324 'method' => __METHOD__
1326 $this->contentModel
= $rev->getContentModel();
1329 // Given that the content models should match, the current selected
1330 // format should be supported.
1331 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1332 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1334 'prev' => $this->contentFormat
,
1335 'new' => $rev->getContentFormat(),
1336 'title' => $this->getTitle()->getPrefixedDBkey(),
1337 'method' => __METHOD__
1339 $this->contentFormat
= $rev->getContentFormat();
1346 * Use this method before edit() to preload some content into the edit box
1348 * @param Content $content
1352 public function setPreloadedContent( Content
$content ) {
1353 $this->mPreloadContent
= $content;
1357 * Get the contents to be preloaded into the box, either set by
1358 * an earlier setPreloadText() or by loading the given page.
1360 * @param string $preload Representing the title to preload from.
1361 * @param array $params Parameters to use (interface-message style) in the preloaded text
1367 protected function getPreloadedContent( $preload, $params = [] ) {
1370 if ( !empty( $this->mPreloadContent
) ) {
1371 return $this->mPreloadContent
;
1374 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1376 if ( $preload === '' ) {
1377 return $handler->makeEmptyContent();
1380 $title = Title
::newFromText( $preload );
1381 # Check for existence to avoid getting MediaWiki:Noarticletext
1382 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1383 // TODO: somehow show a warning to the user!
1384 return $handler->makeEmptyContent();
1387 $page = WikiPage
::factory( $title );
1388 if ( $page->isRedirect() ) {
1389 $title = $page->getRedirectTarget();
1391 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1392 // TODO: somehow show a warning to the user!
1393 return $handler->makeEmptyContent();
1395 $page = WikiPage
::factory( $title );
1398 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1399 $content = $page->getContent( Revision
::RAW
);
1402 // TODO: somehow show a warning to the user!
1403 return $handler->makeEmptyContent();
1406 if ( $content->getModel() !== $handler->getModelID() ) {
1407 $converted = $content->convert( $handler->getModelID() );
1409 if ( !$converted ) {
1410 // TODO: somehow show a warning to the user!
1411 wfDebug( "Attempt to preload incompatible content: " .
1412 "can't convert " . $content->getModel() .
1413 " to " . $handler->getModelID() );
1415 return $handler->makeEmptyContent();
1418 $content = $converted;
1421 return $content->preloadTransform( $title, $parserOptions, $params );
1425 * Make sure the form isn't faking a user's credentials.
1427 * @param WebRequest &$request
1431 public function tokenOk( &$request ) {
1433 $token = $request->getVal( 'wpEditToken' );
1434 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1435 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1436 return $this->mTokenOk
;
1440 * Sets post-edit cookie indicating the user just saved a particular revision.
1442 * This uses a temporary cookie for each revision ID so separate saves will never
1443 * interfere with each other.
1445 * Article::view deletes the cookie on server-side after the redirect and
1446 * converts the value to the global JavaScript variable wgPostEdit.
1448 * If the variable were set on the server, it would be cached, which is unwanted
1449 * since the post-edit state should only apply to the load right after the save.
1451 * @param int $statusValue The status value (to check for new article status)
1453 protected function setPostEditCookie( $statusValue ) {
1454 $revisionId = $this->page
->getLatest();
1455 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1458 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1460 } elseif ( $this->oldid
) {
1464 $response = $this->context
->getRequest()->response();
1465 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1469 * Attempt submission
1470 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1471 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1472 * @return Status The resulting status object.
1474 public function attemptSave( &$resultDetails = false ) {
1477 # Allow bots to exempt some edits from bot flagging
1478 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1479 $status = $this->internalAttemptSave( $resultDetails, $bot );
1481 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1487 * Log when a page was successfully saved after the edit conflict view
1489 private function incrementResolvedConflicts() {
1492 if ( $wgRequest->getText( 'mode' ) !== 'conflict' ) {
1496 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1497 $stats->increment( 'edit.failures.conflict.resolved' );
1501 * Handle status, such as after attempt save
1503 * @param Status $status
1504 * @param array|bool $resultDetails
1506 * @throws ErrorPageError
1507 * @return bool False, if output is done, true if rest of the form should be displayed
1509 private function handleStatus( Status
$status, $resultDetails ) {
1513 * @todo FIXME: once the interface for internalAttemptSave() is made
1514 * nicer, this should use the message in $status
1516 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1517 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1519 $this->incrementResolvedConflicts();
1521 $this->didSave
= true;
1522 if ( !$resultDetails['nullEdit'] ) {
1523 $this->setPostEditCookie( $status->value
);
1527 $out = $this->context
->getOutput();
1529 // "wpExtraQueryRedirect" is a hidden input to modify
1530 // after save URL and is not used by actual edit form
1531 $request = $this->context
->getRequest();
1532 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1534 switch ( $status->value
) {
1535 case self
::AS_HOOK_ERROR_EXPECTED
:
1536 case self
::AS_CONTENT_TOO_BIG
:
1537 case self
::AS_ARTICLE_WAS_DELETED
:
1538 case self
::AS_CONFLICT_DETECTED
:
1539 case self
::AS_SUMMARY_NEEDED
:
1540 case self
::AS_TEXTBOX_EMPTY
:
1541 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1543 case self
::AS_BLANK_ARTICLE
:
1544 case self
::AS_SELF_REDIRECT
:
1547 case self
::AS_HOOK_ERROR
:
1550 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1551 case self
::AS_PARSE_ERROR
:
1552 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1555 case self
::AS_SUCCESS_NEW_ARTICLE
:
1556 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1557 if ( $extraQueryRedirect ) {
1558 if ( $query === '' ) {
1559 $query = $extraQueryRedirect;
1561 $query = $query . '&' . $extraQueryRedirect;
1564 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1565 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1568 case self
::AS_SUCCESS_UPDATE
:
1570 $sectionanchor = $resultDetails['sectionanchor'];
1572 // Give extensions a chance to modify URL query on update
1574 'ArticleUpdateBeforeRedirect',
1575 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1578 if ( $resultDetails['redirect'] ) {
1579 if ( $extraQuery == '' ) {
1580 $extraQuery = 'redirect=no';
1582 $extraQuery = 'redirect=no&' . $extraQuery;
1585 if ( $extraQueryRedirect ) {
1586 if ( $extraQuery === '' ) {
1587 $extraQuery = $extraQueryRedirect;
1589 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1593 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1596 case self
::AS_SPAM_ERROR
:
1597 $this->spamPageWithContent( $resultDetails['spam'] );
1600 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1601 throw new UserBlockedError( $wgUser->getBlock() );
1603 case self
::AS_IMAGE_REDIRECT_ANON
:
1604 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1605 throw new PermissionsError( 'upload' );
1607 case self
::AS_READ_ONLY_PAGE_ANON
:
1608 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1609 throw new PermissionsError( 'edit' );
1611 case self
::AS_READ_ONLY_PAGE
:
1612 throw new ReadOnlyError
;
1614 case self
::AS_RATE_LIMITED
:
1615 throw new ThrottledError();
1617 case self
::AS_NO_CREATE_PERMISSION
:
1618 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1619 throw new PermissionsError( $permission );
1621 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1622 throw new PermissionsError( 'editcontentmodel' );
1625 // We don't recognize $status->value. The only way that can happen
1626 // is if an extension hook aborted from inside ArticleSave.
1627 // Render the status object into $this->hookError
1628 // FIXME this sucks, we should just use the Status object throughout
1629 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1636 * Run hooks that can filter edits just before they get saved.
1638 * @param Content $content The Content to filter.
1639 * @param Status $status For reporting the outcome to the caller
1640 * @param User $user The user performing the edit
1644 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1645 // Run old style post-section-merge edit filter
1646 if ( $this->hookError
!= '' ) {
1647 # ...or the hook could be expecting us to produce an error
1648 $status->fatal( 'hookaborted' );
1649 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1653 // Run new style post-section-merge edit filter
1654 if ( !Hooks
::run( 'EditFilterMergedContent',
1655 [ $this->mArticle
->getContext(), $content, $status, $this->summary
,
1656 $user, $this->minoredit
] )
1658 # Error messages etc. could be handled within the hook...
1659 if ( $status->isGood() ) {
1660 $status->fatal( 'hookaborted' );
1661 // Not setting $this->hookError here is a hack to allow the hook
1662 // to cause a return to the edit page without $this->hookError
1663 // being set. This is used by ConfirmEdit to display a captcha
1664 // without any error message cruft.
1666 $this->hookError
= $status->getWikiText();
1668 // Use the existing $status->value if the hook set it
1669 if ( !$status->value
) {
1670 $status->value
= self
::AS_HOOK_ERROR
;
1673 } elseif ( !$status->isOK() ) {
1674 # ...or the hook could be expecting us to produce an error
1675 // FIXME this sucks, we should just use the Status object throughout
1676 $this->hookError
= $status->getWikiText();
1677 $status->fatal( 'hookaborted' );
1678 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1686 * Return the summary to be used for a new section.
1688 * @param string $sectionanchor Set to the section anchor text
1691 private function newSectionSummary( &$sectionanchor = null ) {
1694 if ( $this->sectiontitle
!== '' ) {
1695 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1696 // If no edit summary was specified, create one automatically from the section
1697 // title and have it link to the new section. Otherwise, respect the summary as
1699 if ( $this->summary
=== '' ) {
1700 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1701 return $this->context
->msg( 'newsectionsummary' )
1702 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1704 } elseif ( $this->summary
!== '' ) {
1705 $sectionanchor = $this->guessSectionName( $this->summary
);
1706 # This is a new section, so create a link to the new section
1707 # in the revision summary.
1708 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1709 return $this->context
->msg( 'newsectionsummary' )
1710 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1712 return $this->summary
;
1716 * Attempt submission (no UI)
1718 * @param array &$result Array to add statuses to, currently with the
1720 * - spam (string): Spam string from content if any spam is detected by
1722 * - sectionanchor (string): Section anchor for a section save.
1723 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1725 * - redirect (bool): Set if doEditContent is OK. True if resulting
1726 * revision is a redirect.
1727 * @param bool $bot True if edit is being made under the bot right.
1729 * @return Status Status object, possibly with a message, but always with
1730 * one of the AS_* constants in $status->value,
1732 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1733 * various error display idiosyncrasies. There are also lots of cases
1734 * where error metadata is set in the object and retrieved later instead
1735 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1736 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1739 public function internalAttemptSave( &$result, $bot = false ) {
1740 global $wgUser, $wgRequest, $wgMaxArticleSize;
1741 global $wgContentHandlerUseDB;
1743 $status = Status
::newGood();
1745 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1746 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1747 $status->fatal( 'hookaborted' );
1748 $status->value
= self
::AS_HOOK_ERROR
;
1752 $spam = $wgRequest->getText( 'wpAntispam' );
1753 if ( $spam !== '' ) {
1756 $wgUser->getName() .
1758 $this->mTitle
->getPrefixedText() .
1759 '" submitted bogus field "' .
1763 $status->fatal( 'spamprotectionmatch', false );
1764 $status->value
= self
::AS_SPAM_ERROR
;
1769 # Construct Content object
1770 $textbox_content = $this->toEditContent( $this->textbox1
);
1771 } catch ( MWContentSerializationException
$ex ) {
1773 'content-failed-to-parse',
1774 $this->contentModel
,
1775 $this->contentFormat
,
1778 $status->value
= self
::AS_PARSE_ERROR
;
1782 # Check image redirect
1783 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1784 $textbox_content->isRedirect() &&
1785 !$wgUser->isAllowed( 'upload' )
1787 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1788 $status->setResult( false, $code );
1794 $match = self
::matchSummarySpamRegex( $this->summary
);
1795 if ( $match === false && $this->section
== 'new' ) {
1796 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1797 # regular summaries, it is added to the actual wikitext.
1798 if ( $this->sectiontitle
!== '' ) {
1799 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1800 $match = self
::matchSpamRegex( $this->sectiontitle
);
1802 # This branch is taken when the "Add Topic" user interface is used, or the API
1803 # is used with the 'summary' parameter.
1804 $match = self
::matchSpamRegex( $this->summary
);
1807 if ( $match === false ) {
1808 $match = self
::matchSpamRegex( $this->textbox1
);
1810 if ( $match !== false ) {
1811 $result['spam'] = $match;
1812 $ip = $wgRequest->getIP();
1813 $pdbk = $this->mTitle
->getPrefixedDBkey();
1814 $match = str_replace( "\n", '', $match );
1815 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1816 $status->fatal( 'spamprotectionmatch', $match );
1817 $status->value
= self
::AS_SPAM_ERROR
;
1822 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1824 # Error messages etc. could be handled within the hook...
1825 $status->fatal( 'hookaborted' );
1826 $status->value
= self
::AS_HOOK_ERROR
;
1828 } elseif ( $this->hookError
!= '' ) {
1829 # ...or the hook could be expecting us to produce an error
1830 $status->fatal( 'hookaborted' );
1831 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1835 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1836 // Auto-block user's IP if the account was "hard" blocked
1837 if ( !wfReadOnly() ) {
1838 $wgUser->spreadAnyEditBlock();
1840 # Check block state against master, thus 'false'.
1841 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1845 $this->contentLength
= strlen( $this->textbox1
);
1846 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
1847 // Error will be displayed by showEditForm()
1848 $this->tooBig
= true;
1849 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1853 if ( !$wgUser->isAllowed( 'edit' ) ) {
1854 if ( $wgUser->isAnon() ) {
1855 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1858 $status->fatal( 'readonlytext' );
1859 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1864 $changingContentModel = false;
1865 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1866 if ( !$wgContentHandlerUseDB ) {
1867 $status->fatal( 'editpage-cannot-use-custom-model' );
1868 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1870 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1871 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1874 // Make sure the user can edit the page under the new content model too
1875 $titleWithNewContentModel = clone $this->mTitle
;
1876 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1877 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $wgUser )
1878 ||
!$titleWithNewContentModel->userCan( 'edit', $wgUser )
1880 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1884 $changingContentModel = true;
1885 $oldContentModel = $this->mTitle
->getContentModel();
1888 if ( $this->changeTags
) {
1889 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1890 $this->changeTags
, $wgUser );
1891 if ( !$changeTagsStatus->isOK() ) {
1892 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1893 return $changeTagsStatus;
1897 if ( wfReadOnly() ) {
1898 $status->fatal( 'readonlytext' );
1899 $status->value
= self
::AS_READ_ONLY_PAGE
;
1902 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 )
1903 ||
( $changingContentModel && $wgUser->pingLimiter( 'editcontentmodel' ) )
1905 $status->fatal( 'actionthrottledtext' );
1906 $status->value
= self
::AS_RATE_LIMITED
;
1910 # If the article has been deleted while editing, don't save it without
1912 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1913 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1917 # Load the page data from the master. If anything changes in the meantime,
1918 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1919 $this->page
->loadPageData( 'fromdbmaster' );
1920 $new = !$this->page
->exists();
1923 // Late check for create permission, just in case *PARANOIA*
1924 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1925 $status->fatal( 'nocreatetext' );
1926 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1927 wfDebug( __METHOD__
. ": no create permission\n" );
1931 // Don't save a new page if it's blank or if it's a MediaWiki:
1932 // message with content equivalent to default (allow empty pages
1933 // in this case to disable messages, see T52124)
1934 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1935 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1936 $defaultText = $defaultMessageText;
1941 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1942 $this->blankArticle
= true;
1943 $status->fatal( 'blankarticle' );
1944 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1948 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1952 $content = $textbox_content;
1954 $result['sectionanchor'] = '';
1955 if ( $this->section
== 'new' ) {
1956 if ( $this->sectiontitle
!== '' ) {
1957 // Insert the section title above the content.
1958 $content = $content->addSectionHeader( $this->sectiontitle
);
1959 } elseif ( $this->summary
!== '' ) {
1960 // Insert the section title above the content.
1961 $content = $content->addSectionHeader( $this->summary
);
1963 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1966 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1970 # Article exists. Check for edit conflict.
1972 $this->page
->clear(); # Force reload of dates, etc.
1973 $timestamp = $this->page
->getTimestamp();
1974 $latest = $this->page
->getLatest();
1976 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1978 // Check editRevId if set, which handles same-second timestamp collisions
1979 if ( $timestamp != $this->edittime
1980 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
1982 $this->isConflict
= true;
1983 if ( $this->section
== 'new' ) {
1984 if ( $this->page
->getUserText() == $wgUser->getName() &&
1985 $this->page
->getComment() == $this->newSectionSummary()
1987 // Probably a duplicate submission of a new comment.
1988 // This can happen when CDN resends a request after
1989 // a timeout but the first one actually went through.
1991 . ": duplicate new section submission; trigger edit conflict!\n" );
1993 // New comment; suppress conflict.
1994 $this->isConflict
= false;
1995 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1997 } elseif ( $this->section
== ''
1998 && Revision
::userWasLastToEdit(
1999 DB_MASTER
, $this->mTitle
->getArticleID(),
2000 $wgUser->getId(), $this->edittime
2003 # Suppress edit conflict with self, except for section edits where merging is required.
2004 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2005 $this->isConflict
= false;
2009 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2010 if ( $this->sectiontitle
!== '' ) {
2011 $sectionTitle = $this->sectiontitle
;
2013 $sectionTitle = $this->summary
;
2018 if ( $this->isConflict
) {
2020 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2021 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2022 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2023 // ...or disable section editing for non-current revisions (not exposed anyway).
2024 if ( $this->editRevId
!== null ) {
2025 $content = $this->page
->replaceSectionAtRev(
2032 $content = $this->page
->replaceSectionContent(
2040 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2041 $content = $this->page
->replaceSectionContent(
2048 if ( is_null( $content ) ) {
2049 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2050 $this->isConflict
= true;
2051 $content = $textbox_content; // do not try to merge here!
2052 } elseif ( $this->isConflict
) {
2054 if ( $this->mergeChangesIntoContent( $content ) ) {
2055 // Successful merge! Maybe we should tell the user the good news?
2056 $this->isConflict
= false;
2057 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2059 $this->section
= '';
2060 $this->textbox1
= ContentHandler
::getContentText( $content );
2061 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2065 if ( $this->isConflict
) {
2066 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2070 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
2074 if ( $this->section
== 'new' ) {
2075 // Handle the user preference to force summaries here
2076 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2077 $this->missingSummary
= true;
2078 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2079 $status->value
= self
::AS_SUMMARY_NEEDED
;
2083 // Do not allow the user to post an empty comment
2084 if ( $this->textbox1
== '' ) {
2085 $this->missingComment
= true;
2086 $status->fatal( 'missingcommenttext' );
2087 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2090 } elseif ( !$this->allowBlankSummary
2091 && !$content->equals( $this->getOriginalContent( $wgUser ) )
2092 && !$content->isRedirect()
2093 && md5( $this->summary
) == $this->autoSumm
2095 $this->missingSummary
= true;
2096 $status->fatal( 'missingsummary' );
2097 $status->value
= self
::AS_SUMMARY_NEEDED
;
2102 $sectionanchor = '';
2103 if ( $this->section
== 'new' ) {
2104 $this->summary
= $this->newSectionSummary( $sectionanchor );
2105 } elseif ( $this->section
!= '' ) {
2106 # Try to get a section anchor from the section source, redirect
2107 # to edited section if header found.
2108 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2109 # for duplicate heading checking and maybe parsing.
2110 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2111 # We can't deal with anchors, includes, html etc in the header for now,
2112 # headline would need to be parsed to improve this.
2113 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2114 $sectionanchor = $this->guessSectionName( $matches[2] );
2117 $result['sectionanchor'] = $sectionanchor;
2119 // Save errors may fall down to the edit form, but we've now
2120 // merged the section into full text. Clear the section field
2121 // so that later submission of conflict forms won't try to
2122 // replace that into a duplicated mess.
2123 $this->textbox1
= $this->toEditText( $content );
2124 $this->section
= '';
2126 $status->value
= self
::AS_SUCCESS_UPDATE
;
2129 if ( !$this->allowSelfRedirect
2130 && $content->isRedirect()
2131 && $content->getRedirectTarget()->equals( $this->getTitle() )
2133 // If the page already redirects to itself, don't warn.
2134 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2135 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2136 $this->selfRedirect
= true;
2137 $status->fatal( 'selfredirect' );
2138 $status->value
= self
::AS_SELF_REDIRECT
;
2143 // Check for length errors again now that the section is merged in
2144 $this->contentLength
= strlen( $this->toEditText( $content ) );
2145 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
2146 $this->tooBig
= true;
2147 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2151 $flags = EDIT_AUTOSUMMARY |
2152 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2153 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2154 ( $bot ? EDIT_FORCE_BOT
: 0 );
2156 $doEditStatus = $this->page
->doEditContent(
2162 $content->getDefaultFormat(),
2167 if ( !$doEditStatus->isOK() ) {
2168 // Failure from doEdit()
2169 // Show the edit conflict page for certain recognized errors from doEdit(),
2170 // but don't show it for errors from extension hooks
2171 $errors = $doEditStatus->getErrorsArray();
2172 if ( in_array( $errors[0][0],
2173 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2175 $this->isConflict
= true;
2176 // Destroys data doEdit() put in $status->value but who cares
2177 $doEditStatus->value
= self
::AS_END
;
2179 return $doEditStatus;
2182 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2183 if ( $result['nullEdit'] ) {
2184 // We don't know if it was a null edit until now, so increment here
2185 $wgUser->pingLimiter( 'linkpurge' );
2187 $result['redirect'] = $content->isRedirect();
2189 $this->updateWatchlist();
2191 // If the content model changed, add a log entry
2192 if ( $changingContentModel ) {
2193 $this->addContentModelChangeLogEntry(
2195 $new ?
false : $oldContentModel,
2196 $this->contentModel
,
2206 * @param string|false $oldModel false if the page is being newly created
2207 * @param string $newModel
2208 * @param string $reason
2210 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2211 $new = $oldModel === false;
2212 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2213 $log->setPerformer( $user );
2214 $log->setTarget( $this->mTitle
);
2215 $log->setComment( $reason );
2216 $log->setParameters( [
2217 '4::oldmodel' => $oldModel,
2218 '5::newmodel' => $newModel
2220 $logid = $log->insert();
2221 $log->publish( $logid );
2225 * Register the change of watch status
2227 protected function updateWatchlist() {
2230 if ( !$wgUser->isLoggedIn() ) {
2235 $title = $this->mTitle
;
2236 $watch = $this->watchthis
;
2237 // Do this in its own transaction to reduce contention...
2238 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2239 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2240 return; // nothing to change
2242 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2247 * Attempts to do 3-way merge of edit content with a base revision
2248 * and current content, in case of edit conflict, in whichever way appropriate
2249 * for the content type.
2253 * @param Content $editContent
2257 private function mergeChangesIntoContent( &$editContent ) {
2258 $db = wfGetDB( DB_MASTER
);
2260 // This is the revision the editor started from
2261 $baseRevision = $this->getBaseRevision();
2262 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2264 if ( is_null( $baseContent ) ) {
2268 // The current state, we want to merge updates into it
2269 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2270 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2272 if ( is_null( $currentContent ) ) {
2276 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2278 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2281 $editContent = $result;
2282 // Update parentRevId to what we just merged.
2283 $this->parentRevId
= $currentRevision->getId();
2291 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2292 * one might think of X as the "base revision", which is NOT what this returns.
2293 * @return Revision Current version when the edit was started
2295 public function getBaseRevision() {
2296 if ( !$this->mBaseRevision
) {
2297 $db = wfGetDB( DB_MASTER
);
2298 $this->mBaseRevision
= $this->editRevId
2299 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2300 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2302 return $this->mBaseRevision
;
2306 * Check given input text against $wgSpamRegex, and return the text of the first match.
2308 * @param string $text
2310 * @return string|bool Matching string or false
2312 public static function matchSpamRegex( $text ) {
2313 global $wgSpamRegex;
2314 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2315 $regexes = (array)$wgSpamRegex;
2316 return self
::matchSpamRegexInternal( $text, $regexes );
2320 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2322 * @param string $text
2324 * @return string|bool Matching string or false
2326 public static function matchSummarySpamRegex( $text ) {
2327 global $wgSummarySpamRegex;
2328 $regexes = (array)$wgSummarySpamRegex;
2329 return self
::matchSpamRegexInternal( $text, $regexes );
2333 * @param string $text
2334 * @param array $regexes
2335 * @return bool|string
2337 protected static function matchSpamRegexInternal( $text, $regexes ) {
2338 foreach ( $regexes as $regex ) {
2340 if ( preg_match( $regex, $text, $matches ) ) {
2347 public function setHeaders() {
2348 global $wgUser, $wgAjaxEditStash;
2350 $out = $this->context
->getOutput();
2352 $out->addModules( 'mediawiki.action.edit' );
2353 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2355 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2356 // The addition of default buttons is handled by getEditToolbar() which
2357 // has its own dependency on this module. The call here ensures the module
2358 // is loaded in time (it has position "top") for other modules to register
2359 // buttons (e.g. extensions, gadgets, user scripts).
2360 $out->addModules( 'mediawiki.toolbar' );
2363 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2364 $out->addModules( 'mediawiki.action.edit.preview' );
2367 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2368 $out->addModules( 'mediawiki.action.edit.editWarning' );
2371 # Enabled article-related sidebar, toplinks, etc.
2372 $out->setArticleRelated( true );
2374 $contextTitle = $this->getContextTitle();
2375 if ( $this->isConflict
) {
2376 $msg = 'editconflict';
2377 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2378 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2380 $msg = $contextTitle->exists()
2381 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2382 && $contextTitle->getDefaultMessageText() !== false
2388 # Use the title defined by DISPLAYTITLE magic word when present
2389 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2390 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2391 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2392 if ( $displayTitle === false ) {
2393 $displayTitle = $contextTitle->getPrefixedText();
2395 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2396 # Transmit the name of the message to JavaScript for live preview
2397 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2398 $out->addJsConfigVars( [
2399 'wgEditMessage' => $msg,
2400 'wgAjaxEditStash' => $wgAjaxEditStash,
2405 * Show all applicable editing introductions
2407 protected function showIntro() {
2409 if ( $this->suppressIntro
) {
2413 $out = $this->context
->getOutput();
2414 $namespace = $this->mTitle
->getNamespace();
2416 if ( $namespace == NS_MEDIAWIKI
) {
2417 # Show a warning if editing an interface message
2418 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2419 # If this is a default message (but not css or js),
2420 # show a hint that it is translatable on translatewiki.net
2421 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2422 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2424 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2425 if ( $defaultMessageText !== false ) {
2426 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2427 'translateinterface' );
2430 } elseif ( $namespace == NS_FILE
) {
2431 # Show a hint to shared repo
2432 $file = wfFindFile( $this->mTitle
);
2433 if ( $file && !$file->isLocal() ) {
2434 $descUrl = $file->getDescriptionUrl();
2435 # there must be a description url to show a hint to shared repo
2437 if ( !$this->mTitle
->exists() ) {
2438 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2439 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2442 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2443 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2450 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2451 # Show log extract when the user is currently blocked
2452 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2453 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2454 $user = User
::newFromName( $username, false /* allow IP users */ );
2455 $ip = User
::isIP( $username );
2456 $block = Block
::newFromTarget( $user, $user );
2457 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2458 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2459 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2460 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2461 # Show log extract if the user is currently blocked
2462 LogEventsList
::showLogExtract(
2465 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2469 'showIfEmpty' => false,
2471 'blocked-notice-logextract',
2472 $user->getName() # Support GENDER in notice
2478 # Try to add a custom edit intro, or use the standard one if this is not possible.
2479 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2480 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2481 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2483 if ( $wgUser->isLoggedIn() ) {
2485 // Suppress the external link icon, consider the help url an internal one
2486 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2494 // Suppress the external link icon, consider the help url an internal one
2495 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2497 'newarticletextanon',
2503 # Give a notice if the user is editing a deleted/moved page...
2504 if ( !$this->mTitle
->exists() ) {
2505 $dbr = wfGetDB( DB_REPLICA
);
2507 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2511 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2512 'showIfEmpty' => false,
2513 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2520 * Attempt to show a custom editing introduction, if supplied
2524 protected function showCustomIntro() {
2525 if ( $this->editintro
) {
2526 $title = Title
::newFromText( $this->editintro
);
2527 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2528 // Added using template syntax, to take <noinclude>'s into account.
2529 $this->context
->getOutput()->addWikiTextTitleTidy(
2530 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2540 * Gets an editable textual representation of $content.
2541 * The textual representation can be turned by into a Content object by the
2542 * toEditContent() method.
2544 * If $content is null or false or a string, $content is returned unchanged.
2546 * If the given Content object is not of a type that can be edited using
2547 * the text base EditPage, an exception will be raised. Set
2548 * $this->allowNonTextContent to true to allow editing of non-textual
2551 * @param Content|null|bool|string $content
2552 * @return string The editable text form of the content.
2554 * @throws MWException If $content is not an instance of TextContent and
2555 * $this->allowNonTextContent is not true.
2557 protected function toEditText( $content ) {
2558 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2562 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2563 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2566 return $content->serialize( $this->contentFormat
);
2570 * Turns the given text into a Content object by unserializing it.
2572 * If the resulting Content object is not of a type that can be edited using
2573 * the text base EditPage, an exception will be raised. Set
2574 * $this->allowNonTextContent to true to allow editing of non-textual
2577 * @param string|null|bool $text Text to unserialize
2578 * @return Content|bool|null The content object created from $text. If $text was false
2579 * or null, false resp. null will be returned instead.
2581 * @throws MWException If unserializing the text results in a Content
2582 * object that is not an instance of TextContent and
2583 * $this->allowNonTextContent is not true.
2585 protected function toEditContent( $text ) {
2586 if ( $text === false ||
$text === null ) {
2590 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2591 $this->contentModel
, $this->contentFormat
);
2593 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2594 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2601 * Send the edit form and related headers to OutputPage
2602 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2603 * during form output near the top, for captchas and the like.
2605 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2606 * use the EditPage::showEditForm:fields hook instead.
2608 public function showEditForm( $formCallback = null ) {
2611 # need to parse the preview early so that we know which templates are used,
2612 # otherwise users with "show preview after edit box" will get a blank list
2613 # we parse this near the beginning so that setHeaders can do the title
2614 # setting work instead of leaving it in getPreviewText
2615 $previewOutput = '';
2616 if ( $this->formtype
== 'preview' ) {
2617 $previewOutput = $this->getPreviewText();
2620 $out = $this->context
->getOutput();
2622 // Avoid PHP 7.1 warning of passing $this by reference
2624 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2626 $this->setHeaders();
2628 $this->addTalkPageText();
2629 $this->addEditNotices();
2631 if ( !$this->isConflict
&&
2632 $this->section
!= '' &&
2633 !$this->isSectionEditSupported() ) {
2634 // We use $this->section to much before this and getVal('wgSection') directly in other places
2635 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2636 // Someone is welcome to try refactoring though
2637 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2641 $this->showHeader();
2643 $out->addHTML( $this->editFormPageTop
);
2645 if ( $wgUser->getOption( 'previewontop' ) ) {
2646 $this->displayPreviewArea( $previewOutput, true );
2649 $out->addHTML( $this->editFormTextTop
);
2651 $showToolbar = true;
2652 if ( $this->wasDeletedSinceLastEdit() ) {
2653 if ( $this->formtype
== 'save' ) {
2654 // Hide the toolbar and edit area, user can click preview to get it back
2655 // Add an confirmation checkbox and explanation.
2656 $showToolbar = false;
2658 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2659 'deletedwhileediting' );
2663 // @todo add EditForm plugin interface and use it here!
2664 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2665 $out->addHTML( Html
::openElement(
2668 'class' => 'mw-editform',
2669 'id' => self
::EDITFORM_ID
,
2670 'name' => self
::EDITFORM_ID
,
2672 'action' => $this->getActionURL( $this->getContextTitle() ),
2673 'enctype' => 'multipart/form-data'
2677 if ( is_callable( $formCallback ) ) {
2678 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2679 call_user_func_array( $formCallback, [ &$out ] );
2682 // Add an empty field to trip up spambots
2684 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2687 [ 'for' => 'wpAntispam' ],
2688 $this->context
->msg( 'simpleantispam-label' )->parse()
2694 'name' => 'wpAntispam',
2695 'id' => 'wpAntispam',
2699 . Xml
::closeElement( 'div' )
2702 // Avoid PHP 7.1 warning of passing $this by reference
2704 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2706 // Put these up at the top to ensure they aren't lost on early form submission
2707 $this->showFormBeforeText();
2709 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2710 $username = $this->lastDelete
->user_name
;
2711 $comment = CommentStore
::newKey( 'log_comment' )->getComment( $this->lastDelete
)->text
;
2713 // It is better to not parse the comment at all than to have templates expanded in the middle
2714 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2715 $key = $comment === ''
2716 ?
'confirmrecreate-noreason'
2717 : 'confirmrecreate';
2719 '<div class="mw-confirm-recreate">' .
2720 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2721 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2722 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2728 # When the summary is hidden, also hide them on preview/show changes
2729 if ( $this->nosummary
) {
2730 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2733 # If a blank edit summary was previously provided, and the appropriate
2734 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2735 # user being bounced back more than once in the event that a summary
2738 # For a bit more sophisticated detection of blank summaries, hash the
2739 # automatic one and pass that in the hidden field wpAutoSummary.
2740 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2741 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2744 if ( $this->undidRev
) {
2745 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2748 if ( $this->selfRedirect
) {
2749 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2752 if ( $this->hasPresetSummary
) {
2753 // If a summary has been preset using &summary= we don't want to prompt for
2754 // a different summary. Only prompt for a summary if the summary is blanked.
2756 $this->autoSumm
= md5( '' );
2759 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2760 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2762 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2763 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2765 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2766 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2770 if ( $this->section
== 'new' ) {
2771 $this->showSummaryInput( true, $this->summary
);
2772 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2775 $out->addHTML( $this->editFormTextBeforeContent
);
2777 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2778 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2781 if ( $this->blankArticle
) {
2782 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2785 if ( $this->isConflict
) {
2786 // In an edit conflict bypass the overridable content form method
2787 // and fallback to the raw wpTextbox1 since editconflicts can't be
2788 // resolved between page source edits and custom ui edits using the
2790 $this->textbox2
= $this->textbox1
;
2792 $content = $this->getCurrentContent();
2793 $this->textbox1
= $this->toEditText( $content );
2795 $this->showTextbox1();
2797 $this->showContentForm();
2800 $out->addHTML( $this->editFormTextAfterContent
);
2802 $this->showStandardInputs();
2804 $this->showFormAfterText();
2806 $this->showTosSummary();
2808 $this->showEditTools();
2810 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2812 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2814 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2815 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2817 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2818 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2820 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2822 if ( $this->isConflict
) {
2824 $this->showConflict();
2825 } catch ( MWContentSerializationException
$ex ) {
2826 // this can't really happen, but be nice if it does.
2827 $msg = $this->context
->msg(
2828 'content-failed-to-parse',
2829 $this->contentModel
,
2830 $this->contentFormat
,
2833 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2837 // Set a hidden field so JS knows what edit form mode we are in
2838 if ( $this->isConflict
) {
2840 } elseif ( $this->preview
) {
2842 } elseif ( $this->diff
) {
2847 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2849 // Marker for detecting truncated form data. This must be the last
2850 // parameter sent in order to be of use, so do not move me.
2851 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2852 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2854 if ( !$wgUser->getOption( 'previewontop' ) ) {
2855 $this->displayPreviewArea( $previewOutput, false );
2860 * Wrapper around TemplatesOnThisPageFormatter to make
2861 * a "templates on this page" list.
2863 * @param Title[] $templates
2864 * @return string HTML
2866 public function makeTemplatesOnThisPageList( array $templates ) {
2867 $templateListFormatter = new TemplatesOnThisPageFormatter(
2868 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2871 // preview if preview, else section if section, else false
2873 if ( $this->preview
) {
2875 } elseif ( $this->section
!= '' ) {
2879 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2880 $templateListFormatter->format( $templates, $type )
2885 * Extract the section title from current section text, if any.
2887 * @param string $text
2888 * @return string|bool String or false
2890 public static function extractSectionTitle( $text ) {
2891 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2892 if ( !empty( $matches[2] ) ) {
2894 return $wgParser->stripSectionName( trim( $matches[2] ) );
2900 protected function showHeader() {
2902 global $wgAllowUserCss, $wgAllowUserJs;
2904 $out = $this->context
->getOutput();
2905 if ( $this->isConflict
) {
2906 $this->addExplainConflictHeader( $out );
2907 $this->editRevId
= $this->page
->getLatest();
2909 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2910 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2911 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2912 if ( $sectionTitle !== false ) {
2913 $this->summary
= "/* $sectionTitle */ ";
2918 $buttonLabel = $this->context
->msg( $this->getSaveButtonLabel() )->text();
2920 if ( $this->missingComment
) {
2921 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2924 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2926 "<div id='mw-missingsummary'>\n$1\n</div>",
2927 [ 'missingsummary', $buttonLabel ]
2931 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2933 "<div id='mw-missingcommentheader'>\n$1\n</div>",
2934 [ 'missingcommentheader', $buttonLabel ]
2938 if ( $this->blankArticle
) {
2940 "<div id='mw-blankarticle'>\n$1\n</div>",
2941 [ 'blankarticle', $buttonLabel ]
2945 if ( $this->selfRedirect
) {
2947 "<div id='mw-selfredirect'>\n$1\n</div>",
2948 [ 'selfredirect', $buttonLabel ]
2952 if ( $this->hookError
!== '' ) {
2953 $out->addWikiText( $this->hookError
);