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';
239 public $isConflict = false;
242 * @deprecated since 1.30 use Title::isCssJsSubpage()
245 public $isCssJsSubpage = false;
248 * @deprecated since 1.30 use Title::isCssSubpage()
251 public $isCssSubpage = false;
254 * @deprecated since 1.30 use Title::isJsSubpage()
257 public $isJsSubpage = false;
260 * @deprecated since 1.30
263 public $isWrongCaseCssJsPage = false;
265 /** @var bool New page or new section */
266 public $isNew = false;
269 public $deletedSinceEdit;
277 /** @var bool|stdClass */
281 public $mTokenOk = false;
284 public $mTokenOkExceptSuffix = false;
287 public $mTriedSave = false;
290 public $incompleteForm = false;
293 public $tooBig = false;
296 public $missingComment = false;
299 public $missingSummary = false;
302 public $allowBlankSummary = false;
305 protected $blankArticle = false;
308 protected $allowBlankArticle = false;
311 protected $selfRedirect = false;
314 protected $allowSelfRedirect = false;
317 public $autoSumm = '';
320 public $hookError = '';
322 /** @var ParserOutput */
323 public $mParserOutput;
325 /** @var bool Has a summary been preset using GET parameter &summary= ? */
326 public $hasPresetSummary = false;
328 /** @var Revision|bool */
329 public $mBaseRevision = false;
332 public $mShowSummaryField = true;
337 public $save = false;
340 public $preview = false;
343 public $diff = false;
346 public $minoredit = false;
349 public $watchthis = false;
352 public $recreate = false;
355 public $textbox1 = '';
358 public $textbox2 = '';
361 public $summary = '';
364 public $nosummary = false;
367 public $edittime = '';
370 private $editRevId = null;
373 public $section = '';
376 public $sectiontitle = '';
379 public $starttime = '';
385 public $parentRevId = 0;
388 public $editintro = '';
391 public $scrolltop = null;
397 public $contentModel;
399 /** @var null|string */
400 public $contentFormat = null;
402 /** @var null|array */
403 private $changeTags = null;
405 # Placeholders for text injection by hooks (must be HTML)
406 # extensions should take care to _append_ to the present value
408 /** @var string Before even the preview */
409 public $editFormPageTop = '';
410 public $editFormTextTop = '';
411 public $editFormTextBeforeContent = '';
412 public $editFormTextAfterWarn = '';
413 public $editFormTextAfterTools = '';
414 public $editFormTextBottom = '';
415 public $editFormTextAfterContent = '';
416 public $previewTextAfterContent = '';
417 public $mPreloadContent = null;
419 /* $didSave should be set to true whenever an article was successfully altered. */
420 public $didSave = false;
421 public $undidRev = 0;
423 public $suppressIntro = false;
429 protected $contentLength = false;
432 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
434 private $enableApiEditOverride = false;
437 * @var IContextSource
442 * @var bool Whether an old revision is edited
444 private $isOldRev = false;
447 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
449 private $unicodeCheck;
452 * Factory function to create an edit conflict helper
456 private $editConflictHelperFactory;
459 * @var TextConflictHelper|null
461 private $editConflictHelper;
464 * @param Article $article
466 public function __construct( Article
$article ) {
467 $this->mArticle
= $article;
468 $this->page
= $article->getPage(); // model object
469 $this->mTitle
= $article->getTitle();
470 $this->context
= $article->getContext();
472 $this->contentModel
= $this->mTitle
->getContentModel();
474 $handler = ContentHandler
::getForModelID( $this->contentModel
);
475 $this->contentFormat
= $handler->getDefaultFormat();
476 $this->editConflictHelperFactory
= [ $this, 'newTextConflictHelper' ];
482 public function getArticle() {
483 return $this->mArticle
;
488 * @return IContextSource
490 public function getContext() {
491 return $this->context
;
498 public function getTitle() {
499 return $this->mTitle
;
503 * Set the context Title object
505 * @param Title|null $title Title object or null
507 public function setContextTitle( $title ) {
508 $this->mContextTitle
= $title;
512 * Get the context title object.
513 * If not set, $wgTitle will be returned. This behavior might change in
514 * the future to return $this->mTitle instead.
518 public function getContextTitle() {
519 if ( is_null( $this->mContextTitle
) ) {
522 __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.'
527 return $this->mContextTitle
;
532 * Check if the edit page is using OOUI controls
533 * @return bool Always true
534 * @deprecated since 1.30
536 public function isOouiEnabled() {
537 wfDeprecated( __METHOD__
, '1.30' );
542 * Returns if the given content model is editable.
544 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
546 * @throws MWException If $modelId has no known handler
548 public function isSupportedContentModel( $modelId ) {
549 return $this->enableApiEditOverride
=== true ||
550 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
554 * Allow editing of content that supports API direct editing, but not general
555 * direct editing. Set to false by default.
557 * @param bool $enableOverride
559 public function setApiEditOverride( $enableOverride ) {
560 $this->enableApiEditOverride
= $enableOverride;
564 * @deprecated since 1.29, call edit directly
566 public function submit() {
567 wfDeprecated( __METHOD__
, '1.29' );
572 * This is the function that gets called for "action=edit". It
573 * sets up various member variables, then passes execution to
574 * another function, usually showEditForm()
576 * The edit form is self-submitting, so that when things like
577 * preview and edit conflicts occur, we get the same form back
578 * with the extra stuff added. Only when the final submission
579 * is made and all is well do we actually save and redirect to
580 * the newly-edited page.
582 public function edit() {
583 // Allow extensions to modify/prevent this form or submission
584 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
588 wfDebug( __METHOD__
. ": enter\n" );
590 $request = $this->context
->getRequest();
591 // If they used redlink=1 and the page exists, redirect to the main article
592 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
593 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
597 $this->importFormData( $request );
598 $this->firsttime
= false;
600 if ( wfReadOnly() && $this->save
) {
603 $this->preview
= true;
607 $this->formtype
= 'save';
608 } elseif ( $this->preview
) {
609 $this->formtype
= 'preview';
610 } elseif ( $this->diff
) {
611 $this->formtype
= 'diff';
612 } else { # First time through
613 $this->firsttime
= true;
614 if ( $this->previewOnOpen() ) {
615 $this->formtype
= 'preview';
617 $this->formtype
= 'initial';
621 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
623 wfDebug( __METHOD__
. ": User can't edit\n" );
624 // Auto-block user's IP if the account was "hard" blocked
625 if ( !wfReadOnly() ) {
626 DeferredUpdates
::addCallableUpdate( function () {
627 $this->context
->getUser()->spreadAnyEditBlock();
630 $this->displayPermissionsError( $permErrors );
635 $revision = $this->mArticle
->getRevisionFetched();
636 // Disallow editing revisions with content models different from the current one
637 // Undo edits being an exception in order to allow reverting content model changes.
639 && $revision->getContentModel() !== $this->contentModel
642 if ( $this->undidRev
) {
643 $undidRevObj = Revision
::newFromId( $this->undidRev
);
644 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
646 if ( !$this->undidRev
648 ||
$prevRev->getContentModel() !== $this->contentModel
650 $this->displayViewSourcePage(
651 $this->getContentObject(),
653 'contentmodelediterror',
654 $revision->getContentModel(),
662 $this->isConflict
= false;
663 // css / js subpages of user pages get a special treatment
664 // The following member variables are deprecated since 1.30,
665 // the functions should be used instead.
666 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
667 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
668 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
669 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
671 # Show applicable editing introductions
672 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
676 # Attempt submission here. This will check for edit conflicts,
677 # and redundantly check for locked database, blocked IPs, etc.
678 # that edit() already checked just in case someone tries to sneak
679 # in the back door with a hand-edited submission URL.
681 if ( 'save' == $this->formtype
) {
682 $resultDetails = null;
683 $status = $this->attemptSave( $resultDetails );
684 if ( !$this->handleStatus( $status, $resultDetails ) ) {
689 # First time through: get contents, set time for conflict
691 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
692 if ( $this->initialiseForm() === false ) {
693 $this->noSuchSectionPage();
697 if ( !$this->mTitle
->getArticleID() ) {
698 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
700 Hooks
::run( 'EditFormInitialText', [ $this ] );
705 $this->showEditForm();
709 * @param string $rigor Same format as Title::getUserPermissionErrors()
712 protected function getEditPermissionErrors( $rigor = 'secure' ) {
713 $user = $this->context
->getUser();
714 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
715 # Can this title be created?
716 if ( !$this->mTitle
->exists() ) {
717 $permErrors = array_merge(
720 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
725 # Ignore some permissions errors when a user is just previewing/viewing diffs
727 foreach ( $permErrors as $error ) {
728 if ( ( $this->preview ||
$this->diff
)
730 $error[0] == 'blockedtext' ||
731 $error[0] == 'autoblockedtext' ||
732 $error[0] == 'systemblockedtext'
738 $permErrors = wfArrayDiff2( $permErrors, $remove );
744 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
745 * but with the following differences:
746 * - If redlink=1, the user will be redirected to the page
747 * - If there is content to display or the error occurs while either saving,
748 * previewing or showing the difference, it will be a
749 * "View source for ..." page displaying the source code after the error message.
752 * @param array $permErrors Array of permissions errors, as returned by
753 * Title::getUserPermissionsErrors().
754 * @throws PermissionsError
756 protected function displayPermissionsError( array $permErrors ) {
757 $out = $this->context
->getOutput();
758 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
759 // The edit page was reached via a red link.
760 // Redirect to the article page and let them click the edit tab if
761 // they really want a permission error.
762 $out->redirect( $this->mTitle
->getFullURL() );
766 $content = $this->getContentObject();
768 # Use the normal message if there's nothing to display
769 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
770 $action = $this->mTitle
->exists() ?
'edit' :
771 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
772 throw new PermissionsError( $action, $permErrors );
775 $this->displayViewSourcePage(
777 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
782 * Display a read-only View Source page
783 * @param Content $content content object
784 * @param string $errorMessage additional wikitext error message to display
786 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
787 $out = $this->context
->getOutput();
788 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
790 $out->setRobotPolicy( 'noindex,nofollow' );
791 $out->setPageTitle( $this->context
->msg(
793 $this->getContextTitle()->getPrefixedText()
795 $out->addBacklinkSubtitle( $this->getContextTitle() );
796 $out->addHTML( $this->editFormPageTop
);
797 $out->addHTML( $this->editFormTextTop
);
799 if ( $errorMessage !== '' ) {
800 $out->addWikiText( $errorMessage );
801 $out->addHTML( "<hr />\n" );
804 # If the user made changes, preserve them when showing the markup
805 # (This happens when a user is blocked during edit, for instance)
806 if ( !$this->firsttime
) {
807 $text = $this->textbox1
;
808 $out->addWikiMsg( 'viewyourtext' );
811 $text = $this->toEditText( $content );
812 } catch ( MWException
$e ) {
813 # Serialize using the default format if the content model is not supported
814 # (e.g. for an old revision with a different model)
815 $text = $content->serialize();
817 $out->addWikiMsg( 'viewsourcetext' );
820 $out->addHTML( $this->editFormTextBeforeContent
);
821 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
822 $out->addHTML( $this->editFormTextAfterContent
);
824 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
826 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
828 $out->addHTML( $this->editFormTextBottom
);
829 if ( $this->mTitle
->exists() ) {
830 $out->returnToMain( null, $this->mTitle
);
835 * Should we show a preview when the edit form is first shown?
839 protected function previewOnOpen() {
840 $config = $this->context
->getConfig();
841 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
842 $request = $this->context
->getRequest();
843 if ( $config->get( 'RawHtml' ) ) {
844 // If raw HTML is enabled, disable preview on open
845 // since it has to be posted with a token for
849 if ( $request->getVal( 'preview' ) == 'yes' ) {
850 // Explicit override from request
852 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
853 // Explicit override from request
855 } elseif ( $this->section
== 'new' ) {
856 // Nothing *to* preview for new sections
858 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
859 && $this->context
->getUser()->getOption( 'previewonfirst' )
861 // Standard preference behavior
863 } elseif ( !$this->mTitle
->exists()
864 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
865 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
867 // Categories are special
875 * Checks whether the user entered a skin name in uppercase,
876 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
880 protected function isWrongCaseCssJsPage() {
881 if ( $this->mTitle
->isCssJsSubpage() ) {
882 $name = $this->mTitle
->getSkinFromCssJsSubpage();
883 $skins = array_merge(
884 array_keys( Skin
::getSkinNames() ),
887 return !in_array( $name, $skins )
888 && in_array( strtolower( $name ), $skins );
895 * Returns whether section editing is supported for the current page.
896 * Subclasses may override this to replace the default behavior, which is
897 * to check ContentHandler::supportsSections.
899 * @return bool True if this edit page supports sections, false otherwise.
901 protected function isSectionEditSupported() {
902 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
903 return $contentHandler->supportsSections();
907 * This function collects the form data and uses it to populate various member variables.
908 * @param WebRequest &$request
909 * @throws ErrorPageError
911 public function importFormData( &$request ) {
912 # Section edit can come from either the form or a link
913 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
915 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
916 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
919 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
921 if ( $request->wasPosted() ) {
922 # These fields need to be checked for encoding.
923 # Also remove trailing whitespace, but don't remove _initial_
924 # whitespace from the text boxes. This may be significant formatting.
925 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
926 if ( !$request->getCheck( 'wpTextbox2' ) ) {
927 // Skip this if wpTextbox2 has input, it indicates that we came
928 // from a conflict page with raw page text, not a custom form
929 // modified by subclasses
930 $textbox1 = $this->importContentFormData( $request );
931 if ( $textbox1 !== null ) {
932 $this->textbox1
= $textbox1;
936 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
938 $this->summary
= $request->getText( 'wpSummary' );
940 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
941 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
943 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
945 # Treat sectiontitle the same way as summary.
946 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
947 # currently doing double duty as both edit summary and section title. Right now this
948 # is just to allow API edits to work around this limitation, but this should be
949 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
950 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
951 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
953 $this->edittime
= $request->getVal( 'wpEdittime' );
954 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
955 $this->starttime
= $request->getVal( 'wpStarttime' );
957 $undidRev = $request->getInt( 'wpUndidRevision' );
959 $this->undidRev
= $undidRev;
962 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
964 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
965 // wpTextbox1 field is missing, possibly due to being "too big"
966 // according to some filter rules such as Suhosin's setting for
967 // suhosin.request.max_value_length (d'oh)
968 $this->incompleteForm
= true;
970 // If we receive the last parameter of the request, we can fairly
971 // claim the POST request has not been truncated.
973 // TODO: softened the check for cutover. Once we determine
974 // that it is safe, we should complete the transition by
975 // removing the "edittime" clause.
976 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
977 && is_null( $this->edittime
) );
979 if ( $this->incompleteForm
) {
980 # If the form is incomplete, force to preview.
981 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
982 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
983 $this->preview
= true;
985 $this->preview
= $request->getCheck( 'wpPreview' );
986 $this->diff
= $request->getCheck( 'wpDiff' );
988 // Remember whether a save was requested, so we can indicate
989 // if we forced preview due to session failure.
990 $this->mTriedSave
= !$this->preview
;
992 if ( $this->tokenOk( $request ) ) {
993 # Some browsers will not report any submit button
994 # if the user hits enter in the comment box.
995 # The unmarked state will be assumed to be a save,
996 # if the form seems otherwise complete.
997 wfDebug( __METHOD__
. ": Passed token check.\n" );
998 } elseif ( $this->diff
) {
999 # Failed token check, but only requested "Show Changes".
1000 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
1002 # Page might be a hack attempt posted from
1003 # an external site. Preview instead of saving.
1004 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
1005 $this->preview
= true;
1008 $this->save
= !$this->preview
&& !$this->diff
;
1009 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
1010 $this->edittime
= null;
1013 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
1014 $this->starttime
= null;
1017 $this->recreate
= $request->getCheck( 'wpRecreate' );
1019 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
1020 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
1022 $user = $this->context
->getUser();
1023 # Don't force edit summaries when a user is editing their own user or talk page
1024 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
1025 && $this->mTitle
->getText() == $user->getName()
1027 $this->allowBlankSummary
= true;
1029 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1030 ||
!$user->getOption( 'forceeditsummary' );
1033 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1035 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1036 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1038 $changeTags = $request->getVal( 'wpChangeTags' );
1039 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1040 $this->changeTags
= [];
1042 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1046 # Not a posted form? Start with nothing.
1047 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1048 $this->textbox1
= '';
1049 $this->summary
= '';
1050 $this->sectiontitle
= '';
1051 $this->edittime
= '';
1052 $this->editRevId
= null;
1053 $this->starttime
= wfTimestampNow();
1054 $this->edit
= false;
1055 $this->preview
= false;
1056 $this->save
= false;
1057 $this->diff
= false;
1058 $this->minoredit
= false;
1059 // Watch may be overridden by request parameters
1060 $this->watchthis
= $request->getBool( 'watchthis', false );
1061 $this->recreate
= false;
1063 // When creating a new section, we can preload a section title by passing it as the
1064 // preloadtitle parameter in the URL (T15100)
1065 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1066 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1067 // Once wpSummary isn't being use for setting section titles, we should delete this.
1068 $this->summary
= $request->getVal( 'preloadtitle' );
1069 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1070 $this->summary
= $request->getText( 'summary' );
1071 if ( $this->summary
!== '' ) {
1072 $this->hasPresetSummary
= true;
1076 if ( $request->getVal( 'minor' ) ) {
1077 $this->minoredit
= true;
1081 $this->oldid
= $request->getInt( 'oldid' );
1082 $this->parentRevId
= $request->getInt( 'parentRevId' );
1084 $this->bot
= $request->getBool( 'bot', true );
1085 $this->nosummary
= $request->getBool( 'nosummary' );
1087 // May be overridden by revision.
1088 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1089 // May be overridden by revision.
1090 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1093 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1094 } catch ( MWUnknownContentModelException
$e ) {
1095 throw new ErrorPageError(
1096 'editpage-invalidcontentmodel-title',
1097 'editpage-invalidcontentmodel-text',
1098 [ wfEscapeWikiText( $this->contentModel
) ]
1102 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1103 throw new ErrorPageError(
1104 'editpage-notsupportedcontentformat-title',
1105 'editpage-notsupportedcontentformat-text',
1107 wfEscapeWikiText( $this->contentFormat
),
1108 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1114 * @todo Check if the desired model is allowed in this namespace, and if
1115 * a transition from the page's current model to the new model is
1119 $this->editintro
= $request->getText( 'editintro',
1120 // Custom edit intro for new sections
1121 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1123 // Allow extensions to modify form data
1124 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1128 * Subpage overridable method for extracting the page content data from the
1129 * posted form to be placed in $this->textbox1, if using customized input
1130 * this method should be overridden and return the page text that will be used
1131 * for saving, preview parsing and so on...
1133 * @param WebRequest &$request
1134 * @return string|null
1136 protected function importContentFormData( &$request ) {
1137 return; // Don't do anything, EditPage already extracted wpTextbox1
1141 * Initialise form fields in the object
1142 * Called on the first invocation, e.g. when a user clicks an edit link
1143 * @return bool If the requested section is valid
1145 public function initialiseForm() {
1146 $this->edittime
= $this->page
->getTimestamp();
1147 $this->editRevId
= $this->page
->getLatest();
1149 $content = $this->getContentObject( false ); # TODO: track content object?!
1150 if ( $content === false ) {
1153 $this->textbox1
= $this->toEditText( $content );
1155 $user = $this->context
->getUser();
1156 // activate checkboxes if user wants them to be always active
1157 # Sort out the "watch" checkbox
1158 if ( $user->getOption( 'watchdefault' ) ) {
1160 $this->watchthis
= true;
1161 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1163 $this->watchthis
= true;
1164 } elseif ( $user->isWatched( $this->mTitle
) ) {
1166 $this->watchthis
= true;
1168 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1169 $this->minoredit
= true;
1171 if ( $this->textbox1
=== false ) {
1178 * @param Content|null $def_content The default value to return
1180 * @return Content|null Content on success, $def_content for invalid sections
1184 protected function getContentObject( $def_content = null ) {
1189 $user = $this->context
->getUser();
1190 $request = $this->context
->getRequest();
1191 // For message page not locally set, use the i18n message.
1192 // For other non-existent articles, use preload text if any.
1193 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1194 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1195 # If this is a system message, get the default text.
1196 $msg = $this->mTitle
->getDefaultMessageText();
1198 $content = $this->toEditContent( $msg );
1200 if ( $content === false ) {
1201 # If requested, preload some text.
1202 $preload = $request->getVal( 'preload',
1203 // Custom preload text for new sections
1204 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1205 $params = $request->getArray( 'preloadparams', [] );
1207 $content = $this->getPreloadedContent( $preload, $params );
1209 // For existing pages, get text based on "undo" or section parameters.
1211 if ( $this->section
!= '' ) {
1212 // Get section edit text (returns $def_text for invalid sections)
1213 $orig = $this->getOriginalContent( $user );
1214 $content = $orig ?
$orig->getSection( $this->section
) : null;
1217 $content = $def_content;
1220 $undoafter = $request->getInt( 'undoafter' );
1221 $undo = $request->getInt( 'undo' );
1223 if ( $undo > 0 && $undoafter > 0 ) {
1224 $undorev = Revision
::newFromId( $undo );
1225 $oldrev = Revision
::newFromId( $undoafter );
1227 # Sanity check, make sure it's the right page,
1228 # the revisions exist and they were not deleted.
1229 # Otherwise, $content will be left as-is.
1230 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1231 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1232 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1234 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1236 if ( $content === false ) {
1237 # Warn the user that something went wrong
1238 $undoMsg = 'failure';
1240 $oldContent = $this->page
->getContent( Revision
::RAW
);
1241 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1242 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1243 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1244 // The undo may change content
1245 // model if its reverting the top
1246 // edit. This can result in
1247 // mismatched content model/format.
1248 $this->contentModel
= $newContent->getModel();
1249 $this->contentFormat
= $oldrev->getContentFormat();
1252 if ( $newContent->equals( $oldContent ) ) {
1253 # Tell the user that the undo results in no change,
1254 # i.e. the revisions were already undone.
1255 $undoMsg = 'nochange';
1258 # Inform the user of our success and set an automatic edit summary
1259 $undoMsg = 'success';
1261 # If we just undid one rev, use an autosummary
1262 $firstrev = $oldrev->getNext();
1263 if ( $firstrev && $firstrev->getId() == $undo ) {
1264 $userText = $undorev->getUserText();
1265 if ( $userText === '' ) {
1266 $undoSummary = $this->context
->msg(
1267 'undo-summary-username-hidden',
1269 )->inContentLanguage()->text();
1271 $undoSummary = $this->context
->msg(
1275 )->inContentLanguage()->text();
1277 if ( $this->summary
=== '' ) {
1278 $this->summary
= $undoSummary;
1280 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1281 ->inContentLanguage()->text() . $this->summary
;
1283 $this->undidRev
= $undo;
1285 $this->formtype
= 'diff';
1289 // Failed basic sanity checks.
1290 // Older revisions may have been removed since the link
1291 // was created, or we may simply have got bogus input.
1295 $out = $this->context
->getOutput();
1296 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1297 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1298 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1299 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1302 if ( $content === false ) {
1303 $content = $this->getOriginalContent( $user );
1312 * Get the content of the wanted revision, without section extraction.
1314 * The result of this function can be used to compare user's input with
1315 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1316 * to the original text of the edit.
1318 * This differs from Article::getContent() that when a missing revision is
1319 * encountered the result will be null and not the
1320 * 'missing-revision' message.
1323 * @param User $user The user to get the revision for
1324 * @return Content|null
1326 private function getOriginalContent( User
$user ) {
1327 if ( $this->section
== 'new' ) {
1328 return $this->getCurrentContent();
1330 $revision = $this->mArticle
->getRevisionFetched();
1331 if ( $revision === null ) {
1332 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1333 return $handler->makeEmptyContent();
1335 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1340 * Get the edit's parent revision ID
1342 * The "parent" revision is the ancestor that should be recorded in this
1343 * page's revision history. It is either the revision ID of the in-memory
1344 * article content, or in the case of a 3-way merge in order to rebase
1345 * across a recoverable edit conflict, the ID of the newer revision to
1346 * which we have rebased this page.
1349 * @return int Revision ID
1351 public function getParentRevId() {
1352 if ( $this->parentRevId
) {
1353 return $this->parentRevId
;
1355 return $this->mArticle
->getRevIdFetched();
1360 * Get the current content of the page. This is basically similar to
1361 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1362 * content object is returned instead of null.
1367 protected function getCurrentContent() {
1368 $rev = $this->page
->getRevision();
1369 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1371 if ( $content === false ||
$content === null ) {
1372 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1373 return $handler->makeEmptyContent();
1374 } elseif ( !$this->undidRev
) {
1375 // Content models should always be the same since we error
1376 // out if they are different before this point (in ->edit()).
1377 // The exception being, during an undo, the current revision might
1378 // differ from the prior revision.
1379 $logger = LoggerFactory
::getInstance( 'editpage' );
1380 if ( $this->contentModel
!== $rev->getContentModel() ) {
1381 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1382 'prev' => $this->contentModel
,
1383 'new' => $rev->getContentModel(),
1384 'title' => $this->getTitle()->getPrefixedDBkey(),
1385 'method' => __METHOD__
1387 $this->contentModel
= $rev->getContentModel();
1390 // Given that the content models should match, the current selected
1391 // format should be supported.
1392 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1393 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1395 'prev' => $this->contentFormat
,
1396 'new' => $rev->getContentFormat(),
1397 'title' => $this->getTitle()->getPrefixedDBkey(),
1398 'method' => __METHOD__
1400 $this->contentFormat
= $rev->getContentFormat();
1407 * Use this method before edit() to preload some content into the edit box
1409 * @param Content $content
1413 public function setPreloadedContent( Content
$content ) {
1414 $this->mPreloadContent
= $content;
1418 * Get the contents to be preloaded into the box, either set by
1419 * an earlier setPreloadText() or by loading the given page.
1421 * @param string $preload Representing the title to preload from.
1422 * @param array $params Parameters to use (interface-message style) in the preloaded text
1428 protected function getPreloadedContent( $preload, $params = [] ) {
1429 if ( !empty( $this->mPreloadContent
) ) {
1430 return $this->mPreloadContent
;
1433 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1435 if ( $preload === '' ) {
1436 return $handler->makeEmptyContent();
1439 $user = $this->context
->getUser();
1440 $title = Title
::newFromText( $preload );
1441 # Check for existence to avoid getting MediaWiki:Noarticletext
1442 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1443 // TODO: somehow show a warning to the user!
1444 return $handler->makeEmptyContent();
1447 $page = WikiPage
::factory( $title );
1448 if ( $page->isRedirect() ) {
1449 $title = $page->getRedirectTarget();
1451 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1452 // TODO: somehow show a warning to the user!
1453 return $handler->makeEmptyContent();
1455 $page = WikiPage
::factory( $title );
1458 $parserOptions = ParserOptions
::newFromUser( $user );
1459 $content = $page->getContent( Revision
::RAW
);
1462 // TODO: somehow show a warning to the user!
1463 return $handler->makeEmptyContent();
1466 if ( $content->getModel() !== $handler->getModelID() ) {
1467 $converted = $content->convert( $handler->getModelID() );
1469 if ( !$converted ) {
1470 // TODO: somehow show a warning to the user!
1471 wfDebug( "Attempt to preload incompatible content: " .
1472 "can't convert " . $content->getModel() .
1473 " to " . $handler->getModelID() );
1475 return $handler->makeEmptyContent();
1478 $content = $converted;
1481 return $content->preloadTransform( $title, $parserOptions, $params );
1485 * Make sure the form isn't faking a user's credentials.
1487 * @param WebRequest &$request
1491 public function tokenOk( &$request ) {
1492 $token = $request->getVal( 'wpEditToken' );
1493 $user = $this->context
->getUser();
1494 $this->mTokenOk
= $user->matchEditToken( $token );
1495 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1496 return $this->mTokenOk
;
1500 * Sets post-edit cookie indicating the user just saved a particular revision.
1502 * This uses a temporary cookie for each revision ID so separate saves will never
1503 * interfere with each other.
1505 * Article::view deletes the cookie on server-side after the redirect and
1506 * converts the value to the global JavaScript variable wgPostEdit.
1508 * If the variable were set on the server, it would be cached, which is unwanted
1509 * since the post-edit state should only apply to the load right after the save.
1511 * @param int $statusValue The status value (to check for new article status)
1513 protected function setPostEditCookie( $statusValue ) {
1514 $revisionId = $this->page
->getLatest();
1515 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1518 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1520 } elseif ( $this->oldid
) {
1524 $response = $this->context
->getRequest()->response();
1525 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1529 * Attempt submission
1530 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1531 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1532 * @return Status The resulting status object.
1534 public function attemptSave( &$resultDetails = false ) {
1535 # Allow bots to exempt some edits from bot flagging
1536 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1537 $status = $this->internalAttemptSave( $resultDetails, $bot );
1539 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1545 * Log when a page was successfully saved after the edit conflict view
1547 private function incrementResolvedConflicts() {
1548 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1552 $this->getEditConflictHelper()->incrementResolvedStats();
1556 * Handle status, such as after attempt save
1558 * @param Status $status
1559 * @param array|bool $resultDetails
1561 * @throws ErrorPageError
1562 * @return bool False, if output is done, true if rest of the form should be displayed
1564 private function handleStatus( Status
$status, $resultDetails ) {
1566 * @todo FIXME: once the interface for internalAttemptSave() is made
1567 * nicer, this should use the message in $status
1569 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1570 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1572 $this->incrementResolvedConflicts();
1574 $this->didSave
= true;
1575 if ( !$resultDetails['nullEdit'] ) {
1576 $this->setPostEditCookie( $status->value
);
1580 $out = $this->context
->getOutput();
1582 // "wpExtraQueryRedirect" is a hidden input to modify
1583 // after save URL and is not used by actual edit form
1584 $request = $this->context
->getRequest();
1585 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1587 switch ( $status->value
) {
1588 case self
::AS_HOOK_ERROR_EXPECTED
:
1589 case self
::AS_CONTENT_TOO_BIG
:
1590 case self
::AS_ARTICLE_WAS_DELETED
:
1591 case self
::AS_CONFLICT_DETECTED
:
1592 case self
::AS_SUMMARY_NEEDED
:
1593 case self
::AS_TEXTBOX_EMPTY
:
1594 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1596 case self
::AS_BLANK_ARTICLE
:
1597 case self
::AS_SELF_REDIRECT
:
1600 case self
::AS_HOOK_ERROR
:
1603 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1604 case self
::AS_PARSE_ERROR
:
1605 case self
::AS_UNICODE_NOT_SUPPORTED
:
1606 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1609 case self
::AS_SUCCESS_NEW_ARTICLE
:
1610 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1611 if ( $extraQueryRedirect ) {
1612 if ( $query === '' ) {
1613 $query = $extraQueryRedirect;
1615 $query = $query . '&' . $extraQueryRedirect;
1618 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1619 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1622 case self
::AS_SUCCESS_UPDATE
:
1624 $sectionanchor = $resultDetails['sectionanchor'];
1626 // Give extensions a chance to modify URL query on update
1628 'ArticleUpdateBeforeRedirect',
1629 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1632 if ( $resultDetails['redirect'] ) {
1633 if ( $extraQuery == '' ) {
1634 $extraQuery = 'redirect=no';
1636 $extraQuery = 'redirect=no&' . $extraQuery;
1639 if ( $extraQueryRedirect ) {
1640 if ( $extraQuery === '' ) {
1641 $extraQuery = $extraQueryRedirect;
1643 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1647 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1650 case self
::AS_SPAM_ERROR
:
1651 $this->spamPageWithContent( $resultDetails['spam'] );
1654 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1655 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1657 case self
::AS_IMAGE_REDIRECT_ANON
:
1658 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1659 throw new PermissionsError( 'upload' );
1661 case self
::AS_READ_ONLY_PAGE_ANON
:
1662 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1663 throw new PermissionsError( 'edit' );
1665 case self
::AS_READ_ONLY_PAGE
:
1666 throw new ReadOnlyError
;
1668 case self
::AS_RATE_LIMITED
:
1669 throw new ThrottledError();
1671 case self
::AS_NO_CREATE_PERMISSION
:
1672 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1673 throw new PermissionsError( $permission );
1675 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1676 throw new PermissionsError( 'editcontentmodel' );
1679 // We don't recognize $status->value. The only way that can happen
1680 // is if an extension hook aborted from inside ArticleSave.
1681 // Render the status object into $this->hookError
1682 // FIXME this sucks, we should just use the Status object throughout
1683 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1690 * Run hooks that can filter edits just before they get saved.
1692 * @param Content $content The Content to filter.
1693 * @param Status $status For reporting the outcome to the caller
1694 * @param User $user The user performing the edit
1698 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1699 // Run old style post-section-merge edit filter
1700 if ( $this->hookError
!= '' ) {
1701 # ...or the hook could be expecting us to produce an error
1702 $status->fatal( 'hookaborted' );
1703 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1707 // Run new style post-section-merge edit filter
1708 if ( !Hooks
::run( 'EditFilterMergedContent',
1709 [ $this->context
, $content, $status, $this->summary
,
1710 $user, $this->minoredit
] )
1712 # Error messages etc. could be handled within the hook...
1713 if ( $status->isGood() ) {
1714 $status->fatal( 'hookaborted' );
1715 // Not setting $this->hookError here is a hack to allow the hook
1716 // to cause a return to the edit page without $this->hookError
1717 // being set. This is used by ConfirmEdit to display a captcha
1718 // without any error message cruft.
1720 $this->hookError
= $status->getWikiText();
1722 // Use the existing $status->value if the hook set it
1723 if ( !$status->value
) {
1724 $status->value
= self
::AS_HOOK_ERROR
;
1727 } elseif ( !$status->isOK() ) {
1728 # ...or the hook could be expecting us to produce an error
1729 // FIXME this sucks, we should just use the Status object throughout
1730 $this->hookError
= $status->getWikiText();
1731 $status->fatal( 'hookaborted' );
1732 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1740 * Return the summary to be used for a new section.
1742 * @param string $sectionanchor Set to the section anchor text
1745 private function newSectionSummary( &$sectionanchor = null ) {
1748 if ( $this->sectiontitle
!== '' ) {
1749 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1750 // If no edit summary was specified, create one automatically from the section
1751 // title and have it link to the new section. Otherwise, respect the summary as
1753 if ( $this->summary
=== '' ) {
1754 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1755 return $this->context
->msg( 'newsectionsummary' )
1756 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1758 } elseif ( $this->summary
!== '' ) {
1759 $sectionanchor = $this->guessSectionName( $this->summary
);
1760 # This is a new section, so create a link to the new section
1761 # in the revision summary.
1762 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1763 return $this->context
->msg( 'newsectionsummary' )
1764 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1766 return $this->summary
;
1770 * Attempt submission (no UI)
1772 * @param array &$result Array to add statuses to, currently with the
1774 * - spam (string): Spam string from content if any spam is detected by
1776 * - sectionanchor (string): Section anchor for a section save.
1777 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1779 * - redirect (bool): Set if doEditContent is OK. True if resulting
1780 * revision is a redirect.
1781 * @param bool $bot True if edit is being made under the bot right.
1783 * @return Status Status object, possibly with a message, but always with
1784 * one of the AS_* constants in $status->value,
1786 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1787 * various error display idiosyncrasies. There are also lots of cases
1788 * where error metadata is set in the object and retrieved later instead
1789 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1790 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1793 public function internalAttemptSave( &$result, $bot = false ) {
1794 $status = Status
::newGood();
1795 $user = $this->context
->getUser();
1797 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1798 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1799 $status->fatal( 'hookaborted' );
1800 $status->value
= self
::AS_HOOK_ERROR
;
1804 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1805 $status->fatal( 'unicode-support-fail' );
1806 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1810 $request = $this->context
->getRequest();
1811 $spam = $request->getText( 'wpAntispam' );
1812 if ( $spam !== '' ) {
1817 $this->mTitle
->getPrefixedText() .
1818 '" submitted bogus field "' .
1822 $status->fatal( 'spamprotectionmatch', false );
1823 $status->value
= self
::AS_SPAM_ERROR
;
1828 # Construct Content object
1829 $textbox_content = $this->toEditContent( $this->textbox1
);
1830 } catch ( MWContentSerializationException
$ex ) {
1832 'content-failed-to-parse',
1833 $this->contentModel
,
1834 $this->contentFormat
,
1837 $status->value
= self
::AS_PARSE_ERROR
;
1841 # Check image redirect
1842 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1843 $textbox_content->isRedirect() &&
1844 !$user->isAllowed( 'upload' )
1846 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1847 $status->setResult( false, $code );
1853 $match = self
::matchSummarySpamRegex( $this->summary
);
1854 if ( $match === false && $this->section
== 'new' ) {
1855 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1856 # regular summaries, it is added to the actual wikitext.
1857 if ( $this->sectiontitle
!== '' ) {
1858 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1859 $match = self
::matchSpamRegex( $this->sectiontitle
);
1861 # This branch is taken when the "Add Topic" user interface is used, or the API
1862 # is used with the 'summary' parameter.
1863 $match = self
::matchSpamRegex( $this->summary
);
1866 if ( $match === false ) {
1867 $match = self
::matchSpamRegex( $this->textbox1
);
1869 if ( $match !== false ) {
1870 $result['spam'] = $match;
1871 $ip = $request->getIP();
1872 $pdbk = $this->mTitle
->getPrefixedDBkey();
1873 $match = str_replace( "\n", '', $match );
1874 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1875 $status->fatal( 'spamprotectionmatch', $match );
1876 $status->value
= self
::AS_SPAM_ERROR
;
1881 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1883 # Error messages etc. could be handled within the hook...
1884 $status->fatal( 'hookaborted' );
1885 $status->value
= self
::AS_HOOK_ERROR
;
1887 } elseif ( $this->hookError
!= '' ) {
1888 # ...or the hook could be expecting us to produce an error
1889 $status->fatal( 'hookaborted' );
1890 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1894 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1895 // Auto-block user's IP if the account was "hard" blocked
1896 if ( !wfReadOnly() ) {
1897 $user->spreadAnyEditBlock();
1899 # Check block state against master, thus 'false'.
1900 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1904 $this->contentLength
= strlen( $this->textbox1
);
1905 $config = $this->context
->getConfig();
1906 $maxArticleSize = $config->get( 'MaxArticleSize' );
1907 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1908 // Error will be displayed by showEditForm()
1909 $this->tooBig
= true;
1910 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1914 if ( !$user->isAllowed( 'edit' ) ) {
1915 if ( $user->isAnon() ) {
1916 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1919 $status->fatal( 'readonlytext' );
1920 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1925 $changingContentModel = false;
1926 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1927 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1928 $status->fatal( 'editpage-cannot-use-custom-model' );
1929 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1931 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1932 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1935 // Make sure the user can edit the page under the new content model too
1936 $titleWithNewContentModel = clone $this->mTitle
;
1937 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1938 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1939 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1941 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1945 $changingContentModel = true;
1946 $oldContentModel = $this->mTitle
->getContentModel();
1949 if ( $this->changeTags
) {
1950 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1951 $this->changeTags
, $user );
1952 if ( !$changeTagsStatus->isOK() ) {
1953 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1954 return $changeTagsStatus;
1958 if ( wfReadOnly() ) {
1959 $status->fatal( 'readonlytext' );
1960 $status->value
= self
::AS_READ_ONLY_PAGE
;
1963 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1964 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1966 $status->fatal( 'actionthrottledtext' );
1967 $status->value
= self
::AS_RATE_LIMITED
;
1971 # If the article has been deleted while editing, don't save it without
1973 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1974 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1978 # Load the page data from the master. If anything changes in the meantime,
1979 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1980 $this->page
->loadPageData( 'fromdbmaster' );
1981 $new = !$this->page
->exists();
1984 // Late check for create permission, just in case *PARANOIA*
1985 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1986 $status->fatal( 'nocreatetext' );
1987 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1988 wfDebug( __METHOD__
. ": no create permission\n" );
1992 // Don't save a new page if it's blank or if it's a MediaWiki:
1993 // message with content equivalent to default (allow empty pages
1994 // in this case to disable messages, see T52124)
1995 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1996 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1997 $defaultText = $defaultMessageText;
2002 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
2003 $this->blankArticle
= true;
2004 $status->fatal( 'blankarticle' );
2005 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
2009 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2013 $content = $textbox_content;
2015 $result['sectionanchor'] = '';
2016 if ( $this->section
== 'new' ) {
2017 if ( $this->sectiontitle
!== '' ) {
2018 // Insert the section title above the content.
2019 $content = $content->addSectionHeader( $this->sectiontitle
);
2020 } elseif ( $this->summary
!== '' ) {
2021 // Insert the section title above the content.
2022 $content = $content->addSectionHeader( $this->summary
);
2024 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2027 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2031 # Article exists. Check for edit conflict.
2033 $this->page
->clear(); # Force reload of dates, etc.
2034 $timestamp = $this->page
->getTimestamp();
2035 $latest = $this->page
->getLatest();
2037 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2039 // Check editRevId if set, which handles same-second timestamp collisions
2040 if ( $timestamp != $this->edittime
2041 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2043 $this->isConflict
= true;
2044 if ( $this->section
== 'new' ) {
2045 if ( $this->page
->getUserText() == $user->getName() &&
2046 $this->page
->getComment() == $this->newSectionSummary()
2048 // Probably a duplicate submission of a new comment.
2049 // This can happen when CDN resends a request after
2050 // a timeout but the first one actually went through.
2052 . ": duplicate new section submission; trigger edit conflict!\n" );
2054 // New comment; suppress conflict.
2055 $this->isConflict
= false;
2056 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2058 } elseif ( $this->section
== ''
2059 && Revision
::userWasLastToEdit(
2060 DB_MASTER
, $this->mTitle
->getArticleID(),
2061 $user->getId(), $this->edittime
2064 # Suppress edit conflict with self, except for section edits where merging is required.
2065 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2066 $this->isConflict
= false;
2070 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2071 if ( $this->sectiontitle
!== '' ) {
2072 $sectionTitle = $this->sectiontitle
;
2074 $sectionTitle = $this->summary
;
2079 if ( $this->isConflict
) {
2081 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2082 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2083 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2084 // ...or disable section editing for non-current revisions (not exposed anyway).
2085 if ( $this->editRevId
!== null ) {
2086 $content = $this->page
->replaceSectionAtRev(
2093 $content = $this->page
->replaceSectionContent(
2101 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2102 $content = $this->page
->replaceSectionContent(
2109 if ( is_null( $content ) ) {
2110 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2111 $this->isConflict
= true;
2112 $content = $textbox_content; // do not try to merge here!
2113 } elseif ( $this->isConflict
) {
2115 if ( $this->mergeChangesIntoContent( $content ) ) {
2116 // Successful merge! Maybe we should tell the user the good news?
2117 $this->isConflict
= false;
2118 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2120 $this->section
= '';
2121 $this->textbox1
= ContentHandler
::getContentText( $content );
2122 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2126 if ( $this->isConflict
) {
2127 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2131 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2135 if ( $this->section
== 'new' ) {
2136 // Handle the user preference to force summaries here
2137 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2138 $this->missingSummary
= true;
2139 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2140 $status->value
= self
::AS_SUMMARY_NEEDED
;
2144 // Do not allow the user to post an empty comment
2145 if ( $this->textbox1
== '' ) {
2146 $this->missingComment
= true;
2147 $status->fatal( 'missingcommenttext' );
2148 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2151 } elseif ( !$this->allowBlankSummary
2152 && !$content->equals( $this->getOriginalContent( $user ) )
2153 && !$content->isRedirect()
2154 && md5( $this->summary
) == $this->autoSumm
2156 $this->missingSummary
= true;
2157 $status->fatal( 'missingsummary' );
2158 $status->value
= self
::AS_SUMMARY_NEEDED
;
2163 $sectionanchor = '';
2164 if ( $this->section
== 'new' ) {
2165 $this->summary
= $this->newSectionSummary( $sectionanchor );
2166 } elseif ( $this->section
!= '' ) {
2167 # Try to get a section anchor from the section source, redirect
2168 # to edited section if header found.
2169 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2170 # for duplicate heading checking and maybe parsing.
2171 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2172 # We can't deal with anchors, includes, html etc in the header for now,
2173 # headline would need to be parsed to improve this.
2174 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2175 $sectionanchor = $this->guessSectionName( $matches[2] );
2178 $result['sectionanchor'] = $sectionanchor;
2180 // Save errors may fall down to the edit form, but we've now
2181 // merged the section into full text. Clear the section field
2182 // so that later submission of conflict forms won't try to
2183 // replace that into a duplicated mess.
2184 $this->textbox1
= $this->toEditText( $content );
2185 $this->section
= '';
2187 $status->value
= self
::AS_SUCCESS_UPDATE
;
2190 if ( !$this->allowSelfRedirect
2191 && $content->isRedirect()
2192 && $content->getRedirectTarget()->equals( $this->getTitle() )
2194 // If the page already redirects to itself, don't warn.
2195 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2196 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2197 $this->selfRedirect
= true;
2198 $status->fatal( 'selfredirect' );
2199 $status->value
= self
::AS_SELF_REDIRECT
;
2204 // Check for length errors again now that the section is merged in
2205 $this->contentLength
= strlen( $this->toEditText( $content ) );
2206 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2207 $this->tooBig
= true;
2208 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2212 $flags = EDIT_AUTOSUMMARY |
2213 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2214 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2215 ( $bot ? EDIT_FORCE_BOT
: 0 );
2217 $doEditStatus = $this->page
->doEditContent(
2223 $content->getDefaultFormat(),
2228 if ( !$doEditStatus->isOK() ) {
2229 // Failure from doEdit()
2230 // Show the edit conflict page for certain recognized errors from doEdit(),
2231 // but don't show it for errors from extension hooks
2232 $errors = $doEditStatus->getErrorsArray();
2233 if ( in_array( $errors[0][0],
2234 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2236 $this->isConflict
= true;
2237 // Destroys data doEdit() put in $status->value but who cares
2238 $doEditStatus->value
= self
::AS_END
;
2240 return $doEditStatus;
2243 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2244 if ( $result['nullEdit'] ) {
2245 // We don't know if it was a null edit until now, so increment here
2246 $user->pingLimiter( 'linkpurge' );
2248 $result['redirect'] = $content->isRedirect();
2250 $this->updateWatchlist();
2252 // If the content model changed, add a log entry
2253 if ( $changingContentModel ) {
2254 $this->addContentModelChangeLogEntry(
2256 $new ?
false : $oldContentModel,
2257 $this->contentModel
,
2267 * @param string|false $oldModel false if the page is being newly created
2268 * @param string $newModel
2269 * @param string $reason
2271 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2272 $new = $oldModel === false;
2273 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2274 $log->setPerformer( $user );
2275 $log->setTarget( $this->mTitle
);
2276 $log->setComment( $reason );
2277 $log->setParameters( [
2278 '4::oldmodel' => $oldModel,
2279 '5::newmodel' => $newModel
2281 $logid = $log->insert();
2282 $log->publish( $logid );
2286 * Register the change of watch status
2288 protected function updateWatchlist() {
2289 $user = $this->context
->getUser();
2290 if ( !$user->isLoggedIn() ) {
2294 $title = $this->mTitle
;
2295 $watch = $this->watchthis
;
2296 // Do this in its own transaction to reduce contention...
2297 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2298 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2299 return; // nothing to change
2301 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2306 * Attempts to do 3-way merge of edit content with a base revision
2307 * and current content, in case of edit conflict, in whichever way appropriate
2308 * for the content type.
2312 * @param Content $editContent
2316 private function mergeChangesIntoContent( &$editContent ) {
2317 $db = wfGetDB( DB_MASTER
);
2319 // This is the revision the editor started from
2320 $baseRevision = $this->getBaseRevision();
2321 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2323 if ( is_null( $baseContent ) ) {
2327 // The current state, we want to merge updates into it
2328 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2329 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2331 if ( is_null( $currentContent ) ) {
2335 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2337 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2340 $editContent = $result;
2341 // Update parentRevId to what we just merged.
2342 $this->parentRevId
= $currentRevision->getId();
2350 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2351 * one might think of X as the "base revision", which is NOT what this returns.
2352 * @return Revision Current version when the edit was started
2354 public function getBaseRevision() {
2355 if ( !$this->mBaseRevision
) {
2356 $db = wfGetDB( DB_MASTER
);
2357 $this->mBaseRevision
= $this->editRevId
2358 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2359 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2361 return $this->mBaseRevision
;
2365 * Check given input text against $wgSpamRegex, and return the text of the first match.
2367 * @param string $text
2369 * @return string|bool Matching string or false
2371 public static function matchSpamRegex( $text ) {
2372 global $wgSpamRegex;
2373 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2374 $regexes = (array)$wgSpamRegex;
2375 return self
::matchSpamRegexInternal( $text, $regexes );
2379 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2381 * @param string $text
2383 * @return string|bool Matching string or false
2385 public static function matchSummarySpamRegex( $text ) {
2386 global $wgSummarySpamRegex;
2387 $regexes = (array)$wgSummarySpamRegex;
2388 return self
::matchSpamRegexInternal( $text, $regexes );
2392 * @param string $text
2393 * @param array $regexes
2394 * @return bool|string
2396 protected static function matchSpamRegexInternal( $text, $regexes ) {
2397 foreach ( $regexes as $regex ) {
2399 if ( preg_match( $regex, $text, $matches ) ) {
2406 public function setHeaders() {
2407 $out = $this->context
->getOutput();
2409 $out->addModules( 'mediawiki.action.edit' );
2410 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2411 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2413 $user = $this->context
->getUser();
2414 if ( $user->getOption( 'showtoolbar' ) ) {
2415 // The addition of default buttons is handled by getEditToolbar() which
2416 // has its own dependency on this module. The call here ensures the module
2417 // is loaded in time (it has position "top") for other modules to register
2418 // buttons (e.g. extensions, gadgets, user scripts).
2419 $out->addModules( 'mediawiki.toolbar' );
2422 if ( $user->getOption( 'uselivepreview' ) ) {
2423 $out->addModules( 'mediawiki.action.edit.preview' );
2426 if ( $user->getOption( 'useeditwarning' ) ) {
2427 $out->addModules( 'mediawiki.action.edit.editWarning' );
2430 # Enabled article-related sidebar, toplinks, etc.
2431 $out->setArticleRelated( true );
2433 $contextTitle = $this->getContextTitle();
2434 if ( $this->isConflict
) {
2435 $msg = 'editconflict';
2436 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2437 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2439 $msg = $contextTitle->exists()
2440 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2441 && $contextTitle->getDefaultMessageText() !== false
2447 # Use the title defined by DISPLAYTITLE magic word when present
2448 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2449 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2450 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2451 if ( $displayTitle === false ) {
2452 $displayTitle = $contextTitle->getPrefixedText();
2454 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2455 # Transmit the name of the message to JavaScript for live preview
2456 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2457 $out->addJsConfigVars( [
2458 'wgEditMessage' => $msg,
2459 'wgAjaxEditStash' => $this->context
->getConfig()->get( 'AjaxEditStash' ),
2464 * Show all applicable editing introductions
2466 protected function showIntro() {
2467 if ( $this->suppressIntro
) {
2471 $out = $this->context
->getOutput();
2472 $namespace = $this->mTitle
->getNamespace();
2474 if ( $namespace == NS_MEDIAWIKI
) {
2475 # Show a warning if editing an interface message
2476 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2477 # If this is a default message (but not css or js),
2478 # show a hint that it is translatable on translatewiki.net
2479 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2480 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2482 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2483 if ( $defaultMessageText !== false ) {
2484 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2485 'translateinterface' );
2488 } elseif ( $namespace == NS_FILE
) {
2489 # Show a hint to shared repo
2490 $file = wfFindFile( $this->mTitle
);
2491 if ( $file && !$file->isLocal() ) {
2492 $descUrl = $file->getDescriptionUrl();
2493 # there must be a description url to show a hint to shared repo
2495 if ( !$this->mTitle
->exists() ) {
2496 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2497 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2500 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2501 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2508 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2509 # Show log extract when the user is currently blocked
2510 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2511 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2512 $user = User
::newFromName( $username, false /* allow IP users */ );
2513 $ip = User
::isIP( $username );
2514 $block = Block
::newFromTarget( $user, $user );
2515 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2516 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2517 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2518 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2519 # Show log extract if the user is currently blocked
2520 LogEventsList
::showLogExtract(
2523 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2527 'showIfEmpty' => false,
2529 'blocked-notice-logextract',
2530 $user->getName() # Support GENDER in notice
2536 # Try to add a custom edit intro, or use the standard one if this is not possible.
2537 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2538 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2539 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2541 if ( $this->context
->getUser()->isLoggedIn() ) {
2543 // Suppress the external link icon, consider the help url an internal one
2544 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2552 // Suppress the external link icon, consider the help url an internal one
2553 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2555 'newarticletextanon',
2561 # Give a notice if the user is editing a deleted/moved page...
2562 if ( !$this->mTitle
->exists() ) {
2563 $dbr = wfGetDB( DB_REPLICA
);
2565 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2569 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2570 'showIfEmpty' => false,
2571 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2578 * Attempt to show a custom editing introduction, if supplied
2582 protected function showCustomIntro() {
2583 if ( $this->editintro
) {
2584 $title = Title
::newFromText( $this->editintro
);
2585 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2586 // Added using template syntax, to take <noinclude>'s into account.
2587 $this->context
->getOutput()->addWikiTextTitleTidy(
2588 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2598 * Gets an editable textual representation of $content.
2599 * The textual representation can be turned by into a Content object by the
2600 * toEditContent() method.
2602 * If $content is null or false or a string, $content is returned unchanged.
2604 * If the given Content object is not of a type that can be edited using
2605 * the text base EditPage, an exception will be raised. Set
2606 * $this->allowNonTextContent to true to allow editing of non-textual
2609 * @param Content|null|bool|string $content
2610 * @return string The editable text form of the content.
2612 * @throws MWException If $content is not an instance of TextContent and
2613 * $this->allowNonTextContent is not true.
2615 protected function toEditText( $content ) {
2616 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2620 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2621 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2624 return $content->serialize( $this->contentFormat
);
2628 * Turns the given text into a Content object by unserializing it.
2630 * If the resulting Content object is not of a type that can be edited using
2631 * the text base EditPage, an exception will be raised. Set
2632 * $this->allowNonTextContent to true to allow editing of non-textual
2635 * @param string|null|bool $text Text to unserialize
2636 * @return Content|bool|null The content object created from $text. If $text was false
2637 * or null, false resp. null will be returned instead.
2639 * @throws MWException If unserializing the text results in a Content
2640 * object that is not an instance of TextContent and
2641 * $this->allowNonTextContent is not true.
2643 protected function toEditContent( $text ) {
2644 if ( $text === false ||
$text === null ) {
2648 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2649 $this->contentModel
, $this->contentFormat
);
2651 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2652 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2659 * Send the edit form and related headers to OutputPage
2660 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2661 * during form output near the top, for captchas and the like.
2663 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2664 * use the EditPage::showEditForm:fields hook instead.
2666 public function showEditForm( $formCallback = null ) {
2667 # need to parse the preview early so that we know which templates are used,
2668 # otherwise users with "show preview after edit box" will get a blank list
2669 # we parse this near the beginning so that setHeaders can do the title
2670 # setting work instead of leaving it in getPreviewText
2671 $previewOutput = '';
2672 if ( $this->formtype
== 'preview' ) {
2673 $previewOutput = $this->getPreviewText();
2676 $out = $this->context
->getOutput();
2678 // Avoid PHP 7.1 warning of passing $this by reference
2680 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2682 $this->setHeaders();
2684 $this->addTalkPageText();
2685 $this->addEditNotices();
2687 if ( !$this->isConflict
&&
2688 $this->section
!= '' &&
2689 !$this->isSectionEditSupported() ) {
2690 // We use $this->section to much before this and getVal('wgSection') directly in other places
2691 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2692 // Someone is welcome to try refactoring though
2693 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2697 $this->showHeader();
2699 $out->addHTML( $this->editFormPageTop
);
2701 $user = $this->context
->getUser();
2702 if ( $user->getOption( 'previewontop' ) ) {
2703 $this->displayPreviewArea( $previewOutput, true );
2706 $out->addHTML( $this->editFormTextTop
);
2708 $showToolbar = true;
2709 if ( $this->wasDeletedSinceLastEdit() ) {
2710 if ( $this->formtype
== 'save' ) {
2711 // Hide the toolbar and edit area, user can click preview to get it back
2712 // Add an confirmation checkbox and explanation.
2713 $showToolbar = false;
2715 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2716 'deletedwhileediting' );
2720 // @todo add EditForm plugin interface and use it here!
2721 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2722 $out->addHTML( Html
::openElement(
2725 'class' => 'mw-editform',
2726 'id' => self
::EDITFORM_ID
,
2727 'name' => self
::EDITFORM_ID
,
2729 'action' => $this->getActionURL( $this->getContextTitle() ),
2730 'enctype' => 'multipart/form-data'
2734 if ( is_callable( $formCallback ) ) {
2735 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2736 call_user_func_array( $formCallback, [ &$out ] );
2739 // Add a check for Unicode support
2740 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2742 // Add an empty field to trip up spambots
2744 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2747 [ 'for' => 'wpAntispam' ],
2748 $this->context
->msg( 'simpleantispam-label' )->parse()
2754 'name' => 'wpAntispam',
2755 'id' => 'wpAntispam',
2759 . Xml
::closeElement( 'div' )
2762 // Avoid PHP 7.1 warning of passing $this by reference
2764 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2766 // Put these up at the top to ensure they aren't lost on early form submission
2767 $this->showFormBeforeText();
2769 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2770 $username = $this->lastDelete
->user_name
;
2771 $comment = CommentStore
::newKey( 'log_comment' )->getComment( $this->lastDelete
)->text
;
2773 // It is better to not parse the comment at all than to have templates expanded in the middle
2774 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2775 $key = $comment === ''
2776 ?
'confirmrecreate-noreason'
2777 : 'confirmrecreate';
2779 '<div class="mw-confirm-recreate">' .
2780 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2781 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2782 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2788 # When the summary is hidden, also hide them on preview/show changes
2789 if ( $this->nosummary
) {
2790 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2793 # If a blank edit summary was previously provided, and the appropriate
2794 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2795 # user being bounced back more than once in the event that a summary
2798 # For a bit more sophisticated detection of blank summaries, hash the
2799 # automatic one and pass that in the hidden field wpAutoSummary.
2800 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2801 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2804 if ( $this->undidRev
) {
2805 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2808 if ( $this->selfRedirect
) {
2809 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2812 if ( $this->hasPresetSummary
) {
2813 // If a summary has been preset using &summary= we don't want to prompt for
2814 // a different summary. Only prompt for a summary if the summary is blanked.
2816 $this->autoSumm
= md5( '' );
2819 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2820 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2822 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2823 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2825 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2826 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2830 if ( $this->section
== 'new' ) {
2831 $this->showSummaryInput( true, $this->summary
);
2832 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2835 $out->addHTML( $this->editFormTextBeforeContent
);
2836 if ( $this->isConflict
) {
2837 // In an edit conflict, we turn textbox2 into the user's text,
2838 // and textbox1 into the stored version
2839 $this->textbox2
= $this->textbox1
;
2841 $content = $this->getCurrentContent();
2842 $this->textbox1
= $this->toEditText( $content );
2844 $editConflictHelper = $this->getEditConflictHelper();
2845 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2846 $editConflictHelper->setContentModel( $this->contentModel
);
2847 $editConflictHelper->setContentFormat( $this->contentFormat
);
2848 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2851 if ( !$this->mTitle
->isCssJsSubpage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2852 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2855 if ( $this->blankArticle
) {
2856 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2859 if ( $this->isConflict
) {
2860 // In an edit conflict bypass the overridable content form method
2861 // and fallback to the raw wpTextbox1 since editconflicts can't be
2862 // resolved between page source edits and custom ui edits using the
2864 $this->showTextbox1();
2865 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2867 $this->showContentForm();
2870 $out->addHTML( $this->editFormTextAfterContent
);
2872 $this->showStandardInputs();
2874 $this->showFormAfterText();
2876 $this->showTosSummary();
2878 $this->showEditTools();
2880 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2882 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2884 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2885 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2887 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2888 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2890 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2892 if ( $this->isConflict
) {
2894 $this->showConflict();
2895 } catch ( MWContentSerializationException
$ex ) {
2896 // this can't really happen, but be nice if it does.
2897 $msg = $this->context
->msg(
2898 'content-failed-to-parse',
2899 $this->contentModel
,
2900 $this->contentFormat
,
2903 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2907 // Set a hidden field so JS knows what edit form mode we are in
2908 if ( $this->isConflict
) {
2910 } elseif ( $this->preview
) {
2912 } elseif ( $this->diff
) {
2917 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2919 // Marker for detecting truncated form data. This must be the last
2920 // parameter sent in order to be of use, so do not move me.
2921 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2922 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2924 if ( !$user->getOption( 'previewontop' ) ) {
2925 $this->displayPreviewArea( $previewOutput, false );
2930 * Wrapper around TemplatesOnThisPageFormatter to make
2931 * a "templates on this page" list.
2933 * @param Title[] $templates
2934 * @return string HTML
2936 public function makeTemplatesOnThisPageList( array $templates ) {
2937 $templateListFormatter = new TemplatesOnThisPageFormatter(
2938 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2941 // preview if preview, else section if section, else false
2943 if ( $this->preview
) {
2945 } elseif ( $this->section
!= '' ) {
2949 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2950 $templateListFormatter->format( $templates, $type )
2955 * Extract the section title from current section text, if any.