3 * User interface for page editing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\EditPage\TextboxBuilder
;
24 use MediaWiki\EditPage\TextConflictHelper
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\ScopedCallback
;
30 * The edit page/HTML interface (split from Article)
31 * The actual database and text munging is still in Article,
32 * but it should get easier to call those from alternate
35 * EditPage cares about two distinct titles:
36 * $this->mContextTitle is the page that forms submit to, links point to,
37 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
38 * page in the database that is actually being edited. These are
39 * usually the same, but they are now allowed to be different.
41 * Surgeon General's Warning: prolonged exposure to this class is known to cause
42 * headaches, which may be fatal.
46 * Used for Unicode support checks
48 const UNICODE_CHECK
= 'β³π²β₯πππΎπΈβ΄πΉβ―';
51 * Status: Article successfully updated
53 const AS_SUCCESS_UPDATE
= 200;
56 * Status: Article successfully created
58 const AS_SUCCESS_NEW_ARTICLE
= 201;
61 * Status: Article update aborted by a hook function
63 const AS_HOOK_ERROR
= 210;
66 * Status: A hook function returned an error
68 const AS_HOOK_ERROR_EXPECTED
= 212;
71 * Status: User is blocked from editing this page
73 const AS_BLOCKED_PAGE_FOR_USER
= 215;
76 * Status: Content too big (> $wgMaxArticleSize)
78 const AS_CONTENT_TOO_BIG
= 216;
81 * Status: this anonymous user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_ANON
= 218;
86 * Status: this logged in user is not allowed to edit this page
88 const AS_READ_ONLY_PAGE_LOGGED
= 219;
91 * Status: wiki is in readonly mode (wfReadOnly() == true)
93 const AS_READ_ONLY_PAGE
= 220;
96 * Status: rate limiter for action 'edit' was tripped
98 const AS_RATE_LIMITED
= 221;
101 * Status: article was deleted while editing and param wpRecreate == false or form
104 const AS_ARTICLE_WAS_DELETED
= 222;
107 * Status: user tried to create this page, but is not allowed to do that
108 * ( Title->userCan('create') == false )
110 const AS_NO_CREATE_PERMISSION
= 223;
113 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
115 const AS_BLANK_ARTICLE
= 224;
118 * Status: (non-resolvable) edit conflict
120 const AS_CONFLICT_DETECTED
= 225;
123 * Status: no edit summary given and the user has forceeditsummary set and the user is not
124 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
126 const AS_SUMMARY_NEEDED
= 226;
129 * Status: user tried to create a new section without content
131 const AS_TEXTBOX_EMPTY
= 228;
134 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
136 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
139 * Status: WikiPage::doEdit() was unsuccessful
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
146 const AS_SPAM_ERROR
= 232;
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
151 const AS_IMAGE_REDIRECT_ANON
= 233;
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
156 const AS_IMAGE_REDIRECT_LOGGED
= 234;
159 * Status: user tried to modify the content model, but is not allowed to do that
160 * ( User::isAllowed('editcontentmodel') == false )
162 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
165 * Status: user tried to create self-redirect (redirect to the same article) and
166 * wpIgnoreSelfRedirect == false
168 const AS_SELF_REDIRECT
= 236;
171 * Status: an error relating to change tagging. Look at the message key for
174 const AS_CHANGE_TAG_ERROR
= 237;
177 * Status: can't parse content
179 const AS_PARSE_ERROR
= 240;
182 * Status: when changing the content model is disallowed due to
183 * $wgContentHandlerUseDB being false
185 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
188 * Status: edit rejected because browser doesn't support Unicode.
190 const AS_UNICODE_NOT_SUPPORTED
= 242;
193 * HTML id and name for the beginning of the edit form.
195 const EDITFORM_ID
= 'editform';
198 * Prefix of key for cookie used to pass post-edit state.
199 * The revision id edited is added after this
201 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
204 * Duration of PostEdit cookie, in seconds.
205 * The cookie will be removed instantly if the JavaScript runs.
207 * Otherwise, though, we don't want the cookies to accumulate.
208 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
209 * limit of only 20 cookies per domain. This still applies at least to some
210 * versions of IE without full updates:
211 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
213 * A value of 20 minutes should be enough to take into account slow loads and minor
214 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
216 const POST_EDIT_COOKIE_DURATION
= 1200;
219 * @deprecated for public usage since 1.30 use EditPage::getArticle()
227 * @deprecated for public usage since 1.30 use EditPage::getTitle()
232 /** @var null|Title */
233 private $mContextTitle = null;
236 public $action = 'submit';
238 /** @var bool Whether an edit conflict needs to be resolved. Detected based on whether
239 * $editRevId is different from the current revision. When a conflict has successfully
240 * been resolved by a 3-way-merge, this field is set to false.
242 public $isConflict = false;
244 /** @var bool New page or new section */
245 public $isNew = false;
248 public $deletedSinceEdit;
256 /** @var bool|stdClass */
260 public $mTokenOk = false;
263 public $mTokenOkExceptSuffix = false;
266 public $mTriedSave = false;
269 public $incompleteForm = false;
272 public $tooBig = false;
275 public $missingComment = false;
278 public $missingSummary = false;
281 public $allowBlankSummary = false;
284 protected $blankArticle = false;
287 protected $allowBlankArticle = false;
290 protected $selfRedirect = false;
293 protected $allowSelfRedirect = false;
296 public $autoSumm = '';
299 public $hookError = '';
301 /** @var ParserOutput */
302 public $mParserOutput;
304 /** @var bool Has a summary been preset using GET parameter &summary= ? */
305 public $hasPresetSummary = false;
307 /** @var Revision|bool|null A revision object corresponding to $this->editRevId. */
308 public $mBaseRevision = false;
311 public $mShowSummaryField = true;
316 public $save = false;
319 public $preview = false;
322 public $diff = false;
325 public $minoredit = false;
328 public $watchthis = false;
331 public $recreate = false;
334 public $textbox1 = '';
337 public $textbox2 = '';
340 public $summary = '';
343 public $nosummary = false;
346 public $edittime = '';
348 /** @var int ID of the current revision at the time editing was initiated on the client.
349 * This is used to detect and resolve edit conflicts.
351 * @note 0 if the page did not exist at that time.
352 * @note When starting an edit from an old revision, this still records the current
353 * revision at the time , not the one the edit is based on.
356 * @see getBaseRevision()
358 private $editRevId = null;
361 public $section = '';
364 public $sectiontitle = '';
367 public $starttime = '';
369 /** @var int Revision ID the edit is based on, or 0 if it's the current revision.
374 /** @var int Revision ID the edit is based on, adjusted when an edit conflict is resolved.
377 * @see getparentRevId()
379 public $parentRevId = 0;
382 public $editintro = '';
385 public $scrolltop = null;
391 public $contentModel;
393 /** @var null|string */
394 public $contentFormat = null;
396 /** @var null|array */
397 private $changeTags = null;
399 # Placeholders for text injection by hooks (must be HTML)
400 # extensions should take care to _append_ to the present value
402 /** @var string Before even the preview */
403 public $editFormPageTop = '';
404 public $editFormTextTop = '';
405 public $editFormTextBeforeContent = '';
406 public $editFormTextAfterWarn = '';
407 public $editFormTextAfterTools = '';
408 public $editFormTextBottom = '';
409 public $editFormTextAfterContent = '';
410 public $previewTextAfterContent = '';
411 public $mPreloadContent = null;
413 /* $didSave should be set to true whenever an article was successfully altered. */
414 public $didSave = false;
415 public $undidRev = 0;
417 public $suppressIntro = false;
423 protected $contentLength = false;
426 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
428 private $enableApiEditOverride = false;
431 * @var IContextSource
436 * @var bool Whether an old revision is edited
438 private $isOldRev = false;
441 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
443 private $unicodeCheck;
446 * Factory function to create an edit conflict helper
450 private $editConflictHelperFactory;
453 * @var TextConflictHelper|null
455 private $editConflictHelper;
458 * @param Article $article
460 public function __construct( Article
$article ) {
461 $this->mArticle
= $article;
462 $this->page
= $article->getPage(); // model object
463 $this->mTitle
= $article->getTitle();
464 $this->context
= $article->getContext();
466 $this->contentModel
= $this->mTitle
->getContentModel();
468 $handler = ContentHandler
::getForModelID( $this->contentModel
);
469 $this->contentFormat
= $handler->getDefaultFormat();
470 $this->editConflictHelperFactory
= [ $this, 'newTextConflictHelper' ];
476 public function getArticle() {
477 return $this->mArticle
;
482 * @return IContextSource
484 public function getContext() {
485 return $this->context
;
492 public function getTitle() {
493 return $this->mTitle
;
497 * Set the context Title object
499 * @param Title|null $title Title object or null
501 public function setContextTitle( $title ) {
502 $this->mContextTitle
= $title;
506 * Get the context title object.
508 * If not set, $wgTitle will be returned, but this is deprecated. This will
509 * throw an exception.
513 public function getContextTitle() {
514 if ( is_null( $this->mContextTitle
) ) {
515 wfDeprecated( __METHOD__
. ' called with no title set', '1.32' );
519 return $this->mContextTitle
;
524 * Returns if the given content model is editable.
526 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
528 * @throws MWException If $modelId has no known handler
530 public function isSupportedContentModel( $modelId ) {
531 return $this->enableApiEditOverride
=== true ||
532 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
536 * Allow editing of content that supports API direct editing, but not general
537 * direct editing. Set to false by default.
539 * @param bool $enableOverride
541 public function setApiEditOverride( $enableOverride ) {
542 $this->enableApiEditOverride
= $enableOverride;
546 * @deprecated since 1.29, call edit directly
548 public function submit() {
549 wfDeprecated( __METHOD__
, '1.29' );
554 * This is the function that gets called for "action=edit". It
555 * sets up various member variables, then passes execution to
556 * another function, usually showEditForm()
558 * The edit form is self-submitting, so that when things like
559 * preview and edit conflicts occur, we get the same form back
560 * with the extra stuff added. Only when the final submission
561 * is made and all is well do we actually save and redirect to
562 * the newly-edited page.
564 public function edit() {
565 // Allow extensions to modify/prevent this form or submission
566 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
570 wfDebug( __METHOD__
. ": enter\n" );
572 $request = $this->context
->getRequest();
573 // If they used redlink=1 and the page exists, redirect to the main article
574 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
575 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
579 $this->importFormData( $request );
580 $this->firsttime
= false;
582 if ( wfReadOnly() && $this->save
) {
585 $this->preview
= true;
589 $this->formtype
= 'save';
590 } elseif ( $this->preview
) {
591 $this->formtype
= 'preview';
592 } elseif ( $this->diff
) {
593 $this->formtype
= 'diff';
594 } else { # First time through
595 $this->firsttime
= true;
596 if ( $this->previewOnOpen() ) {
597 $this->formtype
= 'preview';
599 $this->formtype
= 'initial';
603 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
605 wfDebug( __METHOD__
. ": User can't edit\n" );
607 // track block with a cookie if it doesn't exists already
608 $this->context
->getUser()->trackBlockWithCookie();
610 // Auto-block user's IP if the account was "hard" blocked
611 if ( !wfReadOnly() ) {
612 DeferredUpdates
::addCallableUpdate( function () {
613 $this->context
->getUser()->spreadAnyEditBlock();
616 $this->displayPermissionsError( $permErrors );
621 $revision = $this->mArticle
->getRevisionFetched();
622 // Disallow editing revisions with content models different from the current one
623 // Undo edits being an exception in order to allow reverting content model changes.
625 && $revision->getContentModel() !== $this->contentModel
628 if ( $this->undidRev
) {
629 $undidRevObj = Revision
::newFromId( $this->undidRev
);
630 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
632 if ( !$this->undidRev
634 ||
$prevRev->getContentModel() !== $this->contentModel
636 $this->displayViewSourcePage(
637 $this->getContentObject(),
639 'contentmodelediterror',
640 $revision->getContentModel(),
648 $this->isConflict
= false;
650 # Show applicable editing introductions
651 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
655 # Attempt submission here. This will check for edit conflicts,
656 # and redundantly check for locked database, blocked IPs, etc.
657 # that edit() already checked just in case someone tries to sneak
658 # in the back door with a hand-edited submission URL.
660 if ( 'save' == $this->formtype
) {
661 $resultDetails = null;
662 $status = $this->attemptSave( $resultDetails );
663 if ( !$this->handleStatus( $status, $resultDetails ) ) {
668 # First time through: get contents, set time for conflict
670 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
671 if ( $this->initialiseForm() === false ) {
672 $this->noSuchSectionPage();
676 if ( !$this->mTitle
->getArticleID() ) {
677 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
679 Hooks
::run( 'EditFormInitialText', [ $this ] );
684 $this->showEditForm();
688 * @param string $rigor Same format as Title::getUserPermissionErrors()
691 protected function getEditPermissionErrors( $rigor = 'secure' ) {
692 $user = $this->context
->getUser();
693 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
694 # Can this title be created?
695 if ( !$this->mTitle
->exists() ) {
696 $permErrors = array_merge(
699 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
704 # Ignore some permissions errors when a user is just previewing/viewing diffs
706 foreach ( $permErrors as $error ) {
707 if ( ( $this->preview ||
$this->diff
)
709 $error[0] == 'blockedtext' ||
710 $error[0] == 'autoblockedtext' ||
711 $error[0] == 'systemblockedtext'
717 $permErrors = wfArrayDiff2( $permErrors, $remove );
723 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
724 * but with the following differences:
725 * - If redlink=1, the user will be redirected to the page
726 * - If there is content to display or the error occurs while either saving,
727 * previewing or showing the difference, it will be a
728 * "View source for ..." page displaying the source code after the error message.
731 * @param array $permErrors Array of permissions errors, as returned by
732 * Title::getUserPermissionsErrors().
733 * @throws PermissionsError
735 protected function displayPermissionsError( array $permErrors ) {
736 $out = $this->context
->getOutput();
737 if ( $this->context
->getRequest()->getBool( 'redlink' ) ) {
738 // The edit page was reached via a red link.
739 // Redirect to the article page and let them click the edit tab if
740 // they really want a permission error.
741 $out->redirect( $this->mTitle
->getFullURL() );
745 $content = $this->getContentObject();
747 # Use the normal message if there's nothing to display
748 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
749 $action = $this->mTitle
->exists() ?
'edit' :
750 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
751 throw new PermissionsError( $action, $permErrors );
754 $this->displayViewSourcePage(
756 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
761 * Display a read-only View Source page
762 * @param Content $content
763 * @param string $errorMessage additional wikitext error message to display
765 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
766 $out = $this->context
->getOutput();
767 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
769 $out->setRobotPolicy( 'noindex,nofollow' );
770 $out->setPageTitle( $this->context
->msg(
772 $this->getContextTitle()->getPrefixedText()
774 $out->addBacklinkSubtitle( $this->getContextTitle() );
775 $out->addHTML( $this->editFormPageTop
);
776 $out->addHTML( $this->editFormTextTop
);
778 if ( $errorMessage !== '' ) {
779 $out->addWikiText( $errorMessage );
780 $out->addHTML( "<hr />\n" );
783 # If the user made changes, preserve them when showing the markup
784 # (This happens when a user is blocked during edit, for instance)
785 if ( !$this->firsttime
) {
786 $text = $this->textbox1
;
787 $out->addWikiMsg( 'viewyourtext' );
790 $text = $this->toEditText( $content );
791 } catch ( MWException
$e ) {
792 # Serialize using the default format if the content model is not supported
793 # (e.g. for an old revision with a different model)
794 $text = $content->serialize();
796 $out->addWikiMsg( 'viewsourcetext' );
799 $out->addHTML( $this->editFormTextBeforeContent
);
800 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
801 $out->addHTML( $this->editFormTextAfterContent
);
803 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
805 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
807 $out->addHTML( $this->editFormTextBottom
);
808 if ( $this->mTitle
->exists() ) {
809 $out->returnToMain( null, $this->mTitle
);
814 * Should we show a preview when the edit form is first shown?
818 protected function previewOnOpen() {
819 $config = $this->context
->getConfig();
820 $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
821 $request = $this->context
->getRequest();
822 if ( $config->get( 'RawHtml' ) ) {
823 // If raw HTML is enabled, disable preview on open
824 // since it has to be posted with a token for
828 if ( $request->getVal( 'preview' ) == 'yes' ) {
829 // Explicit override from request
831 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
832 // Explicit override from request
834 } elseif ( $this->section
== 'new' ) {
835 // Nothing *to* preview for new sections
837 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
838 && $this->context
->getUser()->getOption( 'previewonfirst' )
840 // Standard preference behavior
842 } elseif ( !$this->mTitle
->exists()
843 && isset( $previewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
844 && $previewOnOpenNamespaces[$this->mTitle
->getNamespace()]
846 // Categories are special
854 * Checks whether the user entered a skin name in uppercase,
855 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
859 protected function isWrongCaseUserConfigPage() {
860 if ( $this->mTitle
->isUserConfigPage() ) {
861 $name = $this->mTitle
->getSkinFromConfigSubpage();
862 $skins = array_merge(
863 array_keys( Skin
::getSkinNames() ),
866 return !in_array( $name, $skins )
867 && in_array( strtolower( $name ), $skins );
874 * Returns whether section editing is supported for the current page.
875 * Subclasses may override this to replace the default behavior, which is
876 * to check ContentHandler::supportsSections.
878 * @return bool True if this edit page supports sections, false otherwise.
880 protected function isSectionEditSupported() {
881 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
882 return $contentHandler->supportsSections();
886 * This function collects the form data and uses it to populate various member variables.
887 * @param WebRequest &$request
888 * @throws ErrorPageError
890 public function importFormData( &$request ) {
891 # Section edit can come from either the form or a link
892 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
894 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
895 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
898 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
900 if ( $request->wasPosted() ) {
901 # These fields need to be checked for encoding.
902 # Also remove trailing whitespace, but don't remove _initial_
903 # whitespace from the text boxes. This may be significant formatting.
904 $this->textbox1
= rtrim( $request->getText( 'wpTextbox1' ) );
905 if ( !$request->getCheck( 'wpTextbox2' ) ) {
906 // Skip this if wpTextbox2 has input, it indicates that we came
907 // from a conflict page with raw page text, not a custom form
908 // modified by subclasses
909 $textbox1 = $this->importContentFormData( $request );
910 if ( $textbox1 !== null ) {
911 $this->textbox1
= $textbox1;
915 $this->unicodeCheck
= $request->getText( 'wpUnicodeCheck' );
917 $this->summary
= $request->getText( 'wpSummary' );
919 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
920 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
922 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
924 # Treat sectiontitle the same way as summary.
925 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
926 # currently doing double duty as both edit summary and section title. Right now this
927 # is just to allow API edits to work around this limitation, but this should be
928 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
929 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
930 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
932 $this->edittime
= $request->getVal( 'wpEdittime' );
933 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
934 $this->starttime
= $request->getVal( 'wpStarttime' );
936 $undidRev = $request->getInt( 'wpUndidRevision' );
938 $this->undidRev
= $undidRev;
941 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
943 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
944 // wpTextbox1 field is missing, possibly due to being "too big"
945 // according to some filter rules such as Suhosin's setting for
946 // suhosin.request.max_value_length (d'oh)
947 $this->incompleteForm
= true;
949 // If we receive the last parameter of the request, we can fairly
950 // claim the POST request has not been truncated.
951 $this->incompleteForm
= !$request->getVal( 'wpUltimateParam' );
953 if ( $this->incompleteForm
) {
954 # If the form is incomplete, force to preview.
955 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
956 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) . "\n" );
957 $this->preview
= true;
959 $this->preview
= $request->getCheck( 'wpPreview' );
960 $this->diff
= $request->getCheck( 'wpDiff' );
962 // Remember whether a save was requested, so we can indicate
963 // if we forced preview due to session failure.
964 $this->mTriedSave
= !$this->preview
;
966 if ( $this->tokenOk( $request ) ) {
967 # Some browsers will not report any submit button
968 # if the user hits enter in the comment box.
969 # The unmarked state will be assumed to be a save,
970 # if the form seems otherwise complete.
971 wfDebug( __METHOD__
. ": Passed token check.\n" );
972 } elseif ( $this->diff
) {
973 # Failed token check, but only requested "Show Changes".
974 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
976 # Page might be a hack attempt posted from
977 # an external site. Preview instead of saving.
978 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
979 $this->preview
= true;
982 $this->save
= !$this->preview
&& !$this->diff
;
983 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
984 $this->edittime
= null;
987 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
988 $this->starttime
= null;
991 $this->recreate
= $request->getCheck( 'wpRecreate' );
993 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
994 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
996 $user = $this->context
->getUser();
997 # Don't force edit summaries when a user is editing their own user or talk page
998 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
999 && $this->mTitle
->getText() == $user->getName()
1001 $this->allowBlankSummary
= true;
1003 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
1004 ||
!$user->getOption( 'forceeditsummary' );
1007 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
1009 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
1010 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
1012 $changeTags = $request->getVal( 'wpChangeTags' );
1013 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
1014 $this->changeTags
= [];
1016 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
1020 # Not a posted form? Start with nothing.
1021 wfDebug( __METHOD__
. ": Not a posted form.\n" );
1022 $this->textbox1
= '';
1023 $this->summary
= '';
1024 $this->sectiontitle
= '';
1025 $this->edittime
= '';
1026 $this->editRevId
= null;
1027 $this->starttime
= wfTimestampNow();
1028 $this->edit
= false;
1029 $this->preview
= false;
1030 $this->save
= false;
1031 $this->diff
= false;
1032 $this->minoredit
= false;
1033 // Watch may be overridden by request parameters
1034 $this->watchthis
= $request->getBool( 'watchthis', false );
1035 $this->recreate
= false;
1037 // When creating a new section, we can preload a section title by passing it as the
1038 // preloadtitle parameter in the URL (T15100)
1039 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1040 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1041 // Once wpSummary isn't being use for setting section titles, we should delete this.
1042 $this->summary
= $request->getVal( 'preloadtitle' );
1043 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1044 $this->summary
= $request->getText( 'summary' );
1045 if ( $this->summary
!== '' ) {
1046 $this->hasPresetSummary
= true;
1050 if ( $request->getVal( 'minor' ) ) {
1051 $this->minoredit
= true;
1055 $this->oldid
= $request->getInt( 'oldid' );
1056 $this->parentRevId
= $request->getInt( 'parentRevId' );
1058 $this->bot
= $request->getBool( 'bot', true );
1059 $this->nosummary
= $request->getBool( 'nosummary' );
1061 // May be overridden by revision.
1062 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1063 // May be overridden by revision.
1064 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1067 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1068 } catch ( MWUnknownContentModelException
$e ) {
1069 throw new ErrorPageError(
1070 'editpage-invalidcontentmodel-title',
1071 'editpage-invalidcontentmodel-text',
1072 [ wfEscapeWikiText( $this->contentModel
) ]
1076 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1077 throw new ErrorPageError(
1078 'editpage-notsupportedcontentformat-title',
1079 'editpage-notsupportedcontentformat-text',
1081 wfEscapeWikiText( $this->contentFormat
),
1082 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1088 * @todo Check if the desired model is allowed in this namespace, and if
1089 * a transition from the page's current model to the new model is
1093 $this->editintro
= $request->getText( 'editintro',
1094 // Custom edit intro for new sections
1095 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1097 // Allow extensions to modify form data
1098 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1102 * Subpage overridable method for extracting the page content data from the
1103 * posted form to be placed in $this->textbox1, if using customized input
1104 * this method should be overridden and return the page text that will be used
1105 * for saving, preview parsing and so on...
1107 * @param WebRequest &$request
1108 * @return string|null
1110 protected function importContentFormData( &$request ) {
1111 return; // Don't do anything, EditPage already extracted wpTextbox1
1115 * Initialise form fields in the object
1116 * Called on the first invocation, e.g. when a user clicks an edit link
1117 * @return bool If the requested section is valid
1119 public function initialiseForm() {
1120 $this->edittime
= $this->page
->getTimestamp();
1121 $this->editRevId
= $this->page
->getLatest();
1123 $content = $this->getContentObject( false ); # TODO: track content object?!
1124 if ( $content === false ) {
1127 $this->textbox1
= $this->toEditText( $content );
1129 $user = $this->context
->getUser();
1130 // activate checkboxes if user wants them to be always active
1131 # Sort out the "watch" checkbox
1132 if ( $user->getOption( 'watchdefault' ) ) {
1134 $this->watchthis
= true;
1135 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1137 $this->watchthis
= true;
1138 } elseif ( $user->isWatched( $this->mTitle
) ) {
1140 $this->watchthis
= true;
1142 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1143 $this->minoredit
= true;
1145 if ( $this->textbox1
=== false ) {
1152 * @param Content|null $def_content The default value to return
1154 * @return Content|null Content on success, $def_content for invalid sections
1158 protected function getContentObject( $def_content = null ) {
1163 $user = $this->context
->getUser();
1164 $request = $this->context
->getRequest();
1165 // For message page not locally set, use the i18n message.
1166 // For other non-existent articles, use preload text if any.
1167 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1168 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1169 # If this is a system message, get the default text.
1170 $msg = $this->mTitle
->getDefaultMessageText();
1172 $content = $this->toEditContent( $msg );
1174 if ( $content === false ) {
1175 # If requested, preload some text.
1176 $preload = $request->getVal( 'preload',
1177 // Custom preload text for new sections
1178 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1179 $params = $request->getArray( 'preloadparams', [] );
1181 $content = $this->getPreloadedContent( $preload, $params );
1183 // For existing pages, get text based on "undo" or section parameters.
1185 if ( $this->section
!= '' ) {
1186 // Get section edit text (returns $def_text for invalid sections)
1187 $orig = $this->getOriginalContent( $user );
1188 $content = $orig ?
$orig->getSection( $this->section
) : null;
1191 $content = $def_content;
1194 $undoafter = $request->getInt( 'undoafter' );
1195 $undo = $request->getInt( 'undo' );
1197 if ( $undo > 0 && $undoafter > 0 ) {
1198 $undorev = Revision
::newFromId( $undo );
1199 $oldrev = Revision
::newFromId( $undoafter );
1202 # Sanity check, make sure it's the right page,
1203 # the revisions exist and they were not deleted.
1204 # Otherwise, $content will be left as-is.
1205 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1206 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1207 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1209 if ( WikiPage
::hasDifferencesOutsideMainSlot( $undorev, $oldrev ) ) {
1210 // Cannot yet undo edits that involve anything other the main slot.
1211 $undoMsg = 'main-slot-only';
1213 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1215 if ( $content === false ) {
1216 # Warn the user that something went wrong
1217 $undoMsg = 'failure';
1221 if ( $undoMsg === null ) {
1222 $oldContent = $this->page
->getContent( Revision
::RAW
);
1223 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1224 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1225 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1226 // The undo may change content
1227 // model if its reverting the top
1228 // edit. This can result in
1229 // mismatched content model/format.
1230 $this->contentModel
= $newContent->getModel();
1231 $this->contentFormat
= $oldrev->getContentFormat();
1234 if ( $newContent->equals( $oldContent ) ) {
1235 # Tell the user that the undo results in no change,
1236 # i.e. the revisions were already undone.
1237 $undoMsg = 'nochange';
1240 # Inform the user of our success and set an automatic edit summary
1241 $undoMsg = 'success';
1243 # If we just undid one rev, use an autosummary
1244 $firstrev = $oldrev->getNext();
1245 if ( $firstrev && $firstrev->getId() == $undo ) {
1246 $userText = $undorev->getUserText();
1247 if ( $userText === '' ) {
1248 $undoSummary = $this->context
->msg(
1249 'undo-summary-username-hidden',
1251 )->inContentLanguage()->text();
1253 $undoSummary = $this->context
->msg(
1257 )->inContentLanguage()->text();
1259 if ( $this->summary
=== '' ) {
1260 $this->summary
= $undoSummary;
1262 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1263 ->inContentLanguage()->text() . $this->summary
;
1265 $this->undidRev
= $undo;
1267 $this->formtype
= 'diff';
1271 // Failed basic sanity checks.
1272 // Older revisions may have been removed since the link
1273 // was created, or we may simply have got bogus input.
1277 $out = $this->context
->getOutput();
1278 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1280 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1281 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1282 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1285 if ( $content === false ) {
1286 $content = $this->getOriginalContent( $user );
1295 * Get the content of the wanted revision, without section extraction.
1297 * The result of this function can be used to compare user's input with
1298 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1299 * to the original text of the edit.
1301 * This differs from Article::getContent() that when a missing revision is
1302 * encountered the result will be null and not the
1303 * 'missing-revision' message.
1306 * @param User $user The user to get the revision for
1307 * @return Content|null
1309 private function getOriginalContent( User
$user ) {
1310 if ( $this->section
== 'new' ) {
1311 return $this->getCurrentContent();
1313 $revision = $this->mArticle
->getRevisionFetched();
1314 if ( $revision === null ) {
1315 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1316 return $handler->makeEmptyContent();
1318 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1323 * Get the edit's parent revision ID
1325 * The "parent" revision is the ancestor that should be recorded in this
1326 * page's revision history. It is either the revision ID of the in-memory
1327 * article content, or in the case of a 3-way merge in order to rebase
1328 * across a recoverable edit conflict, the ID of the newer revision to
1329 * which we have rebased this page.
1332 * @return int Revision ID
1334 public function getParentRevId() {
1335 if ( $this->parentRevId
) {
1336 return $this->parentRevId
;
1338 return $this->mArticle
->getRevIdFetched();
1343 * Get the current content of the page. This is basically similar to
1344 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1345 * content object is returned instead of null.
1350 protected function getCurrentContent() {
1351 $rev = $this->page
->getRevision();
1352 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1354 if ( $content === false ||
$content === null ) {
1355 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1356 return $handler->makeEmptyContent();
1357 } elseif ( !$this->undidRev
) {
1358 // Content models should always be the same since we error
1359 // out if they are different before this point (in ->edit()).
1360 // The exception being, during an undo, the current revision might
1361 // differ from the prior revision.
1362 $logger = LoggerFactory
::getInstance( 'editpage' );
1363 if ( $this->contentModel
!== $rev->getContentModel() ) {
1364 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1365 'prev' => $this->contentModel
,
1366 'new' => $rev->getContentModel(),
1367 'title' => $this->getTitle()->getPrefixedDBkey(),
1368 'method' => __METHOD__
1370 $this->contentModel
= $rev->getContentModel();
1373 // Given that the content models should match, the current selected
1374 // format should be supported.
1375 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1376 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1378 'prev' => $this->contentFormat
,
1379 'new' => $rev->getContentFormat(),
1380 'title' => $this->getTitle()->getPrefixedDBkey(),
1381 'method' => __METHOD__
1383 $this->contentFormat
= $rev->getContentFormat();
1390 * Use this method before edit() to preload some content into the edit box
1392 * @param Content $content
1396 public function setPreloadedContent( Content
$content ) {
1397 $this->mPreloadContent
= $content;
1401 * Get the contents to be preloaded into the box, either set by
1402 * an earlier setPreloadText() or by loading the given page.
1404 * @param string $preload Representing the title to preload from.
1405 * @param array $params Parameters to use (interface-message style) in the preloaded text
1411 protected function getPreloadedContent( $preload, $params = [] ) {
1412 if ( !empty( $this->mPreloadContent
) ) {
1413 return $this->mPreloadContent
;
1416 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1418 if ( $preload === '' ) {
1419 return $handler->makeEmptyContent();
1422 $user = $this->context
->getUser();
1423 $title = Title
::newFromText( $preload );
1424 # Check for existence to avoid getting MediaWiki:Noarticletext
1425 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1426 // TODO: somehow show a warning to the user!
1427 return $handler->makeEmptyContent();
1430 $page = WikiPage
::factory( $title );
1431 if ( $page->isRedirect() ) {
1432 $title = $page->getRedirectTarget();
1434 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1435 // TODO: somehow show a warning to the user!
1436 return $handler->makeEmptyContent();
1438 $page = WikiPage
::factory( $title );
1441 $parserOptions = ParserOptions
::newFromUser( $user );
1442 $content = $page->getContent( Revision
::RAW
);
1445 // TODO: somehow show a warning to the user!
1446 return $handler->makeEmptyContent();
1449 if ( $content->getModel() !== $handler->getModelID() ) {
1450 $converted = $content->convert( $handler->getModelID() );
1452 if ( !$converted ) {
1453 // TODO: somehow show a warning to the user!
1454 wfDebug( "Attempt to preload incompatible content: " .
1455 "can't convert " . $content->getModel() .
1456 " to " . $handler->getModelID() );
1458 return $handler->makeEmptyContent();
1461 $content = $converted;
1464 return $content->preloadTransform( $title, $parserOptions, $params );
1468 * Make sure the form isn't faking a user's credentials.
1470 * @param WebRequest &$request
1474 public function tokenOk( &$request ) {
1475 $token = $request->getVal( 'wpEditToken' );
1476 $user = $this->context
->getUser();
1477 $this->mTokenOk
= $user->matchEditToken( $token );
1478 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1479 return $this->mTokenOk
;
1483 * Sets post-edit cookie indicating the user just saved a particular revision.
1485 * This uses a temporary cookie for each revision ID so separate saves will never
1486 * interfere with each other.
1488 * Article::view deletes the cookie on server-side after the redirect and
1489 * converts the value to the global JavaScript variable wgPostEdit.
1491 * If the variable were set on the server, it would be cached, which is unwanted
1492 * since the post-edit state should only apply to the load right after the save.
1494 * @param int $statusValue The status value (to check for new article status)
1496 protected function setPostEditCookie( $statusValue ) {
1497 $revisionId = $this->page
->getLatest();
1498 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1501 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1503 } elseif ( $this->oldid
) {
1507 $response = $this->context
->getRequest()->response();
1508 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1512 * Attempt submission
1513 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1514 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1515 * @return Status The resulting status object.
1517 public function attemptSave( &$resultDetails = false ) {
1518 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1519 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1520 // This is needed since PageUpdater no longer checks these rights!
1522 // Allow bots to exempt some edits from bot flagging
1523 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1524 $status = $this->internalAttemptSave( $resultDetails, $bot );
1526 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1532 * Log when a page was successfully saved after the edit conflict view
1534 private function incrementResolvedConflicts() {
1535 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1539 $this->getEditConflictHelper()->incrementResolvedStats();
1543 * Handle status, such as after attempt save
1545 * @param Status $status
1546 * @param array|bool $resultDetails
1548 * @throws ErrorPageError
1549 * @return bool False, if output is done, true if rest of the form should be displayed
1551 private function handleStatus( Status
$status, $resultDetails ) {
1553 * @todo FIXME: once the interface for internalAttemptSave() is made
1554 * nicer, this should use the message in $status
1556 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1557 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1559 $this->incrementResolvedConflicts();
1561 $this->didSave
= true;
1562 if ( !$resultDetails['nullEdit'] ) {
1563 $this->setPostEditCookie( $status->value
);
1567 $out = $this->context
->getOutput();
1569 // "wpExtraQueryRedirect" is a hidden input to modify
1570 // after save URL and is not used by actual edit form
1571 $request = $this->context
->getRequest();
1572 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1574 switch ( $status->value
) {
1575 case self
::AS_HOOK_ERROR_EXPECTED
:
1576 case self
::AS_CONTENT_TOO_BIG
:
1577 case self
::AS_ARTICLE_WAS_DELETED
:
1578 case self
::AS_CONFLICT_DETECTED
:
1579 case self
::AS_SUMMARY_NEEDED
:
1580 case self
::AS_TEXTBOX_EMPTY
:
1581 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1583 case self
::AS_BLANK_ARTICLE
:
1584 case self
::AS_SELF_REDIRECT
:
1587 case self
::AS_HOOK_ERROR
:
1590 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1591 case self
::AS_PARSE_ERROR
:
1592 case self
::AS_UNICODE_NOT_SUPPORTED
:
1593 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1596 case self
::AS_SUCCESS_NEW_ARTICLE
:
1597 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1598 if ( $extraQueryRedirect ) {
1599 if ( $query === '' ) {
1600 $query = $extraQueryRedirect;
1602 $query = $query . '&' . $extraQueryRedirect;
1605 $anchor = $resultDetails['sectionanchor'] ??
'';
1606 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1609 case self
::AS_SUCCESS_UPDATE
:
1611 $sectionanchor = $resultDetails['sectionanchor'];
1613 // Give extensions a chance to modify URL query on update
1615 'ArticleUpdateBeforeRedirect',
1616 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1619 if ( $resultDetails['redirect'] ) {
1620 if ( $extraQuery == '' ) {
1621 $extraQuery = 'redirect=no';
1623 $extraQuery = 'redirect=no&' . $extraQuery;
1626 if ( $extraQueryRedirect ) {
1627 if ( $extraQuery === '' ) {
1628 $extraQuery = $extraQueryRedirect;
1630 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1634 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1637 case self
::AS_SPAM_ERROR
:
1638 $this->spamPageWithContent( $resultDetails['spam'] );
1641 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1642 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1644 case self
::AS_IMAGE_REDIRECT_ANON
:
1645 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1646 throw new PermissionsError( 'upload' );
1648 case self
::AS_READ_ONLY_PAGE_ANON
:
1649 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1650 throw new PermissionsError( 'edit' );
1652 case self
::AS_READ_ONLY_PAGE
:
1653 throw new ReadOnlyError
;
1655 case self
::AS_RATE_LIMITED
:
1656 throw new ThrottledError();
1658 case self
::AS_NO_CREATE_PERMISSION
:
1659 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1660 throw new PermissionsError( $permission );
1662 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1663 throw new PermissionsError( 'editcontentmodel' );
1666 // We don't recognize $status->value. The only way that can happen
1667 // is if an extension hook aborted from inside ArticleSave.
1668 // Render the status object into $this->hookError
1669 // FIXME this sucks, we should just use the Status object throughout
1670 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1677 * Run hooks that can filter edits just before they get saved.
1679 * @param Content $content The Content to filter.
1680 * @param Status $status For reporting the outcome to the caller
1681 * @param User $user The user performing the edit
1685 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1686 // Run old style post-section-merge edit filter
1687 if ( $this->hookError
!= '' ) {
1688 # ...or the hook could be expecting us to produce an error
1689 $status->fatal( 'hookaborted' );
1690 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1694 // Run new style post-section-merge edit filter
1695 if ( !Hooks
::run( 'EditFilterMergedContent',
1696 [ $this->context
, $content, $status, $this->summary
,
1697 $user, $this->minoredit
] )
1699 # Error messages etc. could be handled within the hook...
1700 if ( $status->isGood() ) {
1701 $status->fatal( 'hookaborted' );
1702 // Not setting $this->hookError here is a hack to allow the hook
1703 // to cause a return to the edit page without $this->hookError
1704 // being set. This is used by ConfirmEdit to display a captcha
1705 // without any error message cruft.
1707 $this->hookError
= $this->formatStatusErrors( $status );
1709 // Use the existing $status->value if the hook set it
1710 if ( !$status->value
) {
1711 $status->value
= self
::AS_HOOK_ERROR
;
1714 } elseif ( !$status->isOK() ) {
1715 # ...or the hook could be expecting us to produce an error
1716 // FIXME this sucks, we should just use the Status object throughout
1717 $this->hookError
= $this->formatStatusErrors( $status );
1718 $status->fatal( 'hookaborted' );
1719 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1727 * Wrap status errors in an errorbox for increased visibility
1729 * @param Status $status
1730 * @return string Wikitext
1732 private function formatStatusErrors( Status
$status ) {
1733 $errmsg = $status->getWikiText(
1736 $this->context
->getLanguage()
1739 <div class="errorbox">
1747 * Return the summary to be used for a new section.
1749 * @param string $sectionanchor Set to the section anchor text
1752 private function newSectionSummary( &$sectionanchor = null ) {
1755 if ( $this->sectiontitle
!== '' ) {
1756 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1757 // If no edit summary was specified, create one automatically from the section
1758 // title and have it link to the new section. Otherwise, respect the summary as
1760 if ( $this->summary
=== '' ) {
1761 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1762 return $this->context
->msg( 'newsectionsummary' )
1763 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1765 } elseif ( $this->summary
!== '' ) {
1766 $sectionanchor = $this->guessSectionName( $this->summary
);
1767 # This is a new section, so create a link to the new section
1768 # in the revision summary.
1769 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1770 return $this->context
->msg( 'newsectionsummary' )
1771 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1773 return $this->summary
;
1777 * Attempt submission (no UI)
1779 * @param array &$result Array to add statuses to, currently with the
1781 * - spam (string): Spam string from content if any spam is detected by
1783 * - sectionanchor (string): Section anchor for a section save.
1784 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1786 * - redirect (bool): Set if doEditContent is OK. True if resulting
1787 * revision is a redirect.
1788 * @param bool $bot True if edit is being made under the bot right.
1790 * @return Status Status object, possibly with a message, but always with
1791 * one of the AS_* constants in $status->value,
1793 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1794 * various error display idiosyncrasies. There are also lots of cases
1795 * where error metadata is set in the object and retrieved later instead
1796 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1797 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1800 public function internalAttemptSave( &$result, $bot = false ) {
1801 $status = Status
::newGood();
1802 $user = $this->context
->getUser();
1804 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1805 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1806 $status->fatal( 'hookaborted' );
1807 $status->value
= self
::AS_HOOK_ERROR
;
1811 if ( $this->unicodeCheck
!== self
::UNICODE_CHECK
) {
1812 $status->fatal( 'unicode-support-fail' );
1813 $status->value
= self
::AS_UNICODE_NOT_SUPPORTED
;
1817 $request = $this->context
->getRequest();
1818 $spam = $request->getText( 'wpAntispam' );
1819 if ( $spam !== '' ) {
1824 $this->mTitle
->getPrefixedText() .
1825 '" submitted bogus field "' .
1829 $status->fatal( 'spamprotectionmatch', false );
1830 $status->value
= self
::AS_SPAM_ERROR
;
1835 # Construct Content object
1836 $textbox_content = $this->toEditContent( $this->textbox1
);
1837 } catch ( MWContentSerializationException
$ex ) {
1839 'content-failed-to-parse',
1840 $this->contentModel
,
1841 $this->contentFormat
,
1844 $status->value
= self
::AS_PARSE_ERROR
;
1848 # Check image redirect
1849 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1850 $textbox_content->isRedirect() &&
1851 !$user->isAllowed( 'upload' )
1853 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1854 $status->setResult( false, $code );
1860 $match = self
::matchSummarySpamRegex( $this->summary
);
1861 if ( $match === false && $this->section
== 'new' ) {
1862 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1863 # regular summaries, it is added to the actual wikitext.
1864 if ( $this->sectiontitle
!== '' ) {
1865 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1866 $match = self
::matchSpamRegex( $this->sectiontitle
);
1868 # This branch is taken when the "Add Topic" user interface is used, or the API
1869 # is used with the 'summary' parameter.
1870 $match = self
::matchSpamRegex( $this->summary
);
1873 if ( $match === false ) {
1874 $match = self
::matchSpamRegex( $this->textbox1
);
1876 if ( $match !== false ) {
1877 $result['spam'] = $match;
1878 $ip = $request->getIP();
1879 $pdbk = $this->mTitle
->getPrefixedDBkey();
1880 $match = str_replace( "\n", '', $match );
1881 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1882 $status->fatal( 'spamprotectionmatch', $match );
1883 $status->value
= self
::AS_SPAM_ERROR
;
1888 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1890 # Error messages etc. could be handled within the hook...
1891 $status->fatal( 'hookaborted' );
1892 $status->value
= self
::AS_HOOK_ERROR
;
1894 } elseif ( $this->hookError
!= '' ) {
1895 # ...or the hook could be expecting us to produce an error
1896 $status->fatal( 'hookaborted' );
1897 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1901 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1902 // Auto-block user's IP if the account was "hard" blocked
1903 if ( !wfReadOnly() ) {
1904 $user->spreadAnyEditBlock();
1906 # Check block state against master, thus 'false'.
1907 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1911 $this->contentLength
= strlen( $this->textbox1
);
1912 $config = $this->context
->getConfig();
1913 $maxArticleSize = $config->get( 'MaxArticleSize' );
1914 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
1915 // Error will be displayed by showEditForm()
1916 $this->tooBig
= true;
1917 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1921 if ( !$user->isAllowed( 'edit' ) ) {
1922 if ( $user->isAnon() ) {
1923 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1926 $status->fatal( 'readonlytext' );
1927 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1932 $changingContentModel = false;
1933 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1934 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1935 $status->fatal( 'editpage-cannot-use-custom-model' );
1936 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1938 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1939 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1942 // Make sure the user can edit the page under the new content model too
1943 $titleWithNewContentModel = clone $this->mTitle
;
1944 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1945 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1946 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1948 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1952 $changingContentModel = true;
1953 $oldContentModel = $this->mTitle
->getContentModel();
1956 if ( $this->changeTags
) {
1957 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1958 $this->changeTags
, $user );
1959 if ( !$changeTagsStatus->isOK() ) {
1960 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1961 return $changeTagsStatus;
1965 if ( wfReadOnly() ) {
1966 $status->fatal( 'readonlytext' );
1967 $status->value
= self
::AS_READ_ONLY_PAGE
;
1970 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1971 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1973 $status->fatal( 'actionthrottledtext' );
1974 $status->value
= self
::AS_RATE_LIMITED
;
1978 # If the article has been deleted while editing, don't save it without
1980 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1981 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1985 # Load the page data from the master. If anything changes in the meantime,
1986 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1987 $this->page
->loadPageData( 'fromdbmaster' );
1988 $new = !$this->page
->exists();
1991 // Late check for create permission, just in case *PARANOIA*
1992 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1993 $status->fatal( 'nocreatetext' );
1994 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1995 wfDebug( __METHOD__
. ": no create permission\n" );
1999 // Don't save a new page if it's blank or if it's a MediaWiki:
2000 // message with content equivalent to default (allow empty pages
2001 // in this case to disable messages, see T52124)
2002 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2003 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
2004 $defaultText = $defaultMessageText;
2009 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
2010 $this->blankArticle
= true;
2011 $status->fatal( 'blankarticle' );
2012 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
2016 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2020 $content = $textbox_content;
2022 $result['sectionanchor'] = '';
2023 if ( $this->section
== 'new' ) {
2024 if ( $this->sectiontitle
!== '' ) {
2025 // Insert the section title above the content.
2026 $content = $content->addSectionHeader( $this->sectiontitle
);
2027 } elseif ( $this->summary
!== '' ) {
2028 // Insert the section title above the content.
2029 $content = $content->addSectionHeader( $this->summary
);
2031 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
2034 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
2038 # Article exists. Check for edit conflict.
2040 $this->page
->clear(); # Force reload of dates, etc.
2041 $timestamp = $this->page
->getTimestamp();
2042 $latest = $this->page
->getLatest();
2044 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2046 // An edit conflict is detected if the current revision is different from the
2047 // revision that was current when editing was initiated on the client.
2048 // This is checked based on the timestamp and revision ID.
2049 // TODO: the timestamp based check can probably go away now.
2050 if ( $timestamp != $this->edittime
2051 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
2053 $this->isConflict
= true;
2054 if ( $this->section
== 'new' ) {
2055 if ( $this->page
->getUserText() == $user->getName() &&
2056 $this->page
->getComment() == $this->newSectionSummary()
2058 // Probably a duplicate submission of a new comment.
2059 // This can happen when CDN resends a request after
2060 // a timeout but the first one actually went through.
2062 . ": duplicate new section submission; trigger edit conflict!\n" );
2064 // New comment; suppress conflict.
2065 $this->isConflict
= false;
2066 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
2068 } elseif ( $this->section
== ''
2069 && Revision
::userWasLastToEdit(
2070 DB_MASTER
, $this->mTitle
->getArticleID(),
2071 $user->getId(), $this->edittime
2074 # Suppress edit conflict with self, except for section edits where merging is required.
2075 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2076 $this->isConflict
= false;
2080 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2081 if ( $this->sectiontitle
!== '' ) {
2082 $sectionTitle = $this->sectiontitle
;
2084 $sectionTitle = $this->summary
;
2089 if ( $this->isConflict
) {
2091 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2092 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2093 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2094 // ...or disable section editing for non-current revisions (not exposed anyway).
2095 if ( $this->editRevId
!== null ) {
2096 $content = $this->page
->replaceSectionAtRev(
2103 $content = $this->page
->replaceSectionContent(
2111 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2112 $content = $this->page
->replaceSectionContent(
2119 if ( is_null( $content ) ) {
2120 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2121 $this->isConflict
= true;
2122 $content = $textbox_content; // do not try to merge here!
2123 } elseif ( $this->isConflict
) {
2125 if ( $this->mergeChangesIntoContent( $content ) ) {
2126 // Successful merge! Maybe we should tell the user the good news?
2127 $this->isConflict
= false;
2128 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2130 $this->section
= '';
2131 $this->textbox1
= ContentHandler
::getContentText( $content );
2132 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2136 if ( $this->isConflict
) {
2137 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2141 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2145 if ( $this->section
== 'new' ) {
2146 // Handle the user preference to force summaries here
2147 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2148 $this->missingSummary
= true;
2149 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2150 $status->value
= self
::AS_SUMMARY_NEEDED
;
2154 // Do not allow the user to post an empty comment
2155 if ( $this->textbox1
== '' ) {
2156 $this->missingComment
= true;
2157 $status->fatal( 'missingcommenttext' );
2158 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2161 } elseif ( !$this->allowBlankSummary
2162 && !$content->equals( $this->getOriginalContent( $user ) )
2163 && !$content->isRedirect()
2164 && md5( $this->summary
) == $this->autoSumm
2166 $this->missingSummary
= true;
2167 $status->fatal( 'missingsummary' );
2168 $status->value
= self
::AS_SUMMARY_NEEDED
;
2173 $sectionanchor = '';
2174 if ( $this->section
== 'new' ) {
2175 $this->summary
= $this->newSectionSummary( $sectionanchor );
2176 } elseif ( $this->section
!= '' ) {
2177 # Try to get a section anchor from the section source, redirect
2178 # to edited section if header found.
2179 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2180 # for duplicate heading checking and maybe parsing.
2181 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2182 # We can't deal with anchors, includes, html etc in the header for now,
2183 # headline would need to be parsed to improve this.
2184 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2185 $sectionanchor = $this->guessSectionName( $matches[2] );
2188 $result['sectionanchor'] = $sectionanchor;
2190 // Save errors may fall down to the edit form, but we've now
2191 // merged the section into full text. Clear the section field
2192 // so that later submission of conflict forms won't try to
2193 // replace that into a duplicated mess.
2194 $this->textbox1
= $this->toEditText( $content );
2195 $this->section
= '';
2197 $status->value
= self
::AS_SUCCESS_UPDATE
;
2200 if ( !$this->allowSelfRedirect
2201 && $content->isRedirect()
2202 && $content->getRedirectTarget()->equals( $this->getTitle() )
2204 // If the page already redirects to itself, don't warn.
2205 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2206 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2207 $this->selfRedirect
= true;
2208 $status->fatal( 'selfredirect' );
2209 $status->value
= self
::AS_SELF_REDIRECT
;
2214 // Check for length errors again now that the section is merged in
2215 $this->contentLength
= strlen( $this->toEditText( $content ) );
2216 if ( $this->contentLength
> $maxArticleSize * 1024 ) {
2217 $this->tooBig
= true;
2218 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2222 $flags = EDIT_AUTOSUMMARY |
2223 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2224 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2225 ( $bot ? EDIT_FORCE_BOT
: 0 );
2227 $doEditStatus = $this->page
->doEditContent(
2233 $content->getDefaultFormat(),
2238 if ( !$doEditStatus->isOK() ) {
2239 // Failure from doEdit()
2240 // Show the edit conflict page for certain recognized errors from doEdit(),
2241 // but don't show it for errors from extension hooks
2242 $errors = $doEditStatus->getErrorsArray();
2243 if ( in_array( $errors[0][0],
2244 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2246 $this->isConflict
= true;
2247 // Destroys data doEdit() put in $status->value but who cares
2248 $doEditStatus->value
= self
::AS_END
;
2250 return $doEditStatus;
2253 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2254 if ( $result['nullEdit'] ) {
2255 // We don't know if it was a null edit until now, so increment here
2256 $user->pingLimiter( 'linkpurge' );
2258 $result['redirect'] = $content->isRedirect();
2260 $this->updateWatchlist();
2262 // If the content model changed, add a log entry
2263 if ( $changingContentModel ) {
2264 $this->addContentModelChangeLogEntry(
2266 $new ?
false : $oldContentModel,
2267 $this->contentModel
,
2277 * @param string|false $oldModel false if the page is being newly created
2278 * @param string $newModel
2279 * @param string $reason
2281 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2282 $new = $oldModel === false;
2283 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2284 $log->setPerformer( $user );
2285 $log->setTarget( $this->mTitle
);
2286 $log->setComment( $reason );
2287 $log->setParameters( [
2288 '4::oldmodel' => $oldModel,
2289 '5::newmodel' => $newModel
2291 $logid = $log->insert();
2292 $log->publish( $logid );
2296 * Register the change of watch status
2298 protected function updateWatchlist() {
2299 $user = $this->context
->getUser();
2300 if ( !$user->isLoggedIn() ) {
2304 $title = $this->mTitle
;
2305 $watch = $this->watchthis
;
2306 // Do this in its own transaction to reduce contention...
2307 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2308 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2309 return; // nothing to change
2311 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2316 * Attempts to do 3-way merge of edit content with a base revision
2317 * and current content, in case of edit conflict, in whichever way appropriate
2318 * for the content type.
2322 * @param Content $editContent
2326 private function mergeChangesIntoContent( &$editContent ) {
2327 $db = wfGetDB( DB_MASTER
);
2329 // This is the revision that was current at the time editing was initiated on the client,
2330 // even if the edit was based on an old revision.
2331 $baseRevision = $this->getBaseRevision();
2332 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2334 if ( is_null( $baseContent ) ) {
2338 // The current state, we want to merge updates into it
2339 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2340 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2342 if ( is_null( $currentContent ) ) {
2346 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2348 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2351 $editContent = $result;
2352 // Update parentRevId to what we just merged.
2353 $this->parentRevId
= $currentRevision->getId();
2361 * Returns the revision that was current at the time editing was initiated on the client,
2362 * even if the edit was based on an old revision.
2364 * @warning: this method is very poorly named. If the user opened the form with ?oldid=X,
2365 * one might think of X as the "base revision", which is NOT what this returns,
2366 * see oldid for that. One might further assume that this corresponds to the $baseRevId
2367 * parameter of WikiPage::doEditContent, which is not the case either.
2368 * getExpectedParentRevision() would perhaps be a better name.
2370 * @return Revision|null Current version when editing was initiated on the client
2372 public function getBaseRevision() {
2373 if ( !$this->mBaseRevision
) {
2374 $db = wfGetDB( DB_MASTER
);
2375 $this->mBaseRevision
= $this->editRevId
2376 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2377 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2379 return $this->mBaseRevision
;
2383 * Check given input text against $wgSpamRegex, and return the text of the first match.
2385 * @param string $text
2387 * @return string|bool Matching string or false
2389 public static function matchSpamRegex( $text ) {
2390 global $wgSpamRegex;
2391 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2392 $regexes = (array)$wgSpamRegex;
2393 return self
::matchSpamRegexInternal( $text, $regexes );
2397 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2399 * @param string $text
2401 * @return string|bool Matching string or false
2403 public static function matchSummarySpamRegex( $text ) {
2404 global $wgSummarySpamRegex;
2405 $regexes = (array)$wgSummarySpamRegex;
2406 return self
::matchSpamRegexInternal( $text, $regexes );
2410 * @param string $text
2411 * @param array $regexes
2412 * @return bool|string
2414 protected static function matchSpamRegexInternal( $text, $regexes ) {
2415 foreach ( $regexes as $regex ) {
2417 if ( preg_match( $regex, $text, $matches ) ) {
2424 public function setHeaders() {
2425 $out = $this->context
->getOutput();
2427 $out->addModules( 'mediawiki.action.edit' );
2428 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2429 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2431 $user = $this->context
->getUser();
2432 if ( $user->getOption( 'showtoolbar' ) ) {
2433 // The addition of default buttons is handled by getEditToolbar() which
2434 // has its own dependency on this module. The call here ensures the module
2435 // is loaded in time (it has position "top") for other modules to register
2436 // buttons (e.g. extensions, gadgets, user scripts).
2437 $out->addModules( 'mediawiki.toolbar' );
2440 if ( $user->getOption( 'uselivepreview' ) ) {
2441 $out->addModules( 'mediawiki.action.edit.preview' );
2444 if ( $user->getOption( 'useeditwarning' ) ) {
2445 $out->addModules( 'mediawiki.action.edit.editWarning' );
2448 # Enabled article-related sidebar, toplinks, etc.
2449 $out->setArticleRelated( true );
2451 $contextTitle = $this->getContextTitle();
2452 if ( $this->isConflict
) {
2453 $msg = 'editconflict';
2454 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2455 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2457 $msg = $contextTitle->exists()
2458 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2459 && $contextTitle->getDefaultMessageText() !== false
2465 # Use the title defined by DISPLAYTITLE magic word when present
2466 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2467 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2468 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2469 if ( $displayTitle === false ) {
2470 $displayTitle = $contextTitle->getPrefixedText();
2472 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2474 $config = $this->context
->getConfig();
2476 # Transmit the name of the message to JavaScript for live preview
2477 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2478 $out->addJsConfigVars( [
2479 'wgEditMessage' => $msg,
2480 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2483 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2485 $out->addJsConfigVars(
2486 'wgEditSubmitButtonLabelPublish',
2487 $config->get( 'EditSubmitButtonLabelPublish' )
2492 * Show all applicable editing introductions
2494 protected function showIntro() {
2495 if ( $this->suppressIntro
) {
2499 $out = $this->context
->getOutput();
2500 $namespace = $this->mTitle
->getNamespace();
2502 if ( $namespace == NS_MEDIAWIKI
) {
2503 # Show a warning if editing an interface message
2504 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2505 # If this is a default message (but not css, json, or js),
2506 # show a hint that it is translatable on translatewiki.net
2508 !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2509 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JSON
)
2510 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2512 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2513 if ( $defaultMessageText !== false ) {
2514 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2515 'translateinterface' );
2518 } elseif ( $namespace == NS_FILE
) {
2519 # Show a hint to shared repo
2520 $file = wfFindFile( $this->mTitle
);
2521 if ( $file && !$file->isLocal() ) {
2522 $descUrl = $file->getDescriptionUrl();
2523 # there must be a description url to show a hint to shared repo
2525 if ( !$this->mTitle
->exists() ) {
2526 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2527 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2530 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2531 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2538 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2539 # Show log extract when the user is currently blocked
2540 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2541 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2542 $user = User
::newFromName( $username, false /* allow IP users */ );
2543 $ip = User
::isIP( $username );
2544 $block = Block
::newFromTarget( $user, $user );
2545 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2546 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2547 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2548 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2549 # Show log extract if the user is currently blocked
2550 LogEventsList
::showLogExtract(
2553 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2557 'showIfEmpty' => false,
2559 'blocked-notice-logextract',
2560 $user->getName() # Support GENDER in notice
2566 # Try to add a custom edit intro, or use the standard one if this is not possible.
2567 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2568 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2569 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2571 if ( $this->context
->getUser()->isLoggedIn() ) {
2573 // Suppress the external link icon, consider the help url an internal one
2574 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2582 // Suppress the external link icon, consider the help url an internal one
2583 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2585 'newarticletextanon',
2591 # Give a notice if the user is editing a deleted/moved page...
2592 if ( !$this->mTitle
->exists() ) {
2593 $dbr = wfGetDB( DB_REPLICA
);
2595 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2599 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2600 'showIfEmpty' => false,
2601 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2608 * Attempt to show a custom editing introduction, if supplied
2612 protected function showCustomIntro() {
2613 if ( $this->editintro
) {
2614 $title = Title
::newFromText( $this->editintro
);
2615 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2616 // Added using template syntax, to take <noinclude>'s into account.
2617 $this->context
->getOutput()->addWikiTextTitleTidy(
2618 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2628 * Gets an editable textual representation of $content.
2629 * The textual representation can be turned by into a Content object by the
2630 * toEditContent() method.
2632 * If $content is null or false or a string, $content is returned unchanged.
2634 * If the given Content object is not of a type that can be edited using
2635 * the text base EditPage, an exception will be raised. Set
2636 * $this->allowNonTextContent to true to allow editing of non-textual
2639 * @param Content|null|bool|string $content
2640 * @return string The editable text form of the content.
2642 * @throws MWException If $content is not an instance of TextContent and
2643 * $this->allowNonTextContent is not true.
2645 protected function toEditText( $content ) {
2646 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2650 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2651 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2654 return $content->serialize( $this->contentFormat
);
2658 * Turns the given text into a Content object by unserializing it.
2660 * If the resulting Content object is not of a type that can be edited using
2661 * the text base EditPage, an exception will be raised. Set
2662 * $this->allowNonTextContent to true to allow editing of non-textual
2665 * @param string|null|bool $text Text to unserialize
2666 * @return Content|bool|null The content object created from $text. If $text was false
2667 * or null, false resp. null will be returned instead.
2669 * @throws MWException If unserializing the text results in a Content
2670 * object that is not an instance of TextContent and
2671 * $this->allowNonTextContent is not true.
2673 protected function toEditContent( $text ) {
2674 if ( $text === false ||
$text === null ) {
2678 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2679 $this->contentModel
, $this->contentFormat
);
2681 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2682 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2689 * Send the edit form and related headers to OutputPage
2690 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2691 * during form output near the top, for captchas and the like.
2693 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2694 * use the EditPage::showEditForm:fields hook instead.
2696 public function showEditForm( $formCallback = null ) {
2697 # need to parse the preview early so that we know which templates are used,
2698 # otherwise users with "show preview after edit box" will get a blank list
2699 # we parse this near the beginning so that setHeaders can do the title
2700 # setting work instead of leaving it in getPreviewText
2701 $previewOutput = '';
2702 if ( $this->formtype
== 'preview' ) {
2703 $previewOutput = $this->getPreviewText();
2706 $out = $this->context
->getOutput();
2708 // Avoid PHP 7.1 warning of passing $this by reference
2710 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2712 $this->setHeaders();
2714 $this->addTalkPageText();
2715 $this->addEditNotices();
2717 if ( !$this->isConflict
&&
2718 $this->section
!= '' &&
2719 !$this->isSectionEditSupported() ) {
2720 // We use $this->section to much before this and getVal('wgSection') directly in other places
2721 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2722 // Someone is welcome to try refactoring though
2723 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2727 $this->showHeader();
2729 $out->addHTML( $this->editFormPageTop
);
2731 $user = $this->context
->getUser();
2732 if ( $user->getOption( 'previewontop' ) ) {
2733 $this->displayPreviewArea( $previewOutput, true );
2736 $out->addHTML( $this->editFormTextTop
);
2738 $showToolbar = true;
2739 if ( $this->wasDeletedSinceLastEdit() ) {
2740 if ( $this->formtype
== 'save' ) {
2741 // Hide the toolbar and edit area, user can click preview to get it back
2742 // Add an confirmation checkbox and explanation.
2743 $showToolbar = false;
2745 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2746 'deletedwhileediting' );
2750 // @todo add EditForm plugin interface and use it here!
2751 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2752 $out->addHTML( Html
::openElement(
2755 'class' => 'mw-editform',
2756 'id' => self
::EDITFORM_ID
,
2757 'name' => self
::EDITFORM_ID
,
2759 'action' => $this->getActionURL( $this->getContextTitle() ),
2760 'enctype' => 'multipart/form-data'
2764 if ( is_callable( $formCallback ) ) {
2765 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2766 call_user_func_array( $formCallback, [ &$out ] );
2769 // Add a check for Unicode support
2770 $out->addHTML( Html
::hidden( 'wpUnicodeCheck', self
::UNICODE_CHECK
) );
2772 // Add an empty field to trip up spambots
2774 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2777 [ 'for' => 'wpAntispam' ],
2778 $this->context
->msg( 'simpleantispam-label' )->parse()
2784 'name' => 'wpAntispam',
2785 'id' => 'wpAntispam',
2789 . Xml
::closeElement( 'div' )
2792 // Avoid PHP 7.1 warning of passing $this by reference
2794 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2796 // Put these up at the top to ensure they aren't lost on early form submission
2797 $this->showFormBeforeText();
2799 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2800 $username = $this->lastDelete
->user_name
;
2801 $comment = CommentStore
::getStore()
2802 ->getComment( 'log_comment', $this->lastDelete
)->text
;
2804 // It is better to not parse the comment at all than to have templates expanded in the middle
2805 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2806 $key = $comment === ''
2807 ?
'confirmrecreate-noreason'
2808 : 'confirmrecreate';
2810 '<div class="mw-confirm-recreate">' .
2811 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2812 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2813 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2819 # When the summary is hidden, also hide them on preview/show changes
2820 if ( $this->nosummary
) {
2821 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2824 # If a blank edit summary was previously provided, and the appropriate
2825 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2826 # user being bounced back more than once in the event that a summary
2829 # For a bit more sophisticated detection of blank summaries, hash the
2830 # automatic one and pass that in the hidden field wpAutoSummary.
2831 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2832 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2835 if ( $this->undidRev
) {
2836 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2839 if ( $this->selfRedirect
) {
2840 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2843 if ( $this->hasPresetSummary
) {
2844 // If a summary has been preset using &summary= we don't want to prompt for
2845 // a different summary. Only prompt for a summary if the summary is blanked.
2847 $this->autoSumm
= md5( '' );
2850 $autosumm = $this->autoSumm ?
: md5( $this->summary
);
2851 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2853 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2854 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2856 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2857 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2861 if ( $this->section
== 'new' ) {
2862 $this->showSummaryInput( true, $this->summary
);
2863 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2866 $out->addHTML( $this->editFormTextBeforeContent
);
2867 if ( $this->isConflict
) {
2868 // In an edit conflict, we turn textbox2 into the user's text,
2869 // and textbox1 into the stored version
2870 $this->textbox2
= $this->textbox1
;
2872 $content = $this->getCurrentContent();
2873 $this->textbox1
= $this->toEditText( $content );
2875 $editConflictHelper = $this->getEditConflictHelper();
2876 $editConflictHelper->setTextboxes( $this->textbox2
, $this->textbox1
);
2877 $editConflictHelper->setContentModel( $this->contentModel
);
2878 $editConflictHelper->setContentFormat( $this->contentFormat
);
2879 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2882 if ( !$this->mTitle
->isUserConfigPage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2883 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2886 if ( $this->blankArticle
) {
2887 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2890 if ( $this->isConflict
) {
2891 // In an edit conflict bypass the overridable content form method
2892 // and fallback to the raw wpTextbox1 since editconflicts can't be
2893 // resolved between page source edits and custom ui edits using the
2895 $conflictTextBoxAttribs = [];
2896 if ( $this->wasDeletedSinceLastEdit() ) {
2897 $conflictTextBoxAttribs['style'] = 'display:none;';
2898 } elseif ( $this->isOldRev
) {
2899 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2902 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2903 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2905 $this->showContentForm();
2908 $out->addHTML( $this->editFormTextAfterContent
);
2910 $this->showStandardInputs();
2912 $this->showFormAfterText();
2914 $this->showTosSummary();
2916 $this->showEditTools();
2918 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2920 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2922 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2923 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2925 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2926 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2928 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2930 if ( $this->isConflict
) {
2932 $this->showConflict();
2933 } catch ( MWContentSerializationException
$ex ) {
2934 // this can't really happen, but be nice if it does.
2935 $msg = $this->context
->msg(
2936 'content-failed-to-parse',
2937 $this->contentModel
,
2938 $this->contentFormat
,
2941 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2945 // Set a hidden field so JS knows what edit form mode we are in
2946 if ( $this->isConflict
) {
2948 } elseif ( $this->preview
) {
2950 } elseif ( $this->diff
) {
2955 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2957 // Marker for detecting truncated form data. This must be the last
2958 // parameter sent in order to be of use, so do not move me.
2959 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2960 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2962 if ( !$user->getOption( 'previewontop' ) ) {
2963 $this->displayPreviewArea( $previewOutput, false );
2968 * Wrapper around TemplatesOnThisPageFormatter to make
2969 * a "templates on this page" list.
2971 * @param Title[] $templates
2972 * @return string HTML
2974 public function makeTemplatesOnThisPageList( array $templates ) {
2975 $templateListFormatter = new TemplatesOnThisPageFormatter(
2976 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2979 // preview if preview, else section if section, else false
2981 if ( $this->preview
) {
2983 } elseif ( $this->section
!= '' ) {
2987 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2988 $templateListFormatter->format( $templates, $type )
2993 * Extract the section title from current section text, if any.
2995 * @param string $text
2996 * @return string|bool String or false
2998 public static function extractSectionTitle( $text ) {
2999 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
3000 if ( !empty( $matches[2] ) ) {
3002 return $wgParser->stripSectionName( trim( $matches[2] ) );
3008 protected function showHeader() {
3009 $out = $this->context
->getOutput();
3010 $user = $this->context
->getUser();
3011 if ( $this->isConflict
) {
3012 $this->addExplainConflictHeader( $out );
3013 $this->editRevId
= $this->page
->getLatest();
3015 if ( $this->section
!= '' && $this->section
!= 'new' ) {
3016 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
3017 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
3018 if ( $sectionTitle !== false ) {
3019 $this->summary
= "/* $sectionTitle */ ";
3024 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
3026 if ( $this->missingComment
) {
3027 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3030 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
3032 "<div id='mw-missingsummary'>\n$1\n</div>",
3033 [ 'missingsummary', $buttonLabel ]
3037 if ( $this->missingSummary
&& $this->section
== 'new' ) {
3039 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3040 [ 'missingcommentheader', $buttonLabel ]
3044 if ( $this->blankArticle
) {
3046 "<div id='mw-blankarticle'>\n$1\n</div>",
3047 [ 'blankarticle', $buttonLabel ]
3051 if ( $this->selfRedirect
) {
3053 "<div id='mw-selfredirect'>\n$1\n</div>",
3054 [ 'selfredirect', $buttonLabel ]
3058 if ( $this->hookError
!== '' ) {
3059 $out->addWikiText( $this->hookError
);
3062 if ( $this->section
!= 'new' ) {
3063 $revision = $this->mArticle
->getRevisionFetched();
3065 // Let sysop know that this will make private content public if saved
3067 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
3069 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3070 'rev-deleted-text-permission'
3072 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
3074 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3075 'rev-deleted-text-view'
3079 if ( !$revision->isCurrent() ) {
3080 $this->mArticle
->setOldSubtitle( $revision->getId() );
3081 $out->addWikiMsg( 'editingold' );
3082 $this->isOldRev
= true;
3084 } elseif ( $this->mTitle
->exists() ) {
3085 // Something went wrong
3087 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3088 [ 'missing-revision', $this->oldid
] );
3093 if ( wfReadOnly() ) {
3095 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3096 [ 'readonlywarning', wfReadOnlyReason() ]
3098 } elseif ( $user->isAnon() ) {
3099 if ( $this->formtype
!= 'preview' ) {
3101 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3102 [ 'anoneditwarning',
3104 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3105 'returnto' => $this->getTitle()->getPrefixedDBkey()
3108 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3109 'returnto' => $this->getTitle()->getPrefixedDBkey()
3114 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3115 'anonpreviewwarning'
3119 if ( $this->mTitle
->isUserConfigPage() ) {
3120 # Check the skin exists
3121 if ( $this->isWrongCaseUserConfigPage() ) {
3123 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3124 [ 'userinvalidconfigtitle', $this->mTitle
->getSkinFromConfigSubpage() ]
3127 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3128 $isUserCssConfig = $this->mTitle
->isUserCssConfigPage();
3129 $isUserJsonConfig = $this->mTitle
->isUserJsonConfigPage();
3130 $isUserJsConfig = $this->mTitle
->isUserJsConfigPage();
3132 $warning = $isUserCssConfig
3134 : ( $isUserJsonConfig ?
'userjsonispublic' : 'userjsispublic' );
3136 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3138 if ( $this->formtype
!== 'preview' ) {
3139 $config = $this->context
->getConfig();
3140 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3142 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3143 [ 'usercssyoucanpreview' ]
3145 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3147 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3148 [ 'userjsonyoucanpreview' ]
3150 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3152 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3153 [ 'userjsyoucanpreview' ]
3161 $this->addPageProtectionWarningHeaders();
3163 $this->addLongPageWarningHeader();
3165 # Add header copyright warning
3166 $this->showHeaderCopyrightWarning();
3170 * Helper function for summary input functions, which returns the neccessary
3171 * attributes for the input.
3173 * @param array|null $inputAttrs Array of attrs to use on the input
3176 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3177 $conf = $this->context
->getConfig();
3178 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
3179 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3180 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3181 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
3182 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3183 'id' => 'wpSummary',
3184 'name' => 'wpSummary',
3185 'maxlength' => $oldCommentSchema ?
200 : CommentStore
::COMMENT_CHARACTER_LIMIT
,
3188 'spellcheck' => 'true',
3193 * Builds a standard summary input with a label.
3195 * @param string $summary The value of the summary input
3196 * @param string|null $labelText The html to place inside the label
3197 * @param array|null $inputAttrs Array of attrs to use on the input
3199 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3201 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3202 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3203 $this->getSummaryInputAttributes( $inputAttrs )
3206 'title' => Linker
::titleAttrib( 'summary' ),
3207 'accessKey' => Linker
::accesskey( 'summary' ),
3210 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3211 $inputAttrs['inputId'] = $inputAttrs['id'];
3212 $inputAttrs['id'] = 'wpSummaryWidget';
3214 return new OOUI\
FieldLayout(
3215 new OOUI\
TextInputWidget( [
3216 'value' => $summary,
3217 'infusable' => true,
3220 'label' => new OOUI\
HtmlSnippet( $labelText ),
3222 'id' => 'wpSummaryLabel',
3223 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3229 * @param bool $isSubjectPreview True if this is the section subject/title
3230 * up top, or false if this is the comment summary
3231 * down below the textarea
3232 * @param string $summary The text of the summary to display
3234 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3235 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3236 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3237 if ( $isSubjectPreview ) {
3238 if ( $this->nosummary
) {
3242 if ( !$this->mShowSummaryField
) {
3247 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3248 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3251 [ 'class' => $summaryClass ]
3256 * @param bool $isSubjectPreview True if this is the section subject/title
3257 * up top, or false if this is the comment summary
3258 * down below the textarea
3259 * @param string $summary The text of the summary to display
3262 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3263 // avoid spaces in preview, gets always trimmed on save
3264 $summary = trim( $summary );
3265 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3271 if ( $isSubjectPreview ) {
3272 $summary = $this->context
->msg( 'newsectionsummary' )
3273 ->rawParams( $wgParser->stripSectionName( $summary ) )
3274 ->inContentLanguage()->text();
3277 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3279 $summary = $this->context
->msg( $message )->parse()
3280 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3281 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3284 protected function showFormBeforeText() {
3285 $out = $this->context
->getOutput();
3286 $out->addHTML( Html
::hidden( 'wpSection', $this->section
) );
3287 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3288 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3289 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3290 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3293 protected function showFormAfterText() {
3295 * To make it harder for someone to slip a user a page
3296 * which submits an edit form to the wiki without their
3297 * knowledge, a random token is associated with the login
3298 * session. If it's not passed back with the submission,
3299 * we won't save the page, or render user JavaScript and
3302 * For anon editors, who may not have a session, we just
3303 * include the constant suffix to prevent editing from
3304 * broken text-mangling proxies.
3306 $this->context
->getOutput()->addHTML(
3308 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3314 * Subpage overridable method for printing the form for page content editing
3315 * By default this simply outputs wpTextbox1
3316 * Subclasses can override this to provide a custom UI for editing;
3317 * be it a form, or simply wpTextbox1 with a modified content that will be
3318 * reverse modified when extracted from the post data.
3319 * Note that this is basically the inverse for importContentFormData
3321 protected function showContentForm() {
3322 $this->showTextbox1();
3326 * Method to output wpTextbox1
3327 * The $textoverride method can be used by subclasses overriding showContentForm
3328 * to pass back to this method.
3330 * @param array|null $customAttribs Array of html attributes to use in the textarea
3331 * @param string|null $textoverride Optional text to override $this->textarea1 with
3333 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3334 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3335 $attribs = [ 'style' => 'display:none;' ];
3337 $builder = new TextboxBuilder();
3338 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3340 # Is an old revision being edited?
3341 if ( $this->isOldRev
) {
3342 $classes[] = 'mw-textarea-oldrev';
3345 $attribs = [ 'tabindex' => 1 ];
3347 if ( is_array( $customAttribs ) ) {
3348 $attribs +
= $customAttribs;
3351 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3355 $textoverride ??
$this->textbox1
,
3361 protected function showTextbox2() {
3362 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3365 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3366 $builder = new TextboxBuilder();
3367 $attribs = $builder->buildTextboxAttribs(
3370 $this->context
->getUser(),
3374 $this->context
->getOutput()->addHTML(
3375 Html
::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3379 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3382 $classes[] = 'ontop';
3385 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3387 if ( $this->formtype
!= 'preview' ) {
3388 $attribs['style'] = 'display: none;';
3391 $out = $this->context
->getOutput();
3392 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3394 if ( $this->formtype
== 'preview' ) {
3395 $this->showPreview( $previewOutput );
3397 // Empty content container for LivePreview
3398 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3399 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3400 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3401 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3404 $out->addHTML( '</div>' );
3406 if ( $this->formtype
== 'diff' ) {
3409 } catch ( MWContentSerializationException
$ex ) {
3410 $msg = $this->context
->msg(
3411 'content-failed-to-parse',
3412 $this->contentModel
,
3413 $this->contentFormat
,
3416 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3422 * Append preview output to OutputPage.
3423 * Includes category rendering if this is a category page.
3425 * @param string $text The HTML to be output for the preview.
3427 protected function showPreview( $text ) {
3428 if ( $this->mArticle
instanceof CategoryPage
) {
3429 $this->mArticle
->openShowCategory();
3431 # This hook seems slightly odd here, but makes things more
3432 # consistent for extensions.
3433 $out = $this->context
->getOutput();
3434 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3435 $out->addHTML( $text );
3436 if ( $this->mArticle
instanceof CategoryPage
) {
3437 $this->mArticle
->closeShowCategory();
3442 * Get a diff between the current contents of the edit box and the
3443 * version of the page we're editing from.
3445 * If this is a section edit, we'll replace the section as for final
3446 * save and then make a comparison.
3448 public function showDiff() {
3451 $oldtitlemsg = 'currentrev';
3452 # if message does not exist, show diff against the preloaded default
3453 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3454 $oldtext = $this->mTitle
->getDefaultMessageText();
3455 if ( $oldtext !== false ) {
3456 $oldtitlemsg = 'defaultmessagetext';
3457 $oldContent = $this->toEditContent( $oldtext );
3462 $oldContent = $this->getCurrentContent();
3465 $textboxContent = $this->toEditContent( $this->textbox1
);
3466 if ( $this->editRevId
!== null ) {
3467 $newContent = $this->page
->replaceSectionAtRev(
3468 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3471 $newContent = $this->page
->replaceSectionContent(
3472 $this->section
, $textboxContent, $this->summary
, $this->edittime
3476 if ( $newContent ) {
3477 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3479 $user = $this->context
->getUser();
3480 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
3481 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3484 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3485 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3486 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3488 if ( !$oldContent ) {
3489 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3492 if ( !$newContent ) {
3493 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3496 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context
);
3497 $de->setContent( $oldContent, $newContent );
3499 $difftext = $de->getDiff( $oldtitle, $newtitle );
3500 $de->showDiffStyle();
3505 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3509 * Show the header copyright warning.
3511 protected function showHeaderCopyrightWarning() {
3512 $msg = 'editpage-head-copy-warn';
3513 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3514 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3515 'editpage-head-copy-warn' );
3520 * Give a chance for site and per-namespace customizations of
3521 * terms of service summary link that might exist separately
3522 * from the copyright notice.
3524 * This will display between the save button and the edit tools,
3525 * so should remain short!
3527 protected function showTosSummary() {
3528 $msg = 'editpage-tos-summary';
3529 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3530 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3531 $out = $this->context
->getOutput();
3532 $out->addHTML( '<div class="mw-tos-summary">' );
3533 $out->addWikiMsg( $msg );
3534 $out->addHTML( '</div>' );
3539 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3540 * characters not present on most keyboards for copying/pasting.
3542 protected function showEditTools() {
3543 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3544 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3549 * Get the copyright warning
3551 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3554 protected function getCopywarn() {
3555 return self
::getCopyrightWarning( $this->mTitle
);
3559 * Get the copyright warning, by default returns wikitext
3561 * @param Title $title
3562 * @param string $format Output format, valid values are any function of a Message object
3563 * @param Language|string|null $langcode Language code or Language object.
3566 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3567 global $wgRightsText;
3568 if ( $wgRightsText ) {
3569 $copywarnMsg = [ 'copyrightwarning',
3570 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3573 $copywarnMsg = [ 'copyrightwarning2',
3574 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3576 // Allow for site and per-namespace customization of contribution/copyright notice.
3577 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3579 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3581 $msg->inLanguage( $langcode );
3583 return "<div id=\"editpage-copywarn\">\n" .
3584 $msg->$format() . "\n</div>";
3588 * Get the Limit report for page previews
3591 * @param ParserOutput $output ParserOutput object from the parse
3592 * @return string HTML
3594 public static function getPreviewLimitReport( $output ) {
3597 if ( !$output ||
!$output->getLimitReportData() ) {
3601 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3602 wfMessage( 'limitreport-title' )->parseAsBlock()
3605 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3606 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3608 $limitReport .= Html
::openElement( 'table', [
3609 'class' => 'preview-limit-report wikitable'
3611 Html
::openElement( 'tbody' );
3613 foreach ( $output->getLimitReportData() as $key => $value ) {
3614 if ( Hooks
::run( 'ParserLimitReportFormat',
3615 [ $key, &$value, &$limitReport, true, true ]
3617 $keyMsg = wfMessage( $key );
3618 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3619 if ( !$valueMsg->exists() ) {
3620 $valueMsg = new RawMessage( '$1' );
3622 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3623 $limitReport .= Html
::openElement( 'tr' ) .
3624 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3625 Html
::rawElement( 'td', null,
3626 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3628 Html
::closeElement( 'tr' );
3633 $limitReport .= Html
::closeElement( 'tbody' ) .
3634 Html
::closeElement( 'table' ) .
3635 Html
::closeElement( 'div' );
3637 return $limitReport;
3640 protected function showStandardInputs( &$tabindex = 2 ) {
3641 $out = $this->context
->getOutput();
3642 $out->addHTML( "<div class='editOptions'>\n" );
3644 if ( $this->section
!= 'new' ) {
3645 $this->showSummaryInput( false, $this->summary
);
3646 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3649 $checkboxes = $this->getCheckboxesWidget(
3651 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3653 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3655 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3657 // Show copyright warning.
3658 $out->addWikiText( $this->getCopywarn() );
3659 $out->addHTML( $this->editFormTextAfterWarn
);
3661 $out->addHTML( "<div class='editButtons'>\n" );
3662 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3664 $cancel = $this->getCancelLink();
3666 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3667 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3670 $this->context
->msg( 'edithelp' )->text(),
3671 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3674 $this->context
->msg( 'word-separator' )->escaped() .
3675 $this->context
->msg( 'newwindow' )->parse();
3677 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3678 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3679 $out->addHTML( "</div><!-- editButtons -->\n" );
3681 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3683 $out->addHTML( "</div><!-- editOptions -->\n" );
3687 * Show an edit conflict. textbox1 is already shown in showEditForm().
3688 * If you want to use another entry point to this function, be careful.
3690 protected function showConflict() {
3691 $out = $this->context
->getOutput();
3692 // Avoid PHP 7.1 warning of passing $this by reference
3694 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3695 $this->incrementConflictStats();
3697 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3701 protected function incrementConflictStats() {
3702 $this->getEditConflictHelper()->incrementConflictStats();
3708 public function getCancelLink() {
3710 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3711 $cancelParams['oldid'] = $this->oldid
;
3712 } elseif ( $this->getContextTitle()->isRedirect() ) {
3713 $cancelParams['redirect'] = 'no';
3716 return new OOUI\
ButtonWidget( [
3717 'id' => 'mw-editform-cancel',
3718 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3719 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3721 'infusable' => true,
3722 'flags' => 'destructive',
3727 * Returns the URL to use in the form's action attribute.
3728 * This is used by EditPage subclasses when simply customizing the action
3729 * variable in the constructor is not enough. This can be used when the
3730 * EditPage lives inside of a Special page rather than a custom page action.
3732 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3735 protected function getActionURL( Title
$title ) {
3736 return $title->getLocalURL( [ 'action' => $this->action
] );
3740 * Check if a page was deleted while the user was editing it, before submit.
3741 * Note that we rely on the logging table, which hasn't been always there,
3742 * but that doesn't matter, because this only applies to brand new
3746 protected function wasDeletedSinceLastEdit() {
3747 if ( $this->deletedSinceEdit
!== null ) {
3748 return $this->deletedSinceEdit
;
3751 $this->deletedSinceEdit
= false;
3753 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3754 $this->lastDelete
= $this->getLastDelete();
3755 if ( $this->lastDelete
) {
3756 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3757 if ( $deleteTime > $this->starttime
) {
3758 $this->deletedSinceEdit
= true;
3763 return $this->deletedSinceEdit
;
3767 * @return bool|stdClass
3769 protected function getLastDelete() {
3770 $dbr = wfGetDB( DB_REPLICA
);
3771 $commentQuery = CommentStore
::getStore()->getJoin( 'log_comment' );
3772 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
3773 $data = $dbr->selectRow(
3774 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3784 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
3786 'log_namespace' => $this->mTitle
->getNamespace(),
3787 'log_title' => $this->mTitle
->getDBkey(),
3788 'log_type' => 'delete',
3789 'log_action' => 'delete',
3792 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3794 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3795 ] +
$commentQuery['joins'] +
$actorQuery['joins']
3797 // Quick paranoid permission checks...
3798 if ( is_object( $data ) ) {
3799 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3800 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3803 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3804 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3805 $data->log_comment_data
= null;
3813 * Get the rendered text for previewing.
3814 * @throws MWException
3817 public function getPreviewText() {
3818 $out = $this->context
->getOutput();
3819 $config = $this->context
->getConfig();
3821 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk
) {
3822 // Could be an offsite preview attempt. This is very unsafe if
3823 // HTML is enabled, as it could be an attack.
3825 if ( $this->textbox1
!== '' ) {
3826 // Do not put big scary notice, if previewing the empty
3827 // string, which happens when you initially edit
3828 // a category page, due to automatic preview-on-open.
3829 $parsedNote = $out->parse( "<div class='previewnote'>" .
3830 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3831 true, /* interface */true );
3833 $this->incrementEditFailureStats( 'session_loss' );
3840 $content = $this->toEditContent( $this->textbox1
);
3844 'AlternateEditPreview',
3845 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3847 return $previewHTML;
3850 # provide a anchor link to the editform
3851 $continueEditing = '<span class="mw-continue-editing">' .
3852 '[[#' . self
::EDITFORM_ID
. '|' .
3853 $this->context
->getLanguage()->getArrow() . ' ' .
3854 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3855 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3856 if ( $this->mTokenOkExceptSuffix
) {
3857 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3858 $this->incrementEditFailureStats( 'bad_token' );
3860 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3861 $this->incrementEditFailureStats( 'session_loss' );
3863 } elseif ( $this->incompleteForm
) {
3864 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3865 if ( $this->mTriedSave
) {
3866 $this->incrementEditFailureStats( 'incomplete_form' );
3869 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3872 # don't parse non-wikitext pages, show message about preview
3873 if ( $this->mTitle
->isUserConfigPage() ||
$this->mTitle
->isSiteConfigPage() ) {
3874 if ( $this->mTitle
->isUserConfigPage() ) {
3876 } elseif ( $this->mTitle
->isSiteConfigPage() ) {
3882 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3884 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3887 } elseif ( $content->getModel() == CONTENT_MODEL_JSON
) {
3889 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3892 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3894 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3901 # Used messages to make sure grep find them:
3902 # Messages: usercsspreview, userjsonpreview, userjspreview,
3903 # sitecsspreview, sitejsonpreview, sitejspreview
3904 if ( $level && $format ) {
3905 $note = "<div id='mw-{$level}{$format}preview'>" .
3906 $this->context
->msg( "{$level}{$format}preview" )->text() .
3907 ' ' . $continueEditing . "</div>";
3911 # If we're adding a comment, we need to show the
3912 # summary as the headline
3913 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3914 $content = $content->addSectionHeader( $this->summary
);
3917 $hook_args = [ $this, &$content ];
3918 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3920 $parserResult = $this->doPreviewParse( $content );
3921 $parserOutput = $parserResult['parserOutput'];
3922 $previewHTML = $parserResult['html'];
3923 $this->mParserOutput
= $parserOutput;
3924 $out->addParserOutputMetadata( $parserOutput );
3925 if ( $out->userCanPreview() ) {
3926 $out->addContentOverride( $this->getTitle(), $content );
3929 if ( count( $parserOutput->getWarnings() ) ) {
3930 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3933 } catch ( MWContentSerializationException
$ex ) {
3934 $m = $this->context
->msg(
3935 'content-failed-to-parse',
3936 $this->contentModel
,
3937 $this->contentFormat
,
3940 $note .= "\n\n" . $m->parse();
3944 if ( $this->isConflict
) {
3945 $conflict = '<h2 id="mw-previewconflict">'
3946 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3948 $conflict = '<hr />';
3951 $previewhead = "<div class='previewnote'>\n" .
3952 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3953 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3955 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3956 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3957 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3958 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3960 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3963 private function incrementEditFailureStats( $failureType ) {
3964 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3965 $stats->increment( 'edit.failures.' . $failureType );
3969 * Get parser options for a preview
3970 * @return ParserOptions
3972 protected function getPreviewParserOptions() {
3973 $parserOptions = $this->page
->makeParserOptions( $this->context
);
3974 $parserOptions->setIsPreview( true );
3975 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3976 $parserOptions->enableLimitReport();
3977 return $parserOptions;
3981 * Parse the page for a preview. Subclasses may override this class, in order
3982 * to parse with different options, or to otherwise modify the preview HTML.
3984 * @param Content $content The page content
3985 * @return array with keys:
3986 * - parserOutput: The ParserOutput object
3987 * - html: The HTML to be displayed
3989 protected function doPreviewParse( Content
$content ) {
3990 $user = $this->context
->getUser();
3991 $parserOptions = $this->getPreviewParserOptions();
3992 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
3993 $scopedCallback = $parserOptions->setupFakeRevision(
3994 $this->mTitle
, $pstContent, $user );
3995 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3996 ScopedCallback
::consume( $scopedCallback );
3998 'parserOutput' => $parserOutput,
3999 'html' => $parserOutput->getText( [
4000 'enableSectionEditLinks' => false
4008 public function getTemplates() {
4009 if ( $this->preview ||
$this->section
!= '' ) {
4011 if ( !isset( $this->mParserOutput
) ) {
4014 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
4015 foreach ( array_keys( $template ) as $dbk ) {
4016 $templates[] = Title
::makeTitle( $ns, $dbk );
4021 return $this->mTitle
->getTemplateLinksFrom();
4026 * Shows a bulletin board style toolbar for common editing functions.
4027 * It can be disabled in the user preferences.
4029 * @param Title|null $title Title object for the page being edited (optional)
4032 public static function getEditToolbar( $title = null ) {
4033 global $wgContLang, $wgOut;
4034 global $wgEnableUploads, $wgForeignFileRepos;
4036 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
4037 $showSignature = true;
4039 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4043 * $toolarray is an array of arrays each of which includes the
4044 * opening tag, the closing tag, optionally a sample text that is
4045 * inserted between the two when no selection is highlighted
4046 * and. The tip text is shown when the user moves the mouse
4049 * Images are defined in ResourceLoaderEditToolbarModule.
4053 'id' => 'mw-editbutton-bold',
4055 'close' => '\'\'\'',
4056 'sample' => wfMessage( 'bold_sample' )->text(),
4057 'tip' => wfMessage( 'bold_tip' )->text(),
4060 'id' => 'mw-editbutton-italic',
4063 'sample' => wfMessage( 'italic_sample' )->text(),
4064 'tip' => wfMessage( 'italic_tip' )->text(),
4067 'id' => 'mw-editbutton-link',
4070 'sample' => wfMessage( 'link_sample' )->text(),
4071 'tip' => wfMessage( 'link_tip' )->text(),
4074 'id' => 'mw-editbutton-extlink',
4077 'sample' => wfMessage( 'extlink_sample' )->text(),
4078 'tip' => wfMessage( 'extlink_tip' )->text(),
4081 'id' => 'mw-editbutton-headline',
4084 'sample' => wfMessage( 'headline_sample' )->text(),
4085 'tip' => wfMessage( 'headline_tip' )->text(),
4087 $imagesAvailable ?
[
4088 'id' => 'mw-editbutton-image',
4089 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4091 'sample' => wfMessage( 'image_sample' )->text(),
4092 'tip' => wfMessage( 'image_tip' )->text(),
4094 $imagesAvailable ?
[
4095 'id' => 'mw-editbutton-media',
4096 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4098 'sample' => wfMessage( 'media_sample' )->text(),
4099 'tip' => wfMessage( 'media_tip' )->text(),
4102 'id' => 'mw-editbutton-nowiki',
4103 'open' => "<nowiki>",
4104 'close' => "</nowiki>",
4105 'sample' => wfMessage( 'nowiki_sample' )->text(),
4106 'tip' => wfMessage( 'nowiki_tip' )->text(),
4109 'id' => 'mw-editbutton-signature',
4110 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4113 'tip' => wfMessage( 'sig_tip' )->text(),
4116 'id' => 'mw-editbutton-hr',
4117 'open' => "\n----\n",
4120 'tip' => wfMessage( 'hr_tip' )->text(),
4124 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4125 foreach ( $toolarray as $tool ) {
4131 // Images are defined in ResourceLoaderEditToolbarModule
4133 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4134 // Older browsers show a "speedtip" type message only for ALT.
4135 // Ideally these should be different, realistically they
4136 // probably don't need to be.
4144 $script .= Xml
::encodeJsCall(
4145 'mw.toolbar.addButton',
4147 ResourceLoader
::inDebugMode()
4153 $toolbar = '<div id="toolbar"></div>';
4155 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4156 // Only add the old toolbar cruft to the page payload if the toolbar has not
4157 // been over-written by a hook caller
4158 $nonce = $wgOut->getCSPNonce();
4159 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script, $nonce ) );
4166 * Return an array of checkbox definitions.
4168 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4170 * Array values are associative arrays with the following keys:
4171 * - 'label-message' (required): message for label text
4172 * - 'id' (required): 'id' attribute for the `<input>`
4173 * - 'default' (required): default checkedness (true or false)
4174 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4175 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4176 * from messages like 'tooltip-foo', 'accesskey-foo'
4177 * - 'label-id' (optional): 'id' attribute for the `<label>`
4178 * - 'legacy-name' (optional): short name for backwards-compatibility
4179 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4180 * where bool indicates the checked status of the checkbox
4183 public function getCheckboxesDefinition( $checked ) {
4186 $user = $this->context
->getUser();
4187 // don't show the minor edit checkbox if it's a new page or section
4188 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4189 $checkboxes['wpMinoredit'] = [
4190 'id' => 'wpMinoredit',
4191 'label-message' => 'minoredit',
4192 // Uses messages: tooltip-minoredit, accesskey-minoredit
4193 'tooltip' => 'minoredit',
4194 'label-id' => 'mw-editpage-minoredit',
4195 'legacy-name' => 'minor',
4196 'default' => $checked['minor'],
4200 if ( $user->isLoggedIn() ) {
4201 $checkboxes['wpWatchthis'] = [
4202 'id' => 'wpWatchthis',
4203 'label-message' => 'watchthis',
4204 // Uses messages: tooltip-watch, accesskey-watch
4205 'tooltip' => 'watch',
4206 'label-id' => 'mw-editpage-watch',
4207 'legacy-name' => 'watch',
4208 'default' => $checked['watch'],
4213 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4219 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4220 * any other added by extensions.
4222 * @param int &$tabindex Current tabindex
4223 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4224 * status of the checkbox
4226 * @return array Associative array of string keys to OOUI\FieldLayout instances
4228 public function getCheckboxesWidget( &$tabindex, $checked ) {
4230 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4232 foreach ( $checkboxesDef as $name => $options ) {
4233 $legacyName = $options['legacy-name'] ??
$name;
4237 if ( isset( $options['tooltip'] ) ) {
4238 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4239 $title = Linker
::titleAttrib( $options['tooltip'] );
4241 if ( isset( $options['title-message'] ) ) {
4242 $title = $this->context
->msg( $options['title-message'] )->text();
4245 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4246 new OOUI\
CheckboxInputWidget( [
4247 'tabIndex' => ++
$tabindex,
4248 'accessKey' => $accesskey,
4249 'id' => $options['id'] . 'Widget',
4250 'inputId' => $options['id'],
4252 'selected' => $options['default'],
4253 'infusable' => true,
4256 'align' => 'inline',
4257 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4259 'id' => $options['label-id'] ??
null,
4268 * Get the message key of the label for the button to save the page
4273 protected function getSubmitButtonLabel() {
4275 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4277 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4278 $newPage = !$this->mTitle
->exists();
4280 if ( $labelAsPublish ) {
4281 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4283 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4286 return $buttonLabelKey;
4290 * Returns an array of html code of the following buttons:
4291 * save, diff and preview
4293 * @param int &$tabindex Current tabindex
4297 public function getEditButtons( &$tabindex ) {
4301 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4303 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4304 $buttonTooltip = $labelAsPublish ?
'publish' : 'save';
4306 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4308 'tabIndex' => ++
$tabindex,
4309 'id' => 'wpSaveWidget',
4310 'inputId' => 'wpSave',
4311 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4312 'useInputTag' => true,
4313 'flags' => [ 'progressive', 'primary' ],
4314 'label' => $buttonLabel,
4315 'infusable' => true,
4317 // Messages used: tooltip-save, tooltip-publish
4318 'title' => Linker
::titleAttrib( $buttonTooltip ),
4319 // Messages used: accesskey-save, accesskey-publish
4320 'accessKey' => Linker
::accesskey( $buttonTooltip ),
4323 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4324 'name' => 'wpPreview',
4325 'tabIndex' => ++
$tabindex,
4326 'id' => 'wpPreviewWidget',
4327 'inputId' => 'wpPreview',
4328 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4329 'useInputTag' => true,
4330 'label' => $this->context
->msg( 'showpreview' )->text(),
4331 'infusable' => true,
4333 // Message used: tooltip-preview
4334 'title' => Linker
::titleAttrib( 'preview' ),
4335 // Message used: accesskey-preview
4336 'accessKey' => Linker
::accesskey( 'preview' ),
4339 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4341 'tabIndex' => ++
$tabindex,
4342 'id' => 'wpDiffWidget',
4343 'inputId' => 'wpDiff',
4344 // Support: IE 6 βΒ Use <input>, otherwise it can't distinguish which button was clicked
4345 'useInputTag' => true,
4346 'label' => $this->context
->msg( 'showdiff' )->text(),
4347 'infusable' => true,
4349 // Message used: tooltip-diff
4350 'title' => Linker
::titleAttrib( 'diff' ),
4351 // Message used: accesskey-diff
4352 'accessKey' => Linker
::accesskey( 'diff' ),
4355 // Avoid PHP 7.1 warning of passing $this by reference
4357 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4363 * Creates a basic error page which informs the user that
4364 * they have attempted to edit a nonexistent section.
4366 public function noSuchSectionPage() {
4367 $out = $this->context
->getOutput();
4368 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4370 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4372 // Avoid PHP 7.1 warning of passing $this by reference
4374 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4375 $out->addHTML( $res );
4377 $out->returnToMain( false, $this->mTitle
);
4381 * Show "your edit contains spam" page with your diff and text
4383 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4385 public function spamPageWithContent( $match = false ) {
4386 $this->textbox2
= $this->textbox1
;
4388 if ( is_array( $match ) ) {
4389 $match = $this->context
->getLanguage()->listToText( $match );
4391 $out = $this->context
->getOutput();
4392 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4394 $out->addHTML( '<div id="spamprotected">' );
4395 $out->addWikiMsg( 'spamprotectiontext' );
4397 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4399 $out->addHTML( '</div>' );
4401 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4404 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4405 $this->showTextbox2();
4407 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4411 * Filter an input field through a Unicode de-armoring process if it
4412 * came from an old browser with known broken Unicode editing issues.
4414 * @deprecated since 1.30, does nothing
4416 * @param WebRequest $request
4417 * @param string $field
4420 protected function safeUnicodeInput( $request, $field ) {
4421 return rtrim( $request->getText( $field ) );
4425 * Filter an output field through a Unicode armoring process if it is
4426 * going to an old browser with known broken Unicode editing issues.
4428 * @deprecated since 1.30, does nothing
4430 * @param string $text
4433 protected function safeUnicodeOutput( $text ) {
4440 protected function addEditNotices() {
4441 $out = $this->context
->getOutput();
4442 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4443 if ( count( $editNotices ) ) {
4444 $out->addHTML( implode( "\n", $editNotices ) );
4446 $msg = $this->context
->msg( 'editnotice-notext' );
4447 if ( !$msg->isDisabled() ) {
4449 '<div class="mw-editnotice-notext">'
4450 . $msg->parseAsBlock()
4460 protected function addTalkPageText() {
4461 if ( $this->mTitle
->isTalkPage() ) {
4462 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4469 protected function addLongPageWarningHeader() {
4470 if ( $this->contentLength
=== false ) {
4471 $this->contentLength
= strlen( $this->textbox1
);
4474 $out = $this->context
->getOutput();
4475 $lang = $this->context
->getLanguage();
4476 $maxArticleSize = $this->context
->getConfig()->get( 'MaxArticleSize' );
4477 if ( $this->tooBig ||
$this->contentLength
> $maxArticleSize * 1024 ) {
4478 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4481 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4482 $lang->formatNum( $maxArticleSize )
4486 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4487 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4490 $lang->formatSize( strlen( $this->textbox1
) ),
4491 strlen( $this->textbox1
)
4501 protected function addPageProtectionWarningHeaders() {
4502 $out = $this->context
->getOutput();
4503 if ( $this->mTitle
->isProtected( 'edit' ) &&
4504 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4506 # Is the title semi-protected?
4507 if ( $this->mTitle
->isSemiProtected() ) {
4508 $noticeMsg = 'semiprotectedpagewarning';
4510 # Then it must be protected based on static groups (regular)
4511 $noticeMsg = 'protectedpagewarning';
4513 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4514 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4516 if ( $this->mTitle
->isCascadeProtected() ) {
4517 # Is this page under cascading protection from some source pages?
4518 /** @var Title[] $cascadeSources */
4519 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4520 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4521 $cascadeSourcesCount = count( $cascadeSources );
4522 if ( $cascadeSourcesCount > 0 ) {
4523 # Explain, and list the titles responsible
4524 foreach ( $cascadeSources as $page ) {
4525 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4528 $notice .= '</div>';
4529 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4531 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4532 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4534 'showIfEmpty' => false,
4535 'msgKey' => [ 'titleprotectedwarning' ],
4536 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4541 * @param OutputPage $out
4544 protected function addExplainConflictHeader( OutputPage
$out ) {
4546 $this->getEditConflictHelper()->getExplainHeader()
4551 * @param string $name
4552 * @param mixed[] $customAttribs
4557 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4558 return ( new TextboxBuilder() )->buildTextboxAttribs(
4559 $name, $customAttribs, $user, $this->mTitle
4564 * @param string $wikitext
4568 protected function addNewLineAtEnd( $wikitext ) {
4569 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4573 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4574 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4575 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4576 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4577 * spread the new style links more efficiently.
4579 * @param string $text
4582 private function guessSectionName( $text ) {
4585 // Detect Microsoft browsers
4586 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4587 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4588 // ...and redirect them to legacy encoding, if available
4589 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4591 // Meanwhile, real browsers get real anchors
4592 return $wgParser->guessSectionNameFromWikiText( $text );
4596 * Set a factory function to create an EditConflictHelper
4598 * @param callable $factory Factory function
4601 public function setEditConflictHelperFactory( callable
$factory ) {
4602 $this->editConflictHelperFactory
= $factory;
4603 $this->editConflictHelper
= null;
4607 * @return TextConflictHelper
4609 private function getEditConflictHelper() {
4610 if ( !$this->editConflictHelper
) {
4611 $this->editConflictHelper
= call_user_func(
4612 $this->editConflictHelperFactory
,
4613 $this->getSubmitButtonLabel()
4617 return $this->editConflictHelper
;
4621 * @param string $submitButtonLabel
4622 * @return TextConflictHelper
4624 private function newTextConflictHelper( $submitButtonLabel ) {
4625 return new TextConflictHelper(
4627 $this->getContext()->getOutput(),
4628 MediaWikiServices
::getInstance()->getStatsdDataFactory(),