3 * User interface for page editing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\ScopedCallback
;
28 * The edit page/HTML interface (split from Article)
29 * The actual database and text munging is still in Article,
30 * but it should get easier to call those from alternate
33 * EditPage cares about two distinct titles:
34 * $this->mContextTitle is the page that forms submit to, links point to,
35 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
36 * page in the database that is actually being edited. These are
37 * usually the same, but they are now allowed to be different.
39 * Surgeon General's Warning: prolonged exposure to this class is known to cause
40 * headaches, which may be fatal.
44 * Status: Article successfully updated
46 const AS_SUCCESS_UPDATE
= 200;
49 * Status: Article successfully created
51 const AS_SUCCESS_NEW_ARTICLE
= 201;
54 * Status: Article update aborted by a hook function
56 const AS_HOOK_ERROR
= 210;
59 * Status: A hook function returned an error
61 const AS_HOOK_ERROR_EXPECTED
= 212;
64 * Status: User is blocked from editing this page
66 const AS_BLOCKED_PAGE_FOR_USER
= 215;
69 * Status: Content too big (> $wgMaxArticleSize)
71 const AS_CONTENT_TOO_BIG
= 216;
74 * Status: this anonymous user is not allowed to edit this page
76 const AS_READ_ONLY_PAGE_ANON
= 218;
79 * Status: this logged in user is not allowed to edit this page
81 const AS_READ_ONLY_PAGE_LOGGED
= 219;
84 * Status: wiki is in readonly mode (wfReadOnly() == true)
86 const AS_READ_ONLY_PAGE
= 220;
89 * Status: rate limiter for action 'edit' was tripped
91 const AS_RATE_LIMITED
= 221;
94 * Status: article was deleted while editing and param wpRecreate == false or form
97 const AS_ARTICLE_WAS_DELETED
= 222;
100 * Status: user tried to create this page, but is not allowed to do that
101 * ( Title->userCan('create') == false )
103 const AS_NO_CREATE_PERMISSION
= 223;
106 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
108 const AS_BLANK_ARTICLE
= 224;
111 * Status: (non-resolvable) edit conflict
113 const AS_CONFLICT_DETECTED
= 225;
116 * Status: no edit summary given and the user has forceeditsummary set and the user is not
117 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
119 const AS_SUMMARY_NEEDED
= 226;
122 * Status: user tried to create a new section without content
124 const AS_TEXTBOX_EMPTY
= 228;
127 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
129 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
132 * Status: WikiPage::doEdit() was unsuccessful
137 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
139 const AS_SPAM_ERROR
= 232;
142 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
144 const AS_IMAGE_REDIRECT_ANON
= 233;
147 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
149 const AS_IMAGE_REDIRECT_LOGGED
= 234;
152 * Status: user tried to modify the content model, but is not allowed to do that
153 * ( User::isAllowed('editcontentmodel') == false )
155 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
158 * Status: user tried to create self-redirect (redirect to the same article) and
159 * wpIgnoreSelfRedirect == false
161 const AS_SELF_REDIRECT
= 236;
164 * Status: an error relating to change tagging. Look at the message key for
167 const AS_CHANGE_TAG_ERROR
= 237;
170 * Status: can't parse content
172 const AS_PARSE_ERROR
= 240;
175 * Status: when changing the content model is disallowed due to
176 * $wgContentHandlerUseDB being false
178 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
181 * HTML id and name for the beginning of the edit form.
183 const EDITFORM_ID
= 'editform';
186 * Prefix of key for cookie used to pass post-edit state.
187 * The revision id edited is added after this
189 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
192 * Duration of PostEdit cookie, in seconds.
193 * The cookie will be removed instantly if the JavaScript runs.
195 * Otherwise, though, we don't want the cookies to accumulate.
196 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
197 * limit of only 20 cookies per domain. This still applies at least to some
198 * versions of IE without full updates:
199 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
201 * A value of 20 minutes should be enough to take into account slow loads and minor
202 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
204 const POST_EDIT_COOKIE_DURATION
= 1200;
214 /** @var null|Title */
215 private $mContextTitle = null;
218 public $action = 'submit';
221 public $isConflict = false;
224 public $isCssJsSubpage = false;
227 public $isCssSubpage = false;
230 public $isJsSubpage = false;
233 public $isWrongCaseCssJsPage = false;
235 /** @var bool New page or new section */
236 public $isNew = false;
239 public $deletedSinceEdit;
247 /** @var bool|stdClass */
251 public $mTokenOk = false;
254 public $mTokenOkExceptSuffix = false;
257 public $mTriedSave = false;
260 public $incompleteForm = false;
263 public $tooBig = false;
266 public $missingComment = false;
269 public $missingSummary = false;
272 public $allowBlankSummary = false;
275 protected $blankArticle = false;
278 protected $allowBlankArticle = false;
281 protected $selfRedirect = false;
284 protected $allowSelfRedirect = false;
287 public $autoSumm = '';
290 public $hookError = '';
292 /** @var ParserOutput */
293 public $mParserOutput;
295 /** @var bool Has a summary been preset using GET parameter &summary= ? */
296 public $hasPresetSummary = false;
298 /** @var Revision|bool */
299 public $mBaseRevision = false;
302 public $mShowSummaryField = true;
307 public $save = false;
310 public $preview = false;
313 public $diff = false;
316 public $minoredit = false;
319 public $watchthis = false;
322 public $recreate = false;
325 public $textbox1 = '';
328 public $textbox2 = '';
331 public $summary = '';
334 public $nosummary = false;
337 public $edittime = '';
340 private $editRevId = null;
343 public $section = '';
346 public $sectiontitle = '';
349 public $starttime = '';
355 public $parentRevId = 0;
358 public $editintro = '';
361 public $scrolltop = null;
367 public $contentModel;
369 /** @var null|string */
370 public $contentFormat = null;
372 /** @var null|array */
373 private $changeTags = null;
375 # Placeholders for text injection by hooks (must be HTML)
376 # extensions should take care to _append_ to the present value
378 /** @var string Before even the preview */
379 public $editFormPageTop = '';
380 public $editFormTextTop = '';
381 public $editFormTextBeforeContent = '';
382 public $editFormTextAfterWarn = '';
383 public $editFormTextAfterTools = '';
384 public $editFormTextBottom = '';
385 public $editFormTextAfterContent = '';
386 public $previewTextAfterContent = '';
387 public $mPreloadContent = null;
389 /* $didSave should be set to true whenever an article was successfully altered. */
390 public $didSave = false;
391 public $undidRev = 0;
393 public $suppressIntro = false;
399 protected $contentLength = false;
402 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
404 private $enableApiEditOverride = false;
407 * @var IContextSource
412 * @var bool Whether an old revision is edited
414 private $isOldRev = false;
417 * @param Article $article
419 public function __construct( Article
$article ) {
420 $this->mArticle
= $article;
421 $this->page
= $article->getPage(); // model object
422 $this->mTitle
= $article->getTitle();
423 $this->context
= $article->getContext();
425 $this->contentModel
= $this->mTitle
->getContentModel();
427 $handler = ContentHandler
::getForModelID( $this->contentModel
);
428 $this->contentFormat
= $handler->getDefaultFormat();
434 public function getArticle() {
435 return $this->mArticle
;
440 * @return IContextSource
442 public function getContext() {
443 return $this->context
;
450 public function getTitle() {
451 return $this->mTitle
;
455 * Set the context Title object
457 * @param Title|null $title Title object or null
459 public function setContextTitle( $title ) {
460 $this->mContextTitle
= $title;
464 * Get the context title object.
465 * If not set, $wgTitle will be returned. This behavior might change in
466 * the future to return $this->mTitle instead.
470 public function getContextTitle() {
471 if ( is_null( $this->mContextTitle
) ) {
475 return $this->mContextTitle
;
480 * Check if the edit page is using OOUI controls
481 * @return bool Always true
482 * @deprecated since 1.30
484 public function isOouiEnabled() {
489 * Returns if the given content model is editable.
491 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
493 * @throws MWException If $modelId has no known handler
495 public function isSupportedContentModel( $modelId ) {
496 return $this->enableApiEditOverride
=== true ||
497 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
501 * Allow editing of content that supports API direct editing, but not general
502 * direct editing. Set to false by default.
504 * @param bool $enableOverride
506 public function setApiEditOverride( $enableOverride ) {
507 $this->enableApiEditOverride
= $enableOverride;
511 * @deprecated since 1.29, call edit directly
513 public function submit() {
514 wfDeprecated( __METHOD__
, '1.29' );
519 * This is the function that gets called for "action=edit". It
520 * sets up various member variables, then passes execution to
521 * another function, usually showEditForm()
523 * The edit form is self-submitting, so that when things like
524 * preview and edit conflicts occur, we get the same form back
525 * with the extra stuff added. Only when the final submission
526 * is made and all is well do we actually save and redirect to
527 * the newly-edited page.
529 public function edit() {
531 // Allow extensions to modify/prevent this form or submission
532 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
536 wfDebug( __METHOD__
. ": enter\n" );
538 // If they used redlink=1 and the page exists, redirect to the main article
539 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
540 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
544 $this->importFormData( $wgRequest );
545 $this->firsttime
= false;
547 if ( wfReadOnly() && $this->save
) {
550 $this->preview
= true;
554 $this->formtype
= 'save';
555 } elseif ( $this->preview
) {
556 $this->formtype
= 'preview';
557 } elseif ( $this->diff
) {
558 $this->formtype
= 'diff';
559 } else { # First time through
560 $this->firsttime
= true;
561 if ( $this->previewOnOpen() ) {
562 $this->formtype
= 'preview';
564 $this->formtype
= 'initial';
568 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
570 wfDebug( __METHOD__
. ": User can't edit\n" );
571 // Auto-block user's IP if the account was "hard" blocked
572 if ( !wfReadOnly() ) {
573 DeferredUpdates
::addCallableUpdate( function () {
574 $this->context
->getUser()->spreadAnyEditBlock();
577 $this->displayPermissionsError( $permErrors );
582 $revision = $this->mArticle
->getRevisionFetched();
583 // Disallow editing revisions with content models different from the current one
584 // Undo edits being an exception in order to allow reverting content model changes.
586 && $revision->getContentModel() !== $this->contentModel
589 if ( $this->undidRev
) {
590 $undidRevObj = Revision
::newFromId( $this->undidRev
);
591 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
593 if ( !$this->undidRev
595 ||
$prevRev->getContentModel() !== $this->contentModel
597 $this->displayViewSourcePage(
598 $this->getContentObject(),
600 'contentmodelediterror',
601 $revision->getContentModel(),
609 $this->isConflict
= false;
610 // css / js subpages of user pages get a special treatment
611 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
612 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
613 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
614 // @todo FIXME: Silly assignment.
615 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
617 # Show applicable editing introductions
618 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
622 # Attempt submission here. This will check for edit conflicts,
623 # and redundantly check for locked database, blocked IPs, etc.
624 # that edit() already checked just in case someone tries to sneak
625 # in the back door with a hand-edited submission URL.
627 if ( 'save' == $this->formtype
) {
628 $resultDetails = null;
629 $status = $this->attemptSave( $resultDetails );
630 if ( !$this->handleStatus( $status, $resultDetails ) ) {
635 # First time through: get contents, set time for conflict
637 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
638 if ( $this->initialiseForm() === false ) {
639 $this->noSuchSectionPage();
643 if ( !$this->mTitle
->getArticleID() ) {
644 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
646 Hooks
::run( 'EditFormInitialText', [ $this ] );
651 $this->showEditForm();
655 * @param string $rigor Same format as Title::getUserPermissionErrors()
658 protected function getEditPermissionErrors( $rigor = 'secure' ) {
659 $user = $this->context
->getUser();
660 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
661 # Can this title be created?
662 if ( !$this->mTitle
->exists() ) {
663 $permErrors = array_merge(
666 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
671 # Ignore some permissions errors when a user is just previewing/viewing diffs
673 foreach ( $permErrors as $error ) {
674 if ( ( $this->preview ||
$this->diff
)
676 $error[0] == 'blockedtext' ||
677 $error[0] == 'autoblockedtext' ||
678 $error[0] == 'systemblockedtext'
684 $permErrors = wfArrayDiff2( $permErrors, $remove );
690 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
691 * but with the following differences:
692 * - If redlink=1, the user will be redirected to the page
693 * - If there is content to display or the error occurs while either saving,
694 * previewing or showing the difference, it will be a
695 * "View source for ..." page displaying the source code after the error message.
698 * @param array $permErrors Array of permissions errors, as returned by
699 * Title::getUserPermissionsErrors().
700 * @throws PermissionsError
702 protected function displayPermissionsError( array $permErrors ) {
705 $out = $this->context
->getOutput();
706 if ( $wgRequest->getBool( 'redlink' ) ) {
707 // The edit page was reached via a red link.
708 // Redirect to the article page and let them click the edit tab if
709 // they really want a permission error.
710 $out->redirect( $this->mTitle
->getFullURL() );
714 $content = $this->getContentObject();
716 # Use the normal message if there's nothing to display
717 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
718 $action = $this->mTitle
->exists() ?
'edit' :
719 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
720 throw new PermissionsError( $action, $permErrors );
723 $this->displayViewSourcePage(
725 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
730 * Display a read-only View Source page
731 * @param Content $content content object
732 * @param string $errorMessage additional wikitext error message to display
734 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
735 $out = $this->context
->getOutput();
736 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
738 $out->setRobotPolicy( 'noindex,nofollow' );
739 $out->setPageTitle( $this->context
->msg(
741 $this->getContextTitle()->getPrefixedText()
743 $out->addBacklinkSubtitle( $this->getContextTitle() );
744 $out->addHTML( $this->editFormPageTop
);
745 $out->addHTML( $this->editFormTextTop
);
747 if ( $errorMessage !== '' ) {
748 $out->addWikiText( $errorMessage );
749 $out->addHTML( "<hr />\n" );
752 # If the user made changes, preserve them when showing the markup
753 # (This happens when a user is blocked during edit, for instance)
754 if ( !$this->firsttime
) {
755 $text = $this->textbox1
;
756 $out->addWikiMsg( 'viewyourtext' );
759 $text = $this->toEditText( $content );
760 } catch ( MWException
$e ) {
761 # Serialize using the default format if the content model is not supported
762 # (e.g. for an old revision with a different model)
763 $text = $content->serialize();
765 $out->addWikiMsg( 'viewsourcetext' );
768 $out->addHTML( $this->editFormTextBeforeContent
);
769 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
770 $out->addHTML( $this->editFormTextAfterContent
);
772 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
774 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
776 $out->addHTML( $this->editFormTextBottom
);
777 if ( $this->mTitle
->exists() ) {
778 $out->returnToMain( null, $this->mTitle
);
783 * Should we show a preview when the edit form is first shown?
787 protected function previewOnOpen() {
788 global $wgRequest, $wgPreviewOnOpenNamespaces;
789 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
790 // Explicit override from request
792 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
793 // Explicit override from request
795 } elseif ( $this->section
== 'new' ) {
796 // Nothing *to* preview for new sections
798 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
799 && $this->context
->getUser()->getOption( 'previewonfirst' )
801 // Standard preference behavior
803 } elseif ( !$this->mTitle
->exists()
804 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
805 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
807 // Categories are special
815 * Checks whether the user entered a skin name in uppercase,
816 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
820 protected function isWrongCaseCssJsPage() {
821 if ( $this->mTitle
->isCssJsSubpage() ) {
822 $name = $this->mTitle
->getSkinFromCssJsSubpage();
823 $skins = array_merge(
824 array_keys( Skin
::getSkinNames() ),
827 return !in_array( $name, $skins )
828 && in_array( strtolower( $name ), $skins );
835 * Returns whether section editing is supported for the current page.
836 * Subclasses may override this to replace the default behavior, which is
837 * to check ContentHandler::supportsSections.
839 * @return bool True if this edit page supports sections, false otherwise.
841 protected function isSectionEditSupported() {
842 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
843 return $contentHandler->supportsSections();
847 * This function collects the form data and uses it to populate various member variables.
848 * @param WebRequest &$request
849 * @throws ErrorPageError
851 public function importFormData( &$request ) {
852 # Section edit can come from either the form or a link
853 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
855 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
856 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
859 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
861 if ( $request->wasPosted() ) {
862 # These fields need to be checked for encoding.
863 # Also remove trailing whitespace, but don't remove _initial_
864 # whitespace from the text boxes. This may be significant formatting.
865 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
866 if ( !$request->getCheck( 'wpTextbox2' ) ) {
867 // Skip this if wpTextbox2 has input, it indicates that we came
868 // from a conflict page with raw page text, not a custom form
869 // modified by subclasses
870 $textbox1 = $this->importContentFormData( $request );
871 if ( $textbox1 !== null ) {
872 $this->textbox1
= $textbox1;
876 $this->summary
= $request->getText( 'wpSummary' );
878 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
879 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
881 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
883 # Treat sectiontitle the same way as summary.
884 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
885 # currently doing double duty as both edit summary and section title. Right now this
886 # is just to allow API edits to work around this limitation, but this should be
887 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
888 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
889 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
891 $this->edittime
= $request->getVal( 'wpEdittime' );
892 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
893 $this->starttime
= $request->getVal( 'wpStarttime' );
895 $undidRev = $request->getInt( 'wpUndidRevision' );
897 $this->undidRev
= $undidRev;
900 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
902 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
903 // wpTextbox1 field is missing, possibly due to being "too big"
904 // according to some filter rules such as Suhosin's setting for
905 // suhosin.request.max_value_length (d'oh)
906 $this->incompleteForm
= true;
908 // If we receive the last parameter of the request, we can fairly
909 // claim the POST request has not been truncated.
911 // TODO: softened the check for cutover. Once we determine
912 // that it is safe, we should complete the transition by
913 // removing the "edittime" clause.
914 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
915 && is_null( $this->edittime
) );
917 if ( $this->incompleteForm
) {
918 # If the form is incomplete, force to preview.
919 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
920 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
921 $this->preview
= true;
923 $this->preview
= $request->getCheck( 'wpPreview' );
924 $this->diff
= $request->getCheck( 'wpDiff' );
926 // Remember whether a save was requested, so we can indicate
927 // if we forced preview due to session failure.
928 $this->mTriedSave
= !$this->preview
;
930 if ( $this->tokenOk( $request ) ) {
931 # Some browsers will not report any submit button
932 # if the user hits enter in the comment box.
933 # The unmarked state will be assumed to be a save,
934 # if the form seems otherwise complete.
935 wfDebug( __METHOD__
. ": Passed token check.\n" );
936 } elseif ( $this->diff
) {
937 # Failed token check, but only requested "Show Changes".
938 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
940 # Page might be a hack attempt posted from
941 # an external site. Preview instead of saving.
942 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
943 $this->preview
= true;
946 $this->save
= !$this->preview
&& !$this->diff
;
947 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
948 $this->edittime
= null;
951 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
952 $this->starttime
= null;
955 $this->recreate
= $request->getCheck( 'wpRecreate' );
957 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
958 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
960 $user = $this->context
->getUser();
961 # Don't force edit summaries when a user is editing their own user or talk page
962 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
963 && $this->mTitle
->getText() == $user->getName()
965 $this->allowBlankSummary
= true;
967 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
968 ||
!$user->getOption( 'forceeditsummary' );
971 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
973 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
974 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
976 $changeTags = $request->getVal( 'wpChangeTags' );
977 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
978 $this->changeTags
= [];
980 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
984 # Not a posted form? Start with nothing.
985 wfDebug( __METHOD__
. ": Not a posted form.\n" );
986 $this->textbox1
= '';
988 $this->sectiontitle
= '';
989 $this->edittime
= '';
990 $this->editRevId
= null;
991 $this->starttime
= wfTimestampNow();
993 $this->preview
= false;
996 $this->minoredit
= false;
997 // Watch may be overridden by request parameters
998 $this->watchthis
= $request->getBool( 'watchthis', false );
999 $this->recreate
= false;
1001 // When creating a new section, we can preload a section title by passing it as the
1002 // preloadtitle parameter in the URL (T15100)
1003 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1004 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1005 // Once wpSummary isn't being use for setting section titles, we should delete this.
1006 $this->summary
= $request->getVal( 'preloadtitle' );
1007 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1008 $this->summary
= $request->getText( 'summary' );
1009 if ( $this->summary
!== '' ) {
1010 $this->hasPresetSummary
= true;
1014 if ( $request->getVal( 'minor' ) ) {
1015 $this->minoredit
= true;
1019 $this->oldid
= $request->getInt( 'oldid' );
1020 $this->parentRevId
= $request->getInt( 'parentRevId' );
1022 $this->bot
= $request->getBool( 'bot', true );
1023 $this->nosummary
= $request->getBool( 'nosummary' );
1025 // May be overridden by revision.
1026 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1027 // May be overridden by revision.
1028 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1031 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1032 } catch ( MWUnknownContentModelException
$e ) {
1033 throw new ErrorPageError(
1034 'editpage-invalidcontentmodel-title',
1035 'editpage-invalidcontentmodel-text',
1036 [ wfEscapeWikiText( $this->contentModel
) ]
1040 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1041 throw new ErrorPageError(
1042 'editpage-notsupportedcontentformat-title',
1043 'editpage-notsupportedcontentformat-text',
1045 wfEscapeWikiText( $this->contentFormat
),
1046 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1052 * @todo Check if the desired model is allowed in this namespace, and if
1053 * a transition from the page's current model to the new model is
1057 $this->editintro
= $request->getText( 'editintro',
1058 // Custom edit intro for new sections
1059 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1061 // Allow extensions to modify form data
1062 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1066 * Subpage overridable method for extracting the page content data from the
1067 * posted form to be placed in $this->textbox1, if using customized input
1068 * this method should be overridden and return the page text that will be used
1069 * for saving, preview parsing and so on...
1071 * @param WebRequest &$request
1072 * @return string|null
1074 protected function importContentFormData( &$request ) {
1075 return; // Don't do anything, EditPage already extracted wpTextbox1
1079 * Initialise form fields in the object
1080 * Called on the first invocation, e.g. when a user clicks an edit link
1081 * @return bool If the requested section is valid
1083 public function initialiseForm() {
1084 $this->edittime
= $this->page
->getTimestamp();
1085 $this->editRevId
= $this->page
->getLatest();
1087 $content = $this->getContentObject( false ); # TODO: track content object?!
1088 if ( $content === false ) {
1091 $this->textbox1
= $this->toEditText( $content );
1093 $user = $this->context
->getUser();
1094 // activate checkboxes if user wants them to be always active
1095 # Sort out the "watch" checkbox
1096 if ( $user->getOption( 'watchdefault' ) ) {
1098 $this->watchthis
= true;
1099 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1101 $this->watchthis
= true;
1102 } elseif ( $user->isWatched( $this->mTitle
) ) {
1104 $this->watchthis
= true;
1106 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1107 $this->minoredit
= true;
1109 if ( $this->textbox1
=== false ) {
1116 * @param Content|null $def_content The default value to return
1118 * @return Content|null Content on success, $def_content for invalid sections
1122 protected function getContentObject( $def_content = null ) {
1123 global $wgRequest, $wgContLang;
1127 $user = $this->context
->getUser();
1128 // For message page not locally set, use the i18n message.
1129 // For other non-existent articles, use preload text if any.
1130 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1131 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1132 # If this is a system message, get the default text.
1133 $msg = $this->mTitle
->getDefaultMessageText();
1135 $content = $this->toEditContent( $msg );
1137 if ( $content === false ) {
1138 # If requested, preload some text.
1139 $preload = $wgRequest->getVal( 'preload',
1140 // Custom preload text for new sections
1141 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1142 $params = $wgRequest->getArray( 'preloadparams', [] );
1144 $content = $this->getPreloadedContent( $preload, $params );
1146 // For existing pages, get text based on "undo" or section parameters.
1148 if ( $this->section
!= '' ) {
1149 // Get section edit text (returns $def_text for invalid sections)
1150 $orig = $this->getOriginalContent( $user );
1151 $content = $orig ?
$orig->getSection( $this->section
) : null;
1154 $content = $def_content;
1157 $undoafter = $wgRequest->getInt( 'undoafter' );
1158 $undo = $wgRequest->getInt( 'undo' );
1160 if ( $undo > 0 && $undoafter > 0 ) {
1161 $undorev = Revision
::newFromId( $undo );
1162 $oldrev = Revision
::newFromId( $undoafter );
1164 # Sanity check, make sure it's the right page,
1165 # the revisions exist and they were not deleted.
1166 # Otherwise, $content will be left as-is.
1167 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1168 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1169 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1171 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1173 if ( $content === false ) {
1174 # Warn the user that something went wrong
1175 $undoMsg = 'failure';
1177 $oldContent = $this->page
->getContent( Revision
::RAW
);
1178 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1179 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1180 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1181 // The undo may change content
1182 // model if its reverting the top
1183 // edit. This can result in
1184 // mismatched content model/format.
1185 $this->contentModel
= $newContent->getModel();
1186 $this->contentFormat
= $oldrev->getContentFormat();
1189 if ( $newContent->equals( $oldContent ) ) {
1190 # Tell the user that the undo results in no change,
1191 # i.e. the revisions were already undone.
1192 $undoMsg = 'nochange';
1195 # Inform the user of our success and set an automatic edit summary
1196 $undoMsg = 'success';
1198 # If we just undid one rev, use an autosummary
1199 $firstrev = $oldrev->getNext();
1200 if ( $firstrev && $firstrev->getId() == $undo ) {
1201 $userText = $undorev->getUserText();
1202 if ( $userText === '' ) {
1203 $undoSummary = $this->context
->msg(
1204 'undo-summary-username-hidden',
1206 )->inContentLanguage()->text();
1208 $undoSummary = $this->context
->msg(
1212 )->inContentLanguage()->text();
1214 if ( $this->summary
=== '' ) {
1215 $this->summary
= $undoSummary;
1217 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1218 ->inContentLanguage()->text() . $this->summary
;
1220 $this->undidRev
= $undo;
1222 $this->formtype
= 'diff';
1226 // Failed basic sanity checks.
1227 // Older revisions may have been removed since the link
1228 // was created, or we may simply have got bogus input.
1232 $out = $this->context
->getOutput();
1233 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1234 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1235 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1236 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1239 if ( $content === false ) {
1240 $content = $this->getOriginalContent( $user );
1249 * Get the content of the wanted revision, without section extraction.
1251 * The result of this function can be used to compare user's input with
1252 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1253 * to the original text of the edit.
1255 * This differs from Article::getContent() that when a missing revision is
1256 * encountered the result will be null and not the
1257 * 'missing-revision' message.
1260 * @param User $user The user to get the revision for
1261 * @return Content|null
1263 private function getOriginalContent( User
$user ) {
1264 if ( $this->section
== 'new' ) {
1265 return $this->getCurrentContent();
1267 $revision = $this->mArticle
->getRevisionFetched();
1268 if ( $revision === null ) {
1269 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1270 return $handler->makeEmptyContent();
1272 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1277 * Get the edit's parent revision ID
1279 * The "parent" revision is the ancestor that should be recorded in this
1280 * page's revision history. It is either the revision ID of the in-memory
1281 * article content, or in the case of a 3-way merge in order to rebase
1282 * across a recoverable edit conflict, the ID of the newer revision to
1283 * which we have rebased this page.
1286 * @return int Revision ID
1288 public function getParentRevId() {
1289 if ( $this->parentRevId
) {
1290 return $this->parentRevId
;
1292 return $this->mArticle
->getRevIdFetched();
1297 * Get the current content of the page. This is basically similar to
1298 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1299 * content object is returned instead of null.
1304 protected function getCurrentContent() {
1305 $rev = $this->page
->getRevision();
1306 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1308 if ( $content === false ||
$content === null ) {
1309 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1310 return $handler->makeEmptyContent();
1311 } elseif ( !$this->undidRev
) {
1312 // Content models should always be the same since we error
1313 // out if they are different before this point (in ->edit()).
1314 // The exception being, during an undo, the current revision might
1315 // differ from the prior revision.
1316 $logger = LoggerFactory
::getInstance( 'editpage' );
1317 if ( $this->contentModel
!== $rev->getContentModel() ) {
1318 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1319 'prev' => $this->contentModel
,
1320 'new' => $rev->getContentModel(),
1321 'title' => $this->getTitle()->getPrefixedDBkey(),
1322 'method' => __METHOD__
1324 $this->contentModel
= $rev->getContentModel();
1327 // Given that the content models should match, the current selected
1328 // format should be supported.
1329 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1330 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1332 'prev' => $this->contentFormat
,
1333 'new' => $rev->getContentFormat(),
1334 'title' => $this->getTitle()->getPrefixedDBkey(),
1335 'method' => __METHOD__
1337 $this->contentFormat
= $rev->getContentFormat();
1344 * Use this method before edit() to preload some content into the edit box
1346 * @param Content $content
1350 public function setPreloadedContent( Content
$content ) {
1351 $this->mPreloadContent
= $content;
1355 * Get the contents to be preloaded into the box, either set by
1356 * an earlier setPreloadText() or by loading the given page.
1358 * @param string $preload Representing the title to preload from.
1359 * @param array $params Parameters to use (interface-message style) in the preloaded text
1365 protected function getPreloadedContent( $preload, $params = [] ) {
1366 if ( !empty( $this->mPreloadContent
) ) {
1367 return $this->mPreloadContent
;
1370 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1372 if ( $preload === '' ) {
1373 return $handler->makeEmptyContent();
1376 $user = $this->context
->getUser();
1377 $title = Title
::newFromText( $preload );
1378 # Check for existence to avoid getting MediaWiki:Noarticletext
1379 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1380 // TODO: somehow show a warning to the user!
1381 return $handler->makeEmptyContent();
1384 $page = WikiPage
::factory( $title );
1385 if ( $page->isRedirect() ) {
1386 $title = $page->getRedirectTarget();
1388 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1389 // TODO: somehow show a warning to the user!
1390 return $handler->makeEmptyContent();
1392 $page = WikiPage
::factory( $title );
1395 $parserOptions = ParserOptions
::newFromUser( $user );
1396 $content = $page->getContent( Revision
::RAW
);
1399 // TODO: somehow show a warning to the user!
1400 return $handler->makeEmptyContent();
1403 if ( $content->getModel() !== $handler->getModelID() ) {
1404 $converted = $content->convert( $handler->getModelID() );
1406 if ( !$converted ) {
1407 // TODO: somehow show a warning to the user!
1408 wfDebug( "Attempt to preload incompatible content: " .
1409 "can't convert " . $content->getModel() .
1410 " to " . $handler->getModelID() );
1412 return $handler->makeEmptyContent();
1415 $content = $converted;
1418 return $content->preloadTransform( $title, $parserOptions, $params );
1422 * Make sure the form isn't faking a user's credentials.
1424 * @param WebRequest &$request
1428 public function tokenOk( &$request ) {
1429 $token = $request->getVal( 'wpEditToken' );
1430 $user = $this->context
->getUser();
1431 $this->mTokenOk
= $user->matchEditToken( $token );
1432 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1433 return $this->mTokenOk
;
1437 * Sets post-edit cookie indicating the user just saved a particular revision.
1439 * This uses a temporary cookie for each revision ID so separate saves will never
1440 * interfere with each other.
1442 * Article::view deletes the cookie on server-side after the redirect and
1443 * converts the value to the global JavaScript variable wgPostEdit.
1445 * If the variable were set on the server, it would be cached, which is unwanted
1446 * since the post-edit state should only apply to the load right after the save.
1448 * @param int $statusValue The status value (to check for new article status)
1450 protected function setPostEditCookie( $statusValue ) {
1451 $revisionId = $this->page
->getLatest();
1452 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1455 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1457 } elseif ( $this->oldid
) {
1461 $response = $this->context
->getRequest()->response();
1462 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1466 * Attempt submission
1467 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1468 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1469 * @return Status The resulting status object.
1471 public function attemptSave( &$resultDetails = false ) {
1472 # Allow bots to exempt some edits from bot flagging
1473 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1474 $status = $this->internalAttemptSave( $resultDetails, $bot );
1476 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1482 * Log when a page was successfully saved after the edit conflict view
1484 private function incrementResolvedConflicts() {
1487 if ( $wgRequest->getText( 'mode' ) !== 'conflict' ) {
1491 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1492 $stats->increment( 'edit.failures.conflict.resolved' );
1496 * Handle status, such as after attempt save
1498 * @param Status $status
1499 * @param array|bool $resultDetails
1501 * @throws ErrorPageError
1502 * @return bool False, if output is done, true if rest of the form should be displayed
1504 private function handleStatus( Status
$status, $resultDetails ) {
1506 * @todo FIXME: once the interface for internalAttemptSave() is made
1507 * nicer, this should use the message in $status
1509 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1510 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1512 $this->incrementResolvedConflicts();
1514 $this->didSave
= true;
1515 if ( !$resultDetails['nullEdit'] ) {
1516 $this->setPostEditCookie( $status->value
);
1520 $out = $this->context
->getOutput();
1522 // "wpExtraQueryRedirect" is a hidden input to modify
1523 // after save URL and is not used by actual edit form
1524 $request = $this->context
->getRequest();
1525 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1527 switch ( $status->value
) {
1528 case self
::AS_HOOK_ERROR_EXPECTED
:
1529 case self
::AS_CONTENT_TOO_BIG
:
1530 case self
::AS_ARTICLE_WAS_DELETED
:
1531 case self
::AS_CONFLICT_DETECTED
:
1532 case self
::AS_SUMMARY_NEEDED
:
1533 case self
::AS_TEXTBOX_EMPTY
:
1534 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1536 case self
::AS_BLANK_ARTICLE
:
1537 case self
::AS_SELF_REDIRECT
:
1540 case self
::AS_HOOK_ERROR
:
1543 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1544 case self
::AS_PARSE_ERROR
:
1545 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1548 case self
::AS_SUCCESS_NEW_ARTICLE
:
1549 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1550 if ( $extraQueryRedirect ) {
1551 if ( $query === '' ) {
1552 $query = $extraQueryRedirect;
1554 $query = $query . '&' . $extraQueryRedirect;
1557 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1558 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1561 case self
::AS_SUCCESS_UPDATE
:
1563 $sectionanchor = $resultDetails['sectionanchor'];
1565 // Give extensions a chance to modify URL query on update
1567 'ArticleUpdateBeforeRedirect',
1568 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1571 if ( $resultDetails['redirect'] ) {
1572 if ( $extraQuery == '' ) {
1573 $extraQuery = 'redirect=no';
1575 $extraQuery = 'redirect=no&' . $extraQuery;
1578 if ( $extraQueryRedirect ) {
1579 if ( $extraQuery === '' ) {
1580 $extraQuery = $extraQueryRedirect;
1582 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1586 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1589 case self
::AS_SPAM_ERROR
:
1590 $this->spamPageWithContent( $resultDetails['spam'] );
1593 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1594 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1596 case self
::AS_IMAGE_REDIRECT_ANON
:
1597 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1598 throw new PermissionsError( 'upload' );
1600 case self
::AS_READ_ONLY_PAGE_ANON
:
1601 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1602 throw new PermissionsError( 'edit' );
1604 case self
::AS_READ_ONLY_PAGE
:
1605 throw new ReadOnlyError
;
1607 case self
::AS_RATE_LIMITED
:
1608 throw new ThrottledError();
1610 case self
::AS_NO_CREATE_PERMISSION
:
1611 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1612 throw new PermissionsError( $permission );
1614 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1615 throw new PermissionsError( 'editcontentmodel' );
1618 // We don't recognize $status->value. The only way that can happen
1619 // is if an extension hook aborted from inside ArticleSave.
1620 // Render the status object into $this->hookError
1621 // FIXME this sucks, we should just use the Status object throughout
1622 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1629 * Run hooks that can filter edits just before they get saved.
1631 * @param Content $content The Content to filter.
1632 * @param Status $status For reporting the outcome to the caller
1633 * @param User $user The user performing the edit
1637 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1638 // Run old style post-section-merge edit filter
1639 if ( $this->hookError
!= '' ) {
1640 # ...or the hook could be expecting us to produce an error
1641 $status->fatal( 'hookaborted' );
1642 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1646 // Run new style post-section-merge edit filter
1647 if ( !Hooks
::run( 'EditFilterMergedContent',
1648 [ $this->mArticle
->getContext(), $content, $status, $this->summary
,
1649 $user, $this->minoredit
] )
1651 # Error messages etc. could be handled within the hook...
1652 if ( $status->isGood() ) {
1653 $status->fatal( 'hookaborted' );
1654 // Not setting $this->hookError here is a hack to allow the hook
1655 // to cause a return to the edit page without $this->hookError
1656 // being set. This is used by ConfirmEdit to display a captcha
1657 // without any error message cruft.
1659 $this->hookError
= $status->getWikiText();
1661 // Use the existing $status->value if the hook set it
1662 if ( !$status->value
) {
1663 $status->value
= self
::AS_HOOK_ERROR
;
1666 } elseif ( !$status->isOK() ) {
1667 # ...or the hook could be expecting us to produce an error
1668 // FIXME this sucks, we should just use the Status object throughout
1669 $this->hookError
= $status->getWikiText();
1670 $status->fatal( 'hookaborted' );
1671 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1679 * Return the summary to be used for a new section.
1681 * @param string $sectionanchor Set to the section anchor text
1684 private function newSectionSummary( &$sectionanchor = null ) {
1687 if ( $this->sectiontitle
!== '' ) {
1688 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1689 // If no edit summary was specified, create one automatically from the section
1690 // title and have it link to the new section. Otherwise, respect the summary as
1692 if ( $this->summary
=== '' ) {
1693 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1694 return $this->context
->msg( 'newsectionsummary' )
1695 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1697 } elseif ( $this->summary
!== '' ) {
1698 $sectionanchor = $this->guessSectionName( $this->summary
);
1699 # This is a new section, so create a link to the new section
1700 # in the revision summary.
1701 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1702 return $this->context
->msg( 'newsectionsummary' )
1703 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1705 return $this->summary
;
1709 * Attempt submission (no UI)
1711 * @param array &$result Array to add statuses to, currently with the
1713 * - spam (string): Spam string from content if any spam is detected by
1715 * - sectionanchor (string): Section anchor for a section save.
1716 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1718 * - redirect (bool): Set if doEditContent is OK. True if resulting
1719 * revision is a redirect.
1720 * @param bool $bot True if edit is being made under the bot right.
1722 * @return Status Status object, possibly with a message, but always with
1723 * one of the AS_* constants in $status->value,
1725 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1726 * various error display idiosyncrasies. There are also lots of cases
1727 * where error metadata is set in the object and retrieved later instead
1728 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1729 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1732 public function internalAttemptSave( &$result, $bot = false ) {
1733 global $wgRequest, $wgMaxArticleSize;
1734 global $wgContentHandlerUseDB;
1736 $status = Status
::newGood();
1737 $user = $this->context
->getUser();
1739 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1740 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1741 $status->fatal( 'hookaborted' );
1742 $status->value
= self
::AS_HOOK_ERROR
;
1746 $spam = $wgRequest->getText( 'wpAntispam' );
1747 if ( $spam !== '' ) {
1752 $this->mTitle
->getPrefixedText() .
1753 '" submitted bogus field "' .
1757 $status->fatal( 'spamprotectionmatch', false );
1758 $status->value
= self
::AS_SPAM_ERROR
;
1763 # Construct Content object
1764 $textbox_content = $this->toEditContent( $this->textbox1
);
1765 } catch ( MWContentSerializationException
$ex ) {
1767 'content-failed-to-parse',
1768 $this->contentModel
,
1769 $this->contentFormat
,
1772 $status->value
= self
::AS_PARSE_ERROR
;
1776 # Check image redirect
1777 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1778 $textbox_content->isRedirect() &&
1779 !$user->isAllowed( 'upload' )
1781 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1782 $status->setResult( false, $code );
1788 $match = self
::matchSummarySpamRegex( $this->summary
);
1789 if ( $match === false && $this->section
== 'new' ) {
1790 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1791 # regular summaries, it is added to the actual wikitext.
1792 if ( $this->sectiontitle
!== '' ) {
1793 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1794 $match = self
::matchSpamRegex( $this->sectiontitle
);
1796 # This branch is taken when the "Add Topic" user interface is used, or the API
1797 # is used with the 'summary' parameter.
1798 $match = self
::matchSpamRegex( $this->summary
);
1801 if ( $match === false ) {
1802 $match = self
::matchSpamRegex( $this->textbox1
);
1804 if ( $match !== false ) {
1805 $result['spam'] = $match;
1806 $ip = $wgRequest->getIP();
1807 $pdbk = $this->mTitle
->getPrefixedDBkey();
1808 $match = str_replace( "\n", '', $match );
1809 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1810 $status->fatal( 'spamprotectionmatch', $match );
1811 $status->value
= self
::AS_SPAM_ERROR
;
1816 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1818 # Error messages etc. could be handled within the hook...
1819 $status->fatal( 'hookaborted' );
1820 $status->value
= self
::AS_HOOK_ERROR
;
1822 } elseif ( $this->hookError
!= '' ) {
1823 # ...or the hook could be expecting us to produce an error
1824 $status->fatal( 'hookaborted' );
1825 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1829 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1830 // Auto-block user's IP if the account was "hard" blocked
1831 if ( !wfReadOnly() ) {
1832 $user->spreadAnyEditBlock();
1834 # Check block state against master, thus 'false'.
1835 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1839 $this->contentLength
= strlen( $this->textbox1
);
1840 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
1841 // Error will be displayed by showEditForm()
1842 $this->tooBig
= true;
1843 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1847 if ( !$user->isAllowed( 'edit' ) ) {
1848 if ( $user->isAnon() ) {
1849 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1852 $status->fatal( 'readonlytext' );
1853 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1858 $changingContentModel = false;
1859 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1860 if ( !$wgContentHandlerUseDB ) {
1861 $status->fatal( 'editpage-cannot-use-custom-model' );
1862 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1864 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1865 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1868 // Make sure the user can edit the page under the new content model too
1869 $titleWithNewContentModel = clone $this->mTitle
;
1870 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1871 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1872 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1874 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1878 $changingContentModel = true;
1879 $oldContentModel = $this->mTitle
->getContentModel();
1882 if ( $this->changeTags
) {
1883 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1884 $this->changeTags
, $user );
1885 if ( !$changeTagsStatus->isOK() ) {
1886 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1887 return $changeTagsStatus;
1891 if ( wfReadOnly() ) {
1892 $status->fatal( 'readonlytext' );
1893 $status->value
= self
::AS_READ_ONLY_PAGE
;
1896 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1897 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1899 $status->fatal( 'actionthrottledtext' );
1900 $status->value
= self
::AS_RATE_LIMITED
;
1904 # If the article has been deleted while editing, don't save it without
1906 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1907 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1911 # Load the page data from the master. If anything changes in the meantime,
1912 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1913 $this->page
->loadPageData( 'fromdbmaster' );
1914 $new = !$this->page
->exists();
1917 // Late check for create permission, just in case *PARANOIA*
1918 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1919 $status->fatal( 'nocreatetext' );
1920 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1921 wfDebug( __METHOD__
. ": no create permission\n" );
1925 // Don't save a new page if it's blank or if it's a MediaWiki:
1926 // message with content equivalent to default (allow empty pages
1927 // in this case to disable messages, see T52124)
1928 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1929 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1930 $defaultText = $defaultMessageText;
1935 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1936 $this->blankArticle
= true;
1937 $status->fatal( 'blankarticle' );
1938 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1942 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
1946 $content = $textbox_content;
1948 $result['sectionanchor'] = '';
1949 if ( $this->section
== 'new' ) {
1950 if ( $this->sectiontitle
!== '' ) {
1951 // Insert the section title above the content.
1952 $content = $content->addSectionHeader( $this->sectiontitle
);
1953 } elseif ( $this->summary
!== '' ) {
1954 // Insert the section title above the content.
1955 $content = $content->addSectionHeader( $this->summary
);
1957 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1960 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1964 # Article exists. Check for edit conflict.
1966 $this->page
->clear(); # Force reload of dates, etc.
1967 $timestamp = $this->page
->getTimestamp();
1968 $latest = $this->page
->getLatest();
1970 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1972 // Check editRevId if set, which handles same-second timestamp collisions
1973 if ( $timestamp != $this->edittime
1974 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
1976 $this->isConflict
= true;
1977 if ( $this->section
== 'new' ) {
1978 if ( $this->page
->getUserText() == $user->getName() &&
1979 $this->page
->getComment() == $this->newSectionSummary()
1981 // Probably a duplicate submission of a new comment.
1982 // This can happen when CDN resends a request after
1983 // a timeout but the first one actually went through.
1985 . ": duplicate new section submission; trigger edit conflict!\n" );
1987 // New comment; suppress conflict.
1988 $this->isConflict
= false;
1989 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1991 } elseif ( $this->section
== ''
1992 && Revision
::userWasLastToEdit(
1993 DB_MASTER
, $this->mTitle
->getArticleID(),
1994 $user->getId(), $this->edittime
1997 # Suppress edit conflict with self, except for section edits where merging is required.
1998 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1999 $this->isConflict
= false;
2003 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2004 if ( $this->sectiontitle
!== '' ) {
2005 $sectionTitle = $this->sectiontitle
;
2007 $sectionTitle = $this->summary
;
2012 if ( $this->isConflict
) {
2014 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2015 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2016 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2017 // ...or disable section editing for non-current revisions (not exposed anyway).
2018 if ( $this->editRevId
!== null ) {
2019 $content = $this->page
->replaceSectionAtRev(
2026 $content = $this->page
->replaceSectionContent(
2034 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2035 $content = $this->page
->replaceSectionContent(
2042 if ( is_null( $content ) ) {
2043 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2044 $this->isConflict
= true;
2045 $content = $textbox_content; // do not try to merge here!
2046 } elseif ( $this->isConflict
) {
2048 if ( $this->mergeChangesIntoContent( $content ) ) {
2049 // Successful merge! Maybe we should tell the user the good news?
2050 $this->isConflict
= false;
2051 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2053 $this->section
= '';
2054 $this->textbox1
= ContentHandler
::getContentText( $content );
2055 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2059 if ( $this->isConflict
) {
2060 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2064 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2068 if ( $this->section
== 'new' ) {
2069 // Handle the user preference to force summaries here
2070 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2071 $this->missingSummary
= true;
2072 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2073 $status->value
= self
::AS_SUMMARY_NEEDED
;
2077 // Do not allow the user to post an empty comment
2078 if ( $this->textbox1
== '' ) {
2079 $this->missingComment
= true;
2080 $status->fatal( 'missingcommenttext' );
2081 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2084 } elseif ( !$this->allowBlankSummary
2085 && !$content->equals( $this->getOriginalContent( $user ) )
2086 && !$content->isRedirect()
2087 && md5( $this->summary
) == $this->autoSumm
2089 $this->missingSummary
= true;
2090 $status->fatal( 'missingsummary' );
2091 $status->value
= self
::AS_SUMMARY_NEEDED
;
2096 $sectionanchor = '';
2097 if ( $this->section
== 'new' ) {
2098 $this->summary
= $this->newSectionSummary( $sectionanchor );
2099 } elseif ( $this->section
!= '' ) {
2100 # Try to get a section anchor from the section source, redirect
2101 # to edited section if header found.
2102 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2103 # for duplicate heading checking and maybe parsing.
2104 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2105 # We can't deal with anchors, includes, html etc in the header for now,
2106 # headline would need to be parsed to improve this.
2107 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2108 $sectionanchor = $this->guessSectionName( $matches[2] );
2111 $result['sectionanchor'] = $sectionanchor;
2113 // Save errors may fall down to the edit form, but we've now
2114 // merged the section into full text. Clear the section field
2115 // so that later submission of conflict forms won't try to
2116 // replace that into a duplicated mess.
2117 $this->textbox1
= $this->toEditText( $content );
2118 $this->section
= '';
2120 $status->value
= self
::AS_SUCCESS_UPDATE
;
2123 if ( !$this->allowSelfRedirect
2124 && $content->isRedirect()
2125 && $content->getRedirectTarget()->equals( $this->getTitle() )
2127 // If the page already redirects to itself, don't warn.
2128 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2129 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2130 $this->selfRedirect
= true;
2131 $status->fatal( 'selfredirect' );
2132 $status->value
= self
::AS_SELF_REDIRECT
;
2137 // Check for length errors again now that the section is merged in
2138 $this->contentLength
= strlen( $this->toEditText( $content ) );
2139 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
2140 $this->tooBig
= true;
2141 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2145 $flags = EDIT_AUTOSUMMARY |
2146 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2147 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2148 ( $bot ? EDIT_FORCE_BOT
: 0 );
2150 $doEditStatus = $this->page
->doEditContent(
2156 $content->getDefaultFormat(),
2161 if ( !$doEditStatus->isOK() ) {
2162 // Failure from doEdit()
2163 // Show the edit conflict page for certain recognized errors from doEdit(),
2164 // but don't show it for errors from extension hooks
2165 $errors = $doEditStatus->getErrorsArray();
2166 if ( in_array( $errors[0][0],
2167 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2169 $this->isConflict
= true;
2170 // Destroys data doEdit() put in $status->value but who cares
2171 $doEditStatus->value
= self
::AS_END
;
2173 return $doEditStatus;
2176 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2177 if ( $result['nullEdit'] ) {
2178 // We don't know if it was a null edit until now, so increment here
2179 $user->pingLimiter( 'linkpurge' );
2181 $result['redirect'] = $content->isRedirect();
2183 $this->updateWatchlist();
2185 // If the content model changed, add a log entry
2186 if ( $changingContentModel ) {
2187 $this->addContentModelChangeLogEntry(
2189 $new ?
false : $oldContentModel,
2190 $this->contentModel
,
2200 * @param string|false $oldModel false if the page is being newly created
2201 * @param string $newModel
2202 * @param string $reason
2204 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2205 $new = $oldModel === false;
2206 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2207 $log->setPerformer( $user );
2208 $log->setTarget( $this->mTitle
);
2209 $log->setComment( $reason );
2210 $log->setParameters( [
2211 '4::oldmodel' => $oldModel,
2212 '5::newmodel' => $newModel
2214 $logid = $log->insert();
2215 $log->publish( $logid );
2219 * Register the change of watch status
2221 protected function updateWatchlist() {
2222 $user = $this->context
->getUser();
2223 if ( !$user->isLoggedIn() ) {
2227 $title = $this->mTitle
;
2228 $watch = $this->watchthis
;
2229 // Do this in its own transaction to reduce contention...
2230 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2231 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2232 return; // nothing to change
2234 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2239 * Attempts to do 3-way merge of edit content with a base revision
2240 * and current content, in case of edit conflict, in whichever way appropriate
2241 * for the content type.
2245 * @param Content $editContent
2249 private function mergeChangesIntoContent( &$editContent ) {
2250 $db = wfGetDB( DB_MASTER
);
2252 // This is the revision the editor started from
2253 $baseRevision = $this->getBaseRevision();
2254 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2256 if ( is_null( $baseContent ) ) {
2260 // The current state, we want to merge updates into it
2261 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2262 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2264 if ( is_null( $currentContent ) ) {
2268 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2270 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2273 $editContent = $result;
2274 // Update parentRevId to what we just merged.
2275 $this->parentRevId
= $currentRevision->getId();
2283 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2284 * one might think of X as the "base revision", which is NOT what this returns.
2285 * @return Revision Current version when the edit was started
2287 public function getBaseRevision() {
2288 if ( !$this->mBaseRevision
) {
2289 $db = wfGetDB( DB_MASTER
);
2290 $this->mBaseRevision
= $this->editRevId
2291 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2292 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2294 return $this->mBaseRevision
;
2298 * Check given input text against $wgSpamRegex, and return the text of the first match.
2300 * @param string $text
2302 * @return string|bool Matching string or false
2304 public static function matchSpamRegex( $text ) {
2305 global $wgSpamRegex;
2306 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2307 $regexes = (array)$wgSpamRegex;
2308 return self
::matchSpamRegexInternal( $text, $regexes );
2312 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2314 * @param string $text
2316 * @return string|bool Matching string or false
2318 public static function matchSummarySpamRegex( $text ) {
2319 global $wgSummarySpamRegex;
2320 $regexes = (array)$wgSummarySpamRegex;
2321 return self
::matchSpamRegexInternal( $text, $regexes );
2325 * @param string $text
2326 * @param array $regexes
2327 * @return bool|string
2329 protected static function matchSpamRegexInternal( $text, $regexes ) {
2330 foreach ( $regexes as $regex ) {
2332 if ( preg_match( $regex, $text, $matches ) ) {
2339 public function setHeaders() {
2340 global $wgAjaxEditStash;
2342 $out = $this->context
->getOutput();
2344 $out->addModules( 'mediawiki.action.edit' );
2345 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2347 $user = $this->context
->getUser();
2348 if ( $user->getOption( 'showtoolbar' ) ) {
2349 // The addition of default buttons is handled by getEditToolbar() which
2350 // has its own dependency on this module. The call here ensures the module
2351 // is loaded in time (it has position "top") for other modules to register
2352 // buttons (e.g. extensions, gadgets, user scripts).
2353 $out->addModules( 'mediawiki.toolbar' );
2356 if ( $user->getOption( 'uselivepreview' ) ) {
2357 $out->addModules( 'mediawiki.action.edit.preview' );
2360 if ( $user->getOption( 'useeditwarning' ) ) {
2361 $out->addModules( 'mediawiki.action.edit.editWarning' );
2364 # Enabled article-related sidebar, toplinks, etc.
2365 $out->setArticleRelated( true );
2367 $contextTitle = $this->getContextTitle();
2368 if ( $this->isConflict
) {
2369 $msg = 'editconflict';
2370 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2371 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2373 $msg = $contextTitle->exists()
2374 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2375 && $contextTitle->getDefaultMessageText() !== false
2381 # Use the title defined by DISPLAYTITLE magic word when present
2382 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2383 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2384 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2385 if ( $displayTitle === false ) {
2386 $displayTitle = $contextTitle->getPrefixedText();
2388 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2389 # Transmit the name of the message to JavaScript for live preview
2390 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2391 $out->addJsConfigVars( [
2392 'wgEditMessage' => $msg,
2393 'wgAjaxEditStash' => $wgAjaxEditStash,
2398 * Show all applicable editing introductions
2400 protected function showIntro() {
2401 if ( $this->suppressIntro
) {
2405 $out = $this->context
->getOutput();
2406 $namespace = $this->mTitle
->getNamespace();
2408 if ( $namespace == NS_MEDIAWIKI
) {
2409 # Show a warning if editing an interface message
2410 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2411 # If this is a default message (but not css or js),
2412 # show a hint that it is translatable on translatewiki.net
2413 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2414 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2416 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2417 if ( $defaultMessageText !== false ) {
2418 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2419 'translateinterface' );
2422 } elseif ( $namespace == NS_FILE
) {
2423 # Show a hint to shared repo
2424 $file = wfFindFile( $this->mTitle
);
2425 if ( $file && !$file->isLocal() ) {
2426 $descUrl = $file->getDescriptionUrl();
2427 # there must be a description url to show a hint to shared repo
2429 if ( !$this->mTitle
->exists() ) {
2430 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2431 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2434 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2435 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2442 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2443 # Show log extract when the user is currently blocked
2444 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2445 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2446 $user = User
::newFromName( $username, false /* allow IP users */ );
2447 $ip = User
::isIP( $username );
2448 $block = Block
::newFromTarget( $user, $user );
2449 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2450 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2451 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2452 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2453 # Show log extract if the user is currently blocked
2454 LogEventsList
::showLogExtract(
2457 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2461 'showIfEmpty' => false,
2463 'blocked-notice-logextract',
2464 $user->getName() # Support GENDER in notice
2470 # Try to add a custom edit intro, or use the standard one if this is not possible.
2471 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2472 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2473 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2475 if ( $this->context
->getUser()->isLoggedIn() ) {
2477 // Suppress the external link icon, consider the help url an internal one
2478 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2486 // Suppress the external link icon, consider the help url an internal one
2487 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2489 'newarticletextanon',
2495 # Give a notice if the user is editing a deleted/moved page...
2496 if ( !$this->mTitle
->exists() ) {
2497 $dbr = wfGetDB( DB_REPLICA
);
2499 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2503 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2504 'showIfEmpty' => false,
2505 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2512 * Attempt to show a custom editing introduction, if supplied
2516 protected function showCustomIntro() {
2517 if ( $this->editintro
) {
2518 $title = Title
::newFromText( $this->editintro
);
2519 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2520 // Added using template syntax, to take <noinclude>'s into account.
2521 $this->context
->getOutput()->addWikiTextTitleTidy(
2522 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2532 * Gets an editable textual representation of $content.
2533 * The textual representation can be turned by into a Content object by the
2534 * toEditContent() method.
2536 * If $content is null or false or a string, $content is returned unchanged.
2538 * If the given Content object is not of a type that can be edited using
2539 * the text base EditPage, an exception will be raised. Set
2540 * $this->allowNonTextContent to true to allow editing of non-textual
2543 * @param Content|null|bool|string $content
2544 * @return string The editable text form of the content.
2546 * @throws MWException If $content is not an instance of TextContent and
2547 * $this->allowNonTextContent is not true.
2549 protected function toEditText( $content ) {
2550 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2554 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2555 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2558 return $content->serialize( $this->contentFormat
);
2562 * Turns the given text into a Content object by unserializing it.
2564 * If the resulting Content object is not of a type that can be edited using
2565 * the text base EditPage, an exception will be raised. Set
2566 * $this->allowNonTextContent to true to allow editing of non-textual
2569 * @param string|null|bool $text Text to unserialize
2570 * @return Content|bool|null The content object created from $text. If $text was false
2571 * or null, false resp. null will be returned instead.
2573 * @throws MWException If unserializing the text results in a Content
2574 * object that is not an instance of TextContent and
2575 * $this->allowNonTextContent is not true.
2577 protected function toEditContent( $text ) {
2578 if ( $text === false ||
$text === null ) {
2582 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2583 $this->contentModel
, $this->contentFormat
);
2585 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2586 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2593 * Send the edit form and related headers to OutputPage
2594 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2595 * during form output near the top, for captchas and the like.
2597 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2598 * use the EditPage::showEditForm:fields hook instead.
2600 public function showEditForm( $formCallback = null ) {
2601 # need to parse the preview early so that we know which templates are used,
2602 # otherwise users with "show preview after edit box" will get a blank list
2603 # we parse this near the beginning so that setHeaders can do the title
2604 # setting work instead of leaving it in getPreviewText
2605 $previewOutput = '';
2606 if ( $this->formtype
== 'preview' ) {
2607 $previewOutput = $this->getPreviewText();
2610 $out = $this->context
->getOutput();
2612 // Avoid PHP 7.1 warning of passing $this by reference
2614 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2616 $this->setHeaders();
2618 $this->addTalkPageText();
2619 $this->addEditNotices();
2621 if ( !$this->isConflict
&&
2622 $this->section
!= '' &&
2623 !$this->isSectionEditSupported() ) {
2624 // We use $this->section to much before this and getVal('wgSection') directly in other places
2625 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2626 // Someone is welcome to try refactoring though
2627 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2631 $this->showHeader();
2633 $out->addHTML( $this->editFormPageTop
);
2635 $user = $this->context
->getUser();
2636 if ( $user->getOption( 'previewontop' ) ) {
2637 $this->displayPreviewArea( $previewOutput, true );
2640 $out->addHTML( $this->editFormTextTop
);
2642 $showToolbar = true;
2643 if ( $this->wasDeletedSinceLastEdit() ) {
2644 if ( $this->formtype
== 'save' ) {
2645 // Hide the toolbar and edit area, user can click preview to get it back
2646 // Add an confirmation checkbox and explanation.
2647 $showToolbar = false;
2649 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2650 'deletedwhileediting' );
2654 // @todo add EditForm plugin interface and use it here!
2655 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2656 $out->addHTML( Html
::openElement(
2659 'class' => 'mw-editform',
2660 'id' => self
::EDITFORM_ID
,
2661 'name' => self
::EDITFORM_ID
,
2663 'action' => $this->getActionURL( $this->getContextTitle() ),
2664 'enctype' => 'multipart/form-data'
2668 if ( is_callable( $formCallback ) ) {
2669 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2670 call_user_func_array( $formCallback, [ &$out ] );
2673 // Add an empty field to trip up spambots
2675 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2678 [ 'for' => 'wpAntispam' ],
2679 $this->context
->msg( 'simpleantispam-label' )->parse()
2685 'name' => 'wpAntispam',
2686 'id' => 'wpAntispam',
2690 . Xml
::closeElement( 'div' )
2693 // Avoid PHP 7.1 warning of passing $this by reference
2695 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2697 // Put these up at the top to ensure they aren't lost on early form submission
2698 $this->showFormBeforeText();
2700 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2701 $username = $this->lastDelete
->user_name
;
2702 $comment = CommentStore
::newKey( 'log_comment' )->getComment( $this->lastDelete
)->text
;
2704 // It is better to not parse the comment at all than to have templates expanded in the middle
2705 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2706 $key = $comment === ''
2707 ?
'confirmrecreate-noreason'
2708 : 'confirmrecreate';
2710 '<div class="mw-confirm-recreate">' .
2711 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2712 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2713 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2719 # When the summary is hidden, also hide them on preview/show changes
2720 if ( $this->nosummary
) {
2721 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2724 # If a blank edit summary was previously provided, and the appropriate
2725 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2726 # user being bounced back more than once in the event that a summary
2729 # For a bit more sophisticated detection of blank summaries, hash the
2730 # automatic one and pass that in the hidden field wpAutoSummary.
2731 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2732 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2735 if ( $this->undidRev
) {
2736 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2739 if ( $this->selfRedirect
) {
2740 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2743 if ( $this->hasPresetSummary
) {
2744 // If a summary has been preset using &summary= we don't want to prompt for
2745 // a different summary. Only prompt for a summary if the summary is blanked.
2747 $this->autoSumm
= md5( '' );
2750 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2751 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2753 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2754 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2756 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2757 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2761 if ( $this->section
== 'new' ) {
2762 $this->showSummaryInput( true, $this->summary
);
2763 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2766 $out->addHTML( $this->editFormTextBeforeContent
);
2768 if ( !$this->isCssJsSubpage
&& $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2769 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2772 if ( $this->blankArticle
) {
2773 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2776 if ( $this->isConflict
) {
2777 // In an edit conflict bypass the overridable content form method
2778 // and fallback to the raw wpTextbox1 since editconflicts can't be
2779 // resolved between page source edits and custom ui edits using the
2781 $this->textbox2
= $this->textbox1
;
2783 $content = $this->getCurrentContent();
2784 $this->textbox1
= $this->toEditText( $content );
2786 $this->showTextbox1();
2788 $this->showContentForm();
2791 $out->addHTML( $this->editFormTextAfterContent
);
2793 $this->showStandardInputs();
2795 $this->showFormAfterText();
2797 $this->showTosSummary();
2799 $this->showEditTools();
2801 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2803 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2805 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2806 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2808 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2809 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2811 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2813 if ( $this->isConflict
) {
2815 $this->showConflict();
2816 } catch ( MWContentSerializationException
$ex ) {
2817 // this can't really happen, but be nice if it does.
2818 $msg = $this->context
->msg(
2819 'content-failed-to-parse',
2820 $this->contentModel
,
2821 $this->contentFormat
,
2824 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2828 // Set a hidden field so JS knows what edit form mode we are in
2829 if ( $this->isConflict
) {
2831 } elseif ( $this->preview
) {
2833 } elseif ( $this->diff
) {
2838 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2840 // Marker for detecting truncated form data. This must be the last
2841 // parameter sent in order to be of use, so do not move me.
2842 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2843 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2845 if ( !$user->getOption( 'previewontop' ) ) {
2846 $this->displayPreviewArea( $previewOutput, false );
2851 * Wrapper around TemplatesOnThisPageFormatter to make
2852 * a "templates on this page" list.
2854 * @param Title[] $templates
2855 * @return string HTML
2857 public function makeTemplatesOnThisPageList( array $templates ) {
2858 $templateListFormatter = new TemplatesOnThisPageFormatter(
2859 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2862 // preview if preview, else section if section, else false
2864 if ( $this->preview
) {
2866 } elseif ( $this->section
!= '' ) {
2870 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2871 $templateListFormatter->format( $templates, $type )
2876 * Extract the section title from current section text, if any.
2878 * @param string $text
2879 * @return string|bool String or false
2881 public static function extractSectionTitle( $text ) {
2882 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2883 if ( !empty( $matches[2] ) ) {
2885 return $wgParser->stripSectionName( trim( $matches[2] ) );
2891 protected function showHeader() {
2892 global $wgAllowUserCss, $wgAllowUserJs;
2894 $out = $this->context
->getOutput();
2895 $user = $this->context
->getUser();
2896 if ( $this->isConflict
) {
2897 $this->addExplainConflictHeader( $out );
2898 $this->editRevId
= $this->page
->getLatest();
2900 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2901 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2902 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2903 if ( $sectionTitle !== false ) {
2904 $this->summary
= "/* $sectionTitle */ ";
2909 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
2911 if ( $this->missingComment
) {
2912 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2915 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2917 "<div id='mw-missingsummary'>\n$1\n</div>",
2918 [ 'missingsummary', $buttonLabel ]
2922 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2924 "<div id='mw-missingcommentheader'>\n$1\n</div>",
2925 [ 'missingcommentheader', $buttonLabel ]
2929 if ( $this->blankArticle
) {
2931 "<div id='mw-blankarticle'>\n$1\n</div>",
2932 [ 'blankarticle', $buttonLabel ]
2936 if ( $this->selfRedirect
) {
2938 "<div id='mw-selfredirect'>\n$1\n</div>",
2939 [ 'selfredirect', $buttonLabel ]
2943 if ( $this->hookError
!== '' ) {
2944 $out->addWikiText( $this->hookError
);
2947 if ( !$this->checkUnicodeCompliantBrowser() ) {
2948 $out->addWikiMsg( 'nonunicodebrowser' );
2951 if ( $this->section
!= 'new' ) {
2952 $revision = $this->mArticle
->getRevisionFetched();
2954 // Let sysop know that this will make private content public if saved
2956 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
2958 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2959 'rev-deleted-text-permission'
2961 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2963 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2964 'rev-deleted-text-view'
2968 if ( !$revision->isCurrent() ) {
2969 $this->mArticle
->setOldSubtitle( $revision->getId() );
2970 $out->addWikiMsg( 'editingold' );
2971 $this->isOldRev
= true;
2973 } elseif ( $this->mTitle
->exists() ) {
2974 // Something went wrong
2976 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2977 [ 'missing-revision', $this->oldid
] );
2982 if ( wfReadOnly() ) {
2984 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2985 [ 'readonlywarning', wfReadOnlyReason() ]
2987 } elseif ( $user->isAnon() ) {
2988 if ( $this->formtype
!= 'preview' ) {
2990 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
2991 [ 'anoneditwarning',
2993 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
2994 'returnto' => $this->getTitle()->getPrefixedDBkey()
2997 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
2998 'returnto' => $this->getTitle()->getPrefixedDBkey()
3003 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3004 'anonpreviewwarning'
3008 if ( $this->isCssJsSubpage
) {
3009 # Check the skin exists
3010 if ( $this->isWrongCaseCssJsPage
) {
3012 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
3013 [ 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ]
3016 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3017 $out->wrapWikiMsg( '<div class="mw-usercssjspublic">$1</div>',
3018 $this->isCssSubpage ?
'usercssispublic' : 'userjsispublic'
3020 if ( $this->formtype
!== 'preview' ) {
3021 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
3023 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3024 [ 'usercssyoucanpreview' ]
3028 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
3030 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3031 [ 'userjsyoucanpreview' ]
3039 $this->addPageProtectionWarningHeaders();
3041 $this->addLongPageWarningHeader();
3043 # Add header copyright warning
3044 $this->showHeaderCopyrightWarning();
3048 * Helper function for summary input functions, which returns the neccessary
3049 * attributes for the input.
3051 * @param array|null $inputAttrs Array of attrs to use on the input
3054 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3055 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
3056 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3057 'id' => 'wpSummary',
3058 'name' => 'wpSummary',
3059 'maxlength' => '200',
3062 'spellcheck' => 'true',
3067 * Standard summary input and label (wgSummary), abstracted so EditPage
3068 * subclasses may reorganize the form.
3069 * Note that you do not need to worry about the label's for=, it will be
3070 * inferred by the id given to the input. You can remove them both by
3071 * passing [ 'id' => false ] to $userInputAttrs.
3073 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3074 * @param string $summary The value of the summary input
3075 * @param string $labelText The html to place inside the label
3076 * @param array $inputAttrs Array of attrs to use on the input
3077 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
3078 * @return array An array in the format [ $label, $input ]
3080 public function getSummaryInput( $summary = "", $labelText = null,
3081 $inputAttrs = null, $spanLabelAttrs = null
3083 wfDeprecated( __METHOD__
, '1.30' );
3084 $inputAttrs = $this->getSummaryInputAttributes( $inputAttrs );
3085 $inputAttrs +
= Linker
::tooltipAndAccesskeyAttribs( 'summary' );
3087 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : [] ) +
[
3088 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
3089 'id' => "wpSummaryLabel"
3096 $inputAttrs['id'] ?
[ 'for' => $inputAttrs['id'] ] : null,
3099 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
3102 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
3104 return [ $label, $input ];
3108 * Builds a standard summary input with a label.
3110 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3111 * @param string $summary The value of the summary input
3112 * @param string $labelText The html to place inside the label
3113 * @param array $inputAttrs Array of attrs to use on the input
3115 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3117 function getSummaryInputOOUI( $summary = "", $labelText = null, $inputAttrs = null ) {
3118 wfDeprecated( __METHOD__
, '1.30' );
3119 $this->getSummaryInputWidget( $summary, $labelText, $inputAttrs );
3123 * Builds a standard summary input with a label.
3125 * @param string $summary The value of the summary input
3126 * @param string $labelText The html to place inside the label
3127 * @param array $inputAttrs Array of attrs to use on the input
3129 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3131 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3132 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3133 $this->getSummaryInputAttributes( $inputAttrs )
3136 'title' => Linker
::titleAttrib( 'summary' ),
3137 'accessKey' => Linker
::accesskey( 'summary' ),
3140 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3141 $inputAttrs['inputId'] = $inputAttrs['id'];
3142 $inputAttrs['id'] = 'wpSummaryWidget';
3144 return new OOUI\
FieldLayout(
3145 new OOUI\
TextInputWidget( [
3146 'value' => $summary,
3147 'infusable' => true,
3150 'label' => new OOUI\
HtmlSnippet( $labelText ),
3152 'id' => 'wpSummaryLabel',
3153 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3159 * @param bool $isSubjectPreview True if this is the section subject/title
3160 * up top, or false if this is the comment summary
3161 * down below the textarea
3162 * @param string $summary The text of the summary to display
3164 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3165 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3166 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3167 if ( $isSubjectPreview ) {
3168 if ( $this->nosummary
) {
3172 if ( !$this->mShowSummaryField
) {
3177 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3178 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3181 [ 'class' => $summaryClass ]
3186 * @param bool $isSubjectPreview True if this is the section subject/title
3187 * up top, or false if this is the comment summary
3188 * down below the textarea
3189 * @param string $summary The text of the summary to display
3192 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3193 // avoid spaces in preview, gets always trimmed on save
3194 $summary = trim( $summary );
3195 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3201 if ( $isSubjectPreview ) {
3202 $summary = $this->context
->msg( 'newsectionsummary' )
3203 ->rawParams( $wgParser->stripSectionName( $summary ) )
3204 ->inContentLanguage()->text();
3207 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3209 $summary = $this->context
->msg( $message )->parse()
3210 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3211 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3214 protected function showFormBeforeText() {
3215 $out = $this->context
->getOutput();
3216 $out->addHTML( Html
::hidden( 'wpSection', htmlspecialchars( $this->section
) ) );
3217 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3218 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3219 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3220 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3222 if ( !$this->checkUnicodeCompliantBrowser() ) {
3223 $out->addHTML( Html
::hidden( 'safemode', '1' ) );
3227 protected function showFormAfterText() {
3229 * To make it harder for someone to slip a user a page
3230 * which submits an edit form to the wiki without their
3231 * knowledge, a random token is associated with the login
3232 * session. If it's not passed back with the submission,
3233 * we won't save the page, or render user JavaScript and
3236 * For anon editors, who may not have a session, we just
3237 * include the constant suffix to prevent editing from
3238 * broken text-mangling proxies.
3240 $this->context
->getOutput()->addHTML(
3242 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3248 * Subpage overridable method for printing the form for page content editing
3249 * By default this simply outputs wpTextbox1
3250 * Subclasses can override this to provide a custom UI for editing;
3251 * be it a form, or simply wpTextbox1 with a modified content that will be
3252 * reverse modified when extracted from the post data.
3253 * Note that this is basically the inverse for importContentFormData
3255 protected function showContentForm() {
3256 $this->showTextbox1();
3260 * Method to output wpTextbox1
3261 * The $textoverride method can be used by subclasses overriding showContentForm
3262 * to pass back to this method.
3264 * @param array $customAttribs Array of html attributes to use in the textarea
3265 * @param string $textoverride Optional text to override $this->textarea1 with
3267 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3268 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3269 $attribs = [ 'style' => 'display:none;' ];
3271 $classes = []; // Textarea CSS
3272 if ( $this->mTitle
->isProtected( 'edit' ) &&
3273 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
3275 # Is the title semi-protected?
3276 if ( $this->mTitle
->isSemiProtected() ) {
3277 $classes[] = 'mw-textarea-sprotected';
3279 # Then it must be protected based on static groups (regular)
3280 $classes[] = 'mw-textarea-protected';
3282 # Is the title cascade-protected?
3283 if ( $this->mTitle
->isCascadeProtected() ) {
3284 $classes[] = 'mw-textarea-cprotected';
3287 # Is an old revision being edited?
3288 if ( $this->isOldRev
) {
3289 $classes[] = 'mw-textarea-oldrev';
3292 $attribs = [ 'tabindex' => 1 ];
3294 if ( is_array( $customAttribs ) ) {
3295 $attribs +
= $customAttribs;
3298 if ( count( $classes ) ) {
3299 if ( isset( $attribs['class'] ) ) {
3300 $classes[] = $attribs['class'];
3302 $attribs['class'] = implode( ' ', $classes );
3307 $textoverride !== null ?
$textoverride : $this->textbox1
,
3313 protected function showTextbox2() {
3314 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3317 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3318 $wikitext = $this->safeUnicodeOutput( $text );
3319 $wikitext = $this->addNewLineAtEnd( $wikitext );
3321 $attribs = $this->buildTextboxAttribs( $name, $customAttribs, $this->context
->getUser() );
3323 $this->context
->getOutput()->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3326 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3329 $classes[] = 'ontop';
3332 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3334 if ( $this->formtype
!= 'preview' ) {
3335 $attribs['style'] = 'display: none;';
3338 $out = $this->context
->getOutput();
3339 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3341 if ( $this->formtype
== 'preview' ) {
3342 $this->showPreview( $previewOutput );
3344 // Empty content container for LivePreview
3345 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3346 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3347 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3348 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3351 $out->addHTML( '</div>' );
3353 if ( $this->formtype
== 'diff' ) {
3356 } catch ( MWContentSerializationException
$ex ) {
3357 $msg = $this->context
->msg(
3358 'content-failed-to-parse',
3359 $this->contentModel
,
3360 $this->contentFormat
,
3363 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3369 * Append preview output to OutputPage.
3370 * Includes category rendering if this is a category page.
3372 * @param string $text The HTML to be output for the preview.
3374 protected function showPreview( $text ) {
3375 if ( $this->mArticle
instanceof CategoryPage
) {
3376 $this->mArticle
->openShowCategory();
3378 # This hook seems slightly odd here, but makes things more
3379 # consistent for extensions.
3380 $out = $this->context
->getOutput();
3381 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3382 $out->addHTML( $text );
3383 if ( $this->mArticle
instanceof CategoryPage
) {
3384 $this->mArticle
->closeShowCategory();
3389 * Get a diff between the current contents of the edit box and the
3390 * version of the page we're editing from.
3392 * If this is a section edit, we'll replace the section as for final
3393 * save and then make a comparison.
3395 public function showDiff() {
3398 $oldtitlemsg = 'currentrev';
3399 # if message does not exist, show diff against the preloaded default
3400 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3401 $oldtext = $this->mTitle
->getDefaultMessageText();
3402 if ( $oldtext !== false ) {
3403 $oldtitlemsg = 'defaultmessagetext';
3404 $oldContent = $this->toEditContent( $oldtext );
3409 $oldContent = $this->getCurrentContent();
3412 $textboxContent = $this->toEditContent( $this->textbox1
);
3413 if ( $this->editRevId
!== null ) {
3414 $newContent = $this->page
->replaceSectionAtRev(
3415 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3418 $newContent = $this->page
->replaceSectionContent(
3419 $this->section
, $textboxContent, $this->summary
, $this->edittime
3423 if ( $newContent ) {
3424 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3426 $user = $this->context
->getUser();
3427 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
3428 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3431 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3432 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3433 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3435 if ( !$oldContent ) {
3436 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3439 if ( !$newContent ) {
3440 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3443 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3444 $de->setContent( $oldContent, $newContent );
3446 $difftext = $de->getDiff( $oldtitle, $newtitle );
3447 $de->showDiffStyle();
3452 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3456 * Show the header copyright warning.
3458 protected function showHeaderCopyrightWarning() {
3459 $msg = 'editpage-head-copy-warn';
3460 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3461 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3462 'editpage-head-copy-warn' );
3467 * Give a chance for site and per-namespace customizations of
3468 * terms of service summary link that might exist separately
3469 * from the copyright notice.
3471 * This will display between the save button and the edit tools,
3472 * so should remain short!
3474 protected function showTosSummary() {
3475 $msg = 'editpage-tos-summary';
3476 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3477 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3478 $out = $this->context
->getOutput();
3479 $out->addHTML( '<div class="mw-tos-summary">' );
3480 $out->addWikiMsg( $msg );
3481 $out->addHTML( '</div>' );
3486 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3487 * characters not present on most keyboards for copying/pasting.
3489 protected function showEditTools() {
3490 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3491 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3496 * Get the copyright warning
3498 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3501 protected function getCopywarn() {
3502 return self
::getCopyrightWarning( $this->mTitle
);
3506 * Get the copyright warning, by default returns wikitext
3508 * @param Title $title
3509 * @param string $format Output format, valid values are any function of a Message object
3510 * @param Language|string|null $langcode Language code or Language object.
3513 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3514 global $wgRightsText;
3515 if ( $wgRightsText ) {
3516 $copywarnMsg = [ 'copyrightwarning',
3517 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3520 $copywarnMsg = [ 'copyrightwarning2',
3521 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3523 // Allow for site and per-namespace customization of contribution/copyright notice.
3524 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3526 $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
3528 $msg->inLanguage( $langcode );
3530 return "<div id=\"editpage-copywarn\">\n" .
3531 $msg->$format() . "\n</div>";
3535 * Get the Limit report for page previews
3538 * @param ParserOutput $output ParserOutput object from the parse
3539 * @return string HTML
3541 public static function getPreviewLimitReport( $output ) {
3542 if ( !$output ||
!$output->getLimitReportData() ) {
3546 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3547 wfMessage( 'limitreport-title' )->parseAsBlock()
3550 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3551 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3553 $limitReport .= Html
::openElement( 'table', [
3554 'class' => 'preview-limit-report wikitable'
3556 Html
::openElement( 'tbody' );
3558 foreach ( $output->getLimitReportData() as $key => $value ) {
3559 if ( Hooks
::run( 'ParserLimitReportFormat',
3560 [ $key, &$value, &$limitReport, true, true ]
3562 $keyMsg = wfMessage( $key );
3563 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3564 if ( !$valueMsg->exists() ) {
3565 $valueMsg = new RawMessage( '$1' );
3567 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3568 $limitReport .= Html
::openElement( 'tr' ) .
3569 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3570 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3571 Html
::closeElement( 'tr' );
3576 $limitReport .= Html
::closeElement( 'tbody' ) .
3577 Html
::closeElement( 'table' ) .
3578 Html
::closeElement( 'div' );
3580 return $limitReport;
3583 protected function showStandardInputs( &$tabindex = 2 ) {
3584 $out = $this->context
->getOutput();
3585 $out->addHTML( "<div class='editOptions'>\n" );
3587 if ( $this->section
!= 'new' ) {
3588 $this->showSummaryInput( false, $this->summary
);
3589 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3592 $checkboxes = $this->getCheckboxesWidget(
3594 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3596 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3598 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3600 // Show copyright warning.
3601 $out->addWikiText( $this->getCopywarn() );
3602 $out->addHTML( $this->editFormTextAfterWarn
);
3604 $out->addHTML( "<div class='editButtons'>\n" );
3605 $out->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3607 $cancel = $this->getCancelLink();
3608 if ( $cancel !== '' ) {
3609 $cancel .= Html
::element( 'span',
3610 [ 'class' => 'mw-editButtons-pipe-separator' ],
3611 $this->context
->msg( 'pipe-separator' )->text() );
3614 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3615 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3618 $this->context
->msg( 'edithelp' )->text(),
3619 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3622 $this->context
->msg( 'word-separator' )->escaped() .
3623 $this->context
->msg( 'newwindow' )->parse();
3625 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3626 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3627 $out->addHTML( "</div><!-- editButtons -->\n" );
3629 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3631 $out->addHTML( "</div><!-- editOptions -->\n" );
3635 * Show an edit conflict. textbox1 is already shown in showEditForm().
3636 * If you want to use another entry point to this function, be careful.
3638 protected function showConflict() {
3639 $out = $this->context
->getOutput();
3640 // Avoid PHP 7.1 warning of passing $this by reference
3642 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3643 $this->incrementConflictStats();
3645 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3647 $content1 = $this->toEditContent( $this->textbox1
);
3648 $content2 = $this->toEditContent( $this->textbox2
);
3650 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3651 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3652 $de->setContent( $content2, $content1 );
3654 $this->context
->msg( 'yourtext' )->parse(),
3655 $this->context
->msg( 'storedversion' )->text()
3658 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3659 $this->showTextbox2();
3663 protected function incrementConflictStats() {
3664 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3665 $stats->increment( 'edit.failures.conflict' );
3666 // Only include 'standard' namespaces to avoid creating unknown numbers of statsd metrics
3668 $this->mTitle
->getNamespace() >= NS_MAIN
&&
3669 $this->mTitle
->getNamespace() <= NS_CATEGORY_TALK
3671 $stats->increment( 'edit.failures.conflict.byNamespaceId.' . $this->mTitle
->getNamespace() );
3678 public function getCancelLink() {
3680 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3681 $cancelParams['oldid'] = $this->oldid
;
3682 } elseif ( $this->getContextTitle()->isRedirect() ) {
3683 $cancelParams['redirect'] = 'no';
3686 return new OOUI\
ButtonWidget( [
3687 'id' => 'mw-editform-cancel',
3688 'href' => $this->getContextTitle()->getLinkUrl( $cancelParams ),
3689 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3691 'infusable' => true,
3692 'flags' => 'destructive',
3697 * Returns the URL to use in the form's action attribute.
3698 * This is used by EditPage subclasses when simply customizing the action
3699 * variable in the constructor is not enough. This can be used when the
3700 * EditPage lives inside of a Special page rather than a custom page action.
3702 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3705 protected function getActionURL( Title
$title ) {
3706 return $title->getLocalURL( [ 'action' => $this->action
] );
3710 * Check if a page was deleted while the user was editing it, before submit.
3711 * Note that we rely on the logging table, which hasn't been always there,
3712 * but that doesn't matter, because this only applies to brand new
3716 protected function wasDeletedSinceLastEdit() {
3717 if ( $this->deletedSinceEdit
!== null ) {
3718 return $this->deletedSinceEdit
;
3721 $this->deletedSinceEdit
= false;
3723 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3724 $this->lastDelete
= $this->getLastDelete();
3725 if ( $this->lastDelete
) {
3726 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3727 if ( $deleteTime > $this->starttime
) {
3728 $this->deletedSinceEdit
= true;
3733 return $this->deletedSinceEdit
;
3737 * @return bool|stdClass
3739 protected function getLastDelete() {
3740 $dbr = wfGetDB( DB_REPLICA
);
3741 $commentQuery = CommentStore
::newKey( 'log_comment' )->getJoin();
3742 $data = $dbr->selectRow(
3743 [ 'logging', 'user' ] +
$commentQuery['tables'],
3754 ] +
$commentQuery['fields'], [
3755 'log_namespace' => $this->mTitle
->getNamespace(),
3756 'log_title' => $this->mTitle
->getDBkey(),
3757 'log_type' => 'delete',
3758 'log_action' => 'delete',
3762 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3764 'user' => [ 'JOIN', 'user_id=log_user' ],
3765 ] +
$commentQuery['joins']
3767 // Quick paranoid permission checks...
3768 if ( is_object( $data ) ) {
3769 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3770 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3773 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3774 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3775 $data->log_comment_data
= null;
3783 * Get the rendered text for previewing.
3784 * @throws MWException
3787 public function getPreviewText() {
3789 global $wgAllowUserCss, $wgAllowUserJs;
3791 $out = $this->context
->getOutput();
3793 if ( $wgRawHtml && !$this->mTokenOk
) {
3794 // Could be an offsite preview attempt. This is very unsafe if
3795 // HTML is enabled, as it could be an attack.
3797 if ( $this->textbox1
!== '' ) {
3798 // Do not put big scary notice, if previewing the empty
3799 // string, which happens when you initially edit
3800 // a category page, due to automatic preview-on-open.
3801 $parsedNote = $out->parse( "<div class='previewnote'>" .
3802 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3803 true, /* interface */true );
3805 $this->incrementEditFailureStats( 'session_loss' );
3812 $content = $this->toEditContent( $this->textbox1
);
3816 'AlternateEditPreview',
3817 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3819 return $previewHTML;
3822 # provide a anchor link to the editform
3823 $continueEditing = '<span class="mw-continue-editing">' .
3824 '[[#' . self
::EDITFORM_ID
. '|' .
3825 $this->context
->getLanguage()->getArrow() . ' ' .
3826 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3827 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3828 if ( $this->mTokenOkExceptSuffix
) {
3829 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3830 $this->incrementEditFailureStats( 'bad_token' );
3832 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3833 $this->incrementEditFailureStats( 'session_loss' );
3835 } elseif ( $this->incompleteForm
) {
3836 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3837 if ( $this->mTriedSave
) {
3838 $this->incrementEditFailureStats( 'incomplete_form' );
3841 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3844 # don't parse non-wikitext pages, show message about preview
3845 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3846 if ( $this->mTitle
->isCssJsSubpage() ) {
3848 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3854 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3856 if ( $level === 'user' && !$wgAllowUserCss ) {
3859 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3861 if ( $level === 'user' && !$wgAllowUserJs ) {
3868 # Used messages to make sure grep find them:
3869 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3870 if ( $level && $format ) {
3871 $note = "<div id='mw-{$level}{$format}preview'>" .
3872 $this->context
->msg( "{$level}{$format}preview" )->text() .
3873 ' ' . $continueEditing . "</div>";
3877 # If we're adding a comment, we need to show the
3878 # summary as the headline
3879 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3880 $content = $content->addSectionHeader( $this->summary
);
3883 $hook_args = [ $this, &$content ];
3884 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3886 $parserResult = $this->doPreviewParse( $content );
3887 $parserOutput = $parserResult['parserOutput'];
3888 $previewHTML = $parserResult['html'];
3889 $this->mParserOutput
= $parserOutput;
3890 $out->addParserOutputMetadata( $parserOutput );
3892 if ( count( $parserOutput->getWarnings() ) ) {
3893 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3896 } catch ( MWContentSerializationException
$ex ) {
3897 $m = $this->context
->msg(
3898 'content-failed-to-parse',
3899 $this->contentModel
,
3900 $this->contentFormat
,
3903 $note .= "\n\n" . $m->parse();
3907 if ( $this->isConflict
) {
3908 $conflict = '<h2 id="mw-previewconflict">'
3909 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3911 $conflict = '<hr />';
3914 $previewhead = "<div class='previewnote'>\n" .
3915 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3916 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3918 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3919 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3920 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3921 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3923 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3926 private function incrementEditFailureStats( $failureType ) {
3927 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3928 $stats->increment( 'edit.failures.' . $failureType );
3932 * Get parser options for a preview
3933 * @return ParserOptions
3935 protected function getPreviewParserOptions() {
3936 $parserOptions = $this->page
->makeParserOptions( $this->mArticle
->getContext() );
3937 $parserOptions->setIsPreview( true );
3938 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3939 $parserOptions->enableLimitReport();
3940 return $parserOptions;
3944 * Parse the page for a preview. Subclasses may override this class, in order
3945 * to parse with different options, or to otherwise modify the preview HTML.
3947 * @param Content $content The page content
3948 * @return array with keys:
3949 * - parserOutput: The ParserOutput object
3950 * - html: The HTML to be displayed
3952 protected function doPreviewParse( Content
$content ) {
3953 $user = $this->context
->getUser();
3954 $parserOptions = $this->getPreviewParserOptions();
3955 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
3956 $scopedCallback = $parserOptions->setupFakeRevision(
3957 $this->mTitle
, $pstContent, $user );
3958 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3959 ScopedCallback
::consume( $scopedCallback );
3960 $parserOutput->setEditSectionTokens( false ); // no section edit links
3962 'parserOutput' => $parserOutput,
3963 'html' => $parserOutput->getText() ];
3969 public function getTemplates() {
3970 if ( $this->preview ||
$this->section
!= '' ) {
3972 if ( !isset( $this->mParserOutput
) ) {
3975 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3976 foreach ( array_keys( $template ) as $dbk ) {
3977 $templates[] = Title
::makeTitle( $ns, $dbk );
3982 return $this->mTitle
->getTemplateLinksFrom();
3987 * Shows a bulletin board style toolbar for common editing functions.
3988 * It can be disabled in the user preferences.
3990 * @param Title $title Title object for the page being edited (optional)
3993 public static function getEditToolbar( $title = null ) {
3994 global $wgContLang, $wgOut;
3995 global $wgEnableUploads, $wgForeignFileRepos;
3997 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3998 $showSignature = true;
4000 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4004 * $toolarray is an array of arrays each of which includes the
4005 * opening tag, the closing tag, optionally a sample text that is
4006 * inserted between the two when no selection is highlighted
4007 * and. The tip text is shown when the user moves the mouse
4010 * Images are defined in ResourceLoaderEditToolbarModule.
4014 'id' => 'mw-editbutton-bold',
4016 'close' => '\'\'\'',
4017 'sample' => wfMessage( 'bold_sample' )->text(),
4018 'tip' => wfMessage( 'bold_tip' )->text(),
4021 'id' => 'mw-editbutton-italic',
4024 'sample' => wfMessage( 'italic_sample' )->text(),
4025 'tip' => wfMessage( 'italic_tip' )->text(),
4028 'id' => 'mw-editbutton-link',
4031 'sample' => wfMessage( 'link_sample' )->text(),
4032 'tip' => wfMessage( 'link_tip' )->text(),
4035 'id' => 'mw-editbutton-extlink',
4038 'sample' => wfMessage( 'extlink_sample' )->text(),
4039 'tip' => wfMessage( 'extlink_tip' )->text(),
4042 'id' => 'mw-editbutton-headline',
4045 'sample' => wfMessage( 'headline_sample' )->text(),
4046 'tip' => wfMessage( 'headline_tip' )->text(),
4048 $imagesAvailable ?
[
4049 'id' => 'mw-editbutton-image',
4050 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4052 'sample' => wfMessage( 'image_sample' )->text(),
4053 'tip' => wfMessage( 'image_tip' )->text(),
4055 $imagesAvailable ?
[
4056 'id' => 'mw-editbutton-media',
4057 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4059 'sample' => wfMessage( 'media_sample' )->text(),
4060 'tip' => wfMessage( 'media_tip' )->text(),
4063 'id' => 'mw-editbutton-nowiki',
4064 'open' => "<nowiki>",
4065 'close' => "</nowiki>",
4066 'sample' => wfMessage( 'nowiki_sample' )->text(),
4067 'tip' => wfMessage( 'nowiki_tip' )->text(),
4070 'id' => 'mw-editbutton-signature',
4071 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4074 'tip' => wfMessage( 'sig_tip' )->text(),
4077 'id' => 'mw-editbutton-hr',
4078 'open' => "\n----\n",
4081 'tip' => wfMessage( 'hr_tip' )->text(),
4085 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4086 foreach ( $toolarray as $tool ) {
4092 // Images are defined in ResourceLoaderEditToolbarModule
4094 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4095 // Older browsers show a "speedtip" type message only for ALT.
4096 // Ideally these should be different, realistically they
4097 // probably don't need to be.
4105 $script .= Xml
::encodeJsCall(
4106 'mw.toolbar.addButton',
4108 ResourceLoader
::inDebugMode()
4114 $toolbar = '<div id="toolbar"></div>';
4116 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4117 // Only add the old toolbar cruft to the page payload if the toolbar has not
4118 // been over-written by a hook caller
4119 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
4126 * Return an array of checkbox definitions.
4128 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4130 * Array values are associative arrays with the following keys:
4131 * - 'label-message' (required): message for label text
4132 * - 'id' (required): 'id' attribute for the `<input>`
4133 * - 'default' (required): default checkedness (true or false)
4134 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4135 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4136 * from messages like 'tooltip-foo', 'accesskey-foo'
4137 * - 'label-id' (optional): 'id' attribute for the `<label>`
4138 * - 'legacy-name' (optional): short name for backwards-compatibility
4139 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4140 * where bool indicates the checked status of the checkbox
4143 public function getCheckboxesDefinition( $checked ) {
4146 $user = $this->context
->getUser();
4147 // don't show the minor edit checkbox if it's a new page or section
4148 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4149 $checkboxes['wpMinoredit'] = [
4150 'id' => 'wpMinoredit',
4151 'label-message' => 'minoredit',
4152 // Uses messages: tooltip-minoredit, accesskey-minoredit
4153 'tooltip' => 'minoredit',
4154 'label-id' => 'mw-editpage-minoredit',
4155 'legacy-name' => 'minor',
4156 'default' => $checked['minor'],
4160 if ( $user->isLoggedIn() ) {
4161 $checkboxes['wpWatchthis'] = [
4162 'id' => 'wpWatchthis',
4163 'label-message' => 'watchthis',
4164 // Uses messages: tooltip-watch, accesskey-watch
4165 'tooltip' => 'watch',
4166 'label-id' => 'mw-editpage-watch',
4167 'legacy-name' => 'watch',
4168 'default' => $checked['watch'],
4173 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4179 * Returns an array of html code of the following checkboxes old style:
4182 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4183 * @param int &$tabindex Current tabindex
4184 * @param array $checked See getCheckboxesDefinition()
4187 public function getCheckboxes( &$tabindex, $checked ) {
4189 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4191 // Backwards-compatibility for the EditPageBeforeEditChecks hook
4192 if ( !$this->isNew
) {
4193 $checkboxes['minor'] = '';
4195 $checkboxes['watch'] = '';
4197 foreach ( $checkboxesDef as $name => $options ) {
4198 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4199 $label = $this->context
->msg( $options['label-message'] )->parse();
4201 'tabindex' => ++
$tabindex,
4202 'id' => $options['id'],
4205 'for' => $options['id'],
4207 if ( isset( $options['tooltip'] ) ) {
4208 $attribs['accesskey'] = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4209 $labelAttribs['title'] = Linker
::titleAttrib( $options['tooltip'], 'withaccess' );
4211 if ( isset( $options['title-message'] ) ) {
4212 $labelAttribs['title'] = $this->context
->msg( $options['title-message'] )->text();
4214 if ( isset( $options['label-id'] ) ) {
4215 $labelAttribs['id'] = $options['label-id'];
4218 Xml
::check( $name, $options['default'], $attribs ) .
4220 Xml
::tags( 'label', $labelAttribs, $label );
4222 $checkboxes[ $legacyName ] = $checkboxHtml;
4225 // Avoid PHP 7.1 warning of passing $this by reference
4227 Hooks
::run( 'EditPageBeforeEditChecks', [ &$editPage, &$checkboxes, &$tabindex ], '1.29' );
4232 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4233 * any other added by extensions.
4235 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4236 * @param int &$tabindex Current tabindex
4237 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4238 * status of the checkbox
4240 * @return array Associative array of string keys to OOUI\FieldLayout instances
4242 public function getCheckboxesOOUI( &$tabindex, $checked ) {
4243 return $this->getCheckboxesWidget( $tabindex, $checked );
4247 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4248 * any other added by extensions.
4250 * @param int &$tabindex Current tabindex
4251 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4252 * status of the checkbox
4254 * @return array Associative array of string keys to OOUI\FieldLayout instances
4256 public function getCheckboxesWidget( &$tabindex, $checked ) {
4258 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4260 foreach ( $checkboxesDef as $name => $options ) {
4261 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4265 if ( isset( $options['tooltip'] ) ) {
4266 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4267 $title = Linker
::titleAttrib( $options['tooltip'] );
4269 if ( isset( $options['title-message'] ) ) {
4270 $title = $this->context
->msg( $options['title-message'] )->text();
4273 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4274 new OOUI\
CheckboxInputWidget( [
4275 'tabIndex' => ++
$tabindex,
4276 'accessKey' => $accesskey,
4277 'id' => $options['id'] . 'Widget',
4278 'inputId' => $options['id'],
4280 'selected' => $options['default'],
4281 'infusable' => true,
4284 'align' => 'inline',
4285 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4287 'id' => isset( $options['label-id'] ) ?
$options['label-id'] : null,
4292 // Backwards-compatibility hack to run the EditPageBeforeEditChecks hook. It's important,
4293 // people have used it for the weirdest things completely unrelated to checkboxes...
4294 // And if we're gonna run it, might as well allow its legacy checkboxes to be shown.
4295 $legacyCheckboxes = [];
4296 if ( !$this->isNew
) {
4297 $legacyCheckboxes['minor'] = '';
4299 $legacyCheckboxes['watch'] = '';
4300 // Copy new-style checkboxes into an old-style structure
4301 foreach ( $checkboxes as $name => $oouiLayout ) {
4302 $legacyCheckboxes[$name] = (string)$oouiLayout;
4304 // Avoid PHP 7.1 warning of passing $this by reference
4306 Hooks
::run( 'EditPageBeforeEditChecks', [ &$ep, &$legacyCheckboxes, &$tabindex ], '1.29' );
4307 // Copy back any additional old-style checkboxes into the new-style structure
4308 foreach ( $legacyCheckboxes as $name => $html ) {
4309 if ( $html && !isset( $checkboxes[$name] ) ) {
4310 $checkboxes[$name] = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $html ) ] );
4318 * Get the message key of the label for the button to save the page
4322 protected function getSubmitButtonLabel() {
4324 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4326 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4327 $newPage = !$this->mTitle
->exists();
4329 if ( $labelAsPublish ) {
4330 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4332 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4335 return $buttonLabelKey;
4339 * Returns an array of html code of the following buttons:
4340 * save, diff and preview
4342 * @param int &$tabindex Current tabindex
4346 public function getEditButtons( &$tabindex ) {
4349 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4353 'tabindex' => ++
$tabindex,
4356 $saveConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4357 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4358 'id' => 'wpSaveWidget',
4359 'inputId' => 'wpSave',
4360 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4361 'useInputTag' => true,
4362 'flags' => [ 'constructive', 'primary' ],
4363 'label' => $buttonLabel,
4364 'infusable' => true,
4366 'title' => Linker
::titleAttrib( 'save' ),
4367 'accessKey' => Linker
::accesskey( 'save' ),
4371 'name' => 'wpPreview',
4372 'tabindex' => ++
$tabindex,
4375 $previewConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4376 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4377 'id' => 'wpPreviewWidget',
4378 'inputId' => 'wpPreview',
4379 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4380 'useInputTag' => true,
4381 'label' => $this->context
->msg( 'showpreview' )->text(),
4382 'infusable' => true,
4384 'title' => Linker
::titleAttrib( 'preview' ),
4385 'accessKey' => Linker
::accesskey( 'preview' ),
4386 ] +
$previewConfig );
4390 'tabindex' => ++
$tabindex,
4393 $diffConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4394 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4395 'id' => 'wpDiffWidget',
4396 'inputId' => 'wpDiff',
4397 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4398 'useInputTag' => true,
4399 'label' => $this->context
->msg( 'showdiff' )->text(),
4400 'infusable' => true,
4402 'title' => Linker
::titleAttrib( 'diff' ),
4403 'accessKey' => Linker
::accesskey( 'diff' ),
4406 // Avoid PHP 7.1 warning of passing $this by reference
4408 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4414 * Creates a basic error page which informs the user that
4415 * they have attempted to edit a nonexistent section.
4417 public function noSuchSectionPage() {
4418 $out = $this->context
->getOutput();
4419 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4421 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4423 // Avoid PHP 7.1 warning of passing $this by reference
4425 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4426 $out->addHTML( $res );
4428 $out->returnToMain( false, $this->mTitle
);
4432 * Show "your edit contains spam" page with your diff and text
4434 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4436 public function spamPageWithContent( $match = false ) {
4437 $this->textbox2
= $this->textbox1
;
4439 if ( is_array( $match ) ) {
4440 $match = $this->context
->getLanguage()->listToText( $match );
4442 $out = $this->context
->getOutput();
4443 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4445 $out->addHTML( '<div id="spamprotected">' );
4446 $out->addWikiMsg( 'spamprotectiontext' );
4448 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4450 $out->addHTML( '</div>' );
4452 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4455 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4456 $this->showTextbox2();
4458 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4462 * Check if the browser is on a blacklist of user-agents known to
4463 * mangle UTF-8 data on form submission. Returns true if Unicode
4464 * should make it through, false if it's known to be a problem.
4467 private function checkUnicodeCompliantBrowser() {
4468 global $wgBrowserBlackList, $wgRequest;
4470 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
4471 if ( $currentbrowser === false ) {
4472 // No User-Agent header sent? Trust it by default...
4476 foreach ( $wgBrowserBlackList as $browser ) {
4477 if ( preg_match( $browser, $currentbrowser ) ) {
4485 * Filter an input field through a Unicode de-armoring process if it
4486 * came from an old browser with known broken Unicode editing issues.
4488 * @param WebRequest $request
4489 * @param string $field
4492 protected function safeUnicodeInput( $request, $field ) {
4493 $text = rtrim( $request->getText( $field ) );
4494 return $request->getBool( 'safemode' )
4495 ?
$this->unmakeSafe( $text )
4500 * Filter an output field through a Unicode armoring process if it is
4501 * going to an old browser with known broken Unicode editing issues.
4503 * @param string $text
4506 protected function safeUnicodeOutput( $text ) {
4507 return $this->checkUnicodeCompliantBrowser()
4509 : $this->makeSafe( $text );
4513 * A number of web browsers are known to corrupt non-ASCII characters
4514 * in a UTF-8 text editing environment. To protect against this,
4515 * detected browsers will be served an armored version of the text,
4516 * with non-ASCII chars converted to numeric HTML character references.
4518 * Preexisting such character references will have a 0 added to them
4519 * to ensure that round-trips do not alter the original data.
4521 * @param string $invalue
4524 private function makeSafe( $invalue ) {
4525 // Armor existing references for reversibility.
4526 $invalue = strtr( $invalue, [ "&#x" => "�" ] );
4531 $valueLength = strlen( $invalue );
4532 for ( $i = 0; $i < $valueLength; $i++
) {
4533 $bytevalue = ord( $invalue[$i] );
4534 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4535 $result .= chr( $bytevalue );
4537 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4538 $working = $working << 6;
4539 $working +
= ( $bytevalue & 0x3F );
4541 if ( $bytesleft <= 0 ) {
4542 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4544 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4545 $working = $bytevalue & 0x1F;
4547 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4548 $working = $bytevalue & 0x0F;
4550 } else { // 1111 0xxx
4551 $working = $bytevalue & 0x07;
4559 * Reverse the previously applied transliteration of non-ASCII characters
4560 * back to UTF-8. Used to protect data from corruption by broken web browsers
4561 * as listed in $wgBrowserBlackList.
4563 * @param string $invalue
4566 private function unmakeSafe( $invalue ) {
4568 $valueLength = strlen( $invalue );
4569 for ( $i = 0; $i < $valueLength; $i++
) {
4570 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4574 $hexstring .= $invalue[$i];
4576 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4578 // Do some sanity checks. These aren't needed for reversibility,
4579 // but should help keep the breakage down if the editor
4580 // breaks one of the entities whilst editing.
4581 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4582 $codepoint = hexdec( $hexstring );
4583 $result .= UtfNormal\Utils
::codepointToUtf8( $codepoint );
4585 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4588 $result .= substr( $invalue, $i, 1 );
4591 // reverse the transform that we made for reversibility reasons.
4592 return strtr( $result, [ "�" => "&#x" ] );
4598 protected function addEditNotices() {
4599 $out = $this->context
->getOutput();
4600 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4601 if ( count( $editNotices ) ) {
4602 $out->addHTML( implode( "\n", $editNotices ) );
4604 $msg = $this->context
->msg( 'editnotice-notext' );
4605 if ( !$msg->isDisabled() ) {
4607 '<div class="mw-editnotice-notext">'
4608 . $msg->parseAsBlock()
4618 protected function addTalkPageText() {
4619 if ( $this->mTitle
->isTalkPage() ) {
4620 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4627 protected function addLongPageWarningHeader() {
4628 global $wgMaxArticleSize;
4630 if ( $this->contentLength
=== false ) {
4631 $this->contentLength
= strlen( $this->textbox1
);
4634 $out = $this->context
->getOutput();
4635 $lang = $this->context
->getLanguage();
4636 if ( $this->tooBig ||
$this->contentLength
> $wgMaxArticleSize * 1024 ) {
4637 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4640 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4641 $lang->formatNum( $wgMaxArticleSize )
4645 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4646 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4649 $lang->formatSize( strlen( $this->textbox1
) ),
4650 strlen( $this->textbox1
)
4660 protected function addPageProtectionWarningHeaders() {
4661 $out = $this->context
->getOutput();
4662 if ( $this->mTitle
->isProtected( 'edit' ) &&
4663 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4665 # Is the title semi-protected?
4666 if ( $this->mTitle
->isSemiProtected() ) {
4667 $noticeMsg = 'semiprotectedpagewarning';
4669 # Then it must be protected based on static groups (regular)
4670 $noticeMsg = 'protectedpagewarning';
4672 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4673 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4675 if ( $this->mTitle
->isCascadeProtected() ) {
4676 # Is this page under cascading protection from some source pages?
4677 /** @var Title[] $cascadeSources */
4678 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4679 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4680 $cascadeSourcesCount = count( $cascadeSources );
4681 if ( $cascadeSourcesCount > 0 ) {
4682 # Explain, and list the titles responsible
4683 foreach ( $cascadeSources as $page ) {
4684 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4687 $notice .= '</div>';
4688 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4690 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4691 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4693 'showIfEmpty' => false,
4694 'msgKey' => [ 'titleprotectedwarning' ],
4695 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4700 * @param OutputPage $out
4703 protected function addExplainConflictHeader( OutputPage
$out ) {
4705 "<div class='mw-explainconflict'>\n$1\n</div>",
4706 [ 'explainconflict', $this->context
->msg( $this->getSubmitButtonLabel() )->text() ]
4711 * @param string $name
4712 * @param mixed[] $customAttribs
4717 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4718 $attribs = $customAttribs +
[
4723 // Avoid PHP notices when appending preferences
4724 // (appending allows customAttribs['style'] to still work).
4728 // The following classes can be used here:
4729 // * mw-editfont-default
4730 // * mw-editfont-monospace
4731 // * mw-editfont-sans-serif
4732 // * mw-editfont-serif
4733 $class = 'mw-editfont-' . $user->getOption( 'editfont' );
4735 if ( isset( $attribs['class'] ) ) {
4736 if ( is_string( $attribs['class'] ) ) {
4737 $attribs['class'] .= ' ' . $class;
4738 } elseif ( is_array( $attribs['class'] ) ) {
4739 $attribs['class'][] = $class;
4742 $attribs['class'] = $class;
4745 $pageLang = $this->mTitle
->getPageLanguage();
4746 $attribs['lang'] = $pageLang->getHtmlCode();
4747 $attribs['dir'] = $pageLang->getDir();
4753 * @param string $wikitext
4757 protected function addNewLineAtEnd( $wikitext ) {
4758 if ( strval( $wikitext ) !== '' ) {
4759 // Ensure there's a newline at the end, otherwise adding lines
4761 // But don't add a newline if the text is empty, or Firefox in XHTML
4762 // mode will show an extra newline. A bit annoying.
4770 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4771 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4772 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4773 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4774 * spread the new style links more efficiently.
4776 * @param string $text
4779 private function guessSectionName( $text ) {
4782 // Detect Microsoft browsers
4783 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4784 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4785 // ...and redirect them to legacy encoding, if available
4786 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4788 // Meanwhile, real browsers get real anchors
4789 return $wgParser->guessSectionNameFromWikiText( $text );