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
) ) {
474 __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.'
479 return $this->mContextTitle
;
484 * Check if the edit page is using OOUI controls
485 * @return bool Always true
486 * @deprecated since 1.30
488 public function isOouiEnabled() {
493 * Returns if the given content model is editable.
495 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
497 * @throws MWException If $modelId has no known handler
499 public function isSupportedContentModel( $modelId ) {
500 return $this->enableApiEditOverride
=== true ||
501 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
505 * Allow editing of content that supports API direct editing, but not general
506 * direct editing. Set to false by default.
508 * @param bool $enableOverride
510 public function setApiEditOverride( $enableOverride ) {
511 $this->enableApiEditOverride
= $enableOverride;
515 * @deprecated since 1.29, call edit directly
517 public function submit() {
518 wfDeprecated( __METHOD__
, '1.29' );
523 * This is the function that gets called for "action=edit". It
524 * sets up various member variables, then passes execution to
525 * another function, usually showEditForm()
527 * The edit form is self-submitting, so that when things like
528 * preview and edit conflicts occur, we get the same form back
529 * with the extra stuff added. Only when the final submission
530 * is made and all is well do we actually save and redirect to
531 * the newly-edited page.
533 public function edit() {
534 // Allow extensions to modify/prevent this form or submission
535 if ( !Hooks
::run( 'AlternateEdit', [ $this ] ) ) {
539 wfDebug( __METHOD__
. ": enter\n" );
541 $request = $this->context
->getRequest();
542 // If they used redlink=1 and the page exists, redirect to the main article
543 if ( $request->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
544 $this->context
->getOutput()->redirect( $this->mTitle
->getFullURL() );
548 $this->importFormData( $request );
549 $this->firsttime
= false;
551 if ( wfReadOnly() && $this->save
) {
554 $this->preview
= true;
558 $this->formtype
= 'save';
559 } elseif ( $this->preview
) {
560 $this->formtype
= 'preview';
561 } elseif ( $this->diff
) {
562 $this->formtype
= 'diff';
563 } else { # First time through
564 $this->firsttime
= true;
565 if ( $this->previewOnOpen() ) {
566 $this->formtype
= 'preview';
568 $this->formtype
= 'initial';
572 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
574 wfDebug( __METHOD__
. ": User can't edit\n" );
575 // Auto-block user's IP if the account was "hard" blocked
576 if ( !wfReadOnly() ) {
577 DeferredUpdates
::addCallableUpdate( function () {
578 $this->context
->getUser()->spreadAnyEditBlock();
581 $this->displayPermissionsError( $permErrors );
586 $revision = $this->mArticle
->getRevisionFetched();
587 // Disallow editing revisions with content models different from the current one
588 // Undo edits being an exception in order to allow reverting content model changes.
590 && $revision->getContentModel() !== $this->contentModel
593 if ( $this->undidRev
) {
594 $undidRevObj = Revision
::newFromId( $this->undidRev
);
595 $prevRev = $undidRevObj ?
$undidRevObj->getPrevious() : null;
597 if ( !$this->undidRev
599 ||
$prevRev->getContentModel() !== $this->contentModel
601 $this->displayViewSourcePage(
602 $this->getContentObject(),
604 'contentmodelediterror',
605 $revision->getContentModel(),
613 $this->isConflict
= false;
614 // css / js subpages of user pages get a special treatment
615 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
616 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
617 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
618 // @todo FIXME: Silly assignment.
619 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
621 # Show applicable editing introductions
622 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
626 # Attempt submission here. This will check for edit conflicts,
627 # and redundantly check for locked database, blocked IPs, etc.
628 # that edit() already checked just in case someone tries to sneak
629 # in the back door with a hand-edited submission URL.
631 if ( 'save' == $this->formtype
) {
632 $resultDetails = null;
633 $status = $this->attemptSave( $resultDetails );
634 if ( !$this->handleStatus( $status, $resultDetails ) ) {
639 # First time through: get contents, set time for conflict
641 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
642 if ( $this->initialiseForm() === false ) {
643 $this->noSuchSectionPage();
647 if ( !$this->mTitle
->getArticleID() ) {
648 Hooks
::run( 'EditFormPreloadText', [ &$this->textbox1
, &$this->mTitle
] );
650 Hooks
::run( 'EditFormInitialText', [ $this ] );
655 $this->showEditForm();
659 * @param string $rigor Same format as Title::getUserPermissionErrors()
662 protected function getEditPermissionErrors( $rigor = 'secure' ) {
663 $user = $this->context
->getUser();
664 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $user, $rigor );
665 # Can this title be created?
666 if ( !$this->mTitle
->exists() ) {
667 $permErrors = array_merge(
670 $this->mTitle
->getUserPermissionsErrors( 'create', $user, $rigor ),
675 # Ignore some permissions errors when a user is just previewing/viewing diffs
677 foreach ( $permErrors as $error ) {
678 if ( ( $this->preview ||
$this->diff
)
680 $error[0] == 'blockedtext' ||
681 $error[0] == 'autoblockedtext' ||
682 $error[0] == 'systemblockedtext'
688 $permErrors = wfArrayDiff2( $permErrors, $remove );
694 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
695 * but with the following differences:
696 * - If redlink=1, the user will be redirected to the page
697 * - If there is content to display or the error occurs while either saving,
698 * previewing or showing the difference, it will be a
699 * "View source for ..." page displaying the source code after the error message.
702 * @param array $permErrors Array of permissions errors, as returned by
703 * Title::getUserPermissionsErrors().
704 * @throws PermissionsError
706 protected function displayPermissionsError( array $permErrors ) {
707 $out = $this->context
->getOutput();
708 if ( $this->context
->getRequest()->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 $wgPreviewOnOpenNamespaces;
791 $request = $this->context
->getRequest();
792 if ( $request->getVal( 'preview' ) == 'yes' ) {
793 // Explicit override from request
795 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
796 // Explicit override from request
798 } elseif ( $this->section
== 'new' ) {
799 // Nothing *to* preview for new sections
801 } elseif ( ( $request->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
802 && $this->context
->getUser()->getOption( 'previewonfirst' )
804 // Standard preference behavior
806 } elseif ( !$this->mTitle
->exists()
807 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
808 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
810 // Categories are special
818 * Checks whether the user entered a skin name in uppercase,
819 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
823 protected function isWrongCaseCssJsPage() {
824 if ( $this->mTitle
->isCssJsSubpage() ) {
825 $name = $this->mTitle
->getSkinFromCssJsSubpage();
826 $skins = array_merge(
827 array_keys( Skin
::getSkinNames() ),
830 return !in_array( $name, $skins )
831 && in_array( strtolower( $name ), $skins );
838 * Returns whether section editing is supported for the current page.
839 * Subclasses may override this to replace the default behavior, which is
840 * to check ContentHandler::supportsSections.
842 * @return bool True if this edit page supports sections, false otherwise.
844 protected function isSectionEditSupported() {
845 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
846 return $contentHandler->supportsSections();
850 * This function collects the form data and uses it to populate various member variables.
851 * @param WebRequest &$request
852 * @throws ErrorPageError
854 public function importFormData( &$request ) {
855 # Section edit can come from either the form or a link
856 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
858 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
859 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
862 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
864 if ( $request->wasPosted() ) {
865 # These fields need to be checked for encoding.
866 # Also remove trailing whitespace, but don't remove _initial_
867 # whitespace from the text boxes. This may be significant formatting.
868 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
869 if ( !$request->getCheck( 'wpTextbox2' ) ) {
870 // Skip this if wpTextbox2 has input, it indicates that we came
871 // from a conflict page with raw page text, not a custom form
872 // modified by subclasses
873 $textbox1 = $this->importContentFormData( $request );
874 if ( $textbox1 !== null ) {
875 $this->textbox1
= $textbox1;
879 $this->summary
= $request->getText( 'wpSummary' );
881 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
882 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
884 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
886 # Treat sectiontitle the same way as summary.
887 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
888 # currently doing double duty as both edit summary and section title. Right now this
889 # is just to allow API edits to work around this limitation, but this should be
890 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
891 $this->sectiontitle
= $request->getText( 'wpSectionTitle' );
892 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
894 $this->edittime
= $request->getVal( 'wpEdittime' );
895 $this->editRevId
= $request->getIntOrNull( 'editRevId' );
896 $this->starttime
= $request->getVal( 'wpStarttime' );
898 $undidRev = $request->getInt( 'wpUndidRevision' );
900 $this->undidRev
= $undidRev;
903 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
905 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
906 // wpTextbox1 field is missing, possibly due to being "too big"
907 // according to some filter rules such as Suhosin's setting for
908 // suhosin.request.max_value_length (d'oh)
909 $this->incompleteForm
= true;
911 // If we receive the last parameter of the request, we can fairly
912 // claim the POST request has not been truncated.
914 // TODO: softened the check for cutover. Once we determine
915 // that it is safe, we should complete the transition by
916 // removing the "edittime" clause.
917 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
918 && is_null( $this->edittime
) );
920 if ( $this->incompleteForm
) {
921 # If the form is incomplete, force to preview.
922 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
923 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
924 $this->preview
= true;
926 $this->preview
= $request->getCheck( 'wpPreview' );
927 $this->diff
= $request->getCheck( 'wpDiff' );
929 // Remember whether a save was requested, so we can indicate
930 // if we forced preview due to session failure.
931 $this->mTriedSave
= !$this->preview
;
933 if ( $this->tokenOk( $request ) ) {
934 # Some browsers will not report any submit button
935 # if the user hits enter in the comment box.
936 # The unmarked state will be assumed to be a save,
937 # if the form seems otherwise complete.
938 wfDebug( __METHOD__
. ": Passed token check.\n" );
939 } elseif ( $this->diff
) {
940 # Failed token check, but only requested "Show Changes".
941 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
943 # Page might be a hack attempt posted from
944 # an external site. Preview instead of saving.
945 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
946 $this->preview
= true;
949 $this->save
= !$this->preview
&& !$this->diff
;
950 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
951 $this->edittime
= null;
954 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
955 $this->starttime
= null;
958 $this->recreate
= $request->getCheck( 'wpRecreate' );
960 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
961 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
963 $user = $this->context
->getUser();
964 # Don't force edit summaries when a user is editing their own user or talk page
965 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
966 && $this->mTitle
->getText() == $user->getName()
968 $this->allowBlankSummary
= true;
970 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
971 ||
!$user->getOption( 'forceeditsummary' );
974 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
976 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
977 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
979 $changeTags = $request->getVal( 'wpChangeTags' );
980 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
981 $this->changeTags
= [];
983 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
987 # Not a posted form? Start with nothing.
988 wfDebug( __METHOD__
. ": Not a posted form.\n" );
989 $this->textbox1
= '';
991 $this->sectiontitle
= '';
992 $this->edittime
= '';
993 $this->editRevId
= null;
994 $this->starttime
= wfTimestampNow();
996 $this->preview
= false;
999 $this->minoredit
= false;
1000 // Watch may be overridden by request parameters
1001 $this->watchthis
= $request->getBool( 'watchthis', false );
1002 $this->recreate
= false;
1004 // When creating a new section, we can preload a section title by passing it as the
1005 // preloadtitle parameter in the URL (T15100)
1006 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
1007 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
1008 // Once wpSummary isn't being use for setting section titles, we should delete this.
1009 $this->summary
= $request->getVal( 'preloadtitle' );
1010 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
1011 $this->summary
= $request->getText( 'summary' );
1012 if ( $this->summary
!== '' ) {
1013 $this->hasPresetSummary
= true;
1017 if ( $request->getVal( 'minor' ) ) {
1018 $this->minoredit
= true;
1022 $this->oldid
= $request->getInt( 'oldid' );
1023 $this->parentRevId
= $request->getInt( 'parentRevId' );
1025 $this->bot
= $request->getBool( 'bot', true );
1026 $this->nosummary
= $request->getBool( 'nosummary' );
1028 // May be overridden by revision.
1029 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
1030 // May be overridden by revision.
1031 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
1034 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1035 } catch ( MWUnknownContentModelException
$e ) {
1036 throw new ErrorPageError(
1037 'editpage-invalidcontentmodel-title',
1038 'editpage-invalidcontentmodel-text',
1039 [ wfEscapeWikiText( $this->contentModel
) ]
1043 if ( !$handler->isSupportedFormat( $this->contentFormat
) ) {
1044 throw new ErrorPageError(
1045 'editpage-notsupportedcontentformat-title',
1046 'editpage-notsupportedcontentformat-text',
1048 wfEscapeWikiText( $this->contentFormat
),
1049 wfEscapeWikiText( ContentHandler
::getLocalizedName( $this->contentModel
) )
1055 * @todo Check if the desired model is allowed in this namespace, and if
1056 * a transition from the page's current model to the new model is
1060 $this->editintro
= $request->getText( 'editintro',
1061 // Custom edit intro for new sections
1062 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
1064 // Allow extensions to modify form data
1065 Hooks
::run( 'EditPage::importFormData', [ $this, $request ] );
1069 * Subpage overridable method for extracting the page content data from the
1070 * posted form to be placed in $this->textbox1, if using customized input
1071 * this method should be overridden and return the page text that will be used
1072 * for saving, preview parsing and so on...
1074 * @param WebRequest &$request
1075 * @return string|null
1077 protected function importContentFormData( &$request ) {
1078 return; // Don't do anything, EditPage already extracted wpTextbox1
1082 * Initialise form fields in the object
1083 * Called on the first invocation, e.g. when a user clicks an edit link
1084 * @return bool If the requested section is valid
1086 public function initialiseForm() {
1087 $this->edittime
= $this->page
->getTimestamp();
1088 $this->editRevId
= $this->page
->getLatest();
1090 $content = $this->getContentObject( false ); # TODO: track content object?!
1091 if ( $content === false ) {
1094 $this->textbox1
= $this->toEditText( $content );
1096 $user = $this->context
->getUser();
1097 // activate checkboxes if user wants them to be always active
1098 # Sort out the "watch" checkbox
1099 if ( $user->getOption( 'watchdefault' ) ) {
1101 $this->watchthis
= true;
1102 } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1104 $this->watchthis
= true;
1105 } elseif ( $user->isWatched( $this->mTitle
) ) {
1107 $this->watchthis
= true;
1109 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
1110 $this->minoredit
= true;
1112 if ( $this->textbox1
=== false ) {
1119 * @param Content|null $def_content The default value to return
1121 * @return Content|null Content on success, $def_content for invalid sections
1125 protected function getContentObject( $def_content = null ) {
1130 $user = $this->context
->getUser();
1131 $request = $this->context
->getRequest();
1132 // For message page not locally set, use the i18n message.
1133 // For other non-existent articles, use preload text if any.
1134 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1135 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1136 # If this is a system message, get the default text.
1137 $msg = $this->mTitle
->getDefaultMessageText();
1139 $content = $this->toEditContent( $msg );
1141 if ( $content === false ) {
1142 # If requested, preload some text.
1143 $preload = $request->getVal( 'preload',
1144 // Custom preload text for new sections
1145 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1146 $params = $request->getArray( 'preloadparams', [] );
1148 $content = $this->getPreloadedContent( $preload, $params );
1150 // For existing pages, get text based on "undo" or section parameters.
1152 if ( $this->section
!= '' ) {
1153 // Get section edit text (returns $def_text for invalid sections)
1154 $orig = $this->getOriginalContent( $user );
1155 $content = $orig ?
$orig->getSection( $this->section
) : null;
1158 $content = $def_content;
1161 $undoafter = $request->getInt( 'undoafter' );
1162 $undo = $request->getInt( 'undo' );
1164 if ( $undo > 0 && $undoafter > 0 ) {
1165 $undorev = Revision
::newFromId( $undo );
1166 $oldrev = Revision
::newFromId( $undoafter );
1168 # Sanity check, make sure it's the right page,
1169 # the revisions exist and they were not deleted.
1170 # Otherwise, $content will be left as-is.
1171 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1172 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1173 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1175 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1177 if ( $content === false ) {
1178 # Warn the user that something went wrong
1179 $undoMsg = 'failure';
1181 $oldContent = $this->page
->getContent( Revision
::RAW
);
1182 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
1183 $newContent = $content->preSaveTransform( $this->mTitle
, $user, $popts );
1184 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1185 // The undo may change content
1186 // model if its reverting the top
1187 // edit. This can result in
1188 // mismatched content model/format.
1189 $this->contentModel
= $newContent->getModel();
1190 $this->contentFormat
= $oldrev->getContentFormat();
1193 if ( $newContent->equals( $oldContent ) ) {
1194 # Tell the user that the undo results in no change,
1195 # i.e. the revisions were already undone.
1196 $undoMsg = 'nochange';
1199 # Inform the user of our success and set an automatic edit summary
1200 $undoMsg = 'success';
1202 # If we just undid one rev, use an autosummary
1203 $firstrev = $oldrev->getNext();
1204 if ( $firstrev && $firstrev->getId() == $undo ) {
1205 $userText = $undorev->getUserText();
1206 if ( $userText === '' ) {
1207 $undoSummary = $this->context
->msg(
1208 'undo-summary-username-hidden',
1210 )->inContentLanguage()->text();
1212 $undoSummary = $this->context
->msg(
1216 )->inContentLanguage()->text();
1218 if ( $this->summary
=== '' ) {
1219 $this->summary
= $undoSummary;
1221 $this->summary
= $undoSummary . $this->context
->msg( 'colon-separator' )
1222 ->inContentLanguage()->text() . $this->summary
;
1224 $this->undidRev
= $undo;
1226 $this->formtype
= 'diff';
1230 // Failed basic sanity checks.
1231 // Older revisions may have been removed since the link
1232 // was created, or we may simply have got bogus input.
1236 $out = $this->context
->getOutput();
1237 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1238 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1239 $this->editFormPageTop
.= $out->parse( "<div class=\"{$class}\">" .
1240 $this->context
->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1243 if ( $content === false ) {
1244 $content = $this->getOriginalContent( $user );
1253 * Get the content of the wanted revision, without section extraction.
1255 * The result of this function can be used to compare user's input with
1256 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1257 * to the original text of the edit.
1259 * This differs from Article::getContent() that when a missing revision is
1260 * encountered the result will be null and not the
1261 * 'missing-revision' message.
1264 * @param User $user The user to get the revision for
1265 * @return Content|null
1267 private function getOriginalContent( User
$user ) {
1268 if ( $this->section
== 'new' ) {
1269 return $this->getCurrentContent();
1271 $revision = $this->mArticle
->getRevisionFetched();
1272 if ( $revision === null ) {
1273 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1274 return $handler->makeEmptyContent();
1276 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1281 * Get the edit's parent revision ID
1283 * The "parent" revision is the ancestor that should be recorded in this
1284 * page's revision history. It is either the revision ID of the in-memory
1285 * article content, or in the case of a 3-way merge in order to rebase
1286 * across a recoverable edit conflict, the ID of the newer revision to
1287 * which we have rebased this page.
1290 * @return int Revision ID
1292 public function getParentRevId() {
1293 if ( $this->parentRevId
) {
1294 return $this->parentRevId
;
1296 return $this->mArticle
->getRevIdFetched();
1301 * Get the current content of the page. This is basically similar to
1302 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1303 * content object is returned instead of null.
1308 protected function getCurrentContent() {
1309 $rev = $this->page
->getRevision();
1310 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1312 if ( $content === false ||
$content === null ) {
1313 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1314 return $handler->makeEmptyContent();
1315 } elseif ( !$this->undidRev
) {
1316 // Content models should always be the same since we error
1317 // out if they are different before this point (in ->edit()).
1318 // The exception being, during an undo, the current revision might
1319 // differ from the prior revision.
1320 $logger = LoggerFactory
::getInstance( 'editpage' );
1321 if ( $this->contentModel
!== $rev->getContentModel() ) {
1322 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1323 'prev' => $this->contentModel
,
1324 'new' => $rev->getContentModel(),
1325 'title' => $this->getTitle()->getPrefixedDBkey(),
1326 'method' => __METHOD__
1328 $this->contentModel
= $rev->getContentModel();
1331 // Given that the content models should match, the current selected
1332 // format should be supported.
1333 if ( !$content->isSupportedFormat( $this->contentFormat
) ) {
1334 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1336 'prev' => $this->contentFormat
,
1337 'new' => $rev->getContentFormat(),
1338 'title' => $this->getTitle()->getPrefixedDBkey(),
1339 'method' => __METHOD__
1341 $this->contentFormat
= $rev->getContentFormat();
1348 * Use this method before edit() to preload some content into the edit box
1350 * @param Content $content
1354 public function setPreloadedContent( Content
$content ) {
1355 $this->mPreloadContent
= $content;
1359 * Get the contents to be preloaded into the box, either set by
1360 * an earlier setPreloadText() or by loading the given page.
1362 * @param string $preload Representing the title to preload from.
1363 * @param array $params Parameters to use (interface-message style) in the preloaded text
1369 protected function getPreloadedContent( $preload, $params = [] ) {
1370 if ( !empty( $this->mPreloadContent
) ) {
1371 return $this->mPreloadContent
;
1374 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1376 if ( $preload === '' ) {
1377 return $handler->makeEmptyContent();
1380 $user = $this->context
->getUser();
1381 $title = Title
::newFromText( $preload );
1382 # Check for existence to avoid getting MediaWiki:Noarticletext
1383 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
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', $user ) ) {
1393 // TODO: somehow show a warning to the user!
1394 return $handler->makeEmptyContent();
1396 $page = WikiPage
::factory( $title );
1399 $parserOptions = ParserOptions
::newFromUser( $user );
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 ) {
1433 $token = $request->getVal( 'wpEditToken' );
1434 $user = $this->context
->getUser();
1435 $this->mTokenOk
= $user->matchEditToken( $token );
1436 $this->mTokenOkExceptSuffix
= $user->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 ) {
1476 # Allow bots to exempt some edits from bot flagging
1477 $bot = $this->context
->getUser()->isAllowed( 'bot' ) && $this->bot
;
1478 $status = $this->internalAttemptSave( $resultDetails, $bot );
1480 Hooks
::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1486 * Log when a page was successfully saved after the edit conflict view
1488 private function incrementResolvedConflicts() {
1489 if ( $this->context
->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1493 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1494 $stats->increment( 'edit.failures.conflict.resolved' );
1498 * Handle status, such as after attempt save
1500 * @param Status $status
1501 * @param array|bool $resultDetails
1503 * @throws ErrorPageError
1504 * @return bool False, if output is done, true if rest of the form should be displayed
1506 private function handleStatus( Status
$status, $resultDetails ) {
1508 * @todo FIXME: once the interface for internalAttemptSave() is made
1509 * nicer, this should use the message in $status
1511 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1512 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1514 $this->incrementResolvedConflicts();
1516 $this->didSave
= true;
1517 if ( !$resultDetails['nullEdit'] ) {
1518 $this->setPostEditCookie( $status->value
);
1522 $out = $this->context
->getOutput();
1524 // "wpExtraQueryRedirect" is a hidden input to modify
1525 // after save URL and is not used by actual edit form
1526 $request = $this->context
->getRequest();
1527 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1529 switch ( $status->value
) {
1530 case self
::AS_HOOK_ERROR_EXPECTED
:
1531 case self
::AS_CONTENT_TOO_BIG
:
1532 case self
::AS_ARTICLE_WAS_DELETED
:
1533 case self
::AS_CONFLICT_DETECTED
:
1534 case self
::AS_SUMMARY_NEEDED
:
1535 case self
::AS_TEXTBOX_EMPTY
:
1536 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1538 case self
::AS_BLANK_ARTICLE
:
1539 case self
::AS_SELF_REDIRECT
:
1542 case self
::AS_HOOK_ERROR
:
1545 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1546 case self
::AS_PARSE_ERROR
:
1547 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1550 case self
::AS_SUCCESS_NEW_ARTICLE
:
1551 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1552 if ( $extraQueryRedirect ) {
1553 if ( $query === '' ) {
1554 $query = $extraQueryRedirect;
1556 $query = $query . '&' . $extraQueryRedirect;
1559 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1560 $out->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1563 case self
::AS_SUCCESS_UPDATE
:
1565 $sectionanchor = $resultDetails['sectionanchor'];
1567 // Give extensions a chance to modify URL query on update
1569 'ArticleUpdateBeforeRedirect',
1570 [ $this->mArticle
, &$sectionanchor, &$extraQuery ]
1573 if ( $resultDetails['redirect'] ) {
1574 if ( $extraQuery == '' ) {
1575 $extraQuery = 'redirect=no';
1577 $extraQuery = 'redirect=no&' . $extraQuery;
1580 if ( $extraQueryRedirect ) {
1581 if ( $extraQuery === '' ) {
1582 $extraQuery = $extraQueryRedirect;
1584 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1588 $out->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1591 case self
::AS_SPAM_ERROR
:
1592 $this->spamPageWithContent( $resultDetails['spam'] );
1595 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1596 throw new UserBlockedError( $this->context
->getUser()->getBlock() );
1598 case self
::AS_IMAGE_REDIRECT_ANON
:
1599 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1600 throw new PermissionsError( 'upload' );
1602 case self
::AS_READ_ONLY_PAGE_ANON
:
1603 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1604 throw new PermissionsError( 'edit' );
1606 case self
::AS_READ_ONLY_PAGE
:
1607 throw new ReadOnlyError
;
1609 case self
::AS_RATE_LIMITED
:
1610 throw new ThrottledError();
1612 case self
::AS_NO_CREATE_PERMISSION
:
1613 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1614 throw new PermissionsError( $permission );
1616 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1617 throw new PermissionsError( 'editcontentmodel' );
1620 // We don't recognize $status->value. The only way that can happen
1621 // is if an extension hook aborted from inside ArticleSave.
1622 // Render the status object into $this->hookError
1623 // FIXME this sucks, we should just use the Status object throughout
1624 $this->hookError
= '<div class="error">' ."\n" . $status->getWikiText() .
1631 * Run hooks that can filter edits just before they get saved.
1633 * @param Content $content The Content to filter.
1634 * @param Status $status For reporting the outcome to the caller
1635 * @param User $user The user performing the edit
1639 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1640 // Run old style post-section-merge edit filter
1641 if ( $this->hookError
!= '' ) {
1642 # ...or the hook could be expecting us to produce an error
1643 $status->fatal( 'hookaborted' );
1644 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1648 // Run new style post-section-merge edit filter
1649 if ( !Hooks
::run( 'EditFilterMergedContent',
1650 [ $this->mArticle
->getContext(), $content, $status, $this->summary
,
1651 $user, $this->minoredit
] )
1653 # Error messages etc. could be handled within the hook...
1654 if ( $status->isGood() ) {
1655 $status->fatal( 'hookaborted' );
1656 // Not setting $this->hookError here is a hack to allow the hook
1657 // to cause a return to the edit page without $this->hookError
1658 // being set. This is used by ConfirmEdit to display a captcha
1659 // without any error message cruft.
1661 $this->hookError
= $status->getWikiText();
1663 // Use the existing $status->value if the hook set it
1664 if ( !$status->value
) {
1665 $status->value
= self
::AS_HOOK_ERROR
;
1668 } elseif ( !$status->isOK() ) {
1669 # ...or the hook could be expecting us to produce an error
1670 // FIXME this sucks, we should just use the Status object throughout
1671 $this->hookError
= $status->getWikiText();
1672 $status->fatal( 'hookaborted' );
1673 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1681 * Return the summary to be used for a new section.
1683 * @param string $sectionanchor Set to the section anchor text
1686 private function newSectionSummary( &$sectionanchor = null ) {
1689 if ( $this->sectiontitle
!== '' ) {
1690 $sectionanchor = $this->guessSectionName( $this->sectiontitle
);
1691 // If no edit summary was specified, create one automatically from the section
1692 // title and have it link to the new section. Otherwise, respect the summary as
1694 if ( $this->summary
=== '' ) {
1695 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1696 return $this->context
->msg( 'newsectionsummary' )
1697 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1699 } elseif ( $this->summary
!== '' ) {
1700 $sectionanchor = $this->guessSectionName( $this->summary
);
1701 # This is a new section, so create a link to the new section
1702 # in the revision summary.
1703 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1704 return $this->context
->msg( 'newsectionsummary' )
1705 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1707 return $this->summary
;
1711 * Attempt submission (no UI)
1713 * @param array &$result Array to add statuses to, currently with the
1715 * - spam (string): Spam string from content if any spam is detected by
1717 * - sectionanchor (string): Section anchor for a section save.
1718 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1720 * - redirect (bool): Set if doEditContent is OK. True if resulting
1721 * revision is a redirect.
1722 * @param bool $bot True if edit is being made under the bot right.
1724 * @return Status Status object, possibly with a message, but always with
1725 * one of the AS_* constants in $status->value,
1727 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1728 * various error display idiosyncrasies. There are also lots of cases
1729 * where error metadata is set in the object and retrieved later instead
1730 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1731 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1734 public function internalAttemptSave( &$result, $bot = false ) {
1735 global $wgMaxArticleSize;
1736 global $wgContentHandlerUseDB;
1738 $status = Status
::newGood();
1739 $user = $this->context
->getUser();
1741 if ( !Hooks
::run( 'EditPage::attemptSave', [ $this ] ) ) {
1742 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1743 $status->fatal( 'hookaborted' );
1744 $status->value
= self
::AS_HOOK_ERROR
;
1748 $request = $this->context
->getRequest();
1749 $spam = $request->getText( 'wpAntispam' );
1750 if ( $spam !== '' ) {
1755 $this->mTitle
->getPrefixedText() .
1756 '" submitted bogus field "' .
1760 $status->fatal( 'spamprotectionmatch', false );
1761 $status->value
= self
::AS_SPAM_ERROR
;
1766 # Construct Content object
1767 $textbox_content = $this->toEditContent( $this->textbox1
);
1768 } catch ( MWContentSerializationException
$ex ) {
1770 'content-failed-to-parse',
1771 $this->contentModel
,
1772 $this->contentFormat
,
1775 $status->value
= self
::AS_PARSE_ERROR
;
1779 # Check image redirect
1780 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1781 $textbox_content->isRedirect() &&
1782 !$user->isAllowed( 'upload' )
1784 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1785 $status->setResult( false, $code );
1791 $match = self
::matchSummarySpamRegex( $this->summary
);
1792 if ( $match === false && $this->section
== 'new' ) {
1793 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1794 # regular summaries, it is added to the actual wikitext.
1795 if ( $this->sectiontitle
!== '' ) {
1796 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1797 $match = self
::matchSpamRegex( $this->sectiontitle
);
1799 # This branch is taken when the "Add Topic" user interface is used, or the API
1800 # is used with the 'summary' parameter.
1801 $match = self
::matchSpamRegex( $this->summary
);
1804 if ( $match === false ) {
1805 $match = self
::matchSpamRegex( $this->textbox1
);
1807 if ( $match !== false ) {
1808 $result['spam'] = $match;
1809 $ip = $request->getIP();
1810 $pdbk = $this->mTitle
->getPrefixedDBkey();
1811 $match = str_replace( "\n", '', $match );
1812 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1813 $status->fatal( 'spamprotectionmatch', $match );
1814 $status->value
= self
::AS_SPAM_ERROR
;
1819 [ $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
] )
1821 # Error messages etc. could be handled within the hook...
1822 $status->fatal( 'hookaborted' );
1823 $status->value
= self
::AS_HOOK_ERROR
;
1825 } elseif ( $this->hookError
!= '' ) {
1826 # ...or the hook could be expecting us to produce an error
1827 $status->fatal( 'hookaborted' );
1828 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1832 if ( $user->isBlockedFrom( $this->mTitle
, false ) ) {
1833 // Auto-block user's IP if the account was "hard" blocked
1834 if ( !wfReadOnly() ) {
1835 $user->spreadAnyEditBlock();
1837 # Check block state against master, thus 'false'.
1838 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1842 $this->contentLength
= strlen( $this->textbox1
);
1843 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
1844 // Error will be displayed by showEditForm()
1845 $this->tooBig
= true;
1846 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1850 if ( !$user->isAllowed( 'edit' ) ) {
1851 if ( $user->isAnon() ) {
1852 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1855 $status->fatal( 'readonlytext' );
1856 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1861 $changingContentModel = false;
1862 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1863 if ( !$wgContentHandlerUseDB ) {
1864 $status->fatal( 'editpage-cannot-use-custom-model' );
1865 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1867 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1868 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1871 // Make sure the user can edit the page under the new content model too
1872 $titleWithNewContentModel = clone $this->mTitle
;
1873 $titleWithNewContentModel->setContentModel( $this->contentModel
);
1874 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1875 ||
!$titleWithNewContentModel->userCan( 'edit', $user )
1877 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1881 $changingContentModel = true;
1882 $oldContentModel = $this->mTitle
->getContentModel();
1885 if ( $this->changeTags
) {
1886 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1887 $this->changeTags
, $user );
1888 if ( !$changeTagsStatus->isOK() ) {
1889 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1890 return $changeTagsStatus;
1894 if ( wfReadOnly() ) {
1895 $status->fatal( 'readonlytext' );
1896 $status->value
= self
::AS_READ_ONLY_PAGE
;
1899 if ( $user->pingLimiter() ||
$user->pingLimiter( 'linkpurge', 0 )
1900 ||
( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1902 $status->fatal( 'actionthrottledtext' );
1903 $status->value
= self
::AS_RATE_LIMITED
;
1907 # If the article has been deleted while editing, don't save it without
1909 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1910 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1914 # Load the page data from the master. If anything changes in the meantime,
1915 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1916 $this->page
->loadPageData( 'fromdbmaster' );
1917 $new = !$this->page
->exists();
1920 // Late check for create permission, just in case *PARANOIA*
1921 if ( !$this->mTitle
->userCan( 'create', $user ) ) {
1922 $status->fatal( 'nocreatetext' );
1923 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1924 wfDebug( __METHOD__
. ": no create permission\n" );
1928 // Don't save a new page if it's blank or if it's a MediaWiki:
1929 // message with content equivalent to default (allow empty pages
1930 // in this case to disable messages, see T52124)
1931 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1932 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1933 $defaultText = $defaultMessageText;
1938 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1939 $this->blankArticle
= true;
1940 $status->fatal( 'blankarticle' );
1941 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1945 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
1949 $content = $textbox_content;
1951 $result['sectionanchor'] = '';
1952 if ( $this->section
== 'new' ) {
1953 if ( $this->sectiontitle
!== '' ) {
1954 // Insert the section title above the content.
1955 $content = $content->addSectionHeader( $this->sectiontitle
);
1956 } elseif ( $this->summary
!== '' ) {
1957 // Insert the section title above the content.
1958 $content = $content->addSectionHeader( $this->summary
);
1960 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1963 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1967 # Article exists. Check for edit conflict.
1969 $this->page
->clear(); # Force reload of dates, etc.
1970 $timestamp = $this->page
->getTimestamp();
1971 $latest = $this->page
->getLatest();
1973 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1975 // Check editRevId if set, which handles same-second timestamp collisions
1976 if ( $timestamp != $this->edittime
1977 ||
( $this->editRevId
!== null && $this->editRevId
!= $latest )
1979 $this->isConflict
= true;
1980 if ( $this->section
== 'new' ) {
1981 if ( $this->page
->getUserText() == $user->getName() &&
1982 $this->page
->getComment() == $this->newSectionSummary()
1984 // Probably a duplicate submission of a new comment.
1985 // This can happen when CDN resends a request after
1986 // a timeout but the first one actually went through.
1988 . ": duplicate new section submission; trigger edit conflict!\n" );
1990 // New comment; suppress conflict.
1991 $this->isConflict
= false;
1992 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1994 } elseif ( $this->section
== ''
1995 && Revision
::userWasLastToEdit(
1996 DB_MASTER
, $this->mTitle
->getArticleID(),
1997 $user->getId(), $this->edittime
2000 # Suppress edit conflict with self, except for section edits where merging is required.
2001 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
2002 $this->isConflict
= false;
2006 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2007 if ( $this->sectiontitle
!== '' ) {
2008 $sectionTitle = $this->sectiontitle
;
2010 $sectionTitle = $this->summary
;
2015 if ( $this->isConflict
) {
2017 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2018 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2019 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2020 // ...or disable section editing for non-current revisions (not exposed anyway).
2021 if ( $this->editRevId
!== null ) {
2022 $content = $this->page
->replaceSectionAtRev(
2029 $content = $this->page
->replaceSectionContent(
2037 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
2038 $content = $this->page
->replaceSectionContent(
2045 if ( is_null( $content ) ) {
2046 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
2047 $this->isConflict
= true;
2048 $content = $textbox_content; // do not try to merge here!
2049 } elseif ( $this->isConflict
) {
2051 if ( $this->mergeChangesIntoContent( $content ) ) {
2052 // Successful merge! Maybe we should tell the user the good news?
2053 $this->isConflict
= false;
2054 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
2056 $this->section
= '';
2057 $this->textbox1
= ContentHandler
::getContentText( $content );
2058 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
2062 if ( $this->isConflict
) {
2063 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
2067 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2071 if ( $this->section
== 'new' ) {
2072 // Handle the user preference to force summaries here
2073 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
2074 $this->missingSummary
= true;
2075 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2076 $status->value
= self
::AS_SUMMARY_NEEDED
;
2080 // Do not allow the user to post an empty comment
2081 if ( $this->textbox1
== '' ) {
2082 $this->missingComment
= true;
2083 $status->fatal( 'missingcommenttext' );
2084 $status->value
= self
::AS_TEXTBOX_EMPTY
;
2087 } elseif ( !$this->allowBlankSummary
2088 && !$content->equals( $this->getOriginalContent( $user ) )
2089 && !$content->isRedirect()
2090 && md5( $this->summary
) == $this->autoSumm
2092 $this->missingSummary
= true;
2093 $status->fatal( 'missingsummary' );
2094 $status->value
= self
::AS_SUMMARY_NEEDED
;
2099 $sectionanchor = '';
2100 if ( $this->section
== 'new' ) {
2101 $this->summary
= $this->newSectionSummary( $sectionanchor );
2102 } elseif ( $this->section
!= '' ) {
2103 # Try to get a section anchor from the section source, redirect
2104 # to edited section if header found.
2105 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2106 # for duplicate heading checking and maybe parsing.
2107 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
2108 # We can't deal with anchors, includes, html etc in the header for now,
2109 # headline would need to be parsed to improve this.
2110 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2111 $sectionanchor = $this->guessSectionName( $matches[2] );
2114 $result['sectionanchor'] = $sectionanchor;
2116 // Save errors may fall down to the edit form, but we've now
2117 // merged the section into full text. Clear the section field
2118 // so that later submission of conflict forms won't try to
2119 // replace that into a duplicated mess.
2120 $this->textbox1
= $this->toEditText( $content );
2121 $this->section
= '';
2123 $status->value
= self
::AS_SUCCESS_UPDATE
;
2126 if ( !$this->allowSelfRedirect
2127 && $content->isRedirect()
2128 && $content->getRedirectTarget()->equals( $this->getTitle() )
2130 // If the page already redirects to itself, don't warn.
2131 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2132 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
2133 $this->selfRedirect
= true;
2134 $status->fatal( 'selfredirect' );
2135 $status->value
= self
::AS_SELF_REDIRECT
;
2140 // Check for length errors again now that the section is merged in
2141 $this->contentLength
= strlen( $this->toEditText( $content ) );
2142 if ( $this->contentLength
> $wgMaxArticleSize * 1024 ) {
2143 $this->tooBig
= true;
2144 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2148 $flags = EDIT_AUTOSUMMARY |
2149 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2150 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2151 ( $bot ? EDIT_FORCE_BOT
: 0 );
2153 $doEditStatus = $this->page
->doEditContent(
2159 $content->getDefaultFormat(),
2164 if ( !$doEditStatus->isOK() ) {
2165 // Failure from doEdit()
2166 // Show the edit conflict page for certain recognized errors from doEdit(),
2167 // but don't show it for errors from extension hooks
2168 $errors = $doEditStatus->getErrorsArray();
2169 if ( in_array( $errors[0][0],
2170 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2172 $this->isConflict
= true;
2173 // Destroys data doEdit() put in $status->value but who cares
2174 $doEditStatus->value
= self
::AS_END
;
2176 return $doEditStatus;
2179 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2180 if ( $result['nullEdit'] ) {
2181 // We don't know if it was a null edit until now, so increment here
2182 $user->pingLimiter( 'linkpurge' );
2184 $result['redirect'] = $content->isRedirect();
2186 $this->updateWatchlist();
2188 // If the content model changed, add a log entry
2189 if ( $changingContentModel ) {
2190 $this->addContentModelChangeLogEntry(
2192 $new ?
false : $oldContentModel,
2193 $this->contentModel
,
2203 * @param string|false $oldModel false if the page is being newly created
2204 * @param string $newModel
2205 * @param string $reason
2207 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2208 $new = $oldModel === false;
2209 $log = new ManualLogEntry( 'contentmodel', $new ?
'new' : 'change' );
2210 $log->setPerformer( $user );
2211 $log->setTarget( $this->mTitle
);
2212 $log->setComment( $reason );
2213 $log->setParameters( [
2214 '4::oldmodel' => $oldModel,
2215 '5::newmodel' => $newModel
2217 $logid = $log->insert();
2218 $log->publish( $logid );
2222 * Register the change of watch status
2224 protected function updateWatchlist() {
2225 $user = $this->context
->getUser();
2226 if ( !$user->isLoggedIn() ) {
2230 $title = $this->mTitle
;
2231 $watch = $this->watchthis
;
2232 // Do this in its own transaction to reduce contention...
2233 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2234 if ( $watch == $user->isWatched( $title, User
::IGNORE_USER_RIGHTS
) ) {
2235 return; // nothing to change
2237 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2242 * Attempts to do 3-way merge of edit content with a base revision
2243 * and current content, in case of edit conflict, in whichever way appropriate
2244 * for the content type.
2248 * @param Content $editContent
2252 private function mergeChangesIntoContent( &$editContent ) {
2253 $db = wfGetDB( DB_MASTER
);
2255 // This is the revision the editor started from
2256 $baseRevision = $this->getBaseRevision();
2257 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2259 if ( is_null( $baseContent ) ) {
2263 // The current state, we want to merge updates into it
2264 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2265 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2267 if ( is_null( $currentContent ) ) {
2271 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2273 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2276 $editContent = $result;
2277 // Update parentRevId to what we just merged.
2278 $this->parentRevId
= $currentRevision->getId();
2286 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2287 * one might think of X as the "base revision", which is NOT what this returns.
2288 * @return Revision Current version when the edit was started
2290 public function getBaseRevision() {
2291 if ( !$this->mBaseRevision
) {
2292 $db = wfGetDB( DB_MASTER
);
2293 $this->mBaseRevision
= $this->editRevId
2294 ? Revision
::newFromId( $this->editRevId
, Revision
::READ_LATEST
)
2295 : Revision
::loadFromTimestamp( $db, $this->mTitle
, $this->edittime
);
2297 return $this->mBaseRevision
;
2301 * Check given input text against $wgSpamRegex, and return the text of the first match.
2303 * @param string $text
2305 * @return string|bool Matching string or false
2307 public static function matchSpamRegex( $text ) {
2308 global $wgSpamRegex;
2309 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2310 $regexes = (array)$wgSpamRegex;
2311 return self
::matchSpamRegexInternal( $text, $regexes );
2315 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2317 * @param string $text
2319 * @return string|bool Matching string or false
2321 public static function matchSummarySpamRegex( $text ) {
2322 global $wgSummarySpamRegex;
2323 $regexes = (array)$wgSummarySpamRegex;
2324 return self
::matchSpamRegexInternal( $text, $regexes );
2328 * @param string $text
2329 * @param array $regexes
2330 * @return bool|string
2332 protected static function matchSpamRegexInternal( $text, $regexes ) {
2333 foreach ( $regexes as $regex ) {
2335 if ( preg_match( $regex, $text, $matches ) ) {
2342 public function setHeaders() {
2343 global $wgAjaxEditStash;
2345 $out = $this->context
->getOutput();
2347 $out->addModules( 'mediawiki.action.edit' );
2348 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2350 $user = $this->context
->getUser();
2351 if ( $user->getOption( 'showtoolbar' ) ) {
2352 // The addition of default buttons is handled by getEditToolbar() which
2353 // has its own dependency on this module. The call here ensures the module
2354 // is loaded in time (it has position "top") for other modules to register
2355 // buttons (e.g. extensions, gadgets, user scripts).
2356 $out->addModules( 'mediawiki.toolbar' );
2359 if ( $user->getOption( 'uselivepreview' ) ) {
2360 $out->addModules( 'mediawiki.action.edit.preview' );
2363 if ( $user->getOption( 'useeditwarning' ) ) {
2364 $out->addModules( 'mediawiki.action.edit.editWarning' );
2367 # Enabled article-related sidebar, toplinks, etc.
2368 $out->setArticleRelated( true );
2370 $contextTitle = $this->getContextTitle();
2371 if ( $this->isConflict
) {
2372 $msg = 'editconflict';
2373 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2374 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2376 $msg = $contextTitle->exists()
2377 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2378 && $contextTitle->getDefaultMessageText() !== false
2384 # Use the title defined by DISPLAYTITLE magic word when present
2385 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2386 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2387 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2388 if ( $displayTitle === false ) {
2389 $displayTitle = $contextTitle->getPrefixedText();
2391 $out->setPageTitle( $this->context
->msg( $msg, $displayTitle ) );
2392 # Transmit the name of the message to JavaScript for live preview
2393 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2394 $out->addJsConfigVars( [
2395 'wgEditMessage' => $msg,
2396 'wgAjaxEditStash' => $wgAjaxEditStash,
2401 * Show all applicable editing introductions
2403 protected function showIntro() {
2404 if ( $this->suppressIntro
) {
2408 $out = $this->context
->getOutput();
2409 $namespace = $this->mTitle
->getNamespace();
2411 if ( $namespace == NS_MEDIAWIKI
) {
2412 # Show a warning if editing an interface message
2413 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2414 # If this is a default message (but not css or js),
2415 # show a hint that it is translatable on translatewiki.net
2416 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2417 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2419 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2420 if ( $defaultMessageText !== false ) {
2421 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2422 'translateinterface' );
2425 } elseif ( $namespace == NS_FILE
) {
2426 # Show a hint to shared repo
2427 $file = wfFindFile( $this->mTitle
);
2428 if ( $file && !$file->isLocal() ) {
2429 $descUrl = $file->getDescriptionUrl();
2430 # there must be a description url to show a hint to shared repo
2432 if ( !$this->mTitle
->exists() ) {
2433 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2434 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2437 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2438 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2445 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2446 # Show log extract when the user is currently blocked
2447 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2448 $username = explode( '/', $this->mTitle
->getText(), 2 )[0];
2449 $user = User
::newFromName( $username, false /* allow IP users */ );
2450 $ip = User
::isIP( $username );
2451 $block = Block
::newFromTarget( $user, $user );
2452 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2453 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2454 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2455 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2456 # Show log extract if the user is currently blocked
2457 LogEventsList
::showLogExtract(
2460 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2464 'showIfEmpty' => false,
2466 'blocked-notice-logextract',
2467 $user->getName() # Support GENDER in notice
2473 # Try to add a custom edit intro, or use the standard one if this is not possible.
2474 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2475 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2476 $this->context
->msg( 'helppage' )->inContentLanguage()->text()
2478 if ( $this->context
->getUser()->isLoggedIn() ) {
2480 // Suppress the external link icon, consider the help url an internal one
2481 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2489 // Suppress the external link icon, consider the help url an internal one
2490 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2492 'newarticletextanon',
2498 # Give a notice if the user is editing a deleted/moved page...
2499 if ( !$this->mTitle
->exists() ) {
2500 $dbr = wfGetDB( DB_REPLICA
);
2502 LogEventsList
::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle
,
2506 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2507 'showIfEmpty' => false,
2508 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2515 * Attempt to show a custom editing introduction, if supplied
2519 protected function showCustomIntro() {
2520 if ( $this->editintro
) {
2521 $title = Title
::newFromText( $this->editintro
);
2522 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2523 // Added using template syntax, to take <noinclude>'s into account.
2524 $this->context
->getOutput()->addWikiTextTitleTidy(
2525 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2535 * Gets an editable textual representation of $content.
2536 * The textual representation can be turned by into a Content object by the
2537 * toEditContent() method.
2539 * If $content is null or false or a string, $content is returned unchanged.
2541 * If the given Content object is not of a type that can be edited using
2542 * the text base EditPage, an exception will be raised. Set
2543 * $this->allowNonTextContent to true to allow editing of non-textual
2546 * @param Content|null|bool|string $content
2547 * @return string The editable text form of the content.
2549 * @throws MWException If $content is not an instance of TextContent and
2550 * $this->allowNonTextContent is not true.
2552 protected function toEditText( $content ) {
2553 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2557 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2558 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2561 return $content->serialize( $this->contentFormat
);
2565 * Turns the given text into a Content object by unserializing it.
2567 * If the resulting Content object is not of a type that can be edited using
2568 * the text base EditPage, an exception will be raised. Set
2569 * $this->allowNonTextContent to true to allow editing of non-textual
2572 * @param string|null|bool $text Text to unserialize
2573 * @return Content|bool|null The content object created from $text. If $text was false
2574 * or null, false resp. null will be returned instead.
2576 * @throws MWException If unserializing the text results in a Content
2577 * object that is not an instance of TextContent and
2578 * $this->allowNonTextContent is not true.
2580 protected function toEditContent( $text ) {
2581 if ( $text === false ||
$text === null ) {
2585 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2586 $this->contentModel
, $this->contentFormat
);
2588 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2589 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2596 * Send the edit form and related headers to OutputPage
2597 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2598 * during form output near the top, for captchas and the like.
2600 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2601 * use the EditPage::showEditForm:fields hook instead.
2603 public function showEditForm( $formCallback = null ) {
2604 # need to parse the preview early so that we know which templates are used,
2605 # otherwise users with "show preview after edit box" will get a blank list
2606 # we parse this near the beginning so that setHeaders can do the title
2607 # setting work instead of leaving it in getPreviewText
2608 $previewOutput = '';
2609 if ( $this->formtype
== 'preview' ) {
2610 $previewOutput = $this->getPreviewText();
2613 $out = $this->context
->getOutput();
2615 // Avoid PHP 7.1 warning of passing $this by reference
2617 Hooks
::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2619 $this->setHeaders();
2621 $this->addTalkPageText();
2622 $this->addEditNotices();
2624 if ( !$this->isConflict
&&
2625 $this->section
!= '' &&
2626 !$this->isSectionEditSupported() ) {
2627 // We use $this->section to much before this and getVal('wgSection') directly in other places
2628 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2629 // Someone is welcome to try refactoring though
2630 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2634 $this->showHeader();
2636 $out->addHTML( $this->editFormPageTop
);
2638 $user = $this->context
->getUser();
2639 if ( $user->getOption( 'previewontop' ) ) {
2640 $this->displayPreviewArea( $previewOutput, true );
2643 $out->addHTML( $this->editFormTextTop
);
2645 $showToolbar = true;
2646 if ( $this->wasDeletedSinceLastEdit() ) {
2647 if ( $this->formtype
== 'save' ) {
2648 // Hide the toolbar and edit area, user can click preview to get it back
2649 // Add an confirmation checkbox and explanation.
2650 $showToolbar = false;
2652 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2653 'deletedwhileediting' );
2657 // @todo add EditForm plugin interface and use it here!
2658 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2659 $out->addHTML( Html
::openElement(
2662 'class' => 'mw-editform',
2663 'id' => self
::EDITFORM_ID
,
2664 'name' => self
::EDITFORM_ID
,
2666 'action' => $this->getActionURL( $this->getContextTitle() ),
2667 'enctype' => 'multipart/form-data'
2671 if ( is_callable( $formCallback ) ) {
2672 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2673 call_user_func_array( $formCallback, [ &$out ] );
2676 // Add an empty field to trip up spambots
2678 Xml
::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2681 [ 'for' => 'wpAntispam' ],
2682 $this->context
->msg( 'simpleantispam-label' )->parse()
2688 'name' => 'wpAntispam',
2689 'id' => 'wpAntispam',
2693 . Xml
::closeElement( 'div' )
2696 // Avoid PHP 7.1 warning of passing $this by reference
2698 Hooks
::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2700 // Put these up at the top to ensure they aren't lost on early form submission
2701 $this->showFormBeforeText();
2703 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2704 $username = $this->lastDelete
->user_name
;
2705 $comment = CommentStore
::newKey( 'log_comment' )->getComment( $this->lastDelete
)->text
;
2707 // It is better to not parse the comment at all than to have templates expanded in the middle
2708 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2709 $key = $comment === ''
2710 ?
'confirmrecreate-noreason'
2711 : 'confirmrecreate';
2713 '<div class="mw-confirm-recreate">' .
2714 $this->context
->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2715 Xml
::checkLabel( $this->context
->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2716 [ 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2722 # When the summary is hidden, also hide them on preview/show changes
2723 if ( $this->nosummary
) {
2724 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2727 # If a blank edit summary was previously provided, and the appropriate
2728 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2729 # user being bounced back more than once in the event that a summary
2732 # For a bit more sophisticated detection of blank summaries, hash the
2733 # automatic one and pass that in the hidden field wpAutoSummary.
2734 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2735 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2738 if ( $this->undidRev
) {
2739 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2742 if ( $this->selfRedirect
) {
2743 $out->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2746 if ( $this->hasPresetSummary
) {
2747 // If a summary has been preset using &summary= we don't want to prompt for
2748 // a different summary. Only prompt for a summary if the summary is blanked.
2750 $this->autoSumm
= md5( '' );
2753 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2754 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2756 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2757 $out->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2759 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2760 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2764 if ( $this->section
== 'new' ) {
2765 $this->showSummaryInput( true, $this->summary
);
2766 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2769 $out->addHTML( $this->editFormTextBeforeContent
);
2771 if ( !$this->isCssJsSubpage
&& $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2772 $out->addHTML( self
::getEditToolbar( $this->mTitle
) );
2775 if ( $this->blankArticle
) {
2776 $out->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2779 if ( $this->isConflict
) {
2780 // In an edit conflict bypass the overridable content form method
2781 // and fallback to the raw wpTextbox1 since editconflicts can't be
2782 // resolved between page source edits and custom ui edits using the
2784 $this->textbox2
= $this->textbox1
;
2786 $content = $this->getCurrentContent();
2787 $this->textbox1
= $this->toEditText( $content );
2789 $this->showTextbox1();
2791 $this->showContentForm();
2794 $out->addHTML( $this->editFormTextAfterContent
);
2796 $this->showStandardInputs();
2798 $this->showFormAfterText();
2800 $this->showTosSummary();
2802 $this->showEditTools();
2804 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2806 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2808 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'hiddencats' ],
2809 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2811 $out->addHTML( Html
::rawElement( 'div', [ 'class' => 'limitreport' ],
2812 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2814 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2816 if ( $this->isConflict
) {
2818 $this->showConflict();
2819 } catch ( MWContentSerializationException
$ex ) {
2820 // this can't really happen, but be nice if it does.
2821 $msg = $this->context
->msg(
2822 'content-failed-to-parse',
2823 $this->contentModel
,
2824 $this->contentFormat
,
2827 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2831 // Set a hidden field so JS knows what edit form mode we are in
2832 if ( $this->isConflict
) {
2834 } elseif ( $this->preview
) {
2836 } elseif ( $this->diff
) {
2841 $out->addHTML( Html
::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2843 // Marker for detecting truncated form data. This must be the last
2844 // parameter sent in order to be of use, so do not move me.
2845 $out->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2846 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2848 if ( !$user->getOption( 'previewontop' ) ) {
2849 $this->displayPreviewArea( $previewOutput, false );
2854 * Wrapper around TemplatesOnThisPageFormatter to make
2855 * a "templates on this page" list.
2857 * @param Title[] $templates
2858 * @return string HTML
2860 public function makeTemplatesOnThisPageList( array $templates ) {
2861 $templateListFormatter = new TemplatesOnThisPageFormatter(
2862 $this->context
, MediaWikiServices
::getInstance()->getLinkRenderer()
2865 // preview if preview, else section if section, else false
2867 if ( $this->preview
) {
2869 } elseif ( $this->section
!= '' ) {
2873 return Html
::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2874 $templateListFormatter->format( $templates, $type )
2879 * Extract the section title from current section text, if any.
2881 * @param string $text
2882 * @return string|bool String or false
2884 public static function extractSectionTitle( $text ) {
2885 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2886 if ( !empty( $matches[2] ) ) {
2888 return $wgParser->stripSectionName( trim( $matches[2] ) );
2894 protected function showHeader() {
2895 global $wgAllowUserCss, $wgAllowUserJs;
2897 $out = $this->context
->getOutput();
2898 $user = $this->context
->getUser();
2899 if ( $this->isConflict
) {
2900 $this->addExplainConflictHeader( $out );
2901 $this->editRevId
= $this->page
->getLatest();
2903 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2904 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2905 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2906 if ( $sectionTitle !== false ) {
2907 $this->summary
= "/* $sectionTitle */ ";
2912 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
2914 if ( $this->missingComment
) {
2915 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2918 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2920 "<div id='mw-missingsummary'>\n$1\n</div>",
2921 [ 'missingsummary', $buttonLabel ]
2925 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2927 "<div id='mw-missingcommentheader'>\n$1\n</div>",
2928 [ 'missingcommentheader', $buttonLabel ]
2932 if ( $this->blankArticle
) {
2934 "<div id='mw-blankarticle'>\n$1\n</div>",
2935 [ 'blankarticle', $buttonLabel ]
2939 if ( $this->selfRedirect
) {
2941 "<div id='mw-selfredirect'>\n$1\n</div>",
2942 [ 'selfredirect', $buttonLabel ]
2946 if ( $this->hookError
!== '' ) {
2947 $out->addWikiText( $this->hookError
);
2950 if ( !$this->checkUnicodeCompliantBrowser() ) {
2951 $out->addWikiMsg( 'nonunicodebrowser' );
2954 if ( $this->section
!= 'new' ) {
2955 $revision = $this->mArticle
->getRevisionFetched();
2957 // Let sysop know that this will make private content public if saved
2959 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $user ) ) {
2961 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2962 'rev-deleted-text-permission'
2964 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2966 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2967 'rev-deleted-text-view'
2971 if ( !$revision->isCurrent() ) {
2972 $this->mArticle
->setOldSubtitle( $revision->getId() );
2973 $out->addWikiMsg( 'editingold' );
2974 $this->isOldRev
= true;
2976 } elseif ( $this->mTitle
->exists() ) {
2977 // Something went wrong
2979 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2980 [ 'missing-revision', $this->oldid
] );
2985 if ( wfReadOnly() ) {
2987 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2988 [ 'readonlywarning', wfReadOnlyReason() ]
2990 } elseif ( $user->isAnon() ) {
2991 if ( $this->formtype
!= 'preview' ) {
2993 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
2994 [ 'anoneditwarning',
2996 SpecialPage
::getTitleFor( 'Userlogin' )->getFullURL( [
2997 'returnto' => $this->getTitle()->getPrefixedDBkey()
3000 SpecialPage
::getTitleFor( 'CreateAccount' )->getFullURL( [
3001 'returnto' => $this->getTitle()->getPrefixedDBkey()
3006 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3007 'anonpreviewwarning'
3011 if ( $this->isCssJsSubpage
) {
3012 # Check the skin exists
3013 if ( $this->isWrongCaseCssJsPage
) {
3015 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
3016 [ 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ]
3019 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3020 $out->wrapWikiMsg( '<div class="mw-usercssjspublic">$1</div>',
3021 $this->isCssSubpage ?
'usercssispublic' : 'userjsispublic'
3023 if ( $this->formtype
!== 'preview' ) {
3024 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
3026 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3027 [ 'usercssyoucanpreview' ]
3031 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
3033 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3034 [ 'userjsyoucanpreview' ]
3042 $this->addPageProtectionWarningHeaders();
3044 $this->addLongPageWarningHeader();
3046 # Add header copyright warning
3047 $this->showHeaderCopyrightWarning();
3051 * Helper function for summary input functions, which returns the neccessary
3052 * attributes for the input.
3054 * @param array|null $inputAttrs Array of attrs to use on the input
3057 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3058 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
3059 return ( is_array( $inputAttrs ) ?
$inputAttrs : [] ) +
[
3060 'id' => 'wpSummary',
3061 'name' => 'wpSummary',
3062 'maxlength' => '200',
3065 'spellcheck' => 'true',
3070 * Standard summary input and label (wgSummary), abstracted so EditPage
3071 * subclasses may reorganize the form.
3072 * Note that you do not need to worry about the label's for=, it will be
3073 * inferred by the id given to the input. You can remove them both by
3074 * passing [ 'id' => false ] to $userInputAttrs.
3076 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3077 * @param string $summary The value of the summary input
3078 * @param string $labelText The html to place inside the label
3079 * @param array $inputAttrs Array of attrs to use on the input
3080 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
3081 * @return array An array in the format [ $label, $input ]
3083 public function getSummaryInput( $summary = "", $labelText = null,
3084 $inputAttrs = null, $spanLabelAttrs = null
3086 wfDeprecated( __METHOD__
, '1.30' );
3087 $inputAttrs = $this->getSummaryInputAttributes( $inputAttrs );
3088 $inputAttrs +
= Linker
::tooltipAndAccesskeyAttribs( 'summary' );
3090 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : [] ) +
[
3091 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
3092 'id' => "wpSummaryLabel"
3099 $inputAttrs['id'] ?
[ 'for' => $inputAttrs['id'] ] : null,
3102 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
3105 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
3107 return [ $label, $input ];
3111 * Builds a standard summary input with a label.
3113 * @deprecated since 1.30 Use getSummaryInputWidget() instead
3114 * @param string $summary The value of the summary input
3115 * @param string $labelText The html to place inside the label
3116 * @param array $inputAttrs Array of attrs to use on the input
3118 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3120 function getSummaryInputOOUI( $summary = "", $labelText = null, $inputAttrs = null ) {
3121 wfDeprecated( __METHOD__
, '1.30' );
3122 $this->getSummaryInputWidget( $summary, $labelText, $inputAttrs );
3126 * Builds a standard summary input with a label.
3128 * @param string $summary The value of the summary input
3129 * @param string $labelText The html to place inside the label
3130 * @param array $inputAttrs Array of attrs to use on the input
3132 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3134 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3135 $inputAttrs = OOUI\Element
::configFromHtmlAttributes(
3136 $this->getSummaryInputAttributes( $inputAttrs )
3139 'title' => Linker
::titleAttrib( 'summary' ),
3140 'accessKey' => Linker
::accesskey( 'summary' ),
3143 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3144 $inputAttrs['inputId'] = $inputAttrs['id'];
3145 $inputAttrs['id'] = 'wpSummaryWidget';
3147 return new OOUI\
FieldLayout(
3148 new OOUI\
TextInputWidget( [
3149 'value' => $summary,
3150 'infusable' => true,
3153 'label' => new OOUI\
HtmlSnippet( $labelText ),
3155 'id' => 'wpSummaryLabel',
3156 'classes' => [ $this->missingSummary ?
'mw-summarymissed' : 'mw-summary' ],
3162 * @param bool $isSubjectPreview True if this is the section subject/title
3163 * up top, or false if this is the comment summary
3164 * down below the textarea
3165 * @param string $summary The text of the summary to display
3167 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3168 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3169 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
3170 if ( $isSubjectPreview ) {
3171 if ( $this->nosummary
) {
3175 if ( !$this->mShowSummaryField
) {
3180 $labelText = $this->context
->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
3181 $this->context
->getOutput()->addHTML( $this->getSummaryInputWidget(
3184 [ 'class' => $summaryClass ]
3189 * @param bool $isSubjectPreview True if this is the section subject/title
3190 * up top, or false if this is the comment summary
3191 * down below the textarea
3192 * @param string $summary The text of the summary to display
3195 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3196 // avoid spaces in preview, gets always trimmed on save
3197 $summary = trim( $summary );
3198 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3204 if ( $isSubjectPreview ) {
3205 $summary = $this->context
->msg( 'newsectionsummary' )
3206 ->rawParams( $wgParser->stripSectionName( $summary ) )
3207 ->inContentLanguage()->text();
3210 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3212 $summary = $this->context
->msg( $message )->parse()
3213 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3214 return Xml
::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3217 protected function showFormBeforeText() {
3218 $out = $this->context
->getOutput();
3219 $out->addHTML( Html
::hidden( 'wpSection', htmlspecialchars( $this->section
) ) );
3220 $out->addHTML( Html
::hidden( 'wpStarttime', $this->starttime
) );
3221 $out->addHTML( Html
::hidden( 'wpEdittime', $this->edittime
) );
3222 $out->addHTML( Html
::hidden( 'editRevId', $this->editRevId
) );
3223 $out->addHTML( Html
::hidden( 'wpScrolltop', $this->scrolltop
, [ 'id' => 'wpScrolltop' ] ) );
3225 if ( !$this->checkUnicodeCompliantBrowser() ) {
3226 $out->addHTML( Html
::hidden( 'safemode', '1' ) );
3230 protected function showFormAfterText() {
3232 * To make it harder for someone to slip a user a page
3233 * which submits an edit form to the wiki without their
3234 * knowledge, a random token is associated with the login
3235 * session. If it's not passed back with the submission,
3236 * we won't save the page, or render user JavaScript and
3239 * For anon editors, who may not have a session, we just
3240 * include the constant suffix to prevent editing from
3241 * broken text-mangling proxies.
3243 $this->context
->getOutput()->addHTML(
3245 Html
::hidden( "wpEditToken", $this->context
->getUser()->getEditToken() ) .
3251 * Subpage overridable method for printing the form for page content editing
3252 * By default this simply outputs wpTextbox1
3253 * Subclasses can override this to provide a custom UI for editing;
3254 * be it a form, or simply wpTextbox1 with a modified content that will be
3255 * reverse modified when extracted from the post data.
3256 * Note that this is basically the inverse for importContentFormData
3258 protected function showContentForm() {
3259 $this->showTextbox1();
3263 * Method to output wpTextbox1
3264 * The $textoverride method can be used by subclasses overriding showContentForm
3265 * to pass back to this method.
3267 * @param array $customAttribs Array of html attributes to use in the textarea
3268 * @param string $textoverride Optional text to override $this->textarea1 with
3270 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3271 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3272 $attribs = [ 'style' => 'display:none;' ];
3274 $classes = []; // Textarea CSS
3275 if ( $this->mTitle
->isProtected( 'edit' ) &&
3276 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
3278 # Is the title semi-protected?
3279 if ( $this->mTitle
->isSemiProtected() ) {
3280 $classes[] = 'mw-textarea-sprotected';
3282 # Then it must be protected based on static groups (regular)
3283 $classes[] = 'mw-textarea-protected';
3285 # Is the title cascade-protected?
3286 if ( $this->mTitle
->isCascadeProtected() ) {
3287 $classes[] = 'mw-textarea-cprotected';
3290 # Is an old revision being edited?
3291 if ( $this->isOldRev
) {
3292 $classes[] = 'mw-textarea-oldrev';
3295 $attribs = [ 'tabindex' => 1 ];
3297 if ( is_array( $customAttribs ) ) {
3298 $attribs +
= $customAttribs;
3301 if ( count( $classes ) ) {
3302 if ( isset( $attribs['class'] ) ) {
3303 $classes[] = $attribs['class'];
3305 $attribs['class'] = implode( ' ', $classes );
3310 $textoverride !== null ?
$textoverride : $this->textbox1
,
3316 protected function showTextbox2() {
3317 $this->showTextbox( $this->textbox2
, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3320 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3321 $wikitext = $this->safeUnicodeOutput( $text );
3322 $wikitext = $this->addNewLineAtEnd( $wikitext );
3324 $attribs = $this->buildTextboxAttribs( $name, $customAttribs, $this->context
->getUser() );
3326 $this->context
->getOutput()->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3329 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3332 $classes[] = 'ontop';
3335 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3337 if ( $this->formtype
!= 'preview' ) {
3338 $attribs['style'] = 'display: none;';
3341 $out = $this->context
->getOutput();
3342 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
3344 if ( $this->formtype
== 'preview' ) {
3345 $this->showPreview( $previewOutput );
3347 // Empty content container for LivePreview
3348 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3349 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3350 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3351 $out->addHTML( Html
::rawElement( 'div', $attribs ) );
3354 $out->addHTML( '</div>' );
3356 if ( $this->formtype
== 'diff' ) {
3359 } catch ( MWContentSerializationException
$ex ) {
3360 $msg = $this->context
->msg(
3361 'content-failed-to-parse',
3362 $this->contentModel
,
3363 $this->contentFormat
,
3366 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3372 * Append preview output to OutputPage.
3373 * Includes category rendering if this is a category page.
3375 * @param string $text The HTML to be output for the preview.
3377 protected function showPreview( $text ) {
3378 if ( $this->mArticle
instanceof CategoryPage
) {
3379 $this->mArticle
->openShowCategory();
3381 # This hook seems slightly odd here, but makes things more
3382 # consistent for extensions.
3383 $out = $this->context
->getOutput();
3384 Hooks
::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3385 $out->addHTML( $text );
3386 if ( $this->mArticle
instanceof CategoryPage
) {
3387 $this->mArticle
->closeShowCategory();
3392 * Get a diff between the current contents of the edit box and the
3393 * version of the page we're editing from.
3395 * If this is a section edit, we'll replace the section as for final
3396 * save and then make a comparison.
3398 public function showDiff() {
3401 $oldtitlemsg = 'currentrev';
3402 # if message does not exist, show diff against the preloaded default
3403 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3404 $oldtext = $this->mTitle
->getDefaultMessageText();
3405 if ( $oldtext !== false ) {
3406 $oldtitlemsg = 'defaultmessagetext';
3407 $oldContent = $this->toEditContent( $oldtext );
3412 $oldContent = $this->getCurrentContent();
3415 $textboxContent = $this->toEditContent( $this->textbox1
);
3416 if ( $this->editRevId
!== null ) {
3417 $newContent = $this->page
->replaceSectionAtRev(
3418 $this->section
, $textboxContent, $this->summary
, $this->editRevId
3421 $newContent = $this->page
->replaceSectionContent(
3422 $this->section
, $textboxContent, $this->summary
, $this->edittime
3426 if ( $newContent ) {
3427 Hooks
::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3429 $user = $this->context
->getUser();
3430 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
3431 $newContent = $newContent->preSaveTransform( $this->mTitle
, $user, $popts );
3434 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3435 $oldtitle = $this->context
->msg( $oldtitlemsg )->parse();
3436 $newtitle = $this->context
->msg( 'yourtext' )->parse();
3438 if ( !$oldContent ) {
3439 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3442 if ( !$newContent ) {
3443 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3446 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3447 $de->setContent( $oldContent, $newContent );
3449 $difftext = $de->getDiff( $oldtitle, $newtitle );
3450 $de->showDiffStyle();
3455 $this->context
->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3459 * Show the header copyright warning.
3461 protected function showHeaderCopyrightWarning() {
3462 $msg = 'editpage-head-copy-warn';
3463 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3464 $this->context
->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3465 'editpage-head-copy-warn' );
3470 * Give a chance for site and per-namespace customizations of
3471 * terms of service summary link that might exist separately
3472 * from the copyright notice.
3474 * This will display between the save button and the edit tools,
3475 * so should remain short!
3477 protected function showTosSummary() {
3478 $msg = 'editpage-tos-summary';
3479 Hooks
::run( 'EditPageTosSummary', [ $this->mTitle
, &$msg ] );
3480 if ( !$this->context
->msg( $msg )->isDisabled() ) {
3481 $out = $this->context
->getOutput();
3482 $out->addHTML( '<div class="mw-tos-summary">' );
3483 $out->addWikiMsg( $msg );
3484 $out->addHTML( '</div>' );
3489 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3490 * characters not present on most keyboards for copying/pasting.
3492 protected function showEditTools() {
3493 $this->context
->getOutput()->addHTML( '<div class="mw-editTools">' .
3494 $this->context
->msg( 'edittools' )->inContentLanguage()->parse() .
3499 * Get the copyright warning
3501 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3504 protected function getCopywarn() {
3505 return self
::getCopyrightWarning( $this->mTitle
);
3509 * Get the copyright warning, by default returns wikitext
3511 * @param Title $title
3512 * @param string $format Output format, valid values are any function of a Message object
3513 * @param Language|string|null $langcode Language code or Language object.
3516 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3517 global $wgRightsText;
3518 if ( $wgRightsText ) {
3519 $copywarnMsg = [ 'copyrightwarning',
3520 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3523 $copywarnMsg = [ 'copyrightwarning2',
3524 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3526 // Allow for site and per-namespace customization of contribution/copyright notice.
3527 Hooks
::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3529 $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
3531 $msg->inLanguage( $langcode );
3533 return "<div id=\"editpage-copywarn\">\n" .
3534 $msg->$format() . "\n</div>";
3538 * Get the Limit report for page previews
3541 * @param ParserOutput $output ParserOutput object from the parse
3542 * @return string HTML
3544 public static function getPreviewLimitReport( $output ) {
3545 if ( !$output ||
!$output->getLimitReportData() ) {
3549 $limitReport = Html
::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3550 wfMessage( 'limitreport-title' )->parseAsBlock()
3553 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3554 $limitReport .= Html
::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3556 $limitReport .= Html
::openElement( 'table', [
3557 'class' => 'preview-limit-report wikitable'
3559 Html
::openElement( 'tbody' );
3561 foreach ( $output->getLimitReportData() as $key => $value ) {
3562 if ( Hooks
::run( 'ParserLimitReportFormat',
3563 [ $key, &$value, &$limitReport, true, true ]
3565 $keyMsg = wfMessage( $key );
3566 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3567 if ( !$valueMsg->exists() ) {
3568 $valueMsg = new RawMessage( '$1' );
3570 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3571 $limitReport .= Html
::openElement( 'tr' ) .
3572 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3573 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3574 Html
::closeElement( 'tr' );
3579 $limitReport .= Html
::closeElement( 'tbody' ) .
3580 Html
::closeElement( 'table' ) .
3581 Html
::closeElement( 'div' );
3583 return $limitReport;
3586 protected function showStandardInputs( &$tabindex = 2 ) {
3587 $out = $this->context
->getOutput();
3588 $out->addHTML( "<div class='editOptions'>\n" );
3590 if ( $this->section
!= 'new' ) {
3591 $this->showSummaryInput( false, $this->summary
);
3592 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3595 $checkboxes = $this->getCheckboxesWidget(
3597 [ 'minor' => $this->minoredit
, 'watch' => $this->watchthis
]
3599 $checkboxesHTML = new OOUI\
HorizontalLayout( [ 'items' => $checkboxes ] );
3601 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3603 // Show copyright warning.
3604 $out->addWikiText( $this->getCopywarn() );
3605 $out->addHTML( $this->editFormTextAfterWarn
);
3607 $out->addHTML( "<div class='editButtons'>\n" );
3608 $out->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3610 $cancel = $this->getCancelLink();
3611 if ( $cancel !== '' ) {
3612 $cancel .= Html
::element( 'span',
3613 [ 'class' => 'mw-editButtons-pipe-separator' ],
3614 $this->context
->msg( 'pipe-separator' )->text() );
3617 $message = $this->context
->msg( 'edithelppage' )->inContentLanguage()->text();
3618 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3621 $this->context
->msg( 'edithelp' )->text(),
3622 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3625 $this->context
->msg( 'word-separator' )->escaped() .
3626 $this->context
->msg( 'newwindow' )->parse();
3628 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3629 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3630 $out->addHTML( "</div><!-- editButtons -->\n" );
3632 Hooks
::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3634 $out->addHTML( "</div><!-- editOptions -->\n" );
3638 * Show an edit conflict. textbox1 is already shown in showEditForm().
3639 * If you want to use another entry point to this function, be careful.
3641 protected function showConflict() {
3642 $out = $this->context
->getOutput();
3643 // Avoid PHP 7.1 warning of passing $this by reference
3645 if ( Hooks
::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3646 $this->incrementConflictStats();
3648 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3650 $content1 = $this->toEditContent( $this->textbox1
);
3651 $content2 = $this->toEditContent( $this->textbox2
);
3653 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3654 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3655 $de->setContent( $content2, $content1 );
3657 $this->context
->msg( 'yourtext' )->parse(),
3658 $this->context
->msg( 'storedversion' )->text()
3661 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3662 $this->showTextbox2();
3666 protected function incrementConflictStats() {
3667 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3668 $stats->increment( 'edit.failures.conflict' );
3669 // Only include 'standard' namespaces to avoid creating unknown numbers of statsd metrics
3671 $this->mTitle
->getNamespace() >= NS_MAIN
&&
3672 $this->mTitle
->getNamespace() <= NS_CATEGORY_TALK
3674 $stats->increment( 'edit.failures.conflict.byNamespaceId.' . $this->mTitle
->getNamespace() );
3681 public function getCancelLink() {
3683 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3684 $cancelParams['oldid'] = $this->oldid
;
3685 } elseif ( $this->getContextTitle()->isRedirect() ) {
3686 $cancelParams['redirect'] = 'no';
3689 return new OOUI\
ButtonWidget( [
3690 'id' => 'mw-editform-cancel',
3691 'href' => $this->getContextTitle()->getLinkUrl( $cancelParams ),
3692 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( 'cancel' )->parse() ),
3694 'infusable' => true,
3695 'flags' => 'destructive',
3700 * Returns the URL to use in the form's action attribute.
3701 * This is used by EditPage subclasses when simply customizing the action
3702 * variable in the constructor is not enough. This can be used when the
3703 * EditPage lives inside of a Special page rather than a custom page action.
3705 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3708 protected function getActionURL( Title
$title ) {
3709 return $title->getLocalURL( [ 'action' => $this->action
] );
3713 * Check if a page was deleted while the user was editing it, before submit.
3714 * Note that we rely on the logging table, which hasn't been always there,
3715 * but that doesn't matter, because this only applies to brand new
3719 protected function wasDeletedSinceLastEdit() {
3720 if ( $this->deletedSinceEdit
!== null ) {
3721 return $this->deletedSinceEdit
;
3724 $this->deletedSinceEdit
= false;
3726 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3727 $this->lastDelete
= $this->getLastDelete();
3728 if ( $this->lastDelete
) {
3729 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3730 if ( $deleteTime > $this->starttime
) {
3731 $this->deletedSinceEdit
= true;
3736 return $this->deletedSinceEdit
;
3740 * @return bool|stdClass
3742 protected function getLastDelete() {
3743 $dbr = wfGetDB( DB_REPLICA
);
3744 $commentQuery = CommentStore
::newKey( 'log_comment' )->getJoin();
3745 $data = $dbr->selectRow(
3746 [ 'logging', 'user' ] +
$commentQuery['tables'],
3757 ] +
$commentQuery['fields'], [
3758 'log_namespace' => $this->mTitle
->getNamespace(),
3759 'log_title' => $this->mTitle
->getDBkey(),
3760 'log_type' => 'delete',
3761 'log_action' => 'delete',
3765 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3767 'user' => [ 'JOIN', 'user_id=log_user' ],
3768 ] +
$commentQuery['joins']
3770 // Quick paranoid permission checks...
3771 if ( is_object( $data ) ) {
3772 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3773 $data->user_name
= $this->context
->msg( 'rev-deleted-user' )->escaped();
3776 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3777 $data->log_comment_text
= $this->context
->msg( 'rev-deleted-comment' )->escaped();
3778 $data->log_comment_data
= null;
3786 * Get the rendered text for previewing.
3787 * @throws MWException
3790 public function getPreviewText() {
3792 global $wgAllowUserCss, $wgAllowUserJs;
3794 $out = $this->context
->getOutput();
3796 if ( $wgRawHtml && !$this->mTokenOk
) {
3797 // Could be an offsite preview attempt. This is very unsafe if
3798 // HTML is enabled, as it could be an attack.
3800 if ( $this->textbox1
!== '' ) {
3801 // Do not put big scary notice, if previewing the empty
3802 // string, which happens when you initially edit
3803 // a category page, due to automatic preview-on-open.
3804 $parsedNote = $out->parse( "<div class='previewnote'>" .
3805 $this->context
->msg( 'session_fail_preview_html' )->text() . "</div>",
3806 true, /* interface */true );
3808 $this->incrementEditFailureStats( 'session_loss' );
3815 $content = $this->toEditContent( $this->textbox1
);
3819 'AlternateEditPreview',
3820 [ $this, &$content, &$previewHTML, &$this->mParserOutput
] )
3822 return $previewHTML;
3825 # provide a anchor link to the editform
3826 $continueEditing = '<span class="mw-continue-editing">' .
3827 '[[#' . self
::EDITFORM_ID
. '|' .
3828 $this->context
->getLanguage()->getArrow() . ' ' .
3829 $this->context
->msg( 'continue-editing' )->text() . ']]</span>';
3830 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3831 if ( $this->mTokenOkExceptSuffix
) {
3832 $note = $this->context
->msg( 'token_suffix_mismatch' )->plain();
3833 $this->incrementEditFailureStats( 'bad_token' );
3835 $note = $this->context
->msg( 'session_fail_preview' )->plain();
3836 $this->incrementEditFailureStats( 'session_loss' );
3838 } elseif ( $this->incompleteForm
) {
3839 $note = $this->context
->msg( 'edit_form_incomplete' )->plain();
3840 if ( $this->mTriedSave
) {
3841 $this->incrementEditFailureStats( 'incomplete_form' );
3844 $note = $this->context
->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3847 # don't parse non-wikitext pages, show message about preview
3848 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3849 if ( $this->mTitle
->isCssJsSubpage() ) {
3851 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3857 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3859 if ( $level === 'user' && !$wgAllowUserCss ) {
3862 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3864 if ( $level === 'user' && !$wgAllowUserJs ) {
3871 # Used messages to make sure grep find them:
3872 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3873 if ( $level && $format ) {
3874 $note = "<div id='mw-{$level}{$format}preview'>" .
3875 $this->context
->msg( "{$level}{$format}preview" )->text() .
3876 ' ' . $continueEditing . "</div>";
3880 # If we're adding a comment, we need to show the
3881 # summary as the headline
3882 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3883 $content = $content->addSectionHeader( $this->summary
);
3886 $hook_args = [ $this, &$content ];
3887 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3889 $parserResult = $this->doPreviewParse( $content );
3890 $parserOutput = $parserResult['parserOutput'];
3891 $previewHTML = $parserResult['html'];
3892 $this->mParserOutput
= $parserOutput;
3893 $out->addParserOutputMetadata( $parserOutput );
3895 if ( count( $parserOutput->getWarnings() ) ) {
3896 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3899 } catch ( MWContentSerializationException
$ex ) {
3900 $m = $this->context
->msg(
3901 'content-failed-to-parse',
3902 $this->contentModel
,
3903 $this->contentFormat
,
3906 $note .= "\n\n" . $m->parse();
3910 if ( $this->isConflict
) {
3911 $conflict = '<h2 id="mw-previewconflict">'
3912 . $this->context
->msg( 'previewconflict' )->escaped() . "</h2>\n";
3914 $conflict = '<hr />';
3917 $previewhead = "<div class='previewnote'>\n" .
3918 '<h2 id="mw-previewheader">' . $this->context
->msg( 'preview' )->escaped() . "</h2>" .
3919 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3921 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3922 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3923 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3924 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3926 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3929 private function incrementEditFailureStats( $failureType ) {
3930 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
3931 $stats->increment( 'edit.failures.' . $failureType );
3935 * Get parser options for a preview
3936 * @return ParserOptions
3938 protected function getPreviewParserOptions() {
3939 $parserOptions = $this->page
->makeParserOptions( $this->mArticle
->getContext() );
3940 $parserOptions->setIsPreview( true );
3941 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3942 $parserOptions->enableLimitReport();
3943 return $parserOptions;
3947 * Parse the page for a preview. Subclasses may override this class, in order
3948 * to parse with different options, or to otherwise modify the preview HTML.
3950 * @param Content $content The page content
3951 * @return array with keys:
3952 * - parserOutput: The ParserOutput object
3953 * - html: The HTML to be displayed
3955 protected function doPreviewParse( Content
$content ) {
3956 $user = $this->context
->getUser();
3957 $parserOptions = $this->getPreviewParserOptions();
3958 $pstContent = $content->preSaveTransform( $this->mTitle
, $user, $parserOptions );
3959 $scopedCallback = $parserOptions->setupFakeRevision(
3960 $this->mTitle
, $pstContent, $user );
3961 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3962 ScopedCallback
::consume( $scopedCallback );
3963 $parserOutput->setEditSectionTokens( false ); // no section edit links
3965 'parserOutput' => $parserOutput,
3966 'html' => $parserOutput->getText() ];
3972 public function getTemplates() {
3973 if ( $this->preview ||
$this->section
!= '' ) {
3975 if ( !isset( $this->mParserOutput
) ) {
3978 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3979 foreach ( array_keys( $template ) as $dbk ) {
3980 $templates[] = Title
::makeTitle( $ns, $dbk );
3985 return $this->mTitle
->getTemplateLinksFrom();
3990 * Shows a bulletin board style toolbar for common editing functions.
3991 * It can be disabled in the user preferences.
3993 * @param Title $title Title object for the page being edited (optional)
3996 public static function getEditToolbar( $title = null ) {
3997 global $wgContLang, $wgOut;
3998 global $wgEnableUploads, $wgForeignFileRepos;
4000 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
4001 $showSignature = true;
4003 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
4007 * $toolarray is an array of arrays each of which includes the
4008 * opening tag, the closing tag, optionally a sample text that is
4009 * inserted between the two when no selection is highlighted
4010 * and. The tip text is shown when the user moves the mouse
4013 * Images are defined in ResourceLoaderEditToolbarModule.
4017 'id' => 'mw-editbutton-bold',
4019 'close' => '\'\'\'',
4020 'sample' => wfMessage( 'bold_sample' )->text(),
4021 'tip' => wfMessage( 'bold_tip' )->text(),
4024 'id' => 'mw-editbutton-italic',
4027 'sample' => wfMessage( 'italic_sample' )->text(),
4028 'tip' => wfMessage( 'italic_tip' )->text(),
4031 'id' => 'mw-editbutton-link',
4034 'sample' => wfMessage( 'link_sample' )->text(),
4035 'tip' => wfMessage( 'link_tip' )->text(),
4038 'id' => 'mw-editbutton-extlink',
4041 'sample' => wfMessage( 'extlink_sample' )->text(),
4042 'tip' => wfMessage( 'extlink_tip' )->text(),
4045 'id' => 'mw-editbutton-headline',
4048 'sample' => wfMessage( 'headline_sample' )->text(),
4049 'tip' => wfMessage( 'headline_tip' )->text(),
4051 $imagesAvailable ?
[
4052 'id' => 'mw-editbutton-image',
4053 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
4055 'sample' => wfMessage( 'image_sample' )->text(),
4056 'tip' => wfMessage( 'image_tip' )->text(),
4058 $imagesAvailable ?
[
4059 'id' => 'mw-editbutton-media',
4060 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
4062 'sample' => wfMessage( 'media_sample' )->text(),
4063 'tip' => wfMessage( 'media_tip' )->text(),
4066 'id' => 'mw-editbutton-nowiki',
4067 'open' => "<nowiki>",
4068 'close' => "</nowiki>",
4069 'sample' => wfMessage( 'nowiki_sample' )->text(),
4070 'tip' => wfMessage( 'nowiki_tip' )->text(),
4073 'id' => 'mw-editbutton-signature',
4074 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4077 'tip' => wfMessage( 'sig_tip' )->text(),
4080 'id' => 'mw-editbutton-hr',
4081 'open' => "\n----\n",
4084 'tip' => wfMessage( 'hr_tip' )->text(),
4088 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4089 foreach ( $toolarray as $tool ) {
4095 // Images are defined in ResourceLoaderEditToolbarModule
4097 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4098 // Older browsers show a "speedtip" type message only for ALT.
4099 // Ideally these should be different, realistically they
4100 // probably don't need to be.
4108 $script .= Xml
::encodeJsCall(
4109 'mw.toolbar.addButton',
4111 ResourceLoader
::inDebugMode()
4117 $toolbar = '<div id="toolbar"></div>';
4119 if ( Hooks
::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4120 // Only add the old toolbar cruft to the page payload if the toolbar has not
4121 // been over-written by a hook caller
4122 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
4129 * Return an array of checkbox definitions.
4131 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4133 * Array values are associative arrays with the following keys:
4134 * - 'label-message' (required): message for label text
4135 * - 'id' (required): 'id' attribute for the `<input>`
4136 * - 'default' (required): default checkedness (true or false)
4137 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4138 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4139 * from messages like 'tooltip-foo', 'accesskey-foo'
4140 * - 'label-id' (optional): 'id' attribute for the `<label>`
4141 * - 'legacy-name' (optional): short name for backwards-compatibility
4142 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4143 * where bool indicates the checked status of the checkbox
4146 public function getCheckboxesDefinition( $checked ) {
4149 $user = $this->context
->getUser();
4150 // don't show the minor edit checkbox if it's a new page or section
4151 if ( !$this->isNew
&& $user->isAllowed( 'minoredit' ) ) {
4152 $checkboxes['wpMinoredit'] = [
4153 'id' => 'wpMinoredit',
4154 'label-message' => 'minoredit',
4155 // Uses messages: tooltip-minoredit, accesskey-minoredit
4156 'tooltip' => 'minoredit',
4157 'label-id' => 'mw-editpage-minoredit',
4158 'legacy-name' => 'minor',
4159 'default' => $checked['minor'],
4163 if ( $user->isLoggedIn() ) {
4164 $checkboxes['wpWatchthis'] = [
4165 'id' => 'wpWatchthis',
4166 'label-message' => 'watchthis',
4167 // Uses messages: tooltip-watch, accesskey-watch
4168 'tooltip' => 'watch',
4169 'label-id' => 'mw-editpage-watch',
4170 'legacy-name' => 'watch',
4171 'default' => $checked['watch'],
4176 Hooks
::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4182 * Returns an array of html code of the following checkboxes old style:
4185 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4186 * @param int &$tabindex Current tabindex
4187 * @param array $checked See getCheckboxesDefinition()
4190 public function getCheckboxes( &$tabindex, $checked ) {
4191 global $wgUseMediaWikiUIEverywhere;
4194 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4196 // Backwards-compatibility for the EditPageBeforeEditChecks hook
4197 if ( !$this->isNew
) {
4198 $checkboxes['minor'] = '';
4200 $checkboxes['watch'] = '';
4202 foreach ( $checkboxesDef as $name => $options ) {
4203 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4204 $label = $this->context
->msg( $options['label-message'] )->parse();
4206 'tabindex' => ++
$tabindex,
4207 'id' => $options['id'],
4210 'for' => $options['id'],
4212 if ( isset( $options['tooltip'] ) ) {
4213 $attribs['accesskey'] = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4214 $labelAttribs['title'] = Linker
::titleAttrib( $options['tooltip'], 'withaccess' );
4216 if ( isset( $options['title-message'] ) ) {
4217 $labelAttribs['title'] = $this->context
->msg( $options['title-message'] )->text();
4219 if ( isset( $options['label-id'] ) ) {
4220 $labelAttribs['id'] = $options['label-id'];
4223 Xml
::check( $name, $options['default'], $attribs ) .
4225 Xml
::tags( 'label', $labelAttribs, $label );
4227 if ( $wgUseMediaWikiUIEverywhere ) {
4228 $checkboxHtml = Html
::rawElement( 'div', [ 'class' => 'mw-ui-checkbox' ], $checkboxHtml );
4231 $checkboxes[ $legacyName ] = $checkboxHtml;
4234 // Avoid PHP 7.1 warning of passing $this by reference
4236 Hooks
::run( 'EditPageBeforeEditChecks', [ &$editPage, &$checkboxes, &$tabindex ], '1.29' );
4241 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4242 * any other added by extensions.
4244 * @deprecated since 1.30 Use getCheckboxesWidget() or getCheckboxesDefinition() instead
4245 * @param int &$tabindex Current tabindex
4246 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4247 * status of the checkbox
4249 * @return array Associative array of string keys to OOUI\FieldLayout instances
4251 public function getCheckboxesOOUI( &$tabindex, $checked ) {
4252 return $this->getCheckboxesWidget( $tabindex, $checked );
4256 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4257 * any other added by extensions.
4259 * @param int &$tabindex Current tabindex
4260 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4261 * status of the checkbox
4263 * @return array Associative array of string keys to OOUI\FieldLayout instances
4265 public function getCheckboxesWidget( &$tabindex, $checked ) {
4267 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4269 foreach ( $checkboxesDef as $name => $options ) {
4270 $legacyName = isset( $options['legacy-name'] ) ?
$options['legacy-name'] : $name;
4274 if ( isset( $options['tooltip'] ) ) {
4275 $accesskey = $this->context
->msg( "accesskey-{$options['tooltip']}" )->text();
4276 $title = Linker
::titleAttrib( $options['tooltip'] );
4278 if ( isset( $options['title-message'] ) ) {
4279 $title = $this->context
->msg( $options['title-message'] )->text();
4282 $checkboxes[ $legacyName ] = new OOUI\
FieldLayout(
4283 new OOUI\
CheckboxInputWidget( [
4284 'tabIndex' => ++
$tabindex,
4285 'accessKey' => $accesskey,
4286 'id' => $options['id'] . 'Widget',
4287 'inputId' => $options['id'],
4289 'selected' => $options['default'],
4290 'infusable' => true,
4293 'align' => 'inline',
4294 'label' => new OOUI\
HtmlSnippet( $this->context
->msg( $options['label-message'] )->parse() ),
4296 'id' => isset( $options['label-id'] ) ?
$options['label-id'] : null,
4301 // Backwards-compatibility hack to run the EditPageBeforeEditChecks hook. It's important,
4302 // people have used it for the weirdest things completely unrelated to checkboxes...
4303 // And if we're gonna run it, might as well allow its legacy checkboxes to be shown.
4304 $legacyCheckboxes = [];
4305 if ( !$this->isNew
) {
4306 $legacyCheckboxes['minor'] = '';
4308 $legacyCheckboxes['watch'] = '';
4309 // Copy new-style checkboxes into an old-style structure
4310 foreach ( $checkboxes as $name => $oouiLayout ) {
4311 $legacyCheckboxes[$name] = (string)$oouiLayout;
4313 // Avoid PHP 7.1 warning of passing $this by reference
4315 Hooks
::run( 'EditPageBeforeEditChecks', [ &$ep, &$legacyCheckboxes, &$tabindex ], '1.29' );
4316 // Copy back any additional old-style checkboxes into the new-style structure
4317 foreach ( $legacyCheckboxes as $name => $html ) {
4318 if ( $html && !isset( $checkboxes[$name] ) ) {
4319 $checkboxes[$name] = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $html ) ] );
4327 * Get the message key of the label for the button to save the page
4331 protected function getSubmitButtonLabel() {
4333 $this->context
->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4335 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4336 $newPage = !$this->mTitle
->exists();
4338 if ( $labelAsPublish ) {
4339 $buttonLabelKey = $newPage ?
'publishpage' : 'publishchanges';
4341 $buttonLabelKey = $newPage ?
'savearticle' : 'savechanges';
4344 return $buttonLabelKey;
4348 * Returns an array of html code of the following buttons:
4349 * save, diff and preview
4351 * @param int &$tabindex Current tabindex
4355 public function getEditButtons( &$tabindex ) {
4358 $buttonLabel = $this->context
->msg( $this->getSubmitButtonLabel() )->text();
4362 'tabindex' => ++
$tabindex,
4365 $saveConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4366 $buttons['save'] = new OOUI\
ButtonInputWidget( [
4367 'id' => 'wpSaveWidget',
4368 'inputId' => 'wpSave',
4369 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4370 'useInputTag' => true,
4371 'flags' => [ 'constructive', 'primary' ],
4372 'label' => $buttonLabel,
4373 'infusable' => true,
4375 'title' => Linker
::titleAttrib( 'save' ),
4376 'accessKey' => Linker
::accesskey( 'save' ),
4380 'name' => 'wpPreview',
4381 'tabindex' => ++
$tabindex,
4384 $previewConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4385 $buttons['preview'] = new OOUI\
ButtonInputWidget( [
4386 'id' => 'wpPreviewWidget',
4387 'inputId' => 'wpPreview',
4388 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4389 'useInputTag' => true,
4390 'label' => $this->context
->msg( 'showpreview' )->text(),
4391 'infusable' => true,
4393 'title' => Linker
::titleAttrib( 'preview' ),
4394 'accessKey' => Linker
::accesskey( 'preview' ),
4395 ] +
$previewConfig );
4399 'tabindex' => ++
$tabindex,
4402 $diffConfig = OOUI\Element
::configFromHtmlAttributes( $attribs );
4403 $buttons['diff'] = new OOUI\
ButtonInputWidget( [
4404 'id' => 'wpDiffWidget',
4405 'inputId' => 'wpDiff',
4406 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4407 'useInputTag' => true,
4408 'label' => $this->context
->msg( 'showdiff' )->text(),
4409 'infusable' => true,
4411 'title' => Linker
::titleAttrib( 'diff' ),
4412 'accessKey' => Linker
::accesskey( 'diff' ),
4415 // Avoid PHP 7.1 warning of passing $this by reference
4417 Hooks
::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4423 * Creates a basic error page which informs the user that
4424 * they have attempted to edit a nonexistent section.
4426 public function noSuchSectionPage() {
4427 $out = $this->context
->getOutput();
4428 $out->prepareErrorPage( $this->context
->msg( 'nosuchsectiontitle' ) );
4430 $res = $this->context
->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4432 // Avoid PHP 7.1 warning of passing $this by reference
4434 Hooks
::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4435 $out->addHTML( $res );
4437 $out->returnToMain( false, $this->mTitle
);
4441 * Show "your edit contains spam" page with your diff and text
4443 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4445 public function spamPageWithContent( $match = false ) {
4446 $this->textbox2
= $this->textbox1
;
4448 if ( is_array( $match ) ) {
4449 $match = $this->context
->getLanguage()->listToText( $match );
4451 $out = $this->context
->getOutput();
4452 $out->prepareErrorPage( $this->context
->msg( 'spamprotectiontitle' ) );
4454 $out->addHTML( '<div id="spamprotected">' );
4455 $out->addWikiMsg( 'spamprotectiontext' );
4457 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4459 $out->addHTML( '</div>' );
4461 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4464 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4465 $this->showTextbox2();
4467 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4471 * Check if the browser is on a blacklist of user-agents known to
4472 * mangle UTF-8 data on form submission. Returns true if Unicode
4473 * should make it through, false if it's known to be a problem.
4476 private function checkUnicodeCompliantBrowser() {
4477 global $wgBrowserBlackList;
4479 $currentbrowser = $this->context
->getRequest()->getHeader( 'User-Agent' );
4480 if ( $currentbrowser === false ) {
4481 // No User-Agent header sent? Trust it by default...
4485 foreach ( $wgBrowserBlackList as $browser ) {
4486 if ( preg_match( $browser, $currentbrowser ) ) {
4494 * Filter an input field through a Unicode de-armoring process if it
4495 * came from an old browser with known broken Unicode editing issues.
4497 * @param WebRequest $request
4498 * @param string $field
4501 protected function safeUnicodeInput( $request, $field ) {
4502 $text = rtrim( $request->getText( $field ) );
4503 return $request->getBool( 'safemode' )
4504 ?
$this->unmakeSafe( $text )
4509 * Filter an output field through a Unicode armoring process if it is
4510 * going to an old browser with known broken Unicode editing issues.
4512 * @param string $text
4515 protected function safeUnicodeOutput( $text ) {
4516 return $this->checkUnicodeCompliantBrowser()
4518 : $this->makeSafe( $text );
4522 * A number of web browsers are known to corrupt non-ASCII characters
4523 * in a UTF-8 text editing environment. To protect against this,
4524 * detected browsers will be served an armored version of the text,
4525 * with non-ASCII chars converted to numeric HTML character references.
4527 * Preexisting such character references will have a 0 added to them
4528 * to ensure that round-trips do not alter the original data.
4530 * @param string $invalue
4533 private function makeSafe( $invalue ) {
4534 // Armor existing references for reversibility.
4535 $invalue = strtr( $invalue, [ "&#x" => "�" ] );
4540 $valueLength = strlen( $invalue );
4541 for ( $i = 0; $i < $valueLength; $i++
) {
4542 $bytevalue = ord( $invalue[$i] );
4543 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4544 $result .= chr( $bytevalue );
4546 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4547 $working = $working << 6;
4548 $working +
= ( $bytevalue & 0x3F );
4550 if ( $bytesleft <= 0 ) {
4551 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4553 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4554 $working = $bytevalue & 0x1F;
4556 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4557 $working = $bytevalue & 0x0F;
4559 } else { // 1111 0xxx
4560 $working = $bytevalue & 0x07;
4568 * Reverse the previously applied transliteration of non-ASCII characters
4569 * back to UTF-8. Used to protect data from corruption by broken web browsers
4570 * as listed in $wgBrowserBlackList.
4572 * @param string $invalue
4575 private function unmakeSafe( $invalue ) {
4577 $valueLength = strlen( $invalue );
4578 for ( $i = 0; $i < $valueLength; $i++
) {
4579 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4583 $hexstring .= $invalue[$i];
4585 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4587 // Do some sanity checks. These aren't needed for reversibility,
4588 // but should help keep the breakage down if the editor
4589 // breaks one of the entities whilst editing.
4590 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4591 $codepoint = hexdec( $hexstring );
4592 $result .= UtfNormal\Utils
::codepointToUtf8( $codepoint );
4594 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4597 $result .= substr( $invalue, $i, 1 );
4600 // reverse the transform that we made for reversibility reasons.
4601 return strtr( $result, [ "�" => "&#x" ] );
4607 protected function addEditNotices() {
4608 $out = $this->context
->getOutput();
4609 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
4610 if ( count( $editNotices ) ) {
4611 $out->addHTML( implode( "\n", $editNotices ) );
4613 $msg = $this->context
->msg( 'editnotice-notext' );
4614 if ( !$msg->isDisabled() ) {
4616 '<div class="mw-editnotice-notext">'
4617 . $msg->parseAsBlock()
4627 protected function addTalkPageText() {
4628 if ( $this->mTitle
->isTalkPage() ) {
4629 $this->context
->getOutput()->addWikiMsg( 'talkpagetext' );
4636 protected function addLongPageWarningHeader() {
4637 global $wgMaxArticleSize;
4639 if ( $this->contentLength
=== false ) {
4640 $this->contentLength
= strlen( $this->textbox1
);
4643 $out = $this->context
->getOutput();
4644 $lang = $this->context
->getLanguage();
4645 if ( $this->tooBig ||
$this->contentLength
> $wgMaxArticleSize * 1024 ) {
4646 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4649 $lang->formatNum( round( $this->contentLength
/ 1024, 3 ) ),
4650 $lang->formatNum( $wgMaxArticleSize )
4654 if ( !$this->context
->msg( 'longpage-hint' )->isDisabled() ) {
4655 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4658 $lang->formatSize( strlen( $this->textbox1
) ),
4659 strlen( $this->textbox1
)
4669 protected function addPageProtectionWarningHeaders() {
4670 $out = $this->context
->getOutput();
4671 if ( $this->mTitle
->isProtected( 'edit' ) &&
4672 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== [ '' ]
4674 # Is the title semi-protected?
4675 if ( $this->mTitle
->isSemiProtected() ) {
4676 $noticeMsg = 'semiprotectedpagewarning';
4678 # Then it must be protected based on static groups (regular)
4679 $noticeMsg = 'protectedpagewarning';
4681 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4682 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4684 if ( $this->mTitle
->isCascadeProtected() ) {
4685 # Is this page under cascading protection from some source pages?
4686 /** @var Title[] $cascadeSources */
4687 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
4688 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4689 $cascadeSourcesCount = count( $cascadeSources );
4690 if ( $cascadeSourcesCount > 0 ) {
4691 # Explain, and list the titles responsible
4692 foreach ( $cascadeSources as $page ) {
4693 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4696 $notice .= '</div>';
4697 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4699 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
4700 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
, '',
4702 'showIfEmpty' => false,
4703 'msgKey' => [ 'titleprotectedwarning' ],
4704 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4709 * @param OutputPage $out
4712 protected function addExplainConflictHeader( OutputPage
$out ) {
4714 "<div class='mw-explainconflict'>\n$1\n</div>",
4715 [ 'explainconflict', $this->context
->msg( $this->getSubmitButtonLabel() )->text() ]
4720 * @param string $name
4721 * @param mixed[] $customAttribs
4726 protected function buildTextboxAttribs( $name, array $customAttribs, User
$user ) {
4727 $attribs = $customAttribs +
[
4732 // Avoid PHP notices when appending preferences
4733 // (appending allows customAttribs['style'] to still work).
4737 // The following classes can be used here:
4738 // * mw-editfont-default
4739 // * mw-editfont-monospace
4740 // * mw-editfont-sans-serif
4741 // * mw-editfont-serif
4742 $class = 'mw-editfont-' . $user->getOption( 'editfont' );
4744 if ( isset( $attribs['class'] ) ) {
4745 if ( is_string( $attribs['class'] ) ) {
4746 $attribs['class'] .= ' ' . $class;
4747 } elseif ( is_array( $attribs['class'] ) ) {
4748 $attribs['class'][] = $class;
4751 $attribs['class'] = $class;
4754 $pageLang = $this->mTitle
->getPageLanguage();
4755 $attribs['lang'] = $pageLang->getHtmlCode();
4756 $attribs['dir'] = $pageLang->getDir();
4762 * @param string $wikitext
4766 protected function addNewLineAtEnd( $wikitext ) {
4767 if ( strval( $wikitext ) !== '' ) {
4768 // Ensure there's a newline at the end, otherwise adding lines
4770 // But don't add a newline if the text is empty, or Firefox in XHTML
4771 // mode will show an extra newline. A bit annoying.
4779 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4780 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4781 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4782 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4783 * spread the new style links more efficiently.
4785 * @param string $text
4788 private function guessSectionName( $text ) {
4791 // Detect Microsoft browsers
4792 $userAgent = $this->context
->getRequest()->getHeader( 'User-Agent' );
4793 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4794 // ...and redirect them to legacy encoding, if available
4795 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4797 // Meanwhile, real browsers get real anchors
4798 return $wgParser->guessSectionNameFromWikiText( $text );