Merge "EditPage: Make input and button widgets infusable"
[mediawiki.git] / includes / EditPage.php
blobf97f16469a1c818323e0a7fb06e197c3fc5c03e2
1 <?php
2 /**
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
20 * @file
23 use MediaWiki\Logger\LoggerFactory;
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\ScopedCallback;
27 /**
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
31 * interfaces.
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.
42 class EditPage {
43 /**
44 * Status: Article successfully updated
46 const AS_SUCCESS_UPDATE = 200;
48 /**
49 * Status: Article successfully created
51 const AS_SUCCESS_NEW_ARTICLE = 201;
53 /**
54 * Status: Article update aborted by a hook function
56 const AS_HOOK_ERROR = 210;
58 /**
59 * Status: A hook function returned an error
61 const AS_HOOK_ERROR_EXPECTED = 212;
63 /**
64 * Status: User is blocked from editing this page
66 const AS_BLOCKED_PAGE_FOR_USER = 215;
68 /**
69 * Status: Content too big (> $wgMaxArticleSize)
71 const AS_CONTENT_TOO_BIG = 216;
73 /**
74 * Status: this anonymous user is not allowed to edit this page
76 const AS_READ_ONLY_PAGE_ANON = 218;
78 /**
79 * Status: this logged in user is not allowed to edit this page
81 const AS_READ_ONLY_PAGE_LOGGED = 219;
83 /**
84 * Status: wiki is in readonly mode (wfReadOnly() == true)
86 const AS_READ_ONLY_PAGE = 220;
88 /**
89 * Status: rate limiter for action 'edit' was tripped
91 const AS_RATE_LIMITED = 221;
93 /**
94 * Status: article was deleted while editing and param wpRecreate == false or form
95 * was not posted
97 const AS_ARTICLE_WAS_DELETED = 222;
99 /**
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
134 const AS_END = 231;
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
165 * more details
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;
206 /** @var Article */
207 public $mArticle;
208 /** @var WikiPage */
209 private $page;
211 /** @var Title */
212 public $mTitle;
214 /** @var null|Title */
215 private $mContextTitle = null;
217 /** @var string */
218 public $action = 'submit';
220 /** @var bool */
221 public $isConflict = false;
223 /** @var bool */
224 public $isCssJsSubpage = false;
226 /** @var bool */
227 public $isCssSubpage = false;
229 /** @var bool */
230 public $isJsSubpage = false;
232 /** @var bool */
233 public $isWrongCaseCssJsPage = false;
235 /** @var bool New page or new section */
236 public $isNew = false;
238 /** @var bool */
239 public $deletedSinceEdit;
241 /** @var string */
242 public $formtype;
244 /** @var bool */
245 public $firsttime;
247 /** @var bool|stdClass */
248 public $lastDelete;
250 /** @var bool */
251 public $mTokenOk = false;
253 /** @var bool */
254 public $mTokenOkExceptSuffix = false;
256 /** @var bool */
257 public $mTriedSave = false;
259 /** @var bool */
260 public $incompleteForm = false;
262 /** @var bool */
263 public $tooBig = false;
265 /** @var bool */
266 public $missingComment = false;
268 /** @var bool */
269 public $missingSummary = false;
271 /** @var bool */
272 public $allowBlankSummary = false;
274 /** @var bool */
275 protected $blankArticle = false;
277 /** @var bool */
278 protected $allowBlankArticle = false;
280 /** @var bool */
281 protected $selfRedirect = false;
283 /** @var bool */
284 protected $allowSelfRedirect = false;
286 /** @var string */
287 public $autoSumm = '';
289 /** @var string */
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;
301 /** @var bool */
302 public $mShowSummaryField = true;
304 # Form values
306 /** @var bool */
307 public $save = false;
309 /** @var bool */
310 public $preview = false;
312 /** @var bool */
313 public $diff = false;
315 /** @var bool */
316 public $minoredit = false;
318 /** @var bool */
319 public $watchthis = false;
321 /** @var bool */
322 public $recreate = false;
324 /** @var string */
325 public $textbox1 = '';
327 /** @var string */
328 public $textbox2 = '';
330 /** @var string */
331 public $summary = '';
333 /** @var bool */
334 public $nosummary = false;
336 /** @var string */
337 public $edittime = '';
339 /** @var integer */
340 private $editRevId = null;
342 /** @var string */
343 public $section = '';
345 /** @var string */
346 public $sectiontitle = '';
348 /** @var string */
349 public $starttime = '';
351 /** @var int */
352 public $oldid = 0;
354 /** @var int */
355 public $parentRevId = 0;
357 /** @var string */
358 public $editintro = '';
360 /** @var null */
361 public $scrolltop = null;
363 /** @var bool */
364 public $bot = true;
366 /** @var string */
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;
395 /** @var bool */
396 protected $edit;
398 /** @var bool|int */
399 protected $contentLength = false;
402 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
404 private $enableApiEditOverride = false;
407 * @var IContextSource
409 protected $context;
412 * @var bool Whether an old revision is edited
414 private $isOldRev = false;
417 * @var bool Whether OOUI should be enabled here
419 private $oouiEnabled = false;
422 * @param Article $article
424 public function __construct( Article $article ) {
425 global $wgOOUIEditPage;
427 $this->mArticle = $article;
428 $this->page = $article->getPage(); // model object
429 $this->mTitle = $article->getTitle();
430 $this->context = $article->getContext();
432 $this->contentModel = $this->mTitle->getContentModel();
434 $handler = ContentHandler::getForModelID( $this->contentModel );
435 $this->contentFormat = $handler->getDefaultFormat();
437 $this->oouiEnabled = $wgOOUIEditPage;
441 * @return Article
443 public function getArticle() {
444 return $this->mArticle;
448 * @since 1.28
449 * @return IContextSource
451 public function getContext() {
452 return $this->context;
456 * @since 1.19
457 * @return Title
459 public function getTitle() {
460 return $this->mTitle;
464 * Set the context Title object
466 * @param Title|null $title Title object or null
468 public function setContextTitle( $title ) {
469 $this->mContextTitle = $title;
473 * Get the context title object.
474 * If not set, $wgTitle will be returned. This behavior might change in
475 * the future to return $this->mTitle instead.
477 * @return Title
479 public function getContextTitle() {
480 if ( is_null( $this->mContextTitle ) ) {
481 global $wgTitle;
482 return $wgTitle;
483 } else {
484 return $this->mContextTitle;
489 * Check if the edit page is using OOUI controls
490 * @return bool
492 public function isOouiEnabled() {
493 return $this->oouiEnabled;
497 * Returns if the given content model is editable.
499 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
500 * @return bool
501 * @throws MWException If $modelId has no known handler
503 public function isSupportedContentModel( $modelId ) {
504 return $this->enableApiEditOverride === true ||
505 ContentHandler::getForModelID( $modelId )->supportsDirectEditing();
509 * Allow editing of content that supports API direct editing, but not general
510 * direct editing. Set to false by default.
512 * @param bool $enableOverride
514 public function setApiEditOverride( $enableOverride ) {
515 $this->enableApiEditOverride = $enableOverride;
519 * @deprecated since 1.29, call edit directly
521 public function submit() {
522 $this->edit();
526 * This is the function that gets called for "action=edit". It
527 * sets up various member variables, then passes execution to
528 * another function, usually showEditForm()
530 * The edit form is self-submitting, so that when things like
531 * preview and edit conflicts occur, we get the same form back
532 * with the extra stuff added. Only when the final submission
533 * is made and all is well do we actually save and redirect to
534 * the newly-edited page.
536 public function edit() {
537 global $wgOut, $wgRequest, $wgUser;
538 // Allow extensions to modify/prevent this form or submission
539 if ( !Hooks::run( 'AlternateEdit', [ $this ] ) ) {
540 return;
543 wfDebug( __METHOD__ . ": enter\n" );
545 // If they used redlink=1 and the page exists, redirect to the main article
546 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
547 $wgOut->redirect( $this->mTitle->getFullURL() );
548 return;
551 $this->importFormData( $wgRequest );
552 $this->firsttime = false;
554 if ( wfReadOnly() && $this->save ) {
555 // Force preview
556 $this->save = false;
557 $this->preview = true;
560 if ( $this->save ) {
561 $this->formtype = 'save';
562 } elseif ( $this->preview ) {
563 $this->formtype = 'preview';
564 } elseif ( $this->diff ) {
565 $this->formtype = 'diff';
566 } else { # First time through
567 $this->firsttime = true;
568 if ( $this->previewOnOpen() ) {
569 $this->formtype = 'preview';
570 } else {
571 $this->formtype = 'initial';
575 $permErrors = $this->getEditPermissionErrors( $this->save ? 'secure' : 'full' );
576 if ( $permErrors ) {
577 wfDebug( __METHOD__ . ": User can't edit\n" );
578 // Auto-block user's IP if the account was "hard" blocked
579 if ( !wfReadOnly() ) {
580 $user = $wgUser;
581 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
582 $user->spreadAnyEditBlock();
583 } );
585 $this->displayPermissionsError( $permErrors );
587 return;
590 $revision = $this->mArticle->getRevisionFetched();
591 // Disallow editing revisions with content models different from the current one
592 // Undo edits being an exception in order to allow reverting content model changes.
593 if ( $revision
594 && $revision->getContentModel() !== $this->contentModel
596 $prevRev = null;
597 if ( $this->undidRev ) {
598 $undidRevObj = Revision::newFromId( $this->undidRev );
599 $prevRev = $undidRevObj ? $undidRevObj->getPrevious() : null;
601 if ( !$this->undidRev
602 || !$prevRev
603 || $prevRev->getContentModel() !== $this->contentModel
605 $this->displayViewSourcePage(
606 $this->getContentObject(),
607 $this->context->msg(
608 'contentmodelediterror',
609 $revision->getContentModel(),
610 $this->contentModel
611 )->plain()
613 return;
617 $this->isConflict = false;
618 // css / js subpages of user pages get a special treatment
619 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
620 $this->isCssSubpage = $this->mTitle->isCssSubpage();
621 $this->isJsSubpage = $this->mTitle->isJsSubpage();
622 // @todo FIXME: Silly assignment.
623 $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
625 # Show applicable editing introductions
626 if ( $this->formtype == 'initial' || $this->firsttime ) {
627 $this->showIntro();
630 # Attempt submission here. This will check for edit conflicts,
631 # and redundantly check for locked database, blocked IPs, etc.
632 # that edit() already checked just in case someone tries to sneak
633 # in the back door with a hand-edited submission URL.
635 if ( 'save' == $this->formtype ) {
636 $resultDetails = null;
637 $status = $this->attemptSave( $resultDetails );
638 if ( !$this->handleStatus( $status, $resultDetails ) ) {
639 return;
643 # First time through: get contents, set time for conflict
644 # checking, etc.
645 if ( 'initial' == $this->formtype || $this->firsttime ) {
646 if ( $this->initialiseForm() === false ) {
647 $this->noSuchSectionPage();
648 return;
651 if ( !$this->mTitle->getArticleID() ) {
652 Hooks::run( 'EditFormPreloadText', [ &$this->textbox1, &$this->mTitle ] );
653 } else {
654 Hooks::run( 'EditFormInitialText', [ $this ] );
659 $this->showEditForm();
663 * @param string $rigor Same format as Title::getUserPermissionErrors()
664 * @return array
666 protected function getEditPermissionErrors( $rigor = 'secure' ) {
667 global $wgUser;
669 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
670 # Can this title be created?
671 if ( !$this->mTitle->exists() ) {
672 $permErrors = array_merge(
673 $permErrors,
674 wfArrayDiff2(
675 $this->mTitle->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
676 $permErrors
680 # Ignore some permissions errors when a user is just previewing/viewing diffs
681 $remove = [];
682 foreach ( $permErrors as $error ) {
683 if ( ( $this->preview || $this->diff )
684 && (
685 $error[0] == 'blockedtext' ||
686 $error[0] == 'autoblockedtext' ||
687 $error[0] == 'systemblockedtext'
690 $remove[] = $error;
693 $permErrors = wfArrayDiff2( $permErrors, $remove );
695 return $permErrors;
699 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
700 * but with the following differences:
701 * - If redlink=1, the user will be redirected to the page
702 * - If there is content to display or the error occurs while either saving,
703 * previewing or showing the difference, it will be a
704 * "View source for ..." page displaying the source code after the error message.
706 * @since 1.19
707 * @param array $permErrors Array of permissions errors, as returned by
708 * Title::getUserPermissionsErrors().
709 * @throws PermissionsError
711 protected function displayPermissionsError( array $permErrors ) {
712 global $wgRequest, $wgOut;
714 if ( $wgRequest->getBool( 'redlink' ) ) {
715 // The edit page was reached via a red link.
716 // Redirect to the article page and let them click the edit tab if
717 // they really want a permission error.
718 $wgOut->redirect( $this->mTitle->getFullURL() );
719 return;
722 $content = $this->getContentObject();
724 # Use the normal message if there's nothing to display
725 if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
726 $action = $this->mTitle->exists() ? 'edit' :
727 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
728 throw new PermissionsError( $action, $permErrors );
731 $this->displayViewSourcePage(
732 $content,
733 $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' )
738 * Display a read-only View Source page
739 * @param Content $content content object
740 * @param string $errorMessage additional wikitext error message to display
742 protected function displayViewSourcePage( Content $content, $errorMessage = '' ) {
743 global $wgOut;
745 Hooks::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$wgOut ] );
747 $wgOut->setRobotPolicy( 'noindex,nofollow' );
748 $wgOut->setPageTitle( $this->context->msg(
749 'viewsource-title',
750 $this->getContextTitle()->getPrefixedText()
751 ) );
752 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
753 $wgOut->addHTML( $this->editFormPageTop );
754 $wgOut->addHTML( $this->editFormTextTop );
756 if ( $errorMessage !== '' ) {
757 $wgOut->addWikiText( $errorMessage );
758 $wgOut->addHTML( "<hr />\n" );
761 # If the user made changes, preserve them when showing the markup
762 # (This happens when a user is blocked during edit, for instance)
763 if ( !$this->firsttime ) {
764 $text = $this->textbox1;
765 $wgOut->addWikiMsg( 'viewyourtext' );
766 } else {
767 try {
768 $text = $this->toEditText( $content );
769 } catch ( MWException $e ) {
770 # Serialize using the default format if the content model is not supported
771 # (e.g. for an old revision with a different model)
772 $text = $content->serialize();
774 $wgOut->addWikiMsg( 'viewsourcetext' );
777 $wgOut->addHTML( $this->editFormTextBeforeContent );
778 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
779 $wgOut->addHTML( $this->editFormTextAfterContent );
781 $wgOut->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
783 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
785 $wgOut->addHTML( $this->editFormTextBottom );
786 if ( $this->mTitle->exists() ) {
787 $wgOut->returnToMain( null, $this->mTitle );
792 * Should we show a preview when the edit form is first shown?
794 * @return bool
796 protected function previewOnOpen() {
797 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
798 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
799 // Explicit override from request
800 return true;
801 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
802 // Explicit override from request
803 return false;
804 } elseif ( $this->section == 'new' ) {
805 // Nothing *to* preview for new sections
806 return false;
807 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() )
808 && $wgUser->getOption( 'previewonfirst' )
810 // Standard preference behavior
811 return true;
812 } elseif ( !$this->mTitle->exists()
813 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
814 && $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]
816 // Categories are special
817 return true;
818 } else {
819 return false;
824 * Checks whether the user entered a skin name in uppercase,
825 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
827 * @return bool
829 protected function isWrongCaseCssJsPage() {
830 if ( $this->mTitle->isCssJsSubpage() ) {
831 $name = $this->mTitle->getSkinFromCssJsSubpage();
832 $skins = array_merge(
833 array_keys( Skin::getSkinNames() ),
834 [ 'common' ]
836 return !in_array( $name, $skins )
837 && in_array( strtolower( $name ), $skins );
838 } else {
839 return false;
844 * Returns whether section editing is supported for the current page.
845 * Subclasses may override this to replace the default behavior, which is
846 * to check ContentHandler::supportsSections.
848 * @return bool True if this edit page supports sections, false otherwise.
850 protected function isSectionEditSupported() {
851 $contentHandler = ContentHandler::getForTitle( $this->mTitle );
852 return $contentHandler->supportsSections();
856 * This function collects the form data and uses it to populate various member variables.
857 * @param WebRequest $request
858 * @throws ErrorPageError
860 public function importFormData( &$request ) {
861 global $wgContLang, $wgUser;
863 # Allow users to change the mode for testing
864 $this->oouiEnabled = $request->getFuzzyBool( 'ooui', $this->oouiEnabled );
866 # Section edit can come from either the form or a link
867 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
869 if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
870 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
873 $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
875 if ( $request->wasPosted() ) {
876 # These fields need to be checked for encoding.
877 # Also remove trailing whitespace, but don't remove _initial_
878 # whitespace from the text boxes. This may be significant formatting.
879 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
880 if ( !$request->getCheck( 'wpTextbox2' ) ) {
881 // Skip this if wpTextbox2 has input, it indicates that we came
882 // from a conflict page with raw page text, not a custom form
883 // modified by subclasses
884 $textbox1 = $this->importContentFormData( $request );
885 if ( $textbox1 !== null ) {
886 $this->textbox1 = $textbox1;
890 # Truncate for whole multibyte characters
891 $this->summary = $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
893 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
894 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
895 # section titles.
896 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
898 # Treat sectiontitle the same way as summary.
899 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
900 # currently doing double duty as both edit summary and section title. Right now this
901 # is just to allow API edits to work around this limitation, but this should be
902 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
903 $this->sectiontitle = $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
904 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
906 $this->edittime = $request->getVal( 'wpEdittime' );
907 $this->editRevId = $request->getIntOrNull( 'editRevId' );
908 $this->starttime = $request->getVal( 'wpStarttime' );
910 $undidRev = $request->getInt( 'wpUndidRevision' );
911 if ( $undidRev ) {
912 $this->undidRev = $undidRev;
915 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
917 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
918 // wpTextbox1 field is missing, possibly due to being "too big"
919 // according to some filter rules such as Suhosin's setting for
920 // suhosin.request.max_value_length (d'oh)
921 $this->incompleteForm = true;
922 } else {
923 // If we receive the last parameter of the request, we can fairly
924 // claim the POST request has not been truncated.
926 // TODO: softened the check for cutover. Once we determine
927 // that it is safe, we should complete the transition by
928 // removing the "edittime" clause.
929 $this->incompleteForm = ( !$request->getVal( 'wpUltimateParam' )
930 && is_null( $this->edittime ) );
932 if ( $this->incompleteForm ) {
933 # If the form is incomplete, force to preview.
934 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
935 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
936 $this->preview = true;
937 } else {
938 $this->preview = $request->getCheck( 'wpPreview' );
939 $this->diff = $request->getCheck( 'wpDiff' );
941 // Remember whether a save was requested, so we can indicate
942 // if we forced preview due to session failure.
943 $this->mTriedSave = !$this->preview;
945 if ( $this->tokenOk( $request ) ) {
946 # Some browsers will not report any submit button
947 # if the user hits enter in the comment box.
948 # The unmarked state will be assumed to be a save,
949 # if the form seems otherwise complete.
950 wfDebug( __METHOD__ . ": Passed token check.\n" );
951 } elseif ( $this->diff ) {
952 # Failed token check, but only requested "Show Changes".
953 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
954 } else {
955 # Page might be a hack attempt posted from
956 # an external site. Preview instead of saving.
957 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
958 $this->preview = true;
961 $this->save = !$this->preview && !$this->diff;
962 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
963 $this->edittime = null;
966 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
967 $this->starttime = null;
970 $this->recreate = $request->getCheck( 'wpRecreate' );
972 $this->minoredit = $request->getCheck( 'wpMinoredit' );
973 $this->watchthis = $request->getCheck( 'wpWatchthis' );
975 # Don't force edit summaries when a user is editing their own user or talk page
976 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
977 && $this->mTitle->getText() == $wgUser->getName()
979 $this->allowBlankSummary = true;
980 } else {
981 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
982 || !$wgUser->getOption( 'forceeditsummary' );
985 $this->autoSumm = $request->getText( 'wpAutoSummary' );
987 $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
988 $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
990 $changeTags = $request->getVal( 'wpChangeTags' );
991 if ( is_null( $changeTags ) || $changeTags === '' ) {
992 $this->changeTags = [];
993 } else {
994 $this->changeTags = array_filter( array_map( 'trim', explode( ',',
995 $changeTags ) ) );
997 } else {
998 # Not a posted form? Start with nothing.
999 wfDebug( __METHOD__ . ": Not a posted form.\n" );
1000 $this->textbox1 = '';
1001 $this->summary = '';
1002 $this->sectiontitle = '';
1003 $this->edittime = '';
1004 $this->editRevId = null;
1005 $this->starttime = wfTimestampNow();
1006 $this->edit = false;
1007 $this->preview = false;
1008 $this->save = false;
1009 $this->diff = false;
1010 $this->minoredit = false;
1011 // Watch may be overridden by request parameters
1012 $this->watchthis = $request->getBool( 'watchthis', false );
1013 $this->recreate = false;
1015 // When creating a new section, we can preload a section title by passing it as the
1016 // preloadtitle parameter in the URL (T15100)
1017 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
1018 $this->sectiontitle = $request->getVal( 'preloadtitle' );
1019 // Once wpSummary isn't being use for setting section titles, we should delete this.
1020 $this->summary = $request->getVal( 'preloadtitle' );
1021 } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
1022 $this->summary = $request->getText( 'summary' );
1023 if ( $this->summary !== '' ) {
1024 $this->hasPresetSummary = true;
1028 if ( $request->getVal( 'minor' ) ) {
1029 $this->minoredit = true;
1033 $this->oldid = $request->getInt( 'oldid' );
1034 $this->parentRevId = $request->getInt( 'parentRevId' );
1036 $this->bot = $request->getBool( 'bot', true );
1037 $this->nosummary = $request->getBool( 'nosummary' );
1039 // May be overridden by revision.
1040 $this->contentModel = $request->getText( 'model', $this->contentModel );
1041 // May be overridden by revision.
1042 $this->contentFormat = $request->getText( 'format', $this->contentFormat );
1044 try {
1045 $handler = ContentHandler::getForModelID( $this->contentModel );
1046 } catch ( MWUnknownContentModelException $e ) {
1047 throw new ErrorPageError(
1048 'editpage-invalidcontentmodel-title',
1049 'editpage-invalidcontentmodel-text',
1050 [ wfEscapeWikiText( $this->contentModel ) ]
1054 if ( !$handler->isSupportedFormat( $this->contentFormat ) ) {
1055 throw new ErrorPageError(
1056 'editpage-notsupportedcontentformat-title',
1057 'editpage-notsupportedcontentformat-text',
1059 wfEscapeWikiText( $this->contentFormat ),
1060 wfEscapeWikiText( ContentHandler::getLocalizedName( $this->contentModel ) )
1066 * @todo Check if the desired model is allowed in this namespace, and if
1067 * a transition from the page's current model to the new model is
1068 * allowed.
1071 $this->editintro = $request->getText( 'editintro',
1072 // Custom edit intro for new sections
1073 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
1075 // Allow extensions to modify form data
1076 Hooks::run( 'EditPage::importFormData', [ $this, $request ] );
1080 * Subpage overridable method for extracting the page content data from the
1081 * posted form to be placed in $this->textbox1, if using customized input
1082 * this method should be overridden and return the page text that will be used
1083 * for saving, preview parsing and so on...
1085 * @param WebRequest $request
1086 * @return string|null
1088 protected function importContentFormData( &$request ) {
1089 return; // Don't do anything, EditPage already extracted wpTextbox1
1093 * Initialise form fields in the object
1094 * Called on the first invocation, e.g. when a user clicks an edit link
1095 * @return bool If the requested section is valid
1097 public function initialiseForm() {
1098 global $wgUser;
1099 $this->edittime = $this->page->getTimestamp();
1100 $this->editRevId = $this->page->getLatest();
1102 $content = $this->getContentObject( false ); # TODO: track content object?!
1103 if ( $content === false ) {
1104 return false;
1106 $this->textbox1 = $this->toEditText( $content );
1108 // activate checkboxes if user wants them to be always active
1109 # Sort out the "watch" checkbox
1110 if ( $wgUser->getOption( 'watchdefault' ) ) {
1111 # Watch all edits
1112 $this->watchthis = true;
1113 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1114 # Watch creations
1115 $this->watchthis = true;
1116 } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
1117 # Already watched
1118 $this->watchthis = true;
1120 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
1121 $this->minoredit = true;
1123 if ( $this->textbox1 === false ) {
1124 return false;
1126 return true;
1130 * @param Content|null $def_content The default value to return
1132 * @return Content|null Content on success, $def_content for invalid sections
1134 * @since 1.21
1136 protected function getContentObject( $def_content = null ) {
1137 global $wgOut, $wgRequest, $wgUser, $wgContLang;
1139 $content = false;
1141 // For message page not locally set, use the i18n message.
1142 // For other non-existent articles, use preload text if any.
1143 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
1144 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
1145 # If this is a system message, get the default text.
1146 $msg = $this->mTitle->getDefaultMessageText();
1148 $content = $this->toEditContent( $msg );
1150 if ( $content === false ) {
1151 # If requested, preload some text.
1152 $preload = $wgRequest->getVal( 'preload',
1153 // Custom preload text for new sections
1154 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
1155 $params = $wgRequest->getArray( 'preloadparams', [] );
1157 $content = $this->getPreloadedContent( $preload, $params );
1159 // For existing pages, get text based on "undo" or section parameters.
1160 } else {
1161 if ( $this->section != '' ) {
1162 // Get section edit text (returns $def_text for invalid sections)
1163 $orig = $this->getOriginalContent( $wgUser );
1164 $content = $orig ? $orig->getSection( $this->section ) : null;
1166 if ( !$content ) {
1167 $content = $def_content;
1169 } else {
1170 $undoafter = $wgRequest->getInt( 'undoafter' );
1171 $undo = $wgRequest->getInt( 'undo' );
1173 if ( $undo > 0 && $undoafter > 0 ) {
1174 $undorev = Revision::newFromId( $undo );
1175 $oldrev = Revision::newFromId( $undoafter );
1177 # Sanity check, make sure it's the right page,
1178 # the revisions exist and they were not deleted.
1179 # Otherwise, $content will be left as-is.
1180 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1181 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
1182 !$oldrev->isDeleted( Revision::DELETED_TEXT )
1184 $content = $this->page->getUndoContent( $undorev, $oldrev );
1186 if ( $content === false ) {
1187 # Warn the user that something went wrong
1188 $undoMsg = 'failure';
1189 } else {
1190 $oldContent = $this->page->getContent( Revision::RAW );
1191 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
1192 $newContent = $content->preSaveTransform( $this->mTitle, $wgUser, $popts );
1193 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1194 // The undo may change content
1195 // model if its reverting the top
1196 // edit. This can result in
1197 // mismatched content model/format.
1198 $this->contentModel = $newContent->getModel();
1199 $this->contentFormat = $oldrev->getContentFormat();
1202 if ( $newContent->equals( $oldContent ) ) {
1203 # Tell the user that the undo results in no change,
1204 # i.e. the revisions were already undone.
1205 $undoMsg = 'nochange';
1206 $content = false;
1207 } else {
1208 # Inform the user of our success and set an automatic edit summary
1209 $undoMsg = 'success';
1211 # If we just undid one rev, use an autosummary
1212 $firstrev = $oldrev->getNext();
1213 if ( $firstrev && $firstrev->getId() == $undo ) {
1214 $userText = $undorev->getUserText();
1215 if ( $userText === '' ) {
1216 $undoSummary = $this->context->msg(
1217 'undo-summary-username-hidden',
1218 $undo
1219 )->inContentLanguage()->text();
1220 } else {
1221 $undoSummary = $this->context->msg(
1222 'undo-summary',
1223 $undo,
1224 $userText
1225 )->inContentLanguage()->text();
1227 if ( $this->summary === '' ) {
1228 $this->summary = $undoSummary;
1229 } else {
1230 $this->summary = $undoSummary . $this->context->msg( 'colon-separator' )
1231 ->inContentLanguage()->text() . $this->summary;
1233 $this->undidRev = $undo;
1235 $this->formtype = 'diff';
1238 } else {
1239 // Failed basic sanity checks.
1240 // Older revisions may have been removed since the link
1241 // was created, or we may simply have got bogus input.
1242 $undoMsg = 'norev';
1245 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1246 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1247 $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
1248 $this->context->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1251 if ( $content === false ) {
1252 $content = $this->getOriginalContent( $wgUser );
1257 return $content;
1261 * Get the content of the wanted revision, without section extraction.
1263 * The result of this function can be used to compare user's input with
1264 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1265 * to the original text of the edit.
1267 * This differs from Article::getContent() that when a missing revision is
1268 * encountered the result will be null and not the
1269 * 'missing-revision' message.
1271 * @since 1.19
1272 * @param User $user The user to get the revision for
1273 * @return Content|null
1275 private function getOriginalContent( User $user ) {
1276 if ( $this->section == 'new' ) {
1277 return $this->getCurrentContent();
1279 $revision = $this->mArticle->getRevisionFetched();
1280 if ( $revision === null ) {
1281 $handler = ContentHandler::getForModelID( $this->contentModel );
1282 return $handler->makeEmptyContent();
1284 $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
1285 return $content;
1289 * Get the edit's parent revision ID
1291 * The "parent" revision is the ancestor that should be recorded in this
1292 * page's revision history. It is either the revision ID of the in-memory
1293 * article content, or in the case of a 3-way merge in order to rebase
1294 * across a recoverable edit conflict, the ID of the newer revision to
1295 * which we have rebased this page.
1297 * @since 1.27
1298 * @return int Revision ID
1300 public function getParentRevId() {
1301 if ( $this->parentRevId ) {
1302 return $this->parentRevId;
1303 } else {
1304 return $this->mArticle->getRevIdFetched();
1309 * Get the current content of the page. This is basically similar to
1310 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1311 * content object is returned instead of null.
1313 * @since 1.21
1314 * @return Content
1316 protected function getCurrentContent() {
1317 $rev = $this->page->getRevision();
1318 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1320 if ( $content === false || $content === null ) {
1321 $handler = ContentHandler::getForModelID( $this->contentModel );
1322 return $handler->makeEmptyContent();
1323 } elseif ( !$this->undidRev ) {
1324 // Content models should always be the same since we error
1325 // out if they are different before this point (in ->edit()).
1326 // The exception being, during an undo, the current revision might
1327 // differ from the prior revision.
1328 $logger = LoggerFactory::getInstance( 'editpage' );
1329 if ( $this->contentModel !== $rev->getContentModel() ) {
1330 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1331 'prev' => $this->contentModel,
1332 'new' => $rev->getContentModel(),
1333 'title' => $this->getTitle()->getPrefixedDBkey(),
1334 'method' => __METHOD__
1335 ] );
1336 $this->contentModel = $rev->getContentModel();
1339 // Given that the content models should match, the current selected
1340 // format should be supported.
1341 if ( !$content->isSupportedFormat( $this->contentFormat ) ) {
1342 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1344 'prev' => $this->contentFormat,
1345 'new' => $rev->getContentFormat(),
1346 'title' => $this->getTitle()->getPrefixedDBkey(),
1347 'method' => __METHOD__
1348 ] );
1349 $this->contentFormat = $rev->getContentFormat();
1352 return $content;
1356 * Use this method before edit() to preload some content into the edit box
1358 * @param Content $content
1360 * @since 1.21
1362 public function setPreloadedContent( Content $content ) {
1363 $this->mPreloadContent = $content;
1367 * Get the contents to be preloaded into the box, either set by
1368 * an earlier setPreloadText() or by loading the given page.
1370 * @param string $preload Representing the title to preload from.
1371 * @param array $params Parameters to use (interface-message style) in the preloaded text
1373 * @return Content
1375 * @since 1.21
1377 protected function getPreloadedContent( $preload, $params = [] ) {
1378 global $wgUser;
1380 if ( !empty( $this->mPreloadContent ) ) {
1381 return $this->mPreloadContent;
1384 $handler = ContentHandler::getForModelID( $this->contentModel );
1386 if ( $preload === '' ) {
1387 return $handler->makeEmptyContent();
1390 $title = Title::newFromText( $preload );
1391 # Check for existence to avoid getting MediaWiki:Noarticletext
1392 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1393 // TODO: somehow show a warning to the user!
1394 return $handler->makeEmptyContent();
1397 $page = WikiPage::factory( $title );
1398 if ( $page->isRedirect() ) {
1399 $title = $page->getRedirectTarget();
1400 # Same as before
1401 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1402 // TODO: somehow show a warning to the user!
1403 return $handler->makeEmptyContent();
1405 $page = WikiPage::factory( $title );
1408 $parserOptions = ParserOptions::newFromUser( $wgUser );
1409 $content = $page->getContent( Revision::RAW );
1411 if ( !$content ) {
1412 // TODO: somehow show a warning to the user!
1413 return $handler->makeEmptyContent();
1416 if ( $content->getModel() !== $handler->getModelID() ) {
1417 $converted = $content->convert( $handler->getModelID() );
1419 if ( !$converted ) {
1420 // TODO: somehow show a warning to the user!
1421 wfDebug( "Attempt to preload incompatible content: " .
1422 "can't convert " . $content->getModel() .
1423 " to " . $handler->getModelID() );
1425 return $handler->makeEmptyContent();
1428 $content = $converted;
1431 return $content->preloadTransform( $title, $parserOptions, $params );
1435 * Make sure the form isn't faking a user's credentials.
1437 * @param WebRequest $request
1438 * @return bool
1439 * @private
1441 public function tokenOk( &$request ) {
1442 global $wgUser;
1443 $token = $request->getVal( 'wpEditToken' );
1444 $this->mTokenOk = $wgUser->matchEditToken( $token );
1445 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1446 return $this->mTokenOk;
1450 * Sets post-edit cookie indicating the user just saved a particular revision.
1452 * This uses a temporary cookie for each revision ID so separate saves will never
1453 * interfere with each other.
1455 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1456 * the redirect. It must be clearable by JavaScript code, so it must not be
1457 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1458 * variable.
1460 * If the variable were set on the server, it would be cached, which is unwanted
1461 * since the post-edit state should only apply to the load right after the save.
1463 * @param int $statusValue The status value (to check for new article status)
1465 protected function setPostEditCookie( $statusValue ) {
1466 $revisionId = $this->page->getLatest();
1467 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1469 $val = 'saved';
1470 if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1471 $val = 'created';
1472 } elseif ( $this->oldid ) {
1473 $val = 'restored';
1476 $response = RequestContext::getMain()->getRequest()->response();
1477 $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION, [
1478 'httpOnly' => false,
1479 ] );
1483 * Attempt submission
1484 * @param array|bool $resultDetails See docs for $result in internalAttemptSave
1485 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1486 * @return Status The resulting status object.
1488 public function attemptSave( &$resultDetails = false ) {
1489 global $wgUser;
1491 # Allow bots to exempt some edits from bot flagging
1492 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1493 $status = $this->internalAttemptSave( $resultDetails, $bot );
1495 Hooks::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1497 return $status;
1501 * Handle status, such as after attempt save
1503 * @param Status $status
1504 * @param array|bool $resultDetails
1506 * @throws ErrorPageError
1507 * @return bool False, if output is done, true if rest of the form should be displayed
1509 private function handleStatus( Status $status, $resultDetails ) {
1510 global $wgUser, $wgOut;
1513 * @todo FIXME: once the interface for internalAttemptSave() is made
1514 * nicer, this should use the message in $status
1516 if ( $status->value == self::AS_SUCCESS_UPDATE
1517 || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1519 $this->didSave = true;
1520 if ( !$resultDetails['nullEdit'] ) {
1521 $this->setPostEditCookie( $status->value );
1525 // "wpExtraQueryRedirect" is a hidden input to modify
1526 // after save URL and is not used by actual edit form
1527 $request = RequestContext::getMain()->getRequest();
1528 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1530 switch ( $status->value ) {
1531 case self::AS_HOOK_ERROR_EXPECTED:
1532 case self::AS_CONTENT_TOO_BIG:
1533 case self::AS_ARTICLE_WAS_DELETED:
1534 case self::AS_CONFLICT_DETECTED:
1535 case self::AS_SUMMARY_NEEDED:
1536 case self::AS_TEXTBOX_EMPTY:
1537 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1538 case self::AS_END:
1539 case self::AS_BLANK_ARTICLE:
1540 case self::AS_SELF_REDIRECT:
1541 return true;
1543 case self::AS_HOOK_ERROR:
1544 return false;
1546 case self::AS_CANNOT_USE_CUSTOM_MODEL:
1547 case self::AS_PARSE_ERROR:
1548 $wgOut->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1549 return true;
1551 case self::AS_SUCCESS_NEW_ARTICLE:
1552 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1553 if ( $extraQueryRedirect ) {
1554 if ( $query === '' ) {
1555 $query = $extraQueryRedirect;
1556 } else {
1557 $query = $query . '&' . $extraQueryRedirect;
1560 $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1561 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1562 return false;
1564 case self::AS_SUCCESS_UPDATE:
1565 $extraQuery = '';
1566 $sectionanchor = $resultDetails['sectionanchor'];
1568 // Give extensions a chance to modify URL query on update
1569 Hooks::run(
1570 'ArticleUpdateBeforeRedirect',
1571 [ $this->mArticle, &$sectionanchor, &$extraQuery ]
1574 if ( $resultDetails['redirect'] ) {
1575 if ( $extraQuery == '' ) {
1576 $extraQuery = 'redirect=no';
1577 } else {
1578 $extraQuery = 'redirect=no&' . $extraQuery;
1581 if ( $extraQueryRedirect ) {
1582 if ( $extraQuery === '' ) {
1583 $extraQuery = $extraQueryRedirect;
1584 } else {
1585 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1589 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1590 return false;
1592 case self::AS_SPAM_ERROR:
1593 $this->spamPageWithContent( $resultDetails['spam'] );
1594 return false;
1596 case self::AS_BLOCKED_PAGE_FOR_USER:
1597 throw new UserBlockedError( $wgUser->getBlock() );
1599 case self::AS_IMAGE_REDIRECT_ANON:
1600 case self::AS_IMAGE_REDIRECT_LOGGED:
1601 throw new PermissionsError( 'upload' );
1603 case self::AS_READ_ONLY_PAGE_ANON:
1604 case self::AS_READ_ONLY_PAGE_LOGGED:
1605 throw new PermissionsError( 'edit' );
1607 case self::AS_READ_ONLY_PAGE:
1608 throw new ReadOnlyError;
1610 case self::AS_RATE_LIMITED:
1611 throw new ThrottledError();
1613 case self::AS_NO_CREATE_PERMISSION:
1614 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1615 throw new PermissionsError( $permission );
1617 case self::AS_NO_CHANGE_CONTENT_MODEL:
1618 throw new PermissionsError( 'editcontentmodel' );
1620 default:
1621 // We don't recognize $status->value. The only way that can happen
1622 // is if an extension hook aborted from inside ArticleSave.
1623 // Render the status object into $this->hookError
1624 // FIXME this sucks, we should just use the Status object throughout
1625 $this->hookError = '<div class="error">' ."\n" . $status->getWikiText() .
1626 '</div>';
1627 return true;
1632 * Run hooks that can filter edits just before they get saved.
1634 * @param Content $content The Content to filter.
1635 * @param Status $status For reporting the outcome to the caller
1636 * @param User $user The user performing the edit
1638 * @return bool
1640 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1641 // Run old style post-section-merge edit filter
1642 if ( $this->hookError != '' ) {
1643 # ...or the hook could be expecting us to produce an error
1644 $status->fatal( 'hookaborted' );
1645 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1646 return false;
1649 // Run new style post-section-merge edit filter
1650 if ( !Hooks::run( 'EditFilterMergedContent',
1651 [ $this->mArticle->getContext(), $content, $status, $this->summary,
1652 $user, $this->minoredit ] )
1654 # Error messages etc. could be handled within the hook...
1655 if ( $status->isGood() ) {
1656 $status->fatal( 'hookaborted' );
1657 // Not setting $this->hookError here is a hack to allow the hook
1658 // to cause a return to the edit page without $this->hookError
1659 // being set. This is used by ConfirmEdit to display a captcha
1660 // without any error message cruft.
1661 } else {
1662 $this->hookError = $status->getWikiText();
1664 // Use the existing $status->value if the hook set it
1665 if ( !$status->value ) {
1666 $status->value = self::AS_HOOK_ERROR;
1668 return false;
1669 } elseif ( !$status->isOK() ) {
1670 # ...or the hook could be expecting us to produce an error
1671 // FIXME this sucks, we should just use the Status object throughout
1672 $this->hookError = $status->getWikiText();
1673 $status->fatal( 'hookaborted' );
1674 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1675 return false;
1678 return true;
1682 * Return the summary to be used for a new section.
1684 * @param string $sectionanchor Set to the section anchor text
1685 * @return string
1687 private function newSectionSummary( &$sectionanchor = null ) {
1688 global $wgParser;
1690 if ( $this->sectiontitle !== '' ) {
1691 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1692 // If no edit summary was specified, create one automatically from the section
1693 // title and have it link to the new section. Otherwise, respect the summary as
1694 // passed.
1695 if ( $this->summary === '' ) {
1696 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1697 return $this->context->msg( 'newsectionsummary' )
1698 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1700 } elseif ( $this->summary !== '' ) {
1701 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1702 # This is a new section, so create a link to the new section
1703 # in the revision summary.
1704 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1705 return $this->context->msg( 'newsectionsummary' )
1706 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1708 return $this->summary;
1712 * Attempt submission (no UI)
1714 * @param array $result Array to add statuses to, currently with the
1715 * possible keys:
1716 * - spam (string): Spam string from content if any spam is detected by
1717 * matchSpamRegex.
1718 * - sectionanchor (string): Section anchor for a section save.
1719 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1720 * false otherwise.
1721 * - redirect (bool): Set if doEditContent is OK. True if resulting
1722 * revision is a redirect.
1723 * @param bool $bot True if edit is being made under the bot right.
1725 * @return Status Status object, possibly with a message, but always with
1726 * one of the AS_* constants in $status->value,
1728 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1729 * various error display idiosyncrasies. There are also lots of cases
1730 * where error metadata is set in the object and retrieved later instead
1731 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1732 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1733 * time.
1735 public function internalAttemptSave( &$result, $bot = false ) {
1736 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1737 global $wgContentHandlerUseDB;
1739 $status = Status::newGood();
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;
1745 return $status;
1748 $spam = $wgRequest->getText( 'wpAntispam' );
1749 if ( $spam !== '' ) {
1750 wfDebugLog(
1751 'SimpleAntiSpam',
1752 $wgUser->getName() .
1753 ' editing "' .
1754 $this->mTitle->getPrefixedText() .
1755 '" submitted bogus field "' .
1756 $spam .
1759 $status->fatal( 'spamprotectionmatch', false );
1760 $status->value = self::AS_SPAM_ERROR;
1761 return $status;
1764 try {
1765 # Construct Content object
1766 $textbox_content = $this->toEditContent( $this->textbox1 );
1767 } catch ( MWContentSerializationException $ex ) {
1768 $status->fatal(
1769 'content-failed-to-parse',
1770 $this->contentModel,
1771 $this->contentFormat,
1772 $ex->getMessage()
1774 $status->value = self::AS_PARSE_ERROR;
1775 return $status;
1778 # Check image redirect
1779 if ( $this->mTitle->getNamespace() == NS_FILE &&
1780 $textbox_content->isRedirect() &&
1781 !$wgUser->isAllowed( 'upload' )
1783 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1784 $status->setResult( false, $code );
1786 return $status;
1789 # Check for spam
1790 $match = self::matchSummarySpamRegex( $this->summary );
1791 if ( $match === false && $this->section == 'new' ) {
1792 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1793 # regular summaries, it is added to the actual wikitext.
1794 if ( $this->sectiontitle !== '' ) {
1795 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1796 $match = self::matchSpamRegex( $this->sectiontitle );
1797 } else {
1798 # This branch is taken when the "Add Topic" user interface is used, or the API
1799 # is used with the 'summary' parameter.
1800 $match = self::matchSpamRegex( $this->summary );
1803 if ( $match === false ) {
1804 $match = self::matchSpamRegex( $this->textbox1 );
1806 if ( $match !== false ) {
1807 $result['spam'] = $match;
1808 $ip = $wgRequest->getIP();
1809 $pdbk = $this->mTitle->getPrefixedDBkey();
1810 $match = str_replace( "\n", '', $match );
1811 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1812 $status->fatal( 'spamprotectionmatch', $match );
1813 $status->value = self::AS_SPAM_ERROR;
1814 return $status;
1816 if ( !Hooks::run(
1817 'EditFilter',
1818 [ $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ] )
1820 # Error messages etc. could be handled within the hook...
1821 $status->fatal( 'hookaborted' );
1822 $status->value = self::AS_HOOK_ERROR;
1823 return $status;
1824 } elseif ( $this->hookError != '' ) {
1825 # ...or the hook could be expecting us to produce an error
1826 $status->fatal( 'hookaborted' );
1827 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1828 return $status;
1831 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1832 // Auto-block user's IP if the account was "hard" blocked
1833 if ( !wfReadOnly() ) {
1834 $wgUser->spreadAnyEditBlock();
1836 # Check block state against master, thus 'false'.
1837 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1838 return $status;
1841 $this->contentLength = strlen( $this->textbox1 );
1842 if ( $this->contentLength > $wgMaxArticleSize * 1024 ) {
1843 // Error will be displayed by showEditForm()
1844 $this->tooBig = true;
1845 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1846 return $status;
1849 if ( !$wgUser->isAllowed( 'edit' ) ) {
1850 if ( $wgUser->isAnon() ) {
1851 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1852 return $status;
1853 } else {
1854 $status->fatal( 'readonlytext' );
1855 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1856 return $status;
1860 $changingContentModel = false;
1861 if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
1862 if ( !$wgContentHandlerUseDB ) {
1863 $status->fatal( 'editpage-cannot-use-custom-model' );
1864 $status->value = self::AS_CANNOT_USE_CUSTOM_MODEL;
1865 return $status;
1866 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1867 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1868 return $status;
1870 // Make sure the user can edit the page under the new content model too
1871 $titleWithNewContentModel = clone $this->mTitle;
1872 $titleWithNewContentModel->setContentModel( $this->contentModel );
1873 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $wgUser )
1874 || !$titleWithNewContentModel->userCan( 'edit', $wgUser )
1876 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1877 return $status;
1880 $changingContentModel = true;
1881 $oldContentModel = $this->mTitle->getContentModel();
1884 if ( $this->changeTags ) {
1885 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
1886 $this->changeTags, $wgUser );
1887 if ( !$changeTagsStatus->isOK() ) {
1888 $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
1889 return $changeTagsStatus;
1893 if ( wfReadOnly() ) {
1894 $status->fatal( 'readonlytext' );
1895 $status->value = self::AS_READ_ONLY_PAGE;
1896 return $status;
1898 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 )
1899 || ( $changingContentModel && $wgUser->pingLimiter( 'editcontentmodel' ) )
1901 $status->fatal( 'actionthrottledtext' );
1902 $status->value = self::AS_RATE_LIMITED;
1903 return $status;
1906 # If the article has been deleted while editing, don't save it without
1907 # confirmation
1908 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1909 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1910 return $status;
1913 # Load the page data from the master. If anything changes in the meantime,
1914 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1915 $this->page->loadPageData( 'fromdbmaster' );
1916 $new = !$this->page->exists();
1918 if ( $new ) {
1919 // Late check for create permission, just in case *PARANOIA*
1920 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1921 $status->fatal( 'nocreatetext' );
1922 $status->value = self::AS_NO_CREATE_PERMISSION;
1923 wfDebug( __METHOD__ . ": no create permission\n" );
1924 return $status;
1927 // Don't save a new page if it's blank or if it's a MediaWiki:
1928 // message with content equivalent to default (allow empty pages
1929 // in this case to disable messages, see T52124)
1930 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1931 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1932 $defaultText = $defaultMessageText;
1933 } else {
1934 $defaultText = '';
1937 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
1938 $this->blankArticle = true;
1939 $status->fatal( 'blankarticle' );
1940 $status->setResult( false, self::AS_BLANK_ARTICLE );
1941 return $status;
1944 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1945 return $status;
1948 $content = $textbox_content;
1950 $result['sectionanchor'] = '';
1951 if ( $this->section == 'new' ) {
1952 if ( $this->sectiontitle !== '' ) {
1953 // Insert the section title above the content.
1954 $content = $content->addSectionHeader( $this->sectiontitle );
1955 } elseif ( $this->summary !== '' ) {
1956 // Insert the section title above the content.
1957 $content = $content->addSectionHeader( $this->summary );
1959 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
1962 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1964 } else { # not $new
1966 # Article exists. Check for edit conflict.
1968 $this->page->clear(); # Force reload of dates, etc.
1969 $timestamp = $this->page->getTimestamp();
1970 $latest = $this->page->getLatest();
1972 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1974 // Check editRevId if set, which handles same-second timestamp collisions
1975 if ( $timestamp != $this->edittime
1976 || ( $this->editRevId !== null && $this->editRevId != $latest )
1978 $this->isConflict = true;
1979 if ( $this->section == 'new' ) {
1980 if ( $this->page->getUserText() == $wgUser->getName() &&
1981 $this->page->getComment() == $this->newSectionSummary()
1983 // Probably a duplicate submission of a new comment.
1984 // This can happen when CDN resends a request after
1985 // a timeout but the first one actually went through.
1986 wfDebug( __METHOD__
1987 . ": duplicate new section submission; trigger edit conflict!\n" );
1988 } else {
1989 // New comment; suppress conflict.
1990 $this->isConflict = false;
1991 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1993 } elseif ( $this->section == ''
1994 && Revision::userWasLastToEdit(
1995 DB_MASTER, $this->mTitle->getArticleID(),
1996 $wgUser->getId(), $this->edittime
1999 # Suppress edit conflict with self, except for section edits where merging is required.
2000 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
2001 $this->isConflict = false;
2005 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2006 if ( $this->sectiontitle !== '' ) {
2007 $sectionTitle = $this->sectiontitle;
2008 } else {
2009 $sectionTitle = $this->summary;
2012 $content = null;
2014 if ( $this->isConflict ) {
2015 wfDebug( __METHOD__
2016 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2017 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2018 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2019 // ...or disable section editing for non-current revisions (not exposed anyway).
2020 if ( $this->editRevId !== null ) {
2021 $content = $this->page->replaceSectionAtRev(
2022 $this->section,
2023 $textbox_content,
2024 $sectionTitle,
2025 $this->editRevId
2027 } else {
2028 $content = $this->page->replaceSectionContent(
2029 $this->section,
2030 $textbox_content,
2031 $sectionTitle,
2032 $this->edittime
2035 } else {
2036 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
2037 $content = $this->page->replaceSectionContent(
2038 $this->section,
2039 $textbox_content,
2040 $sectionTitle
2044 if ( is_null( $content ) ) {
2045 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
2046 $this->isConflict = true;
2047 $content = $textbox_content; // do not try to merge here!
2048 } elseif ( $this->isConflict ) {
2049 # Attempt merge
2050 if ( $this->mergeChangesIntoContent( $content ) ) {
2051 // Successful merge! Maybe we should tell the user the good news?
2052 $this->isConflict = false;
2053 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
2054 } else {
2055 $this->section = '';
2056 $this->textbox1 = ContentHandler::getContentText( $content );
2057 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
2061 if ( $this->isConflict ) {
2062 $status->setResult( false, self::AS_CONFLICT_DETECTED );
2063 return $status;
2066 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
2067 return $status;
2070 if ( $this->section == 'new' ) {
2071 // Handle the user preference to force summaries here
2072 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
2073 $this->missingSummary = true;
2074 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2075 $status->value = self::AS_SUMMARY_NEEDED;
2076 return $status;
2079 // Do not allow the user to post an empty comment
2080 if ( $this->textbox1 == '' ) {
2081 $this->missingComment = true;
2082 $status->fatal( 'missingcommenttext' );
2083 $status->value = self::AS_TEXTBOX_EMPTY;
2084 return $status;
2086 } elseif ( !$this->allowBlankSummary
2087 && !$content->equals( $this->getOriginalContent( $wgUser ) )
2088 && !$content->isRedirect()
2089 && md5( $this->summary ) == $this->autoSumm
2091 $this->missingSummary = true;
2092 $status->fatal( 'missingsummary' );
2093 $status->value = self::AS_SUMMARY_NEEDED;
2094 return $status;
2097 # All's well
2098 $sectionanchor = '';
2099 if ( $this->section == 'new' ) {
2100 $this->summary = $this->newSectionSummary( $sectionanchor );
2101 } elseif ( $this->section != '' ) {
2102 # Try to get a section anchor from the section source, redirect
2103 # to edited section if header found.
2104 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2105 # for duplicate heading checking and maybe parsing.
2106 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
2107 # We can't deal with anchors, includes, html etc in the header for now,
2108 # headline would need to be parsed to improve this.
2109 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2110 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
2113 $result['sectionanchor'] = $sectionanchor;
2115 // Save errors may fall down to the edit form, but we've now
2116 // merged the section into full text. Clear the section field
2117 // so that later submission of conflict forms won't try to
2118 // replace that into a duplicated mess.
2119 $this->textbox1 = $this->toEditText( $content );
2120 $this->section = '';
2122 $status->value = self::AS_SUCCESS_UPDATE;
2125 if ( !$this->allowSelfRedirect
2126 && $content->isRedirect()
2127 && $content->getRedirectTarget()->equals( $this->getTitle() )
2129 // If the page already redirects to itself, don't warn.
2130 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2131 if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
2132 $this->selfRedirect = true;
2133 $status->fatal( 'selfredirect' );
2134 $status->value = self::AS_SELF_REDIRECT;
2135 return $status;
2139 // Check for length errors again now that the section is merged in
2140 $this->contentLength = strlen( $this->toEditText( $content ) );
2141 if ( $this->contentLength > $wgMaxArticleSize * 1024 ) {
2142 $this->tooBig = true;
2143 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
2144 return $status;
2147 $flags = EDIT_AUTOSUMMARY |
2148 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
2149 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
2150 ( $bot ? EDIT_FORCE_BOT : 0 );
2152 $doEditStatus = $this->page->doEditContent(
2153 $content,
2154 $this->summary,
2155 $flags,
2156 false,
2157 $wgUser,
2158 $content->getDefaultFormat(),
2159 $this->changeTags,
2160 $this->undidRev
2163 if ( !$doEditStatus->isOK() ) {
2164 // Failure from doEdit()
2165 // Show the edit conflict page for certain recognized errors from doEdit(),
2166 // but don't show it for errors from extension hooks
2167 $errors = $doEditStatus->getErrorsArray();
2168 if ( in_array( $errors[0][0],
2169 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2171 $this->isConflict = true;
2172 // Destroys data doEdit() put in $status->value but who cares
2173 $doEditStatus->value = self::AS_END;
2175 return $doEditStatus;
2178 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2179 if ( $result['nullEdit'] ) {
2180 // We don't know if it was a null edit until now, so increment here
2181 $wgUser->pingLimiter( 'linkpurge' );
2183 $result['redirect'] = $content->isRedirect();
2185 $this->updateWatchlist();
2187 // If the content model changed, add a log entry
2188 if ( $changingContentModel ) {
2189 $this->addContentModelChangeLogEntry(
2190 $wgUser,
2191 $new ? false : $oldContentModel,
2192 $this->contentModel,
2193 $this->summary
2197 return $status;
2201 * @param User $user
2202 * @param string|false $oldModel false if the page is being newly created
2203 * @param string $newModel
2204 * @param string $reason
2206 protected function addContentModelChangeLogEntry( User $user, $oldModel, $newModel, $reason ) {
2207 $new = $oldModel === false;
2208 $log = new ManualLogEntry( 'contentmodel', $new ? 'new' : 'change' );
2209 $log->setPerformer( $user );
2210 $log->setTarget( $this->mTitle );
2211 $log->setComment( $reason );
2212 $log->setParameters( [
2213 '4::oldmodel' => $oldModel,
2214 '5::newmodel' => $newModel
2215 ] );
2216 $logid = $log->insert();
2217 $log->publish( $logid );
2221 * Register the change of watch status
2223 protected function updateWatchlist() {
2224 global $wgUser;
2226 if ( !$wgUser->isLoggedIn() ) {
2227 return;
2230 $user = $wgUser;
2231 $title = $this->mTitle;
2232 $watch = $this->watchthis;
2233 // Do this in its own transaction to reduce contention...
2234 DeferredUpdates::addCallableUpdate( function () use ( $user, $title, $watch ) {
2235 if ( $watch == $user->isWatched( $title, User::IGNORE_USER_RIGHTS ) ) {
2236 return; // nothing to change
2238 WatchAction::doWatchOrUnwatch( $watch, $title, $user );
2239 } );
2243 * Attempts to do 3-way merge of edit content with a base revision
2244 * and current content, in case of edit conflict, in whichever way appropriate
2245 * for the content type.
2247 * @since 1.21
2249 * @param Content $editContent
2251 * @return bool
2253 private function mergeChangesIntoContent( &$editContent ) {
2254 $db = wfGetDB( DB_MASTER );
2256 // This is the revision the editor started from
2257 $baseRevision = $this->getBaseRevision();
2258 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
2260 if ( is_null( $baseContent ) ) {
2261 return false;
2264 // The current state, we want to merge updates into it
2265 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2266 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2268 if ( is_null( $currentContent ) ) {
2269 return false;
2272 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2274 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2276 if ( $result ) {
2277 $editContent = $result;
2278 // Update parentRevId to what we just merged.
2279 $this->parentRevId = $currentRevision->getId();
2280 return true;
2283 return false;
2287 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2288 * one might think of X as the "base revision", which is NOT what this returns.
2289 * @return Revision Current version when the edit was started
2291 public function getBaseRevision() {
2292 if ( !$this->mBaseRevision ) {
2293 $db = wfGetDB( DB_MASTER );
2294 $this->mBaseRevision = $this->editRevId
2295 ? Revision::newFromId( $this->editRevId, Revision::READ_LATEST )
2296 : Revision::loadFromTimestamp( $db, $this->mTitle, $this->edittime );
2298 return $this->mBaseRevision;
2302 * Check given input text against $wgSpamRegex, and return the text of the first match.
2304 * @param string $text
2306 * @return string|bool Matching string or false
2308 public static function matchSpamRegex( $text ) {
2309 global $wgSpamRegex;
2310 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2311 $regexes = (array)$wgSpamRegex;
2312 return self::matchSpamRegexInternal( $text, $regexes );
2316 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2318 * @param string $text
2320 * @return string|bool Matching string or false
2322 public static function matchSummarySpamRegex( $text ) {
2323 global $wgSummarySpamRegex;
2324 $regexes = (array)$wgSummarySpamRegex;
2325 return self::matchSpamRegexInternal( $text, $regexes );
2329 * @param string $text
2330 * @param array $regexes
2331 * @return bool|string
2333 protected static function matchSpamRegexInternal( $text, $regexes ) {
2334 foreach ( $regexes as $regex ) {
2335 $matches = [];
2336 if ( preg_match( $regex, $text, $matches ) ) {
2337 return $matches[0];
2340 return false;
2343 public function setHeaders() {
2344 global $wgOut, $wgUser, $wgAjaxEditStash;
2346 $wgOut->addModules( 'mediawiki.action.edit' );
2347 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2349 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2350 // The addition of default buttons is handled by getEditToolbar() which
2351 // has its own dependency on this module. The call here ensures the module
2352 // is loaded in time (it has position "top") for other modules to register
2353 // buttons (e.g. extensions, gadgets, user scripts).
2354 $wgOut->addModules( 'mediawiki.toolbar' );
2357 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2358 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2361 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2362 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2365 # Enabled article-related sidebar, toplinks, etc.
2366 $wgOut->setArticleRelated( true );
2368 $contextTitle = $this->getContextTitle();
2369 if ( $this->isConflict ) {
2370 $msg = 'editconflict';
2371 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2372 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2373 } else {
2374 $msg = $contextTitle->exists()
2375 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2376 && $contextTitle->getDefaultMessageText() !== false
2378 ? 'editing'
2379 : 'creating';
2382 # Use the title defined by DISPLAYTITLE magic word when present
2383 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2384 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2385 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2386 if ( $displayTitle === false ) {
2387 $displayTitle = $contextTitle->getPrefixedText();
2389 $wgOut->setPageTitle( $this->context->msg( $msg, $displayTitle ) );
2390 # Transmit the name of the message to JavaScript for live preview
2391 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2392 $wgOut->addJsConfigVars( [
2393 'wgEditMessage' => $msg,
2394 'wgAjaxEditStash' => $wgAjaxEditStash,
2395 ] );
2399 * Show all applicable editing introductions
2401 protected function showIntro() {
2402 global $wgOut, $wgUser;
2403 if ( $this->suppressIntro ) {
2404 return;
2407 $namespace = $this->mTitle->getNamespace();
2409 if ( $namespace == NS_MEDIAWIKI ) {
2410 # Show a warning if editing an interface message
2411 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2412 # If this is a default message (but not css or js),
2413 # show a hint that it is translatable on translatewiki.net
2414 if ( !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2415 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2417 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2418 if ( $defaultMessageText !== false ) {
2419 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2420 'translateinterface' );
2423 } elseif ( $namespace == NS_FILE ) {
2424 # Show a hint to shared repo
2425 $file = wfFindFile( $this->mTitle );
2426 if ( $file && !$file->isLocal() ) {
2427 $descUrl = $file->getDescriptionUrl();
2428 # there must be a description url to show a hint to shared repo
2429 if ( $descUrl ) {
2430 if ( !$this->mTitle->exists() ) {
2431 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2432 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2433 ] );
2434 } else {
2435 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2436 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2437 ] );
2443 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2444 # Show log extract when the user is currently blocked
2445 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2446 $username = explode( '/', $this->mTitle->getText(), 2 )[0];
2447 $user = User::newFromName( $username, false /* allow IP users */ );
2448 $ip = User::isIP( $username );
2449 $block = Block::newFromTarget( $user, $user );
2450 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2451 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2452 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2453 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2454 # Show log extract if the user is currently blocked
2455 LogEventsList::showLogExtract(
2456 $wgOut,
2457 'block',
2458 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2461 'lim' => 1,
2462 'showIfEmpty' => false,
2463 'msgKey' => [
2464 'blocked-notice-logextract',
2465 $user->getName() # Support GENDER in notice
2471 # Try to add a custom edit intro, or use the standard one if this is not possible.
2472 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2473 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2474 $this->context->msg( 'helppage' )->inContentLanguage()->text()
2475 ) );
2476 if ( $wgUser->isLoggedIn() ) {
2477 $wgOut->wrapWikiMsg(
2478 // Suppress the external link icon, consider the help url an internal one
2479 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2481 'newarticletext',
2482 $helpLink
2485 } else {
2486 $wgOut->wrapWikiMsg(
2487 // Suppress the external link icon, consider the help url an internal one
2488 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2490 'newarticletextanon',
2491 $helpLink
2496 # Give a notice if the user is editing a deleted/moved page...
2497 if ( !$this->mTitle->exists() ) {
2498 $dbr = wfGetDB( DB_REPLICA );
2500 LogEventsList::showLogExtract( $wgOut, [ 'delete', 'move' ], $this->mTitle,
2503 'lim' => 10,
2504 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2505 'showIfEmpty' => false,
2506 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2513 * Attempt to show a custom editing introduction, if supplied
2515 * @return bool
2517 protected function showCustomIntro() {
2518 if ( $this->editintro ) {
2519 $title = Title::newFromText( $this->editintro );
2520 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2521 global $wgOut;
2522 // Added using template syntax, to take <noinclude>'s into account.
2523 $wgOut->addWikiTextTitleTidy(
2524 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2525 $this->mTitle
2527 return true;
2530 return false;
2534 * Gets an editable textual representation of $content.
2535 * The textual representation can be turned by into a Content object by the
2536 * toEditContent() method.
2538 * If $content is null or false or a string, $content is returned unchanged.
2540 * If the given Content object is not of a type that can be edited using
2541 * the text base EditPage, an exception will be raised. Set
2542 * $this->allowNonTextContent to true to allow editing of non-textual
2543 * content.
2545 * @param Content|null|bool|string $content
2546 * @return string The editable text form of the content.
2548 * @throws MWException If $content is not an instance of TextContent and
2549 * $this->allowNonTextContent is not true.
2551 protected function toEditText( $content ) {
2552 if ( $content === null || $content === false || is_string( $content ) ) {
2553 return $content;
2556 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2557 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2560 return $content->serialize( $this->contentFormat );
2564 * Turns the given text into a Content object by unserializing it.
2566 * If the resulting Content object is not of a type that can be edited using
2567 * the text base EditPage, an exception will be raised. Set
2568 * $this->allowNonTextContent to true to allow editing of non-textual
2569 * content.
2571 * @param string|null|bool $text Text to unserialize
2572 * @return Content|bool|null The content object created from $text. If $text was false
2573 * or null, false resp. null will be returned instead.
2575 * @throws MWException If unserializing the text results in a Content
2576 * object that is not an instance of TextContent and
2577 * $this->allowNonTextContent is not true.
2579 protected function toEditContent( $text ) {
2580 if ( $text === false || $text === null ) {
2581 return $text;
2584 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2585 $this->contentModel, $this->contentFormat );
2587 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2588 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2591 return $content;
2595 * Send the edit form and related headers to $wgOut
2596 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2597 * during form output near the top, for captchas and the like.
2599 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2600 * use the EditPage::showEditForm:fields hook instead.
2602 public function showEditForm( $formCallback = null ) {
2603 global $wgOut, $wgUser;
2605 # need to parse the preview early so that we know which templates are used,
2606 # otherwise users with "show preview after edit box" will get a blank list
2607 # we parse this near the beginning so that setHeaders can do the title
2608 # setting work instead of leaving it in getPreviewText
2609 $previewOutput = '';
2610 if ( $this->formtype == 'preview' ) {
2611 $previewOutput = $this->getPreviewText();
2614 // Avoid PHP 7.1 warning of passing $this by reference
2615 $editPage = $this;
2616 Hooks::run( 'EditPage::showEditForm:initial', [ &$editPage, &$wgOut ] );
2618 $this->setHeaders();
2620 $this->addTalkPageText();
2621 $this->addEditNotices();
2623 if ( !$this->isConflict &&
2624 $this->section != '' &&
2625 !$this->isSectionEditSupported() ) {
2626 // We use $this->section to much before this and getVal('wgSection') directly in other places
2627 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2628 // Someone is welcome to try refactoring though
2629 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2630 return;
2633 $this->showHeader();
2635 $wgOut->addHTML( $this->editFormPageTop );
2637 if ( $wgUser->getOption( 'previewontop' ) ) {
2638 $this->displayPreviewArea( $previewOutput, true );
2641 $wgOut->addHTML( $this->editFormTextTop );
2643 $showToolbar = true;
2644 if ( $this->wasDeletedSinceLastEdit() ) {
2645 if ( $this->formtype == 'save' ) {
2646 // Hide the toolbar and edit area, user can click preview to get it back
2647 // Add an confirmation checkbox and explanation.
2648 $showToolbar = false;
2649 } else {
2650 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2651 'deletedwhileediting' );
2655 // @todo add EditForm plugin interface and use it here!
2656 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2657 $wgOut->addHTML( Html::openElement(
2658 'form',
2660 'class' => $this->oouiEnabled ? 'mw-editform-ooui' : 'mw-editform-legacy',
2661 'id' => self::EDITFORM_ID,
2662 'name' => self::EDITFORM_ID,
2663 'method' => 'post',
2664 'action' => $this->getActionURL( $this->getContextTitle() ),
2665 'enctype' => 'multipart/form-data'
2667 ) );
2669 if ( is_callable( $formCallback ) ) {
2670 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2671 call_user_func_array( $formCallback, [ &$wgOut ] );
2674 // Add an empty field to trip up spambots
2675 $wgOut->addHTML(
2676 Xml::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2677 . Html::rawElement(
2678 'label',
2679 [ 'for' => 'wpAntispam' ],
2680 $this->context->msg( 'simpleantispam-label' )->parse()
2682 . Xml::element(
2683 'input',
2685 'type' => 'text',
2686 'name' => 'wpAntispam',
2687 'id' => 'wpAntispam',
2688 'value' => ''
2691 . Xml::closeElement( 'div' )
2694 // Avoid PHP 7.1 warning of passing $this by reference
2695 $editPage = $this;
2696 Hooks::run( 'EditPage::showEditForm:fields', [ &$editPage, &$wgOut ] );
2698 // Put these up at the top to ensure they aren't lost on early form submission
2699 $this->showFormBeforeText();
2701 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2702 $username = $this->lastDelete->user_name;
2703 $comment = $this->lastDelete->log_comment;
2705 // It is better to not parse the comment at all than to have templates expanded in the middle
2706 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2707 $key = $comment === ''
2708 ? 'confirmrecreate-noreason'
2709 : 'confirmrecreate';
2710 $wgOut->addHTML(
2711 '<div class="mw-confirm-recreate">' .
2712 $this->context->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2713 Xml::checkLabel( $this->context->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2714 [ 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2716 '</div>'
2720 # When the summary is hidden, also hide them on preview/show changes
2721 if ( $this->nosummary ) {
2722 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2725 # If a blank edit summary was previously provided, and the appropriate
2726 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2727 # user being bounced back more than once in the event that a summary
2728 # is not required.
2729 # ####
2730 # For a bit more sophisticated detection of blank summaries, hash the
2731 # automatic one and pass that in the hidden field wpAutoSummary.
2732 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2733 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2736 if ( $this->undidRev ) {
2737 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2740 if ( $this->selfRedirect ) {
2741 $wgOut->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2744 if ( $this->hasPresetSummary ) {
2745 // If a summary has been preset using &summary= we don't want to prompt for
2746 // a different summary. Only prompt for a summary if the summary is blanked.
2747 // (T19416)
2748 $this->autoSumm = md5( '' );
2751 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2752 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2754 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2755 $wgOut->addHTML( Html::hidden( 'parentRevId', $this->getParentRevId() ) );
2757 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2758 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2760 // following functions will need OOUI, enable it only once; here.
2761 if ( $this->oouiEnabled ) {
2762 $wgOut->enableOOUI();
2765 if ( $this->section == 'new' ) {
2766 $this->showSummaryInput( true, $this->summary );
2767 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2770 $wgOut->addHTML( $this->editFormTextBeforeContent );
2772 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2773 $wgOut->addHTML( EditPage::getEditToolbar( $this->mTitle ) );
2776 if ( $this->blankArticle ) {
2777 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2780 if ( $this->isConflict ) {
2781 // In an edit conflict bypass the overridable content form method
2782 // and fallback to the raw wpTextbox1 since editconflicts can't be
2783 // resolved between page source edits and custom ui edits using the
2784 // custom edit ui.
2785 $this->textbox2 = $this->textbox1;
2787 $content = $this->getCurrentContent();
2788 $this->textbox1 = $this->toEditText( $content );
2790 $this->showTextbox1();
2791 } else {
2792 $this->showContentForm();
2795 $wgOut->addHTML( $this->editFormTextAfterContent );
2797 $this->showStandardInputs();
2799 $this->showFormAfterText();
2801 $this->showTosSummary();
2803 $this->showEditTools();
2805 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2807 $wgOut->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2809 $wgOut->addHTML( Html::rawElement( 'div', [ 'class' => 'hiddencats' ],
2810 Linker::formatHiddenCategories( $this->page->getHiddenCategories() ) ) );
2812 $wgOut->addHTML( Html::rawElement( 'div', [ 'class' => 'limitreport' ],
2813 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2815 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2817 if ( $this->isConflict ) {
2818 try {
2819 $this->showConflict();
2820 } catch ( MWContentSerializationException $ex ) {
2821 // this can't really happen, but be nice if it does.
2822 $msg = $this->context->msg(
2823 'content-failed-to-parse',
2824 $this->contentModel,
2825 $this->contentFormat,
2826 $ex->getMessage()
2828 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2832 // Set a hidden field so JS knows what edit form mode we are in
2833 if ( $this->isConflict ) {
2834 $mode = 'conflict';
2835 } elseif ( $this->preview ) {
2836 $mode = 'preview';
2837 } elseif ( $this->diff ) {
2838 $mode = 'diff';
2839 } else {
2840 $mode = 'text';
2842 $wgOut->addHTML( Html::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2844 // Marker for detecting truncated form data. This must be the last
2845 // parameter sent in order to be of use, so do not move me.
2846 $wgOut->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2847 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2849 if ( !$wgUser->getOption( 'previewontop' ) ) {
2850 $this->displayPreviewArea( $previewOutput, false );
2855 * Wrapper around TemplatesOnThisPageFormatter to make
2856 * a "templates on this page" list.
2858 * @param Title[] $templates
2859 * @return string HTML
2861 public function makeTemplatesOnThisPageList( array $templates ) {
2862 $templateListFormatter = new TemplatesOnThisPageFormatter(
2863 $this->context, MediaWikiServices::getInstance()->getLinkRenderer()
2866 // preview if preview, else section if section, else false
2867 $type = false;
2868 if ( $this->preview ) {
2869 $type = 'preview';
2870 } elseif ( $this->section != '' ) {
2871 $type = 'section';
2874 return Html::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2875 $templateListFormatter->format( $templates, $type )
2880 * Extract the section title from current section text, if any.
2882 * @param string $text
2883 * @return string|bool String or false
2885 public static function extractSectionTitle( $text ) {
2886 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2887 if ( !empty( $matches[2] ) ) {
2888 global $wgParser;
2889 return $wgParser->stripSectionName( trim( $matches[2] ) );
2890 } else {
2891 return false;
2895 protected function showHeader() {
2896 global $wgOut, $wgUser;
2897 global $wgAllowUserCss, $wgAllowUserJs;
2899 if ( $this->isConflict ) {
2900 $this->addExplainConflictHeader( $wgOut );
2901 $this->editRevId = $this->page->getLatest();
2902 } else {
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 if ( $this->missingComment ) {
2913 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2916 if ( $this->missingSummary && $this->section != 'new' ) {
2917 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2920 if ( $this->missingSummary && $this->section == 'new' ) {
2921 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2924 if ( $this->blankArticle ) {
2925 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2928 if ( $this->selfRedirect ) {
2929 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2932 if ( $this->hookError !== '' ) {
2933 $wgOut->addWikiText( $this->hookError );
2936 if ( !$this->checkUnicodeCompliantBrowser() ) {
2937 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2940 if ( $this->section != 'new' ) {
2941 $revision = $this->mArticle->getRevisionFetched();
2942 if ( $revision ) {
2943 // Let sysop know that this will make private content public if saved
2945 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2946 $wgOut->wrapWikiMsg(
2947 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2948 'rev-deleted-text-permission'
2950 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2951 $wgOut->wrapWikiMsg(
2952 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2953 'rev-deleted-text-view'
2957 if ( !$revision->isCurrent() ) {
2958 $this->mArticle->setOldSubtitle( $revision->getId() );
2959 $wgOut->addWikiMsg( 'editingold' );
2960 $this->isOldRev = true;
2962 } elseif ( $this->mTitle->exists() ) {
2963 // Something went wrong
2965 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2966 [ 'missing-revision', $this->oldid ] );
2971 if ( wfReadOnly() ) {
2972 $wgOut->wrapWikiMsg(
2973 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2974 [ 'readonlywarning', wfReadOnlyReason() ]
2976 } elseif ( $wgUser->isAnon() ) {
2977 if ( $this->formtype != 'preview' ) {
2978 $wgOut->wrapWikiMsg(
2979 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
2980 [ 'anoneditwarning',
2981 // Log-in link
2982 SpecialPage::getTitleFor( 'Userlogin' )->getFullURL( [
2983 'returnto' => $this->getTitle()->getPrefixedDBkey()
2984 ] ),
2985 // Sign-up link
2986 SpecialPage::getTitleFor( 'CreateAccount' )->getFullURL( [
2987 'returnto' => $this->getTitle()->getPrefixedDBkey()
2991 } else {
2992 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
2993 'anonpreviewwarning'
2996 } else {
2997 if ( $this->isCssJsSubpage ) {
2998 # Check the skin exists
2999 if ( $this->isWrongCaseCssJsPage ) {
3000 $wgOut->wrapWikiMsg(
3001 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
3002 [ 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ]
3005 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
3006 $wgOut->wrapWikiMsg( '<div class="mw-usercssjspublic">$1</div>',
3007 $this->isCssSubpage ? 'usercssispublic' : 'userjsispublic'
3009 if ( $this->formtype !== 'preview' ) {
3010 if ( $this->isCssSubpage && $wgAllowUserCss ) {
3011 $wgOut->wrapWikiMsg(
3012 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3013 [ 'usercssyoucanpreview' ]
3017 if ( $this->isJsSubpage && $wgAllowUserJs ) {
3018 $wgOut->wrapWikiMsg(
3019 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3020 [ 'userjsyoucanpreview' ]
3028 $this->addPageProtectionWarningHeaders();
3030 $this->addLongPageWarningHeader();
3032 # Add header copyright warning
3033 $this->showHeaderCopyrightWarning();
3037 * Helper function for summary input functions, which returns the neccessary
3038 * attributes for the input.
3040 * @param array|null $inputAttrs Array of attrs to use on the input
3041 * @return array
3043 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3044 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
3045 return ( is_array( $inputAttrs ) ? $inputAttrs : [] ) + [
3046 'id' => 'wpSummary',
3047 'maxlength' => '200',
3048 'tabindex' => '1',
3049 'size' => 60,
3050 'spellcheck' => 'true',
3051 ] + Linker::tooltipAndAccesskeyAttribs( 'summary' );
3055 * Standard summary input and label (wgSummary), abstracted so EditPage
3056 * subclasses may reorganize the form.
3057 * Note that you do not need to worry about the label's for=, it will be
3058 * inferred by the id given to the input. You can remove them both by
3059 * passing [ 'id' => false ] to $userInputAttrs.
3061 * @param string $summary The value of the summary input
3062 * @param string $labelText The html to place inside the label
3063 * @param array $inputAttrs Array of attrs to use on the input
3064 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
3066 * @return array An array in the format [ $label, $input ]
3068 public function getSummaryInput( $summary = "", $labelText = null,
3069 $inputAttrs = null, $spanLabelAttrs = null
3071 $inputAttrs = $this->getSummaryInputAttributes( $inputAttrs );
3073 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : [] ) + [
3074 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
3075 'id' => "wpSummaryLabel"
3078 $label = null;
3079 if ( $labelText ) {
3080 $label = Xml::tags(
3081 'label',
3082 $inputAttrs['id'] ? [ 'for' => $inputAttrs['id'] ] : null,
3083 $labelText
3085 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
3088 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
3090 return [ $label, $input ];
3094 * Same as self::getSummaryInput, but uses OOUI, instead of plain HTML.
3095 * Builds a standard summary input with a label.
3097 * @param string $summary The value of the summary input
3098 * @param string $labelText The html to place inside the label
3099 * @param array $inputAttrs Array of attrs to use on the input
3101 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3103 function getSummaryInputOOUI( $summary = "", $labelText = null, $inputAttrs = null ) {
3104 $inputAttrs = OOUI\Element::configFromHtmlAttributes(
3105 $this->getSummaryInputAttributes( $inputAttrs )
3108 return new OOUI\FieldLayout(
3109 new OOUI\TextInputWidget( [
3110 'value' => $summary,
3111 'infusable' => true,
3112 ] + $inputAttrs ),
3114 'label' => new OOUI\HtmlSnippet( $labelText ),
3115 'align' => 'top',
3116 'id' => 'wpSummaryLabel',
3117 'classes' => [ $this->missingSummary ? 'mw-summarymissed' : 'mw-summary' ],
3123 * @param bool $isSubjectPreview True if this is the section subject/title
3124 * up top, or false if this is the comment summary
3125 * down below the textarea
3126 * @param string $summary The text of the summary to display
3128 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3129 global $wgOut;
3131 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3132 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
3133 if ( $isSubjectPreview ) {
3134 if ( $this->nosummary ) {
3135 return;
3137 } else {
3138 if ( !$this->mShowSummaryField ) {
3139 return;
3143 $labelText = $this->context->msg( $isSubjectPreview ? 'subject' : 'summary' )->parse();
3144 if ( $this->oouiEnabled ) {
3145 $wgOut->addHTML( $this->getSummaryInputOOUI(
3146 $summary,
3147 $labelText,
3148 [ 'class' => $summaryClass ]
3149 ) );
3150 } else {
3151 list( $label, $input ) = $this->getSummaryInput(
3152 $summary,
3153 $labelText,
3154 [ 'class' => $summaryClass ]
3156 $wgOut->addHTML( "{$label} {$input}" );
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
3166 * @return string
3168 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3169 // avoid spaces in preview, gets always trimmed on save
3170 $summary = trim( $summary );
3171 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
3172 return "";
3175 global $wgParser;
3177 if ( $isSubjectPreview ) {
3178 $summary = $this->context->msg( 'newsectionsummary' )
3179 ->rawParams( $wgParser->stripSectionName( $summary ) )
3180 ->inContentLanguage()->text();
3183 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
3185 $summary = $this->context->msg( $message )->parse()
3186 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
3187 return Xml::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3190 protected function showFormBeforeText() {
3191 global $wgOut;
3192 $section = htmlspecialchars( $this->section );
3193 $wgOut->addHTML( <<<HTML
3194 <input type='hidden' value="{$section}" name="wpSection"/>
3195 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
3196 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
3197 <input type='hidden' value="{$this->editRevId}" name="editRevId" />
3198 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
3200 HTML
3202 if ( !$this->checkUnicodeCompliantBrowser() ) {
3203 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
3207 protected function showFormAfterText() {
3208 global $wgOut, $wgUser;
3210 * To make it harder for someone to slip a user a page
3211 * which submits an edit form to the wiki without their
3212 * knowledge, a random token is associated with the login
3213 * session. If it's not passed back with the submission,
3214 * we won't save the page, or render user JavaScript and
3215 * CSS previews.
3217 * For anon editors, who may not have a session, we just
3218 * include the constant suffix to prevent editing from
3219 * broken text-mangling proxies.
3221 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
3225 * Subpage overridable method for printing the form for page content editing
3226 * By default this simply outputs wpTextbox1
3227 * Subclasses can override this to provide a custom UI for editing;
3228 * be it a form, or simply wpTextbox1 with a modified content that will be
3229 * reverse modified when extracted from the post data.
3230 * Note that this is basically the inverse for importContentFormData
3232 protected function showContentForm() {
3233 $this->showTextbox1();
3237 * Method to output wpTextbox1
3238 * The $textoverride method can be used by subclasses overriding showContentForm
3239 * to pass back to this method.
3241 * @param array $customAttribs Array of html attributes to use in the textarea
3242 * @param string $textoverride Optional text to override $this->textarea1 with
3244 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3245 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
3246 $attribs = [ 'style' => 'display:none;' ];
3247 } else {
3248 $classes = []; // Textarea CSS
3249 if ( $this->mTitle->isProtected( 'edit' ) &&
3250 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== [ '' ]
3252 # Is the title semi-protected?
3253 if ( $this->mTitle->isSemiProtected() ) {
3254 $classes[] = 'mw-textarea-sprotected';
3255 } else {
3256 # Then it must be protected based on static groups (regular)
3257 $classes[] = 'mw-textarea-protected';
3259 # Is the title cascade-protected?
3260 if ( $this->mTitle->isCascadeProtected() ) {
3261 $classes[] = 'mw-textarea-cprotected';
3264 # Is an old revision being edited?
3265 if ( $this->isOldRev ) {
3266 $classes[] = 'mw-textarea-oldrev';
3269 $attribs = [ 'tabindex' => 1 ];
3271 if ( is_array( $customAttribs ) ) {
3272 $attribs += $customAttribs;
3275 if ( count( $classes ) ) {
3276 if ( isset( $attribs['class'] ) ) {
3277 $classes[] = $attribs['class'];
3279 $attribs['class'] = implode( ' ', $classes );
3283 $this->showTextbox(
3284 $textoverride !== null ? $textoverride : $this->textbox1,
3285 'wpTextbox1',
3286 $attribs
3290 protected function showTextbox2() {
3291 $this->showTextbox( $this->textbox2, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3294 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3295 global $wgOut, $wgUser;
3297 $wikitext = $this->safeUnicodeOutput( $text );
3298 $wikitext = $this->addNewLineAtEnd( $wikitext );
3300 $attribs = $this->buildTextboxAttribs( $name, $customAttribs, $wgUser );
3302 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
3305 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3306 global $wgOut;
3307 $classes = [];
3308 if ( $isOnTop ) {
3309 $classes[] = 'ontop';
3312 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3314 if ( $this->formtype != 'preview' ) {
3315 $attribs['style'] = 'display: none;';
3318 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
3320 if ( $this->formtype == 'preview' ) {
3321 $this->showPreview( $previewOutput );
3322 } else {
3323 // Empty content container for LivePreview
3324 $pageViewLang = $this->mTitle->getPageViewLanguage();
3325 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3326 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3327 $wgOut->addHTML( Html::rawElement( 'div', $attribs ) );
3330 $wgOut->addHTML( '</div>' );
3332 if ( $this->formtype == 'diff' ) {
3333 try {
3334 $this->showDiff();
3335 } catch ( MWContentSerializationException $ex ) {
3336 $msg = $this->context->msg(
3337 'content-failed-to-parse',
3338 $this->contentModel,
3339 $this->contentFormat,
3340 $ex->getMessage()
3342 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3348 * Append preview output to $wgOut.
3349 * Includes category rendering if this is a category page.
3351 * @param string $text The HTML to be output for the preview.
3353 protected function showPreview( $text ) {
3354 global $wgOut;
3355 if ( $this->mArticle instanceof CategoryPage ) {
3356 $this->mArticle->openShowCategory();
3358 # This hook seems slightly odd here, but makes things more
3359 # consistent for extensions.
3360 Hooks::run( 'OutputPageBeforeHTML', [ &$wgOut, &$text ] );
3361 $wgOut->addHTML( $text );
3362 if ( $this->mArticle instanceof CategoryPage ) {
3363 $this->mArticle->closeShowCategory();
3368 * Get a diff between the current contents of the edit box and the
3369 * version of the page we're editing from.
3371 * If this is a section edit, we'll replace the section as for final
3372 * save and then make a comparison.
3374 public function showDiff() {
3375 global $wgUser, $wgContLang, $wgOut;
3377 $oldtitlemsg = 'currentrev';
3378 # if message does not exist, show diff against the preloaded default
3379 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3380 $oldtext = $this->mTitle->getDefaultMessageText();
3381 if ( $oldtext !== false ) {
3382 $oldtitlemsg = 'defaultmessagetext';
3383 $oldContent = $this->toEditContent( $oldtext );
3384 } else {
3385 $oldContent = null;
3387 } else {
3388 $oldContent = $this->getCurrentContent();
3391 $textboxContent = $this->toEditContent( $this->textbox1 );
3392 if ( $this->editRevId !== null ) {
3393 $newContent = $this->page->replaceSectionAtRev(
3394 $this->section, $textboxContent, $this->summary, $this->editRevId
3396 } else {
3397 $newContent = $this->page->replaceSectionContent(
3398 $this->section, $textboxContent, $this->summary, $this->edittime
3402 if ( $newContent ) {
3403 Hooks::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3405 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
3406 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
3409 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3410 $oldtitle = $this->context->msg( $oldtitlemsg )->parse();
3411 $newtitle = $this->context->msg( 'yourtext' )->parse();
3413 if ( !$oldContent ) {
3414 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3417 if ( !$newContent ) {
3418 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3421 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
3422 $de->setContent( $oldContent, $newContent );
3424 $difftext = $de->getDiff( $oldtitle, $newtitle );
3425 $de->showDiffStyle();
3426 } else {
3427 $difftext = '';
3430 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3434 * Show the header copyright warning.
3436 protected function showHeaderCopyrightWarning() {
3437 $msg = 'editpage-head-copy-warn';
3438 if ( !$this->context->msg( $msg )->isDisabled() ) {
3439 global $wgOut;
3440 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3441 'editpage-head-copy-warn' );
3446 * Give a chance for site and per-namespace customizations of
3447 * terms of service summary link that might exist separately
3448 * from the copyright notice.
3450 * This will display between the save button and the edit tools,
3451 * so should remain short!
3453 protected function showTosSummary() {
3454 $msg = 'editpage-tos-summary';
3455 Hooks::run( 'EditPageTosSummary', [ $this->mTitle, &$msg ] );
3456 if ( !$this->context->msg( $msg )->isDisabled() ) {
3457 global $wgOut;
3458 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3459 $wgOut->addWikiMsg( $msg );
3460 $wgOut->addHTML( '</div>' );
3464 protected function showEditTools() {
3465 global $wgOut;
3466 $wgOut->addHTML( '<div class="mw-editTools">' .
3467 $this->context->msg( 'edittools' )->inContentLanguage()->parse() .
3468 '</div>' );
3472 * Get the copyright warning
3474 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3475 * @return string
3477 protected function getCopywarn() {
3478 return self::getCopyrightWarning( $this->mTitle );
3482 * Get the copyright warning, by default returns wikitext
3484 * @param Title $title
3485 * @param string $format Output format, valid values are any function of a Message object
3486 * @param Language|string|null $langcode Language code or Language object.
3487 * @return string
3489 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3490 global $wgRightsText;
3491 if ( $wgRightsText ) {
3492 $copywarnMsg = [ 'copyrightwarning',
3493 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3494 $wgRightsText ];
3495 } else {
3496 $copywarnMsg = [ 'copyrightwarning2',
3497 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3499 // Allow for site and per-namespace customization of contribution/copyright notice.
3500 Hooks::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3502 $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
3503 if ( $langcode ) {
3504 $msg->inLanguage( $langcode );
3506 return "<div id=\"editpage-copywarn\">\n" .
3507 $msg->$format() . "\n</div>";
3511 * Get the Limit report for page previews
3513 * @since 1.22
3514 * @param ParserOutput $output ParserOutput object from the parse
3515 * @return string HTML
3517 public static function getPreviewLimitReport( $output ) {
3518 if ( !$output || !$output->getLimitReportData() ) {
3519 return '';
3522 $limitReport = Html::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3523 wfMessage( 'limitreport-title' )->parseAsBlock()
3526 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3527 $limitReport .= Html::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3529 $limitReport .= Html::openElement( 'table', [
3530 'class' => 'preview-limit-report wikitable'
3531 ] ) .
3532 Html::openElement( 'tbody' );
3534 foreach ( $output->getLimitReportData() as $key => $value ) {
3535 if ( Hooks::run( 'ParserLimitReportFormat',
3536 [ $key, &$value, &$limitReport, true, true ]
3537 ) ) {
3538 $keyMsg = wfMessage( $key );
3539 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3540 if ( !$valueMsg->exists() ) {
3541 $valueMsg = new RawMessage( '$1' );
3543 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3544 $limitReport .= Html::openElement( 'tr' ) .
3545 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3546 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3547 Html::closeElement( 'tr' );
3552 $limitReport .= Html::closeElement( 'tbody' ) .
3553 Html::closeElement( 'table' ) .
3554 Html::closeElement( 'div' );
3556 return $limitReport;
3559 protected function showStandardInputs( &$tabindex = 2 ) {
3560 global $wgOut;
3561 $wgOut->addHTML( "<div class='editOptions'>\n" );
3563 if ( $this->section != 'new' ) {
3564 $this->showSummaryInput( false, $this->summary );
3565 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3568 if ( $this->oouiEnabled ) {
3569 $checkboxes = $this->getCheckboxesOOUI(
3570 $tabindex,
3571 [ 'minor' => $this->minoredit, 'watch' => $this->watchthis ]
3573 $checkboxesHTML = new OOUI\HorizontalLayout( [ 'items' => $checkboxes ] );
3574 } else {
3575 $checkboxes = $this->getCheckboxes(
3576 $tabindex,
3577 [ 'minor' => $this->minoredit, 'watch' => $this->watchthis ]
3579 $checkboxesHTML = implode( $checkboxes, "\n" );
3582 $wgOut->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3584 // Show copyright warning.
3585 $wgOut->addWikiText( $this->getCopywarn() );
3586 $wgOut->addHTML( $this->editFormTextAfterWarn );
3588 $wgOut->addHTML( "<div class='editButtons'>\n" );
3589 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3591 $cancel = $this->getCancelLink();
3592 if ( $cancel !== '' ) {
3593 $cancel .= Html::element( 'span',
3594 [ 'class' => 'mw-editButtons-pipe-separator' ],
3595 $this->context->msg( 'pipe-separator' )->text() );
3598 $message = $this->context->msg( 'edithelppage' )->inContentLanguage()->text();
3599 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3600 $edithelp =
3601 Html::linkButton(
3602 $this->context->msg( 'edithelp' )->text(),
3603 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3604 [ 'mw-ui-quiet' ]
3606 $this->context->msg( 'word-separator' )->escaped() .
3607 $this->context->msg( 'newwindow' )->parse();
3609 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3610 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3611 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3613 Hooks::run( 'EditPage::showStandardInputs:options', [ $this, $wgOut, &$tabindex ] );
3615 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3619 * Show an edit conflict. textbox1 is already shown in showEditForm().
3620 * If you want to use another entry point to this function, be careful.
3622 protected function showConflict() {
3623 global $wgOut;
3625 // Avoid PHP 7.1 warning of passing $this by reference
3626 $editPage = $this;
3627 if ( Hooks::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$wgOut ] ) ) {
3628 $this->incrementConflictStats();
3630 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3632 $content1 = $this->toEditContent( $this->textbox1 );
3633 $content2 = $this->toEditContent( $this->textbox2 );
3635 $handler = ContentHandler::getForModelID( $this->contentModel );
3636 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3637 $de->setContent( $content2, $content1 );
3638 $de->showDiff(
3639 $this->context->msg( 'yourtext' )->parse(),
3640 $this->context->msg( 'storedversion' )->text()
3643 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3644 $this->showTextbox2();
3648 protected function incrementConflictStats() {
3649 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
3650 $stats->increment( 'edit.failures.conflict' );
3651 // Only include 'standard' namespaces to avoid creating unknown numbers of statsd metrics
3652 if (
3653 $this->mTitle->getNamespace() >= NS_MAIN &&
3654 $this->mTitle->getNamespace() <= NS_CATEGORY_TALK
3656 $stats->increment( 'edit.failures.conflict.byNamespaceId.' . $this->mTitle->getNamespace() );
3661 * @return string
3663 public function getCancelLink() {
3664 $cancelParams = [];
3665 if ( !$this->isConflict && $this->oldid > 0 ) {
3666 $cancelParams['oldid'] = $this->oldid;
3667 } elseif ( $this->getContextTitle()->isRedirect() ) {
3668 $cancelParams['redirect'] = 'no';
3670 if ( $this->oouiEnabled ) {
3671 return new OOUI\ButtonWidget( [
3672 'id' => 'mw-editform-cancel',
3673 'href' => $this->getContextTitle()->getLinkUrl( $cancelParams ),
3674 'label' => new OOUI\HtmlSnippet( $this->context->msg( 'cancel' )->parse() ),
3675 'framed' => false,
3676 'infusable' => true,
3677 'flags' => 'destructive',
3678 ] );
3679 } else {
3680 return MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
3681 $this->getContextTitle(),
3682 new HtmlArmor( $this->context->msg( 'cancel' )->parse() ),
3683 Html::buttonAttributes( [ 'id' => 'mw-editform-cancel' ], [ 'mw-ui-quiet' ] ),
3684 $cancelParams
3690 * Returns the URL to use in the form's action attribute.
3691 * This is used by EditPage subclasses when simply customizing the action
3692 * variable in the constructor is not enough. This can be used when the
3693 * EditPage lives inside of a Special page rather than a custom page action.
3695 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3696 * @return string
3698 protected function getActionURL( Title $title ) {
3699 return $title->getLocalURL( [ 'action' => $this->action ] );
3703 * Check if a page was deleted while the user was editing it, before submit.
3704 * Note that we rely on the logging table, which hasn't been always there,
3705 * but that doesn't matter, because this only applies to brand new
3706 * deletes.
3707 * @return bool
3709 protected function wasDeletedSinceLastEdit() {
3710 if ( $this->deletedSinceEdit !== null ) {
3711 return $this->deletedSinceEdit;
3714 $this->deletedSinceEdit = false;
3716 if ( !$this->mTitle->exists() && $this->mTitle->isDeletedQuick() ) {
3717 $this->lastDelete = $this->getLastDelete();
3718 if ( $this->lastDelete ) {
3719 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3720 if ( $deleteTime > $this->starttime ) {
3721 $this->deletedSinceEdit = true;
3726 return $this->deletedSinceEdit;
3730 * @return bool|stdClass
3732 protected function getLastDelete() {
3733 $dbr = wfGetDB( DB_REPLICA );
3734 $data = $dbr->selectRow(
3735 [ 'logging', 'user' ],
3737 'log_type',
3738 'log_action',
3739 'log_timestamp',
3740 'log_user',
3741 'log_namespace',
3742 'log_title',
3743 'log_comment',
3744 'log_params',
3745 'log_deleted',
3746 'user_name'
3747 ], [
3748 'log_namespace' => $this->mTitle->getNamespace(),
3749 'log_title' => $this->mTitle->getDBkey(),
3750 'log_type' => 'delete',
3751 'log_action' => 'delete',
3752 'user_id=log_user'
3754 __METHOD__,
3755 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ]
3757 // Quick paranoid permission checks...
3758 if ( is_object( $data ) ) {
3759 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3760 $data->user_name = $this->context->msg( 'rev-deleted-user' )->escaped();
3763 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3764 $data->log_comment = $this->context->msg( 'rev-deleted-comment' )->escaped();
3768 return $data;
3772 * Get the rendered text for previewing.
3773 * @throws MWException
3774 * @return string
3776 public function getPreviewText() {
3777 global $wgOut, $wgRawHtml, $wgLang;
3778 global $wgAllowUserCss, $wgAllowUserJs;
3780 if ( $wgRawHtml && !$this->mTokenOk ) {
3781 // Could be an offsite preview attempt. This is very unsafe if
3782 // HTML is enabled, as it could be an attack.
3783 $parsedNote = '';
3784 if ( $this->textbox1 !== '' ) {
3785 // Do not put big scary notice, if previewing the empty
3786 // string, which happens when you initially edit
3787 // a category page, due to automatic preview-on-open.
3788 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3789 $this->context->msg( 'session_fail_preview_html' )->text() . "</div>",
3790 true, /* interface */true );
3792 $this->incrementEditFailureStats( 'session_loss' );
3793 return $parsedNote;
3796 $note = '';
3798 try {
3799 $content = $this->toEditContent( $this->textbox1 );
3801 $previewHTML = '';
3802 if ( !Hooks::run(
3803 'AlternateEditPreview',
3804 [ $this, &$content, &$previewHTML, &$this->mParserOutput ] )
3806 return $previewHTML;
3809 # provide a anchor link to the editform
3810 $continueEditing = '<span class="mw-continue-editing">' .
3811 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3812 $this->context->msg( 'continue-editing' )->text() . ']]</span>';
3813 if ( $this->mTriedSave && !$this->mTokenOk ) {
3814 if ( $this->mTokenOkExceptSuffix ) {
3815 $note = $this->context->msg( 'token_suffix_mismatch' )->plain();
3816 $this->incrementEditFailureStats( 'bad_token' );
3817 } else {
3818 $note = $this->context->msg( 'session_fail_preview' )->plain();
3819 $this->incrementEditFailureStats( 'session_loss' );
3821 } elseif ( $this->incompleteForm ) {
3822 $note = $this->context->msg( 'edit_form_incomplete' )->plain();
3823 if ( $this->mTriedSave ) {
3824 $this->incrementEditFailureStats( 'incomplete_form' );
3826 } else {
3827 $note = $this->context->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3830 # don't parse non-wikitext pages, show message about preview
3831 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3832 if ( $this->mTitle->isCssJsSubpage() ) {
3833 $level = 'user';
3834 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3835 $level = 'site';
3836 } else {
3837 $level = false;
3840 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3841 $format = 'css';
3842 if ( $level === 'user' && !$wgAllowUserCss ) {
3843 $format = false;
3845 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3846 $format = 'js';
3847 if ( $level === 'user' && !$wgAllowUserJs ) {
3848 $format = false;
3850 } else {
3851 $format = false;
3854 # Used messages to make sure grep find them:
3855 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3856 if ( $level && $format ) {
3857 $note = "<div id='mw-{$level}{$format}preview'>" .
3858 $this->context->msg( "{$level}{$format}preview" )->text() .
3859 ' ' . $continueEditing . "</div>";
3863 # If we're adding a comment, we need to show the
3864 # summary as the headline
3865 if ( $this->section === "new" && $this->summary !== "" ) {
3866 $content = $content->addSectionHeader( $this->summary );
3869 $hook_args = [ $this, &$content ];
3870 Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3872 $parserResult = $this->doPreviewParse( $content );
3873 $parserOutput = $parserResult['parserOutput'];
3874 $previewHTML = $parserResult['html'];
3875 $this->mParserOutput = $parserOutput;
3876 $wgOut->addParserOutputMetadata( $parserOutput );
3878 if ( count( $parserOutput->getWarnings() ) ) {
3879 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3882 } catch ( MWContentSerializationException $ex ) {
3883 $m = $this->context->msg(
3884 'content-failed-to-parse',
3885 $this->contentModel,
3886 $this->contentFormat,
3887 $ex->getMessage()
3889 $note .= "\n\n" . $m->parse();
3890 $previewHTML = '';
3893 if ( $this->isConflict ) {
3894 $conflict = '<h2 id="mw-previewconflict">'
3895 . $this->context->msg( 'previewconflict' )->escaped() . "</h2>\n";
3896 } else {
3897 $conflict = '<hr />';
3900 $previewhead = "<div class='previewnote'>\n" .
3901 '<h2 id="mw-previewheader">' . $this->context->msg( 'preview' )->escaped() . "</h2>" .
3902 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3904 $pageViewLang = $this->mTitle->getPageViewLanguage();
3905 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3906 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3907 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3909 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3912 private function incrementEditFailureStats( $failureType ) {
3913 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
3914 $stats->increment( 'edit.failures.' . $failureType );
3918 * Get parser options for a preview
3919 * @return ParserOptions
3921 protected function getPreviewParserOptions() {
3922 $parserOptions = $this->page->makeParserOptions( $this->mArticle->getContext() );
3923 $parserOptions->setIsPreview( true );
3924 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3925 $parserOptions->enableLimitReport();
3926 return $parserOptions;
3930 * Parse the page for a preview. Subclasses may override this class, in order
3931 * to parse with different options, or to otherwise modify the preview HTML.
3933 * @param Content $content The page content
3934 * @return array with keys:
3935 * - parserOutput: The ParserOutput object
3936 * - html: The HTML to be displayed
3938 protected function doPreviewParse( Content $content ) {
3939 global $wgUser;
3940 $parserOptions = $this->getPreviewParserOptions();
3941 $pstContent = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3942 $scopedCallback = $parserOptions->setupFakeRevision(
3943 $this->mTitle, $pstContent, $wgUser );
3944 $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
3945 ScopedCallback::consume( $scopedCallback );
3946 $parserOutput->setEditSectionTokens( false ); // no section edit links
3947 return [
3948 'parserOutput' => $parserOutput,
3949 'html' => $parserOutput->getText() ];
3953 * @return array
3955 public function getTemplates() {
3956 if ( $this->preview || $this->section != '' ) {
3957 $templates = [];
3958 if ( !isset( $this->mParserOutput ) ) {
3959 return $templates;
3961 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3962 foreach ( array_keys( $template ) as $dbk ) {
3963 $templates[] = Title::makeTitle( $ns, $dbk );
3966 return $templates;
3967 } else {
3968 return $this->mTitle->getTemplateLinksFrom();
3973 * Shows a bulletin board style toolbar for common editing functions.
3974 * It can be disabled in the user preferences.
3976 * @param Title $title Title object for the page being edited (optional)
3977 * @return string
3979 public static function getEditToolbar( $title = null ) {
3980 global $wgContLang, $wgOut;
3981 global $wgEnableUploads, $wgForeignFileRepos;
3983 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3984 $showSignature = true;
3985 if ( $title ) {
3986 $showSignature = MWNamespace::wantSignatures( $title->getNamespace() );
3990 * $toolarray is an array of arrays each of which includes the
3991 * opening tag, the closing tag, optionally a sample text that is
3992 * inserted between the two when no selection is highlighted
3993 * and. The tip text is shown when the user moves the mouse
3994 * over the button.
3996 * Images are defined in ResourceLoaderEditToolbarModule.
3998 $toolarray = [
4000 'id' => 'mw-editbutton-bold',
4001 'open' => '\'\'\'',
4002 'close' => '\'\'\'',
4003 'sample' => wfMessage( 'bold_sample' )->text(),
4004 'tip' => wfMessage( 'bold_tip' )->text(),
4007 'id' => 'mw-editbutton-italic',
4008 'open' => '\'\'',
4009 'close' => '\'\'',
4010 'sample' => wfMessage( 'italic_sample' )->text(),
4011 'tip' => wfMessage( 'italic_tip' )->text(),
4014 'id' => 'mw-editbutton-link',
4015 'open' => '[[',
4016 'close' => ']]',
4017 'sample' => wfMessage( 'link_sample' )->text(),
4018 'tip' => wfMessage( 'link_tip' )->text(),
4021 'id' => 'mw-editbutton-extlink',
4022 'open' => '[',
4023 'close' => ']',
4024 'sample' => wfMessage( 'extlink_sample' )->text(),
4025 'tip' => wfMessage( 'extlink_tip' )->text(),
4028 'id' => 'mw-editbutton-headline',
4029 'open' => "\n== ",
4030 'close' => " ==\n",
4031 'sample' => wfMessage( 'headline_sample' )->text(),
4032 'tip' => wfMessage( 'headline_tip' )->text(),
4034 $imagesAvailable ? [
4035 'id' => 'mw-editbutton-image',
4036 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
4037 'close' => ']]',
4038 'sample' => wfMessage( 'image_sample' )->text(),
4039 'tip' => wfMessage( 'image_tip' )->text(),
4040 ] : false,
4041 $imagesAvailable ? [
4042 'id' => 'mw-editbutton-media',
4043 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
4044 'close' => ']]',
4045 'sample' => wfMessage( 'media_sample' )->text(),
4046 'tip' => wfMessage( 'media_tip' )->text(),
4047 ] : false,
4049 'id' => 'mw-editbutton-nowiki',
4050 'open' => "<nowiki>",
4051 'close' => "</nowiki>",
4052 'sample' => wfMessage( 'nowiki_sample' )->text(),
4053 'tip' => wfMessage( 'nowiki_tip' )->text(),
4055 $showSignature ? [
4056 'id' => 'mw-editbutton-signature',
4057 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4058 'close' => '',
4059 'sample' => '',
4060 'tip' => wfMessage( 'sig_tip' )->text(),
4061 ] : false,
4063 'id' => 'mw-editbutton-hr',
4064 'open' => "\n----\n",
4065 'close' => '',
4066 'sample' => '',
4067 'tip' => wfMessage( 'hr_tip' )->text(),
4071 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4072 foreach ( $toolarray as $tool ) {
4073 if ( !$tool ) {
4074 continue;
4077 $params = [
4078 // Images are defined in ResourceLoaderEditToolbarModule
4079 false,
4080 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4081 // Older browsers show a "speedtip" type message only for ALT.
4082 // Ideally these should be different, realistically they
4083 // probably don't need to be.
4084 $tool['tip'],
4085 $tool['open'],
4086 $tool['close'],
4087 $tool['sample'],
4088 $tool['id'],
4091 $script .= Xml::encodeJsCall(
4092 'mw.toolbar.addButton',
4093 $params,
4094 ResourceLoader::inDebugMode()
4098 $script .= '});';
4099 $wgOut->addScript( ResourceLoader::makeInlineScript( $script ) );
4101 $toolbar = '<div id="toolbar"></div>';
4103 Hooks::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] );
4105 return $toolbar;
4109 * Return an array of checkbox definitions.
4111 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4113 * Array values are associative arrays with the following keys:
4114 * - 'label-message' (required): message for label text
4115 * - 'id' (required): 'id' attribute for the `<input>`
4116 * - 'default' (required): default checkedness (true or false)
4117 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4118 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4119 * from messages like 'tooltip-foo', 'accesskey-foo'
4120 * - 'label-id' (optional): 'id' attribute for the `<label>`
4121 * - 'legacy-name' (optional): short name for backwards-compatibility
4122 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4123 * where bool indicates the checked status of the checkbox
4124 * @return array
4126 protected function getCheckboxesDefinition( $checked ) {
4127 global $wgUser;
4128 $checkboxes = [];
4130 // don't show the minor edit checkbox if it's a new page or section
4131 if ( !$this->isNew && $wgUser->isAllowed( 'minoredit' ) ) {
4132 $checkboxes['wpMinoredit'] = [
4133 'id' => 'wpMinoredit',
4134 'label-message' => 'minoredit',
4135 // Uses messages: tooltip-minoredit, accesskey-minoredit
4136 'tooltip' => 'minoredit',
4137 'label-id' => 'mw-editpage-minoredit',
4138 'legacy-name' => 'minor',
4139 'default' => $checked['minor'],
4143 if ( $wgUser->isLoggedIn() ) {
4144 $checkboxes['wpWatchthis'] = [
4145 'id' => 'wpWatchthis',
4146 'label-message' => 'watchthis',
4147 // Uses messages: tooltip-watch, accesskey-watch
4148 'tooltip' => 'watch',
4149 'label-id' => 'mw-editpage-watch',
4150 'legacy-name' => 'watch',
4151 'default' => $checked['watch'],
4155 $editPage = $this;
4156 Hooks::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4158 return $checkboxes;
4162 * Returns an array of html code of the following checkboxes old style:
4163 * minor and watch
4165 * @param int $tabindex Current tabindex
4166 * @param array $checked See getCheckboxesDefinition()
4167 * @return array
4169 public function getCheckboxes( &$tabindex, $checked ) {
4170 global $wgUseMediaWikiUIEverywhere;
4172 $checkboxes = [];
4173 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4175 // Backwards-compatibility for the EditPageBeforeEditChecks hook
4176 if ( !$this->isNew ) {
4177 $checkboxes['minor'] = '';
4179 $checkboxes['watch'] = '';
4181 foreach ( $checkboxesDef as $name => $options ) {
4182 $legacyName = isset( $options['legacy-name'] ) ? $options['legacy-name'] : $name;
4183 $label = $this->context->msg( $options['label-message'] )->parse();
4184 $attribs = [
4185 'tabindex' => ++$tabindex,
4186 'id' => $options['id'],
4188 $labelAttribs = [
4189 'for' => $options['id'],
4191 if ( isset( $options['tooltip'] ) ) {
4192 $attribs['accesskey'] = $this->context->msg( "accesskey-{$options['tooltip']}" )->text();
4193 $labelAttribs['title'] = Linker::titleAttrib( $options['tooltip'], 'withaccess' );
4195 if ( isset( $options['title-message'] ) ) {
4196 $labelAttribs['title'] = $this->context->msg( $options['title-message'] )->text();
4198 if ( isset( $options['label-id'] ) ) {
4199 $labelAttribs['id'] = $options['label-id'];
4201 $checkboxHtml =
4202 Xml::check( $name, $options['default'], $attribs ) .
4203 '&#160;' .
4204 Xml::tags( 'label', $labelAttribs, $label );
4206 if ( $wgUseMediaWikiUIEverywhere ) {
4207 $checkboxHtml = Html::rawElement( 'div', [ 'class' => 'mw-ui-checkbox' ], $checkboxHtml );
4210 $checkboxes[ $legacyName ] = $checkboxHtml;
4213 // Avoid PHP 7.1 warning of passing $this by reference
4214 $editPage = $this;
4215 Hooks::run( 'EditPageBeforeEditChecks', [ &$editPage, &$checkboxes, &$tabindex ], '1.29' );
4216 return $checkboxes;
4220 * Returns an array of html code of the following checkboxes:
4221 * minor and watch
4223 * @param int $tabindex Current tabindex
4224 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4225 * status of the checkbox
4227 * @return array
4229 public function getCheckboxesOOUI( &$tabindex, $checked ) {
4230 $checkboxes = [];
4231 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4233 $origTabindex = $tabindex;
4235 foreach ( $checkboxesDef as $name => $options ) {
4236 $legacyName = isset( $options['legacy-name'] ) ? $options['legacy-name'] : $name;
4238 $title = null;
4239 $accesskey = null;
4240 if ( isset( $options['tooltip'] ) ) {
4241 $accesskey = $this->context->msg( "accesskey-{$options['tooltip']}" )->text();
4242 $title = Linker::titleAttrib( $options['tooltip'], 'withaccess' );
4244 if ( isset( $options['title-message'] ) ) {
4245 $title = $this->context->msg( $options['title-message'] )->text();
4247 if ( isset( $options['label-id'] ) ) {
4248 $labelAttribs['id'] = $options['label-id'];
4251 $checkboxes[ $legacyName ] = new OOUI\FieldLayout(
4252 new OOUI\CheckboxInputWidget( [
4253 'tabIndex' => ++$tabindex,
4254 'accessKey' => $accesskey,
4255 'id' => $options['id'],
4256 'name' => $name,
4257 'selected' => $options['default'],
4258 'infusable' => true,
4259 ] ),
4261 'align' => 'inline',
4262 'label' => new OOUI\HtmlSnippet( $this->context->msg( $options['label-message'] )->parse() ),
4263 'title' => $title,
4264 'id' => isset( $options['label-id'] ) ? $options['label-id'] : null,
4269 // Backwards-compatibility hack to run the EditPageBeforeEditChecks hook. It's important,
4270 // people have used it for the weirdest things completely unrelated to checkboxes...
4271 // And if we're gonna run it, might as well allow its legacy checkboxes to be shown.
4272 $legacyCheckboxes = $this->getCheckboxes( $origTabindex, $checked );
4273 foreach ( $legacyCheckboxes as $name => $html ) {
4274 if ( $html && !isset( $checkboxes[$name] ) ) {
4275 $checkboxes[$name] = new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $html ) ] );
4279 return $checkboxes;
4283 * Returns an array of html code of the following buttons:
4284 * save, diff and preview
4286 * @param int $tabindex Current tabindex
4288 * @return array
4290 public function getEditButtons( &$tabindex ) {
4291 $buttons = [];
4293 $labelAsPublish =
4294 $this->mArticle->getContext()->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4296 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4297 if ( $labelAsPublish ) {
4298 $buttonLabelKey = !$this->mTitle->exists() ? 'publishpage' : 'publishchanges';
4299 } else {
4300 $buttonLabelKey = !$this->mTitle->exists() ? 'savearticle' : 'savechanges';
4302 $attribs = [
4303 'id' => 'wpSave',
4304 'name' => 'wpSave',
4305 'tabindex' => ++$tabindex,
4306 ] + Linker::tooltipAndAccesskeyAttribs( 'save' );
4308 if ( $this->oouiEnabled ) {
4309 $saveConfig = OOUI\Element::configFromHtmlAttributes( $attribs );
4310 $buttons['save'] = new OOUI\ButtonInputWidget( [
4311 'flags' => [ 'constructive', 'primary' ],
4312 'label' => $this->context->msg( $buttonLabelKey )->text(),
4313 'infusable' => true,
4314 'type' => 'submit',
4315 ] + $saveConfig );
4316 } else {
4317 $buttons['save'] = Html::submitButton(
4318 $this->context->msg( $buttonLabelKey )->text(),
4319 $attribs,
4320 [ 'mw-ui-progressive' ]
4324 $attribs = [
4325 'id' => 'wpPreview',
4326 'name' => 'wpPreview',
4327 'tabindex' => ++$tabindex,
4328 ] + Linker::tooltipAndAccesskeyAttribs( 'preview' );
4329 if ( $this->oouiEnabled ) {
4330 $previewConfig = OOUI\Element::configFromHtmlAttributes( $attribs );
4331 $buttons['preview'] = new OOUI\ButtonInputWidget( [
4332 'label' => $this->context->msg( 'showpreview' )->text(),
4333 'infusable' => true,
4334 'type' => 'submit'
4335 ] + $previewConfig );
4336 } else {
4337 $buttons['preview'] = Html::submitButton(
4338 $this->context->msg( 'showpreview' )->text(),
4339 $attribs
4342 $attribs = [
4343 'id' => 'wpDiff',
4344 'name' => 'wpDiff',
4345 'tabindex' => ++$tabindex,
4346 ] + Linker::tooltipAndAccesskeyAttribs( 'diff' );
4347 if ( $this->oouiEnabled ) {
4348 $diffConfig = OOUI\Element::configFromHtmlAttributes( $attribs );
4349 $buttons['diff'] = new OOUI\ButtonInputWidget( [
4350 'label' => $this->context->msg( 'showdiff' )->text(),
4351 'infusable' => true,
4352 'type' => 'submit',
4353 ] + $diffConfig );
4354 } else {
4355 $buttons['diff'] = Html::submitButton(
4356 $this->context->msg( 'showdiff' )->text(),
4357 $attribs
4361 // Avoid PHP 7.1 warning of passing $this by reference
4362 $editPage = $this;
4363 Hooks::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4365 return $buttons;
4369 * Creates a basic error page which informs the user that
4370 * they have attempted to edit a nonexistent section.
4372 public function noSuchSectionPage() {
4373 global $wgOut;
4375 $wgOut->prepareErrorPage( $this->context->msg( 'nosuchsectiontitle' ) );
4377 $res = $this->context->msg( 'nosuchsectiontext', $this->section )->parseAsBlock();
4379 // Avoid PHP 7.1 warning of passing $this by reference
4380 $editPage = $this;
4381 Hooks::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4382 $wgOut->addHTML( $res );
4384 $wgOut->returnToMain( false, $this->mTitle );
4388 * Show "your edit contains spam" page with your diff and text
4390 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4392 public function spamPageWithContent( $match = false ) {
4393 global $wgOut, $wgLang;
4394 $this->textbox2 = $this->textbox1;
4396 if ( is_array( $match ) ) {
4397 $match = $wgLang->listToText( $match );
4399 $wgOut->prepareErrorPage( $this->context->msg( 'spamprotectiontitle' ) );
4401 $wgOut->addHTML( '<div id="spamprotected">' );
4402 $wgOut->addWikiMsg( 'spamprotectiontext' );
4403 if ( $match ) {
4404 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4406 $wgOut->addHTML( '</div>' );
4408 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4409 $this->showDiff();
4411 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4412 $this->showTextbox2();
4414 $wgOut->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4418 * Check if the browser is on a blacklist of user-agents known to
4419 * mangle UTF-8 data on form submission. Returns true if Unicode
4420 * should make it through, false if it's known to be a problem.
4421 * @return bool
4423 private function checkUnicodeCompliantBrowser() {
4424 global $wgBrowserBlackList, $wgRequest;
4426 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
4427 if ( $currentbrowser === false ) {
4428 // No User-Agent header sent? Trust it by default...
4429 return true;
4432 foreach ( $wgBrowserBlackList as $browser ) {
4433 if ( preg_match( $browser, $currentbrowser ) ) {
4434 return false;
4437 return true;
4441 * Filter an input field through a Unicode de-armoring process if it
4442 * came from an old browser with known broken Unicode editing issues.
4444 * @param WebRequest $request
4445 * @param string $field
4446 * @return string
4448 protected function safeUnicodeInput( $request, $field ) {
4449 $text = rtrim( $request->getText( $field ) );
4450 return $request->getBool( 'safemode' )
4451 ? $this->unmakeSafe( $text )
4452 : $text;
4456 * Filter an output field through a Unicode armoring process if it is
4457 * going to an old browser with known broken Unicode editing issues.
4459 * @param string $text
4460 * @return string
4462 protected function safeUnicodeOutput( $text ) {
4463 return $this->checkUnicodeCompliantBrowser()
4464 ? $text
4465 : $this->makeSafe( $text );
4469 * A number of web browsers are known to corrupt non-ASCII characters
4470 * in a UTF-8 text editing environment. To protect against this,
4471 * detected browsers will be served an armored version of the text,
4472 * with non-ASCII chars converted to numeric HTML character references.
4474 * Preexisting such character references will have a 0 added to them
4475 * to ensure that round-trips do not alter the original data.
4477 * @param string $invalue
4478 * @return string
4480 private function makeSafe( $invalue ) {
4481 // Armor existing references for reversibility.
4482 $invalue = strtr( $invalue, [ "&#x" => "&#x0" ] );
4484 $bytesleft = 0;
4485 $result = "";
4486 $working = 0;
4487 $valueLength = strlen( $invalue );
4488 for ( $i = 0; $i < $valueLength; $i++ ) {
4489 $bytevalue = ord( $invalue[$i] );
4490 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4491 $result .= chr( $bytevalue );
4492 $bytesleft = 0;
4493 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4494 $working = $working << 6;
4495 $working += ( $bytevalue & 0x3F );
4496 $bytesleft--;
4497 if ( $bytesleft <= 0 ) {
4498 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4500 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4501 $working = $bytevalue & 0x1F;
4502 $bytesleft = 1;
4503 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4504 $working = $bytevalue & 0x0F;
4505 $bytesleft = 2;
4506 } else { // 1111 0xxx
4507 $working = $bytevalue & 0x07;
4508 $bytesleft = 3;
4511 return $result;
4515 * Reverse the previously applied transliteration of non-ASCII characters
4516 * back to UTF-8. Used to protect data from corruption by broken web browsers
4517 * as listed in $wgBrowserBlackList.
4519 * @param string $invalue
4520 * @return string
4522 private function unmakeSafe( $invalue ) {
4523 $result = "";
4524 $valueLength = strlen( $invalue );
4525 for ( $i = 0; $i < $valueLength; $i++ ) {
4526 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
4527 $i += 3;
4528 $hexstring = "";
4529 do {
4530 $hexstring .= $invalue[$i];
4531 $i++;
4532 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4534 // Do some sanity checks. These aren't needed for reversibility,
4535 // but should help keep the breakage down if the editor
4536 // breaks one of the entities whilst editing.
4537 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4538 $codepoint = hexdec( $hexstring );
4539 $result .= UtfNormal\Utils::codepointToUtf8( $codepoint );
4540 } else {
4541 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4543 } else {
4544 $result .= substr( $invalue, $i, 1 );
4547 // reverse the transform that we made for reversibility reasons.
4548 return strtr( $result, [ "&#x0" => "&#x" ] );
4552 * @since 1.29
4554 protected function addEditNotices() {
4555 global $wgOut;
4557 $editNotices = $this->mTitle->getEditNotices( $this->oldid );
4558 if ( count( $editNotices ) ) {
4559 $wgOut->addHTML( implode( "\n", $editNotices ) );
4560 } else {
4561 $msg = $this->context->msg( 'editnotice-notext' );
4562 if ( !$msg->isDisabled() ) {
4563 $wgOut->addHTML(
4564 '<div class="mw-editnotice-notext">'
4565 . $msg->parseAsBlock()
4566 . '</div>'
4573 * @since 1.29
4575 protected function addTalkPageText() {
4576 global $wgOut;
4578 if ( $this->mTitle->isTalkPage() ) {
4579 $wgOut->addWikiMsg( 'talkpagetext' );
4584 * @since 1.29
4586 protected function addLongPageWarningHeader() {
4587 global $wgMaxArticleSize, $wgOut, $wgLang;
4589 if ( $this->contentLength === false ) {
4590 $this->contentLength = strlen( $this->textbox1 );
4593 if ( $this->tooBig || $this->contentLength > $wgMaxArticleSize * 1024 ) {
4594 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4596 'longpageerror',
4597 $wgLang->formatNum( round( $this->contentLength / 1024, 3 ) ),
4598 $wgLang->formatNum( $wgMaxArticleSize )
4601 } else {
4602 if ( !$this->context->msg( 'longpage-hint' )->isDisabled() ) {
4603 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4605 'longpage-hint',
4606 $wgLang->formatSize( strlen( $this->textbox1 ) ),
4607 strlen( $this->textbox1 )
4615 * @since 1.29
4617 protected function addPageProtectionWarningHeaders() {
4618 global $wgOut;
4620 if ( $this->mTitle->isProtected( 'edit' ) &&
4621 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== [ '' ]
4623 # Is the title semi-protected?
4624 if ( $this->mTitle->isSemiProtected() ) {
4625 $noticeMsg = 'semiprotectedpagewarning';
4626 } else {
4627 # Then it must be protected based on static groups (regular)
4628 $noticeMsg = 'protectedpagewarning';
4630 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
4631 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4633 if ( $this->mTitle->isCascadeProtected() ) {
4634 # Is this page under cascading protection from some source pages?
4635 /** @var Title[] $cascadeSources */
4636 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
4637 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4638 $cascadeSourcesCount = count( $cascadeSources );
4639 if ( $cascadeSourcesCount > 0 ) {
4640 # Explain, and list the titles responsible
4641 foreach ( $cascadeSources as $page ) {
4642 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4645 $notice .= '</div>';
4646 $wgOut->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4648 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
4649 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
4650 [ 'lim' => 1,
4651 'showIfEmpty' => false,
4652 'msgKey' => [ 'titleprotectedwarning' ],
4653 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4658 * @param OutputPage $out
4659 * @since 1.29
4661 protected function addExplainConflictHeader( OutputPage $out ) {
4662 $out->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
4666 * @param string $name
4667 * @param mixed[] $customAttribs
4668 * @param User $user
4669 * @return mixed[]
4670 * @since 1.29
4672 protected function buildTextboxAttribs( $name, array $customAttribs, User $user ) {
4673 $attribs = $customAttribs + [
4674 'accesskey' => ',',
4675 'id' => $name,
4676 'cols' => 80,
4677 'rows' => 25,
4678 // Avoid PHP notices when appending preferences
4679 // (appending allows customAttribs['style'] to still work).
4680 'style' => ''
4683 // The following classes can be used here:
4684 // * mw-editfont-default
4685 // * mw-editfont-monospace
4686 // * mw-editfont-sans-serif
4687 // * mw-editfont-serif
4688 $class = 'mw-editfont-' . $user->getOption( 'editfont' );
4690 if ( isset( $attribs['class'] ) ) {
4691 if ( is_string( $attribs['class'] ) ) {
4692 $attribs['class'] .= ' ' . $class;
4693 } elseif ( is_array( $attribs['class'] ) ) {
4694 $attribs['class'][] = $class;
4696 } else {
4697 $attribs['class'] = $class;
4700 $pageLang = $this->mTitle->getPageLanguage();
4701 $attribs['lang'] = $pageLang->getHtmlCode();
4702 $attribs['dir'] = $pageLang->getDir();
4704 return $attribs;
4708 * @param string $wikitext
4709 * @return string
4710 * @since 1.29
4712 protected function addNewLineAtEnd( $wikitext ) {
4713 if ( strval( $wikitext ) !== '' ) {
4714 // Ensure there's a newline at the end, otherwise adding lines
4715 // is awkward.
4716 // But don't add a newline if the text is empty, or Firefox in XHTML
4717 // mode will show an extra newline. A bit annoying.
4718 $wikitext .= "\n";
4719 return $wikitext;
4721 return $wikitext;