Special case opus mime detction
[mediawiki.git] / includes / EditPage.php
blob05fa366ebafb5286b2385bd0e2b446995eb2431c
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 null|string */
367 public $contentModel = null;
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 * @param Article $article
419 public function __construct( Article $article ) {
420 $this->mArticle = $article;
421 $this->page = $article->getPage(); // model object
422 $this->mTitle = $article->getTitle();
423 $this->context = $article->getContext();
425 $this->contentModel = $this->mTitle->getContentModel();
427 $handler = ContentHandler::getForModelID( $this->contentModel );
428 $this->contentFormat = $handler->getDefaultFormat();
432 * @return Article
434 public function getArticle() {
435 return $this->mArticle;
439 * @since 1.28
440 * @return IContextSource
442 public function getContext() {
443 return $this->context;
447 * @since 1.19
448 * @return Title
450 public function getTitle() {
451 return $this->mTitle;
455 * Set the context Title object
457 * @param Title|null $title Title object or null
459 public function setContextTitle( $title ) {
460 $this->mContextTitle = $title;
464 * Get the context title object.
465 * If not set, $wgTitle will be returned. This behavior might change in
466 * the future to return $this->mTitle instead.
468 * @return Title
470 public function getContextTitle() {
471 if ( is_null( $this->mContextTitle ) ) {
472 global $wgTitle;
473 return $wgTitle;
474 } else {
475 return $this->mContextTitle;
480 * Returns if the given content model is editable.
482 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
483 * @return bool
484 * @throws MWException If $modelId has no known handler
486 public function isSupportedContentModel( $modelId ) {
487 return $this->enableApiEditOverride === true ||
488 ContentHandler::getForModelID( $modelId )->supportsDirectEditing();
492 * Allow editing of content that supports API direct editing, but not general
493 * direct editing. Set to false by default.
495 * @param bool $enableOverride
497 public function setApiEditOverride( $enableOverride ) {
498 $this->enableApiEditOverride = $enableOverride;
501 function submit() {
502 $this->edit();
506 * This is the function that gets called for "action=edit". It
507 * sets up various member variables, then passes execution to
508 * another function, usually showEditForm()
510 * The edit form is self-submitting, so that when things like
511 * preview and edit conflicts occur, we get the same form back
512 * with the extra stuff added. Only when the final submission
513 * is made and all is well do we actually save and redirect to
514 * the newly-edited page.
516 function edit() {
517 global $wgOut, $wgRequest, $wgUser;
518 // Allow extensions to modify/prevent this form or submission
519 if ( !Hooks::run( 'AlternateEdit', [ $this ] ) ) {
520 return;
523 wfDebug( __METHOD__ . ": enter\n" );
525 // If they used redlink=1 and the page exists, redirect to the main article
526 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
527 $wgOut->redirect( $this->mTitle->getFullURL() );
528 return;
531 $this->importFormData( $wgRequest );
532 $this->firsttime = false;
534 if ( wfReadOnly() && $this->save ) {
535 // Force preview
536 $this->save = false;
537 $this->preview = true;
540 if ( $this->save ) {
541 $this->formtype = 'save';
542 } elseif ( $this->preview ) {
543 $this->formtype = 'preview';
544 } elseif ( $this->diff ) {
545 $this->formtype = 'diff';
546 } else { # First time through
547 $this->firsttime = true;
548 if ( $this->previewOnOpen() ) {
549 $this->formtype = 'preview';
550 } else {
551 $this->formtype = 'initial';
555 $permErrors = $this->getEditPermissionErrors( $this->save ? 'secure' : 'full' );
556 if ( $permErrors ) {
557 wfDebug( __METHOD__ . ": User can't edit\n" );
558 // Auto-block user's IP if the account was "hard" blocked
559 if ( !wfReadOnly() ) {
560 $user = $wgUser;
561 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
562 $user->spreadAnyEditBlock();
563 } );
565 $this->displayPermissionsError( $permErrors );
567 return;
570 $revision = $this->mArticle->getRevisionFetched();
571 // Disallow editing revisions with content models different from the current one
572 // Undo edits being an exception in order to allow reverting content model changes.
573 if ( $revision
574 && $revision->getContentModel() !== $this->contentModel
576 $prevRev = null;
577 if ( $this->undidRev ) {
578 $undidRevObj = Revision::newFromId( $this->undidRev );
579 $prevRev = $undidRevObj ? $undidRevObj->getPrevious() : null;
581 if ( !$this->undidRev
582 || !$prevRev
583 || $prevRev->getContentModel() !== $this->contentModel
585 $this->displayViewSourcePage(
586 $this->getContentObject(),
587 $this->context->msg(
588 'contentmodelediterror',
589 $revision->getContentModel(),
590 $this->contentModel
591 )->plain()
593 return;
597 $this->isConflict = false;
598 // css / js subpages of user pages get a special treatment
599 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
600 $this->isCssSubpage = $this->mTitle->isCssSubpage();
601 $this->isJsSubpage = $this->mTitle->isJsSubpage();
602 // @todo FIXME: Silly assignment.
603 $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
605 # Show applicable editing introductions
606 if ( $this->formtype == 'initial' || $this->firsttime ) {
607 $this->showIntro();
610 # Attempt submission here. This will check for edit conflicts,
611 # and redundantly check for locked database, blocked IPs, etc.
612 # that edit() already checked just in case someone tries to sneak
613 # in the back door with a hand-edited submission URL.
615 if ( 'save' == $this->formtype ) {
616 $resultDetails = null;
617 $status = $this->attemptSave( $resultDetails );
618 if ( !$this->handleStatus( $status, $resultDetails ) ) {
619 return;
623 # First time through: get contents, set time for conflict
624 # checking, etc.
625 if ( 'initial' == $this->formtype || $this->firsttime ) {
626 if ( $this->initialiseForm() === false ) {
627 $this->noSuchSectionPage();
628 return;
631 if ( !$this->mTitle->getArticleID() ) {
632 Hooks::run( 'EditFormPreloadText', [ &$this->textbox1, &$this->mTitle ] );
633 } else {
634 Hooks::run( 'EditFormInitialText', [ $this ] );
639 $this->showEditForm();
643 * @param string $rigor Same format as Title::getUserPermissionErrors()
644 * @return array
646 protected function getEditPermissionErrors( $rigor = 'secure' ) {
647 global $wgUser;
649 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
650 # Can this title be created?
651 if ( !$this->mTitle->exists() ) {
652 $permErrors = array_merge(
653 $permErrors,
654 wfArrayDiff2(
655 $this->mTitle->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
656 $permErrors
660 # Ignore some permissions errors when a user is just previewing/viewing diffs
661 $remove = [];
662 foreach ( $permErrors as $error ) {
663 if ( ( $this->preview || $this->diff )
664 && (
665 $error[0] == 'blockedtext' ||
666 $error[0] == 'autoblockedtext' ||
667 $error[0] == 'systemblockedtext'
670 $remove[] = $error;
673 $permErrors = wfArrayDiff2( $permErrors, $remove );
675 return $permErrors;
679 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
680 * but with the following differences:
681 * - If redlink=1, the user will be redirected to the page
682 * - If there is content to display or the error occurs while either saving,
683 * previewing or showing the difference, it will be a
684 * "View source for ..." page displaying the source code after the error message.
686 * @since 1.19
687 * @param array $permErrors Array of permissions errors, as returned by
688 * Title::getUserPermissionsErrors().
689 * @throws PermissionsError
691 protected function displayPermissionsError( array $permErrors ) {
692 global $wgRequest, $wgOut;
694 if ( $wgRequest->getBool( 'redlink' ) ) {
695 // The edit page was reached via a red link.
696 // Redirect to the article page and let them click the edit tab if
697 // they really want a permission error.
698 $wgOut->redirect( $this->mTitle->getFullURL() );
699 return;
702 $content = $this->getContentObject();
704 # Use the normal message if there's nothing to display
705 if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
706 $action = $this->mTitle->exists() ? 'edit' :
707 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
708 throw new PermissionsError( $action, $permErrors );
711 $this->displayViewSourcePage(
712 $content,
713 $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' )
718 * Display a read-only View Source page
719 * @param Content $content content object
720 * @param string $errorMessage additional wikitext error message to display
722 protected function displayViewSourcePage( Content $content, $errorMessage = '' ) {
723 global $wgOut;
725 Hooks::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$wgOut ] );
727 $wgOut->setRobotPolicy( 'noindex,nofollow' );
728 $wgOut->setPageTitle( $this->context->msg(
729 'viewsource-title',
730 $this->getContextTitle()->getPrefixedText()
731 ) );
732 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
733 $wgOut->addHTML( $this->editFormPageTop );
734 $wgOut->addHTML( $this->editFormTextTop );
736 if ( $errorMessage !== '' ) {
737 $wgOut->addWikiText( $errorMessage );
738 $wgOut->addHTML( "<hr />\n" );
741 # If the user made changes, preserve them when showing the markup
742 # (This happens when a user is blocked during edit, for instance)
743 if ( !$this->firsttime ) {
744 $text = $this->textbox1;
745 $wgOut->addWikiMsg( 'viewyourtext' );
746 } else {
747 try {
748 $text = $this->toEditText( $content );
749 } catch ( MWException $e ) {
750 # Serialize using the default format if the content model is not supported
751 # (e.g. for an old revision with a different model)
752 $text = $content->serialize();
754 $wgOut->addWikiMsg( 'viewsourcetext' );
757 $wgOut->addHTML( $this->editFormTextBeforeContent );
758 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
759 $wgOut->addHTML( $this->editFormTextAfterContent );
761 $wgOut->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
763 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
765 $wgOut->addHTML( $this->editFormTextBottom );
766 if ( $this->mTitle->exists() ) {
767 $wgOut->returnToMain( null, $this->mTitle );
772 * Should we show a preview when the edit form is first shown?
774 * @return bool
776 protected function previewOnOpen() {
777 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
778 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
779 // Explicit override from request
780 return true;
781 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
782 // Explicit override from request
783 return false;
784 } elseif ( $this->section == 'new' ) {
785 // Nothing *to* preview for new sections
786 return false;
787 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() )
788 && $wgUser->getOption( 'previewonfirst' )
790 // Standard preference behavior
791 return true;
792 } elseif ( !$this->mTitle->exists()
793 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
794 && $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]
796 // Categories are special
797 return true;
798 } else {
799 return false;
804 * Checks whether the user entered a skin name in uppercase,
805 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
807 * @return bool
809 protected function isWrongCaseCssJsPage() {
810 if ( $this->mTitle->isCssJsSubpage() ) {
811 $name = $this->mTitle->getSkinFromCssJsSubpage();
812 $skins = array_merge(
813 array_keys( Skin::getSkinNames() ),
814 [ 'common' ]
816 return !in_array( $name, $skins )
817 && in_array( strtolower( $name ), $skins );
818 } else {
819 return false;
824 * Returns whether section editing is supported for the current page.
825 * Subclasses may override this to replace the default behavior, which is
826 * to check ContentHandler::supportsSections.
828 * @return bool True if this edit page supports sections, false otherwise.
830 protected function isSectionEditSupported() {
831 $contentHandler = ContentHandler::getForTitle( $this->mTitle );
832 return $contentHandler->supportsSections();
836 * This function collects the form data and uses it to populate various member variables.
837 * @param WebRequest $request
838 * @throws ErrorPageError
840 function importFormData( &$request ) {
841 global $wgContLang, $wgUser;
843 # Section edit can come from either the form or a link
844 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
846 if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
847 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
850 $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
852 if ( $request->wasPosted() ) {
853 # These fields need to be checked for encoding.
854 # Also remove trailing whitespace, but don't remove _initial_
855 # whitespace from the text boxes. This may be significant formatting.
856 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
857 if ( !$request->getCheck( 'wpTextbox2' ) ) {
858 // Skip this if wpTextbox2 has input, it indicates that we came
859 // from a conflict page with raw page text, not a custom form
860 // modified by subclasses
861 $textbox1 = $this->importContentFormData( $request );
862 if ( $textbox1 !== null ) {
863 $this->textbox1 = $textbox1;
867 # Truncate for whole multibyte characters
868 $this->summary = $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
870 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
871 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
872 # section titles.
873 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
875 # Treat sectiontitle the same way as summary.
876 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
877 # currently doing double duty as both edit summary and section title. Right now this
878 # is just to allow API edits to work around this limitation, but this should be
879 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
880 $this->sectiontitle = $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
881 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
883 $this->edittime = $request->getVal( 'wpEdittime' );
884 $this->editRevId = $request->getIntOrNull( 'editRevId' );
885 $this->starttime = $request->getVal( 'wpStarttime' );
887 $undidRev = $request->getInt( 'wpUndidRevision' );
888 if ( $undidRev ) {
889 $this->undidRev = $undidRev;
892 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
894 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
895 // wpTextbox1 field is missing, possibly due to being "too big"
896 // according to some filter rules such as Suhosin's setting for
897 // suhosin.request.max_value_length (d'oh)
898 $this->incompleteForm = true;
899 } else {
900 // If we receive the last parameter of the request, we can fairly
901 // claim the POST request has not been truncated.
903 // TODO: softened the check for cutover. Once we determine
904 // that it is safe, we should complete the transition by
905 // removing the "edittime" clause.
906 $this->incompleteForm = ( !$request->getVal( 'wpUltimateParam' )
907 && is_null( $this->edittime ) );
909 if ( $this->incompleteForm ) {
910 # If the form is incomplete, force to preview.
911 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
912 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
913 $this->preview = true;
914 } else {
915 $this->preview = $request->getCheck( 'wpPreview' );
916 $this->diff = $request->getCheck( 'wpDiff' );
918 // Remember whether a save was requested, so we can indicate
919 // if we forced preview due to session failure.
920 $this->mTriedSave = !$this->preview;
922 if ( $this->tokenOk( $request ) ) {
923 # Some browsers will not report any submit button
924 # if the user hits enter in the comment box.
925 # The unmarked state will be assumed to be a save,
926 # if the form seems otherwise complete.
927 wfDebug( __METHOD__ . ": Passed token check.\n" );
928 } elseif ( $this->diff ) {
929 # Failed token check, but only requested "Show Changes".
930 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
931 } else {
932 # Page might be a hack attempt posted from
933 # an external site. Preview instead of saving.
934 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
935 $this->preview = true;
938 $this->save = !$this->preview && !$this->diff;
939 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
940 $this->edittime = null;
943 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
944 $this->starttime = null;
947 $this->recreate = $request->getCheck( 'wpRecreate' );
949 $this->minoredit = $request->getCheck( 'wpMinoredit' );
950 $this->watchthis = $request->getCheck( 'wpWatchthis' );
952 # Don't force edit summaries when a user is editing their own user or talk page
953 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
954 && $this->mTitle->getText() == $wgUser->getName()
956 $this->allowBlankSummary = true;
957 } else {
958 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
959 || !$wgUser->getOption( 'forceeditsummary' );
962 $this->autoSumm = $request->getText( 'wpAutoSummary' );
964 $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
965 $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
967 $changeTags = $request->getVal( 'wpChangeTags' );
968 if ( is_null( $changeTags ) || $changeTags === '' ) {
969 $this->changeTags = [];
970 } else {
971 $this->changeTags = array_filter( array_map( 'trim', explode( ',',
972 $changeTags ) ) );
974 } else {
975 # Not a posted form? Start with nothing.
976 wfDebug( __METHOD__ . ": Not a posted form.\n" );
977 $this->textbox1 = '';
978 $this->summary = '';
979 $this->sectiontitle = '';
980 $this->edittime = '';
981 $this->editRevId = null;
982 $this->starttime = wfTimestampNow();
983 $this->edit = false;
984 $this->preview = false;
985 $this->save = false;
986 $this->diff = false;
987 $this->minoredit = false;
988 // Watch may be overridden by request parameters
989 $this->watchthis = $request->getBool( 'watchthis', false );
990 $this->recreate = false;
992 // When creating a new section, we can preload a section title by passing it as the
993 // preloadtitle parameter in the URL (Bug 13100)
994 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
995 $this->sectiontitle = $request->getVal( 'preloadtitle' );
996 // Once wpSummary isn't being use for setting section titles, we should delete this.
997 $this->summary = $request->getVal( 'preloadtitle' );
998 } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
999 $this->summary = $request->getText( 'summary' );
1000 if ( $this->summary !== '' ) {
1001 $this->hasPresetSummary = true;
1005 if ( $request->getVal( 'minor' ) ) {
1006 $this->minoredit = true;
1010 $this->oldid = $request->getInt( 'oldid' );
1011 $this->parentRevId = $request->getInt( 'parentRevId' );
1013 $this->bot = $request->getBool( 'bot', true );
1014 $this->nosummary = $request->getBool( 'nosummary' );
1016 // May be overridden by revision.
1017 $this->contentModel = $request->getText( 'model', $this->contentModel );
1018 // May be overridden by revision.
1019 $this->contentFormat = $request->getText( 'format', $this->contentFormat );
1021 try {
1022 $handler = ContentHandler::getForModelID( $this->contentModel );
1023 } catch ( MWUnknownContentModelException $e ) {
1024 throw new ErrorPageError(
1025 'editpage-invalidcontentmodel-title',
1026 'editpage-invalidcontentmodel-text',
1027 [ $this->contentModel ]
1031 if ( !$handler->isSupportedFormat( $this->contentFormat ) ) {
1032 throw new ErrorPageError(
1033 'editpage-notsupportedcontentformat-title',
1034 'editpage-notsupportedcontentformat-text',
1035 [ $this->contentFormat, ContentHandler::getLocalizedName( $this->contentModel ) ]
1040 * @todo Check if the desired model is allowed in this namespace, and if
1041 * a transition from the page's current model to the new model is
1042 * allowed.
1045 $this->editintro = $request->getText( 'editintro',
1046 // Custom edit intro for new sections
1047 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
1049 // Allow extensions to modify form data
1050 Hooks::run( 'EditPage::importFormData', [ $this, $request ] );
1054 * Subpage overridable method for extracting the page content data from the
1055 * posted form to be placed in $this->textbox1, if using customized input
1056 * this method should be overridden and return the page text that will be used
1057 * for saving, preview parsing and so on...
1059 * @param WebRequest $request
1060 * @return string|null
1062 protected function importContentFormData( &$request ) {
1063 return; // Don't do anything, EditPage already extracted wpTextbox1
1067 * Initialise form fields in the object
1068 * Called on the first invocation, e.g. when a user clicks an edit link
1069 * @return bool If the requested section is valid
1071 function initialiseForm() {
1072 global $wgUser;
1073 $this->edittime = $this->page->getTimestamp();
1074 $this->editRevId = $this->page->getLatest();
1076 $content = $this->getContentObject( false ); # TODO: track content object?!
1077 if ( $content === false ) {
1078 return false;
1080 $this->textbox1 = $this->toEditText( $content );
1082 // activate checkboxes if user wants them to be always active
1083 # Sort out the "watch" checkbox
1084 if ( $wgUser->getOption( 'watchdefault' ) ) {
1085 # Watch all edits
1086 $this->watchthis = true;
1087 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1088 # Watch creations
1089 $this->watchthis = true;
1090 } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
1091 # Already watched
1092 $this->watchthis = true;
1094 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
1095 $this->minoredit = true;
1097 if ( $this->textbox1 === false ) {
1098 return false;
1100 return true;
1104 * @param Content|null $def_content The default value to return
1106 * @return Content|null Content on success, $def_content for invalid sections
1108 * @since 1.21
1110 protected function getContentObject( $def_content = null ) {
1111 global $wgOut, $wgRequest, $wgUser, $wgContLang;
1113 $content = false;
1115 // For message page not locally set, use the i18n message.
1116 // For other non-existent articles, use preload text if any.
1117 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
1118 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
1119 # If this is a system message, get the default text.
1120 $msg = $this->mTitle->getDefaultMessageText();
1122 $content = $this->toEditContent( $msg );
1124 if ( $content === false ) {
1125 # If requested, preload some text.
1126 $preload = $wgRequest->getVal( 'preload',
1127 // Custom preload text for new sections
1128 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
1129 $params = $wgRequest->getArray( 'preloadparams', [] );
1131 $content = $this->getPreloadedContent( $preload, $params );
1133 // For existing pages, get text based on "undo" or section parameters.
1134 } else {
1135 if ( $this->section != '' ) {
1136 // Get section edit text (returns $def_text for invalid sections)
1137 $orig = $this->getOriginalContent( $wgUser );
1138 $content = $orig ? $orig->getSection( $this->section ) : null;
1140 if ( !$content ) {
1141 $content = $def_content;
1143 } else {
1144 $undoafter = $wgRequest->getInt( 'undoafter' );
1145 $undo = $wgRequest->getInt( 'undo' );
1147 if ( $undo > 0 && $undoafter > 0 ) {
1148 $undorev = Revision::newFromId( $undo );
1149 $oldrev = Revision::newFromId( $undoafter );
1151 # Sanity check, make sure it's the right page,
1152 # the revisions exist and they were not deleted.
1153 # Otherwise, $content will be left as-is.
1154 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1155 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
1156 !$oldrev->isDeleted( Revision::DELETED_TEXT )
1158 $content = $this->page->getUndoContent( $undorev, $oldrev );
1160 if ( $content === false ) {
1161 # Warn the user that something went wrong
1162 $undoMsg = 'failure';
1163 } else {
1164 $oldContent = $this->page->getContent( Revision::RAW );
1165 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
1166 $newContent = $content->preSaveTransform( $this->mTitle, $wgUser, $popts );
1167 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1168 // The undo may change content
1169 // model if its reverting the top
1170 // edit. This can result in
1171 // mismatched content model/format.
1172 $this->contentModel = $newContent->getModel();
1173 $this->contentFormat = $oldrev->getContentFormat();
1176 if ( $newContent->equals( $oldContent ) ) {
1177 # Tell the user that the undo results in no change,
1178 # i.e. the revisions were already undone.
1179 $undoMsg = 'nochange';
1180 $content = false;
1181 } else {
1182 # Inform the user of our success and set an automatic edit summary
1183 $undoMsg = 'success';
1185 # If we just undid one rev, use an autosummary
1186 $firstrev = $oldrev->getNext();
1187 if ( $firstrev && $firstrev->getId() == $undo ) {
1188 $userText = $undorev->getUserText();
1189 if ( $userText === '' ) {
1190 $undoSummary = $this->context->msg(
1191 'undo-summary-username-hidden',
1192 $undo
1193 )->inContentLanguage()->text();
1194 } else {
1195 $undoSummary = $this->context->msg(
1196 'undo-summary',
1197 $undo,
1198 $userText
1199 )->inContentLanguage()->text();
1201 if ( $this->summary === '' ) {
1202 $this->summary = $undoSummary;
1203 } else {
1204 $this->summary = $undoSummary . $this->context->msg( 'colon-separator' )
1205 ->inContentLanguage()->text() . $this->summary;
1207 $this->undidRev = $undo;
1209 $this->formtype = 'diff';
1212 } else {
1213 // Failed basic sanity checks.
1214 // Older revisions may have been removed since the link
1215 // was created, or we may simply have got bogus input.
1216 $undoMsg = 'norev';
1219 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1220 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1221 $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
1222 $this->context->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1225 if ( $content === false ) {
1226 $content = $this->getOriginalContent( $wgUser );
1231 return $content;
1235 * Get the content of the wanted revision, without section extraction.
1237 * The result of this function can be used to compare user's input with
1238 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1239 * to the original text of the edit.
1241 * This differs from Article::getContent() that when a missing revision is
1242 * encountered the result will be null and not the
1243 * 'missing-revision' message.
1245 * @since 1.19
1246 * @param User $user The user to get the revision for
1247 * @return Content|null
1249 private function getOriginalContent( User $user ) {
1250 if ( $this->section == 'new' ) {
1251 return $this->getCurrentContent();
1253 $revision = $this->mArticle->getRevisionFetched();
1254 if ( $revision === null ) {
1255 if ( !$this->contentModel ) {
1256 $this->contentModel = $this->getTitle()->getContentModel();
1258 $handler = ContentHandler::getForModelID( $this->contentModel );
1260 return $handler->makeEmptyContent();
1262 $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
1263 return $content;
1267 * Get the edit's parent revision ID
1269 * The "parent" revision is the ancestor that should be recorded in this
1270 * page's revision history. It is either the revision ID of the in-memory
1271 * article content, or in the case of a 3-way merge in order to rebase
1272 * across a recoverable edit conflict, the ID of the newer revision to
1273 * which we have rebased this page.
1275 * @since 1.27
1276 * @return int Revision ID
1278 public function getParentRevId() {
1279 if ( $this->parentRevId ) {
1280 return $this->parentRevId;
1281 } else {
1282 return $this->mArticle->getRevIdFetched();
1287 * Get the current content of the page. This is basically similar to
1288 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1289 * content object is returned instead of null.
1291 * @since 1.21
1292 * @return Content
1294 protected function getCurrentContent() {
1295 $rev = $this->page->getRevision();
1296 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1298 if ( $content === false || $content === null ) {
1299 if ( !$this->contentModel ) {
1300 $this->contentModel = $this->getTitle()->getContentModel();
1302 $handler = ContentHandler::getForModelID( $this->contentModel );
1304 return $handler->makeEmptyContent();
1305 } elseif ( !$this->undidRev ) {
1306 // Content models should always be the same since we error
1307 // out if they are different before this point (in ->edit()).
1308 // The exception being, during an undo, the current revision might
1309 // differ from the prior revision.
1310 $logger = LoggerFactory::getInstance( 'editpage' );
1311 if ( $this->contentModel !== $rev->getContentModel() ) {
1312 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1313 'prev' => $this->contentModel,
1314 'new' => $rev->getContentModel(),
1315 'title' => $this->getTitle()->getPrefixedDBkey(),
1316 'method' => __METHOD__
1317 ] );
1318 $this->contentModel = $rev->getContentModel();
1321 // Given that the content models should match, the current selected
1322 // format should be supported.
1323 if ( !$content->isSupportedFormat( $this->contentFormat ) ) {
1324 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1326 'prev' => $this->contentFormat,
1327 'new' => $rev->getContentFormat(),
1328 'title' => $this->getTitle()->getPrefixedDBkey(),
1329 'method' => __METHOD__
1330 ] );
1331 $this->contentFormat = $rev->getContentFormat();
1334 return $content;
1338 * Use this method before edit() to preload some content into the edit box
1340 * @param Content $content
1342 * @since 1.21
1344 public function setPreloadedContent( Content $content ) {
1345 $this->mPreloadContent = $content;
1349 * Get the contents to be preloaded into the box, either set by
1350 * an earlier setPreloadText() or by loading the given page.
1352 * @param string $preload Representing the title to preload from.
1353 * @param array $params Parameters to use (interface-message style) in the preloaded text
1355 * @return Content
1357 * @since 1.21
1359 protected function getPreloadedContent( $preload, $params = [] ) {
1360 global $wgUser;
1362 if ( !empty( $this->mPreloadContent ) ) {
1363 return $this->mPreloadContent;
1366 $handler = ContentHandler::getForModelID( $this->contentModel );
1368 if ( $preload === '' ) {
1369 return $handler->makeEmptyContent();
1372 $title = Title::newFromText( $preload );
1373 # Check for existence to avoid getting MediaWiki:Noarticletext
1374 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1375 // TODO: somehow show a warning to the user!
1376 return $handler->makeEmptyContent();
1379 $page = WikiPage::factory( $title );
1380 if ( $page->isRedirect() ) {
1381 $title = $page->getRedirectTarget();
1382 # Same as before
1383 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1384 // TODO: somehow show a warning to the user!
1385 return $handler->makeEmptyContent();
1387 $page = WikiPage::factory( $title );
1390 $parserOptions = ParserOptions::newFromUser( $wgUser );
1391 $content = $page->getContent( Revision::RAW );
1393 if ( !$content ) {
1394 // TODO: somehow show a warning to the user!
1395 return $handler->makeEmptyContent();
1398 if ( $content->getModel() !== $handler->getModelID() ) {
1399 $converted = $content->convert( $handler->getModelID() );
1401 if ( !$converted ) {
1402 // TODO: somehow show a warning to the user!
1403 wfDebug( "Attempt to preload incompatible content: " .
1404 "can't convert " . $content->getModel() .
1405 " to " . $handler->getModelID() );
1407 return $handler->makeEmptyContent();
1410 $content = $converted;
1413 return $content->preloadTransform( $title, $parserOptions, $params );
1417 * Make sure the form isn't faking a user's credentials.
1419 * @param WebRequest $request
1420 * @return bool
1421 * @private
1423 function tokenOk( &$request ) {
1424 global $wgUser;
1425 $token = $request->getVal( 'wpEditToken' );
1426 $this->mTokenOk = $wgUser->matchEditToken( $token );
1427 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1428 return $this->mTokenOk;
1432 * Sets post-edit cookie indicating the user just saved a particular revision.
1434 * This uses a temporary cookie for each revision ID so separate saves will never
1435 * interfere with each other.
1437 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1438 * the redirect. It must be clearable by JavaScript code, so it must not be
1439 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1440 * variable.
1442 * If the variable were set on the server, it would be cached, which is unwanted
1443 * since the post-edit state should only apply to the load right after the save.
1445 * @param int $statusValue The status value (to check for new article status)
1447 protected function setPostEditCookie( $statusValue ) {
1448 $revisionId = $this->page->getLatest();
1449 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1451 $val = 'saved';
1452 if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1453 $val = 'created';
1454 } elseif ( $this->oldid ) {
1455 $val = 'restored';
1458 $response = RequestContext::getMain()->getRequest()->response();
1459 $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION, [
1460 'httpOnly' => false,
1461 ] );
1465 * Attempt submission
1466 * @param array|bool $resultDetails See docs for $result in internalAttemptSave
1467 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1468 * @return Status The resulting status object.
1470 public function attemptSave( &$resultDetails = false ) {
1471 global $wgUser;
1473 # Allow bots to exempt some edits from bot flagging
1474 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1475 $status = $this->internalAttemptSave( $resultDetails, $bot );
1477 Hooks::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1479 return $status;
1483 * Handle status, such as after attempt save
1485 * @param Status $status
1486 * @param array|bool $resultDetails
1488 * @throws ErrorPageError
1489 * @return bool False, if output is done, true if rest of the form should be displayed
1491 private function handleStatus( Status $status, $resultDetails ) {
1492 global $wgUser, $wgOut;
1495 * @todo FIXME: once the interface for internalAttemptSave() is made
1496 * nicer, this should use the message in $status
1498 if ( $status->value == self::AS_SUCCESS_UPDATE
1499 || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1501 $this->didSave = true;
1502 if ( !$resultDetails['nullEdit'] ) {
1503 $this->setPostEditCookie( $status->value );
1507 // "wpExtraQueryRedirect" is a hidden input to modify
1508 // after save URL and is not used by actual edit form
1509 $request = RequestContext::getMain()->getRequest();
1510 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1512 switch ( $status->value ) {
1513 case self::AS_HOOK_ERROR_EXPECTED:
1514 case self::AS_CONTENT_TOO_BIG:
1515 case self::AS_ARTICLE_WAS_DELETED:
1516 case self::AS_CONFLICT_DETECTED:
1517 case self::AS_SUMMARY_NEEDED:
1518 case self::AS_TEXTBOX_EMPTY:
1519 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1520 case self::AS_END:
1521 case self::AS_BLANK_ARTICLE:
1522 case self::AS_SELF_REDIRECT:
1523 return true;
1525 case self::AS_HOOK_ERROR:
1526 return false;
1528 case self::AS_CANNOT_USE_CUSTOM_MODEL:
1529 case self::AS_PARSE_ERROR:
1530 $wgOut->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1531 return true;
1533 case self::AS_SUCCESS_NEW_ARTICLE:
1534 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1535 if ( $extraQueryRedirect ) {
1536 if ( $query === '' ) {
1537 $query = $extraQueryRedirect;
1538 } else {
1539 $query = $query . '&' . $extraQueryRedirect;
1542 $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1543 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1544 return false;
1546 case self::AS_SUCCESS_UPDATE:
1547 $extraQuery = '';
1548 $sectionanchor = $resultDetails['sectionanchor'];
1550 // Give extensions a chance to modify URL query on update
1551 Hooks::run(
1552 'ArticleUpdateBeforeRedirect',
1553 [ $this->mArticle, &$sectionanchor, &$extraQuery ]
1556 if ( $resultDetails['redirect'] ) {
1557 if ( $extraQuery == '' ) {
1558 $extraQuery = 'redirect=no';
1559 } else {
1560 $extraQuery = 'redirect=no&' . $extraQuery;
1563 if ( $extraQueryRedirect ) {
1564 if ( $extraQuery === '' ) {
1565 $extraQuery = $extraQueryRedirect;
1566 } else {
1567 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1571 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1572 return false;
1574 case self::AS_SPAM_ERROR:
1575 $this->spamPageWithContent( $resultDetails['spam'] );
1576 return false;
1578 case self::AS_BLOCKED_PAGE_FOR_USER:
1579 throw new UserBlockedError( $wgUser->getBlock() );
1581 case self::AS_IMAGE_REDIRECT_ANON:
1582 case self::AS_IMAGE_REDIRECT_LOGGED:
1583 throw new PermissionsError( 'upload' );
1585 case self::AS_READ_ONLY_PAGE_ANON:
1586 case self::AS_READ_ONLY_PAGE_LOGGED:
1587 throw new PermissionsError( 'edit' );
1589 case self::AS_READ_ONLY_PAGE:
1590 throw new ReadOnlyError;
1592 case self::AS_RATE_LIMITED:
1593 throw new ThrottledError();
1595 case self::AS_NO_CREATE_PERMISSION:
1596 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1597 throw new PermissionsError( $permission );
1599 case self::AS_NO_CHANGE_CONTENT_MODEL:
1600 throw new PermissionsError( 'editcontentmodel' );
1602 default:
1603 // We don't recognize $status->value. The only way that can happen
1604 // is if an extension hook aborted from inside ArticleSave.
1605 // Render the status object into $this->hookError
1606 // FIXME this sucks, we should just use the Status object throughout
1607 $this->hookError = '<div class="error">' ."\n" . $status->getWikiText() .
1608 '</div>';
1609 return true;
1614 * Run hooks that can filter edits just before they get saved.
1616 * @param Content $content The Content to filter.
1617 * @param Status $status For reporting the outcome to the caller
1618 * @param User $user The user performing the edit
1620 * @return bool
1622 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1623 // Run old style post-section-merge edit filter
1624 if ( !ContentHandler::runLegacyHooks( 'EditFilterMerged',
1625 [ $this, $content, &$this->hookError, $this->summary ],
1626 '1.21'
1627 ) ) {
1628 # Error messages etc. could be handled within the hook...
1629 $status->fatal( 'hookaborted' );
1630 $status->value = self::AS_HOOK_ERROR;
1631 return false;
1632 } elseif ( $this->hookError != '' ) {
1633 # ...or the hook could be expecting us to produce an error
1634 $status->fatal( 'hookaborted' );
1635 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1636 return false;
1639 // Run new style post-section-merge edit filter
1640 if ( !Hooks::run( 'EditFilterMergedContent',
1641 [ $this->mArticle->getContext(), $content, $status, $this->summary,
1642 $user, $this->minoredit ] )
1644 # Error messages etc. could be handled within the hook...
1645 if ( $status->isGood() ) {
1646 $status->fatal( 'hookaborted' );
1647 // Not setting $this->hookError here is a hack to allow the hook
1648 // to cause a return to the edit page without $this->hookError
1649 // being set. This is used by ConfirmEdit to display a captcha
1650 // without any error message cruft.
1651 } else {
1652 $this->hookError = $status->getWikiText();
1654 // Use the existing $status->value if the hook set it
1655 if ( !$status->value ) {
1656 $status->value = self::AS_HOOK_ERROR;
1658 return false;
1659 } elseif ( !$status->isOK() ) {
1660 # ...or the hook could be expecting us to produce an error
1661 // FIXME this sucks, we should just use the Status object throughout
1662 $this->hookError = $status->getWikiText();
1663 $status->fatal( 'hookaborted' );
1664 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1665 return false;
1668 return true;
1672 * Return the summary to be used for a new section.
1674 * @param string $sectionanchor Set to the section anchor text
1675 * @return string
1677 private function newSectionSummary( &$sectionanchor = null ) {
1678 global $wgParser;
1680 if ( $this->sectiontitle !== '' ) {
1681 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1682 // If no edit summary was specified, create one automatically from the section
1683 // title and have it link to the new section. Otherwise, respect the summary as
1684 // passed.
1685 if ( $this->summary === '' ) {
1686 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1687 return $this->context->msg( 'newsectionsummary' )
1688 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1690 } elseif ( $this->summary !== '' ) {
1691 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1692 # This is a new section, so create a link to the new section
1693 # in the revision summary.
1694 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1695 return $this->context->msg( 'newsectionsummary' )
1696 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1698 return $this->summary;
1702 * Attempt submission (no UI)
1704 * @param array $result Array to add statuses to, currently with the
1705 * possible keys:
1706 * - spam (string): Spam string from content if any spam is detected by
1707 * matchSpamRegex.
1708 * - sectionanchor (string): Section anchor for a section save.
1709 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1710 * false otherwise.
1711 * - redirect (bool): Set if doEditContent is OK. True if resulting
1712 * revision is a redirect.
1713 * @param bool $bot True if edit is being made under the bot right.
1715 * @return Status Status object, possibly with a message, but always with
1716 * one of the AS_* constants in $status->value,
1718 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1719 * various error display idiosyncrasies. There are also lots of cases
1720 * where error metadata is set in the object and retrieved later instead
1721 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1722 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1723 * time.
1725 function internalAttemptSave( &$result, $bot = false ) {
1726 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1727 global $wgContentHandlerUseDB;
1729 $status = Status::newGood();
1731 if ( !Hooks::run( 'EditPage::attemptSave', [ $this ] ) ) {
1732 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1733 $status->fatal( 'hookaborted' );
1734 $status->value = self::AS_HOOK_ERROR;
1735 return $status;
1738 $spam = $wgRequest->getText( 'wpAntispam' );
1739 if ( $spam !== '' ) {
1740 wfDebugLog(
1741 'SimpleAntiSpam',
1742 $wgUser->getName() .
1743 ' editing "' .
1744 $this->mTitle->getPrefixedText() .
1745 '" submitted bogus field "' .
1746 $spam .
1749 $status->fatal( 'spamprotectionmatch', false );
1750 $status->value = self::AS_SPAM_ERROR;
1751 return $status;
1754 try {
1755 # Construct Content object
1756 $textbox_content = $this->toEditContent( $this->textbox1 );
1757 } catch ( MWContentSerializationException $ex ) {
1758 $status->fatal(
1759 'content-failed-to-parse',
1760 $this->contentModel,
1761 $this->contentFormat,
1762 $ex->getMessage()
1764 $status->value = self::AS_PARSE_ERROR;
1765 return $status;
1768 # Check image redirect
1769 if ( $this->mTitle->getNamespace() == NS_FILE &&
1770 $textbox_content->isRedirect() &&
1771 !$wgUser->isAllowed( 'upload' )
1773 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1774 $status->setResult( false, $code );
1776 return $status;
1779 # Check for spam
1780 $match = self::matchSummarySpamRegex( $this->summary );
1781 if ( $match === false && $this->section == 'new' ) {
1782 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1783 # regular summaries, it is added to the actual wikitext.
1784 if ( $this->sectiontitle !== '' ) {
1785 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1786 $match = self::matchSpamRegex( $this->sectiontitle );
1787 } else {
1788 # This branch is taken when the "Add Topic" user interface is used, or the API
1789 # is used with the 'summary' parameter.
1790 $match = self::matchSpamRegex( $this->summary );
1793 if ( $match === false ) {
1794 $match = self::matchSpamRegex( $this->textbox1 );
1796 if ( $match !== false ) {
1797 $result['spam'] = $match;
1798 $ip = $wgRequest->getIP();
1799 $pdbk = $this->mTitle->getPrefixedDBkey();
1800 $match = str_replace( "\n", '', $match );
1801 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1802 $status->fatal( 'spamprotectionmatch', $match );
1803 $status->value = self::AS_SPAM_ERROR;
1804 return $status;
1806 if ( !Hooks::run(
1807 'EditFilter',
1808 [ $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ] )
1810 # Error messages etc. could be handled within the hook...
1811 $status->fatal( 'hookaborted' );
1812 $status->value = self::AS_HOOK_ERROR;
1813 return $status;
1814 } elseif ( $this->hookError != '' ) {
1815 # ...or the hook could be expecting us to produce an error
1816 $status->fatal( 'hookaborted' );
1817 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1818 return $status;
1821 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1822 // Auto-block user's IP if the account was "hard" blocked
1823 if ( !wfReadOnly() ) {
1824 $wgUser->spreadAnyEditBlock();
1826 # Check block state against master, thus 'false'.
1827 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1828 return $status;
1831 $this->contentLength = strlen( $this->textbox1 );
1832 if ( $this->contentLength > $wgMaxArticleSize * 1024 ) {
1833 // Error will be displayed by showEditForm()
1834 $this->tooBig = true;
1835 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1836 return $status;
1839 if ( !$wgUser->isAllowed( 'edit' ) ) {
1840 if ( $wgUser->isAnon() ) {
1841 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1842 return $status;
1843 } else {
1844 $status->fatal( 'readonlytext' );
1845 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1846 return $status;
1850 $changingContentModel = false;
1851 if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
1852 if ( !$wgContentHandlerUseDB ) {
1853 $status->fatal( 'editpage-cannot-use-custom-model' );
1854 $status->value = self::AS_CANNOT_USE_CUSTOM_MODEL;
1855 return $status;
1856 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1857 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1858 return $status;
1860 // Make sure the user can edit the page under the new content model too
1861 $titleWithNewContentModel = clone $this->mTitle;
1862 $titleWithNewContentModel->setContentModel( $this->contentModel );
1863 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $wgUser )
1864 || !$titleWithNewContentModel->userCan( 'edit', $wgUser )
1866 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1867 return $status;
1870 $changingContentModel = true;
1871 $oldContentModel = $this->mTitle->getContentModel();
1874 if ( $this->changeTags ) {
1875 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
1876 $this->changeTags, $wgUser );
1877 if ( !$changeTagsStatus->isOK() ) {
1878 $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
1879 return $changeTagsStatus;
1883 if ( wfReadOnly() ) {
1884 $status->fatal( 'readonlytext' );
1885 $status->value = self::AS_READ_ONLY_PAGE;
1886 return $status;
1888 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 )
1889 || ( $changingContentModel && $wgUser->pingLimiter( 'editcontentmodel' ) )
1891 $status->fatal( 'actionthrottledtext' );
1892 $status->value = self::AS_RATE_LIMITED;
1893 return $status;
1896 # If the article has been deleted while editing, don't save it without
1897 # confirmation
1898 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1899 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1900 return $status;
1903 # Load the page data from the master. If anything changes in the meantime,
1904 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1905 $this->page->loadPageData( 'fromdbmaster' );
1906 $new = !$this->page->exists();
1908 if ( $new ) {
1909 // Late check for create permission, just in case *PARANOIA*
1910 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1911 $status->fatal( 'nocreatetext' );
1912 $status->value = self::AS_NO_CREATE_PERMISSION;
1913 wfDebug( __METHOD__ . ": no create permission\n" );
1914 return $status;
1917 // Don't save a new page if it's blank or if it's a MediaWiki:
1918 // message with content equivalent to default (allow empty pages
1919 // in this case to disable messages, see bug 50124)
1920 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1921 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1922 $defaultText = $defaultMessageText;
1923 } else {
1924 $defaultText = '';
1927 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
1928 $this->blankArticle = true;
1929 $status->fatal( 'blankarticle' );
1930 $status->setResult( false, self::AS_BLANK_ARTICLE );
1931 return $status;
1934 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1935 return $status;
1938 $content = $textbox_content;
1940 $result['sectionanchor'] = '';
1941 if ( $this->section == 'new' ) {
1942 if ( $this->sectiontitle !== '' ) {
1943 // Insert the section title above the content.
1944 $content = $content->addSectionHeader( $this->sectiontitle );
1945 } elseif ( $this->summary !== '' ) {
1946 // Insert the section title above the content.
1947 $content = $content->addSectionHeader( $this->summary );
1949 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
1952 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1954 } else { # not $new
1956 # Article exists. Check for edit conflict.
1958 $this->page->clear(); # Force reload of dates, etc.
1959 $timestamp = $this->page->getTimestamp();
1960 $latest = $this->page->getLatest();
1962 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1964 // Check editRevId if set, which handles same-second timestamp collisions
1965 if ( $timestamp != $this->edittime
1966 || ( $this->editRevId !== null && $this->editRevId != $latest )
1968 $this->isConflict = true;
1969 if ( $this->section == 'new' ) {
1970 if ( $this->page->getUserText() == $wgUser->getName() &&
1971 $this->page->getComment() == $this->newSectionSummary()
1973 // Probably a duplicate submission of a new comment.
1974 // This can happen when CDN resends a request after
1975 // a timeout but the first one actually went through.
1976 wfDebug( __METHOD__
1977 . ": duplicate new section submission; trigger edit conflict!\n" );
1978 } else {
1979 // New comment; suppress conflict.
1980 $this->isConflict = false;
1981 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1983 } elseif ( $this->section == ''
1984 && Revision::userWasLastToEdit(
1985 DB_MASTER, $this->mTitle->getArticleID(),
1986 $wgUser->getId(), $this->edittime
1989 # Suppress edit conflict with self, except for section edits where merging is required.
1990 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1991 $this->isConflict = false;
1995 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1996 if ( $this->sectiontitle !== '' ) {
1997 $sectionTitle = $this->sectiontitle;
1998 } else {
1999 $sectionTitle = $this->summary;
2002 $content = null;
2004 if ( $this->isConflict ) {
2005 wfDebug( __METHOD__
2006 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2007 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2008 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2009 // ...or disable section editing for non-current revisions (not exposed anyway).
2010 if ( $this->editRevId !== null ) {
2011 $content = $this->page->replaceSectionAtRev(
2012 $this->section,
2013 $textbox_content,
2014 $sectionTitle,
2015 $this->editRevId
2017 } else {
2018 $content = $this->page->replaceSectionContent(
2019 $this->section,
2020 $textbox_content,
2021 $sectionTitle,
2022 $this->edittime
2025 } else {
2026 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
2027 $content = $this->page->replaceSectionContent(
2028 $this->section,
2029 $textbox_content,
2030 $sectionTitle
2034 if ( is_null( $content ) ) {
2035 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
2036 $this->isConflict = true;
2037 $content = $textbox_content; // do not try to merge here!
2038 } elseif ( $this->isConflict ) {
2039 # Attempt merge
2040 if ( $this->mergeChangesIntoContent( $content ) ) {
2041 // Successful merge! Maybe we should tell the user the good news?
2042 $this->isConflict = false;
2043 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
2044 } else {
2045 $this->section = '';
2046 $this->textbox1 = ContentHandler::getContentText( $content );
2047 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
2051 if ( $this->isConflict ) {
2052 $status->setResult( false, self::AS_CONFLICT_DETECTED );
2053 return $status;
2056 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
2057 return $status;
2060 if ( $this->section == 'new' ) {
2061 // Handle the user preference to force summaries here
2062 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
2063 $this->missingSummary = true;
2064 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2065 $status->value = self::AS_SUMMARY_NEEDED;
2066 return $status;
2069 // Do not allow the user to post an empty comment
2070 if ( $this->textbox1 == '' ) {
2071 $this->missingComment = true;
2072 $status->fatal( 'missingcommenttext' );
2073 $status->value = self::AS_TEXTBOX_EMPTY;
2074 return $status;
2076 } elseif ( !$this->allowBlankSummary
2077 && !$content->equals( $this->getOriginalContent( $wgUser ) )
2078 && !$content->isRedirect()
2079 && md5( $this->summary ) == $this->autoSumm
2081 $this->missingSummary = true;
2082 $status->fatal( 'missingsummary' );
2083 $status->value = self::AS_SUMMARY_NEEDED;
2084 return $status;
2087 # All's well
2088 $sectionanchor = '';
2089 if ( $this->section == 'new' ) {
2090 $this->summary = $this->newSectionSummary( $sectionanchor );
2091 } elseif ( $this->section != '' ) {
2092 # Try to get a section anchor from the section source, redirect
2093 # to edited section if header found.
2094 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2095 # for duplicate heading checking and maybe parsing.
2096 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
2097 # We can't deal with anchors, includes, html etc in the header for now,
2098 # headline would need to be parsed to improve this.
2099 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2100 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
2103 $result['sectionanchor'] = $sectionanchor;
2105 // Save errors may fall down to the edit form, but we've now
2106 // merged the section into full text. Clear the section field
2107 // so that later submission of conflict forms won't try to
2108 // replace that into a duplicated mess.
2109 $this->textbox1 = $this->toEditText( $content );
2110 $this->section = '';
2112 $status->value = self::AS_SUCCESS_UPDATE;
2115 if ( !$this->allowSelfRedirect
2116 && $content->isRedirect()
2117 && $content->getRedirectTarget()->equals( $this->getTitle() )
2119 // If the page already redirects to itself, don't warn.
2120 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2121 if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
2122 $this->selfRedirect = true;
2123 $status->fatal( 'selfredirect' );
2124 $status->value = self::AS_SELF_REDIRECT;
2125 return $status;
2129 // Check for length errors again now that the section is merged in
2130 $this->contentLength = strlen( $this->toEditText( $content ) );
2131 if ( $this->contentLength > $wgMaxArticleSize * 1024 ) {
2132 $this->tooBig = true;
2133 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
2134 return $status;
2137 $flags = EDIT_AUTOSUMMARY |
2138 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
2139 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
2140 ( $bot ? EDIT_FORCE_BOT : 0 );
2142 $doEditStatus = $this->page->doEditContent(
2143 $content,
2144 $this->summary,
2145 $flags,
2146 false,
2147 $wgUser,
2148 $content->getDefaultFormat(),
2149 $this->changeTags,
2150 $this->undidRev
2153 if ( !$doEditStatus->isOK() ) {
2154 // Failure from doEdit()
2155 // Show the edit conflict page for certain recognized errors from doEdit(),
2156 // but don't show it for errors from extension hooks
2157 $errors = $doEditStatus->getErrorsArray();
2158 if ( in_array( $errors[0][0],
2159 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2161 $this->isConflict = true;
2162 // Destroys data doEdit() put in $status->value but who cares
2163 $doEditStatus->value = self::AS_END;
2165 return $doEditStatus;
2168 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2169 if ( $result['nullEdit'] ) {
2170 // We don't know if it was a null edit until now, so increment here
2171 $wgUser->pingLimiter( 'linkpurge' );
2173 $result['redirect'] = $content->isRedirect();
2175 $this->updateWatchlist();
2177 // If the content model changed, add a log entry
2178 if ( $changingContentModel ) {
2179 $this->addContentModelChangeLogEntry(
2180 $wgUser,
2181 $new ? false : $oldContentModel,
2182 $this->contentModel,
2183 $this->summary
2187 return $status;
2191 * @param User $user
2192 * @param string|false $oldModel false if the page is being newly created
2193 * @param string $newModel
2194 * @param string $reason
2196 protected function addContentModelChangeLogEntry( User $user, $oldModel, $newModel, $reason ) {
2197 $new = $oldModel === false;
2198 $log = new ManualLogEntry( 'contentmodel', $new ? 'new' : 'change' );
2199 $log->setPerformer( $user );
2200 $log->setTarget( $this->mTitle );
2201 $log->setComment( $reason );
2202 $log->setParameters( [
2203 '4::oldmodel' => $oldModel,
2204 '5::newmodel' => $newModel
2205 ] );
2206 $logid = $log->insert();
2207 $log->publish( $logid );
2211 * Register the change of watch status
2213 protected function updateWatchlist() {
2214 global $wgUser;
2216 if ( !$wgUser->isLoggedIn() ) {
2217 return;
2220 $user = $wgUser;
2221 $title = $this->mTitle;
2222 $watch = $this->watchthis;
2223 // Do this in its own transaction to reduce contention...
2224 DeferredUpdates::addCallableUpdate( function () use ( $user, $title, $watch ) {
2225 if ( $watch == $user->isWatched( $title, User::IGNORE_USER_RIGHTS ) ) {
2226 return; // nothing to change
2228 WatchAction::doWatchOrUnwatch( $watch, $title, $user );
2229 } );
2233 * Attempts to do 3-way merge of edit content with a base revision
2234 * and current content, in case of edit conflict, in whichever way appropriate
2235 * for the content type.
2237 * @since 1.21
2239 * @param Content $editContent
2241 * @return bool
2243 private function mergeChangesIntoContent( &$editContent ) {
2244 $db = wfGetDB( DB_MASTER );
2246 // This is the revision the editor started from
2247 $baseRevision = $this->getBaseRevision();
2248 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
2250 if ( is_null( $baseContent ) ) {
2251 return false;
2254 // The current state, we want to merge updates into it
2255 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2256 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2258 if ( is_null( $currentContent ) ) {
2259 return false;
2262 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2264 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2266 if ( $result ) {
2267 $editContent = $result;
2268 // Update parentRevId to what we just merged.
2269 $this->parentRevId = $currentRevision->getId();
2270 return true;
2273 return false;
2277 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2278 * one might think of X as the "base revision", which is NOT what this returns.
2279 * @return Revision Current version when the edit was started
2281 function getBaseRevision() {
2282 if ( !$this->mBaseRevision ) {
2283 $db = wfGetDB( DB_MASTER );
2284 $this->mBaseRevision = $this->editRevId
2285 ? Revision::newFromId( $this->editRevId, Revision::READ_LATEST )
2286 : Revision::loadFromTimestamp( $db, $this->mTitle, $this->edittime );
2288 return $this->mBaseRevision;
2292 * Check given input text against $wgSpamRegex, and return the text of the first match.
2294 * @param string $text
2296 * @return string|bool Matching string or false
2298 public static function matchSpamRegex( $text ) {
2299 global $wgSpamRegex;
2300 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2301 $regexes = (array)$wgSpamRegex;
2302 return self::matchSpamRegexInternal( $text, $regexes );
2306 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2308 * @param string $text
2310 * @return string|bool Matching string or false
2312 public static function matchSummarySpamRegex( $text ) {
2313 global $wgSummarySpamRegex;
2314 $regexes = (array)$wgSummarySpamRegex;
2315 return self::matchSpamRegexInternal( $text, $regexes );
2319 * @param string $text
2320 * @param array $regexes
2321 * @return bool|string
2323 protected static function matchSpamRegexInternal( $text, $regexes ) {
2324 foreach ( $regexes as $regex ) {
2325 $matches = [];
2326 if ( preg_match( $regex, $text, $matches ) ) {
2327 return $matches[0];
2330 return false;
2333 function setHeaders() {
2334 global $wgOut, $wgUser, $wgAjaxEditStash, $wgCookieSetOnAutoblock;
2336 $wgOut->addModules( 'mediawiki.action.edit' );
2337 if ( $wgCookieSetOnAutoblock === true ) {
2338 $wgOut->addModules( 'mediawiki.user.blockcookie' );
2340 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2342 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2343 // The addition of default buttons is handled by getEditToolbar() which
2344 // has its own dependency on this module. The call here ensures the module
2345 // is loaded in time (it has position "top") for other modules to register
2346 // buttons (e.g. extensions, gadgets, user scripts).
2347 $wgOut->addModules( 'mediawiki.toolbar' );
2350 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2351 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2354 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2355 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2358 # Enabled article-related sidebar, toplinks, etc.
2359 $wgOut->setArticleRelated( true );
2361 $contextTitle = $this->getContextTitle();
2362 if ( $this->isConflict ) {
2363 $msg = 'editconflict';
2364 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2365 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2366 } else {
2367 $msg = $contextTitle->exists()
2368 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2369 && $contextTitle->getDefaultMessageText() !== false
2371 ? 'editing'
2372 : 'creating';
2375 # Use the title defined by DISPLAYTITLE magic word when present
2376 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2377 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2378 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2379 if ( $displayTitle === false ) {
2380 $displayTitle = $contextTitle->getPrefixedText();
2382 $wgOut->setPageTitle( $this->context->msg( $msg, $displayTitle ) );
2383 # Transmit the name of the message to JavaScript for live preview
2384 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2385 $wgOut->addJsConfigVars( [
2386 'wgEditMessage' => $msg,
2387 'wgAjaxEditStash' => $wgAjaxEditStash,
2388 ] );
2392 * Show all applicable editing introductions
2394 protected function showIntro() {
2395 global $wgOut, $wgUser;
2396 if ( $this->suppressIntro ) {
2397 return;
2400 $namespace = $this->mTitle->getNamespace();
2402 if ( $namespace == NS_MEDIAWIKI ) {
2403 # Show a warning if editing an interface message
2404 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2405 # If this is a default message (but not css or js),
2406 # show a hint that it is translatable on translatewiki.net
2407 if ( !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2408 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2410 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2411 if ( $defaultMessageText !== false ) {
2412 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2413 'translateinterface' );
2416 } elseif ( $namespace == NS_FILE ) {
2417 # Show a hint to shared repo
2418 $file = wfFindFile( $this->mTitle );
2419 if ( $file && !$file->isLocal() ) {
2420 $descUrl = $file->getDescriptionUrl();
2421 # there must be a description url to show a hint to shared repo
2422 if ( $descUrl ) {
2423 if ( !$this->mTitle->exists() ) {
2424 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2425 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2426 ] );
2427 } else {
2428 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2429 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2430 ] );
2436 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2437 # Show log extract when the user is currently blocked
2438 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2439 $username = explode( '/', $this->mTitle->getText(), 2 )[0];
2440 $user = User::newFromName( $username, false /* allow IP users*/ );
2441 $ip = User::isIP( $username );
2442 $block = Block::newFromTarget( $user, $user );
2443 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2444 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2445 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2446 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2447 # Show log extract if the user is currently blocked
2448 LogEventsList::showLogExtract(
2449 $wgOut,
2450 'block',
2451 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2454 'lim' => 1,
2455 'showIfEmpty' => false,
2456 'msgKey' => [
2457 'blocked-notice-logextract',
2458 $user->getName() # Support GENDER in notice
2464 # Try to add a custom edit intro, or use the standard one if this is not possible.
2465 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2466 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2467 $this->context->msg( 'helppage' )->inContentLanguage()->text()
2468 ) );
2469 if ( $wgUser->isLoggedIn() ) {
2470 $wgOut->wrapWikiMsg(
2471 // Suppress the external link icon, consider the help url an internal one
2472 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2474 'newarticletext',
2475 $helpLink
2478 } else {
2479 $wgOut->wrapWikiMsg(
2480 // Suppress the external link icon, consider the help url an internal one
2481 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2483 'newarticletextanon',
2484 $helpLink
2489 # Give a notice if the user is editing a deleted/moved page...
2490 if ( !$this->mTitle->exists() ) {
2491 LogEventsList::showLogExtract( $wgOut, [ 'delete', 'move' ], $this->mTitle,
2494 'lim' => 10,
2495 'conds' => [ "log_action != 'revision'" ],
2496 'showIfEmpty' => false,
2497 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2504 * Attempt to show a custom editing introduction, if supplied
2506 * @return bool
2508 protected function showCustomIntro() {
2509 if ( $this->editintro ) {
2510 $title = Title::newFromText( $this->editintro );
2511 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2512 global $wgOut;
2513 // Added using template syntax, to take <noinclude>'s into account.
2514 $wgOut->addWikiTextTitleTidy(
2515 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2516 $this->mTitle
2518 return true;
2521 return false;
2525 * Gets an editable textual representation of $content.
2526 * The textual representation can be turned by into a Content object by the
2527 * toEditContent() method.
2529 * If $content is null or false or a string, $content is returned unchanged.
2531 * If the given Content object is not of a type that can be edited using
2532 * the text base EditPage, an exception will be raised. Set
2533 * $this->allowNonTextContent to true to allow editing of non-textual
2534 * content.
2536 * @param Content|null|bool|string $content
2537 * @return string The editable text form of the content.
2539 * @throws MWException If $content is not an instance of TextContent and
2540 * $this->allowNonTextContent is not true.
2542 protected function toEditText( $content ) {
2543 if ( $content === null || $content === false || is_string( $content ) ) {
2544 return $content;
2547 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2548 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2551 return $content->serialize( $this->contentFormat );
2555 * Turns the given text into a Content object by unserializing it.
2557 * If the resulting Content object is not of a type that can be edited using
2558 * the text base EditPage, an exception will be raised. Set
2559 * $this->allowNonTextContent to true to allow editing of non-textual
2560 * content.
2562 * @param string|null|bool $text Text to unserialize
2563 * @return Content|bool|null The content object created from $text. If $text was false
2564 * or null, false resp. null will be returned instead.
2566 * @throws MWException If unserializing the text results in a Content
2567 * object that is not an instance of TextContent and
2568 * $this->allowNonTextContent is not true.
2570 protected function toEditContent( $text ) {
2571 if ( $text === false || $text === null ) {
2572 return $text;
2575 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2576 $this->contentModel, $this->contentFormat );
2578 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2579 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2582 return $content;
2586 * Send the edit form and related headers to $wgOut
2587 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2588 * during form output near the top, for captchas and the like.
2590 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2591 * use the EditPage::showEditForm:fields hook instead.
2593 function showEditForm( $formCallback = null ) {
2594 global $wgOut, $wgUser;
2596 # need to parse the preview early so that we know which templates are used,
2597 # otherwise users with "show preview after edit box" will get a blank list
2598 # we parse this near the beginning so that setHeaders can do the title
2599 # setting work instead of leaving it in getPreviewText
2600 $previewOutput = '';
2601 if ( $this->formtype == 'preview' ) {
2602 $previewOutput = $this->getPreviewText();
2605 // Avoid PHP 7.1 warning of passing $this by reference
2606 $editPage = $this;
2607 Hooks::run( 'EditPage::showEditForm:initial', [ &$editPage, &$wgOut ] );
2609 $this->setHeaders();
2611 $this->addTalkPageText();
2612 $this->addEditNotices();
2614 if ( !$this->isConflict &&
2615 $this->section != '' &&
2616 !$this->isSectionEditSupported() ) {
2617 // We use $this->section to much before this and getVal('wgSection') directly in other places
2618 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2619 // Someone is welcome to try refactoring though
2620 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2621 return;
2624 $this->showHeader();
2626 $wgOut->addHTML( $this->editFormPageTop );
2628 if ( $wgUser->getOption( 'previewontop' ) ) {
2629 $this->displayPreviewArea( $previewOutput, true );
2632 $wgOut->addHTML( $this->editFormTextTop );
2634 $showToolbar = true;
2635 if ( $this->wasDeletedSinceLastEdit() ) {
2636 if ( $this->formtype == 'save' ) {
2637 // Hide the toolbar and edit area, user can click preview to get it back
2638 // Add an confirmation checkbox and explanation.
2639 $showToolbar = false;
2640 } else {
2641 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2642 'deletedwhileediting' );
2646 // @todo add EditForm plugin interface and use it here!
2647 // search for textarea1 and textares2, and allow EditForm to override all uses.
2648 $wgOut->addHTML( Html::openElement(
2649 'form',
2651 'id' => self::EDITFORM_ID,
2652 'name' => self::EDITFORM_ID,
2653 'method' => 'post',
2654 'action' => $this->getActionURL( $this->getContextTitle() ),
2655 'enctype' => 'multipart/form-data'
2657 ) );
2659 if ( is_callable( $formCallback ) ) {
2660 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2661 call_user_func_array( $formCallback, [ &$wgOut ] );
2664 // Add an empty field to trip up spambots
2665 $wgOut->addHTML(
2666 Xml::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2667 . Html::rawElement(
2668 'label',
2669 [ 'for' => 'wpAntispam' ],
2670 $this->context->msg( 'simpleantispam-label' )->parse()
2672 . Xml::element(
2673 'input',
2675 'type' => 'text',
2676 'name' => 'wpAntispam',
2677 'id' => 'wpAntispam',
2678 'value' => ''
2681 . Xml::closeElement( 'div' )
2684 // Avoid PHP 7.1 warning of passing $this by reference
2685 $editPage = $this;
2686 Hooks::run( 'EditPage::showEditForm:fields', [ &$editPage, &$wgOut ] );
2688 // Put these up at the top to ensure they aren't lost on early form submission
2689 $this->showFormBeforeText();
2691 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2692 $username = $this->lastDelete->user_name;
2693 $comment = $this->lastDelete->log_comment;
2695 // It is better to not parse the comment at all than to have templates expanded in the middle
2696 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2697 $key = $comment === ''
2698 ? 'confirmrecreate-noreason'
2699 : 'confirmrecreate';
2700 $wgOut->addHTML(
2701 '<div class="mw-confirm-recreate">' .
2702 $this->context->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2703 Xml::checkLabel( $this->context->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2704 [ 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2706 '</div>'
2710 # When the summary is hidden, also hide them on preview/show changes
2711 if ( $this->nosummary ) {
2712 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2715 # If a blank edit summary was previously provided, and the appropriate
2716 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2717 # user being bounced back more than once in the event that a summary
2718 # is not required.
2719 # ####
2720 # For a bit more sophisticated detection of blank summaries, hash the
2721 # automatic one and pass that in the hidden field wpAutoSummary.
2722 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2723 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2726 if ( $this->undidRev ) {
2727 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2730 if ( $this->selfRedirect ) {
2731 $wgOut->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2734 if ( $this->hasPresetSummary ) {
2735 // If a summary has been preset using &summary= we don't want to prompt for
2736 // a different summary. Only prompt for a summary if the summary is blanked.
2737 // (Bug 17416)
2738 $this->autoSumm = md5( '' );
2741 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2742 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2744 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2745 $wgOut->addHTML( Html::hidden( 'parentRevId', $this->getParentRevId() ) );
2747 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2748 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2750 if ( $this->section == 'new' ) {
2751 $this->showSummaryInput( true, $this->summary );
2752 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2755 $wgOut->addHTML( $this->editFormTextBeforeContent );
2757 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2758 $wgOut->addHTML( EditPage::getEditToolbar( $this->mTitle ) );
2761 if ( $this->blankArticle ) {
2762 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2765 if ( $this->isConflict ) {
2766 // In an edit conflict bypass the overridable content form method
2767 // and fallback to the raw wpTextbox1 since editconflicts can't be
2768 // resolved between page source edits and custom ui edits using the
2769 // custom edit ui.
2770 $this->textbox2 = $this->textbox1;
2772 $content = $this->getCurrentContent();
2773 $this->textbox1 = $this->toEditText( $content );
2775 $this->showTextbox1();
2776 } else {
2777 $this->showContentForm();
2780 $wgOut->addHTML( $this->editFormTextAfterContent );
2782 $this->showStandardInputs();
2784 $this->showFormAfterText();
2786 $this->showTosSummary();
2788 $this->showEditTools();
2790 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2792 $wgOut->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2794 $wgOut->addHTML( Html::rawElement( 'div', [ 'class' => 'hiddencats' ],
2795 Linker::formatHiddenCategories( $this->page->getHiddenCategories() ) ) );
2797 $wgOut->addHTML( Html::rawElement( 'div', [ 'class' => 'limitreport' ],
2798 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2800 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2802 if ( $this->isConflict ) {
2803 try {
2804 $this->showConflict();
2805 } catch ( MWContentSerializationException $ex ) {
2806 // this can't really happen, but be nice if it does.
2807 $msg = $this->context->msg(
2808 'content-failed-to-parse',
2809 $this->contentModel,
2810 $this->contentFormat,
2811 $ex->getMessage()
2813 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2817 // Set a hidden field so JS knows what edit form mode we are in
2818 if ( $this->isConflict ) {
2819 $mode = 'conflict';
2820 } elseif ( $this->preview ) {
2821 $mode = 'preview';
2822 } elseif ( $this->diff ) {
2823 $mode = 'diff';
2824 } else {
2825 $mode = 'text';
2827 $wgOut->addHTML( Html::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2829 // Marker for detecting truncated form data. This must be the last
2830 // parameter sent in order to be of use, so do not move me.
2831 $wgOut->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2832 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2834 if ( !$wgUser->getOption( 'previewontop' ) ) {
2835 $this->displayPreviewArea( $previewOutput, false );
2840 * Wrapper around TemplatesOnThisPageFormatter to make
2841 * a "templates on this page" list.
2843 * @param Title[] $templates
2844 * @return string HTML
2846 public function makeTemplatesOnThisPageList( array $templates ) {
2847 $templateListFormatter = new TemplatesOnThisPageFormatter(
2848 $this->context, MediaWikiServices::getInstance()->getLinkRenderer()
2851 // preview if preview, else section if section, else false
2852 $type = false;
2853 if ( $this->preview ) {
2854 $type = 'preview';
2855 } elseif ( $this->section != '' ) {
2856 $type = 'section';
2859 return Html::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2860 $templateListFormatter->format( $templates, $type )
2865 * Extract the section title from current section text, if any.
2867 * @param string $text
2868 * @return string|bool String or false
2870 public static function extractSectionTitle( $text ) {
2871 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2872 if ( !empty( $matches[2] ) ) {
2873 global $wgParser;
2874 return $wgParser->stripSectionName( trim( $matches[2] ) );
2875 } else {
2876 return false;
2880 protected function showHeader() {
2881 global $wgOut, $wgUser;
2882 global $wgAllowUserCss, $wgAllowUserJs;
2884 if ( $this->isConflict ) {
2885 $this->addExplainConflictHeader( $wgOut );
2886 $this->editRevId = $this->page->getLatest();
2887 } else {
2888 if ( $this->section != '' && $this->section != 'new' ) {
2889 if ( !$this->summary && !$this->preview && !$this->diff ) {
2890 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
2891 if ( $sectionTitle !== false ) {
2892 $this->summary = "/* $sectionTitle */ ";
2897 if ( $this->missingComment ) {
2898 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2901 if ( $this->missingSummary && $this->section != 'new' ) {
2902 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2905 if ( $this->missingSummary && $this->section == 'new' ) {
2906 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2909 if ( $this->blankArticle ) {
2910 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2913 if ( $this->selfRedirect ) {
2914 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2917 if ( $this->hookError !== '' ) {
2918 $wgOut->addWikiText( $this->hookError );
2921 if ( !$this->checkUnicodeCompliantBrowser() ) {
2922 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2925 if ( $this->section != 'new' ) {
2926 $revision = $this->mArticle->getRevisionFetched();
2927 if ( $revision ) {
2928 // Let sysop know that this will make private content public if saved
2930 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2931 $wgOut->wrapWikiMsg(
2932 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2933 'rev-deleted-text-permission'
2935 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2936 $wgOut->wrapWikiMsg(
2937 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2938 'rev-deleted-text-view'
2942 if ( !$revision->isCurrent() ) {
2943 $this->mArticle->setOldSubtitle( $revision->getId() );
2944 $wgOut->addWikiMsg( 'editingold' );
2945 $this->isOldRev = true;
2947 } elseif ( $this->mTitle->exists() ) {
2948 // Something went wrong
2950 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2951 [ 'missing-revision', $this->oldid ] );
2956 if ( wfReadOnly() ) {
2957 $wgOut->wrapWikiMsg(
2958 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2959 [ 'readonlywarning', wfReadOnlyReason() ]
2961 } elseif ( $wgUser->isAnon() ) {
2962 if ( $this->formtype != 'preview' ) {
2963 $wgOut->wrapWikiMsg(
2964 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
2965 [ 'anoneditwarning',
2966 // Log-in link
2967 SpecialPage::getTitleFor( 'Userlogin' )->getFullURL( [
2968 'returnto' => $this->getTitle()->getPrefixedDBkey()
2969 ] ),
2970 // Sign-up link
2971 SpecialPage::getTitleFor( 'CreateAccount' )->getFullURL( [
2972 'returnto' => $this->getTitle()->getPrefixedDBkey()
2976 } else {
2977 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
2978 'anonpreviewwarning'
2981 } else {
2982 if ( $this->isCssJsSubpage ) {
2983 # Check the skin exists
2984 if ( $this->isWrongCaseCssJsPage ) {
2985 $wgOut->wrapWikiMsg(
2986 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2987 [ 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ]
2990 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
2991 $wgOut->wrapWikiMsg( '<div class="mw-usercssjspublic">$1</div>',
2992 $this->isCssSubpage ? 'usercssispublic' : 'userjsispublic'
2994 if ( $this->formtype !== 'preview' ) {
2995 if ( $this->isCssSubpage && $wgAllowUserCss ) {
2996 $wgOut->wrapWikiMsg(
2997 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2998 [ 'usercssyoucanpreview' ]
3002 if ( $this->isJsSubpage && $wgAllowUserJs ) {
3003 $wgOut->wrapWikiMsg(
3004 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3005 [ 'userjsyoucanpreview' ]
3013 $this->addPageProtectionWarningHeaders();
3015 $this->addLongPageWarningHeader();
3017 # Add header copyright warning
3018 $this->showHeaderCopyrightWarning();
3022 * Standard summary input and label (wgSummary), abstracted so EditPage
3023 * subclasses may reorganize the form.
3024 * Note that you do not need to worry about the label's for=, it will be
3025 * inferred by the id given to the input. You can remove them both by
3026 * passing [ 'id' => false ] to $userInputAttrs.
3028 * @param string $summary The value of the summary input
3029 * @param string $labelText The html to place inside the label
3030 * @param array $inputAttrs Array of attrs to use on the input
3031 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
3033 * @return array An array in the format [ $label, $input ]
3035 function getSummaryInput( $summary = "", $labelText = null,
3036 $inputAttrs = null, $spanLabelAttrs = null
3038 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
3039 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : [] ) + [
3040 'id' => 'wpSummary',
3041 'maxlength' => '200',
3042 'tabindex' => '1',
3043 'size' => 60,
3044 'spellcheck' => 'true',
3045 ] + Linker::tooltipAndAccesskeyAttribs( 'summary' );
3047 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : [] ) + [
3048 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
3049 'id' => "wpSummaryLabel"
3052 $label = null;
3053 if ( $labelText ) {
3054 $label = Xml::tags(
3055 'label',
3056 $inputAttrs['id'] ? [ 'for' => $inputAttrs['id'] ] : null,
3057 $labelText
3059 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
3062 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
3064 return [ $label, $input ];
3068 * @param bool $isSubjectPreview True if this is the section subject/title
3069 * up top, or false if this is the comment summary
3070 * down below the textarea
3071 * @param string $summary The text of the summary to display
3073 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3074 global $wgOut;
3075 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3076 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
3077 if ( $isSubjectPreview ) {
3078 if ( $this->nosummary ) {
3079 return;
3081 } else {
3082 if ( !$this->mShowSummaryField ) {
3083 return;
3086 $labelText = $this->context->msg( $isSubjectPreview ? 'subject' : 'summary' )->parse();
3087 list( $label, $input ) = $this->getSummaryInput(
3088 $summary,
3089 $labelText,
3090 [ 'class' => $summaryClass ],
3093 $wgOut->addHTML( "{$label} {$input}" );
3097 * @param bool $isSubjectPreview True if this is the section subject/title
3098 * up top, or false if this is the comment summary
3099 * down below the textarea
3100 * @param string $summary The text of the summary to display
3101 * @return string
3103 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3104 // avoid spaces in preview, gets always trimmed on save
3105 $summary = trim( $summary );
3106 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
3107 return "";
3110 global $wgParser;
3112 if ( $isSubjectPreview ) {
3113 $summary = $this->context->msg( 'newsectionsummary' )
3114 ->rawParams( $wgParser->stripSectionName( $summary ) )
3115 ->inContentLanguage()->text();
3118 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
3120 $summary = $this->context->msg( $message )->parse()
3121 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
3122 return Xml::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3125 protected function showFormBeforeText() {
3126 global $wgOut;
3127 $section = htmlspecialchars( $this->section );
3128 $wgOut->addHTML( <<<HTML
3129 <input type='hidden' value="{$section}" name="wpSection"/>
3130 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
3131 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
3132 <input type='hidden' value="{$this->editRevId}" name="editRevId" />
3133 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
3135 HTML
3137 if ( !$this->checkUnicodeCompliantBrowser() ) {
3138 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
3142 protected function showFormAfterText() {
3143 global $wgOut, $wgUser;
3145 * To make it harder for someone to slip a user a page
3146 * which submits an edit form to the wiki without their
3147 * knowledge, a random token is associated with the login
3148 * session. If it's not passed back with the submission,
3149 * we won't save the page, or render user JavaScript and
3150 * CSS previews.
3152 * For anon editors, who may not have a session, we just
3153 * include the constant suffix to prevent editing from
3154 * broken text-mangling proxies.
3156 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
3160 * Subpage overridable method for printing the form for page content editing
3161 * By default this simply outputs wpTextbox1
3162 * Subclasses can override this to provide a custom UI for editing;
3163 * be it a form, or simply wpTextbox1 with a modified content that will be
3164 * reverse modified when extracted from the post data.
3165 * Note that this is basically the inverse for importContentFormData
3167 protected function showContentForm() {
3168 $this->showTextbox1();
3172 * Method to output wpTextbox1
3173 * The $textoverride method can be used by subclasses overriding showContentForm
3174 * to pass back to this method.
3176 * @param array $customAttribs Array of html attributes to use in the textarea
3177 * @param string $textoverride Optional text to override $this->textarea1 with
3179 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3180 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
3181 $attribs = [ 'style' => 'display:none;' ];
3182 } else {
3183 $classes = []; // Textarea CSS
3184 if ( $this->mTitle->isProtected( 'edit' ) &&
3185 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== [ '' ]
3187 # Is the title semi-protected?
3188 if ( $this->mTitle->isSemiProtected() ) {
3189 $classes[] = 'mw-textarea-sprotected';
3190 } else {
3191 # Then it must be protected based on static groups (regular)
3192 $classes[] = 'mw-textarea-protected';
3194 # Is the title cascade-protected?
3195 if ( $this->mTitle->isCascadeProtected() ) {
3196 $classes[] = 'mw-textarea-cprotected';
3199 # Is an old revision being edited?
3200 if ( $this->isOldRev ) {
3201 $classes[] = 'mw-textarea-oldrev';
3204 $attribs = [ 'tabindex' => 1 ];
3206 if ( is_array( $customAttribs ) ) {
3207 $attribs += $customAttribs;
3210 if ( count( $classes ) ) {
3211 if ( isset( $attribs['class'] ) ) {
3212 $classes[] = $attribs['class'];
3214 $attribs['class'] = implode( ' ', $classes );
3218 $this->showTextbox(
3219 $textoverride !== null ? $textoverride : $this->textbox1,
3220 'wpTextbox1',
3221 $attribs
3225 protected function showTextbox2() {
3226 $this->showTextbox( $this->textbox2, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3229 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3230 global $wgOut, $wgUser;
3232 $wikitext = $this->safeUnicodeOutput( $text );
3233 $wikitext = $this->addNewLineAtEnd( $wikitext );
3235 $attribs = $this->buildTextboxAttribs( $name, $customAttribs, $wgUser );
3237 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
3240 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3241 global $wgOut;
3242 $classes = [];
3243 if ( $isOnTop ) {
3244 $classes[] = 'ontop';
3247 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3249 if ( $this->formtype != 'preview' ) {
3250 $attribs['style'] = 'display: none;';
3253 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
3255 if ( $this->formtype == 'preview' ) {
3256 $this->showPreview( $previewOutput );
3257 } else {
3258 // Empty content container for LivePreview
3259 $pageViewLang = $this->mTitle->getPageViewLanguage();
3260 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3261 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3262 $wgOut->addHTML( Html::rawElement( 'div', $attribs ) );
3265 $wgOut->addHTML( '</div>' );
3267 if ( $this->formtype == 'diff' ) {
3268 try {
3269 $this->showDiff();
3270 } catch ( MWContentSerializationException $ex ) {
3271 $msg = $this->context->msg(
3272 'content-failed-to-parse',
3273 $this->contentModel,
3274 $this->contentFormat,
3275 $ex->getMessage()
3277 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3283 * Append preview output to $wgOut.
3284 * Includes category rendering if this is a category page.
3286 * @param string $text The HTML to be output for the preview.
3288 protected function showPreview( $text ) {
3289 global $wgOut;
3290 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3291 $this->mArticle->openShowCategory();
3293 # This hook seems slightly odd here, but makes things more
3294 # consistent for extensions.
3295 Hooks::run( 'OutputPageBeforeHTML', [ &$wgOut, &$text ] );
3296 $wgOut->addHTML( $text );
3297 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3298 $this->mArticle->closeShowCategory();
3303 * Get a diff between the current contents of the edit box and the
3304 * version of the page we're editing from.
3306 * If this is a section edit, we'll replace the section as for final
3307 * save and then make a comparison.
3309 function showDiff() {
3310 global $wgUser, $wgContLang, $wgOut;
3312 $oldtitlemsg = 'currentrev';
3313 # if message does not exist, show diff against the preloaded default
3314 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3315 $oldtext = $this->mTitle->getDefaultMessageText();
3316 if ( $oldtext !== false ) {
3317 $oldtitlemsg = 'defaultmessagetext';
3318 $oldContent = $this->toEditContent( $oldtext );
3319 } else {
3320 $oldContent = null;
3322 } else {
3323 $oldContent = $this->getCurrentContent();
3326 $textboxContent = $this->toEditContent( $this->textbox1 );
3327 if ( $this->editRevId !== null ) {
3328 $newContent = $this->page->replaceSectionAtRev(
3329 $this->section, $textboxContent, $this->summary, $this->editRevId
3331 } else {
3332 $newContent = $this->page->replaceSectionContent(
3333 $this->section, $textboxContent, $this->summary, $this->edittime
3337 if ( $newContent ) {
3338 Hooks::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3340 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
3341 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
3344 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3345 $oldtitle = $this->context->msg( $oldtitlemsg )->parse();
3346 $newtitle = $this->context->msg( 'yourtext' )->parse();
3348 if ( !$oldContent ) {
3349 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3352 if ( !$newContent ) {
3353 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3356 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
3357 $de->setContent( $oldContent, $newContent );
3359 $difftext = $de->getDiff( $oldtitle, $newtitle );
3360 $de->showDiffStyle();
3361 } else {
3362 $difftext = '';
3365 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3369 * Show the header copyright warning.
3371 protected function showHeaderCopyrightWarning() {
3372 $msg = 'editpage-head-copy-warn';
3373 if ( !$this->context->msg( $msg )->isDisabled() ) {
3374 global $wgOut;
3375 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3376 'editpage-head-copy-warn' );
3381 * Give a chance for site and per-namespace customizations of
3382 * terms of service summary link that might exist separately
3383 * from the copyright notice.
3385 * This will display between the save button and the edit tools,
3386 * so should remain short!
3388 protected function showTosSummary() {
3389 $msg = 'editpage-tos-summary';
3390 Hooks::run( 'EditPageTosSummary', [ $this->mTitle, &$msg ] );
3391 if ( !$this->context->msg( $msg )->isDisabled() ) {
3392 global $wgOut;
3393 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3394 $wgOut->addWikiMsg( $msg );
3395 $wgOut->addHTML( '</div>' );
3399 protected function showEditTools() {
3400 global $wgOut;
3401 $wgOut->addHTML( '<div class="mw-editTools">' .
3402 $this->context->msg( 'edittools' )->inContentLanguage()->parse() .
3403 '</div>' );
3407 * Get the copyright warning
3409 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3410 * @return string
3412 protected function getCopywarn() {
3413 return self::getCopyrightWarning( $this->mTitle );
3417 * Get the copyright warning, by default returns wikitext
3419 * @param Title $title
3420 * @param string $format Output format, valid values are any function of a Message object
3421 * @param Language|string|null $langcode Language code or Language object.
3422 * @return string
3424 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3425 global $wgRightsText;
3426 if ( $wgRightsText ) {
3427 $copywarnMsg = [ 'copyrightwarning',
3428 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3429 $wgRightsText ];
3430 } else {
3431 $copywarnMsg = [ 'copyrightwarning2',
3432 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3434 // Allow for site and per-namespace customization of contribution/copyright notice.
3435 Hooks::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3437 $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
3438 if ( $langcode ) {
3439 $msg->inLanguage( $langcode );
3441 return "<div id=\"editpage-copywarn\">\n" .
3442 $msg->$format() . "\n</div>";
3446 * Get the Limit report for page previews
3448 * @since 1.22
3449 * @param ParserOutput $output ParserOutput object from the parse
3450 * @return string HTML
3452 public static function getPreviewLimitReport( $output ) {
3453 if ( !$output || !$output->getLimitReportData() ) {
3454 return '';
3457 $limitReport = Html::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3458 wfMessage( 'limitreport-title' )->parseAsBlock()
3461 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3462 $limitReport .= Html::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3464 $limitReport .= Html::openElement( 'table', [
3465 'class' => 'preview-limit-report wikitable'
3466 ] ) .
3467 Html::openElement( 'tbody' );
3469 foreach ( $output->getLimitReportData() as $key => $value ) {
3470 if ( Hooks::run( 'ParserLimitReportFormat',
3471 [ $key, &$value, &$limitReport, true, true ]
3472 ) ) {
3473 $keyMsg = wfMessage( $key );
3474 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3475 if ( !$valueMsg->exists() ) {
3476 $valueMsg = new RawMessage( '$1' );
3478 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3479 $limitReport .= Html::openElement( 'tr' ) .
3480 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3481 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3482 Html::closeElement( 'tr' );
3487 $limitReport .= Html::closeElement( 'tbody' ) .
3488 Html::closeElement( 'table' ) .
3489 Html::closeElement( 'div' );
3491 return $limitReport;
3494 protected function showStandardInputs( &$tabindex = 2 ) {
3495 global $wgOut;
3496 $wgOut->addHTML( "<div class='editOptions'>\n" );
3498 if ( $this->section != 'new' ) {
3499 $this->showSummaryInput( false, $this->summary );
3500 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3503 $checkboxes = $this->getCheckboxes( $tabindex,
3504 [ 'minor' => $this->minoredit, 'watch' => $this->watchthis ] );
3505 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3507 // Show copyright warning.
3508 $wgOut->addWikiText( $this->getCopywarn() );
3509 $wgOut->addHTML( $this->editFormTextAfterWarn );
3511 $wgOut->addHTML( "<div class='editButtons'>\n" );
3512 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3514 $cancel = $this->getCancelLink();
3515 if ( $cancel !== '' ) {
3516 $cancel .= Html::element( 'span',
3517 [ 'class' => 'mw-editButtons-pipe-separator' ],
3518 $this->context->msg( 'pipe-separator' )->text() );
3521 $message = $this->context->msg( 'edithelppage' )->inContentLanguage()->text();
3522 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3523 $attrs = [
3524 'target' => 'helpwindow',
3525 'href' => $edithelpurl,
3527 $edithelp = Html::linkButton( $this->context->msg( 'edithelp' )->text(),
3528 $attrs, [ 'mw-ui-quiet' ] ) .
3529 $this->context->msg( 'word-separator' )->escaped() .
3530 $this->context->msg( 'newwindow' )->parse();
3532 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3533 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3534 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3536 Hooks::run( 'EditPage::showStandardInputs:options', [ $this, $wgOut, &$tabindex ] );
3538 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3542 * Show an edit conflict. textbox1 is already shown in showEditForm().
3543 * If you want to use another entry point to this function, be careful.
3545 protected function showConflict() {
3546 global $wgOut;
3548 // Avoid PHP 7.1 warning of passing $this by reference
3549 $editPage = $this;
3550 if ( Hooks::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$wgOut ] ) ) {
3551 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
3552 $stats->increment( 'edit.failures.conflict' );
3553 // Only include 'standard' namespaces to avoid creating unknown numbers of statsd metrics
3554 if (
3555 $this->mTitle->getNamespace() >= NS_MAIN &&
3556 $this->mTitle->getNamespace() <= NS_CATEGORY_TALK
3558 $stats->increment( 'edit.failures.conflict.byNamespaceId.' . $this->mTitle->getNamespace() );
3561 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3563 $content1 = $this->toEditContent( $this->textbox1 );
3564 $content2 = $this->toEditContent( $this->textbox2 );
3566 $handler = ContentHandler::getForModelID( $this->contentModel );
3567 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3568 $de->setContent( $content2, $content1 );
3569 $de->showDiff(
3570 $this->context->msg( 'yourtext' )->parse(),
3571 $this->context->msg( 'storedversion' )->text()
3574 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3575 $this->showTextbox2();
3580 * @return string
3582 public function getCancelLink() {
3583 $cancelParams = [];
3584 if ( !$this->isConflict && $this->oldid > 0 ) {
3585 $cancelParams['oldid'] = $this->oldid;
3586 } elseif ( $this->getContextTitle()->isRedirect() ) {
3587 $cancelParams['redirect'] = 'no';
3589 $attrs = [ 'id' => 'mw-editform-cancel' ];
3591 return Linker::linkKnown(
3592 $this->getContextTitle(),
3593 $this->context->msg( 'cancel' )->parse(),
3594 Html::buttonAttributes( $attrs, [ 'mw-ui-quiet' ] ),
3595 $cancelParams
3600 * Returns the URL to use in the form's action attribute.
3601 * This is used by EditPage subclasses when simply customizing the action
3602 * variable in the constructor is not enough. This can be used when the
3603 * EditPage lives inside of a Special page rather than a custom page action.
3605 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3606 * @return string
3608 protected function getActionURL( Title $title ) {
3609 return $title->getLocalURL( [ 'action' => $this->action ] );
3613 * Check if a page was deleted while the user was editing it, before submit.
3614 * Note that we rely on the logging table, which hasn't been always there,
3615 * but that doesn't matter, because this only applies to brand new
3616 * deletes.
3617 * @return bool
3619 protected function wasDeletedSinceLastEdit() {
3620 if ( $this->deletedSinceEdit !== null ) {
3621 return $this->deletedSinceEdit;
3624 $this->deletedSinceEdit = false;
3626 if ( !$this->mTitle->exists() && $this->mTitle->isDeletedQuick() ) {
3627 $this->lastDelete = $this->getLastDelete();
3628 if ( $this->lastDelete ) {
3629 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3630 if ( $deleteTime > $this->starttime ) {
3631 $this->deletedSinceEdit = true;
3636 return $this->deletedSinceEdit;
3640 * @return bool|stdClass
3642 protected function getLastDelete() {
3643 $dbr = wfGetDB( DB_REPLICA );
3644 $data = $dbr->selectRow(
3645 [ 'logging', 'user' ],
3647 'log_type',
3648 'log_action',
3649 'log_timestamp',
3650 'log_user',
3651 'log_namespace',
3652 'log_title',
3653 'log_comment',
3654 'log_params',
3655 'log_deleted',
3656 'user_name'
3657 ], [
3658 'log_namespace' => $this->mTitle->getNamespace(),
3659 'log_title' => $this->mTitle->getDBkey(),
3660 'log_type' => 'delete',
3661 'log_action' => 'delete',
3662 'user_id=log_user'
3664 __METHOD__,
3665 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ]
3667 // Quick paranoid permission checks...
3668 if ( is_object( $data ) ) {
3669 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3670 $data->user_name = $this->context->msg( 'rev-deleted-user' )->escaped();
3673 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3674 $data->log_comment = $this->context->msg( 'rev-deleted-comment' )->escaped();
3678 return $data;
3682 * Get the rendered text for previewing.
3683 * @throws MWException
3684 * @return string
3686 function getPreviewText() {
3687 global $wgOut, $wgRawHtml, $wgLang;
3688 global $wgAllowUserCss, $wgAllowUserJs;
3690 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
3692 if ( $wgRawHtml && !$this->mTokenOk ) {
3693 // Could be an offsite preview attempt. This is very unsafe if
3694 // HTML is enabled, as it could be an attack.
3695 $parsedNote = '';
3696 if ( $this->textbox1 !== '' ) {
3697 // Do not put big scary notice, if previewing the empty
3698 // string, which happens when you initially edit
3699 // a category page, due to automatic preview-on-open.
3700 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3701 $this->context->msg( 'session_fail_preview_html' )->text() . "</div>",
3702 true, /* interface */true );
3704 $stats->increment( 'edit.failures.session_loss' );
3705 return $parsedNote;
3708 $note = '';
3710 try {
3711 $content = $this->toEditContent( $this->textbox1 );
3713 $previewHTML = '';
3714 if ( !Hooks::run(
3715 'AlternateEditPreview',
3716 [ $this, &$content, &$previewHTML, &$this->mParserOutput ] )
3718 return $previewHTML;
3721 # provide a anchor link to the editform
3722 $continueEditing = '<span class="mw-continue-editing">' .
3723 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3724 $this->context->msg( 'continue-editing' )->text() . ']]</span>';
3725 if ( $this->mTriedSave && !$this->mTokenOk ) {
3726 if ( $this->mTokenOkExceptSuffix ) {
3727 $note = $this->context->msg( 'token_suffix_mismatch' )->plain();
3728 $stats->increment( 'edit.failures.bad_token' );
3729 } else {
3730 $note = $this->context->msg( 'session_fail_preview' )->plain();
3731 $stats->increment( 'edit.failures.session_loss' );
3733 } elseif ( $this->incompleteForm ) {
3734 $note = $this->context->msg( 'edit_form_incomplete' )->plain();
3735 if ( $this->mTriedSave ) {
3736 $stats->increment( 'edit.failures.incomplete_form' );
3738 } else {
3739 $note = $this->context->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3742 # don't parse non-wikitext pages, show message about preview
3743 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3744 if ( $this->mTitle->isCssJsSubpage() ) {
3745 $level = 'user';
3746 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3747 $level = 'site';
3748 } else {
3749 $level = false;
3752 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3753 $format = 'css';
3754 if ( $level === 'user' && !$wgAllowUserCss ) {
3755 $format = false;
3757 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3758 $format = 'js';
3759 if ( $level === 'user' && !$wgAllowUserJs ) {
3760 $format = false;
3762 } else {
3763 $format = false;
3766 # Used messages to make sure grep find them:
3767 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3768 if ( $level && $format ) {
3769 $note = "<div id='mw-{$level}{$format}preview'>" .
3770 $this->context->msg( "{$level}{$format}preview" )->text() .
3771 ' ' . $continueEditing . "</div>";
3775 # If we're adding a comment, we need to show the
3776 # summary as the headline
3777 if ( $this->section === "new" && $this->summary !== "" ) {
3778 $content = $content->addSectionHeader( $this->summary );
3781 $hook_args = [ $this, &$content ];
3782 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args, '1.25' );
3783 Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3785 $parserResult = $this->doPreviewParse( $content );
3786 $parserOutput = $parserResult['parserOutput'];
3787 $previewHTML = $parserResult['html'];
3788 $this->mParserOutput = $parserOutput;
3789 $wgOut->addParserOutputMetadata( $parserOutput );
3791 if ( count( $parserOutput->getWarnings() ) ) {
3792 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3795 } catch ( MWContentSerializationException $ex ) {
3796 $m = $this->context->msg(
3797 'content-failed-to-parse',
3798 $this->contentModel,
3799 $this->contentFormat,
3800 $ex->getMessage()
3802 $note .= "\n\n" . $m->parse();
3803 $previewHTML = '';
3806 if ( $this->isConflict ) {
3807 $conflict = '<h2 id="mw-previewconflict">'
3808 . $this->context->msg( 'previewconflict' )->escaped() . "</h2>\n";
3809 } else {
3810 $conflict = '<hr />';
3813 $previewhead = "<div class='previewnote'>\n" .
3814 '<h2 id="mw-previewheader">' . $this->context->msg( 'preview' )->escaped() . "</h2>" .
3815 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3817 $pageViewLang = $this->mTitle->getPageViewLanguage();
3818 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3819 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3820 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3822 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3826 * Get parser options for a preview
3827 * @return ParserOptions
3829 protected function getPreviewParserOptions() {
3830 $parserOptions = $this->page->makeParserOptions( $this->mArticle->getContext() );
3831 $parserOptions->setIsPreview( true );
3832 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3833 $parserOptions->enableLimitReport();
3834 return $parserOptions;
3838 * Parse the page for a preview. Subclasses may override this class, in order
3839 * to parse with different options, or to otherwise modify the preview HTML.
3841 * @param Content $content The page content
3842 * @return array with keys:
3843 * - parserOutput: The ParserOutput object
3844 * - html: The HTML to be displayed
3846 protected function doPreviewParse( Content $content ) {
3847 global $wgUser;
3848 $parserOptions = $this->getPreviewParserOptions();
3849 $pstContent = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3850 $scopedCallback = $parserOptions->setupFakeRevision(
3851 $this->mTitle, $pstContent, $wgUser );
3852 $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
3853 ScopedCallback::consume( $scopedCallback );
3854 $parserOutput->setEditSectionTokens( false ); // no section edit links
3855 return [
3856 'parserOutput' => $parserOutput,
3857 'html' => $parserOutput->getText() ];
3861 * @return array
3863 function getTemplates() {
3864 if ( $this->preview || $this->section != '' ) {
3865 $templates = [];
3866 if ( !isset( $this->mParserOutput ) ) {
3867 return $templates;
3869 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3870 foreach ( array_keys( $template ) as $dbk ) {
3871 $templates[] = Title::makeTitle( $ns, $dbk );
3874 return $templates;
3875 } else {
3876 return $this->mTitle->getTemplateLinksFrom();
3881 * Shows a bulletin board style toolbar for common editing functions.
3882 * It can be disabled in the user preferences.
3884 * @param Title $title Title object for the page being edited (optional)
3885 * @return string
3887 static function getEditToolbar( $title = null ) {
3888 global $wgContLang, $wgOut;
3889 global $wgEnableUploads, $wgForeignFileRepos;
3891 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3892 $showSignature = true;
3893 if ( $title ) {
3894 $showSignature = MWNamespace::wantSignatures( $title->getNamespace() );
3898 * $toolarray is an array of arrays each of which includes the
3899 * opening tag, the closing tag, optionally a sample text that is
3900 * inserted between the two when no selection is highlighted
3901 * and. The tip text is shown when the user moves the mouse
3902 * over the button.
3904 * Images are defined in ResourceLoaderEditToolbarModule.
3906 $toolarray = [
3908 'id' => 'mw-editbutton-bold',
3909 'open' => '\'\'\'',
3910 'close' => '\'\'\'',
3911 'sample' => wfMessage( 'bold_sample' )->text(),
3912 'tip' => wfMessage( 'bold_tip' )->text(),
3915 'id' => 'mw-editbutton-italic',
3916 'open' => '\'\'',
3917 'close' => '\'\'',
3918 'sample' => wfMessage( 'italic_sample' )->text(),
3919 'tip' => wfMessage( 'italic_tip' )->text(),
3922 'id' => 'mw-editbutton-link',
3923 'open' => '[[',
3924 'close' => ']]',
3925 'sample' => wfMessage( 'link_sample' )->text(),
3926 'tip' => wfMessage( 'link_tip' )->text(),
3929 'id' => 'mw-editbutton-extlink',
3930 'open' => '[',
3931 'close' => ']',
3932 'sample' => wfMessage( 'extlink_sample' )->text(),
3933 'tip' => wfMessage( 'extlink_tip' )->text(),
3936 'id' => 'mw-editbutton-headline',
3937 'open' => "\n== ",
3938 'close' => " ==\n",
3939 'sample' => wfMessage( 'headline_sample' )->text(),
3940 'tip' => wfMessage( 'headline_tip' )->text(),
3942 $imagesAvailable ? [
3943 'id' => 'mw-editbutton-image',
3944 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3945 'close' => ']]',
3946 'sample' => wfMessage( 'image_sample' )->text(),
3947 'tip' => wfMessage( 'image_tip' )->text(),
3948 ] : false,
3949 $imagesAvailable ? [
3950 'id' => 'mw-editbutton-media',
3951 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3952 'close' => ']]',
3953 'sample' => wfMessage( 'media_sample' )->text(),
3954 'tip' => wfMessage( 'media_tip' )->text(),
3955 ] : false,
3957 'id' => 'mw-editbutton-nowiki',
3958 'open' => "<nowiki>",
3959 'close' => "</nowiki>",
3960 'sample' => wfMessage( 'nowiki_sample' )->text(),
3961 'tip' => wfMessage( 'nowiki_tip' )->text(),
3963 $showSignature ? [
3964 'id' => 'mw-editbutton-signature',
3965 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
3966 'close' => '',
3967 'sample' => '',
3968 'tip' => wfMessage( 'sig_tip' )->text(),
3969 ] : false,
3971 'id' => 'mw-editbutton-hr',
3972 'open' => "\n----\n",
3973 'close' => '',
3974 'sample' => '',
3975 'tip' => wfMessage( 'hr_tip' )->text(),
3979 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3980 foreach ( $toolarray as $tool ) {
3981 if ( !$tool ) {
3982 continue;
3985 $params = [
3986 // Images are defined in ResourceLoaderEditToolbarModule
3987 false,
3988 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3989 // Older browsers show a "speedtip" type message only for ALT.
3990 // Ideally these should be different, realistically they
3991 // probably don't need to be.
3992 $tool['tip'],
3993 $tool['open'],
3994 $tool['close'],
3995 $tool['sample'],
3996 $tool['id'],
3999 $script .= Xml::encodeJsCall(
4000 'mw.toolbar.addButton',
4001 $params,
4002 ResourceLoader::inDebugMode()
4006 $script .= '});';
4007 $wgOut->addScript( ResourceLoader::makeInlineScript( $script ) );
4009 $toolbar = '<div id="toolbar"></div>';
4011 Hooks::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] );
4013 return $toolbar;
4017 * Returns an array of html code of the following checkboxes:
4018 * minor and watch
4020 * @param int $tabindex Current tabindex
4021 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4022 * status of the checkbox
4024 * @return array
4026 public function getCheckboxes( &$tabindex, $checked ) {
4027 global $wgUser, $wgUseMediaWikiUIEverywhere;
4029 $checkboxes = [];
4031 // don't show the minor edit checkbox if it's a new page or section
4032 if ( !$this->isNew ) {
4033 $checkboxes['minor'] = '';
4034 $minorLabel = $this->context->msg( 'minoredit' )->parse();
4035 if ( $wgUser->isAllowed( 'minoredit' ) ) {
4036 $attribs = [
4037 'tabindex' => ++$tabindex,
4038 'accesskey' => $this->context->msg( 'accesskey-minoredit' )->text(),
4039 'id' => 'wpMinoredit',
4041 $minorEditHtml =
4042 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
4043 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
4044 Xml::expandAttributes( [ 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ] ) .
4045 ">{$minorLabel}</label>";
4047 if ( $wgUseMediaWikiUIEverywhere ) {
4048 $checkboxes['minor'] = Html::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
4049 $minorEditHtml .
4050 Html::closeElement( 'div' );
4051 } else {
4052 $checkboxes['minor'] = $minorEditHtml;
4057 $watchLabel = $this->context->msg( 'watchthis' )->parse();
4058 $checkboxes['watch'] = '';
4059 if ( $wgUser->isLoggedIn() ) {
4060 $attribs = [
4061 'tabindex' => ++$tabindex,
4062 'accesskey' => $this->context->msg( 'accesskey-watch' )->text(),
4063 'id' => 'wpWatchthis',
4065 $watchThisHtml =
4066 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
4067 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
4068 Xml::expandAttributes( [ 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ] ) .
4069 ">{$watchLabel}</label>";
4070 if ( $wgUseMediaWikiUIEverywhere ) {
4071 $checkboxes['watch'] = Html::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
4072 $watchThisHtml .
4073 Html::closeElement( 'div' );
4074 } else {
4075 $checkboxes['watch'] = $watchThisHtml;
4079 // Avoid PHP 7.1 warning of passing $this by reference
4080 $editPage = $this;
4081 Hooks::run( 'EditPageBeforeEditChecks', [ &$editPage, &$checkboxes, &$tabindex ] );
4082 return $checkboxes;
4086 * Returns an array of html code of the following buttons:
4087 * save, diff and preview
4089 * @param int $tabindex Current tabindex
4091 * @return array
4093 public function getEditButtons( &$tabindex ) {
4094 $buttons = [];
4096 $labelAsPublish =
4097 $this->mArticle->getContext()->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4099 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4100 if ( $labelAsPublish ) {
4101 $buttonLabelKey = !$this->mTitle->exists() ? 'publishpage' : 'publishchanges';
4102 } else {
4103 $buttonLabelKey = !$this->mTitle->exists() ? 'savearticle' : 'savechanges';
4105 $buttonLabel = $this->context->msg( $buttonLabelKey )->text();
4106 $attribs = [
4107 'id' => 'wpSave',
4108 'name' => 'wpSave',
4109 'tabindex' => ++$tabindex,
4110 ] + Linker::tooltipAndAccesskeyAttribs( 'save' );
4111 $buttons['save'] = Html::submitButton( $buttonLabel, $attribs, [ 'mw-ui-progressive' ] );
4113 ++$tabindex; // use the same for preview and live preview
4114 $attribs = [
4115 'id' => 'wpPreview',
4116 'name' => 'wpPreview',
4117 'tabindex' => $tabindex,
4118 ] + Linker::tooltipAndAccesskeyAttribs( 'preview' );
4119 $buttons['preview'] = Html::submitButton( $this->context->msg( 'showpreview' )->text(),
4120 $attribs );
4122 $attribs = [
4123 'id' => 'wpDiff',
4124 'name' => 'wpDiff',
4125 'tabindex' => ++$tabindex,
4126 ] + Linker::tooltipAndAccesskeyAttribs( 'diff' );
4127 $buttons['diff'] = Html::submitButton( $this->context->msg( 'showdiff' )->text(),
4128 $attribs );
4130 // Avoid PHP 7.1 warning of passing $this by reference
4131 $editPage = $this;
4132 Hooks::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4133 return $buttons;
4137 * Creates a basic error page which informs the user that
4138 * they have attempted to edit a nonexistent section.
4140 function noSuchSectionPage() {
4141 global $wgOut;
4143 $wgOut->prepareErrorPage( $this->context->msg( 'nosuchsectiontitle' ) );
4145 $res = $this->context->msg( 'nosuchsectiontext', $this->section )->parseAsBlock();
4147 // Avoid PHP 7.1 warning of passing $this by reference
4148 $editPage = $this;
4149 Hooks::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4150 $wgOut->addHTML( $res );
4152 $wgOut->returnToMain( false, $this->mTitle );
4156 * Show "your edit contains spam" page with your diff and text
4158 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4160 public function spamPageWithContent( $match = false ) {
4161 global $wgOut, $wgLang;
4162 $this->textbox2 = $this->textbox1;
4164 if ( is_array( $match ) ) {
4165 $match = $wgLang->listToText( $match );
4167 $wgOut->prepareErrorPage( $this->context->msg( 'spamprotectiontitle' ) );
4169 $wgOut->addHTML( '<div id="spamprotected">' );
4170 $wgOut->addWikiMsg( 'spamprotectiontext' );
4171 if ( $match ) {
4172 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4174 $wgOut->addHTML( '</div>' );
4176 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4177 $this->showDiff();
4179 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4180 $this->showTextbox2();
4182 $wgOut->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4186 * Check if the browser is on a blacklist of user-agents known to
4187 * mangle UTF-8 data on form submission. Returns true if Unicode
4188 * should make it through, false if it's known to be a problem.
4189 * @return bool
4191 private function checkUnicodeCompliantBrowser() {
4192 global $wgBrowserBlackList, $wgRequest;
4194 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
4195 if ( $currentbrowser === false ) {
4196 // No User-Agent header sent? Trust it by default...
4197 return true;
4200 foreach ( $wgBrowserBlackList as $browser ) {
4201 if ( preg_match( $browser, $currentbrowser ) ) {
4202 return false;
4205 return true;
4209 * Filter an input field through a Unicode de-armoring process if it
4210 * came from an old browser with known broken Unicode editing issues.
4212 * @param WebRequest $request
4213 * @param string $field
4214 * @return string
4216 protected function safeUnicodeInput( $request, $field ) {
4217 $text = rtrim( $request->getText( $field ) );
4218 return $request->getBool( 'safemode' )
4219 ? $this->unmakeSafe( $text )
4220 : $text;
4224 * Filter an output field through a Unicode armoring process if it is
4225 * going to an old browser with known broken Unicode editing issues.
4227 * @param string $text
4228 * @return string
4230 protected function safeUnicodeOutput( $text ) {
4231 return $this->checkUnicodeCompliantBrowser()
4232 ? $text
4233 : $this->makeSafe( $text );
4237 * A number of web browsers are known to corrupt non-ASCII characters
4238 * in a UTF-8 text editing environment. To protect against this,
4239 * detected browsers will be served an armored version of the text,
4240 * with non-ASCII chars converted to numeric HTML character references.
4242 * Preexisting such character references will have a 0 added to them
4243 * to ensure that round-trips do not alter the original data.
4245 * @param string $invalue
4246 * @return string
4248 private function makeSafe( $invalue ) {
4249 // Armor existing references for reversibility.
4250 $invalue = strtr( $invalue, [ "&#x" => "&#x0" ] );
4252 $bytesleft = 0;
4253 $result = "";
4254 $working = 0;
4255 $valueLength = strlen( $invalue );
4256 for ( $i = 0; $i < $valueLength; $i++ ) {
4257 $bytevalue = ord( $invalue[$i] );
4258 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4259 $result .= chr( $bytevalue );
4260 $bytesleft = 0;
4261 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4262 $working = $working << 6;
4263 $working += ( $bytevalue & 0x3F );
4264 $bytesleft--;
4265 if ( $bytesleft <= 0 ) {
4266 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4268 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4269 $working = $bytevalue & 0x1F;
4270 $bytesleft = 1;
4271 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4272 $working = $bytevalue & 0x0F;
4273 $bytesleft = 2;
4274 } else { // 1111 0xxx
4275 $working = $bytevalue & 0x07;
4276 $bytesleft = 3;
4279 return $result;
4283 * Reverse the previously applied transliteration of non-ASCII characters
4284 * back to UTF-8. Used to protect data from corruption by broken web browsers
4285 * as listed in $wgBrowserBlackList.
4287 * @param string $invalue
4288 * @return string
4290 private function unmakeSafe( $invalue ) {
4291 $result = "";
4292 $valueLength = strlen( $invalue );
4293 for ( $i = 0; $i < $valueLength; $i++ ) {
4294 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
4295 $i += 3;
4296 $hexstring = "";
4297 do {
4298 $hexstring .= $invalue[$i];
4299 $i++;
4300 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4302 // Do some sanity checks. These aren't needed for reversibility,
4303 // but should help keep the breakage down if the editor
4304 // breaks one of the entities whilst editing.
4305 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4306 $codepoint = hexdec( $hexstring );
4307 $result .= UtfNormal\Utils::codepointToUtf8( $codepoint );
4308 } else {
4309 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4311 } else {
4312 $result .= substr( $invalue, $i, 1 );
4315 // reverse the transform that we made for reversibility reasons.
4316 return strtr( $result, [ "&#x0" => "&#x" ] );
4320 * @since 1.29
4322 protected function addEditNotices() {
4323 global $wgOut;
4325 $editNotices = $this->mTitle->getEditNotices( $this->oldid );
4326 if ( count( $editNotices ) ) {
4327 $wgOut->addHTML( implode( "\n", $editNotices ) );
4328 } else {
4329 $msg = $this->context->msg( 'editnotice-notext' );
4330 if ( !$msg->isDisabled() ) {
4331 $wgOut->addHTML(
4332 '<div class="mw-editnotice-notext">'
4333 . $msg->parseAsBlock()
4334 . '</div>'
4341 * @since 1.29
4343 protected function addTalkPageText() {
4344 global $wgOut;
4346 if ( $this->mTitle->isTalkPage() ) {
4347 $wgOut->addWikiMsg( 'talkpagetext' );
4352 * @since 1.29
4354 protected function addLongPageWarningHeader() {
4355 global $wgMaxArticleSize, $wgOut, $wgLang;
4357 if ( $this->contentLength === false ) {
4358 $this->contentLength = strlen( $this->textbox1 );
4361 if ( $this->tooBig || $this->contentLength > $wgMaxArticleSize * 1024 ) {
4362 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4364 'longpageerror',
4365 $wgLang->formatNum( round( $this->contentLength / 1024, 3 ) ),
4366 $wgLang->formatNum( $wgMaxArticleSize )
4369 } else {
4370 if ( !$this->context->msg( 'longpage-hint' )->isDisabled() ) {
4371 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4373 'longpage-hint',
4374 $wgLang->formatSize( strlen( $this->textbox1 ) ),
4375 strlen( $this->textbox1 )
4383 * @since 1.29
4385 protected function addPageProtectionWarningHeaders() {
4386 global $wgOut;
4388 if ( $this->mTitle->isProtected( 'edit' ) &&
4389 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== [ '' ]
4391 # Is the title semi-protected?
4392 if ( $this->mTitle->isSemiProtected() ) {
4393 $noticeMsg = 'semiprotectedpagewarning';
4394 } else {
4395 # Then it must be protected based on static groups (regular)
4396 $noticeMsg = 'protectedpagewarning';
4398 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
4399 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4401 if ( $this->mTitle->isCascadeProtected() ) {
4402 # Is this page under cascading protection from some source pages?
4403 /** @var Title[] $cascadeSources */
4404 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
4405 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4406 $cascadeSourcesCount = count( $cascadeSources );
4407 if ( $cascadeSourcesCount > 0 ) {
4408 # Explain, and list the titles responsible
4409 foreach ( $cascadeSources as $page ) {
4410 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4413 $notice .= '</div>';
4414 $wgOut->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4416 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
4417 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
4418 [ 'lim' => 1,
4419 'showIfEmpty' => false,
4420 'msgKey' => [ 'titleprotectedwarning' ],
4421 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4426 * @param OutputPage $out
4427 * @since 1.29
4429 protected function addExplainConflictHeader( OutputPage $out ) {
4430 $out->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
4434 * @param string $name
4435 * @param mixed[] $customAttribs
4436 * @param User $user
4437 * @return mixed[]
4438 * @since 1.29
4440 protected function buildTextboxAttribs( $name, array $customAttribs, User $user ) {
4441 $attribs = $customAttribs + [
4442 'accesskey' => ',',
4443 'id' => $name,
4444 'cols' => 80,
4445 'rows' => 25,
4446 // Avoid PHP notices when appending preferences
4447 // (appending allows customAttribs['style'] to still work).
4448 'style' => ''
4451 // The following classes can be used here:
4452 // * mw-editfont-default
4453 // * mw-editfont-monospace
4454 // * mw-editfont-sans-serif
4455 // * mw-editfont-serif
4456 $class = 'mw-editfont-' . $user->getOption( 'editfont' );
4458 if ( isset( $attribs['class'] ) ) {
4459 if ( is_string( $attribs['class'] ) ) {
4460 $attribs['class'] .= ' ' . $class;
4461 } elseif ( is_array( $attribs['class'] ) ) {
4462 $attribs['class'][] = $class;
4464 } else {
4465 $attribs['class'] = $class;
4468 $pageLang = $this->mTitle->getPageLanguage();
4469 $attribs['lang'] = $pageLang->getHtmlCode();
4470 $attribs['dir'] = $pageLang->getDir();
4472 return $attribs;
4476 * @param string $wikitext
4477 * @return string
4478 * @since 1.29
4480 protected function addNewLineAtEnd( $wikitext ) {
4481 if ( strval( $wikitext ) !== '' ) {
4482 // Ensure there's a newline at the end, otherwise adding lines
4483 // is awkward.
4484 // But don't add a newline if the text is empty, or Firefox in XHTML
4485 // mode will show an extra newline. A bit annoying.
4486 $wikitext .= "\n";
4487 return $wikitext;
4489 return $wikitext;