3 * User interface for page editing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\ScopedCallback
;
28 * The edit page/HTML interface (split from Article)
29 * The actual database and text munging is still in Article,
30 * but it should get easier to call those from alternate
33 * EditPage cares about two distinct titles:
34 * $this->mContextTitle is the page that forms submit to, links point to,
35 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
36 * page in the database that is actually being edited. These are
37 * usually the same, but they are now allowed to be different.
39 * Surgeon General's Warning: prolonged exposure to this class is known to cause
40 * headaches, which may be fatal.
44 * Used for Unicode support checks
46 const UNICODE_CHECK
= 'β³π²β₯πππΎπΈβ΄πΉβ―';
49 * Status: Article successfully updated
51 const AS_SUCCESS_UPDATE
= 200;
54 * Status: Article successfully created
56 const AS_SUCCESS_NEW_ARTICLE
= 201;
59 * Status: Article update aborted by a hook function
61 const AS_HOOK_ERROR
= 210;
64 * Status: A hook function returned an error
66 const AS_HOOK_ERROR_EXPECTED
= 212;
69 * Status: User is blocked from editing this page
71 const AS_BLOCKED_PAGE_FOR_USER
= 215;
74 * Status: Content too big (> $wgMaxArticleSize)
76 const AS_CONTENT_TOO_BIG
= 216;
79 * Status: this anonymous user is not allowed to edit this page
81 const AS_READ_ONLY_PAGE_ANON
= 218;
84 * Status: this logged in user is not allowed to edit this page
86 const AS_READ_ONLY_PAGE_LOGGED
= 219;
89 * Status: wiki is in readonly mode (wfReadOnly() == true)
91 const AS_READ_ONLY_PAGE
= 220;
94 * Status: rate limiter for action 'edit' was tripped
96 const AS_RATE_LIMITED
= 221;
99 * Status: article was deleted while editing and param wpRecreate == false or form
102 const AS_ARTICLE_WAS_DELETED
= 222;
105 * Status: user tried to create this page, but is not allowed to do that
106 * ( Title->userCan('create') == false )
108 const AS_NO_CREATE_PERMISSION
= 223;
111 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
113 const AS_BLANK_ARTICLE
= 224;
116 * Status: (non-resolvable) edit conflict
118 const AS_CONFLICT_DETECTED
= 225;
121 * Status: no edit summary given and the user has forceeditsummary set and the user is not
122 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
124 const AS_SUMMARY_NEEDED
= 226;
127 * Status: user tried to create a new section without content
129 const AS_TEXTBOX_EMPTY
= 228;
132 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
134 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
137 * Status: WikiPage::doEdit() was unsuccessful
142 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
144 const AS_SPAM_ERROR
= 232;
147 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
149 const AS_IMAGE_REDIRECT_ANON
= 233;
152 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
154 const AS_IMAGE_REDIRECT_LOGGED
= 234;
157 * Status: user tried to modify the content model, but is not allowed to do that
158 * ( User::isAllowed('editcontentmodel') == false )
160 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
163 * Status: user tried to create self-redirect (redirect to the same article) and
164 * wpIgnoreSelfRedirect == false
166 const AS_SELF_REDIRECT
= 236;
169 * Status: an error relating to change tagging. Look at the message key for
172 const AS_CHANGE_TAG_ERROR
= 237;
175 * Status: can't parse content
177 const AS_PARSE_ERROR
= 240;
180 * Status: when changing the content model is disallowed due to
181 * $wgContentHandlerUseDB being false
183 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
186 * Status: edit rejected because browser doesn't support Unicode.
188 const AS_UNICODE_NOT_SUPPORTED
= 242;
191 * HTML id and name for the beginning of the edit form.
193 const EDITFORM_ID
= 'editform';
196 * Prefix of key for cookie used to pass post-edit state.
197 * The revision id edited is added after this
199 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
202 * Duration of PostEdit cookie, in seconds.
203 * The cookie will be removed instantly if the JavaScript runs.
205 * Otherwise, though, we don't want the cookies to accumulate.
206 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
207 * limit of only 20 cookies per domain. This still applies at least to some
208 * versions of IE without full updates:
209 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
211 * A value of 20 minutes should be enough to take into account slow loads and minor
212 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
214 const POST_EDIT_COOKIE_DURATION
= 1200;
217 * @deprecated for public usage since 1.30 use EditPage::getArticle()
225 * @deprecated for public usage since 1.30 use EditPage::getTitle()
230 /** @var null|Title */
231 private $mContextTitle = null;
234 public $action = 'submit';
237 public $isConflict = false;
240 * @deprecated since 1.30 use Title::isCssJsSubpage()
243 public $isCssJsSubpage = false;
246 * @deprecated since 1.30 use Title::isCssSubpage()
249 public $isCssSubpage = false;
252 * @deprecated since 1.30 use Title::isJsSubpage()
255 public $isJsSubpage = false;
258 * @deprecated since 1.30
261 public $isWrongCaseCssJsPage = false;
263 /** @var bool New page or new section */
264 public $isNew = false;
267 public $deletedSinceEdit;
275 /** @var bool|stdClass */
279 public $mTokenOk = false;
282 public $mTokenOkExceptSuffix = false;
285 public $mTriedSave = false;
288 public $incompleteForm = false;
291 public $tooBig = false;
294 public $missingComment = false;
297 public $missingSummary = false;
300 public $allowBlankSummary = false;
303 protected $blankArticle = false;
306 protected $allowBlankArticle = false;
309 protected $selfRedirect = false;
312 protected $allowSelfRedirect = false;
315 public $autoSumm = '';
318 public $hookError = '';
320 /** @var ParserOutput */
321 public $mParserOutput;
323 /** @var bool Has a summary been preset using GET parameter &summary= ? */
324 public $hasPresetSummary = false;
326 /** @var Revision|bool */
327 public $mBaseRevision = false;
330 public $mShowSummaryField = true;
335 public $save = false;
338 public $preview = false;
341 public $diff = false;
344 public $minoredit = false;
347 public $watchthis = false;
350 public $recreate = false;
353 public $textbox1 = '';
356 public $textbox2 = '';
359 public $summary = '';
362 public $nosummary = false;
365 public $edittime = '';
368 private $editRevId = null;
371 public $section = '';
374 public $sectiontitle = '';
377 public $starttime = '';
383 public $parentRevId = 0;
386 public $editintro = '';
389 public $scrolltop = null;
395 public $contentModel;
397 /** @var null|string */
398 public $contentFormat = null;
400 /** @var null|array */
401 private $changeTags = null;
403 # Placeholders for text injection by hooks (must be HTML)
404 # extensions should take care to _append_ to the present value
406 /** @var string Before even the preview */
407 public $editFormPageTop = '';
408 public $editFormTextTop = '';
409 public $editFormTextBeforeContent = '';
410 public $editFormTextAfterWarn = '';
411 public $editFormTextAfterTools = '';
412 public $editFormTextBottom = '';
413 public $editFormTextAfterContent = '';
414 public $previewTextAfterContent = '';
415 public $mPreloadContent = null;
417 /* $didSave should be set to true whenever an article was successfully altered. */
418 public $didSave = false;
419 public $undidRev = 0;
421 public $suppressIntro = false;
427 protected $contentLength = false;
430 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
432 private $enableApiEditOverride = false;
435 * @var IContextSource
440 * @var bool Whether an old revision is edited
442 private $isOldRev = false;
445 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
447 private $unicodeCheck;
450 * @param Article $article
452 public function __construct( Article
$article ) {
453 $this->mArticle
= $article;
454 $this->page
= $article->getPage(); // model object
455 $this->mTitle
= $article->getTitle();
456 $this->context
= $article->getContext();
458 $this->contentModel
= $this->mTitle
->getContentModel();
460 $handler = ContentHandler
::getForModelID( $this->contentModel
);
461 $this->contentFormat
= $handler->getDefaultFormat();
467 public function getArticle() {
468 return $this->mArticle
;
473 * @return IContextSource
475 public function getContext() {
476 return $this->context
;
483 public function getTitle() {
484 return $this->mTitle
;
488 * Set the context Title object
490 * @param Title|null $title Title object or null
492 public function setContextTitle( $title ) {
493 $this->mContextTitle
= $title;
497 * Get the context title object.
498 * If not set, $wgTitle will be returned. This behavior might change in
499 * the future to return $this->mTitle instead.
503 public function getContextTitle() {
504 if ( is_null( $this->mContextTitle
) ) {
507 __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.'
512 return $this->mContextTitle
;
517 * Check if the edit page is using OOUI controls
518 * @return bool Always true
519 * @deprecated since 1.30
521 public function isOouiEnabled() {
526 * Returns if the given content model is editable.
528 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
530 * @throws MWException If $modelId has no known handler
532 public function isSupportedContentModel( $modelId ) {
533 return $this->enableApiEditOverride
=== true ||
534 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
538 * Allow editing of content that supports API direct editing, but not general
539 * direct editing. Set to false by default.
541 * @param bool $enableOverride
543 public function setApiEditOverride( $enableOverride ) {
544 $this->enableApiEditOverride
= $enableOverride;
548 * @deprecated since 1.29, call edit directly
550 public function submit() {
551 wfDeprecated( __METHOD__
, '1.29' );
556 * This is the function that gets called for "action=edit". It
557 * sets up various member variables, then passes execution to
558 * another function, usually showEditForm()
560 * The edit form is self-submitting, so that when things like
561 * preview and edit conflicts occur, we get the same form back
562 * with the extra stuff added. Only when the final submission
563 * is made and all is well do we actually save and redirect to
564 * the newly-edited page.
566 public function edit() {
567 // Allow extensions to modify/prevent this form or submission
568 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
572 wfDebug( __METHOD__
. ": enter\n" );
574 $request = $this->context
->getRequest();
575 // If they used redlink=1 and the page exists, redirect to the main article
576 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
577 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
581 $this->importFormData( $request );
582 $this->firsttime
= false;
584 if ( wfReadOnly() && $this->save
) {
587 $this->preview
= true;
591 $this->formtype
= 'save';
592 } elseif ( $this->preview
) {
593 $this->formtype
= 'preview';
594 } elseif ( $this->diff
) {
595 $this->formtype
= 'diff';
596 } else { # First time through
597 $this->firsttime
= true;
598 if ( $this->previewOnOpen() ) {
599 $this->formtype
= 'preview';
601 $this->formtype
= 'initial';
605 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
607 wfDebug( __METHOD__
. ": User can't edit\n" );
608 // Auto-block user's IP if the account was "hard" blocked
609 if ( !wfReadOnly() ) {
610 DeferredUpdates
::addCallableUpdate( function () {
611 $this->context
->getUser()->spreadAnyEditBlock();
614 $this->displayPermissionsError( $permErrors );
619 $revision = $this->mArticle
->getRevisionFetched();
620 // Disallow editing revisions with content models different from the current one
621 // Undo edits being an exception in order to allow reverting content model changes.
623 && $revision->getContentModel() !== $this->contentModel
626 if ( $this->undidRev
) {
627 $undidRevObj = Revision
::newFromId( $this->undidRev
);
628 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
630 if ( !$this->undidRev
632 ||
$prevRev->getContentModel() !== $this->contentModel
634 $this->displayViewSourcePage(
635 $this->getContentObject(),
637 'contentmodelediterror',
638 $revision->getContentModel(),
646 $this->isConflict
= false;
647 // css / js subpages of user pages get a special treatment
648 // The following member variables are deprecated since 1.30,
649 // the functions should be used instead.
650 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
651 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
652 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
653 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
655 # Show applicable editing introductions
656 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
660 # Attempt submission here. This will check for edit conflicts,
661 # and redundantly check for locked database, blocked IPs, etc.
662 # that edit() already checked just in case someone tries to sneak
663 # in the back door with a hand-edited submission URL.
665 if ( 'save' == $this->formtype
) {
666 $resultDetails = null;
667 $status = $this->attemptSave( $resultDetails );
668 if ( !$this->handleStatus( $status, $resultDetails ) ) {
673 # First time through: get contents, set time for conflict
675 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
676 if ( $this->initialiseForm() === false ) {
677 $this->noSuchSectionPage();
681 if ( !$this->mTitle
->getArticleID() ) {
682 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
684 Hooks
::run( 'EditFormInitialText', [ $this ] );
689 $this->showEditForm();
693 * @param string $rigor Same format as Title::getUserPermissionErrors()
696 protected function getEditPermissionErrors( $rigor = 'secure' ) {
697 $user = $this->context
->getUser();
698 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
699 # Can this title be created?
700 if ( !$this->mTitle
->exists() ) {
701 $permErrors = array_merge(
704 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
709 # Ignore some permissions errors when a user is just previewing/viewing diffs
711 foreach ( $permErrors as $error ) {
712 if ( ( $this->preview ||
$this->diff
)
714 $error[0] == 'blockedtext' ||
715 $error[0] == 'autoblockedtext' ||
716 $error[0] == 'systemblockedtext'
722 $permErrors = wfArrayDiff2( $permErrors, $remove );
728 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
729 * but with the following differences:
730 * - If redlink=1, the user will be redirected to the page
731 * - If there is content to display or the error occurs while either saving,
732 * previewing or showing the difference, it will be a
733 * "View source for ..." page displaying the source code after the error message.
736 * @param array $permErrors Array of permissions errors, as returned by
737 * Title::getUserPermissionsErrors().
738 * @throws PermissionsError
740 protected function displayPermissionsError( array $permErrors ) {
741 $out = $this->context
->getOutput();
742 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
743 // The edit page was reached via a red link.
744 // Redirect to the article page and let them click the edit tab if
745 // they really want a permission error.
746 $out->redirect( $this->mTitle
->getFullURL() );
750 $content = $this->getContentObject();
752 # Use the normal message if there's nothing to display
753 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
754 $action = $this->mTitle
->exists() ?
'edit' :
755 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
756 throw new PermissionsError( $action, $permErrors );
759 $this->displayViewSourcePage(
761 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
766 * Display a read-only View Source page
767 * @param Content $content content object
768 * @param string $errorMessage additional wikitext error message to display
770 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
771 $out = $this->context
->getOutput();
772 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
774 $out->setRobotPolicy( 'noindex,nofollow' );
775 $out->setPageTitle( $this->context
->msg(
777 $this->getContextTitle()->getPrefixedText()
779 $out->addBacklinkSubtitle( $this->getContextTitle() );
780 $out->addHTML( $this->editFormPageTop
);
781 $out->addHTML( $this->editFormTextTop
);
783 if ( $errorMessage !== '' ) {
784 $out->addWikiText( $errorMessage );
785 $out->addHTML( "<hr />\n" );
788 # If the user made changes, preserve them when showing the markup
789 # (This happens when a user is blocked during edit, for instance)
790 if ( !$this->firsttime
) {
791 $text = $this->textbox1
;
792 $out->addWikiMsg( 'viewyourtext' );
795 $text = $this->toEditText( $content );
796 } catch ( MWException
$e ) {
797 # Serialize using the default format if the content model is not supported
798 # (e.g. for an old revision with a different model)
799 $text = $content->serialize();
801 $out->addWikiMsg( 'viewsourcetext' );
804 $out->addHTML( $this->editFormTextBeforeContent
);
805 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
806 $out->addHTML( $this->editFormTextAfterContent
);
808 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
810 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
812 $out->addHTML( $this->editFormTextBottom
);
813 if ( $this->mTitle
->exists() ) {
814 $out->returnToMain( null, $this->mTitle
);
819 * Should we show a preview when the edit form is first shown?
823 protected function previewOnOpen() {
824 $previewOnOpenNamespaces = $this->context
->getConfig()->get( 'PreviewOnOpenNamespaces' );
825 $request = $this->context
->getRequest();
826 if ( $request->getVal( 'preview' ) == 'yes' ) {
827 // Explicit override from request
829 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
830 // Explicit override from request
832 } elseif ( $this->section
== 'new' ) {
833 // Nothing *to* preview for new sections
835 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
836 && $this->context
->getUser()->getOption( 'previewonfirst' )
838 // Standard preference behavior
840 } elseif ( !$this->mTitle
->exists()
841 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
842 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
844 // Categories are special
852 * Checks whether the user entered a skin name in uppercase,
853 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
857 protected function isWrongCaseCssJsPage() {
858 if ( $this->mTitle
->isCssJsSubpage() ) {
859 $name = $this->mTitle
->getSkinFromCssJsSubpage();
860 $skins = array_merge(
861 array_keys( Skin
::getSkinNames() ),
864 return !in_array( $name, $skins )
865 && in_array( strtolower( $name ), $skins );
872 * Returns whether section editing is supported for the current page.
873 * Subclasses may override this to replace the default behavior, which is
874 * to check ContentHandler::supportsSections.
876 * @return bool True if this edit page supports sections, false otherwise.
878 protected function isSectionEditSupported() {
879 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
880 return $contentHandler->supportsSections();
884 * This function collects the form data and uses it to populate various member variables.
885 * @param WebRequest &$request
886 * @throws ErrorPageError
888 public function importFormData( &$request ) {
889 # Section edit can come from either the form or a link
890 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
892 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
893 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
896 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
898 if ( $request->wasPosted() ) {
899 # These fields need to be checked for encoding.
900 # Also remove trailing whitespace, but don't remove _initial_
901 # whitespace from the text boxes. This may be significant formatting.
902 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
903 if ( !$request->getCheck( 'wpTextbox2' ) ) {
904 // Skip this if wpTextbox2 has input, it indicates that we came
905 // from a conflict page with raw page text, not a custom form
906 // modified by subclasses
907 $textbox1 = $this->importContentFormData( $request );
908 if ( $textbox1 !== null ) {
909 $this->textbox1
= $textbox1;
913 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
915 $this->summary
= $request->getText( 'wpSummary' );
917 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
918 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
920 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
922 # Treat sectiontitle the same way as summary.
923 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
924 # currently doing double duty as both edit summary and section title. Right now this
925 # is just to allow API edits to work around this limitation, but this should be
926 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
927 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
928 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
930 $this->edittime
= $request->getVal( 'wpEdittime' );
931 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
932 $this->starttime
= $request->getVal( 'wpStarttime' );
934 $undidRev = $request->getInt( 'wpUndidRevision' );
936 $this->undidRev
= $undidRev;
939 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
941 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
942 // wpTextbox1 field is missing, possibly due to being "too big"
943 // according to some filter rules such as Suhosin's setting for
944 // suhosin.request.max_value_length (d'oh)
945 $this->incompleteForm
= true;
947 // If we receive the last parameter of the request, we can fairly
948 // claim the POST request has not been truncated.
950 // TODO: softened the check for cutover. Once we determine
951 // that it is safe, we should complete the transition by
952 // removing the "edittime" clause.
953 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
954 && is_null( $this->edittime
) );
956 if ( $this->incompleteForm
) {
957 # If the form is incomplete, force to preview.
958 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
959 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
960 $this->preview
= true;
962 $this->preview
= $request->getCheck( 'wpPreview' );
963 $this->diff
= $request->getCheck( 'wpDiff' );
965 // Remember whether a save was requested, so we can indicate
966 // if we forced preview due to session failure.
967 $this->mTriedSave
= !$this->preview
;
969 if ( $this->tokenOk( $request ) ) {
970 # Some browsers will not report any submit button
971 # if the user hits enter in the comment box.
972 # The unmarked state will be assumed to be a save,
973 # if the form seems otherwise complete.
974 wfDebug( __METHOD__
. ": Passed token check.\n" );
975 } elseif ( $this->diff
) {
976 # Failed token check, but only requested "Show Changes".
977 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
979 # Page might be a hack attempt posted from
980 # an external site. Preview instead of saving.
981 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
982 $this->preview
= true;
985 $this->save
= !$this->preview
&& !$this->diff
;
986 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
987 $this->edittime
= null;
990 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
991 $this->starttime
= null;
994 $this->recreate
= $request->getCheck( 'wpRecreate' );
996 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
997 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
999 $user = $this->context
->getUser();
1000 # Don't force edit summaries when a user is editing their own user or talk page
1001 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
1002 && $this->mTitle
->getText() == $user->getName()
1004 $this->allowBlankSummary
= true;
1006 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1007 ||
!$user->getOption( 'forceeditsummary' );
1010 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1012 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1013 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1015 $changeTags = $request->getVal( 'wpChangeTags' );
1016 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1017 $this->changeTags
= [];
1019 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1023 # Not a posted form? Start with nothing.
1024 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1025 $this->textbox1
= '';
1026 $this->summary
= '';
1027 $this->sectiontitle
= '';
1028 $this->edittime
= '';
1029 $this->editRevId
= null;
1030 $this->starttime
= wfTimestampNow();
1031 $this->edit
= false;
1032 $this->preview
= false;
1033 $this->save
= false;
1034 $this->diff
= false;
1035 $this->minoredit
= false;
1036 // Watch may be overridden by request parameters
1037 $this->watchthis
= $request->getBool( 'watchthis', false );
1038 $this->recreate
= false;
1040 // When creating a new section, we can preload a section title by passing it as the
1041 // preloadtitle parameter in the URL (T15100)
1042 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1043 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1044 // Once wpSummary isn't being use for setting section titles, we should delete this.
1045 $this->summary
= $request->getVal( 'preloadtitle' );
1046 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1047 $this->summary
= $request->getText( 'summary' );
1048 if ( $this->summary
!== '' ) {
1049 $this->hasPresetSummary
= true;
1053 if ( $request->getVal( 'minor' ) ) {
1054 $this->minoredit
= true;
1058 $this->oldid
= $request->getInt( 'oldid' );
1059 $this->parentRevId
= $request->getInt( 'parentRevId' );
1061 $this->bot
= $request->getBool( 'bot', true );
1062 $this->nosummary
= $request->getBool( 'nosummary' );
1064 // May be overridden by revision.
1065 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1066 // May be overridden by revision.
1067 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1070 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1071 } catch ( MWUnknownContentModelException
$e ) {
1072 throw new ErrorPageError(
1073 'editpage-invalidcontentmodel-title',
1074 'editpage-invalidcontentmodel-text',
1075 [ wfEscapeWikiText( $this->contentModel
) ]
1079 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1080 throw new ErrorPageError(
1081 'editpage-notsupportedcontentformat-title',
1082 'editpage-notsupportedcontentformat-text',
1084 wfEscapeWikiText( $this->contentFormat
),
1085 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1091 * @todo Check if the desired model is allowed in this namespace, and if
1092 * a transition from the page's current model to the new model is
1096 $this->editintro
= $request->getText( 'editintro',
1097 // Custom edit intro for new sections
1098 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1100 // Allow extensions to modify form data
1101 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1105 * Subpage overridable method for extracting the page content data from the
1106 * posted form to be placed in $this->textbox1, if using customized input
1107 * this method should be overridden and return the page text that will be used
1108 * for saving, preview parsing and so on...
1110 * @param WebRequest &$request
1111 * @return string|null
1113 protected function importContentFormData( &$request ) {
1114 return; // Don't do anything, EditPage already extracted wpTextbox1
1118 * Initialise form fields in the object
1119 * Called on the first invocation, e.g. when a user clicks an edit link
1120 * @return bool If the requested section is valid
1122 public function initialiseForm() {
1123 $this->edittime
= $this->page
->getTimestamp();
1124 $this->editRevId
= $this->page
->getLatest();
1126 $content = $this->getContentObject( false ); # TODO: track content object?!
1127 if ( $content === false ) {
1130 $this->textbox1
= $this->toEditText( $content );
1132 $user = $this->context
->getUser();
1133 // activate checkboxes if user wants them to be always active
1134 # Sort out the "watch" checkbox
1135 if ( $user->getOption( 'watchdefault' ) ) {
1137 $this->watchthis
= true;
1138 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1140 $this->watchthis
= true;
1141 } elseif ( $user->isWatched( $this->mTitle
) ) {
1143 $this->watchthis
= true;
1145 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1146 $this->minoredit
= true;
1148 if ( $this->textbox1
=== false ) {
1155 * @param Content|null $def_content The default value to return
1157 * @return Content|null Content on success, $def_content for invalid sections
1161 protected function getContentObject( $def_content = null ) {
1166 $user = $this->context
->getUser();
1167 $request = $this->context
->getRequest();
1168 // For message page not locally set, use the i18n message.
1169 // For other non-existent articles, use preload text if any.
1170 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1171 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1172 # If this is a system message, get the default text.
1173 $msg = $this->mTitle
->getDefaultMessageText();
1175 $content = $this->toEditContent( $msg );
1177 if ( $content === false ) {
1178 # If requested, preload some text.
1179 $preload = $request->getVal( 'preload',
1180 // Custom preload text for new sections
1181 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1182 $params = $request->getArray( 'preloadparams', [] );
1184 $content = $this->getPreloadedContent( $preload, $params );
1186 // For existing pages, get text based on "undo" or section parameters.
1188 if ( $this->section
!= '' ) {
1189 // Get section edit text (returns $def_text for invalid sections)
1190 $orig = $this->getOriginalContent( $user );
1191 $content = $orig ?
$orig->getSection( $this->section
) : null;
1194 $content = $def_content;
1197 $undoafter = $request->getInt( 'undoafter' );
1198 $undo = $request->getInt( 'undo' );
1200 if ( $undo > 0 && $undoafter > 0 ) {
1201 $undorev = Revision
::newFromId( $undo );
1202 $oldrev = Revision
::newFromId( $undoafter );
1204 # Sanity check, make sure it's the right page,
1205 # the revisions exist and they were not deleted.
1206 # Otherwise, $content will be left as-is.
1207 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1208 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1209 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1211 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1213 if ( $content === false ) {
1214 # Warn the user that something went wrong
1215 $undoMsg = 'failure';
1217 $oldContent = $this->page
->getContent( Revision
::RAW
);
1218 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1219 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1220 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1221 // The undo may change content
1222 // model if its reverting the top
1223 // edit. This can result in
1224 // mismatched content model/format.
1225 $this->contentModel
= $newContent->getModel();
1226 $this->contentFormat
= $oldrev->getContentFormat();
1229 if ( $newContent->equals( $oldContent ) ) {
1230 # Tell the user that the undo results in no change,
1231 # i.e. the revisions were already undone.
1232 $undoMsg = 'nochange';
1235 # Inform the user of our success and set an automatic edit summary
1236 $undoMsg = 'success';
1238 # If we just undid one rev, use an autosummary
1239 $firstrev = $oldrev->getNext();
1240 if ( $firstrev && $firstrev->getId() == $undo ) {
1241 $userText = $undorev->getUserText();
1242 if ( $userText === '' ) {
1243 $undoSummary = $this->context
->msg(
1244 'undo-summary-username-hidden',
1246 )->inContentLanguage()->text();
1248 $undoSummary = $this->context
->msg(
1252 )->inContentLanguage()->text();
1254 if ( $this->summary
=== '' ) {
1255 $this->summary
= $undoSummary;
1257 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1258 ->inContentLanguage()->text() . $this->summary
;
1260 $this->undidRev
= $undo;
1262 $this->formtype
= 'diff';
1266 // Failed basic sanity checks.
1267 // Older revisions may have been removed since the link
1268 // was created, or we may simply have got bogus input.
1272 $out = $this->context
->getOutput();
1273 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1274 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1275 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1276 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1279 if ( $content === false ) {
1280 $content = $this->getOriginalContent( $user );
1289 * Get the content of the wanted revision, without section extraction.
1291 * The result of this function can be used to compare user's input with
1292 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1293 * to the original text of the edit.
1295 * This differs from Article::getContent() that when a missing revision is
1296 * encountered the result will be null and not the
1297 * 'missing-revision' message.
1300 * @param User $user The user to get the revision for
1301 * @return Content|null
1303 private function getOriginalContent( User
$user ) {
1304 if ( $this->section
== 'new' ) {
1305 return $this->getCurrentContent();
1307 $revision = $this->mArticle
->getRevisionFetched();
1308 if ( $revision === null ) {
1309 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1310 return $handler->makeEmptyContent();
1312 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1317 * Get the edit's parent revision ID
1319 * The "parent" revision is the ancestor that should be recorded in this
1320 * page's revision history. It is either the revision ID of the in-memory
1321 * article content, or in the case of a 3-way merge in order to rebase
1322 * across a recoverable edit conflict, the ID of the newer revision to
1323 * which we have rebased this page.
1326 * @return int Revision ID
1328 public function getParentRevId() {
1329 if ( $this->parentRevId
) {
1330 return $this->parentRevId
;
1332 return $this->mArticle
->getRevIdFetched();
1337 * Get the current content of the page. This is basically similar to
1338 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1339 * content object is returned instead of null.
1344 protected function getCurrentContent() {
1345 $rev = $this->page
->getRevision();
1346 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1348 if ( $content === false ||
$content === null ) {
1349 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1350 return $handler->makeEmptyContent();
1351 } elseif ( !$this->undidRev
) {
1352 // Content models should always be the same since we error
1353 // out if they are different before this point (in ->edit()).
1354 // The exception being, during an undo, the current revision might
1355 // differ from the prior revision.
1356 $logger = LoggerFactory
::getInstance( 'editpage' );
1357 if ( $this->contentModel
!== $rev->getContentModel() ) {
1358 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1359 'prev' => $this->contentModel
,
1360 'new' => $rev->getContentModel(),
1361 'title' => $this->getTitle()->getPrefixedDBkey(),
1362 'method' => __METHOD__
1364 $this->contentModel
= $rev->getContentModel();
1367 // Given that the content models should match, the current selected
1368 // format should be supported.
1369 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1370 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1372 'prev' => $this->contentFormat
,
1373 'new' => $rev->getContentFormat(),
1374 'title' => $this->getTitle()->getPrefixedDBkey(),
1375 'method' => __METHOD__
1377 $this->contentFormat
= $rev->getContentFormat();
1384 * Use this method before edit() to preload some content into the edit box
1386 * @param Content $content
1390 public function setPreloadedContent( Content
$content ) {
1391 $this->mPreloadContent
= $content;
1395 * Get the contents to be preloaded into the box, either set by
1396 * an earlier setPreloadText() or by loading the given page.
1398 * @param string $preload Representing the title to preload from.
1399 * @param array $params Parameters to use (interface-message style) in the preloaded text
1405 protected function getPreloadedContent( $preload, $params = [] ) {
1406 if ( !empty( $this->mPreloadContent
) ) {
1407 return $this->mPreloadContent
;
1410 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1412 if ( $preload === '' ) {
1413 return $handler->makeEmptyContent();
1416 $user = $this->context
->getUser();
1417 $title = Title
::newFromText( $preload );
1418 # Check for existence to avoid getting MediaWiki:Noarticletext
1419 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1420 // TODO: somehow show a warning to the user!
1421 return $handler->makeEmptyContent();
1424 $page = WikiPage
::factory( $title );
1425 if ( $page->isRedirect() ) {
1426 $title = $page->getRedirectTarget();
1428 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1429 // TODO: somehow show a warning to the user!
1430 return $handler->makeEmptyContent();
1432 $page = WikiPage
::factory( $title );
1435 $parserOptions = ParserOptions
::newFromUser( $user );
1436 $content = $page->getContent( Revision
::RAW
);
1439 // TODO: somehow show a warning to the user!
1440 return $handler->makeEmptyContent();
1443 if ( $content->getModel() !== $handler->getModelID() ) {
1444 $converted = $content->convert( $handler->getModelID() );
1446 if ( !$converted ) {
1447 // TODO: somehow show a warning to the user!
1448 wfDebug( "Attempt to preload incompatible content: " .
1449 "can't convert " . $content->getModel() .
1450 " to " . $handler->getModelID() );
1452 return $handler->makeEmptyContent();
1455 $content = $converted;
1458 return $content->preloadTransform( $title, $parserOptions, $params );
1462 * Make sure the form isn't faking a user's credentials.
1464 * @param WebRequest &$request
1468 public function tokenOk( &$request ) {
1469 $token = $request->getVal( 'wpEditToken' );
1470 $user = $this->context
->getUser();
1471 $this->mTokenOk
= $user->matchEditToken( $token );
1472 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1473 return $this->mTokenOk
;
1477 * Sets post-edit cookie indicating the user just saved a particular revision.
1479 * This uses a temporary cookie for each revision ID so separate saves will never
1480 * interfere with each other.
1482 * Article::view deletes the cookie on server-side after the redirect and
1483 * converts the value to the global JavaScript variable wgPostEdit.
1485 * If the variable were set on the server, it would be cached, which is unwanted
1486 * since the post-edit state should only apply to the load right after the save.
1488 * @param int $statusValue The status value (to check for new article status)
1490 protected function setPostEditCookie( $statusValue ) {
1491 $revisionId = $this->page
->getLatest();
1492 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1495 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1497 } elseif ( $this->oldid
) {
1501 $response = $this->context
->getRequest()->response();
1502 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1506 * Attempt submission
1507 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1508 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1509 * @return Status The resulting status object.
1511 public function attemptSave( &$resultDetails = false ) {
1512 # Allow bots to exempt some edits from bot flagging
1513 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1514 $status = $this->internalAttemptSave( $resultDetails, $bot );
1516 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1522 * Log when a page was successfully saved after the edit conflict view
1524 private function incrementResolvedConflicts() {
1525 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1529 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1530 $stats->increment( 'edit.failures.conflict.resolved' );
1534 * Handle status, such as after attempt save
1536 * @param Status $status
1537 * @param array|bool $resultDetails
1539 * @throws ErrorPageError
1540 * @return bool False, if output is done, true if rest of the form should be displayed
1542 private function handleStatus( Status
$status, $resultDetails ) {
1544 * @todo FIXME: once the interface for internalAttemptSave() is made
1545 * nicer, this should use the message in $status
1547 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1548 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1550 $this->incrementResolvedConflicts();
1552 $this->didSave
= true;
1553 if ( !$resultDetails['nullEdit'] ) {
1554 $this->setPostEditCookie( $status->value
);
1558 $out = $this->context
->getOutput();
1560 // "wpExtraQueryRedirect" is a hidden input to modify
1561 // after save URL and is not used by actual edit form
1562 $request = $this->context
->getRequest();
1563 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1565 switch ( $status->value
) {
1566 case self
::AS_HOOK_ERROR_EXPECTED
:
1567 case self
::AS_CONTENT_TOO_BIG
:
1568 case self
::AS_ARTICLE_WAS_DELETED
:
1569 case self
::AS_CONFLICT_DETECTED
:
1570 case self
::AS_SUMMARY_NEEDED
:
1571 case self
::AS_TEXTBOX_EMPTY
:
1572 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1574 case self
::AS_BLANK_ARTICLE
:
1575 case self
::AS_SELF_REDIRECT
:
1578 case self
::AS_HOOK_ERROR
:
1581 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1582 case self
::AS_PARSE_ERROR
:
1583 case self
::AS_UNICODE_NOT_SUPPORTED
:
1584 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1587 case self
::AS_SUCCESS_NEW_ARTICLE
:
1588 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1589 if ( $extraQueryRedirect ) {
1590 if ( $query === '' ) {
1591 $query = $extraQueryRedirect;
1593 $query = $query . '&' . $extraQueryRedirect;
1596 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1597 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1600 case self
::AS_SUCCESS_UPDATE
:
1602 $sectionanchor = $resultDetails['sectionanchor'];
1604 // Give extensions a chance to modify URL query on update
1606 'ArticleUpdateBeforeRedirect',
1607 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1610 if ( $resultDetails['redirect'] ) {
1611 if ( $extraQuery == '' ) {
1612 $extraQuery = 'redirect=no';
1614 $extraQuery = 'redirect=no&' . $extraQuery;
1617 if ( $extraQueryRedirect ) {
1618 if ( $extraQuery === '' ) {
1619 $extraQuery = $extraQueryRedirect;
1621 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1625 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1628 case self
::AS_SPAM_ERROR
:
1629 $this->spamPageWithContent( $resultDetails['spam'] );
1632 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1633 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1635 case self
::AS_IMAGE_REDIRECT_ANON
:
1636 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1637 throw new PermissionsError( 'upload' );
1639 case self
::AS_READ_ONLY_PAGE_ANON
:
1640 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1641 throw new PermissionsError( 'edit' );
1643 case self
::AS_READ_ONLY_PAGE
:
1644 throw new ReadOnlyError
;
1646 case self
::AS_RATE_LIMITED
:
1647 throw new ThrottledError();
1649 case self
::AS_NO_CREATE_PERMISSION
:
1650 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1651 throw new PermissionsError( $permission );
1653 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1654 throw new PermissionsError( 'editcontentmodel' );
1657 // We don't recognize $status->value. The only way that can happen
1658 // is if an extension hook aborted from inside ArticleSave.
1659 // Render the status object into $this->hookError
1660 // FIXME this sucks, we should just use the Status object throughout
1661 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1668 * Run hooks that can filter edits just before they get saved.
1670 * @param Content $content The Content to filter.
1671 * @param Status $status For reporting the outcome to the caller
1672 * @param User $user The user performing the edit
1676 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1677 // Run old style post-section-merge edit filter
1678 if ( $this->hookError
!= '' ) {
1679 # ...or the hook could be expecting us to produce an error
1680 $status->fatal( 'hookaborted' );
1681 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1685 // Run new style post-section-merge edit filter
1686 if ( !Hooks
::run( 'EditFilterMergedContent',
1687 [ $this->mArticle
->getContext(), $content, $status, $this->summary
,
1688 $user, $this->minoredit
] )
1690 # Error messages etc. could be handled within the hook...
1691 if ( $status->isGood() ) {
1692 $status->fatal( 'hookaborted' );
1693 // Not setting $this->hookError here is a hack to allow the hook
1694 // to cause a return to the edit page without $this->hookError
1695 // being set. This is used by ConfirmEdit to display a captcha
1696 // without any error message cruft.
1698 $this->hookError
= $status->getWikiText();
1700 // Use the existing $status->value if the hook set it
1701 if ( !$status->value
) {
1702 $status->value
= self
::AS_HOOK_ERROR
;
1705 } elseif ( !$status->isOK() ) {
1706 # ...or the hook could be expecting us to produce an error
1707 // FIXME this sucks, we should just use the Status object throughout
1708 $this->hookError
= $status->getWikiText();
1709 $status->fatal( 'hookaborted' );
1710 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1718 * Return the summary to be used for a new section.
1720 * @param string $sectionanchor Set to the section anchor text
1723 private function newSectionSummary( &$sectionanchor = null ) {
1726 if ( $this->sectiontitle
!== '' ) {
1727 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1728 // If no edit summary was specified, create one automatically from the section
1729 // title and have it link to the new section. Otherwise, respect the summary as
1731 if ( $this->summary
=== '' ) {
1732 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1733 return $this->context
->msg( 'newsectionsummary' )
1734 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1736 } elseif ( $this->summary
!== '' ) {
1737 $sectionanchor = $this->guessSectionName( $this->summary
);
1738 # This is a new section, so create a link to the new section
1739 # in the revision summary.
1740 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1741 return $this->context
->msg( 'newsectionsummary' )
1742 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1744 return $this->summary
;
1748 * Attempt submission (no UI)
1750 * @param array &$result Array to add statuses to, currently with the
1752 * - spam (string): Spam string from content if any spam is detected by
1754 * - sectionanchor (string): Section anchor for a section save.
1755 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1757 * - redirect (bool): Set if doEditContent is OK. True if resulting
1758 * revision is a redirect.
1759 * @param bool $bot True if edit is being made under the bot right.
1761 * @return Status Status object, possibly with a message, but always with
1762 * one of the AS_* constants in $status->value,
1764 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1765 * various error display idiosyncrasies. There are also lots of cases
1766 * where error metadata is set in the object and retrieved later instead
1767 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1768 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1771 public function internalAttemptSave( &$result, $bot = false ) {
1772 $status = Status
::newGood();
1773 $user = $this->context
->getUser();
1775 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1776 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1777 $status->fatal( 'hookaborted' );
1778 $status->value
= self
::AS_HOOK_ERROR
;
1782 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1783 $status->fatal( 'unicode-support-fail' );
1784 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1788 $request = $this->context
->getRequest();
1789 $spam = $request->getText( 'wpAntispam' );
1790 if ( $spam !== '' ) {
1795 $this->mTitle
->getPrefixedText() .
1796 '" submitted bogus field "' .
1800 $status->fatal( 'spamprotectionmatch', false );
1801 $status->value
= self
::AS_SPAM_ERROR
;
1806 # Construct Content object
1807 $textbox_content = $this->toEditContent( $this->textbox1
);
1808 } catch ( MWContentSerializationException
$ex ) {
1810 'content-failed-to-parse',
1811 $this->contentModel
,
1812 $this->contentFormat
,
1815 $status->value
= self
::AS_PARSE_ERROR
;
1819 # Check image redirect
1820 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1821 $textbox_content->isRedirect() &&
1822 !$user->isAllowed( 'upload' )
1824 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1825 $status->setResult( false, $code );
1831 $match = self
::matchSummarySpamRegex( $this->summary
);
1832 if ( $match === false && $this->section
== 'new' ) {
1833 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1834 # regular summaries, it is added to the actual wikitext.
1835 if ( $this->sectiontitle
!== '' ) {
1836 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1837 $match = self
::matchSpamRegex( $this->sectiontitle
);
1839 # This branch is taken when the "Add Topic" user interface is used, or the API
1840 # is used with the 'summary' parameter.
1841 $match = self
::matchSpamRegex( $this->summary
);
1844 if ( $match === false ) {
1845 $match = self
::matchSpamRegex( $this->textbox1
);
1847 if ( $match !== false ) {
1848 $result['spam'] = $match;
1849 $ip = $request->getIP();
1850 $pdbk = $this->mTitle
->getPrefixedDBkey();
1851 $match = str_replace( "\n", '', $match );
1852 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1853 $status->fatal( 'spamprotectionmatch', $match );
1854 $status->value
= self
::AS_SPAM_ERROR
;
1859 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1861 # Error messages etc. could be handled within the hook...
1862 $status->fatal( 'hookaborted' );
1863 $status->value
= self
::AS_HOOK_ERROR
;
1865 } elseif ( $this->hookError
!= '' ) {
1866 # ...or the hook could be expecting us to produce an error
1867 $status->fatal( 'hookaborted' );
1868 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1872 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1873 // Auto-block user's IP if the account was "hard" blocked
1874 if ( !wfReadOnly() ) {
1875 $user->spreadAnyEditBlock();
1877 # Check block state against master, thus 'false'.
1878 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1882 $this->contentLength
= strlen( $this->textbox1
);
1883 $config = $this->context
->getConfig();
1884 $maxArticleSize = $config->get( 'MaxArticleSize' );
1885 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1886 // Error will be displayed by showEditForm()
1887 $this->tooBig
= true;
1888 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1892 if ( !$user->isAllowed( 'edit' ) ) {
1893 if ( $user->isAnon() ) {
1894 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1897 $status->fatal( 'readonlytext' );
1898 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1903 $changingContentModel = false;
1904 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1905 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1906 $status->fatal( 'editpage-cannot-use-custom-model' );
1907 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1909 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1910 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1913 // Make sure the user can edit the page under the new content model too
1914 $titleWithNewContentModel = clone $this->mTitle
;
1915 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1916 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1917 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1919 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1923 $changingContentModel = true;
1924 $oldContentModel = $this->mTitle
->getContentModel();
1927 if ( $this->changeTags
) {
1928 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1929 $this->changeTags
, $user );
1930 if ( !$changeTagsStatus->isOK() ) {
1931 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1932 return $changeTagsStatus;
1936 if ( wfReadOnly() ) {
1937 $status->fatal( 'readonlytext' );
1938 $status->value
= self
::AS_READ_ONLY_PAGE
;
1941 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1942 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1944 $status->fatal( 'actionthrottledtext' );
1945 $status->value
= self
::AS_RATE_LIMITED
;
1949 # If the article has been deleted while editing, don't save it without
1951 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1952 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1956 # Load the page data from the master. If anything changes in the meantime,
1957 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1958 $this->page
->loadPageData( 'fromdbmaster' );
1959 $new = !$this->page
->exists();
1962 // Late check for create permission, just in case *PARANOIA*
1963 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1964 $status->fatal( 'nocreatetext' );
1965 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1966 wfDebug( __METHOD__
. ": no create permission\n" );
1970 // Don't save a new page if it's blank or if it's a MediaWiki:
1971 // message with content equivalent to default (allow empty pages
1972 // in this case to disable messages, see T52124)
1973 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1974 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1975 $defaultText = $defaultMessageText;
1980 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1981 $this->blankArticle
= true;
1982 $status->fatal( 'blankarticle' );
1983 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1987 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
1991 $content = $textbox_content;
1993 $result['sectionanchor'] = '';
1994 if ( $this->section
== 'new' ) {
1995 if ( $this->sectiontitle
!== '' ) {
1996 // Insert the section title above the content.
1997 $content = $content->addSectionHeader( $this->sectiontitle
);
1998 } elseif ( $this->summary
!== '' ) {
1999 // Insert the section title above the content.
2000 $content = $content->addSectionHeader( $this->summary
);
2002 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2005 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2009 # Article exists. Check for edit conflict.
2011 $this->page
->clear(); # Force reload of dates, etc.
2012 $timestamp = $this->page
->getTimestamp();
2013 $latest = $this->page
->getLatest();
2015 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2017 // Check editRevId if set, which handles same-second timestamp collisions
2018 if ( $timestamp != $this->edittime
2019 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2021 $this->isConflict
= true;
2022 if ( $this->section
== 'new' ) {
2023 if ( $this->page
->getUserText() == $user->getName() &&
2024 $this->page
->getComment() == $this->newSectionSummary()
2026 // Probably a duplicate submission of a new comment.
2027 // This can happen when CDN resends a request after
2028 // a timeout but the first one actually went through.
2030 . ": duplicate new section submission; trigger edit conflict!\n" );
2032 // New comment; suppress conflict.
2033 $this->isConflict
= false;
2034 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2036 } elseif ( $this->section
== ''
2037 && Revision
::userWasLastToEdit(
2038 DB_MASTER
, $this->mTitle
->getArticleID(),
2039 $user->getId(), $this->edittime
2042 # Suppress edit conflict with self, except for section edits where merging is required.
2043 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2044 $this->isConflict
= false;
2048 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2049 if ( $this->sectiontitle
!== '' ) {
2050 $sectionTitle = $this->sectiontitle
;
2052 $sectionTitle = $this->summary
;
2057 if ( $this->isConflict
) {
2059 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2060 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2061 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2062 // ...or disable section editing for non-current revisions (not exposed anyway).
2063 if ( $this->editRevId
!== null ) {
2064 $content = $this->page
->replaceSectionAtRev(
2071 $content = $this->page
->replaceSectionContent(
2079 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2080 $content = $this->page
->replaceSectionContent(
2087 if ( is_null( $content ) ) {
2088 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2089 $this->isConflict
= true;
2090 $content = $textbox_content; // do not try to merge here!
2091 } elseif ( $this->isConflict
) {
2093 if ( $this->mergeChangesIntoContent( $content ) ) {
2094 // Successful merge! Maybe we should tell the user the good news?
2095 $this->isConflict
= false;
2096 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2098 $this->section
= '';
2099 $this->textbox1
= ContentHandler
::getContentText( $content );
2100 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2104 if ( $this->isConflict
) {
2105 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2109 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2113 if ( $this->section
== 'new' ) {
2114 // Handle the user preference to force summaries here
2115 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2116 $this->missingSummary
= true;
2117 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2118 $status->value
= self
::AS_SUMMARY_NEEDED
;
2122 // Do not allow the user to post an empty comment
2123 if ( $this->textbox1
== '' ) {
2124 $this->missingComment
= true;
2125 $status->fatal( 'missingcommenttext' );
2126 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2129 } elseif ( !$this->allowBlankSummary
2130 && !$content->equals( $this->getOriginalContent( $user ) )
2131 && !$content->isRedirect()
2132 && md5( $this->summary
) == $this->autoSumm
2134 $this->missingSummary
= true;
2135 $status->fatal( 'missingsummary' );
2136 $status->value
= self
::AS_SUMMARY_NEEDED
;
2141 $sectionanchor = '';
2142 if ( $this->section
== 'new' ) {
2143 $this->summary
= $this->newSectionSummary( $sectionanchor );
2144 } elseif ( $this->section
!= '' ) {
2145 # Try to get a section anchor from the section source, redirect
2146 # to edited section if header found.
2147 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2148 # for duplicate heading checking and maybe parsing.
2149 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2150 # We can't deal with anchors, includes, html etc in the header for now,
2151 # headline would need to be parsed to improve this.
2152 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2153 $sectionanchor = $this->guessSectionName( $matches[2] );
2156 $result['sectionanchor'] = $sectionanchor;
2158 // Save errors may fall down to the edit form, but we've now
2159 // merged the section into full text. Clear the section field
2160 // so that later submission of conflict forms won't try to
2161 // replace that into a duplicated mess.
2162 $this->textbox1
= $this->toEditText( $content );
2163 $this->section
= '';
2165 $status->value
= self
::AS_SUCCESS_UPDATE
;
2168 if ( !$this->allowSelfRedirect
2169 && $content->isRedirect()
2170 && $content->getRedirectTarget()->equals( $this->getTitle() )
2172 // If the page already redirects to itself, don't warn.
2173 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2174 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2175 $this->selfRedirect
= true;
2176 $status->fatal( 'selfredirect' );
2177 $status->value
= self
::AS_SELF_REDIRECT
;
2182 // Check for length errors again now that the section is merged in
2183 $this->contentLength
= strlen( $this->toEditText( $content ) );
2184 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2185 $this->tooBig
= true;
2186 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2190 $flags = EDIT_AUTOSUMMARY |
2191 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2192 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2193 ( $bot ? EDIT_FORCE_BOT
: 0 );
2195 $doEditStatus = $this->page
->doEditContent(
2201 $content->getDefaultFormat(),
2206 if ( !$doEditStatus->isOK() ) {
2207 // Failure from doEdit()
2208 // Show the edit conflict page for certain recognized errors from doEdit(),
2209 // but don't show it for errors from extension hooks
2210 $errors = $doEditStatus->getErrorsArray();
2211 if ( in_array( $errors[0][0],
2212 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2214 $this->isConflict
= true;
2215 // Destroys data doEdit() put in $status->value but who cares
2216 $doEditStatus->value
= self
::AS_END
;
2218 return $doEditStatus;
2221 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2222 if ( $result['nullEdit'] ) {
2223 // We don't know if it was a null edit until now, so increment here
2224 $user->pingLimiter( 'linkpurge' );
2226 $result['redirect'] = $content->isRedirect();
2228 $this->updateWatchlist();
2230 // If the content model changed, add a log entry
2231 if ( $changingContentModel ) {
2232 $this->addContentModelChangeLogEntry(
2234 $new ?
false : $oldContentModel,
2235 $this->contentModel
,
2245 * @param string|false $oldModel false if the page is being newly created
2246 * @param string $newModel
2247 * @param string $reason
2249 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2250 $new = $oldModel === false;
2251 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2252 $log->setPerformer( $user );
2253 $log->setTarget( $this->mTitle
);
2254 $log->setComment( $reason );
2255 $log->setParameters( [
2256 '4::oldmodel' => $oldModel,
2257 '5::newmodel' => $newModel
2259 $logid = $log->insert();
2260 $log->publish( $logid );
2264 * Register the change of watch status
2266 protected function updateWatchlist() {
2267 $user = $this->context
->getUser();
2268 if ( !$user->isLoggedIn() ) {
2272 $title = $this->mTitle
;
2273 $watch = $this->watchthis
;
2274 // Do this in its own transaction to reduce contention...
2275 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2276 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2277 return; // nothing to change
2279 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2284 * Attempts to do 3-way merge of edit content with a base revision
2285 * and current content, in case of edit conflict, in whichever way appropriate
2286 * for the content type.
2290 * @param Content $editContent
2294 private function mergeChangesIntoContent( &$editContent ) {
2295 $db = wfGetDB( DB_MASTER
);
2297 // This is the revision the editor started from
2298 $baseRevision = $this->getBaseRevision();
2299 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2301 if ( is_null( $baseContent ) ) {
2305 // The current state, we want to merge updates into it
2306 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2307 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2309 if ( is_null( $currentContent ) ) {
2313 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2315 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2318 $editContent = $result;
2319 // Update parentRevId to what we just merged.
2320 $this->parentRevId
= $currentRevision->getId();
2328 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2329 * one might think of X as the "base revision", which is NOT what this returns.
2330 * @return Revision Current version when the edit was started
2332 public function getBaseRevision() {
2333 if ( !$this->mBaseRevision
) {
2334 $db = wfGetDB( DB_MASTER
);
2335 $this->mBaseRevision
= $this->editRevId
2336 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2337 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2339 return $this->mBaseRevision
;
2343 * Check given input text against $wgSpamRegex, and return the text of the first match.
2345 * @param string $text
2347 * @return string|bool Matching string or false
2349 public static function matchSpamRegex( $text ) {
2350 global $wgSpamRegex;
2351 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2352 $regexes = (array)$wgSpamRegex;
2353 return self
::matchSpamRegexInternal( $text, $regexes );
2357 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2359 * @param string $text
2361 * @return string|bool Matching string or false
2363 public static function matchSummarySpamRegex( $text ) {
2364 global $wgSummarySpamRegex;
2365 $regexes = (array)$wgSummarySpamRegex;
2366 return self
::matchSpamRegexInternal( $text, $regexes );
2370 * @param string $text
2371 * @param array $regexes
2372 * @return bool|string
2374 protected static function matchSpamRegexInternal( $text, $regexes ) {
2375 foreach ( $regexes as $regex ) {
2377 if ( preg_match( $regex, $text, $matches ) ) {
2384 public function setHeaders() {
2385 $out = $this->context
->getOutput();
2387 $out->addModules( 'mediawiki.action.edit' );
2388 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2390 $user = $this->context
->getUser();
2391 if ( $user->getOption( 'showtoolbar' ) ) {
2392 // The addition of default buttons is handled by getEditToolbar() which
2393 // has its own dependency on this module. The call here ensures the module
2394 // is loaded in time (it has position "top") for other modules to register
2395 // buttons (e.g. extensions, gadgets, user scripts).
2396 $out->addModules( 'mediawiki.toolbar' );
2399 if ( $user->getOption( 'uselivepreview' ) ) {
2400 $out->addModules( 'mediawiki.action.edit.preview' );
2403 if ( $user->getOption( 'useeditwarning' ) ) {
2404 $out->addModules( 'mediawiki.action.edit.editWarning' );
2407 # Enabled article-related sidebar, toplinks, etc.
2408 $out->setArticleRelated( true );
2410 $contextTitle = $this->getContextTitle();
2411 if ( $this->isConflict
) {
2412 $msg = 'editconflict';
2413 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2414 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2416 $msg = $contextTitle->exists()
2417 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2418 && $contextTitle->getDefaultMessageText() !== false
2424 # Use the title defined by DISPLAYTITLE magic word when present
2425 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2426 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2427 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2428 if ( $displayTitle === false ) {
2429 $displayTitle = $contextTitle->getPrefixedText();
2431 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2432 # Transmit the name of the message to JavaScript for live preview
2433 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2434 $out->addJsConfigVars( [
2435 'wgEditMessage' => $msg,
2436 'wgAjaxEditStash' => $this->context
->getConfig()->get( 'AjaxEditStash' ),
2441 * Show all applicable editing introductions
2443 protected function showIntro() {
2444 if ( $this->suppressIntro
) {
2448 $out = $this->context
->getOutput();
2449 $namespace = $this->mTitle
->getNamespace();
2451 if ( $namespace == NS_MEDIAWIKI
) {
2452 # Show a warning if editing an interface message
2453 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2454 # If this is a default message (but not css or js),
2455 # show a hint that it is translatable on translatewiki.net
2456 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2457 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2459 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2460 if ( $defaultMessageText !== false ) {
2461 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2462 'translateinterface' );
2465 } elseif ( $namespace == NS_FILE
) {
2466 # Show a hint to shared repo
2467 $file = wfFindFile( $this->mTitle
);
2468 if ( $file && !$file->isLocal() ) {
2469 $descUrl = $file->getDescriptionUrl();
2470 # there must be a description url to show a hint to shared repo
2472 if ( !$this->mTitle
->exists() ) {
2473 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2474 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2477 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2478 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2485 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2486 # Show log extract when the user is currently blocked
2487 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2488 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2489 $user = User
::newFromName( $username, false /* allow IP users */ );
2490 $ip = User
::isIP( $username );
2491 $block = Block
::newFromTarget( $user, $user );
2492 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2493 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2494 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2495 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2496 # Show log extract if the user is currently blocked
2497 LogEventsList
::showLogExtract(
2500 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2504 'showIfEmpty' => false,
2506 'blocked-notice-logextract',
2507 $user->getName() # Support GENDER in notice
2513 # Try to add a custom edit intro, or use the standard one if this is not possible.
2514 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2515 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2516 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2518 if ( $this->context
->getUser()->isLoggedIn() ) {
2520 // Suppress the external link icon, consider the help url an internal one
2521 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2529 // Suppress the external link icon, consider the help url an internal one
2530 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2532 'newarticletextanon',
2538 # Give a notice if the user is editing a deleted/moved page...
2539 if ( !$this->mTitle
->exists() ) {
2540 $dbr = wfGetDB( DB_REPLICA
);
2542 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2546 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2547 'showIfEmpty' => false,
2548 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2555 * Attempt to show a custom editing introduction, if supplied
2559 protected function showCustomIntro() {
2560 if ( $this->editintro
) {
2561 $title = Title
::newFromText( $this->editintro
);
2562 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2563 // Added using template syntax, to take <noinclude>'s into account.
2564 $this->context
->getOutput()->addWikiTextTitleTidy(
2565 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2575 * Gets an editable textual representation of $content.
2576 * The textual representation can be turned by into a Content object by the
2577 * toEditContent() method.
2579 * If $content is null or false or a string, $content is returned unchanged.
2581 * If the given Content object is not of a type that can be edited using
2582 * the text base EditPage, an exception will be raised. Set
2583 * $this->allowNonTextContent to true to allow editing of non-textual
2586 * @param Content|null|bool|string $content
2587 * @return string The editable text form of the content.
2589 * @throws MWException If $content is not an instance of TextContent and
2590 * $this->allowNonTextContent is not true.
2592 protected function toEditText( $content ) {
2593 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2597 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2598 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2601 return $content->serialize( $this->contentFormat
);
2605 * Turns the given text into a Content object by unserializing it.
2607 * If the resulting Content object is not of a type that can be edited using
2608 * the text base EditPage, an exception will be raised. Set
2609 * $this->allowNonTextContent to true to allow editing of non-textual
2612 * @param string|null|bool $text Text to unserialize
2613 * @return Content|bool|null The content object created from $text. If $text was false
2614 * or null, false resp. null will be returned instead.
2616 * @throws MWException If unserializing the text results in a Content
2617 * object that is not an instance of TextContent and
2618 * $this->allowNonTextContent is not true.
2620 protected function toEditContent( $text ) {
2621 if ( $text === false ||
$text === null ) {
2625 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2626 $this->contentModel
, $this->contentFormat
);
2628 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2629 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2636 * Send the edit form and related headers to OutputPage
2637 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2638 * during form output near the top, for captchas and the like.
2640 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2641 * use the EditPage::showEditForm:fields hook instead.
2643 public function showEditForm( $formCallback = null ) {
2644 # need to parse the preview early so that we know which templates are used,
2645 # otherwise users with "show preview after edit box" will get a blank list
2646 # we parse this near the beginning so that setHeaders can do the title
2647 # setting work instead of leaving it in getPreviewText
2648 $previewOutput = '';
2649 if ( $this->formtype
== 'preview' ) {
2650 $previewOutput = $this->getPreviewText();
2653 $out = $this->context
->getOutput();
2655 // Avoid PHP 7.1 warning of passing $this by reference
2657 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2659 $this->setHeaders();
2661 $this->addTalkPageText();
2662 $this->addEditNotices();
2664 if ( !$this->isConflict
&&
2665 $this->section
!= '' &&
2666 !$this->isSectionEditSupported() ) {
2667 // We use $this->section to much before this and getVal('wgSection') directly in other places
2668 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2669 // Someone is welcome to try refactoring though
2670 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2674 $this->showHeader();
2676 $out->addHTML( $this->editFormPageTop
);
2678 $user = $this->context
->getUser();
2679 if ( $user->getOption( 'previewontop' ) ) {
2680 $this->displayPreviewArea( $previewOutput, true );
2683 $out->addHTML( $this->editFormTextTop
);
2685 $showToolbar = true;
2686 if ( $this->wasDeletedSinceLastEdit() ) {
2687 if ( $this->formtype
== 'save' ) {
2688 // Hide the toolbar and edit area, user can click preview to get it back
2689 // Add an confirmation checkbox and explanation.
2690 $showToolbar = false;
2692 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2693 'deletedwhileediting' );
2697 // @todo add EditForm plugin interface and use it here!
2698 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2699 $out->addHTML( Html
::openElement(
2702 'class' => 'mw-editform',
2703 'id' => self
::EDITFORM_ID
,
2704 'name' => self
::EDITFORM_ID
,
2706 'action' => $this->getActionURL( $this->getContextTitle() ),
2707 'enctype' => 'multipart/form-data'
2711 if ( is_callable( $formCallback ) ) {
2712 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2713 call_user_func_array( $formCallback, [ &$out ] );
2716 // Add a check for Unicode support
2717 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2719 // Add an empty field to trip up spambots
2721 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2724 [ 'for' => 'wpAntispam' ],
2725 $this->context
->msg( 'simpleantispam-label' )->parse()
2731 'name' => 'wpAntispam',
2732 'id' => 'wpAntispam',
2736 . Xml
::closeElement( 'div' )
2739 // Avoid PHP 7.1 warning of passing $this by reference
2741 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2743 // Put these up at the top to ensure they aren't lost on early form submission
2744 $this->showFormBeforeText();
2746 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2747 $username = $this->lastDelete
->user_name
;
2748 $comment = CommentStore
::newKey( 'log_comment' )->getComment( $this->lastDelete
)->text
;
2750 // It is better to not parse the comment at all than to have templates expanded in the middle
2751 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2752 $key = $comment === ''
2753 ?
'confirmrecreate-noreason'
2754 : 'confirmrecreate';
2756 '<div class="mw-confirm-recreate">' .
2757 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2758 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2759 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2765 # When the summary is hidden, also hide them on preview/show changes
2766 if ( $this->nosummary
) {
2767 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2770 # If a blank edit summary was previously provided, and the appropriate
2771 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2772 # user being bounced back more than once in the event that a summary
2775 # For a bit more sophisticated detection of blank summaries, hash the
2776 # automatic one and pass that in the hidden field wpAutoSummary.
2777 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2778 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2781 if ( $this->undidRev
) {
2782 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2785 if ( $this->selfRedirect
) {
2786 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2789 if ( $this->hasPresetSummary
) {
2790 // If a summary has been preset using &summary= we don't want to prompt for
2791 // a different summary. Only prompt for a summary if the summary is blanked.
2793 $this->autoSumm
= md5( '' );
2796 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2797 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2799 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2800 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2802 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2803 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2807 if ( $this->section
== 'new' ) {
2808 $this->showSummaryInput( true, $this->summary
);
2809 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2812 $out->addHTML( $this->editFormTextBeforeContent
);
2814 if ( !$this->mTitle
->isCssJsSubpage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2815 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2818 if ( $this->blankArticle
) {
2819 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2822 if ( $this->isConflict
) {
2823 // In an edit conflict bypass the overridable content form method
2824 // and fallback to the raw wpTextbox1 since editconflicts can't be
2825 // resolved between page source edits and custom ui edits using the
2827 $this->textbox2
= $this->textbox1
;
2829 $content = $this->getCurrentContent();
2830 $this->textbox1
= $this->toEditText( $content );
2832 $this->showTextbox1();
2834 $this->showContentForm();
2837 $out->addHTML( $this->editFormTextAfterContent
);
2839 $this->showStandardInputs();
2841 $this->showFormAfterText();
2843 $this->showTosSummary();
2845 $this->showEditTools();
2847 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2849 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2851 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2852 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2854 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2855 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2857 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2859 if ( $this->isConflict
) {
2861 $this->showConflict();
2862 } catch ( MWContentSerializationException
$ex ) {
2863 // this can't really happen, but be nice if it does.
2864 $msg = $this->context
->msg(
2865 'content-failed-to-parse',
2866 $this->contentModel
,
2867 $this->contentFormat
,
2870 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2874 // Set a hidden field so JS knows what edit form mode we are in
2875 if ( $this->isConflict
) {
2877 } elseif ( $this->preview
) {
2879 } elseif ( $this->diff
) {
2884 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2886 // Marker for detecting truncated form data. This must be the last
2887 // parameter sent in order to be of use, so do not move me.
2888 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2889 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2891 if ( !$user->getOption( 'previewontop' ) ) {
2892 $this->displayPreviewArea( $previewOutput, false );
2897 * Wrapper around TemplatesOnThisPageFormatter to make
2898 * a "templates on this page" list.
2900 * @param Title[] $templates
2901 * @return string HTML
2903 public function makeTemplatesOnThisPageList( array $templates ) {
2904 $templateListFormatter = new TemplatesOnThisPageFormatter(
2905 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2908 // preview if preview, else section if section, else false
2910 if ( $this->preview
) {
2912 } elseif ( $this->section
!= '' ) {
2916 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2917 $templateListFormatter->format( $templates, $type )
2922 * Extract the section title from current section text, if any.
2924 * @param string $text
2925 * @return string|bool String or false
2927 public static function extractSectionTitle( $text ) {
2928 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2929 if ( !empty( $matches[2] ) ) {
2931 return $wgParser->stripSectionName( trim( $matches[2] ) );
2937 protected function showHeader() {
2938 $out = $this->context
->getOutput();
2939 $user = $this->context
->getUser();
2940 if ( $this->isConflict
) {
2941 $this->addExplainConflictHeader( $out );
2942 $this->editRevId
= $this->page
->getLatest();
2944 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2945 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2946 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2947 if ( $sectionTitle !== false ) {
2948 $this->summary
= "/* $sectionTitle */ ";