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() {
530 global $wgRequest, $wgUser;
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() ) {
574 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
575 $user->spreadAnyEditBlock();
578 $this->displayPermissionsError( $permErrors );
583 $revision = $this->mArticle
->getRevisionFetched();
584 // Disallow editing revisions with content models different from the current one
585 // Undo edits being an exception in order to allow reverting content model changes.
587 && $revision->getContentModel() !== $this->contentModel
590 if ( $this->undidRev
) {
591 $undidRevObj = Revision
::newFromId( $this->undidRev
);
592 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
594 if ( !$this->undidRev
596 ||
$prevRev->getContentModel() !== $this->contentModel
598 $this->displayViewSourcePage(
599 $this->getContentObject(),
601 'contentmodelediterror',
602 $revision->getContentModel(),
610 $this->isConflict
= false;
611 // css / js subpages of user pages get a special treatment
612 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
613 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
614 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
615 // @todo FIXME: Silly assignment.
616 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
618 # Show applicable editing introductions
619 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
623 # Attempt submission here. This will check for edit conflicts,
624 # and redundantly check for locked database, blocked IPs, etc.
625 # that edit() already checked just in case someone tries to sneak
626 # in the back door with a hand-edited submission URL.
628 if ( 'save' == $this->formtype
) {
629 $resultDetails = null;
630 $status = $this->attemptSave( $resultDetails );
631 if ( !$this->handleStatus( $status, $resultDetails ) ) {
636 # First time through: get contents, set time for conflict
638 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
639 if ( $this->initialiseForm() === false ) {
640 $this->noSuchSectionPage();
644 if ( !$this->mTitle
->getArticleID() ) {
645 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
647 Hooks
::run( 'EditFormInitialText', [ $this ] );
652 $this->showEditForm();
656 * @param string $rigor Same format as Title::getUserPermissionErrors()
659 protected function getEditPermissionErrors( $rigor = 'secure' ) {
662 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
663 # Can this title be created?
664 if ( !$this->mTitle
->exists() ) {
665 $permErrors = array_merge(
668 $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
673 # Ignore some permissions errors when a user is just previewing/viewing diffs
675 foreach ( $permErrors as $error ) {
676 if ( ( $this->preview ||
$this->diff
)
678 $error[0] == 'blockedtext' ||
679 $error[0] == 'autoblockedtext' ||
680 $error[0] == 'systemblockedtext'
686 $permErrors = wfArrayDiff2( $permErrors, $remove );
692 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
693 * but with the following differences:
694 * - If redlink=1, the user will be redirected to the page
695 * - If there is content to display or the error occurs while either saving,
696 * previewing or showing the difference, it will be a
697 * "View source for ..." page displaying the source code after the error message.
700 * @param array $permErrors Array of permissions errors, as returned by
701 * Title::getUserPermissionsErrors().
702 * @throws PermissionsError
704 protected function displayPermissionsError( array $permErrors ) {
707 $out = $this->context
->getOutput();
708 if ( $wgRequest->getBool( 'redlink' ) ) {
709 // The edit page was reached via a red link.
710 // Redirect to the article page and let them click the edit tab if
711 // they really want a permission error.
712 $out->redirect( $this->mTitle
->getFullURL() );
716 $content = $this->getContentObject();
718 # Use the normal message if there's nothing to display
719 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
720 $action = $this->mTitle
->exists() ?
'edit' :
721 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
722 throw new PermissionsError( $action, $permErrors );
725 $this->displayViewSourcePage(
727 $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
732 * Display a read-only View Source page
733 * @param Content $content content object
734 * @param string $errorMessage additional wikitext error message to display
736 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
737 $out = $this->context
->getOutput();
738 Hooks
::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
740 $out->setRobotPolicy( 'noindex,nofollow' );
741 $out->setPageTitle( $this->context
->msg(
743 $this->getContextTitle()->getPrefixedText()
745 $out->addBacklinkSubtitle( $this->getContextTitle() );
746 $out->addHTML( $this->editFormPageTop
);
747 $out->addHTML( $this->editFormTextTop
);
749 if ( $errorMessage !== '' ) {
750 $out->addWikiText( $errorMessage );
751 $out->addHTML( "<hr />\n" );
754 # If the user made changes, preserve them when showing the markup
755 # (This happens when a user is blocked during edit, for instance)
756 if ( !$this->firsttime
) {
757 $text = $this->textbox1
;
758 $out->addWikiMsg( 'viewyourtext' );
761 $text = $this->toEditText( $content );
762 } catch ( MWException
$e ) {
763 # Serialize using the default format if the content model is not supported
764 # (e.g. for an old revision with a different model)
765 $text = $content->serialize();
767 $out->addWikiMsg( 'viewsourcetext' );
770 $out->addHTML( $this->editFormTextBeforeContent
);
771 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
772 $out->addHTML( $this->editFormTextAfterContent
);
774 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
776 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
778 $out->addHTML( $this->editFormTextBottom
);
779 if ( $this->mTitle
->exists() ) {
780 $out->returnToMain( null, $this->mTitle
);
785 * Should we show a preview when the edit form is first shown?
789 protected function previewOnOpen() {
790 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
791 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
792 // Explicit override from request
794 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
795 // Explicit override from request
797 } elseif ( $this->section
== 'new' ) {
798 // Nothing *to* preview for new sections
800 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
801 && $wgUser->getOption( 'previewonfirst' )
803 // Standard preference behavior
805 } elseif ( !$this->mTitle
->exists()
806 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
807 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
809 // Categories are special
817 * Checks whether the user entered a skin name in uppercase,
818 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
822 protected function isWrongCaseCssJsPage() {
823 if ( $this->mTitle
->isCssJsSubpage() ) {
824 $name = $this->mTitle
->getSkinFromCssJsSubpage();
825 $skins = array_merge(
826 array_keys( Skin
::getSkinNames() ),
829 return !in_array( $name, $skins )
830 && in_array( strtolower( $name ), $skins );
837 * Returns whether section editing is supported for the current page.
838 * Subclasses may override this to replace the default behavior, which is
839 * to check ContentHandler::supportsSections.
841 * @return bool True if this edit page supports sections, false otherwise.
843 protected function isSectionEditSupported() {
844 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
845 return $contentHandler->supportsSections();
849 * This function collects the form data and uses it to populate various member variables.
850 * @param WebRequest &$request
851 * @throws ErrorPageError
853 public function importFormData( &$request ) {
854 global $wgContLang, $wgUser;
856 # Section edit can come from either the form or a link
857 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
859 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
860 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
863 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
865 if ( $request->wasPosted() ) {
866 # These fields need to be checked for encoding.
867 # Also remove trailing whitespace, but don't remove _initial_
868 # whitespace from the text boxes. This may be significant formatting.
869 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
870 if ( !$request->getCheck( 'wpTextbox2' ) ) {
871 // Skip this if wpTextbox2 has input, it indicates that we came
872 // from a conflict page with raw page text, not a custom form
873 // modified by subclasses
874 $textbox1 = $this->importContentFormData( $request );
875 if ( $textbox1 !== null ) {
876 $this->textbox1
= $textbox1;
880 # Truncate for whole multibyte characters
881 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
883 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
884 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
886 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
888 # Treat sectiontitle the same way as summary.
889 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
890 # currently doing double duty as both edit summary and section title. Right now this
891 # is just to allow API edits to work around this limitation, but this should be
892 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
893 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
894 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
896 $this->edittime
= $request->getVal( 'wpEdittime' );
897 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
898 $this->starttime
= $request->getVal( 'wpStarttime' );
900 $undidRev = $request->getInt( 'wpUndidRevision' );
902 $this->undidRev
= $undidRev;
905 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
907 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
908 // wpTextbox1 field is missing, possibly due to being "too big"
909 // according to some filter rules such as Suhosin's setting for
910 // suhosin.request.max_value_length (d'oh)
911 $this->incompleteForm
= true;
913 // If we receive the last parameter of the request, we can fairly
914 // claim the POST request has not been truncated.
916 // TODO: softened the check for cutover. Once we determine
917 // that it is safe, we should complete the transition by
918 // removing the "edittime" clause.
919 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
920 && is_null( $this->edittime
) );
922 if ( $this->incompleteForm
) {
923 # If the form is incomplete, force to preview.
924 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
925 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
926 $this->preview
= true;
928 $this->preview
= $request->getCheck( 'wpPreview' );
929 $this->diff
= $request->getCheck( 'wpDiff' );
931 // Remember whether a save was requested, so we can indicate
932 // if we forced preview due to session failure.
933 $this->mTriedSave
= !$this->preview
;
935 if ( $this->tokenOk( $request ) ) {
936 # Some browsers will not report any submit button
937 # if the user hits enter in the comment box.
938 # The unmarked state will be assumed to be a save,
939 # if the form seems otherwise complete.
940 wfDebug( __METHOD__
. ": Passed token check.\n" );
941 } elseif ( $this->diff
) {
942 # Failed token check, but only requested "Show Changes".
943 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
945 # Page might be a hack attempt posted from
946 # an external site. Preview instead of saving.
947 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
948 $this->preview
= true;
951 $this->save
= !$this->preview
&& !$this->diff
;
952 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
953 $this->edittime
= null;
956 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
957 $this->starttime
= null;
960 $this->recreate
= $request->getCheck( 'wpRecreate' );
962 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
963 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
965 # Don't force edit summaries when a user is editing their own user or talk page
966 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
967 && $this->mTitle
->getText() == $wgUser->getName()
969 $this->allowBlankSummary
= true;
971 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
972 ||
!$wgUser->getOption( 'forceeditsummary' );
975 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
977 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
978 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
980 $changeTags = $request->getVal( 'wpChangeTags' );
981 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
982 $this->changeTags
= [];
984 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
988 # Not a posted form? Start with nothing.
989 wfDebug( __METHOD__
. ": Not a posted form.\n" );
990 $this->textbox1
= '';
992 $this->sectiontitle
= '';
993 $this->edittime
= '';
994 $this->editRevId
= null;
995 $this->starttime
= wfTimestampNow();
997 $this->preview
= false;
1000 $this->minoredit
= false;
1001 // Watch may be overridden by request parameters
1002 $this->watchthis
= $request->getBool( 'watchthis', false );
1003 $this->recreate
= false;
1005 // When creating a new section, we can preload a section title by passing it as the
1006 // preloadtitle parameter in the URL (T15100)
1007 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1008 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1009 // Once wpSummary isn't being use for setting section titles, we should delete this.
1010 $this->summary
= $request->getVal( 'preloadtitle' );
1011 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1012 $this->summary
= $request->getText( 'summary' );
1013 if ( $this->summary
!== '' ) {
1014 $this->hasPresetSummary
= true;
1018 if ( $request->getVal( 'minor' ) ) {
1019 $this->minoredit
= true;
1023 $this->oldid
= $request->getInt( 'oldid' );
1024 $this->parentRevId
= $request->getInt( 'parentRevId' );
1026 $this->bot
= $request->getBool( 'bot', true );
1027 $this->nosummary
= $request->getBool( 'nosummary' );
1029 // May be overridden by revision.
1030 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1031 // May be overridden by revision.
1032 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1035 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1036 } catch ( MWUnknownContentModelException
$e ) {
1037 throw new ErrorPageError(
1038 'editpage-invalidcontentmodel-title',
1039 'editpage-invalidcontentmodel-text',
1040 [ wfEscapeWikiText( $this->contentModel
) ]
1044 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1045 throw new ErrorPageError(
1046 'editpage-notsupportedcontentformat-title',
1047 'editpage-notsupportedcontentformat-text',
1049 wfEscapeWikiText( $this->contentFormat
),
1050 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1056 * @todo Check if the desired model is allowed in this namespace, and if
1057 * a transition from the page's current model to the new model is
1061 $this->editintro
= $request->getText( 'editintro',
1062 // Custom edit intro for new sections
1063 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1065 // Allow extensions to modify form data
1066 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1070 * Subpage overridable method for extracting the page content data from the
1071 * posted form to be placed in $this->textbox1, if using customized input
1072 * this method should be overridden and return the page text that will be used
1073 * for saving, preview parsing and so on...
1075 * @param WebRequest &$request
1076 * @return string|null
1078 protected function importContentFormData( &$request ) {
1079 return; // Don't do anything, EditPage already extracted wpTextbox1
1083 * Initialise form fields in the object
1084 * Called on the first invocation, e.g. when a user clicks an edit link
1085 * @return bool If the requested section is valid
1087 public function initialiseForm() {
1089 $this->edittime
= $this->page
->getTimestamp();
1090 $this->editRevId
= $this->page
->getLatest();
1092 $content = $this->getContentObject( false ); # TODO: track content object?!
1093 if ( $content === false ) {
1096 $this->textbox1
= $this->toEditText( $content );
1098 // activate checkboxes if user wants them to be always active
1099 # Sort out the "watch" checkbox
1100 if ( $wgUser->getOption( 'watchdefault' ) ) {
1102 $this->watchthis
= true;
1103 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1105 $this->watchthis
= true;
1106 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
1108 $this->watchthis
= true;
1110 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
1111 $this->minoredit
= true;
1113 if ( $this->textbox1
=== false ) {
1120 * @param Content|null $def_content The default value to return
1122 * @return Content|null Content on success, $def_content for invalid sections
1126 protected function getContentObject( $def_content = null ) {
1127 global $wgRequest, $wgUser, $wgContLang;
1131 // For message page not locally set, use the i18n message.
1132 // For other non-existent articles, use preload text if any.
1133 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1134 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1135 # If this is a system message, get the default text.
1136 $msg = $this->mTitle
->getDefaultMessageText();
1138 $content = $this->toEditContent( $msg );
1140 if ( $content === false ) {
1141 # If requested, preload some text.
1142 $preload = $wgRequest->getVal( 'preload',
1143 // Custom preload text for new sections
1144 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1145 $params = $wgRequest->getArray( 'preloadparams', [] );
1147 $content = $this->getPreloadedContent( $preload, $params );
1149 // For existing pages, get text based on "undo" or section parameters.
1151 if ( $this->section
!= '' ) {
1152 // Get section edit text (returns $def_text for invalid sections)
1153 $orig = $this->getOriginalContent( $wgUser );
1154 $content = $orig ?
$orig->getSection( $this->section
) : null;
1157 $content = $def_content;
1160 $undoafter = $wgRequest->getInt( 'undoafter' );
1161 $undo = $wgRequest->getInt( 'undo' );
1163 if ( $undo > 0 && $undoafter > 0 ) {
1164 $undorev = Revision
::newFromId( $undo );
1165 $oldrev = Revision
::newFromId( $undoafter );
1167 # Sanity check, make sure it's the right page,
1168 # the revisions exist and they were not deleted.
1169 # Otherwise, $content will be left as-is.
1170 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1171 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1172 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1174 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1176 if ( $content === false ) {
1177 # Warn the user that something went wrong
1178 $undoMsg = 'failure';
1180 $oldContent = $this->page
->getContent( Revision
::RAW
);
1181 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
1182 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
1183 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1184 // The undo may change content
1185 // model if its reverting the top
1186 // edit. This can result in
1187 // mismatched content model/format.
1188 $this->contentModel
= $newContent->getModel();
1189 $this->contentFormat
= $oldrev->getContentFormat();
1192 if ( $newContent->equals( $oldContent ) ) {
1193 # Tell the user that the undo results in no change,
1194 # i.e. the revisions were already undone.
1195 $undoMsg = 'nochange';
1198 # Inform the user of our success and set an automatic edit summary
1199 $undoMsg = 'success';
1201 # If we just undid one rev, use an autosummary
1202 $firstrev = $oldrev->getNext();
1203 if ( $firstrev && $firstrev->getId() == $undo ) {
1204 $userText = $undorev->getUserText();
1205 if ( $userText === '' ) {
1206 $undoSummary = $this->context
->msg(
1207 'undo-summary-username-hidden',
1209 )->inContentLanguage()->text();
1211 $undoSummary = $this->context
->msg(
1215 )->inContentLanguage()->text();
1217 if ( $this->summary
=== '' ) {
1218 $this->summary
= $undoSummary;
1220 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1221 ->inContentLanguage()->text() . $this->summary
;
1223 $this->undidRev
= $undo;
1225 $this->formtype
= 'diff';
1229 // Failed basic sanity checks.
1230 // Older revisions may have been removed since the link
1231 // was created, or we may simply have got bogus input.
1235 $out = $this->context
->getOutput();
1236 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1237 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1238 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1239 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1242 if ( $content === false ) {
1243 $content = $this->getOriginalContent( $wgUser );
1252 * Get the content of the wanted revision, without section extraction.
1254 * The result of this function can be used to compare user's input with
1255 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1256 * to the original text of the edit.
1258 * This differs from Article::getContent() that when a missing revision is
1259 * encountered the result will be null and not the
1260 * 'missing-revision' message.
1263 * @param User $user The user to get the revision for
1264 * @return Content|null
1266 private function getOriginalContent( User
$user ) {
1267 if ( $this->section
== 'new' ) {
1268 return $this->getCurrentContent();
1270 $revision = $this->mArticle
->getRevisionFetched();
1271 if ( $revision === null ) {
1272 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1273 return $handler->makeEmptyContent();
1275 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1280 * Get the edit's parent revision ID
1282 * The "parent" revision is the ancestor that should be recorded in this
1283 * page's revision history. It is either the revision ID of the in-memory
1284 * article content, or in the case of a 3-way merge in order to rebase
1285 * across a recoverable edit conflict, the ID of the newer revision to
1286 * which we have rebased this page.
1289 * @return int Revision ID
1291 public function getParentRevId() {
1292 if ( $this->parentRevId
) {
1293 return $this->parentRevId
;
1295 return $this->mArticle
->getRevIdFetched();
1300 * Get the current content of the page. This is basically similar to
1301 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1302 * content object is returned instead of null.
1307 protected function getCurrentContent() {
1308 $rev = $this->page
->getRevision();
1309 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1311 if ( $content === false ||
$content === null ) {
1312 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1313 return $handler->makeEmptyContent();
1314 } elseif ( !$this->undidRev
) {
1315 // Content models should always be the same since we error
1316 // out if they are different before this point (in ->edit()).
1317 // The exception being, during an undo, the current revision might
1318 // differ from the prior revision.
1319 $logger = LoggerFactory
::getInstance( 'editpage' );
1320 if ( $this->contentModel
!== $rev->getContentModel() ) {
1321 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1322 'prev' => $this->contentModel
,
1323 'new' => $rev->getContentModel(),
1324 'title' => $this->getTitle()->getPrefixedDBkey(),
1325 'method' => __METHOD__
1327 $this->contentModel
= $rev->getContentModel();
1330 // Given that the content models should match, the current selected
1331 // format should be supported.
1332 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1333 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1335 'prev' => $this->contentFormat
,
1336 'new' => $rev->getContentFormat(),
1337 'title' => $this->getTitle()->getPrefixedDBkey(),
1338 'method' => __METHOD__
1340 $this->contentFormat
= $rev->getContentFormat();
1347 * Use this method before edit() to preload some content into the edit box
1349 * @param Content $content
1353 public function setPreloadedContent( Content
$content ) {
1354 $this->mPreloadContent
= $content;
1358 * Get the contents to be preloaded into the box, either set by
1359 * an earlier setPreloadText() or by loading the given page.
1361 * @param string $preload Representing the title to preload from.
1362 * @param array $params Parameters to use (interface-message style) in the preloaded text
1368 protected function getPreloadedContent( $preload, $params = [] ) {
1371 if ( !empty( $this->mPreloadContent
) ) {
1372 return $this->mPreloadContent
;
1375 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1377 if ( $preload === '' ) {
1378 return $handler->makeEmptyContent();
1381 $title = Title
::newFromText( $preload );
1382 # Check for existence to avoid getting MediaWiki:Noarticletext
1383 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1384 // TODO: somehow show a warning to the user!
1385 return $handler->makeEmptyContent();
1388 $page = WikiPage
::factory( $title );
1389 if ( $page->isRedirect() ) {
1390 $title = $page->getRedirectTarget();
1392 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1393 // TODO: somehow show a warning to the user!
1394 return $handler->makeEmptyContent();
1396 $page = WikiPage
::factory( $title );
1399 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1400 $content = $page->getContent( Revision
::RAW
);
1403 // TODO: somehow show a warning to the user!
1404 return $handler->makeEmptyContent();
1407 if ( $content->getModel() !== $handler->getModelID() ) {
1408 $converted = $content->convert( $handler->getModelID() );
1410 if ( !$converted ) {
1411 // TODO: somehow show a warning to the user!
1412 wfDebug( "Attempt to preload incompatible content: " .
1413 "can't convert " . $content->getModel() .
1414 " to " . $handler->getModelID() );
1416 return $handler->makeEmptyContent();
1419 $content = $converted;
1422 return $content->preloadTransform( $title, $parserOptions, $params );
1426 * Make sure the form isn't faking a user's credentials.
1428 * @param WebRequest &$request
1432 public function tokenOk( &$request ) {
1434 $token = $request->getVal( 'wpEditToken' );
1435 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1436 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1437 return $this->mTokenOk
;
1441 * Sets post-edit cookie indicating the user just saved a particular revision.
1443 * This uses a temporary cookie for each revision ID so separate saves will never
1444 * interfere with each other.
1446 * Article::view deletes the cookie on server-side after the redirect and
1447 * converts the value to the global JavaScript variable wgPostEdit.
1449 * If the variable were set on the server, it would be cached, which is unwanted
1450 * since the post-edit state should only apply to the load right after the save.
1452 * @param int $statusValue The status value (to check for new article status)
1454 protected function setPostEditCookie( $statusValue ) {
1455 $revisionId = $this->page
->getLatest();
1456 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1459 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1461 } elseif ( $this->oldid
) {
1465 $response = $this->context
->getRequest()->response();
1466 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
);
1470 * Attempt submission
1471 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1472 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1473 * @return Status The resulting status object.
1475 public function attemptSave( &$resultDetails = false ) {
1478 # Allow bots to exempt some edits from bot flagging
1479 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1480 $status = $this->internalAttemptSave( $resultDetails, $bot );
1482 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1488 * Log when a page was successfully saved after the edit conflict view
1490 private function incrementResolvedConflicts() {
1493 if ( $wgRequest->getText( 'mode' ) !== 'conflict' ) {
1497 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1498 $stats->increment( 'edit.failures.conflict.resolved' );
1502 * Handle status, such as after attempt save
1504 * @param Status $status
1505 * @param array|bool $resultDetails
1507 * @throws ErrorPageError
1508 * @return bool False, if output is done, true if rest of the form should be displayed
1510 private function handleStatus( Status
$status, $resultDetails ) {
1514 * @todo FIXME: once the interface for internalAttemptSave() is made
1515 * nicer, this should use the message in $status
1517 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1518 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1520 $this->incrementResolvedConflicts();
1522 $this->didSave
= true;
1523 if ( !$resultDetails['nullEdit'] ) {
1524 $this->setPostEditCookie( $status->value
);
1528 $out = $this->context
->getOutput();
1530 // "wpExtraQueryRedirect" is a hidden input to modify
1531 // after save URL and is not used by actual edit form
1532 $request = $this->context
->getRequest();
1533 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1535 switch ( $status->value
) {
1536 case self
::AS_HOOK_ERROR_EXPECTED
:
1537 case self
::AS_CONTENT_TOO_BIG
:
1538 case self
::AS_ARTICLE_WAS_DELETED
:
1539 case self
::AS_CONFLICT_DETECTED
:
1540 case self
::AS_SUMMARY_NEEDED
:
1541 case self
::AS_TEXTBOX_EMPTY
:
1542 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1544 case self
::AS_BLANK_ARTICLE
:
1545 case self
::AS_SELF_REDIRECT
:
1548 case self
::AS_HOOK_ERROR
:
1551 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1552 case self
::AS_PARSE_ERROR
:
1553 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1556 case self
::AS_SUCCESS_NEW_ARTICLE
:
1557 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1558 if ( $extraQueryRedirect ) {
1559 if ( $query === '' ) {
1560 $query = $extraQueryRedirect;
1562 $query = $query . '&' . $extraQueryRedirect;
1565 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1566 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1569 case self
::AS_SUCCESS_UPDATE
:
1571 $sectionanchor = $resultDetails['sectionanchor'];
1573 // Give extensions a chance to modify URL query on update
1575 'ArticleUpdateBeforeRedirect',
1576 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1579 if ( $resultDetails['redirect'] ) {
1580 if ( $extraQuery == '' ) {
1581 $extraQuery = 'redirect=no';
1583 $extraQuery = 'redirect=no&' . $extraQuery;
1586 if ( $extraQueryRedirect ) {
1587 if ( $extraQuery === '' ) {
1588 $extraQuery = $extraQueryRedirect;
1590 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1594 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1597 case self
::AS_SPAM_ERROR
:
1598 $this->spamPageWithContent( $resultDetails['spam'] );
1601 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1602 throw new UserBlockedError( $wgUser->getBlock() );
1604 case self
::AS_IMAGE_REDIRECT_ANON
:
1605 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1606 throw new PermissionsError( 'upload' );
1608 case self
::AS_READ_ONLY_PAGE_ANON
:
1609 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1610 throw new PermissionsError( 'edit' );
1612 case self
::AS_READ_ONLY_PAGE
:
1613 throw new ReadOnlyError
;
1615 case self
::AS_RATE_LIMITED
:
1616 throw new ThrottledError();
1618 case self
::AS_NO_CREATE_PERMISSION
:
1619 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1620 throw new PermissionsError( $permission );
1622 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1623 throw new PermissionsError( 'editcontentmodel' );
1626 // We don't recognize $status->value. The only way that can happen
1627 // is if an extension hook aborted from inside ArticleSave.
1628 // Render the status object into $this->hookError
1629 // FIXME this sucks, we should just use the Status object throughout
1630 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1637 * Run hooks that can filter edits just before they get saved.
1639 * @param Content $content The Content to filter.
1640 * @param Status $status For reporting the outcome to the caller
1641 * @param User $user The user performing the edit
1645 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1646 // Run old style post-section-merge edit filter
1647 if ( $this->hookError
!= '' ) {
1648 # ...or the hook could be expecting us to produce an error
1649 $status->fatal( 'hookaborted' );
1650 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1654 // Run new style post-section-merge edit filter
1655 if ( !Hooks
::run( 'EditFilterMergedContent',
1656 [ $this->mArticle
->getContext(), $content, $status, $this->summary
,
1657 $user, $this->minoredit
] )
1659 # Error messages etc. could be handled within the hook...
1660 if ( $status->isGood() ) {
1661 $status->fatal( 'hookaborted' );
1662 // Not setting $this->hookError here is a hack to allow the hook
1663 // to cause a return to the edit page without $this->hookError
1664 // being set. This is used by ConfirmEdit to display a captcha
1665 // without any error message cruft.
1667 $this->hookError
= $status->getWikiText();
1669 // Use the existing $status->value if the hook set it
1670 if ( !$status->value
) {
1671 $status->value
= self
::AS_HOOK_ERROR
;
1674 } elseif ( !$status->isOK() ) {
1675 # ...or the hook could be expecting us to produce an error
1676 // FIXME this sucks, we should just use the Status object throughout
1677 $this->hookError
= $status->getWikiText();
1678 $status->fatal( 'hookaborted' );
1679 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1687 * Return the summary to be used for a new section.
1689 * @param string $sectionanchor Set to the section anchor text
1692 private function newSectionSummary( &$sectionanchor = null ) {
1695 if ( $this->sectiontitle
!== '' ) {
1696 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1697 // If no edit summary was specified, create one automatically from the section
1698 // title and have it link to the new section. Otherwise, respect the summary as
1700 if ( $this->summary
=== '' ) {
1701 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1702 return $this->context
->msg( 'newsectionsummary' )
1703 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1705 } elseif ( $this->summary
!== '' ) {
1706 $sectionanchor = $this->guessSectionName( $this->summary
);
1707 # This is a new section, so create a link to the new section
1708 # in the revision summary.
1709 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1710 return $this->context
->msg( 'newsectionsummary' )
1711 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1713 return $this->summary
;
1717 * Attempt submission (no UI)
1719 * @param array &$result Array to add statuses to, currently with the
1721 * - spam (string): Spam string from content if any spam is detected by
1723 * - sectionanchor (string): Section anchor for a section save.
1724 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1726 * - redirect (bool): Set if doEditContent is OK. True if resulting
1727 * revision is a redirect.
1728 * @param bool $bot True if edit is being made under the bot right.
1730 * @return Status Status object, possibly with a message, but always with
1731 * one of the AS_* constants in $status->value,
1733 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1734 * various error display idiosyncrasies. There are also lots of cases
1735 * where error metadata is set in the object and retrieved later instead
1736 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1737 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1740 public function internalAttemptSave( &$result, $bot = false ) {
1741 global $wgUser, $wgRequest, $wgMaxArticleSize;
1742 global $wgContentHandlerUseDB;
1744 $status = Status
::newGood();
1746 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1747 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1748 $status->fatal( 'hookaborted' );
1749 $status->value
= self
::AS_HOOK_ERROR
;
1753 $spam = $wgRequest->getText( 'wpAntispam' );
1754 if ( $spam !== '' ) {
1757 $wgUser->getName() .
1759 $this->mTitle
->getPrefixedText() .
1760 '" submitted bogus field "' .
1764 $status->fatal( 'spamprotectionmatch', false );
1765 $status->value
= self
::AS_SPAM_ERROR
;
1770 # Construct Content object
1771 $textbox_content = $this->toEditContent( $this->textbox1
);
1772 } catch ( MWContentSerializationException
$ex ) {
1774 'content-failed-to-parse',
1775 $this->contentModel
,
1776 $this->contentFormat
,
1779 $status->value
= self
::AS_PARSE_ERROR
;
1783 # Check image redirect
1784 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1785 $textbox_content->isRedirect() &&
1786 !$wgUser->isAllowed( 'upload' )
1788 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1789 $status->setResult( false, $code );
1795 $match = self
::matchSummarySpamRegex( $this->summary
);
1796 if ( $match === false && $this->section
== 'new' ) {
1797 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1798 # regular summaries, it is added to the actual wikitext.
1799 if ( $this->sectiontitle
!== '' ) {
1800 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1801 $match = self
::matchSpamRegex( $this->sectiontitle
);
1803 # This branch is taken when the "Add Topic" user interface is used, or the API
1804 # is used with the 'summary' parameter.
1805 $match = self
::matchSpamRegex( $this->summary
);
1808 if ( $match === false ) {
1809 $match = self
::matchSpamRegex( $this->textbox1
);
1811 if ( $match !== false ) {
1812 $result['spam'] = $match;
1813 $ip = $wgRequest->getIP();
1814 $pdbk = $this->mTitle
->getPrefixedDBkey();
1815 $match = str_replace( "\n", '', $match );
1816 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1817 $status->fatal( 'spamprotectionmatch', $match );
1818 $status->value
= self
::AS_SPAM_ERROR
;
1823 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1825 # Error messages etc. could be handled within the hook...
1826 $status->fatal( 'hookaborted' );
1827 $status->value
= self
::AS_HOOK_ERROR
;
1829 } elseif ( $this->hookError
!= '' ) {
1830 # ...or the hook could be expecting us to produce an error
1831 $status->fatal( 'hookaborted' );
1832 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1836 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1837 // Auto-block user's IP if the account was "hard" blocked
1838 if ( !wfReadOnly() ) {
1839 $wgUser->spreadAnyEditBlock();
1841 # Check block state against master, thus 'false'.
1842 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1846 $this->contentLength
= strlen( $this->textbox1
);
1847 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
1848 // Error will be displayed by showEditForm()
1849 $this->tooBig
= true;
1850 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1854 if ( !$wgUser->isAllowed( 'edit' ) ) {
1855 if ( $wgUser->isAnon() ) {
1856 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1859 $status->fatal( 'readonlytext' );
1860 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1865 $changingContentModel = false;
1866 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1867 if ( !$wgContentHandlerUseDB ) {
1868 $status->fatal( 'editpage-cannot-use-custom-model' );
1869 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1871 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1872 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1875 // Make sure the user can edit the page under the new content model too
1876 $titleWithNewContentModel = clone $this->mTitle
;
1877 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1878 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $wgUser )
1879 ||
!$titleWithNewContentModel->userCan( 'edit', $wgUser )
1881 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1885 $changingContentModel = true;
1886 $oldContentModel = $this->mTitle
->getContentModel();
1889 if ( $this->changeTags
) {
1890 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1891 $this->changeTags
, $wgUser );
1892 if ( !$changeTagsStatus->isOK() ) {
1893 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1894 return $changeTagsStatus;
1898 if ( wfReadOnly() ) {
1899 $status->fatal( 'readonlytext' );
1900 $status->value
= self
::AS_READ_ONLY_PAGE
;
1903 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 )
1904 ||
( $changingContentModel && $wgUser->pingLimiter( 'editcontentmodel' ) )
1906 $status->fatal( 'actionthrottledtext' );
1907 $status->value
= self
::AS_RATE_LIMITED
;
1911 # If the article has been deleted while editing, don't save it without
1913 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1914 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1918 # Load the page data from the master. If anything changes in the meantime,
1919 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1920 $this->page
->loadPageData( 'fromdbmaster' );
1921 $new = !$this->page
->exists();
1924 // Late check for create permission, just in case *PARANOIA*
1925 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1926 $status->fatal( 'nocreatetext' );
1927 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1928 wfDebug( __METHOD__
. ": no create permission\n" );
1932 // Don't save a new page if it's blank or if it's a MediaWiki:
1933 // message with content equivalent to default (allow empty pages
1934 // in this case to disable messages, see T52124)
1935 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1936 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1937 $defaultText = $defaultMessageText;
1942 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1943 $this->blankArticle
= true;
1944 $status->fatal( 'blankarticle' );
1945 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1949 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1953 $content = $textbox_content;
1955 $result['sectionanchor'] = '';
1956 if ( $this->section
== 'new' ) {
1957 if ( $this->sectiontitle
!== '' ) {
1958 // Insert the section title above the content.
1959 $content = $content->addSectionHeader( $this->sectiontitle
);
1960 } elseif ( $this->summary
!== '' ) {
1961 // Insert the section title above the content.
1962 $content = $content->addSectionHeader( $this->summary
);
1964 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1967 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1971 # Article exists. Check for edit conflict.
1973 $this->page
->clear(); # Force reload of dates, etc.
1974 $timestamp = $this->page
->getTimestamp();
1975 $latest = $this->page
->getLatest();
1977 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1979 // Check editRevId if set, which handles same-second timestamp collisions
1980 if ( $timestamp != $this->edittime
1981 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
1983 $this->isConflict
= true;
1984 if ( $this->section
== 'new' ) {
1985 if ( $this->page
->getUserText() == $wgUser->getName() &&
1986 $this->page
->getComment() == $this->newSectionSummary()
1988 // Probably a duplicate submission of a new comment.
1989 // This can happen when CDN resends a request after
1990 // a timeout but the first one actually went through.
1992 . ": duplicate new section submission; trigger edit conflict!\n" );
1994 // New comment; suppress conflict.
1995 $this->isConflict
= false;
1996 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1998 } elseif ( $this->section
== ''
1999 && Revision
::userWasLastToEdit(
2000 DB_MASTER
, $this->mTitle
->getArticleID(),
2001 $wgUser->getId(), $this->edittime
2004 # Suppress edit conflict with self, except for section edits where merging is required.
2005 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2006 $this->isConflict
= false;
2010 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2011 if ( $this->sectiontitle
!== '' ) {
2012 $sectionTitle = $this->sectiontitle
;
2014 $sectionTitle = $this->summary
;
2019 if ( $this->isConflict
) {
2021 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2022 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2023 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2024 // ...or disable section editing for non-current revisions (not exposed anyway).
2025 if ( $this->editRevId
!== null ) {
2026 $content = $this->page
->replaceSectionAtRev(
2033 $content = $this->page
->replaceSectionContent(
2041 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2042 $content = $this->page
->replaceSectionContent(
2049 if ( is_null( $content ) ) {
2050 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2051 $this->isConflict
= true;
2052 $content = $textbox_content; // do not try to merge here!
2053 } elseif ( $this->isConflict
) {
2055 if ( $this->mergeChangesIntoContent( $content ) ) {
2056 // Successful merge! Maybe we should tell the user the good news?
2057 $this->isConflict
= false;
2058 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2060 $this->section
= '';
2061 $this->textbox1
= ContentHandler
::getContentText( $content );
2062 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2066 if ( $this->isConflict
) {
2067 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2071 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
2075 if ( $this->section
== 'new' ) {
2076 // Handle the user preference to force summaries here
2077 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2078 $this->missingSummary
= true;
2079 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2080 $status->value
= self
::AS_SUMMARY_NEEDED
;
2084 // Do not allow the user to post an empty comment
2085 if ( $this->textbox1
== '' ) {
2086 $this->missingComment
= true;
2087 $status->fatal( 'missingcommenttext' );
2088 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2091 } elseif ( !$this->allowBlankSummary
2092 && !$content->equals( $this->getOriginalContent( $wgUser ) )
2093 && !$content->isRedirect()
2094 && md5( $this->summary
) == $this->autoSumm
2096 $this->missingSummary
= true;
2097 $status->fatal( 'missingsummary' );
2098 $status->value
= self
::AS_SUMMARY_NEEDED
;
2103 $sectionanchor = '';
2104 if ( $this->section
== 'new' ) {
2105 $this->summary
= $this->newSectionSummary( $sectionanchor );
2106 } elseif ( $this->section
!= '' ) {
2107 # Try to get a section anchor from the section source, redirect
2108 # to edited section if header found.
2109 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2110 # for duplicate heading checking and maybe parsing.
2111 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2112 # We can't deal with anchors, includes, html etc in the header for now,
2113 # headline would need to be parsed to improve this.
2114 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2115 $sectionanchor = $this->guessSectionName( $matches[2] );
2118 $result['sectionanchor'] = $sectionanchor;
2120 // Save errors may fall down to the edit form, but we've now
2121 // merged the section into full text. Clear the section field
2122 // so that later submission of conflict forms won't try to
2123 // replace that into a duplicated mess.
2124 $this->textbox1
= $this->toEditText( $content );
2125 $this->section
= '';
2127 $status->value
= self
::AS_SUCCESS_UPDATE
;
2130 if ( !$this->allowSelfRedirect
2131 && $content->isRedirect()
2132 && $content->getRedirectTarget()->equals( $this->getTitle() )
2134 // If the page already redirects to itself, don't warn.
2135 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2136 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2137 $this->selfRedirect
= true;
2138 $status->fatal( 'selfredirect' );
2139 $status->value
= self
::AS_SELF_REDIRECT
;
2144 // Check for length errors again now that the section is merged in
2145 $this->contentLength
= strlen( $this->toEditText( $content ) );
2146 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
2147 $this->tooBig
= true;
2148 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2152 $flags = EDIT_AUTOSUMMARY |
2153 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2154 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2155 ( $bot ? EDIT_FORCE_BOT
: 0 );
2157 $doEditStatus = $this->page
->doEditContent(
2163 $content->getDefaultFormat(),
2168 if ( !$doEditStatus->isOK() ) {
2169 // Failure from doEdit()
2170 // Show the edit conflict page for certain recognized errors from doEdit(),
2171 // but don't show it for errors from extension hooks
2172 $errors = $doEditStatus->getErrorsArray();
2173 if ( in_array( $errors[0][0],
2174 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2176 $this->isConflict
= true;
2177 // Destroys data doEdit() put in $status->value but who cares
2178 $doEditStatus->value
= self
::AS_END
;
2180 return $doEditStatus;
2183 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2184 if ( $result['nullEdit'] ) {
2185 // We don't know if it was a null edit until now, so increment here
2186 $wgUser->pingLimiter( 'linkpurge' );
2188 $result['redirect'] = $content->isRedirect();
2190 $this->updateWatchlist();
2192 // If the content model changed, add a log entry
2193 if ( $changingContentModel ) {
2194 $this->addContentModelChangeLogEntry(
2196 $new ?
false : $oldContentModel,
2197 $this->contentModel
,
2207 * @param string|false $oldModel false if the page is being newly created
2208 * @param string $newModel
2209 * @param string $reason
2211 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2212 $new = $oldModel === false;
2213 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2214 $log->setPerformer( $user );
2215 $log->setTarget( $this->mTitle
);
2216 $log->setComment( $reason );
2217 $log->setParameters( [
2218 '4::oldmodel' => $oldModel,
2219 '5::newmodel' => $newModel
2221 $logid = $log->insert();
2222 $log->publish( $logid );
2226 * Register the change of watch status
2228 protected function updateWatchlist() {
2231 if ( !$wgUser->isLoggedIn() ) {
2236 $title = $this->mTitle
;
2237 $watch = $this->watchthis
;
2238 // Do this in its own transaction to reduce contention...
2239 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2240 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2241 return; // nothing to change
2243 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2248 * Attempts to do 3-way merge of edit content with a base revision
2249 * and current content, in case of edit conflict, in whichever way appropriate
2250 * for the content type.
2254 * @param Content $editContent
2258 private function mergeChangesIntoContent( &$editContent ) {
2259 $db = wfGetDB( DB_MASTER
);
2261 // This is the revision the editor started from
2262 $baseRevision = $this->getBaseRevision();
2263 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2265 if ( is_null( $baseContent ) ) {
2269 // The current state, we want to merge updates into it
2270 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2271 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2273 if ( is_null( $currentContent ) ) {
2277 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2279 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2282 $editContent = $result;
2283 // Update parentRevId to what we just merged.
2284 $this->parentRevId
= $currentRevision->getId();
2292 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2293 * one might think of X as the "base revision", which is NOT what this returns.
2294 * @return Revision Current version when the edit was started
2296 public function getBaseRevision() {
2297 if ( !$this->mBaseRevision
) {
2298 $db = wfGetDB( DB_MASTER
);
2299 $this->mBaseRevision
= $this->editRevId
2300 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2301 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2303 return $this->mBaseRevision
;
2307 * Check given input text against $wgSpamRegex, and return the text of the first match.
2309 * @param string $text
2311 * @return string|bool Matching string or false
2313 public static function matchSpamRegex( $text ) {
2314 global $wgSpamRegex;
2315 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2316 $regexes = (array)$wgSpamRegex;
2317 return self
::matchSpamRegexInternal( $text, $regexes );
2321 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2323 * @param string $text
2325 * @return string|bool Matching string or false
2327 public static function matchSummarySpamRegex( $text ) {
2328 global $wgSummarySpamRegex;
2329 $regexes = (array)$wgSummarySpamRegex;
2330 return self
::matchSpamRegexInternal( $text, $regexes );
2334 * @param string $text
2335 * @param array $regexes
2336 * @return bool|string
2338 protected static function matchSpamRegexInternal( $text, $regexes ) {
2339 foreach ( $regexes as $regex ) {
2341 if ( preg_match( $regex, $text, $matches ) ) {
2348 public function setHeaders() {
2349 global $wgUser, $wgAjaxEditStash;
2351 $out = $this->context
->getOutput();
2353 $out->addModules( 'mediawiki.action.edit' );
2354 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2356 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2357 // The addition of default buttons is handled by getEditToolbar() which
2358 // has its own dependency on this module. The call here ensures the module
2359 // is loaded in time (it has position "top") for other modules to register
2360 // buttons (e.g. extensions, gadgets, user scripts).
2361 $out->addModules( 'mediawiki.toolbar' );
2364 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2365 $out->addModules( 'mediawiki.action.edit.preview' );
2368 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2369 $out->addModules( 'mediawiki.action.edit.editWarning' );
2372 # Enabled article-related sidebar, toplinks, etc.
2373 $out->setArticleRelated( true );
2375 $contextTitle = $this->getContextTitle();
2376 if ( $this->isConflict
) {
2377 $msg = 'editconflict';
2378 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2379 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2381 $msg = $contextTitle->exists()
2382 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2383 && $contextTitle->getDefaultMessageText() !== false
2389 # Use the title defined by DISPLAYTITLE magic word when present
2390 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2391 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2392 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2393 if ( $displayTitle === false ) {
2394 $displayTitle = $contextTitle->getPrefixedText();
2396 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2397 # Transmit the name of the message to JavaScript for live preview
2398 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2399 $out->addJsConfigVars( [
2400 'wgEditMessage' => $msg,
2401 'wgAjaxEditStash' => $wgAjaxEditStash,
2406 * Show all applicable editing introductions
2408 protected function showIntro() {
2410 if ( $this->suppressIntro
) {
2414 $out = $this->context
->getOutput();
2415 $namespace = $this->mTitle
->getNamespace();
2417 if ( $namespace == NS_MEDIAWIKI
) {
2418 # Show a warning if editing an interface message
2419 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2420 # If this is a default message (but not css or js),
2421 # show a hint that it is translatable on translatewiki.net
2422 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2423 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2425 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2426 if ( $defaultMessageText !== false ) {
2427 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2428 'translateinterface' );
2431 } elseif ( $namespace == NS_FILE
) {
2432 # Show a hint to shared repo
2433 $file = wfFindFile( $this->mTitle
);
2434 if ( $file && !$file->isLocal() ) {
2435 $descUrl = $file->getDescriptionUrl();
2436 # there must be a description url to show a hint to shared repo
2438 if ( !$this->mTitle
->exists() ) {
2439 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2440 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2443 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2444 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2451 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2452 # Show log extract when the user is currently blocked
2453 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2454 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2455 $user = User
::newFromName( $username, false /* allow IP users */ );
2456 $ip = User
::isIP( $username );
2457 $block = Block
::newFromTarget( $user, $user );
2458 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2459 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2460 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2461 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2462 # Show log extract if the user is currently blocked
2463 LogEventsList
::showLogExtract(
2466 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2470 'showIfEmpty' => false,
2472 'blocked-notice-logextract',
2473 $user->getName() # Support GENDER in notice
2479 # Try to add a custom edit intro, or use the standard one if this is not possible.
2480 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2481 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2482 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2484 if ( $wgUser->isLoggedIn() ) {
2486 // Suppress the external link icon, consider the help url an internal one
2487 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2495 // Suppress the external link icon, consider the help url an internal one
2496 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2498 'newarticletextanon',
2504 # Give a notice if the user is editing a deleted/moved page...
2505 if ( !$this->mTitle
->exists() ) {
2506 $dbr = wfGetDB( DB_REPLICA
);
2508 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2512 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2513 'showIfEmpty' => false,
2514 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2521 * Attempt to show a custom editing introduction, if supplied
2525 protected function showCustomIntro() {
2526 if ( $this->editintro
) {
2527 $title = Title
::newFromText( $this->editintro
);
2528 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2529 // Added using template syntax, to take <noinclude>'s into account.
2530 $this->context
->getOutput()->addWikiTextTitleTidy(
2531 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2541 * Gets an editable textual representation of $content.
2542 * The textual representation can be turned by into a Content object by the
2543 * toEditContent() method.
2545 * If $content is null or false or a string, $content is returned unchanged.
2547 * If the given Content object is not of a type that can be edited using
2548 * the text base EditPage, an exception will be raised. Set
2549 * $this->allowNonTextContent to true to allow editing of non-textual
2552 * @param Content|null|bool|string $content
2553 * @return string The editable text form of the content.
2555 * @throws MWException If $content is not an instance of TextContent and
2556 * $this->allowNonTextContent is not true.
2558 protected function toEditText( $content ) {
2559 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2563 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2564 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2567 return $content->serialize( $this->contentFormat
);
2571 * Turns the given text into a Content object by unserializing it.
2573 * If the resulting Content object is not of a type that can be edited using
2574 * the text base EditPage, an exception will be raised. Set
2575 * $this->allowNonTextContent to true to allow editing of non-textual
2578 * @param string|null|bool $text Text to unserialize
2579 * @return Content|bool|null The content object created from $text. If $text was false
2580 * or null, false resp. null will be returned instead.
2582 * @throws MWException If unserializing the text results in a Content
2583 * object that is not an instance of TextContent and
2584 * $this->allowNonTextContent is not true.
2586 protected function toEditContent( $text ) {
2587 if ( $text === false ||
$text === null ) {
2591 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2592 $this->contentModel
, $this->contentFormat
);
2594 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2595 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2602 * Send the edit form and related headers to OutputPage
2603 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2604 * during form output near the top, for captchas and the like.
2606 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2607 * use the EditPage::showEditForm:fields hook instead.
2609 public function showEditForm( $formCallback = null ) {
2612 # need to parse the preview early so that we know which templates are used,
2613 # otherwise users with "show preview after edit box" will get a blank list
2614 # we parse this near the beginning so that setHeaders can do the title
2615 # setting work instead of leaving it in getPreviewText
2616 $previewOutput = '';
2617 if ( $this->formtype
== 'preview' ) {
2618 $previewOutput = $this->getPreviewText();
2621 $out = $this->context
->getOutput();
2623 // Avoid PHP 7.1 warning of passing $this by reference
2625 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2627 $this->setHeaders();
2629 $this->addTalkPageText();
2630 $this->addEditNotices();
2632 if ( !$this->isConflict
&&
2633 $this->section
!= '' &&
2634 !$this->isSectionEditSupported() ) {
2635 // We use $this->section to much before this and getVal('wgSection') directly in other places
2636 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2637 // Someone is welcome to try refactoring though
2638 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2642 $this->showHeader();
2644 $out->addHTML( $this->editFormPageTop
);
2646 if ( $wgUser->getOption( 'previewontop' ) ) {
2647 $this->displayPreviewArea( $previewOutput, true );
2650 $out->addHTML( $this->editFormTextTop
);
2652 $showToolbar = true;
2653 if ( $this->wasDeletedSinceLastEdit() ) {
2654 if ( $this->formtype
== 'save' ) {
2655 // Hide the toolbar and edit area, user can click preview to get it back
2656 // Add an confirmation checkbox and explanation.
2657 $showToolbar = false;
2659 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2660 'deletedwhileediting' );
2664 // @todo add EditForm plugin interface and use it here!
2665 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2666 $out->addHTML( Html
::openElement(
2669 'class' => 'mw-editform',
2670 'id' => self
::EDITFORM_ID
,
2671 'name' => self
::EDITFORM_ID
,
2673 'action' => $this->getActionURL( $this->getContextTitle() ),
2674 'enctype' => 'multipart/form-data'
2678 if ( is_callable( $formCallback ) ) {
2679 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2680 call_user_func_array( $formCallback, [ &$out ] );
2683 // Add an empty field to trip up spambots
2685 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2688 [ 'for' => 'wpAntispam' ],
2689 $this->context
->msg( 'simpleantispam-label' )->parse()
2695 'name' => 'wpAntispam',
2696 'id' => 'wpAntispam',
2700 . Xml
::closeElement( 'div' )
2703 // Avoid PHP 7.1 warning of passing $this by reference
2705 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2707 // Put these up at the top to ensure they aren't lost on early form submission
2708 $this->showFormBeforeText();
2710 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2711 $username = $this->lastDelete
->user_name
;
2712 $comment = CommentStore
::newKey( 'log_comment' )->getComment( $this->lastDelete
)->text
;
2714 // It is better to not parse the comment at all than to have templates expanded in the middle
2715 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2716 $key = $comment === ''
2717 ?
'confirmrecreate-noreason'
2718 : 'confirmrecreate';
2720 '<div class="mw-confirm-recreate">' .
2721 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2722 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2723 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2729 # When the summary is hidden, also hide them on preview/show changes
2730 if ( $this->nosummary
) {
2731 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2734 # If a blank edit summary was previously provided, and the appropriate
2735 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2736 # user being bounced back more than once in the event that a summary
2739 # For a bit more sophisticated detection of blank summaries, hash the
2740 # automatic one and pass that in the hidden field wpAutoSummary.
2741 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2742 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2745 if ( $this->undidRev
) {
2746 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2749 if ( $this->selfRedirect
) {
2750 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2753 if ( $this->hasPresetSummary
) {
2754 // If a summary has been preset using &summary= we don't want to prompt for
2755 // a different summary. Only prompt for a summary if the summary is blanked.
2757 $this->autoSumm
= md5( '' );
2760 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2761 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2763 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2764 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2766 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2767 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2771 if ( $this->section
== 'new' ) {
2772 $this->showSummaryInput( true, $this->summary
);
2773 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2776 $out->addHTML( $this->editFormTextBeforeContent
);
2778 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2779 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2782 if ( $this->blankArticle
) {
2783 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2786 if ( $this->isConflict
) {
2787 // In an edit conflict bypass the overridable content form method
2788 // and fallback to the raw wpTextbox1 since editconflicts can't be
2789 // resolved between page source edits and custom ui edits using the
2791 $this->textbox2
= $this->textbox1
;
2793 $content = $this->getCurrentContent();
2794 $this->textbox1
= $this->toEditText( $content );
2796 $this->showTextbox1();
2798 $this->showContentForm();
2801 $out->addHTML( $this->editFormTextAfterContent
);
2803 $this->showStandardInputs();
2805 $this->showFormAfterText();
2807 $this->showTosSummary();
2809 $this->showEditTools();
2811 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2813 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2815 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2816 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2818 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2819 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2821 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2823 if ( $this->isConflict
) {
2825 $this->showConflict();
2826 } catch ( MWContentSerializationException
$ex ) {
2827 // this can't really happen, but be nice if it does.
2828 $msg = $this->context
->msg(
2829 'content-failed-to-parse',
2830 $this->contentModel
,
2831 $this->contentFormat
,
2834 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2838 // Set a hidden field so JS knows what edit form mode we are in
2839 if ( $this->isConflict
) {
2841 } elseif ( $this->preview
) {
2843 } elseif ( $this->diff
) {
2848 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2850 // Marker for detecting truncated form data. This must be the last
2851 // parameter sent in order to be of use, so do not move me.
2852 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2853 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2855 if ( !$wgUser->getOption( 'previewontop' ) ) {
2856 $this->displayPreviewArea( $previewOutput, false );
2861 * Wrapper around TemplatesOnThisPageFormatter to make
2862 * a "templates on this page" list.
2864 * @param Title[] $templates
2865 * @return string HTML
2867 public function makeTemplatesOnThisPageList( array $templates ) {
2868 $templateListFormatter = new TemplatesOnThisPageFormatter(
2869 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2872 // preview if preview, else section if section, else false
2874 if ( $this->preview
) {
2876 } elseif ( $this->section
!= '' ) {
2880 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2881 $templateListFormatter->format( $templates, $type )
2886 * Extract the section title from current section text, if any.
2888 * @param string $text
2889 * @return string|bool String or false
2891 public static function extractSectionTitle( $text ) {
2892 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2893 if ( !empty( $matches[2] ) ) {
2895 return $wgParser->stripSectionName( trim( $matches[2] ) );
2901 protected function showHeader() {
2903 global $wgAllowUserCss, $wgAllowUserJs;
2905 $out = $this->context
->getOutput();
2906 if ( $this->isConflict
) {
2907 $this->addExplainConflictHeader( $out );
2908 $this->editRevId
= $this->page
->getLatest();
2910 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2911 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2912 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2913 if ( $sectionTitle !== false ) {
2914 $this->summary
= "/* $sectionTitle */ ";
2919 $buttonLabel = $this->context
->msg( $this->getSaveButtonLabel() )->text();
2921 if ( $this->missingComment
) {
2922 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2925 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2927 "<div id='mw-missingsummary'>\n$1\n</div>",
2928 [ 'missingsummary', $buttonLabel ]
2932 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2934 "<div id='mw-missingcommentheader'>\n$1\n</div>",
2935 [ 'missingcommentheader', $buttonLabel ]
2939 if ( $this->blankArticle
) {
2941 "<div id='mw-blankarticle'>\n$1\n</div>",
2942 [ 'blankarticle', $buttonLabel ]
2946 if ( $this->selfRedirect
) {
2948 "<div id='mw-selfredirect'>\n$1\n</div>",
2949 [ 'selfredirect', $buttonLabel ]
2953 if ( $this->hookError
!== '' ) {
2954 $out->addWikiText( $this->hookError
);
2957 if ( !$this->checkUnicodeCompliantBrowser() ) {
2958 $out->addWikiMsg( 'nonunicodebrowser' );
2961 if ( $this->section
!= 'new' ) {
2962 $revision = $this->mArticle
->getRevisionFetched();
2964 // Let sysop know that this will make private content public if saved
2966 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2968 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2969 'rev-deleted-text-permission'
2971 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2973 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2974 'rev-deleted-text-view'
2978 if ( !$revision->isCurrent() ) {
2979 $this->mArticle
->setOldSubtitle( $revision->getId() );
2980 $out->addWikiMsg( 'editingold' );
2981 $this->isOldRev
= true;
2983 } elseif ( $this->mTitle
->exists() ) {
2984 // Something went wrong
2986 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2987 [ 'missing-revision', $this->oldid
] );
2992 if ( wfReadOnly() ) {
2994 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2995 [ 'readonlywarning', wfReadOnlyReason() ]
2997 } elseif ( $wgUser->isAnon() ) {
2998 if ( $this->formtype
!= 'preview' ) {
3000 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3001 [ 'anoneditwarning',
3003 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
3004 'returnto' => $this->getTitle()->getPrefixedDBkey()
3007 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3008 'returnto' => $this->getTitle()->getPrefixedDBkey()
3013 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3014 'anonpreviewwarning'
3018 if ( $this->isCssJsSubpage
) {
3019 # Check the skin exists
3020 if ( $this->isWrongCaseCssJsPage
) {
3022 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
3023 [ 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ]
3026 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
3027 $out->wrapWikiMsg( '<div class="mw-usercssjspublic">$1</div>',
3028 $this->isCssSubpage ?
'usercssispublic' : 'userjsispublic'
3030 if ( $this->formtype
!== 'preview' ) {
3031 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
3033 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3034 [ 'usercssyoucanpreview' ]
3038 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
3040 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3041 [ 'userjsyoucanpreview' ]
3049 $this->addPageProtectionWarningHeaders();
3051 $this->addLongPageWarningHeader();
3053 # Add header copyright warning
3054 $this->showHeaderCopyrightWarning();
3058 * Helper function for summary input functions, which returns the neccessary
3059 * attributes for the input.
3061 * @param array|null $inputAttrs Array of attrs to use on the input
3064 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3065 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
3066 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3067 'id' => 'wpSummary',
3068 'name' => 'wpSummary',
3069 'maxlength' => '200',
3072 'spellcheck' => 'true',
3077 * Standard summary input and label (wgSummary), abstracted so EditPage
3078 * subclasses may reorganize the form.
3079 * Note that you do not need to worry about the label's for=, it will be
3080 * inferred by the id given to the input. You can remove them both by
3081 * passing [ 'id' => false ] to $userInputAttrs.
3083 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3084 * @param string $summary The value of the summary input
3085 * @param string $labelText The html to place inside the label
3086 * @param array $inputAttrs Array of attrs to use on the input
3087 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
3088 * @return array An array in the format [ $label, $input ]
3090 public function getSummaryInput( $summary = "", $labelText = null,
3091 $inputAttrs = null, $spanLabelAttrs = null
3093 wfDeprecated( __METHOD__
, '1.30' );
3094 $inputAttrs = $this->getSummaryInputAttributes( $inputAttrs );
3095 $inputAttrs +
= Linker
::tooltipAndAccesskeyAttribs( 'summary' );
3097 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : [] ) +
[
3098 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
3099 'id' => "wpSummaryLabel"
3106 $inputAttrs['id'] ?
[ 'for' => $inputAttrs['id'] ] : null,
3109 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
3112 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
3114 return [ $label, $input ];
3118 * Builds a standard summary input with a label.
3120 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3121 * @param string $summary The value of the summary input
3122 * @param string $labelText The html to place inside the label
3123 * @param array $inputAttrs Array of attrs to use on the input
3125 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3127 function getSummaryInputOOUI( $summary = "", $labelText = null, $inputAttrs = null ) {
3128 wfDeprecated( __METHOD__
, '1.30' );
3129 $this->getSummaryInputWidget( $summary, $labelText, $inputAttrs );
3133 * Builds a standard summary input with a label.
3135 * @param string $summary The value of the summary input
3136 * @param string $labelText The html to place inside the label
3137 * @param array $inputAttrs Array of attrs to use on the input
3139 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3141 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3142 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3143 $this->getSummaryInputAttributes( $inputAttrs )
3146 'title' => Linker
::titleAttrib( 'summary' ),
3147 'accessKey' => Linker
::accesskey( 'summary' ),
3150 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3151 $inputAttrs['inputId'] = $inputAttrs['id'];
3152 $inputAttrs['id'] = 'wpSummaryWidget';
3154 return new OOUI\
FieldLayout(
3155 new OOUI\
TextInputWidget( [
3156 'value' => $summary,
3157 'infusable' => true,
3160 'label' => new OOUI\
HtmlSnippet( $labelText ),
3162 'id' => 'wpSummaryLabel',
3163 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3169 * @param bool $isSubjectPreview True if this is the section subject/title
3170 * up top, or false if this is the comment summary
3171 * down below the textarea
3172 * @param string $summary The text of the summary to display
3174 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3175 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3176 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3177 if ( $isSubjectPreview ) {
3178 if ( $this->nosummary
) {
3182 if ( !$this->mShowSummaryField
) {
3187 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3188 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3191 [ 'class' => $summaryClass ]
3196 * @param bool $isSubjectPreview True if this is the section subject/title
3197 * up top, or false if this is the comment summary
3198 * down below the textarea
3199 * @param string $summary The text of the summary to display
3202 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3203 // avoid spaces in preview, gets always trimmed on save
3204 $summary = trim( $summary );
3205 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3211 if ( $isSubjectPreview ) {
3212 $summary = $this->context
->msg( 'newsectionsummary' )
3213 ->rawParams( $wgParser->stripSectionName( $summary ) )
3214 ->inContentLanguage()->text();
3217 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3219 $summary = $this->context
->msg( $message )->parse()
3220 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3221 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3224 protected function showFormBeforeText() {
3225 $out = $this->context
->getOutput();
3226 $out->addHTML( Html
::hidden( 'wpSection', htmlspecialchars( $this->section
) ) );
3227 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3228 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3229 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3230 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3232 if ( !$this->checkUnicodeCompliantBrowser() ) {
3233 $out->addHTML( Html
::hidden( 'safemode', '1' ) );
3237 protected function showFormAfterText() {
3240 * To make it harder for someone to slip a user a page
3241 * which submits an edit form to the wiki without their
3242 * knowledge, a random token is associated with the login
3243 * session. If it's not passed back with the submission,
3244 * we won't save the page, or render user JavaScript and
3247 * For anon editors, who may not have a session, we just
3248 * include the constant suffix to prevent editing from
3249 * broken text-mangling proxies.
3251 $this->context
->getOutput()->addHTML(
3252 "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n"
3257 * Subpage overridable method for printing the form for page content editing
3258 * By default this simply outputs wpTextbox1
3259 * Subclasses can override this to provide a custom UI for editing;
3260 * be it a form, or simply wpTextbox1 with a modified content that will be
3261 * reverse modified when extracted from the post data.
3262 * Note that this is basically the inverse for importContentFormData
3264 protected function showContentForm() {
3265 $this->showTextbox1();
3269 * Method to output wpTextbox1
3270 * The $textoverride method can be used by subclasses overriding showContentForm
3271 * to pass back to this method.
3273 * @param array $customAttribs Array of html attributes to use in the textarea
3274 * @param string $textoverride Optional text to override $this->textarea1 with
3276 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3277 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3278 $attribs = [ 'style' => 'display:none;' ];
3280 $classes = []; // Textarea CSS
3281 if ( $this->mTitle
->isProtected( 'edit' ) &&
3282 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
3284 # Is the title semi-protected?
3285 if ( $this->mTitle
->isSemiProtected() ) {
3286 $classes[] = 'mw-textarea-sprotected';
3288 # Then it must be protected based on static groups (regular)
3289 $classes[] = 'mw-textarea-protected';
3291 # Is the title cascade-protected?
3292 if ( $this->mTitle
->isCascadeProtected() ) {
3293 $classes[] = 'mw-textarea-cprotected';
3296 # Is an old revision being edited?
3297 if ( $this->isOldRev
) {
3298 $classes[] = 'mw-textarea-oldrev';
3301 $attribs = [ 'tabindex' => 1 ];
3303 if ( is_array( $customAttribs ) ) {
3304 $attribs +
= $customAttribs;
3307 if ( count( $classes ) ) {
3308 if ( isset( $attribs['class'] ) ) {
3309 $classes[] = $attribs['class'];
3311 $attribs['class'] = implode( ' ', $classes );
3316 $textoverride !== null ?
$textoverride : $this->textbox1
,
3322 protected function showTextbox2() {
3323 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3326 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3329 $wikitext = $this->safeUnicodeOutput( $text );
3330 $wikitext = $this->addNewLineAtEnd( $wikitext );
3332 $attribs = $this->buildTextboxAttribs( $name, $customAttribs, $wgUser );
3334 $this->context
->getOutput()->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3337 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3340 $classes[] = 'ontop';
3343 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3345 if ( $this->formtype
!= 'preview' ) {
3346 $attribs['style'] = 'display: none;';
3349 $out = $this->context
->getOutput();
3350 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3352 if ( $this->formtype
== 'preview' ) {
3353 $this->showPreview( $previewOutput );
3355 // Empty content container for LivePreview
3356 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3357 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3358 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3359 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3362 $out->addHTML( '</div>' );
3364 if ( $this->formtype
== 'diff' ) {
3367 } catch ( MWContentSerializationException
$ex ) {
3368 $msg = $this->context
->msg(
3369 'content-failed-to-parse',
3370 $this->contentModel
,
3371 $this->contentFormat
,
3374 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3380 * Append preview output to OutputPage.
3381 * Includes category rendering if this is a category page.
3383 * @param string $text The HTML to be output for the preview.
3385 protected function showPreview( $text ) {
3386 if ( $this->mArticle
instanceof CategoryPage
) {
3387 $this->mArticle
->openShowCategory();
3389 # This hook seems slightly odd here, but makes things more
3390 # consistent for extensions.
3391 $out = $this->context
->getOutput();
3392 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3393 $out->addHTML( $text );
3394 if ( $this->mArticle
instanceof CategoryPage
) {
3395 $this->mArticle
->closeShowCategory();
3400 * Get a diff between the current contents of the edit box and the
3401 * version of the page we're editing from.
3403 * If this is a section edit, we'll replace the section as for final
3404 * save and then make a comparison.
3406 public function showDiff() {
3407 global $wgUser, $wgContLang;
3409 $oldtitlemsg = 'currentrev';
3410 # if message does not exist, show diff against the preloaded default
3411 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3412 $oldtext = $this->mTitle
->getDefaultMessageText();
3413 if ( $oldtext !== false ) {
3414 $oldtitlemsg = 'defaultmessagetext';
3415 $oldContent = $this->toEditContent( $oldtext );
3420 $oldContent = $this->getCurrentContent();
3423 $textboxContent = $this->toEditContent( $this->textbox1
);
3424 if ( $this->editRevId
!== null ) {
3425 $newContent = $this->page
->replaceSectionAtRev(
3426 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3429 $newContent = $this->page
->replaceSectionContent(
3430 $this->section
, $textboxContent, $this->summary
, $this->edittime
3434 if ( $newContent ) {
3435 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3437 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
3438 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
3441 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3442 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3443 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3445 if ( !$oldContent ) {
3446 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3449 if ( !$newContent ) {
3450 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3453 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3454 $de->setContent( $oldContent, $newContent );
3456 $difftext = $de->getDiff( $oldtitle, $newtitle );
3457 $de->showDiffStyle();
3462 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3466 * Show the header copyright warning.
3468 protected function showHeaderCopyrightWarning() {
3469 $msg = 'editpage-head-copy-warn';
3470 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3471 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3472 'editpage-head-copy-warn' );
3477 * Give a chance for site and per-namespace customizations of
3478 * terms of service summary link that might exist separately
3479 * from the copyright notice.
3481 * This will display between the save button and the edit tools,
3482 * so should remain short!
3484 protected function showTosSummary() {
3485 $msg = 'editpage-tos-summary';
3486 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3487 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3488 $out = $this->context
->getOutput();
3489 $out->addHTML( '<div class="mw-tos-summary">' );
3490 $out->addWikiMsg( $msg );
3491 $out->addHTML( '</div>' );
3496 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3497 * characters not present on most keyboards for copying/pasting.
3499 protected function showEditTools() {
3500 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3501 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3506 * Get the copyright warning
3508 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3511 protected function getCopywarn() {
3512 return self
::getCopyrightWarning( $this->mTitle
);
3516 * Get the copyright warning, by default returns wikitext
3518 * @param Title $title
3519 * @param string $format Output format, valid values are any function of a Message object
3520 * @param Language|string|null $langcode Language code or Language object.
3523 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3524 global $wgRightsText;
3525 if ( $wgRightsText ) {
3526 $copywarnMsg = [ 'copyrightwarning',
3527 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3530 $copywarnMsg = [ 'copyrightwarning2',
3531 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3533 // Allow for site and per-namespace customization of contribution/copyright notice.
3534 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3536 $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
3538 $msg->inLanguage( $langcode );
3540 return "<div id=\"editpage-copywarn\">\n" .
3541 $msg->$format() . "\n</div>";
3545 * Get the Limit report for page previews
3548 * @param ParserOutput $output ParserOutput object from the parse
3549 * @return string HTML
3551 public static function getPreviewLimitReport( $output ) {
3552 if ( !$output ||
!$output->getLimitReportData() ) {
3556 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3557 wfMessage( 'limitreport-title' )->parseAsBlock()
3560 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3561 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3563 $limitReport .= Html
::openElement( 'table', [
3564 'class' => 'preview-limit-report wikitable'
3566 Html
::openElement( 'tbody' );
3568 foreach ( $output->getLimitReportData() as $key => $value ) {
3569 if ( Hooks
::run( 'ParserLimitReportFormat',
3570 [ $key, &$value, &$limitReport, true, true ]
3572 $keyMsg = wfMessage( $key );
3573 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3574 if ( !$valueMsg->exists() ) {
3575 $valueMsg = new RawMessage( '$1' );
3577 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3578 $limitReport .= Html
::openElement( 'tr' ) .
3579 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3580 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3581 Html
::closeElement( 'tr' );
3586 $limitReport .= Html
::closeElement( 'tbody' ) .
3587 Html
::closeElement( 'table' ) .
3588 Html
::closeElement( 'div' );
3590 return $limitReport;
3593 protected function showStandardInputs( &$tabindex = 2 ) {
3594 $out = $this->context
->getOutput();
3595 $out->addHTML( "<div class='editOptions'>\n" );
3597 if ( $this->section
!= 'new' ) {
3598 $this->showSummaryInput( false, $this->summary
);
3599 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3602 $checkboxes = $this->getCheckboxesWidget(
3604 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3606 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3608 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3610 // Show copyright warning.
3611 $out->addWikiText( $this->getCopywarn() );
3612 $out->addHTML( $this->editFormTextAfterWarn
);
3614 $out->addHTML( "<div class='editButtons'>\n" );
3615 $out->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3617 $cancel = $this->getCancelLink();
3618 if ( $cancel !== '' ) {
3619 $cancel .= Html
::element( 'span',
3620 [ 'class' => 'mw-editButtons-pipe-separator' ],
3621 $this->context
->msg( 'pipe-separator' )->text() );
3624 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3625 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3628 $this->context
->msg( 'edithelp' )->text(),
3629 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3632 $this->context
->msg( 'word-separator' )->escaped() .
3633 $this->context
->msg( 'newwindow' )->parse();
3635 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3636 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3637 $out->addHTML( "</div><!-- editButtons -->\n" );
3639 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3641 $out->addHTML( "</div><!-- editOptions -->\n" );
3645 * Show an edit conflict. textbox1 is already shown in showEditForm().
3646 * If you want to use another entry point to this function, be careful.
3648 protected function showConflict() {
3649 $out = $this->context
->getOutput();
3650 // Avoid PHP 7.1 warning of passing $this by reference
3652 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3653 $this->incrementConflictStats();
3655 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3657 $content1 = $this->toEditContent( $this->textbox1
);
3658 $content2 = $this->toEditContent( $this->textbox2
);
3660 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3661 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3662 $de->setContent( $content2, $content1 );
3664 $this->context
->msg( 'yourtext' )->parse(),
3665 $this->context
->msg( 'storedversion' )->text()
3668 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3669 $this->showTextbox2();
3673 protected function incrementConflictStats() {
3674 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3675 $stats->increment( 'edit.failures.conflict' );
3676 // Only include 'standard' namespaces to avoid creating unknown numbers of statsd metrics
3678 $this->mTitle
->getNamespace() >= NS_MAIN
&&
3679 $this->mTitle
->getNamespace() <= NS_CATEGORY_TALK
3681 $stats->increment( 'edit.failures.conflict.byNamespaceId.' . $this->mTitle
->getNamespace() );
3688 public function getCancelLink() {
3690 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3691 $cancelParams['oldid'] = $this->oldid
;
3692 } elseif ( $this->getContextTitle()->isRedirect() ) {
3693 $cancelParams['redirect'] = 'no';
3696 return new OOUI\
ButtonWidget( [
3697 'id' => 'mw-editform-cancel',
3698 'href' => $this->getContextTitle()->getLinkUrl( $cancelParams ),
3699 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3701 'infusable' => true,
3702 'flags' => 'destructive',
3707 * Returns the URL to use in the form's action attribute.
3708 * This is used by EditPage subclasses when simply customizing the action
3709 * variable in the constructor is not enough. This can be used when the
3710 * EditPage lives inside of a Special page rather than a custom page action.
3712 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3715 protected function getActionURL( Title
$title ) {
3716 return $title->getLocalURL( [ 'action' => $this->action
] );
3720 * Check if a page was deleted while the user was editing it, before submit.
3721 * Note that we rely on the logging table, which hasn't been always there,
3722 * but that doesn't matter, because this only applies to brand new
3726 protected function wasDeletedSinceLastEdit() {
3727 if ( $this->deletedSinceEdit
!== null ) {
3728 return $this->deletedSinceEdit
;
3731 $this->deletedSinceEdit
= false;
3733 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3734 $this->lastDelete
= $this->getLastDelete();
3735 if ( $this->lastDelete
) {
3736 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3737 if ( $deleteTime > $this->starttime
) {
3738 $this->deletedSinceEdit
= true;
3743 return $this->deletedSinceEdit
;
3747 * @return bool|stdClass
3749 protected function getLastDelete() {
3750 $dbr = wfGetDB( DB_REPLICA
);
3751 $commentQuery = CommentStore
::newKey( 'log_comment' )->getJoin();
3752 $data = $dbr->selectRow(
3753 [ 'logging', 'user' ] +
$commentQuery['tables'],
3764 ] +
$commentQuery['fields'], [
3765 'log_namespace' => $this->mTitle
->getNamespace(),
3766 'log_title' => $this->mTitle
->getDBkey(),
3767 'log_type' => 'delete',
3768 'log_action' => 'delete',
3772 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3774 'user' => [ 'JOIN', 'user_id=log_user' ],
3775 ] +
$commentQuery['joins']
3777 // Quick paranoid permission checks...
3778 if ( is_object( $data ) ) {
3779 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3780 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3783 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3784 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3785 $data->log_comment_data
= null;
3793 * Get the rendered text for previewing.
3794 * @throws MWException
3797 public function getPreviewText() {
3798 global $wgRawHtml, $wgLang;
3799 global $wgAllowUserCss, $wgAllowUserJs;
3801 $out = $this->context
->getOutput();
3803 if ( $wgRawHtml && !$this->mTokenOk
) {
3804 // Could be an offsite preview attempt. This is very unsafe if
3805 // HTML is enabled, as it could be an attack.
3807 if ( $this->textbox1
!== '' ) {
3808 // Do not put big scary notice, if previewing the empty
3809 // string, which happens when you initially edit
3810 // a category page, due to automatic preview-on-open.
3811 $parsedNote = $out->parse( "<div class='previewnote'>" .
3812 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3813 true, /* interface */true );
3815 $this->incrementEditFailureStats( 'session_loss' );
3822 $content = $this->toEditContent( $this->textbox1
);
3826 'AlternateEditPreview',
3827 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3829 return $previewHTML;
3832 # provide a anchor link to the editform
3833 $continueEditing = '<span class="mw-continue-editing">' .
3834 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3835 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3836 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3837 if ( $this->mTokenOkExceptSuffix
) {
3838 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3839 $this->incrementEditFailureStats( 'bad_token' );
3841 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3842 $this->incrementEditFailureStats( 'session_loss' );
3844 } elseif ( $this->incompleteForm
) {
3845 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3846 if ( $this->mTriedSave
) {
3847 $this->incrementEditFailureStats( 'incomplete_form' );
3850 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3853 # don't parse non-wikitext pages, show message about preview
3854 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3855 if ( $this->mTitle
->isCssJsSubpage() ) {
3857 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3863 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3865 if ( $level === 'user' && !$wgAllowUserCss ) {
3868 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3870 if ( $level === 'user' && !$wgAllowUserJs ) {
3877 # Used messages to make sure grep find them:
3878 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3879 if ( $level && $format ) {
3880 $note = "<div id='mw-{$level}{$format}preview'>" .
3881 $this->context
->msg( "{$level}{$format}preview" )->text() .
3882 ' ' . $continueEditing . "</div>";
3886 # If we're adding a comment, we need to show the
3887 # summary as the headline
3888 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3889 $content = $content->addSectionHeader( $this->summary
);
3892 $hook_args = [ $this, &$content ];
3893 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3895 $parserResult = $this->doPreviewParse( $content );
3896 $parserOutput = $parserResult['parserOutput'];
3897 $previewHTML = $parserResult['html'];
3898 $this->mParserOutput
= $parserOutput;
3899 $out->addParserOutputMetadata( $parserOutput );
3901 if ( count( $parserOutput->getWarnings() ) ) {
3902 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3905 } catch ( MWContentSerializationException
$ex ) {
3906 $m = $this->context
->msg(
3907 'content-failed-to-parse',
3908 $this->contentModel
,
3909 $this->contentFormat
,
3912 $note .= "\n\n" . $m->parse();
3916 if ( $this->isConflict
) {
3917 $conflict = '<h2 id="mw-previewconflict">'
3918 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3920 $conflict = '<hr />';
3923 $previewhead = "<div class='previewnote'>\n" .
3924 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3925 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3927 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3928 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3929 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3930 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3932 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3935 private function incrementEditFailureStats( $failureType ) {
3936 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3937 $stats->increment( 'edit.failures.' . $failureType );
3941 * Get parser options for a preview
3942 * @return ParserOptions
3944 protected function getPreviewParserOptions() {
3945 $parserOptions = $this->page
->makeParserOptions( $this->mArticle
->getContext() );
3946 $parserOptions->setIsPreview( true );
3947 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3948 $parserOptions->enableLimitReport();
3949 return $parserOptions;
3953 * Parse the page for a preview. Subclasses may override this class, in order
3954 * to parse with different options, or to otherwise modify the preview HTML.
3956 * @param Content $content The page content
3957 * @return array with keys:
3958 * - parserOutput: The ParserOutput object
3959 * - html: The HTML to be displayed
3961 protected function doPreviewParse( Content
$content ) {
3963 $parserOptions = $this->getPreviewParserOptions();
3964 $pstContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3965 $scopedCallback = $parserOptions->setupFakeRevision(
3966 $this->mTitle
, $pstContent, $wgUser );
3967 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3968 ScopedCallback
::consume( $scopedCallback );
3969 $parserOutput->setEditSectionTokens( false ); // no section edit links
3971 'parserOutput' => $parserOutput,
3972 'html' => $parserOutput->getText() ];
3978 public function getTemplates() {
3979 if ( $this->preview ||
$this->section
!= '' ) {
3981 if ( !isset( $this->mParserOutput
) ) {
3984 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3985 foreach ( array_keys( $template ) as $dbk ) {
3986 $templates[] = Title
::makeTitle( $ns, $dbk );
3991 return $this->mTitle
->getTemplateLinksFrom();
3996 * Shows a bulletin board style toolbar for common editing functions.
3997 * It can be disabled in the user preferences.
3999 * @param Title $title Title object for the page being edited (optional)
4002 public static function getEditToolbar( $title = null ) {
4003 global $wgContLang, $wgOut;
4004 global $wgEnableUploads, $wgForeignFileRepos;
4006 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
4007 $showSignature = true;
4009 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4013 * $toolarray is an array of arrays each of which includes the
4014 * opening tag, the closing tag, optionally a sample text that is
4015 * inserted between the two when no selection is highlighted
4016 * and. The tip text is shown when the user moves the mouse
4019 * Images are defined in ResourceLoaderEditToolbarModule.
4023 'id' => 'mw-editbutton-bold',
4025 'close' => '\'\'\'',
4026 'sample' => wfMessage( 'bold_sample' )->text(),
4027 'tip' => wfMessage( 'bold_tip' )->text(),
4030 'id' => 'mw-editbutton-italic',
4033 'sample' => wfMessage( 'italic_sample' )->text(),
4034 'tip' => wfMessage( 'italic_tip' )->text(),
4037 'id' => 'mw-editbutton-link',
4040 'sample' => wfMessage( 'link_sample' )->text(),
4041 'tip' => wfMessage( 'link_tip' )->text(),
4044 'id' => 'mw-editbutton-extlink',
4047 'sample' => wfMessage( 'extlink_sample' )->text(),
4048 'tip' => wfMessage( 'extlink_tip' )->text(),
4051 'id' => 'mw-editbutton-headline',
4054 'sample' => wfMessage( 'headline_sample' )->text(),
4055 'tip' => wfMessage( 'headline_tip' )->text(),
4057 $imagesAvailable ?
[
4058 'id' => 'mw-editbutton-image',
4059 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4061 'sample' => wfMessage( 'image_sample' )->text(),
4062 'tip' => wfMessage( 'image_tip' )->text(),
4064 $imagesAvailable ?
[
4065 'id' => 'mw-editbutton-media',
4066 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4068 'sample' => wfMessage( 'media_sample' )->text(),
4069 'tip' => wfMessage( 'media_tip' )->text(),
4072 'id' => 'mw-editbutton-nowiki',
4073 'open' => "<nowiki>",
4074 'close' => "</nowiki>",
4075 'sample' => wfMessage( 'nowiki_sample' )->text(),
4076 'tip' => wfMessage( 'nowiki_tip' )->text(),
4079 'id' => 'mw-editbutton-signature',
4080 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4083 'tip' => wfMessage( 'sig_tip' )->text(),
4086 'id' => 'mw-editbutton-hr',
4087 'open' => "\n----\n",
4090 'tip' => wfMessage( 'hr_tip' )->text(),
4094 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4095 foreach ( $toolarray as $tool ) {
4101 // Images are defined in ResourceLoaderEditToolbarModule
4103 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4104 // Older browsers show a "speedtip" type message only for ALT.
4105 // Ideally these should be different, realistically they
4106 // probably don't need to be.
4114 $script .= Xml
::encodeJsCall(
4115 'mw.toolbar.addButton',
4117 ResourceLoader
::inDebugMode()
4123 $toolbar = '<div id="toolbar"></div>';
4125 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4126 // Only add the old toolbar cruft to the page payload if the toolbar has not
4127 // been over-written by a hook caller
4128 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
4135 * Return an array of checkbox definitions.
4137 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4139 * Array values are associative arrays with the following keys:
4140 * - 'label-message' (required): message for label text
4141 * - 'id' (required): 'id' attribute for the `<input>`
4142 * - 'default' (required): default checkedness (true or false)
4143 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4144 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4145 * from messages like 'tooltip-foo', 'accesskey-foo'
4146 * - 'label-id' (optional): 'id' attribute for the `<label>`
4147 * - 'legacy-name' (optional): short name for backwards-compatibility
4148 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4149 * where bool indicates the checked status of the checkbox
4152 public function getCheckboxesDefinition( $checked ) {
4156 // don't show the minor edit checkbox if it's a new page or section
4157 if ( !$this->isNew
&& $wgUser->isAllowed( 'minoredit' ) ) {
4158 $checkboxes['wpMinoredit'] = [
4159 'id' => 'wpMinoredit',
4160 'label-message' => 'minoredit',
4161 // Uses messages: tooltip-minoredit, accesskey-minoredit
4162 'tooltip' => 'minoredit',
4163 'label-id' => 'mw-editpage-minoredit',
4164 'legacy-name' => 'minor',
4165 'default' => $checked['minor'],
4169 if ( $wgUser->isLoggedIn() ) {
4170 $checkboxes['wpWatchthis'] = [
4171 'id' => 'wpWatchthis',
4172 'label-message' => 'watchthis',
4173 // Uses messages: tooltip-watch, accesskey-watch
4174 'tooltip' => 'watch',
4175 'label-id' => 'mw-editpage-watch',
4176 'legacy-name' => 'watch',
4177 'default' => $checked['watch'],
4182 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4188 * Returns an array of html code of the following checkboxes old style:
4191 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4192 * @param int &$tabindex Current tabindex
4193 * @param array $checked See getCheckboxesDefinition()
4196 public function getCheckboxes( &$tabindex, $checked ) {
4197 global $wgUseMediaWikiUIEverywhere;
4200 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4202 // Backwards-compatibility for the EditPageBeforeEditChecks hook
4203 if ( !$this->isNew
) {
4204 $checkboxes['minor'] = '';
4206 $checkboxes['watch'] = '';
4208 foreach ( $checkboxesDef as $name => $options ) {
4209 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4210 $label = $this->context
->msg( $options['label-message'] )->parse();
4212 'tabindex' => ++
$tabindex,
4213 'id' => $options['id'],
4216 'for' => $options['id'],
4218 if ( isset( $options['tooltip'] ) ) {
4219 $attribs['accesskey'] = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4220 $labelAttribs['title'] = Linker
::titleAttrib( $options['tooltip'], 'withaccess' );
4222 if ( isset( $options['title-message'] ) ) {
4223 $labelAttribs['title'] = $this->context
->msg( $options['title-message'] )->text();
4225 if ( isset( $options['label-id'] ) ) {
4226 $labelAttribs['id'] = $options['label-id'];
4229 Xml
::check( $name, $options['default'], $attribs ) .
4231 Xml
::tags( 'label', $labelAttribs, $label );
4233 if ( $wgUseMediaWikiUIEverywhere ) {
4234 $checkboxHtml = Html
::rawElement( 'div', [ 'class' => 'mw-ui-checkbox' ], $checkboxHtml );
4237 $checkboxes[ $legacyName ] = $checkboxHtml;
4240 // Avoid PHP 7.1 warning of passing $this by reference
4242 Hooks
::run( 'EditPageBeforeEditChecks', [ &$editPage, &$checkboxes, &$tabindex ], '1.29' );
4247 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4248 * any other added by extensions.
4250 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4251 * @param int &$tabindex Current tabindex
4252 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4253 * status of the checkbox
4255 * @return array Associative array of string keys to OOUI\FieldLayout instances
4257 public function getCheckboxesOOUI( &$tabindex, $checked ) {
4258 return $this->getCheckboxesWidget( $tabindex, $checked );
4262 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4263 * any other added by extensions.
4265 * @param int &$tabindex Current tabindex
4266 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4267 * status of the checkbox
4269 * @return array Associative array of string keys to OOUI\FieldLayout instances
4271 public function getCheckboxesWidget( &$tabindex, $checked ) {
4273 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4275 foreach ( $checkboxesDef as $name => $options ) {
4276 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4280 if ( isset( $options['tooltip'] ) ) {
4281 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4282 $title = Linker
::titleAttrib( $options['tooltip'] );
4284 if ( isset( $options['title-message'] ) ) {
4285 $title = $this->context
->msg( $options['title-message'] )->text();
4288 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4289 new OOUI\
CheckboxInputWidget( [
4290 'tabIndex' => ++
$tabindex,
4291 'accessKey' => $accesskey,
4292 'id' => $options['id'] . 'Widget',
4293 'inputId' => $options['id'],
4295 'selected' => $options['default'],
4296 'infusable' => true,
4299 'align' => 'inline',
4300 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4302 'id' => isset( $options['label-id'] ) ?
$options['label-id'] : null,
4307 // Backwards-compatibility hack to run the EditPageBeforeEditChecks hook. It's important,
4308 // people have used it for the weirdest things completely unrelated to checkboxes...
4309 // And if we're gonna run it, might as well allow its legacy checkboxes to be shown.
4310 $legacyCheckboxes = [];
4311 if ( !$this->isNew
) {
4312 $legacyCheckboxes['minor'] = '';
4314 $legacyCheckboxes['watch'] = '';
4315 // Copy new-style checkboxes into an old-style structure
4316 foreach ( $checkboxes as $name => $oouiLayout ) {
4317 $legacyCheckboxes[$name] = (string)$oouiLayout;
4319 // Avoid PHP 7.1 warning of passing $this by reference
4321 Hooks
::run( 'EditPageBeforeEditChecks', [ &$ep, &$legacyCheckboxes, &$tabindex ], '1.29' );
4322 // Copy back any additional old-style checkboxes into the new-style structure
4323 foreach ( $legacyCheckboxes as $name => $html ) {
4324 if ( $html && !isset( $checkboxes[$name] ) ) {
4325 $checkboxes[$name] = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $html ) ] );
4333 * Get the message key of the label for the button to save the page
4337 private function getSaveButtonLabel() {
4339 $this->mArticle
->getContext()->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4341 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4342 $newPage = !$this->mTitle
->exists();
4344 if ( $labelAsPublish ) {
4345 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4347 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4350 return $buttonLabelKey;
4354 * Returns an array of html code of the following buttons:
4355 * save, diff and preview
4357 * @param int &$tabindex Current tabindex
4361 public function getEditButtons( &$tabindex ) {
4364 $buttonLabel = $this->context
->msg( $this->getSaveButtonLabel() )->text();
4368 'tabindex' => ++
$tabindex,
4371 $saveConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4372 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4373 'id' => 'wpSaveWidget',
4374 'inputId' => 'wpSave',
4375 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4376 'useInputTag' => true,
4377 'flags' => [ 'constructive', 'primary' ],
4378 'label' => $buttonLabel,
4379 'infusable' => true,
4381 'title' => Linker
::titleAttrib( 'save' ),
4382 'accessKey' => Linker
::accesskey( 'save' ),
4386 'name' => 'wpPreview',
4387 'tabindex' => ++
$tabindex,
4390 $previewConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4391 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4392 'id' => 'wpPreviewWidget',
4393 'inputId' => 'wpPreview',
4394 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4395 'useInputTag' => true,
4396 'label' => $this->context
->msg( 'showpreview' )->text(),
4397 'infusable' => true,
4399 'title' => Linker
::titleAttrib( 'preview' ),
4400 'accessKey' => Linker
::accesskey( 'preview' ),
4401 ] +
$previewConfig );
4405 'tabindex' => ++
$tabindex,
4408 $diffConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4409 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4410 'id' => 'wpDiffWidget',
4411 'inputId' => 'wpDiff',
4412 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4413 'useInputTag' => true,
4414 'label' => $this->context
->msg( 'showdiff' )->text(),
4415 'infusable' => true,
4417 'title' => Linker
::titleAttrib( 'diff' ),
4418 'accessKey' => Linker
::accesskey( 'diff' ),
4421 // Avoid PHP 7.1 warning of passing $this by reference
4423 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4429 * Creates a basic error page which informs the user that
4430 * they have attempted to edit a nonexistent section.
4432 public function noSuchSectionPage() {
4433 $out = $this->context
->getOutput();
4434 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4436 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4438 // Avoid PHP 7.1 warning of passing $this by reference
4440 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4441 $out->addHTML( $res );
4443 $out->returnToMain( false, $this->mTitle
);
4447 * Show "your edit contains spam" page with your diff and text
4449 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4451 public function spamPageWithContent( $match = false ) {
4453 $this->textbox2
= $this->textbox1
;
4455 if ( is_array( $match ) ) {
4456 $match = $wgLang->listToText( $match );
4458 $out = $this->context
->getOutput();
4459 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4461 $out->addHTML( '<div id="spamprotected">' );
4462 $out->addWikiMsg( 'spamprotectiontext' );
4464 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4466 $out->addHTML( '</div>' );
4468 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4471 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4472 $this->showTextbox2();
4474 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4478 * Check if the browser is on a blacklist of user-agents known to
4479 * mangle UTF-8 data on form submission. Returns true if Unicode
4480 * should make it through, false if it's known to be a problem.
4483 private function checkUnicodeCompliantBrowser() {
4484 global $wgBrowserBlackList, $wgRequest;
4486 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
4487 if ( $currentbrowser === false ) {
4488 // No User-Agent header sent? Trust it by default...
4492 foreach ( $wgBrowserBlackList as $browser ) {
4493 if ( preg_match( $browser, $currentbrowser ) ) {
4501 * Filter an input field through a Unicode de-armoring process if it
4502 * came from an old browser with known broken Unicode editing issues.
4504 * @param WebRequest $request
4505 * @param string $field
4508 protected function safeUnicodeInput( $request, $field ) {
4509 $text = rtrim( $request->getText( $field ) );
4510 return $request->getBool( 'safemode' )
4511 ?
$this->unmakeSafe( $text )
4516 * Filter an output field through a Unicode armoring process if it is
4517 * going to an old browser with known broken Unicode editing issues.
4519 * @param string $text
4522 protected function safeUnicodeOutput( $text ) {
4523 return $this->checkUnicodeCompliantBrowser()
4525 : $this->makeSafe( $text );
4529 * A number of web browsers are known to corrupt non-ASCII characters
4530 * in a UTF-8 text editing environment. To protect against this,
4531 * detected browsers will be served an armored version of the text,
4532 * with non-ASCII chars converted to numeric HTML character references.
4534 * Preexisting such character references will have a 0 added to them
4535 * to ensure that round-trips do not alter the original data.
4537 * @param string $invalue
4540 private function makeSafe( $invalue ) {
4541 // Armor existing references for reversibility.
4542 $invalue = strtr( $invalue, [ "&#x" => "�" ] );
4547 $valueLength = strlen( $invalue );
4548 for ( $i = 0; $i < $valueLength; $i++
) {
4549 $bytevalue = ord( $invalue[$i] );
4550 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4551 $result .= chr( $bytevalue );
4553 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4554 $working = $working << 6;
4555 $working +
= ( $bytevalue & 0x3F );
4557 if ( $bytesleft <= 0 ) {
4558 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4560 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4561 $working = $bytevalue & 0x1F;
4563 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4564 $working = $bytevalue & 0x0F;
4566 } else { // 1111 0xxx
4567 $working = $bytevalue & 0x07;
4575 * Reverse the previously applied transliteration of non-ASCII characters
4576 * back to UTF-8. Used to protect data from corruption by broken web browsers
4577 * as listed in $wgBrowserBlackList.
4579 * @param string $invalue
4582 private function unmakeSafe( $invalue ) {
4584 $valueLength = strlen( $invalue );
4585 for ( $i = 0; $i < $valueLength; $i++
) {
4586 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4590 $hexstring .= $invalue[$i];
4592 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4594 // Do some sanity checks. These aren't needed for reversibility,
4595 // but should help keep the breakage down if the editor
4596 // breaks one of the entities whilst editing.
4597 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4598 $codepoint = hexdec( $hexstring );
4599 $result .= UtfNormal\Utils
::codepointToUtf8( $codepoint );
4601 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4604 $result .= substr( $invalue, $i, 1 );
4607 // reverse the transform that we made for reversibility reasons.
4608 return strtr( $result, [ "�" => "&#x" ] );
4614 protected function addEditNotices() {
4615 $out = $this->context
->getOutput();
4616 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4617 if ( count( $editNotices ) ) {
4618 $out->addHTML( implode( "\n", $editNotices ) );
4620 $msg = $this->context
->msg( 'editnotice-notext' );
4621 if ( !$msg->isDisabled() ) {
4623 '<div class="mw-editnotice-notext">'
4624 . $msg->parseAsBlock()
4634 protected function addTalkPageText() {
4635 if ( $this->mTitle
->isTalkPage() ) {
4636 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4643 protected function addLongPageWarningHeader() {
4644 global $wgMaxArticleSize, $wgLang;
4646 if ( $this->contentLength
=== false ) {
4647 $this->contentLength
= strlen( $this->textbox1
);
4650 $out = $this->context
->getOutput();
4651 if ( $this->tooBig ||
$this->contentLength
> $wgMaxArticleSize * 1024 ) {
4652 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4655 $wgLang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4656 $wgLang->formatNum( $wgMaxArticleSize )
4660 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4661 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4664 $wgLang->formatSize( strlen( $this->textbox1
) ),
4665 strlen( $this->textbox1
)
4675 protected function addPageProtectionWarningHeaders() {
4676 $out = $this->context
->getOutput();
4677 if ( $this->mTitle
->isProtected( 'edit' ) &&
4678 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4680 # Is the title semi-protected?
4681 if ( $this->mTitle
->isSemiProtected() ) {
4682 $noticeMsg = 'semiprotectedpagewarning';
4684 # Then it must be protected based on static groups (regular)
4685 $noticeMsg = 'protectedpagewarning';
4687 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4688 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4690 if ( $this->mTitle
->isCascadeProtected() ) {
4691 # Is this page under cascading protection from some source pages?
4692 /** @var Title[] $cascadeSources */
4693 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4694 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4695 $cascadeSourcesCount = count( $cascadeSources );
4696 if ( $cascadeSourcesCount > 0 ) {
4697 # Explain, and list the titles responsible
4698 foreach ( $cascadeSources as $page ) {
4699 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4702 $notice .= '</div>';
4703 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4705 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4706 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4708 'showIfEmpty' => false,
4709 'msgKey' => [ 'titleprotectedwarning' ],
4710 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4715 * @param OutputPage $out
4718 protected function addExplainConflictHeader( OutputPage
$out ) {
4720 "<div class='mw-explainconflict'>\n$1\n</div>",
4721 [ 'explainconflict', $this->context
->msg( $this->getSaveButtonLabel() )->text() ]
4726 * @param string $name
4727 * @param mixed[] $customAttribs
4732 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4733 $attribs = $customAttribs +
[
4738 // Avoid PHP notices when appending preferences
4739 // (appending allows customAttribs['style'] to still work).
4743 // The following classes can be used here:
4744 // * mw-editfont-default
4745 // * mw-editfont-monospace
4746 // * mw-editfont-sans-serif
4747 // * mw-editfont-serif
4748 $class = 'mw-editfont-' . $user->getOption( 'editfont' );
4750 if ( isset( $attribs['class'] ) ) {
4751 if ( is_string( $attribs['class'] ) ) {
4752 $attribs['class'] .= ' ' . $class;
4753 } elseif ( is_array( $attribs['class'] ) ) {
4754 $attribs['class'][] = $class;
4757 $attribs['class'] = $class;
4760 $pageLang = $this->mTitle
->getPageLanguage();
4761 $attribs['lang'] = $pageLang->getHtmlCode();
4762 $attribs['dir'] = $pageLang->getDir();
4768 * @param string $wikitext
4772 protected function addNewLineAtEnd( $wikitext ) {
4773 if ( strval( $wikitext ) !== '' ) {
4774 // Ensure there's a newline at the end, otherwise adding lines
4776 // But don't add a newline if the text is empty, or Firefox in XHTML
4777 // mode will show an extra newline. A bit annoying.
4785 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4786 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4787 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4788 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4789 * spread the new style links more efficiently.
4791 * @param string $text
4794 private function guessSectionName( $text ) {
4797 // Detect Microsoft browsers
4798 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4799 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4800 // ...and redirect them to legacy encoding, if available
4801 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4803 // Meanwhile, real browsers get real anchors
4804 return $wgParser->guessSectionNameFromWikiText( $text );