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
;
27 * The edit page/HTML interface (split from Article)
28 * The actual database and text munging is still in Article,
29 * but it should get easier to call those from alternate
32 * EditPage cares about two distinct titles:
33 * $this->mContextTitle is the page that forms submit to, links point to,
34 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
35 * page in the database that is actually being edited. These are
36 * usually the same, but they are now allowed to be different.
38 * Surgeon General's Warning: prolonged exposure to this class is known to cause
39 * headaches, which may be fatal.
43 * Status: Article successfully updated
45 const AS_SUCCESS_UPDATE
= 200;
48 * Status: Article successfully created
50 const AS_SUCCESS_NEW_ARTICLE
= 201;
53 * Status: Article update aborted by a hook function
55 const AS_HOOK_ERROR
= 210;
58 * Status: A hook function returned an error
60 const AS_HOOK_ERROR_EXPECTED
= 212;
63 * Status: User is blocked from editing this page
65 const AS_BLOCKED_PAGE_FOR_USER
= 215;
68 * Status: Content too big (> $wgMaxArticleSize)
70 const AS_CONTENT_TOO_BIG
= 216;
73 * Status: this anonymous user is not allowed to edit this page
75 const AS_READ_ONLY_PAGE_ANON
= 218;
78 * Status: this logged in user is not allowed to edit this page
80 const AS_READ_ONLY_PAGE_LOGGED
= 219;
83 * Status: wiki is in readonly mode (wfReadOnly() == true)
85 const AS_READ_ONLY_PAGE
= 220;
88 * Status: rate limiter for action 'edit' was tripped
90 const AS_RATE_LIMITED
= 221;
93 * Status: article was deleted while editing and param wpRecreate == false or form
96 const AS_ARTICLE_WAS_DELETED
= 222;
99 * Status: user tried to create this page, but is not allowed to do that
100 * ( Title->userCan('create') == false )
102 const AS_NO_CREATE_PERMISSION
= 223;
105 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
107 const AS_BLANK_ARTICLE
= 224;
110 * Status: (non-resolvable) edit conflict
112 const AS_CONFLICT_DETECTED
= 225;
115 * Status: no edit summary given and the user has forceeditsummary set and the user is not
116 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
118 const AS_SUMMARY_NEEDED
= 226;
121 * Status: user tried to create a new section without content
123 const AS_TEXTBOX_EMPTY
= 228;
126 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
128 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
131 * Status: WikiPage::doEdit() was unsuccessful
136 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
138 const AS_SPAM_ERROR
= 232;
141 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
143 const AS_IMAGE_REDIRECT_ANON
= 233;
146 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
148 const AS_IMAGE_REDIRECT_LOGGED
= 234;
151 * Status: user tried to modify the content model, but is not allowed to do that
152 * ( User::isAllowed('editcontentmodel') == false )
154 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
157 * Status: user tried to create self-redirect (redirect to the same article) and
158 * wpIgnoreSelfRedirect == false
160 const AS_SELF_REDIRECT
= 236;
163 * Status: an error relating to change tagging. Look at the message key for
166 const AS_CHANGE_TAG_ERROR
= 237;
169 * Status: can't parse content
171 const AS_PARSE_ERROR
= 240;
174 * Status: when changing the content model is disallowed due to
175 * $wgContentHandlerUseDB being false
177 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
180 * HTML id and name for the beginning of the edit form.
182 const EDITFORM_ID
= 'editform';
185 * Prefix of key for cookie used to pass post-edit state.
186 * The revision id edited is added after this
188 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
191 * Duration of PostEdit cookie, in seconds.
192 * The cookie will be removed instantly if the JavaScript runs.
194 * Otherwise, though, we don't want the cookies to accumulate.
195 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
196 * limit of only 20 cookies per domain. This still applies at least to some
197 * versions of IE without full updates:
198 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
200 * A value of 20 minutes should be enough to take into account slow loads and minor
201 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
203 const POST_EDIT_COOKIE_DURATION
= 1200;
213 /** @var null|Title */
214 private $mContextTitle = null;
217 public $action = 'submit';
220 public $isConflict = false;
223 public $isCssJsSubpage = false;
226 public $isCssSubpage = false;
229 public $isJsSubpage = false;
232 public $isWrongCaseCssJsPage = false;
234 /** @var bool New page or new section */
235 public $isNew = false;
238 public $deletedSinceEdit;
246 /** @var bool|stdClass */
250 public $mTokenOk = false;
253 public $mTokenOkExceptSuffix = false;
256 public $mTriedSave = false;
259 public $incompleteForm = false;
262 public $tooBig = false;
265 public $missingComment = false;
268 public $missingSummary = false;
271 public $allowBlankSummary = false;
274 protected $blankArticle = false;
277 protected $allowBlankArticle = false;
280 protected $selfRedirect = false;
283 protected $allowSelfRedirect = false;
286 public $autoSumm = '';
289 public $hookError = '';
291 /** @var ParserOutput */
292 public $mParserOutput;
294 /** @var bool Has a summary been preset using GET parameter &summary= ? */
295 public $hasPresetSummary = false;
298 public $mBaseRevision = false;
301 public $mShowSummaryField = true;
306 public $save = false;
309 public $preview = false;
312 public $diff = false;
315 public $minoredit = false;
318 public $watchthis = false;
321 public $recreate = false;
324 public $textbox1 = '';
327 public $textbox2 = '';
330 public $summary = '';
333 public $nosummary = false;
336 public $edittime = '';
339 private $editRevId = null;
342 public $section = '';
345 public $sectiontitle = '';
348 public $starttime = '';
354 public $parentRevId = 0;
357 public $editintro = '';
360 public $scrolltop = null;
365 /** @var null|string */
366 public $contentModel = null;
368 /** @var null|string */
369 public $contentFormat = null;
371 /** @var null|array */
372 private $changeTags = null;
374 # Placeholders for text injection by hooks (must be HTML)
375 # extensions should take care to _append_ to the present value
377 /** @var string Before even the preview */
378 public $editFormPageTop = '';
379 public $editFormTextTop = '';
380 public $editFormTextBeforeContent = '';
381 public $editFormTextAfterWarn = '';
382 public $editFormTextAfterTools = '';
383 public $editFormTextBottom = '';
384 public $editFormTextAfterContent = '';
385 public $previewTextAfterContent = '';
386 public $mPreloadContent = null;
388 /* $didSave should be set to true whenever an article was successfully altered. */
389 public $didSave = false;
390 public $undidRev = 0;
392 public $suppressIntro = false;
398 protected $contentLength = false;
401 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
403 private $enableApiEditOverride = false;
406 * @var IContextSource
411 * @param Article $article
413 public function __construct( Article
$article ) {
414 $this->mArticle
= $article;
415 $this->page
= $article->getPage(); // model object
416 $this->mTitle
= $article->getTitle();
417 $this->context
= $article->getContext();
419 $this->contentModel
= $this->mTitle
->getContentModel();
421 $handler = ContentHandler
::getForModelID( $this->contentModel
);
422 $this->contentFormat
= $handler->getDefaultFormat();
428 public function getArticle() {
429 return $this->mArticle
;
434 * @return IContextSource
436 public function getContext() {
437 return $this->context
;
444 public function getTitle() {
445 return $this->mTitle
;
449 * Set the context Title object
451 * @param Title|null $title Title object or null
453 public function setContextTitle( $title ) {
454 $this->mContextTitle
= $title;
458 * Get the context title object.
459 * If not set, $wgTitle will be returned. This behavior might change in
460 * the future to return $this->mTitle instead.
464 public function getContextTitle() {
465 if ( is_null( $this->mContextTitle
) ) {
469 return $this->mContextTitle
;
474 * Returns if the given content model is editable.
476 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
478 * @throws MWException If $modelId has no known handler
480 public function isSupportedContentModel( $modelId ) {
481 return $this->enableApiEditOverride
=== true ||
482 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
486 * Allow editing of content that supports API direct editing, but not general
487 * direct editing. Set to false by default.
489 * @param bool $enableOverride
491 public function setApiEditOverride( $enableOverride ) {
492 $this->enableApiEditOverride
= $enableOverride;
500 * This is the function that gets called for "action=edit". It
501 * sets up various member variables, then passes execution to
502 * another function, usually showEditForm()
504 * The edit form is self-submitting, so that when things like
505 * preview and edit conflicts occur, we get the same form back
506 * with the extra stuff added. Only when the final submission
507 * is made and all is well do we actually save and redirect to
508 * the newly-edited page.
511 global $wgOut, $wgRequest, $wgUser;
512 // Allow extensions to modify/prevent this form or submission
513 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
517 wfDebug( __METHOD__
. ": enter\n" );
519 // If they used redlink=1 and the page exists, redirect to the main article
520 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
521 $wgOut->redirect( $this->mTitle
->getFullURL() );
525 $this->importFormData( $wgRequest );
526 $this->firsttime
= false;
528 if ( wfReadOnly() && $this->save
) {
531 $this->preview
= true;
535 $this->formtype
= 'save';
536 } elseif ( $this->preview
) {
537 $this->formtype
= 'preview';
538 } elseif ( $this->diff
) {
539 $this->formtype
= 'diff';
540 } else { # First time through
541 $this->firsttime
= true;
542 if ( $this->previewOnOpen() ) {
543 $this->formtype
= 'preview';
545 $this->formtype
= 'initial';
549 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
551 wfDebug( __METHOD__
. ": User can't edit\n" );
552 // Auto-block user's IP if the account was "hard" blocked
553 if ( !wfReadOnly() ) {
555 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
556 $user->spreadAnyEditBlock();
559 $this->displayPermissionsError( $permErrors );
564 $revision = $this->mArticle
->getRevisionFetched();
565 // Disallow editing revisions with content models different from the current one
566 // Undo edits being an exception in order to allow reverting content model changes.
568 && $revision->getContentModel() !== $this->contentModel
571 if ( $this->undidRev
) {
572 $undidRevObj = Revision
::newFromId( $this->undidRev
);
573 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
575 if ( !$this->undidRev
577 ||
$prevRev->getContentModel() !== $this->contentModel
579 $this->displayViewSourcePage(
580 $this->getContentObject(),
582 'contentmodelediterror',
583 $revision->getContentModel(),
591 $this->isConflict
= false;
592 // css / js subpages of user pages get a special treatment
593 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
594 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
595 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
596 // @todo FIXME: Silly assignment.
597 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
599 # Show applicable editing introductions
600 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
604 # Attempt submission here. This will check for edit conflicts,
605 # and redundantly check for locked database, blocked IPs, etc.
606 # that edit() already checked just in case someone tries to sneak
607 # in the back door with a hand-edited submission URL.
609 if ( 'save' == $this->formtype
) {
610 $resultDetails = null;
611 $status = $this->attemptSave( $resultDetails );
612 if ( !$this->handleStatus( $status, $resultDetails ) ) {
617 # First time through: get contents, set time for conflict
619 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
620 if ( $this->initialiseForm() === false ) {
621 $this->noSuchSectionPage();
625 if ( !$this->mTitle
->getArticleID() ) {
626 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
628 Hooks
::run( 'EditFormInitialText', [ $this ] );
633 $this->showEditForm();
637 * @param string $rigor Same format as Title::getUserPermissionErrors()
640 protected function getEditPermissionErrors( $rigor = 'secure' ) {
643 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
644 # Can this title be created?
645 if ( !$this->mTitle
->exists() ) {
646 $permErrors = array_merge(
649 $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
654 # Ignore some permissions errors when a user is just previewing/viewing diffs
656 foreach ( $permErrors as $error ) {
657 if ( ( $this->preview ||
$this->diff
)
658 && ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' )
663 $permErrors = wfArrayDiff2( $permErrors, $remove );
669 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
670 * but with the following differences:
671 * - If redlink=1, the user will be redirected to the page
672 * - If there is content to display or the error occurs while either saving,
673 * previewing or showing the difference, it will be a
674 * "View source for ..." page displaying the source code after the error message.
677 * @param array $permErrors Array of permissions errors, as returned by
678 * Title::getUserPermissionsErrors().
679 * @throws PermissionsError
681 protected function displayPermissionsError( array $permErrors ) {
682 global $wgRequest, $wgOut;
684 if ( $wgRequest->getBool( 'redlink' ) ) {
685 // The edit page was reached via a red link.
686 // Redirect to the article page and let them click the edit tab if
687 // they really want a permission error.
688 $wgOut->redirect( $this->mTitle
->getFullURL() );
692 $content = $this->getContentObject();
694 # Use the normal message if there's nothing to display
695 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
696 $action = $this->mTitle
->exists() ?
'edit' :
697 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
698 throw new PermissionsError( $action, $permErrors );
701 $this->displayViewSourcePage(
703 $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' )
708 * Display a read-only View Source page
709 * @param Content $content content object
710 * @param string $errorMessage additional wikitext error message to display
712 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
715 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$wgOut ] );
717 $wgOut->setRobotPolicy( 'noindex,nofollow' );
718 $wgOut->setPageTitle( $this->context
->msg(
720 $this->getContextTitle()->getPrefixedText()
722 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
723 $wgOut->addHTML( $this->editFormPageTop
);
724 $wgOut->addHTML( $this->editFormTextTop
);
726 if ( $errorMessage !== '' ) {
727 $wgOut->addWikiText( $errorMessage );
728 $wgOut->addHTML( "<hr />\n" );
731 # If the user made changes, preserve them when showing the markup
732 # (This happens when a user is blocked during edit, for instance)
733 if ( !$this->firsttime
) {
734 $text = $this->textbox1
;
735 $wgOut->addWikiMsg( 'viewyourtext' );
738 $text = $this->toEditText( $content );
739 } catch ( MWException
$e ) {
740 # Serialize using the default format if the content model is not supported
741 # (e.g. for an old revision with a different model)
742 $text = $content->serialize();
744 $wgOut->addWikiMsg( 'viewsourcetext' );
747 $wgOut->addHTML( $this->editFormTextBeforeContent
);
748 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
749 $wgOut->addHTML( $this->editFormTextAfterContent
);
751 $wgOut->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
753 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
755 $wgOut->addHTML( $this->editFormTextBottom
);
756 if ( $this->mTitle
->exists() ) {
757 $wgOut->returnToMain( null, $this->mTitle
);
762 * Should we show a preview when the edit form is first shown?
766 protected function previewOnOpen() {
767 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
768 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
769 // Explicit override from request
771 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
772 // Explicit override from request
774 } elseif ( $this->section
== 'new' ) {
775 // Nothing *to* preview for new sections
777 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
778 && $wgUser->getOption( 'previewonfirst' )
780 // Standard preference behavior
782 } elseif ( !$this->mTitle
->exists()
783 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
784 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
786 // Categories are special
794 * Checks whether the user entered a skin name in uppercase,
795 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
799 protected function isWrongCaseCssJsPage() {
800 if ( $this->mTitle
->isCssJsSubpage() ) {
801 $name = $this->mTitle
->getSkinFromCssJsSubpage();
802 $skins = array_merge(
803 array_keys( Skin
::getSkinNames() ),
806 return !in_array( $name, $skins )
807 && in_array( strtolower( $name ), $skins );
814 * Returns whether section editing is supported for the current page.
815 * Subclasses may override this to replace the default behavior, which is
816 * to check ContentHandler::supportsSections.
818 * @return bool True if this edit page supports sections, false otherwise.
820 protected function isSectionEditSupported() {
821 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
822 return $contentHandler->supportsSections();
826 * This function collects the form data and uses it to populate various member variables.
827 * @param WebRequest $request
828 * @throws ErrorPageError
830 function importFormData( &$request ) {
831 global $wgContLang, $wgUser;
833 # Section edit can come from either the form or a link
834 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
836 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
837 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
840 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
842 if ( $request->wasPosted() ) {
843 # These fields need to be checked for encoding.
844 # Also remove trailing whitespace, but don't remove _initial_
845 # whitespace from the text boxes. This may be significant formatting.
846 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
847 if ( !$request->getCheck( 'wpTextbox2' ) ) {
848 // Skip this if wpTextbox2 has input, it indicates that we came
849 // from a conflict page with raw page text, not a custom form
850 // modified by subclasses
851 $textbox1 = $this->importContentFormData( $request );
852 if ( $textbox1 !== null ) {
853 $this->textbox1
= $textbox1;
857 # Truncate for whole multibyte characters
858 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
860 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
861 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
863 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
865 # Treat sectiontitle the same way as summary.
866 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
867 # currently doing double duty as both edit summary and section title. Right now this
868 # is just to allow API edits to work around this limitation, but this should be
869 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
870 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
871 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
873 $this->edittime
= $request->getVal( 'wpEdittime' );
874 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
875 $this->starttime
= $request->getVal( 'wpStarttime' );
877 $undidRev = $request->getInt( 'wpUndidRevision' );
879 $this->undidRev
= $undidRev;
882 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
884 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
885 // wpTextbox1 field is missing, possibly due to being "too big"
886 // according to some filter rules such as Suhosin's setting for
887 // suhosin.request.max_value_length (d'oh)
888 $this->incompleteForm
= true;
890 // If we receive the last parameter of the request, we can fairly
891 // claim the POST request has not been truncated.
893 // TODO: softened the check for cutover. Once we determine
894 // that it is safe, we should complete the transition by
895 // removing the "edittime" clause.
896 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
897 && is_null( $this->edittime
) );
899 if ( $this->incompleteForm
) {
900 # If the form is incomplete, force to preview.
901 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
902 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
903 $this->preview
= true;
905 $this->preview
= $request->getCheck( 'wpPreview' );
906 $this->diff
= $request->getCheck( 'wpDiff' );
908 // Remember whether a save was requested, so we can indicate
909 // if we forced preview due to session failure.
910 $this->mTriedSave
= !$this->preview
;
912 if ( $this->tokenOk( $request ) ) {
913 # Some browsers will not report any submit button
914 # if the user hits enter in the comment box.
915 # The unmarked state will be assumed to be a save,
916 # if the form seems otherwise complete.
917 wfDebug( __METHOD__
. ": Passed token check.\n" );
918 } elseif ( $this->diff
) {
919 # Failed token check, but only requested "Show Changes".
920 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
922 # Page might be a hack attempt posted from
923 # an external site. Preview instead of saving.
924 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
925 $this->preview
= true;
928 $this->save
= !$this->preview
&& !$this->diff
;
929 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
930 $this->edittime
= null;
933 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
934 $this->starttime
= null;
937 $this->recreate
= $request->getCheck( 'wpRecreate' );
939 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
940 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
942 # Don't force edit summaries when a user is editing their own user or talk page
943 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
944 && $this->mTitle
->getText() == $wgUser->getName()
946 $this->allowBlankSummary
= true;
948 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
949 ||
!$wgUser->getOption( 'forceeditsummary' );
952 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
954 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
955 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
957 $changeTags = $request->getVal( 'wpChangeTags' );
958 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
959 $this->changeTags
= [];
961 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
965 # Not a posted form? Start with nothing.
966 wfDebug( __METHOD__
. ": Not a posted form.\n" );
967 $this->textbox1
= '';
969 $this->sectiontitle
= '';
970 $this->edittime
= '';
971 $this->editRevId
= null;
972 $this->starttime
= wfTimestampNow();
974 $this->preview
= false;
977 $this->minoredit
= false;
978 // Watch may be overridden by request parameters
979 $this->watchthis
= $request->getBool( 'watchthis', false );
980 $this->recreate
= false;
982 // When creating a new section, we can preload a section title by passing it as the
983 // preloadtitle parameter in the URL (Bug 13100)
984 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
985 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
986 // Once wpSummary isn't being use for setting section titles, we should delete this.
987 $this->summary
= $request->getVal( 'preloadtitle' );
988 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
989 $this->summary
= $request->getText( 'summary' );
990 if ( $this->summary
!== '' ) {
991 $this->hasPresetSummary
= true;
995 if ( $request->getVal( 'minor' ) ) {
996 $this->minoredit
= true;
1000 $this->oldid
= $request->getInt( 'oldid' );
1001 $this->parentRevId
= $request->getInt( 'parentRevId' );
1003 $this->bot
= $request->getBool( 'bot', true );
1004 $this->nosummary
= $request->getBool( 'nosummary' );
1006 // May be overridden by revision.
1007 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1008 // May be overridden by revision.
1009 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1012 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1013 } catch ( MWUnknownContentModelException
$e ) {
1014 throw new ErrorPageError(
1015 'editpage-invalidcontentmodel-title',
1016 'editpage-invalidcontentmodel-text',
1017 [ $this->contentModel
]
1021 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1022 throw new ErrorPageError(
1023 'editpage-notsupportedcontentformat-title',
1024 'editpage-notsupportedcontentformat-text',
1025 [ $this->contentFormat
, ContentHandler
::getLocalizedName( $this->contentModel
) ]
1030 * @todo Check if the desired model is allowed in this namespace, and if
1031 * a transition from the page's current model to the new model is
1035 $this->editintro
= $request->getText( 'editintro',
1036 // Custom edit intro for new sections
1037 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1039 // Allow extensions to modify form data
1040 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1045 * Subpage overridable method for extracting the page content data from the
1046 * posted form to be placed in $this->textbox1, if using customized input
1047 * this method should be overridden and return the page text that will be used
1048 * for saving, preview parsing and so on...
1050 * @param WebRequest $request
1051 * @return string|null
1053 protected function importContentFormData( &$request ) {
1054 return; // Don't do anything, EditPage already extracted wpTextbox1
1058 * Initialise form fields in the object
1059 * Called on the first invocation, e.g. when a user clicks an edit link
1060 * @return bool If the requested section is valid
1062 function initialiseForm() {
1064 $this->edittime
= $this->page
->getTimestamp();
1065 $this->editRevId
= $this->page
->getLatest();
1067 $content = $this->getContentObject( false ); # TODO: track content object?!
1068 if ( $content === false ) {
1071 $this->textbox1
= $this->toEditText( $content );
1073 // activate checkboxes if user wants them to be always active
1074 # Sort out the "watch" checkbox
1075 if ( $wgUser->getOption( 'watchdefault' ) ) {
1077 $this->watchthis
= true;
1078 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1080 $this->watchthis
= true;
1081 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
1083 $this->watchthis
= true;
1085 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
1086 $this->minoredit
= true;
1088 if ( $this->textbox1
=== false ) {
1095 * @param Content|null $def_content The default value to return
1097 * @return Content|null Content on success, $def_content for invalid sections
1101 protected function getContentObject( $def_content = null ) {
1102 global $wgOut, $wgRequest, $wgUser, $wgContLang;
1106 // For message page not locally set, use the i18n message.
1107 // For other non-existent articles, use preload text if any.
1108 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1109 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1110 # If this is a system message, get the default text.
1111 $msg = $this->mTitle
->getDefaultMessageText();
1113 $content = $this->toEditContent( $msg );
1115 if ( $content === false ) {
1116 # If requested, preload some text.
1117 $preload = $wgRequest->getVal( 'preload',
1118 // Custom preload text for new sections
1119 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1120 $params = $wgRequest->getArray( 'preloadparams', [] );
1122 $content = $this->getPreloadedContent( $preload, $params );
1124 // For existing pages, get text based on "undo" or section parameters.
1126 if ( $this->section
!= '' ) {
1127 // Get section edit text (returns $def_text for invalid sections)
1128 $orig = $this->getOriginalContent( $wgUser );
1129 $content = $orig ?
$orig->getSection( $this->section
) : null;
1132 $content = $def_content;
1135 $undoafter = $wgRequest->getInt( 'undoafter' );
1136 $undo = $wgRequest->getInt( 'undo' );
1138 if ( $undo > 0 && $undoafter > 0 ) {
1139 $undorev = Revision
::newFromId( $undo );
1140 $oldrev = Revision
::newFromId( $undoafter );
1142 # Sanity check, make sure it's the right page,
1143 # the revisions exist and they were not deleted.
1144 # Otherwise, $content will be left as-is.
1145 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1146 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1147 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1149 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1151 if ( $content === false ) {
1152 # Warn the user that something went wrong
1153 $undoMsg = 'failure';
1155 $oldContent = $this->page
->getContent( Revision
::RAW
);
1156 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
1157 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
1158 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1159 // The undo may change content
1160 // model if its reverting the top
1161 // edit. This can result in
1162 // mismatched content model/format.
1163 $this->contentModel
= $newContent->getModel();
1164 $this->contentFormat
= $oldrev->getContentFormat();
1167 if ( $newContent->equals( $oldContent ) ) {
1168 # Tell the user that the undo results in no change,
1169 # i.e. the revisions were already undone.
1170 $undoMsg = 'nochange';
1173 # Inform the user of our success and set an automatic edit summary
1174 $undoMsg = 'success';
1176 # If we just undid one rev, use an autosummary
1177 $firstrev = $oldrev->getNext();
1178 if ( $firstrev && $firstrev->getId() == $undo ) {
1179 $userText = $undorev->getUserText();
1180 if ( $userText === '' ) {
1181 $undoSummary = $this->context
->msg(
1182 'undo-summary-username-hidden',
1184 )->inContentLanguage()->text();
1186 $undoSummary = $this->context
->msg(
1190 )->inContentLanguage()->text();
1192 if ( $this->summary
=== '' ) {
1193 $this->summary
= $undoSummary;
1195 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1196 ->inContentLanguage()->text() . $this->summary
;
1198 $this->undidRev
= $undo;
1200 $this->formtype
= 'diff';
1204 // Failed basic sanity checks.
1205 // Older revisions may have been removed since the link
1206 // was created, or we may simply have got bogus input.
1210 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1211 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1212 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
1213 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1216 if ( $content === false ) {
1217 $content = $this->getOriginalContent( $wgUser );
1226 * Get the content of the wanted revision, without section extraction.
1228 * The result of this function can be used to compare user's input with
1229 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1230 * to the original text of the edit.
1232 * This differs from Article::getContent() that when a missing revision is
1233 * encountered the result will be null and not the
1234 * 'missing-revision' message.
1237 * @param User $user The user to get the revision for
1238 * @return Content|null
1240 private function getOriginalContent( User
$user ) {
1241 if ( $this->section
== 'new' ) {
1242 return $this->getCurrentContent();
1244 $revision = $this->mArticle
->getRevisionFetched();
1245 if ( $revision === null ) {
1246 if ( !$this->contentModel
) {
1247 $this->contentModel
= $this->getTitle()->getContentModel();
1249 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1251 return $handler->makeEmptyContent();
1253 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1258 * Get the edit's parent revision ID
1260 * The "parent" revision is the ancestor that should be recorded in this
1261 * page's revision history. It is either the revision ID of the in-memory
1262 * article content, or in the case of a 3-way merge in order to rebase
1263 * across a recoverable edit conflict, the ID of the newer revision to
1264 * which we have rebased this page.
1267 * @return int Revision ID
1269 public function getParentRevId() {
1270 if ( $this->parentRevId
) {
1271 return $this->parentRevId
;
1273 return $this->mArticle
->getRevIdFetched();
1278 * Get the current content of the page. This is basically similar to
1279 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1280 * content object is returned instead of null.
1285 protected function getCurrentContent() {
1286 $rev = $this->page
->getRevision();
1287 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1289 if ( $content === false ||
$content === null ) {
1290 if ( !$this->contentModel
) {
1291 $this->contentModel
= $this->getTitle()->getContentModel();
1293 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1295 return $handler->makeEmptyContent();
1296 } elseif ( !$this->undidRev
) {
1297 // Content models should always be the same since we error
1298 // out if they are different before this point (in ->edit()).
1299 // The exception being, during an undo, the current revision might
1300 // differ from the prior revision.
1301 $logger = LoggerFactory
::getInstance( 'editpage' );
1302 if ( $this->contentModel
!== $rev->getContentModel() ) {
1303 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1304 'prev' => $this->contentModel
,
1305 'new' => $rev->getContentModel(),
1306 'title' => $this->getTitle()->getPrefixedDBkey(),
1307 'method' => __METHOD__
1309 $this->contentModel
= $rev->getContentModel();
1312 // Given that the content models should match, the current selected
1313 // format should be supported.
1314 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1315 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1317 'prev' => $this->contentFormat
,
1318 'new' => $rev->getContentFormat(),
1319 'title' => $this->getTitle()->getPrefixedDBkey(),
1320 'method' => __METHOD__
1322 $this->contentFormat
= $rev->getContentFormat();
1329 * Use this method before edit() to preload some content into the edit box
1331 * @param Content $content
1335 public function setPreloadedContent( Content
$content ) {
1336 $this->mPreloadContent
= $content;
1340 * Get the contents to be preloaded into the box, either set by
1341 * an earlier setPreloadText() or by loading the given page.
1343 * @param string $preload Representing the title to preload from.
1344 * @param array $params Parameters to use (interface-message style) in the preloaded text
1350 protected function getPreloadedContent( $preload, $params = [] ) {
1353 if ( !empty( $this->mPreloadContent
) ) {
1354 return $this->mPreloadContent
;
1357 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1359 if ( $preload === '' ) {
1360 return $handler->makeEmptyContent();
1363 $title = Title
::newFromText( $preload );
1364 # Check for existence to avoid getting MediaWiki:Noarticletext
1365 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1366 // TODO: somehow show a warning to the user!
1367 return $handler->makeEmptyContent();
1370 $page = WikiPage
::factory( $title );
1371 if ( $page->isRedirect() ) {
1372 $title = $page->getRedirectTarget();
1374 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1375 // TODO: somehow show a warning to the user!
1376 return $handler->makeEmptyContent();
1378 $page = WikiPage
::factory( $title );
1381 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1382 $content = $page->getContent( Revision
::RAW
);
1385 // TODO: somehow show a warning to the user!
1386 return $handler->makeEmptyContent();
1389 if ( $content->getModel() !== $handler->getModelID() ) {
1390 $converted = $content->convert( $handler->getModelID() );
1392 if ( !$converted ) {
1393 // TODO: somehow show a warning to the user!
1394 wfDebug( "Attempt to preload incompatible content: " .
1395 "can't convert " . $content->getModel() .
1396 " to " . $handler->getModelID() );
1398 return $handler->makeEmptyContent();
1401 $content = $converted;
1404 return $content->preloadTransform( $title, $parserOptions, $params );
1408 * Make sure the form isn't faking a user's credentials.
1410 * @param WebRequest $request
1414 function tokenOk( &$request ) {
1416 $token = $request->getVal( 'wpEditToken' );
1417 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1418 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1419 return $this->mTokenOk
;
1423 * Sets post-edit cookie indicating the user just saved a particular revision.
1425 * This uses a temporary cookie for each revision ID so separate saves will never
1426 * interfere with each other.
1428 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1429 * the redirect. It must be clearable by JavaScript code, so it must not be
1430 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1433 * If the variable were set on the server, it would be cached, which is unwanted
1434 * since the post-edit state should only apply to the load right after the save.
1436 * @param int $statusValue The status value (to check for new article status)
1438 protected function setPostEditCookie( $statusValue ) {
1439 $revisionId = $this->page
->getLatest();
1440 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1443 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1445 } elseif ( $this->oldid
) {
1449 $response = RequestContext
::getMain()->getRequest()->response();
1450 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
, [
1451 'httpOnly' => false,
1456 * Attempt submission
1457 * @param array|bool $resultDetails See docs for $result in internalAttemptSave
1458 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1459 * @return Status The resulting status object.
1461 public function attemptSave( &$resultDetails = false ) {
1464 # Allow bots to exempt some edits from bot flagging
1465 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1466 $status = $this->internalAttemptSave( $resultDetails, $bot );
1468 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1474 * Handle status, such as after attempt save
1476 * @param Status $status
1477 * @param array|bool $resultDetails
1479 * @throws ErrorPageError
1480 * @return bool False, if output is done, true if rest of the form should be displayed
1482 private function handleStatus( Status
$status, $resultDetails ) {
1483 global $wgUser, $wgOut;
1486 * @todo FIXME: once the interface for internalAttemptSave() is made
1487 * nicer, this should use the message in $status
1489 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1490 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1492 $this->didSave
= true;
1493 if ( !$resultDetails['nullEdit'] ) {
1494 $this->setPostEditCookie( $status->value
);
1498 // "wpExtraQueryRedirect" is a hidden input to modify
1499 // after save URL and is not used by actual edit form
1500 $request = RequestContext
::getMain()->getRequest();
1501 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1503 switch ( $status->value
) {
1504 case self
::AS_HOOK_ERROR_EXPECTED
:
1505 case self
::AS_CONTENT_TOO_BIG
:
1506 case self
::AS_ARTICLE_WAS_DELETED
:
1507 case self
::AS_CONFLICT_DETECTED
:
1508 case self
::AS_SUMMARY_NEEDED
:
1509 case self
::AS_TEXTBOX_EMPTY
:
1510 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1512 case self
::AS_BLANK_ARTICLE
:
1513 case self
::AS_SELF_REDIRECT
:
1516 case self
::AS_HOOK_ERROR
:
1519 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1520 case self
::AS_PARSE_ERROR
:
1521 $wgOut->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1524 case self
::AS_SUCCESS_NEW_ARTICLE
:
1525 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1526 if ( $extraQueryRedirect ) {
1527 if ( $query === '' ) {
1528 $query = $extraQueryRedirect;
1530 $query = $query . '&' . $extraQueryRedirect;
1533 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1534 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1537 case self
::AS_SUCCESS_UPDATE
:
1539 $sectionanchor = $resultDetails['sectionanchor'];
1541 // Give extensions a chance to modify URL query on update
1543 'ArticleUpdateBeforeRedirect',
1544 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1547 if ( $resultDetails['redirect'] ) {
1548 if ( $extraQuery == '' ) {
1549 $extraQuery = 'redirect=no';
1551 $extraQuery = 'redirect=no&' . $extraQuery;
1554 if ( $extraQueryRedirect ) {
1555 if ( $extraQuery === '' ) {
1556 $extraQuery = $extraQueryRedirect;
1558 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1562 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1565 case self
::AS_SPAM_ERROR
:
1566 $this->spamPageWithContent( $resultDetails['spam'] );
1569 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1570 throw new UserBlockedError( $wgUser->getBlock() );
1572 case self
::AS_IMAGE_REDIRECT_ANON
:
1573 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1574 throw new PermissionsError( 'upload' );
1576 case self
::AS_READ_ONLY_PAGE_ANON
:
1577 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1578 throw new PermissionsError( 'edit' );
1580 case self
::AS_READ_ONLY_PAGE
:
1581 throw new ReadOnlyError
;
1583 case self
::AS_RATE_LIMITED
:
1584 throw new ThrottledError();
1586 case self
::AS_NO_CREATE_PERMISSION
:
1587 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1588 throw new PermissionsError( $permission );
1590 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1591 throw new PermissionsError( 'editcontentmodel' );
1594 // We don't recognize $status->value. The only way that can happen
1595 // is if an extension hook aborted from inside ArticleSave.
1596 // Render the status object into $this->hookError
1597 // FIXME this sucks, we should just use the Status object throughout
1598 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1605 * Run hooks that can filter edits just before they get saved.
1607 * @param Content $content The Content to filter.
1608 * @param Status $status For reporting the outcome to the caller
1609 * @param User $user The user performing the edit
1613 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1614 // Run old style post-section-merge edit filter
1615 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1616 [ $this, $content, &$this->hookError
, $this->summary
],
1619 # Error messages etc. could be handled within the hook...
1620 $status->fatal( 'hookaborted' );
1621 $status->value
= self
::AS_HOOK_ERROR
;
1623 } elseif ( $this->hookError
!= '' ) {
1624 # ...or the hook could be expecting us to produce an error
1625 $status->fatal( 'hookaborted' );
1626 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1630 // Run new style post-section-merge edit filter
1631 if ( !Hooks
::run( 'EditFilterMergedContent',
1632 [ $this->mArticle
->getContext(), $content, $status, $this->summary
,
1633 $user, $this->minoredit
] )
1635 # Error messages etc. could be handled within the hook...
1636 if ( $status->isGood() ) {
1637 $status->fatal( 'hookaborted' );
1638 // Not setting $this->hookError here is a hack to allow the hook
1639 // to cause a return to the edit page without $this->hookError
1640 // being set. This is used by ConfirmEdit to display a captcha
1641 // without any error message cruft.
1643 $this->hookError
= $status->getWikiText();
1645 // Use the existing $status->value if the hook set it
1646 if ( !$status->value
) {
1647 $status->value
= self
::AS_HOOK_ERROR
;
1650 } elseif ( !$status->isOK() ) {
1651 # ...or the hook could be expecting us to produce an error
1652 // FIXME this sucks, we should just use the Status object throughout
1653 $this->hookError
= $status->getWikiText();
1654 $status->fatal( 'hookaborted' );
1655 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1663 * Return the summary to be used for a new section.
1665 * @param string $sectionanchor Set to the section anchor text
1668 private function newSectionSummary( &$sectionanchor = null ) {
1671 if ( $this->sectiontitle
!== '' ) {
1672 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1673 // If no edit summary was specified, create one automatically from the section
1674 // title and have it link to the new section. Otherwise, respect the summary as
1676 if ( $this->summary
=== '' ) {
1677 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1678 return $this->context
->msg( 'newsectionsummary' )
1679 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1681 } elseif ( $this->summary
!== '' ) {
1682 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1683 # This is a new section, so create a link to the new section
1684 # in the revision summary.
1685 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1686 return $this->context
->msg( 'newsectionsummary' )
1687 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1689 return $this->summary
;
1693 * Attempt submission (no UI)
1695 * @param array $result Array to add statuses to, currently with the
1697 * - spam (string): Spam string from content if any spam is detected by
1699 * - sectionanchor (string): Section anchor for a section save.
1700 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1702 * - redirect (bool): Set if doEditContent is OK. True if resulting
1703 * revision is a redirect.
1704 * @param bool $bot True if edit is being made under the bot right.
1706 * @return Status Status object, possibly with a message, but always with
1707 * one of the AS_* constants in $status->value,
1709 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1710 * various error display idiosyncrasies. There are also lots of cases
1711 * where error metadata is set in the object and retrieved later instead
1712 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1713 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1716 function internalAttemptSave( &$result, $bot = false ) {
1717 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1718 global $wgContentHandlerUseDB;
1720 $status = Status
::newGood();
1722 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1723 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1724 $status->fatal( 'hookaborted' );
1725 $status->value
= self
::AS_HOOK_ERROR
;
1729 $spam = $wgRequest->getText( 'wpAntispam' );
1730 if ( $spam !== '' ) {
1733 $wgUser->getName() .
1735 $this->mTitle
->getPrefixedText() .
1736 '" submitted bogus field "' .
1740 $status->fatal( 'spamprotectionmatch', false );
1741 $status->value
= self
::AS_SPAM_ERROR
;
1746 # Construct Content object
1747 $textbox_content = $this->toEditContent( $this->textbox1
);
1748 } catch ( MWContentSerializationException
$ex ) {
1750 'content-failed-to-parse',
1751 $this->contentModel
,
1752 $this->contentFormat
,
1755 $status->value
= self
::AS_PARSE_ERROR
;
1759 # Check image redirect
1760 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1761 $textbox_content->isRedirect() &&
1762 !$wgUser->isAllowed( 'upload' )
1764 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1765 $status->setResult( false, $code );
1771 $match = self
::matchSummarySpamRegex( $this->summary
);
1772 if ( $match === false && $this->section
== 'new' ) {
1773 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1774 # regular summaries, it is added to the actual wikitext.
1775 if ( $this->sectiontitle
!== '' ) {
1776 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1777 $match = self
::matchSpamRegex( $this->sectiontitle
);
1779 # This branch is taken when the "Add Topic" user interface is used, or the API
1780 # is used with the 'summary' parameter.
1781 $match = self
::matchSpamRegex( $this->summary
);
1784 if ( $match === false ) {
1785 $match = self
::matchSpamRegex( $this->textbox1
);
1787 if ( $match !== false ) {
1788 $result['spam'] = $match;
1789 $ip = $wgRequest->getIP();
1790 $pdbk = $this->mTitle
->getPrefixedDBkey();
1791 $match = str_replace( "\n", '', $match );
1792 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1793 $status->fatal( 'spamprotectionmatch', $match );
1794 $status->value
= self
::AS_SPAM_ERROR
;
1799 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1801 # Error messages etc. could be handled within the hook...
1802 $status->fatal( 'hookaborted' );
1803 $status->value
= self
::AS_HOOK_ERROR
;
1805 } elseif ( $this->hookError
!= '' ) {
1806 # ...or the hook could be expecting us to produce an error
1807 $status->fatal( 'hookaborted' );
1808 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1812 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1813 // Auto-block user's IP if the account was "hard" blocked
1814 if ( !wfReadOnly() ) {
1815 $wgUser->spreadAnyEditBlock();
1817 # Check block state against master, thus 'false'.
1818 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1822 $this->contentLength
= strlen( $this->textbox1
);
1823 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
1824 // Error will be displayed by showEditForm()
1825 $this->tooBig
= true;
1826 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1830 if ( !$wgUser->isAllowed( 'edit' ) ) {
1831 if ( $wgUser->isAnon() ) {
1832 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1835 $status->fatal( 'readonlytext' );
1836 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1841 $changingContentModel = false;
1842 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1843 if ( !$wgContentHandlerUseDB ) {
1844 $status->fatal( 'editpage-cannot-use-custom-model' );
1845 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1847 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1848 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1851 // Make sure the user can edit the page under the new content model too
1852 $titleWithNewContentModel = clone $this->mTitle
;
1853 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1854 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $wgUser )
1855 ||
!$titleWithNewContentModel->userCan( 'edit', $wgUser )
1857 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1861 $changingContentModel = true;
1862 $oldContentModel = $this->mTitle
->getContentModel();
1865 if ( $this->changeTags
) {
1866 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1867 $this->changeTags
, $wgUser );
1868 if ( !$changeTagsStatus->isOK() ) {
1869 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1870 return $changeTagsStatus;
1874 if ( wfReadOnly() ) {
1875 $status->fatal( 'readonlytext' );
1876 $status->value
= self
::AS_READ_ONLY_PAGE
;
1879 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 )
1880 ||
( $changingContentModel && $wgUser->pingLimiter( 'editcontentmodel' ) )
1882 $status->fatal( 'actionthrottledtext' );
1883 $status->value
= self
::AS_RATE_LIMITED
;
1887 # If the article has been deleted while editing, don't save it without
1889 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1890 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1894 # Load the page data from the master. If anything changes in the meantime,
1895 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1896 $this->page
->loadPageData( 'fromdbmaster' );
1897 $new = !$this->page
->exists();
1900 // Late check for create permission, just in case *PARANOIA*
1901 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1902 $status->fatal( 'nocreatetext' );
1903 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1904 wfDebug( __METHOD__
. ": no create permission\n" );
1908 // Don't save a new page if it's blank or if it's a MediaWiki:
1909 // message with content equivalent to default (allow empty pages
1910 // in this case to disable messages, see bug 50124)
1911 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1912 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1913 $defaultText = $defaultMessageText;
1918 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1919 $this->blankArticle
= true;
1920 $status->fatal( 'blankarticle' );
1921 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1925 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1929 $content = $textbox_content;
1931 $result['sectionanchor'] = '';
1932 if ( $this->section
== 'new' ) {
1933 if ( $this->sectiontitle
!== '' ) {
1934 // Insert the section title above the content.
1935 $content = $content->addSectionHeader( $this->sectiontitle
);
1936 } elseif ( $this->summary
!== '' ) {
1937 // Insert the section title above the content.
1938 $content = $content->addSectionHeader( $this->summary
);
1940 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1943 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1947 # Article exists. Check for edit conflict.
1949 $this->page
->clear(); # Force reload of dates, etc.
1950 $timestamp = $this->page
->getTimestamp();
1951 $latest = $this->page
->getLatest();
1953 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1955 // Check editRevId if set, which handles same-second timestamp collisions
1956 if ( $timestamp != $this->edittime
1957 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
1959 $this->isConflict
= true;
1960 if ( $this->section
== 'new' ) {
1961 if ( $this->page
->getUserText() == $wgUser->getName() &&
1962 $this->page
->getComment() == $this->newSectionSummary()
1964 // Probably a duplicate submission of a new comment.
1965 // This can happen when CDN resends a request after
1966 // a timeout but the first one actually went through.
1968 . ": duplicate new section submission; trigger edit conflict!\n" );
1970 // New comment; suppress conflict.
1971 $this->isConflict
= false;
1972 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1974 } elseif ( $this->section
== ''
1975 && Revision
::userWasLastToEdit(
1976 DB_MASTER
, $this->mTitle
->getArticleID(),
1977 $wgUser->getId(), $this->edittime
1980 # Suppress edit conflict with self, except for section edits where merging is required.
1981 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1982 $this->isConflict
= false;
1986 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1987 if ( $this->sectiontitle
!== '' ) {
1988 $sectionTitle = $this->sectiontitle
;
1990 $sectionTitle = $this->summary
;
1995 if ( $this->isConflict
) {
1997 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1998 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
1999 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2000 // ...or disable section editing for non-current revisions (not exposed anyway).
2001 if ( $this->editRevId
!== null ) {
2002 $content = $this->page
->replaceSectionAtRev(
2009 $content = $this->page
->replaceSectionContent(
2017 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2018 $content = $this->page
->replaceSectionContent(
2025 if ( is_null( $content ) ) {
2026 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2027 $this->isConflict
= true;
2028 $content = $textbox_content; // do not try to merge here!
2029 } elseif ( $this->isConflict
) {
2031 if ( $this->mergeChangesIntoContent( $content ) ) {
2032 // Successful merge! Maybe we should tell the user the good news?
2033 $this->isConflict
= false;
2034 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2036 $this->section
= '';
2037 $this->textbox1
= ContentHandler
::getContentText( $content );
2038 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2042 if ( $this->isConflict
) {
2043 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2047 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
2051 if ( $this->section
== 'new' ) {
2052 // Handle the user preference to force summaries here
2053 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2054 $this->missingSummary
= true;
2055 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2056 $status->value
= self
::AS_SUMMARY_NEEDED
;
2060 // Do not allow the user to post an empty comment
2061 if ( $this->textbox1
== '' ) {
2062 $this->missingComment
= true;
2063 $status->fatal( 'missingcommenttext' );
2064 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2067 } elseif ( !$this->allowBlankSummary
2068 && !$content->equals( $this->getOriginalContent( $wgUser ) )
2069 && !$content->isRedirect()
2070 && md5( $this->summary
) == $this->autoSumm
2072 $this->missingSummary
= true;
2073 $status->fatal( 'missingsummary' );
2074 $status->value
= self
::AS_SUMMARY_NEEDED
;
2079 $sectionanchor = '';
2080 if ( $this->section
== 'new' ) {
2081 $this->summary
= $this->newSectionSummary( $sectionanchor );
2082 } elseif ( $this->section
!= '' ) {
2083 # Try to get a section anchor from the section source, redirect
2084 # to edited section if header found.
2085 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2086 # for duplicate heading checking and maybe parsing.
2087 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2088 # We can't deal with anchors, includes, html etc in the header for now,
2089 # headline would need to be parsed to improve this.
2090 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2091 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
2094 $result['sectionanchor'] = $sectionanchor;
2096 // Save errors may fall down to the edit form, but we've now
2097 // merged the section into full text. Clear the section field
2098 // so that later submission of conflict forms won't try to
2099 // replace that into a duplicated mess.
2100 $this->textbox1
= $this->toEditText( $content );
2101 $this->section
= '';
2103 $status->value
= self
::AS_SUCCESS_UPDATE
;
2106 if ( !$this->allowSelfRedirect
2107 && $content->isRedirect()
2108 && $content->getRedirectTarget()->equals( $this->getTitle() )
2110 // If the page already redirects to itself, don't warn.
2111 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2112 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2113 $this->selfRedirect
= true;
2114 $status->fatal( 'selfredirect' );
2115 $status->value
= self
::AS_SELF_REDIRECT
;
2120 // Check for length errors again now that the section is merged in
2121 $this->contentLength
= strlen( $this->toEditText( $content ) );
2122 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
2123 $this->tooBig
= true;
2124 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2128 $flags = EDIT_AUTOSUMMARY |
2129 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2130 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2131 ( $bot ? EDIT_FORCE_BOT
: 0 );
2133 $doEditStatus = $this->page
->doEditContent(
2139 $content->getDefaultFormat(),
2143 if ( !$doEditStatus->isOK() ) {
2144 // Failure from doEdit()
2145 // Show the edit conflict page for certain recognized errors from doEdit(),
2146 // but don't show it for errors from extension hooks
2147 $errors = $doEditStatus->getErrorsArray();
2148 if ( in_array( $errors[0][0],
2149 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2151 $this->isConflict
= true;
2152 // Destroys data doEdit() put in $status->value but who cares
2153 $doEditStatus->value
= self
::AS_END
;
2155 return $doEditStatus;
2158 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2159 if ( $result['nullEdit'] ) {
2160 // We don't know if it was a null edit until now, so increment here
2161 $wgUser->pingLimiter( 'linkpurge' );
2163 $result['redirect'] = $content->isRedirect();
2165 $this->updateWatchlist();
2167 // If the content model changed, add a log entry
2168 if ( $changingContentModel ) {
2169 $this->addContentModelChangeLogEntry(
2171 $new ?
false : $oldContentModel,
2172 $this->contentModel
,
2182 * @param string|false $oldModel false if the page is being newly created
2183 * @param string $newModel
2184 * @param string $reason
2186 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2187 $new = $oldModel === false;
2188 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2189 $log->setPerformer( $user );
2190 $log->setTarget( $this->mTitle
);
2191 $log->setComment( $reason );
2192 $log->setParameters( [
2193 '4::oldmodel' => $oldModel,
2194 '5::newmodel' => $newModel
2196 $logid = $log->insert();
2197 $log->publish( $logid );
2201 * Register the change of watch status
2203 protected function updateWatchlist() {
2206 if ( !$wgUser->isLoggedIn() ) {
2211 $title = $this->mTitle
;
2212 $watch = $this->watchthis
;
2213 // Do this in its own transaction to reduce contention...
2214 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2215 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2216 return; // nothing to change
2218 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2223 * Attempts to do 3-way merge of edit content with a base revision
2224 * and current content, in case of edit conflict, in whichever way appropriate
2225 * for the content type.
2229 * @param Content $editContent
2233 private function mergeChangesIntoContent( &$editContent ) {
2235 $db = wfGetDB( DB_MASTER
);
2237 // This is the revision the editor started from
2238 $baseRevision = $this->getBaseRevision();
2239 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2241 if ( is_null( $baseContent ) ) {
2245 // The current state, we want to merge updates into it
2246 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2247 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2249 if ( is_null( $currentContent ) ) {
2253 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2255 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2258 $editContent = $result;
2259 // Update parentRevId to what we just merged.
2260 $this->parentRevId
= $currentRevision->getId();
2268 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2269 * one might think of X as the "base revision", which is NOT what this returns.
2270 * @return Revision Current version when the edit was started
2272 function getBaseRevision() {
2273 if ( !$this->mBaseRevision
) {
2274 $db = wfGetDB( DB_MASTER
);
2275 $this->mBaseRevision
= $this->editRevId
2276 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2277 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2279 return $this->mBaseRevision
;
2283 * Check given input text against $wgSpamRegex, and return the text of the first match.
2285 * @param string $text
2287 * @return string|bool Matching string or false
2289 public static function matchSpamRegex( $text ) {
2290 global $wgSpamRegex;
2291 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2292 $regexes = (array)$wgSpamRegex;
2293 return self
::matchSpamRegexInternal( $text, $regexes );
2297 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2299 * @param string $text
2301 * @return string|bool Matching string or false
2303 public static function matchSummarySpamRegex( $text ) {
2304 global $wgSummarySpamRegex;
2305 $regexes = (array)$wgSummarySpamRegex;
2306 return self
::matchSpamRegexInternal( $text, $regexes );
2310 * @param string $text
2311 * @param array $regexes
2312 * @return bool|string
2314 protected static function matchSpamRegexInternal( $text, $regexes ) {
2315 foreach ( $regexes as $regex ) {
2317 if ( preg_match( $regex, $text, $matches ) ) {
2324 function setHeaders() {
2325 global $wgOut, $wgUser, $wgAjaxEditStash;
2327 $wgOut->addModules( 'mediawiki.action.edit' );
2328 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2330 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2331 // The addition of default buttons is handled by getEditToolbar() which
2332 // has its own dependency on this module. The call here ensures the module
2333 // is loaded in time (it has position "top") for other modules to register
2334 // buttons (e.g. extensions, gadgets, user scripts).
2335 $wgOut->addModules( 'mediawiki.toolbar' );
2338 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2339 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2342 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2343 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2346 # Enabled article-related sidebar, toplinks, etc.
2347 $wgOut->setArticleRelated( true );
2349 $contextTitle = $this->getContextTitle();
2350 if ( $this->isConflict
) {
2351 $msg = 'editconflict';
2352 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2353 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2355 $msg = $contextTitle->exists()
2356 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2357 && $contextTitle->getDefaultMessageText() !== false
2363 # Use the title defined by DISPLAYTITLE magic word when present
2364 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2365 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2366 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2367 if ( $displayTitle === false ) {
2368 $displayTitle = $contextTitle->getPrefixedText();
2370 $wgOut->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2371 # Transmit the name of the message to JavaScript for live preview
2372 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2373 $wgOut->addJsConfigVars( [
2374 'wgEditMessage' => $msg,
2375 'wgAjaxEditStash' => $wgAjaxEditStash,
2380 * Show all applicable editing introductions
2382 protected function showIntro() {
2383 global $wgOut, $wgUser;
2384 if ( $this->suppressIntro
) {
2388 $namespace = $this->mTitle
->getNamespace();
2390 if ( $namespace == NS_MEDIAWIKI
) {
2391 # Show a warning if editing an interface message
2392 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2393 # If this is a default message (but not css or js),
2394 # show a hint that it is translatable on translatewiki.net
2395 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2396 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2398 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2399 if ( $defaultMessageText !== false ) {
2400 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2401 'translateinterface' );
2404 } elseif ( $namespace == NS_FILE
) {
2405 # Show a hint to shared repo
2406 $file = wfFindFile( $this->mTitle
);
2407 if ( $file && !$file->isLocal() ) {
2408 $descUrl = $file->getDescriptionUrl();
2409 # there must be a description url to show a hint to shared repo
2411 if ( !$this->mTitle
->exists() ) {
2412 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2413 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2416 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2417 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2424 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2425 # Show log extract when the user is currently blocked
2426 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2427 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2428 $user = User
::newFromName( $username, false /* allow IP users*/ );
2429 $ip = User
::isIP( $username );
2430 $block = Block
::newFromTarget( $user, $user );
2431 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2432 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2433 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2434 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2435 # Show log extract if the user is currently blocked
2436 LogEventsList
::showLogExtract(
2439 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2443 'showIfEmpty' => false,
2445 'blocked-notice-logextract',
2446 $user->getName() # Support GENDER in notice
2452 # Try to add a custom edit intro, or use the standard one if this is not possible.
2453 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2454 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2455 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2457 if ( $wgUser->isLoggedIn() ) {
2458 $wgOut->wrapWikiMsg(
2459 // Suppress the external link icon, consider the help url an internal one
2460 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2467 $wgOut->wrapWikiMsg(
2468 // Suppress the external link icon, consider the help url an internal one
2469 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2471 'newarticletextanon',
2477 # Give a notice if the user is editing a deleted/moved page...
2478 if ( !$this->mTitle
->exists() ) {
2479 LogEventsList
::showLogExtract( $wgOut, [ 'delete', 'move' ], $this->mTitle
,
2483 'conds' => [ "log_action != 'revision'" ],
2484 'showIfEmpty' => false,
2485 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2492 * Attempt to show a custom editing introduction, if supplied
2496 protected function showCustomIntro() {
2497 if ( $this->editintro
) {
2498 $title = Title
::newFromText( $this->editintro
);
2499 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2501 // Added using template syntax, to take <noinclude>'s into account.
2502 $wgOut->addWikiTextTitleTidy(
2503 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2513 * Gets an editable textual representation of $content.
2514 * The textual representation can be turned by into a Content object by the
2515 * toEditContent() method.
2517 * If $content is null or false or a string, $content is returned unchanged.
2519 * If the given Content object is not of a type that can be edited using
2520 * the text base EditPage, an exception will be raised. Set
2521 * $this->allowNonTextContent to true to allow editing of non-textual
2524 * @param Content|null|bool|string $content
2525 * @return string The editable text form of the content.
2527 * @throws MWException If $content is not an instance of TextContent and
2528 * $this->allowNonTextContent is not true.
2530 protected function toEditText( $content ) {
2531 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2535 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2536 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2539 return $content->serialize( $this->contentFormat
);
2543 * Turns the given text into a Content object by unserializing it.
2545 * If the resulting Content object is not of a type that can be edited using
2546 * the text base EditPage, an exception will be raised. Set
2547 * $this->allowNonTextContent to true to allow editing of non-textual
2550 * @param string|null|bool $text Text to unserialize
2551 * @return Content|bool|null The content object created from $text. If $text was false
2552 * or null, false resp. null will be returned instead.
2554 * @throws MWException If unserializing the text results in a Content
2555 * object that is not an instance of TextContent and
2556 * $this->allowNonTextContent is not true.
2558 protected function toEditContent( $text ) {
2559 if ( $text === false ||
$text === null ) {
2563 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2564 $this->contentModel
, $this->contentFormat
);
2566 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2567 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2574 * Send the edit form and related headers to $wgOut
2575 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2576 * during form output near the top, for captchas and the like.
2578 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2579 * use the EditPage::showEditForm:fields hook instead.
2581 function showEditForm( $formCallback = null ) {
2582 global $wgOut, $wgUser;
2584 # need to parse the preview early so that we know which templates are used,
2585 # otherwise users with "show preview after edit box" will get a blank list
2586 # we parse this near the beginning so that setHeaders can do the title
2587 # setting work instead of leaving it in getPreviewText
2588 $previewOutput = '';
2589 if ( $this->formtype
== 'preview' ) {
2590 $previewOutput = $this->getPreviewText();
2593 Hooks
::run( 'EditPage::showEditForm:initial', [ &$this, &$wgOut ] );
2595 $this->setHeaders();
2597 if ( $this->showHeader() === false ) {
2601 $wgOut->addHTML( $this->editFormPageTop
);
2603 if ( $wgUser->getOption( 'previewontop' ) ) {
2604 $this->displayPreviewArea( $previewOutput, true );
2607 $wgOut->addHTML( $this->editFormTextTop
);
2609 $showToolbar = true;
2610 if ( $this->wasDeletedSinceLastEdit() ) {
2611 if ( $this->formtype
== 'save' ) {
2612 // Hide the toolbar and edit area, user can click preview to get it back
2613 // Add an confirmation checkbox and explanation.
2614 $showToolbar = false;
2616 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2617 'deletedwhileediting' );
2621 // @todo add EditForm plugin interface and use it here!
2622 // search for textarea1 and textares2, and allow EditForm to override all uses.
2623 $wgOut->addHTML( Html
::openElement(
2626 'id' => self
::EDITFORM_ID
,
2627 'name' => self
::EDITFORM_ID
,
2629 'action' => $this->getActionURL( $this->getContextTitle() ),
2630 'enctype' => 'multipart/form-data'
2634 if ( is_callable( $formCallback ) ) {
2635 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2636 call_user_func_array( $formCallback, [ &$wgOut ] );
2639 // Add an empty field to trip up spambots
2641 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2644 [ 'for' => 'wpAntispam' ],
2645 $this->context
->msg( 'simpleantispam-label' )->parse()
2651 'name' => 'wpAntispam',
2652 'id' => 'wpAntispam',
2656 . Xml
::closeElement( 'div' )
2659 Hooks
::run( 'EditPage::showEditForm:fields', [ &$this, &$wgOut ] );
2661 // Put these up at the top to ensure they aren't lost on early form submission
2662 $this->showFormBeforeText();
2664 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2665 $username = $this->lastDelete
->user_name
;
2666 $comment = $this->lastDelete
->log_comment
;
2668 // It is better to not parse the comment at all than to have templates expanded in the middle
2669 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2670 $key = $comment === ''
2671 ?
'confirmrecreate-noreason'
2672 : 'confirmrecreate';
2674 '<div class="mw-confirm-recreate">' .
2675 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2676 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2677 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2683 # When the summary is hidden, also hide them on preview/show changes
2684 if ( $this->nosummary
) {
2685 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2688 # If a blank edit summary was previously provided, and the appropriate
2689 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2690 # user being bounced back more than once in the event that a summary
2693 # For a bit more sophisticated detection of blank summaries, hash the
2694 # automatic one and pass that in the hidden field wpAutoSummary.
2695 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2696 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2699 if ( $this->undidRev
) {
2700 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2703 if ( $this->selfRedirect
) {
2704 $wgOut->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2707 if ( $this->hasPresetSummary
) {
2708 // If a summary has been preset using &summary= we don't want to prompt for
2709 // a different summary. Only prompt for a summary if the summary is blanked.
2711 $this->autoSumm
= md5( '' );
2714 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2715 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2717 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2718 $wgOut->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2720 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2721 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2723 if ( $this->section
== 'new' ) {
2724 $this->showSummaryInput( true, $this->summary
);
2725 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2728 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2730 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2731 $wgOut->addHTML( EditPage
::getEditToolbar( $this->mTitle
) );
2734 if ( $this->blankArticle
) {
2735 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2738 if ( $this->isConflict
) {
2739 // In an edit conflict bypass the overridable content form method
2740 // and fallback to the raw wpTextbox1 since editconflicts can't be
2741 // resolved between page source edits and custom ui edits using the
2743 $this->textbox2
= $this->textbox1
;
2745 $content = $this->getCurrentContent();
2746 $this->textbox1
= $this->toEditText( $content );
2748 $this->showTextbox1();
2750 $this->showContentForm();
2753 $wgOut->addHTML( $this->editFormTextAfterContent
);
2755 $this->showStandardInputs();
2757 $this->showFormAfterText();
2759 $this->showTosSummary();
2761 $this->showEditTools();
2763 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2765 $wgOut->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2767 $wgOut->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2768 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2770 if ( $this->mParserOutput
) {
2771 $wgOut->setLimitReportData( $this->mParserOutput
->getLimitReportData() );
2774 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2776 if ( $this->isConflict
) {
2778 $this->showConflict();
2779 } catch ( MWContentSerializationException
$ex ) {
2780 // this can't really happen, but be nice if it does.
2781 $msg = $this->context
->msg(
2782 'content-failed-to-parse',
2783 $this->contentModel
,
2784 $this->contentFormat
,
2787 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2791 // Set a hidden field so JS knows what edit form mode we are in
2792 if ( $this->isConflict
) {
2794 } elseif ( $this->preview
) {
2796 } elseif ( $this->diff
) {
2801 $wgOut->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2803 // Marker for detecting truncated form data. This must be the last
2804 // parameter sent in order to be of use, so do not move me.
2805 $wgOut->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2806 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2808 if ( !$wgUser->getOption( 'previewontop' ) ) {
2809 $this->displayPreviewArea( $previewOutput, false );
2815 * Wrapper around TemplatesOnThisPageFormatter to make
2816 * a "templates on this page" list.
2818 * @param Title[] $templates
2819 * @return string HTML
2821 protected function makeTemplatesOnThisPageList( array $templates ) {
2822 $templateListFormatter = new TemplatesOnThisPageFormatter(
2823 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2826 // preview if preview, else section if section, else false
2828 if ( $this->preview
) {
2830 } elseif ( $this->section
!= '' ) {
2834 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2835 $templateListFormatter->format( $templates, $type )
2841 * Extract the section title from current section text, if any.
2843 * @param string $text
2844 * @return string|bool String or false
2846 public static function extractSectionTitle( $text ) {
2847 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2848 if ( !empty( $matches[2] ) ) {
2850 return $wgParser->stripSectionName( trim( $matches[2] ) );
2859 protected function showHeader() {
2860 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2861 global $wgAllowUserCss, $wgAllowUserJs;
2863 if ( $this->mTitle
->isTalkPage() ) {
2864 $wgOut->addWikiMsg( 'talkpagetext' );
2868 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
2869 if ( count( $editNotices ) ) {
2870 $wgOut->addHTML( implode( "\n", $editNotices ) );
2872 $msg = $this->context
->msg( 'editnotice-notext' );
2873 if ( !$msg->isDisabled() ) {
2875 '<div class="mw-editnotice-notext">'
2876 . $msg->parseAsBlock()
2882 if ( $this->isConflict
) {
2883 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2884 $this->editRevId
= $this->page
->getLatest();
2886 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2887 // We use $this->section to much before this and getVal('wgSection') directly in other places
2888 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2889 // Someone is welcome to try refactoring though
2890 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2894 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2895 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2896 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2897 if ( $sectionTitle !== false ) {
2898 $this->summary
= "/* $sectionTitle */ ";
2903 if ( $this->missingComment
) {
2904 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2907 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2908 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2911 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2912 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2915 if ( $this->blankArticle
) {
2916 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2919 if ( $this->selfRedirect
) {
2920 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2923 if ( $this->hookError
!== '' ) {
2924 $wgOut->addWikiText( $this->hookError
);
2927 if ( !$this->checkUnicodeCompliantBrowser() ) {
2928 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2931 if ( $this->section
!= 'new' ) {
2932 $revision = $this->mArticle
->getRevisionFetched();
2934 // Let sysop know that this will make private content public if saved
2936 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2937 $wgOut->wrapWikiMsg(
2938 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2939 'rev-deleted-text-permission'
2941 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2942 $wgOut->wrapWikiMsg(
2943 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2944 'rev-deleted-text-view'
2948 if ( !$revision->isCurrent() ) {
2949 $this->mArticle
->setOldSubtitle( $revision->getId() );
2950 $wgOut->addWikiMsg( 'editingold' );
2952 } elseif ( $this->mTitle
->exists() ) {
2953 // Something went wrong
2955 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2956 [ 'missing-revision', $this->oldid
] );
2961 if ( wfReadOnly() ) {
2962 $wgOut->wrapWikiMsg(
2963 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2964 [ 'readonlywarning', wfReadOnlyReason() ]
2966 } elseif ( $wgUser->isAnon() ) {
2967 if ( $this->formtype
!= 'preview' ) {
2968 $wgOut->wrapWikiMsg(
2969 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
2970 [ 'anoneditwarning',
2972 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
2973 'returnto' => $this->getTitle()->getPrefixedDBkey()
2976 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
2977 'returnto' => $this->getTitle()->getPrefixedDBkey()
2982 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
2983 'anonpreviewwarning'
2987 if ( $this->isCssJsSubpage
) {
2988 # Check the skin exists
2989 if ( $this->isWrongCaseCssJsPage
) {
2990 $wgOut->wrapWikiMsg(
2991 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2992 [ 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ]
2995 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
2996 $wgOut->wrapWikiMsg( '<div class="mw-usercssjspublic">$1</div>',
2997 $this->isCssSubpage ?
'usercssispublic' : 'userjsispublic'
2999 if ( $this->formtype
!== 'preview' ) {
3000 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
3001 $wgOut->wrapWikiMsg(
3002 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3003 [ 'usercssyoucanpreview' ]
3007 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
3008 $wgOut->wrapWikiMsg(
3009 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3010 [ 'userjsyoucanpreview' ]
3018 if ( $this->mTitle
->isProtected( 'edit' ) &&
3019 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
3021 # Is the title semi-protected?
3022 if ( $this->mTitle
->isSemiProtected() ) {
3023 $noticeMsg = 'semiprotectedpagewarning';
3025 # Then it must be protected based on static groups (regular)
3026 $noticeMsg = 'protectedpagewarning';
3028 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
3029 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
3031 if ( $this->mTitle
->isCascadeProtected() ) {
3032 # Is this page under cascading protection from some source pages?
3033 /** @var Title[] $cascadeSources */
3034 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
3035 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
3036 $cascadeSourcesCount = count( $cascadeSources );
3037 if ( $cascadeSourcesCount > 0 ) {
3038 # Explain, and list the titles responsible
3039 foreach ( $cascadeSources as $page ) {
3040 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
3043 $notice .= '</div>';
3044 $wgOut->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
3046 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
3047 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
3049 'showIfEmpty' => false,
3050 'msgKey' => [ 'titleprotectedwarning' ],
3051 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
3054 if ( $this->contentLength
=== false ) {
3055 $this->contentLength
= strlen( $this->textbox1
);
3058 if ( $this->tooBig ||
$this->contentLength
> $wgMaxArticleSize * 1024 ) {
3059 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
3062 $wgLang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
3063 $wgLang->formatNum( $wgMaxArticleSize )
3067 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
3068 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
3071 $wgLang->formatSize( strlen( $this->textbox1
) ),
3072 strlen( $this->textbox1
)
3077 # Add header copyright warning
3078 $this->showHeaderCopyrightWarning();
3084 * Standard summary input and label (wgSummary), abstracted so EditPage
3085 * subclasses may reorganize the form.
3086 * Note that you do not need to worry about the label's for=, it will be
3087 * inferred by the id given to the input. You can remove them both by
3088 * passing [ 'id' => false ] to $userInputAttrs.
3090 * @param string $summary The value of the summary input
3091 * @param string $labelText The html to place inside the label
3092 * @param array $inputAttrs Array of attrs to use on the input
3093 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
3095 * @return array An array in the format [ $label, $input ]
3097 function getSummaryInput( $summary = "", $labelText = null,
3098 $inputAttrs = null, $spanLabelAttrs = null
3100 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
3101 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3102 'id' => 'wpSummary',
3103 'maxlength' => '200',
3106 'spellcheck' => 'true',
3107 ] + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
3109 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : [] ) +
[
3110 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
3111 'id' => "wpSummaryLabel"
3118 $inputAttrs['id'] ?
[ 'for' => $inputAttrs['id'] ] : null,
3121 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
3124 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
3126 return [ $label, $input ];
3130 * @param bool $isSubjectPreview True if this is the section subject/title
3131 * up top, or false if this is the comment summary
3132 * down below the textarea
3133 * @param string $summary The text of the summary to display
3135 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3137 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3138 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3139 if ( $isSubjectPreview ) {
3140 if ( $this->nosummary
) {
3144 if ( !$this->mShowSummaryField
) {
3148 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3149 list( $label, $input ) = $this->getSummaryInput(
3152 [ 'class' => $summaryClass ],
3155 $wgOut->addHTML( "{$label} {$input}" );
3159 * @param bool $isSubjectPreview True if this is the section subject/title
3160 * up top, or false if this is the comment summary
3161 * down below the textarea
3162 * @param string $summary The text of the summary to display
3165 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3166 // avoid spaces in preview, gets always trimmed on save
3167 $summary = trim( $summary );
3168 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3174 if ( $isSubjectPreview ) {
3175 $summary = $this->context
->msg( 'newsectionsummary' )
3176 ->rawParams( $wgParser->stripSectionName( $summary ) )
3177 ->inContentLanguage()->text();
3180 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3182 $summary = $this->context
->msg( $message )->parse()
3183 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3184 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3187 protected function showFormBeforeText() {
3189 $section = htmlspecialchars( $this->section
);
3190 $wgOut->addHTML( <<<HTML
3191 <input type='hidden' value="{$section}" name="wpSection"/>
3192 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
3193 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
3194 <input type='hidden' value="{$this->editRevId}" name="editRevId" />
3195 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
3199 if ( !$this->checkUnicodeCompliantBrowser() ) {
3200 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
3204 protected function showFormAfterText() {
3205 global $wgOut, $wgUser;
3207 * To make it harder for someone to slip a user a page
3208 * which submits an edit form to the wiki without their
3209 * knowledge, a random token is associated with the login
3210 * session. If it's not passed back with the submission,
3211 * we won't save the page, or render user JavaScript and
3214 * For anon editors, who may not have a session, we just
3215 * include the constant suffix to prevent editing from
3216 * broken text-mangling proxies.
3218 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
3222 * Subpage overridable method for printing the form for page content editing
3223 * By default this simply outputs wpTextbox1
3224 * Subclasses can override this to provide a custom UI for editing;
3225 * be it a form, or simply wpTextbox1 with a modified content that will be
3226 * reverse modified when extracted from the post data.
3227 * Note that this is basically the inverse for importContentFormData
3229 protected function showContentForm() {
3230 $this->showTextbox1();
3234 * Method to output wpTextbox1
3235 * The $textoverride method can be used by subclasses overriding showContentForm
3236 * to pass back to this method.
3238 * @param array $customAttribs Array of html attributes to use in the textarea
3239 * @param string $textoverride Optional text to override $this->textarea1 with
3241 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3242 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3243 $attribs = [ 'style' => 'display:none;' ];
3245 $classes = []; // Textarea CSS
3246 if ( $this->mTitle
->isProtected( 'edit' ) &&
3247 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
3249 # Is the title semi-protected?
3250 if ( $this->mTitle
->isSemiProtected() ) {
3251 $classes[] = 'mw-textarea-sprotected';
3253 # Then it must be protected based on static groups (regular)
3254 $classes[] = 'mw-textarea-protected';
3256 # Is the title cascade-protected?
3257 if ( $this->mTitle
->isCascadeProtected() ) {
3258 $classes[] = 'mw-textarea-cprotected';
3262 $attribs = [ 'tabindex' => 1 ];
3264 if ( is_array( $customAttribs ) ) {
3265 $attribs +
= $customAttribs;
3268 if ( count( $classes ) ) {
3269 if ( isset( $attribs['class'] ) ) {
3270 $classes[] = $attribs['class'];
3272 $attribs['class'] = implode( ' ', $classes );
3277 $textoverride !== null ?
$textoverride : $this->textbox1
,
3283 protected function showTextbox2() {
3284 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3287 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3288 global $wgOut, $wgUser;
3290 $wikitext = $this->safeUnicodeOutput( $text );
3291 if ( strval( $wikitext ) !== '' ) {
3292 // Ensure there's a newline at the end, otherwise adding lines
3294 // But don't add a newline if the ext is empty, or Firefox in XHTML
3295 // mode will show an extra newline. A bit annoying.
3299 $attribs = $customAttribs +
[
3302 'cols' => $wgUser->getIntOption( 'cols' ),
3303 'rows' => $wgUser->getIntOption( 'rows' ),
3304 // The following classes can be used here:
3305 // * mw-editfont-default
3306 // * mw-editfont-monospace
3307 // * mw-editfont-sans-serif
3308 // * mw-editfont-serif
3309 'class' => 'mw-editfont-' . $wgUser->getOption( 'editfont' ),
3310 // Avoid PHP notices when appending preferences
3311 // (appending allows customAttribs['style'] to still work).
3315 $pageLang = $this->mTitle
->getPageLanguage();
3316 $attribs['lang'] = $pageLang->getHtmlCode();
3317 $attribs['dir'] = $pageLang->getDir();
3319 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3322 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3326 $classes[] = 'ontop';
3329 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3331 if ( $this->formtype
!= 'preview' ) {
3332 $attribs['style'] = 'display: none;';
3335 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
3337 if ( $this->formtype
== 'preview' ) {
3338 $this->showPreview( $previewOutput );
3340 // Empty content container for LivePreview
3341 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3342 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3343 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3344 $wgOut->addHTML( Html
::rawElement( 'div', $attribs ) );
3347 $wgOut->addHTML( '</div>' );
3349 if ( $this->formtype
== 'diff' ) {
3352 } catch ( MWContentSerializationException
$ex ) {
3353 $msg = $this->context
->msg(
3354 'content-failed-to-parse',
3355 $this->contentModel
,
3356 $this->contentFormat
,
3359 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3365 * Append preview output to $wgOut.
3366 * Includes category rendering if this is a category page.
3368 * @param string $text The HTML to be output for the preview.
3370 protected function showPreview( $text ) {
3372 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3373 $this->mArticle
->openShowCategory();
3375 # This hook seems slightly odd here, but makes things more
3376 # consistent for extensions.
3377 Hooks
::run( 'OutputPageBeforeHTML', [ &$wgOut, &$text ] );
3378 $wgOut->addHTML( $text );
3379 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3380 $this->mArticle
->closeShowCategory();
3385 * Get a diff between the current contents of the edit box and the
3386 * version of the page we're editing from.
3388 * If this is a section edit, we'll replace the section as for final
3389 * save and then make a comparison.
3391 function showDiff() {
3392 global $wgUser, $wgContLang, $wgOut;
3394 $oldtitlemsg = 'currentrev';
3395 # if message does not exist, show diff against the preloaded default
3396 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3397 $oldtext = $this->mTitle
->getDefaultMessageText();
3398 if ( $oldtext !== false ) {
3399 $oldtitlemsg = 'defaultmessagetext';
3400 $oldContent = $this->toEditContent( $oldtext );
3405 $oldContent = $this->getCurrentContent();
3408 $textboxContent = $this->toEditContent( $this->textbox1
);
3409 if ( $this->editRevId
!== null ) {
3410 $newContent = $this->page
->replaceSectionAtRev(
3411 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3414 $newContent = $this->page
->replaceSectionContent(
3415 $this->section
, $textboxContent, $this->summary
, $this->edittime
3419 if ( $newContent ) {
3420 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', [ $this, &$newContent ], '1.21' );
3421 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3423 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
3424 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
3427 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3428 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3429 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3431 if ( !$oldContent ) {
3432 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3435 if ( !$newContent ) {
3436 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3439 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3440 $de->setContent( $oldContent, $newContent );
3442 $difftext = $de->getDiff( $oldtitle, $newtitle );
3443 $de->showDiffStyle();
3448 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3452 * Show the header copyright warning.
3454 protected function showHeaderCopyrightWarning() {
3455 $msg = 'editpage-head-copy-warn';
3456 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3458 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3459 'editpage-head-copy-warn' );
3464 * Give a chance for site and per-namespace customizations of
3465 * terms of service summary link that might exist separately
3466 * from the copyright notice.
3468 * This will display between the save button and the edit tools,
3469 * so should remain short!
3471 protected function showTosSummary() {
3472 $msg = 'editpage-tos-summary';
3473 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3474 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3476 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3477 $wgOut->addWikiMsg( $msg );
3478 $wgOut->addHTML( '</div>' );
3482 protected function showEditTools() {
3484 $wgOut->addHTML( '<div class="mw-editTools">' .
3485 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3490 * Get the copyright warning
3492 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3495 protected function getCopywarn() {
3496 return self
::getCopyrightWarning( $this->mTitle
);
3500 * Get the copyright warning, by default returns wikitext
3502 * @param Title $title
3503 * @param string $format Output format, valid values are any function of a Message object
3506 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3507 global $wgRightsText;
3508 if ( $wgRightsText ) {
3509 $copywarnMsg = [ 'copyrightwarning',
3510 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3513 $copywarnMsg = [ 'copyrightwarning2',
3514 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3516 // Allow for site and per-namespace customization of contribution/copyright notice.
3517 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3519 $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
3521 $msg->inLanguage( $langcode );
3523 return "<div id=\"editpage-copywarn\">\n" .
3524 $msg->$format() . "\n</div>";
3528 * Get the Limit report for page previews
3531 * @param ParserOutput $output ParserOutput object from the parse
3532 * @return string HTML
3534 public static function getPreviewLimitReport( $output ) {
3535 if ( !$output ||
!$output->getLimitReportData() ) {
3539 return ResourceLoader
::makeInlineScript(
3540 ResourceLoader
::makeConfigSetScript(
3541 [ 'wgPageParseReport' => $output->getLimitReportData() ],
3547 protected function showStandardInputs( &$tabindex = 2 ) {
3549 $wgOut->addHTML( "<div class='editOptions'>\n" );
3551 if ( $this->section
!= 'new' ) {
3552 $this->showSummaryInput( false, $this->summary
);
3553 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3556 $checkboxes = $this->getCheckboxes( $tabindex,
3557 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
] );
3558 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3560 // Show copyright warning.
3561 $wgOut->addWikiText( $this->getCopywarn() );
3562 $wgOut->addHTML( $this->editFormTextAfterWarn
);
3564 $wgOut->addHTML( "<div class='editButtons'>\n" );
3565 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3567 $cancel = $this->getCancelLink();
3568 if ( $cancel !== '' ) {
3569 $cancel .= Html
::element( 'span',
3570 [ 'class' => 'mw-editButtons-pipe-separator' ],
3571 $this->context
->msg( 'pipe-separator' )->text() );
3574 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3575 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3577 'target' => 'helpwindow',
3578 'href' => $edithelpurl,
3580 $edithelp = Html
::linkButton( $this->context
->msg( 'edithelp' )->text(),
3581 $attrs, [ 'mw-ui-quiet' ] ) .
3582 $this->context
->msg( 'word-separator' )->escaped() .
3583 $this->context
->msg( 'newwindow' )->parse();
3585 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3586 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3587 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3589 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $wgOut, &$tabindex ] );
3591 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3595 * Show an edit conflict. textbox1 is already shown in showEditForm().
3596 * If you want to use another entry point to this function, be careful.
3598 protected function showConflict() {
3601 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$this, &$wgOut ] ) ) {
3602 $stats = $wgOut->getContext()->getStats();
3603 $stats->increment( 'edit.failures.conflict' );
3604 // Only include 'standard' namespaces to avoid creating unknown numbers of statsd metrics
3606 $this->mTitle
->getNamespace() >= NS_MAIN
&&
3607 $this->mTitle
->getNamespace() <= NS_CATEGORY_TALK
3609 $stats->increment( 'edit.failures.conflict.byNamespaceId.' . $this->mTitle
->getNamespace() );
3612 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3614 $content1 = $this->toEditContent( $this->textbox1
);
3615 $content2 = $this->toEditContent( $this->textbox2
);
3617 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3618 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3619 $de->setContent( $content2, $content1 );
3621 $this->context
->msg( 'yourtext' )->parse(),
3622 $this->context
->msg( 'storedversion' )->text()
3625 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3626 $this->showTextbox2();
3633 public function getCancelLink() {
3635 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3636 $cancelParams['oldid'] = $this->oldid
;
3637 } elseif ( $this->getContextTitle()->isRedirect() ) {
3638 $cancelParams['redirect'] = 'no';
3640 $attrs = [ 'id' => 'mw-editform-cancel' ];
3642 return Linker
::linkKnown(
3643 $this->getContextTitle(),
3644 $this->context
->msg( 'cancel' )->parse(),
3645 Html
::buttonAttributes( $attrs, [ 'mw-ui-quiet' ] ),
3651 * Returns the URL to use in the form's action attribute.
3652 * This is used by EditPage subclasses when simply customizing the action
3653 * variable in the constructor is not enough. This can be used when the
3654 * EditPage lives inside of a Special page rather than a custom page action.
3656 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3659 protected function getActionURL( Title
$title ) {
3660 return $title->getLocalURL( [ 'action' => $this->action
] );
3664 * Check if a page was deleted while the user was editing it, before submit.
3665 * Note that we rely on the logging table, which hasn't been always there,
3666 * but that doesn't matter, because this only applies to brand new
3670 protected function wasDeletedSinceLastEdit() {
3671 if ( $this->deletedSinceEdit
!== null ) {
3672 return $this->deletedSinceEdit
;
3675 $this->deletedSinceEdit
= false;
3677 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3678 $this->lastDelete
= $this->getLastDelete();
3679 if ( $this->lastDelete
) {
3680 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3681 if ( $deleteTime > $this->starttime
) {
3682 $this->deletedSinceEdit
= true;
3687 return $this->deletedSinceEdit
;
3691 * @return bool|stdClass
3693 protected function getLastDelete() {
3694 $dbr = wfGetDB( DB_REPLICA
);
3695 $data = $dbr->selectRow(
3696 [ 'logging', 'user' ],
3709 'log_namespace' => $this->mTitle
->getNamespace(),
3710 'log_title' => $this->mTitle
->getDBkey(),
3711 'log_type' => 'delete',
3712 'log_action' => 'delete',
3716 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ]
3718 // Quick paranoid permission checks...
3719 if ( is_object( $data ) ) {
3720 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3721 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3724 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3725 $data->log_comment
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3733 * Get the rendered text for previewing.
3734 * @throws MWException
3737 function getPreviewText() {
3738 global $wgOut, $wgRawHtml, $wgLang;
3739 global $wgAllowUserCss, $wgAllowUserJs;
3741 $stats = $wgOut->getContext()->getStats();
3743 if ( $wgRawHtml && !$this->mTokenOk
) {
3744 // Could be an offsite preview attempt. This is very unsafe if
3745 // HTML is enabled, as it could be an attack.
3747 if ( $this->textbox1
!== '' ) {
3748 // Do not put big scary notice, if previewing the empty
3749 // string, which happens when you initially edit
3750 // a category page, due to automatic preview-on-open.
3751 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3752 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3753 true, /* interface */true );
3755 $stats->increment( 'edit.failures.session_loss' );
3762 $content = $this->toEditContent( $this->textbox1
);
3766 'AlternateEditPreview',
3767 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3769 return $previewHTML;
3772 # provide a anchor link to the editform
3773 $continueEditing = '<span class="mw-continue-editing">' .
3774 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3775 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3776 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3777 if ( $this->mTokenOkExceptSuffix
) {
3778 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3779 $stats->increment( 'edit.failures.bad_token' );
3781 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3782 $stats->increment( 'edit.failures.session_loss' );
3784 } elseif ( $this->incompleteForm
) {
3785 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3786 if ( $this->mTriedSave
) {
3787 $stats->increment( 'edit.failures.incomplete_form' );
3790 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3793 # don't parse non-wikitext pages, show message about preview
3794 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3795 if ( $this->mTitle
->isCssJsSubpage() ) {
3797 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3803 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3805 if ( $level === 'user' && !$wgAllowUserCss ) {
3808 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3810 if ( $level === 'user' && !$wgAllowUserJs ) {
3817 # Used messages to make sure grep find them:
3818 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3819 if ( $level && $format ) {
3820 $note = "<div id='mw-{$level}{$format}preview'>" .
3821 $this->context
->msg( "{$level}{$format}preview" )->text() .
3822 ' ' . $continueEditing . "</div>";
3826 # If we're adding a comment, we need to show the
3827 # summary as the headline
3828 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3829 $content = $content->addSectionHeader( $this->summary
);
3832 $hook_args = [ $this, &$content ];
3833 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args, '1.25' );
3834 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3836 $parserResult = $this->doPreviewParse( $content );
3837 $parserOutput = $parserResult['parserOutput'];
3838 $previewHTML = $parserResult['html'];
3839 $this->mParserOutput
= $parserOutput;
3840 $wgOut->addParserOutputMetadata( $parserOutput );
3842 if ( count( $parserOutput->getWarnings() ) ) {
3843 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3846 } catch ( MWContentSerializationException
$ex ) {
3847 $m = $this->context
->msg(
3848 'content-failed-to-parse',
3849 $this->contentModel
,
3850 $this->contentFormat
,
3853 $note .= "\n\n" . $m->parse();
3857 if ( $this->isConflict
) {
3858 $conflict = '<h2 id="mw-previewconflict">'
3859 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3861 $conflict = '<hr />';
3864 $previewhead = "<div class='previewnote'>\n" .
3865 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3866 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3868 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3869 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3870 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3871 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3873 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3877 * Get parser options for a preview
3878 * @return ParserOptions
3880 protected function getPreviewParserOptions() {
3881 $parserOptions = $this->page
->makeParserOptions( $this->mArticle
->getContext() );
3882 $parserOptions->setIsPreview( true );
3883 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3884 $parserOptions->enableLimitReport();
3885 return $parserOptions;
3889 * Parse the page for a preview. Subclasses may override this class, in order
3890 * to parse with different options, or to otherwise modify the preview HTML.
3892 * @param Content $content The page content
3893 * @return array with keys:
3894 * - parserOutput: The ParserOutput object
3895 * - html: The HTML to be displayed
3897 protected function doPreviewParse( Content
$content ) {
3899 $parserOptions = $this->getPreviewParserOptions();
3900 $pstContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3901 $scopedCallback = $parserOptions->setupFakeRevision(
3902 $this->mTitle
, $pstContent, $wgUser );
3903 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3904 ScopedCallback
::consume( $scopedCallback );
3905 $parserOutput->setEditSectionTokens( false ); // no section edit links
3907 'parserOutput' => $parserOutput,
3908 'html' => $parserOutput->getText() ];
3914 function getTemplates() {
3915 if ( $this->preview ||
$this->section
!= '' ) {
3917 if ( !isset( $this->mParserOutput
) ) {
3920 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3921 foreach ( array_keys( $template ) as $dbk ) {
3922 $templates[] = Title
::makeTitle( $ns, $dbk );
3927 return $this->mTitle
->getTemplateLinksFrom();
3932 * Shows a bulletin board style toolbar for common editing functions.
3933 * It can be disabled in the user preferences.
3935 * @param Title $title Title object for the page being edited (optional)
3938 static function getEditToolbar( $title = null ) {
3939 global $wgContLang, $wgOut;
3940 global $wgEnableUploads, $wgForeignFileRepos;
3942 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3943 $showSignature = true;
3945 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
3949 * $toolarray is an array of arrays each of which includes the
3950 * opening tag, the closing tag, optionally a sample text that is
3951 * inserted between the two when no selection is highlighted
3952 * and. The tip text is shown when the user moves the mouse
3955 * Images are defined in ResourceLoaderEditToolbarModule.
3959 'id' => 'mw-editbutton-bold',
3961 'close' => '\'\'\'',
3962 'sample' => wfMessage( 'bold_sample' )->text(),
3963 'tip' => wfMessage( 'bold_tip' )->text(),
3966 'id' => 'mw-editbutton-italic',
3969 'sample' => wfMessage( 'italic_sample' )->text(),
3970 'tip' => wfMessage( 'italic_tip' )->text(),
3973 'id' => 'mw-editbutton-link',
3976 'sample' => wfMessage( 'link_sample' )->text(),
3977 'tip' => wfMessage( 'link_tip' )->text(),
3980 'id' => 'mw-editbutton-extlink',
3983 'sample' => wfMessage( 'extlink_sample' )->text(),
3984 'tip' => wfMessage( 'extlink_tip' )->text(),
3987 'id' => 'mw-editbutton-headline',
3990 'sample' => wfMessage( 'headline_sample' )->text(),
3991 'tip' => wfMessage( 'headline_tip' )->text(),
3993 $imagesAvailable ?
[
3994 'id' => 'mw-editbutton-image',
3995 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3997 'sample' => wfMessage( 'image_sample' )->text(),
3998 'tip' => wfMessage( 'image_tip' )->text(),
4000 $imagesAvailable ?
[
4001 'id' => 'mw-editbutton-media',
4002 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4004 'sample' => wfMessage( 'media_sample' )->text(),
4005 'tip' => wfMessage( 'media_tip' )->text(),
4008 'id' => 'mw-editbutton-nowiki',
4009 'open' => "<nowiki>",
4010 'close' => "</nowiki>",
4011 'sample' => wfMessage( 'nowiki_sample' )->text(),
4012 'tip' => wfMessage( 'nowiki_tip' )->text(),
4015 'id' => 'mw-editbutton-signature',
4016 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4019 'tip' => wfMessage( 'sig_tip' )->text(),
4022 'id' => 'mw-editbutton-hr',
4023 'open' => "\n----\n",
4026 'tip' => wfMessage( 'hr_tip' )->text(),
4030 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4031 foreach ( $toolarray as $tool ) {
4037 // Images are defined in ResourceLoaderEditToolbarModule
4039 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4040 // Older browsers show a "speedtip" type message only for ALT.
4041 // Ideally these should be different, realistically they
4042 // probably don't need to be.
4050 $script .= Xml
::encodeJsCall(
4051 'mw.toolbar.addButton',
4053 ResourceLoader
::inDebugMode()
4058 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
4060 $toolbar = '<div id="toolbar"></div>';
4062 Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] );
4068 * Returns an array of html code of the following checkboxes:
4071 * @param int $tabindex Current tabindex
4072 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4073 * status of the checkbox
4077 public function getCheckboxes( &$tabindex, $checked ) {
4078 global $wgUser, $wgUseMediaWikiUIEverywhere;
4082 // don't show the minor edit checkbox if it's a new page or section
4083 if ( !$this->isNew
) {
4084 $checkboxes['minor'] = '';
4085 $minorLabel = $this->context
->msg( 'minoredit' )->parse();
4086 if ( $wgUser->isAllowed( 'minoredit' ) ) {
4088 'tabindex' => ++
$tabindex,
4089 'accesskey' => $this->context
->msg( 'accesskey-minoredit' )->text(),
4090 'id' => 'wpMinoredit',
4093 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
4094 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
4095 Xml
::expandAttributes( [ 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ] ) .
4096 ">{$minorLabel}</label>";
4098 if ( $wgUseMediaWikiUIEverywhere ) {
4099 $checkboxes['minor'] = Html
::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
4101 Html
::closeElement( 'div' );
4103 $checkboxes['minor'] = $minorEditHtml;
4108 $watchLabel = $this->context
->msg( 'watchthis' )->parse();
4109 $checkboxes['watch'] = '';
4110 if ( $wgUser->isLoggedIn() ) {
4112 'tabindex' => ++
$tabindex,
4113 'accesskey' => $this->context
->msg( 'accesskey-watch' )->text(),
4114 'id' => 'wpWatchthis',
4117 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
4118 " <label for='wpWatchthis' id='mw-editpage-watch'" .
4119 Xml
::expandAttributes( [ 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ] ) .
4120 ">{$watchLabel}</label>";
4121 if ( $wgUseMediaWikiUIEverywhere ) {
4122 $checkboxes['watch'] = Html
::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
4124 Html
::closeElement( 'div' );
4126 $checkboxes['watch'] = $watchThisHtml;
4129 Hooks
::run( 'EditPageBeforeEditChecks', [ &$this, &$checkboxes, &$tabindex ] );
4134 * Returns an array of html code of the following buttons:
4135 * save, diff, preview and live
4137 * @param int $tabindex Current tabindex
4141 public function getEditButtons( &$tabindex ) {
4145 $this->mArticle
->getContext()->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4147 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4148 if ( $labelAsPublish ) {
4149 $buttonLabelKey = !$this->mTitle
->exists() ?
'publishpage' : 'publishchanges';
4151 $buttonLabelKey = !$this->mTitle
->exists() ?
'savearticle' : 'savechanges';
4153 $buttonLabel = $this->context
->msg( $buttonLabelKey )->text();
4157 'tabindex' => ++
$tabindex,
4158 ] + Linker
::tooltipAndAccesskeyAttribs( 'save' );
4159 $buttons['save'] = Html
::submitButton( $buttonLabel, $attribs, [ 'mw-ui-progressive' ] );
4161 ++
$tabindex; // use the same for preview and live preview
4163 'id' => 'wpPreview',
4164 'name' => 'wpPreview',
4165 'tabindex' => $tabindex,
4166 ] + Linker
::tooltipAndAccesskeyAttribs( 'preview' );
4167 $buttons['preview'] = Html
::submitButton( $this->context
->msg( 'showpreview' )->text(),
4169 $buttons['live'] = '';
4174 'tabindex' => ++
$tabindex,
4175 ] + Linker
::tooltipAndAccesskeyAttribs( 'diff' );
4176 $buttons['diff'] = Html
::submitButton( $this->context
->msg( 'showdiff' )->text(),
4179 Hooks
::run( 'EditPageBeforeEditButtons', [ &$this, &$buttons, &$tabindex ] );
4184 * Creates a basic error page which informs the user that
4185 * they have attempted to edit a nonexistent section.
4187 function noSuchSectionPage() {
4190 $wgOut->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4192 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4193 Hooks
::run( 'EditPageNoSuchSection', [ &$this, &$res ] );
4194 $wgOut->addHTML( $res );
4196 $wgOut->returnToMain( false, $this->mTitle
);
4200 * Show "your edit contains spam" page with your diff and text
4202 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4204 public function spamPageWithContent( $match = false ) {
4205 global $wgOut, $wgLang;
4206 $this->textbox2
= $this->textbox1
;
4208 if ( is_array( $match ) ) {
4209 $match = $wgLang->listToText( $match );
4211 $wgOut->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4213 $wgOut->addHTML( '<div id="spamprotected">' );
4214 $wgOut->addWikiMsg( 'spamprotectiontext' );
4216 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4218 $wgOut->addHTML( '</div>' );
4220 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4223 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4224 $this->showTextbox2();
4226 $wgOut->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4230 * Check if the browser is on a blacklist of user-agents known to
4231 * mangle UTF-8 data on form submission. Returns true if Unicode
4232 * should make it through, false if it's known to be a problem.
4235 private function checkUnicodeCompliantBrowser() {
4236 global $wgBrowserBlackList, $wgRequest;
4238 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
4239 if ( $currentbrowser === false ) {
4240 // No User-Agent header sent? Trust it by default...
4244 foreach ( $wgBrowserBlackList as $browser ) {
4245 if ( preg_match( $browser, $currentbrowser ) ) {
4253 * Filter an input field through a Unicode de-armoring process if it
4254 * came from an old browser with known broken Unicode editing issues.
4256 * @param WebRequest $request
4257 * @param string $field
4260 protected function safeUnicodeInput( $request, $field ) {
4261 $text = rtrim( $request->getText( $field ) );
4262 return $request->getBool( 'safemode' )
4263 ?
$this->unmakeSafe( $text )
4268 * Filter an output field through a Unicode armoring process if it is
4269 * going to an old browser with known broken Unicode editing issues.
4271 * @param string $text
4274 protected function safeUnicodeOutput( $text ) {
4275 return $this->checkUnicodeCompliantBrowser()
4277 : $this->makeSafe( $text );
4281 * A number of web browsers are known to corrupt non-ASCII characters
4282 * in a UTF-8 text editing environment. To protect against this,
4283 * detected browsers will be served an armored version of the text,
4284 * with non-ASCII chars converted to numeric HTML character references.
4286 * Preexisting such character references will have a 0 added to them
4287 * to ensure that round-trips do not alter the original data.
4289 * @param string $invalue
4292 private function makeSafe( $invalue ) {
4293 // Armor existing references for reversibility.
4294 $invalue = strtr( $invalue, [ "&#x" => "�" ] );
4299 $valueLength = strlen( $invalue );
4300 for ( $i = 0; $i < $valueLength; $i++
) {
4301 $bytevalue = ord( $invalue[$i] );
4302 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4303 $result .= chr( $bytevalue );
4305 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4306 $working = $working << 6;
4307 $working +
= ( $bytevalue & 0x3F );
4309 if ( $bytesleft <= 0 ) {
4310 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4312 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4313 $working = $bytevalue & 0x1F;
4315 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4316 $working = $bytevalue & 0x0F;
4318 } else { // 1111 0xxx
4319 $working = $bytevalue & 0x07;
4327 * Reverse the previously applied transliteration of non-ASCII characters
4328 * back to UTF-8. Used to protect data from corruption by broken web browsers
4329 * as listed in $wgBrowserBlackList.
4331 * @param string $invalue
4334 private function unmakeSafe( $invalue ) {
4336 $valueLength = strlen( $invalue );
4337 for ( $i = 0; $i < $valueLength; $i++
) {
4338 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4342 $hexstring .= $invalue[$i];
4344 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4346 // Do some sanity checks. These aren't needed for reversibility,
4347 // but should help keep the breakage down if the editor
4348 // breaks one of the entities whilst editing.
4349 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4350 $codepoint = hexdec( $hexstring );
4351 $result .= UtfNormal\Utils
::codepointToUtf8( $codepoint );
4353 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4356 $result .= substr( $invalue, $i, 1 );
4359 // reverse the transform that we made for reversibility reasons.
4360 return strtr( $result, [ "�" => "&#x" ] );