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
24 * The edit page/HTML interface (split from Article)
25 * The actual database and text munging is still in Article,
26 * but it should get easier to call those from alternate
29 * EditPage cares about two distinct titles:
30 * $this->mContextTitle is the page that forms submit to, links point to,
31 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
32 * page in the database that is actually being edited. These are
33 * usually the same, but they are now allowed to be different.
35 * Surgeon General's Warning: prolonged exposure to this class is known to cause
36 * headaches, which may be fatal.
40 * Status: Article successfully updated
42 const AS_SUCCESS_UPDATE
= 200;
45 * Status: Article successfully created
47 const AS_SUCCESS_NEW_ARTICLE
= 201;
50 * Status: Article update aborted by a hook function
52 const AS_HOOK_ERROR
= 210;
55 * Status: A hook function returned an error
57 const AS_HOOK_ERROR_EXPECTED
= 212;
60 * Status: User is blocked from editing this page
62 const AS_BLOCKED_PAGE_FOR_USER
= 215;
65 * Status: Content too big (> $wgMaxArticleSize)
67 const AS_CONTENT_TOO_BIG
= 216;
70 * Status: this anonymous user is not allowed to edit this page
72 const AS_READ_ONLY_PAGE_ANON
= 218;
75 * Status: this logged in user is not allowed to edit this page
77 const AS_READ_ONLY_PAGE_LOGGED
= 219;
80 * Status: wiki is in readonly mode (wfReadOnly() == true)
82 const AS_READ_ONLY_PAGE
= 220;
85 * Status: rate limiter for action 'edit' was tripped
87 const AS_RATE_LIMITED
= 221;
90 * Status: article was deleted while editing and param wpRecreate == false or form
93 const AS_ARTICLE_WAS_DELETED
= 222;
96 * Status: user tried to create this page, but is not allowed to do that
97 * ( Title->userCan('create') == false )
99 const AS_NO_CREATE_PERMISSION
= 223;
102 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
104 const AS_BLANK_ARTICLE
= 224;
107 * Status: (non-resolvable) edit conflict
109 const AS_CONFLICT_DETECTED
= 225;
112 * Status: no edit summary given and the user has forceeditsummary set and the user is not
113 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
115 const AS_SUMMARY_NEEDED
= 226;
118 * Status: user tried to create a new section without content
120 const AS_TEXTBOX_EMPTY
= 228;
123 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
125 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
128 * Status: WikiPage::doEdit() was unsuccessful
133 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
135 const AS_SPAM_ERROR
= 232;
138 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
140 const AS_IMAGE_REDIRECT_ANON
= 233;
143 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
145 const AS_IMAGE_REDIRECT_LOGGED
= 234;
148 * Status: user tried to modify the content model, but is not allowed to do that
149 * ( User::isAllowed('editcontentmodel') == false )
151 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
154 * Status: user tried to create self-redirect (redirect to the same article) and
155 * wpIgnoreSelfRedirect == false
157 const AS_SELF_REDIRECT
= 236;
160 * Status: an error relating to change tagging. Look at the message key for
163 const AS_CHANGE_TAG_ERROR
= 237;
166 * Status: can't parse content
168 const AS_PARSE_ERROR
= 240;
171 * Status: when changing the content model is disallowed due to
172 * $wgContentHandlerUseDB being false
174 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
177 * HTML id and name for the beginning of the edit form.
179 const EDITFORM_ID
= 'editform';
182 * Prefix of key for cookie used to pass post-edit state.
183 * The revision id edited is added after this
185 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
188 * Duration of PostEdit cookie, in seconds.
189 * The cookie will be removed instantly if the JavaScript runs.
191 * Otherwise, though, we don't want the cookies to accumulate.
192 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
193 * limit of only 20 cookies per domain. This still applies at least to some
194 * versions of IE without full updates:
195 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
197 * A value of 20 minutes should be enough to take into account slow loads and minor
198 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
200 const POST_EDIT_COOKIE_DURATION
= 1200;
210 /** @var null|Title */
211 private $mContextTitle = null;
214 public $action = 'submit';
217 public $isConflict = false;
220 public $isCssJsSubpage = false;
223 public $isCssSubpage = false;
226 public $isJsSubpage = false;
229 public $isWrongCaseCssJsPage = false;
231 /** @var bool New page or new section */
232 public $isNew = false;
235 public $deletedSinceEdit;
243 /** @var bool|stdClass */
247 public $mTokenOk = false;
250 public $mTokenOkExceptSuffix = false;
253 public $mTriedSave = false;
256 public $incompleteForm = false;
259 public $tooBig = false;
262 public $kblength = false;
265 public $missingComment = false;
268 public $missingSummary = false;
271 public $allowBlankSummary = false;
274 protected $blankArticle = false;
277 protected $allowBlankArticle = false;
280 protected $selfRedirect = false;
283 protected $allowSelfRedirect = false;
286 public $autoSumm = '';
289 public $hookError = '';
291 /** @var ParserOutput */
292 public $mParserOutput;
294 /** @var bool Has a summary been preset using GET parameter &summary= ? */
295 public $hasPresetSummary = false;
298 public $mBaseRevision = false;
301 public $mShowSummaryField = true;
306 public $save = false;
309 public $preview = false;
312 public $diff = false;
315 public $minoredit = false;
318 public $watchthis = false;
321 public $recreate = false;
324 public $textbox1 = '';
327 public $textbox2 = '';
330 public $summary = '';
333 public $nosummary = false;
336 public $edittime = '';
339 public $section = '';
342 public $sectiontitle = '';
345 public $starttime = '';
351 public $parentRevId = 0;
354 public $editintro = '';
357 public $scrolltop = null;
362 /** @var null|string */
363 public $contentModel = null;
365 /** @var null|string */
366 public $contentFormat = null;
368 /** @var null|array */
369 public $changeTags = null;
371 # Placeholders for text injection by hooks (must be HTML)
372 # extensions should take care to _append_ to the present value
374 /** @var string Before even the preview */
375 public $editFormPageTop = '';
376 public $editFormTextTop = '';
377 public $editFormTextBeforeContent = '';
378 public $editFormTextAfterWarn = '';
379 public $editFormTextAfterTools = '';
380 public $editFormTextBottom = '';
381 public $editFormTextAfterContent = '';
382 public $previewTextAfterContent = '';
383 public $mPreloadContent = null;
385 /* $didSave should be set to true whenever an article was successfully altered. */
386 public $didSave = false;
387 public $undidRev = 0;
389 public $suppressIntro = false;
395 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
397 private $enableApiEditOverride = false;
400 * @param Article $article
402 public function __construct( Article
$article ) {
403 $this->mArticle
= $article;
404 $this->page
= $article->getPage(); // model object
405 $this->mTitle
= $article->getTitle();
407 $this->contentModel
= $this->mTitle
->getContentModel();
409 $handler = ContentHandler
::getForModelID( $this->contentModel
);
410 $this->contentFormat
= $handler->getDefaultFormat();
416 public function getArticle() {
417 return $this->mArticle
;
424 public function getTitle() {
425 return $this->mTitle
;
429 * Set the context Title object
431 * @param Title|null $title Title object or null
433 public function setContextTitle( $title ) {
434 $this->mContextTitle
= $title;
438 * Get the context title object.
439 * If not set, $wgTitle will be returned. This behavior might change in
440 * the future to return $this->mTitle instead.
444 public function getContextTitle() {
445 if ( is_null( $this->mContextTitle
) ) {
449 return $this->mContextTitle
;
454 * Returns if the given content model is editable.
456 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
458 * @throws MWException If $modelId has no known handler
460 public function isSupportedContentModel( $modelId ) {
461 return $this->enableApiEditOverride
=== true ||
462 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
466 * Allow editing of content that supports API direct editing, but not general
467 * direct editing. Set to false by default.
469 * @param bool $enableOverride
471 public function setApiEditOverride( $enableOverride ) {
472 $this->enableApiEditOverride
= $enableOverride;
480 * This is the function that gets called for "action=edit". It
481 * sets up various member variables, then passes execution to
482 * another function, usually showEditForm()
484 * The edit form is self-submitting, so that when things like
485 * preview and edit conflicts occur, we get the same form back
486 * with the extra stuff added. Only when the final submission
487 * is made and all is well do we actually save and redirect to
488 * the newly-edited page.
491 global $wgOut, $wgRequest, $wgUser;
492 // Allow extensions to modify/prevent this form or submission
493 if ( !Hooks
::run( 'AlternateEdit', array( $this ) ) ) {
497 wfDebug( __METHOD__
. ": enter\n" );
499 // If they used redlink=1 and the page exists, redirect to the main article
500 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
501 $wgOut->redirect( $this->mTitle
->getFullURL() );
505 $this->importFormData( $wgRequest );
506 $this->firsttime
= false;
508 if ( wfReadOnly() && $this->save
) {
511 $this->preview
= true;
515 $this->formtype
= 'save';
516 } elseif ( $this->preview
) {
517 $this->formtype
= 'preview';
518 } elseif ( $this->diff
) {
519 $this->formtype
= 'diff';
520 } else { # First time through
521 $this->firsttime
= true;
522 if ( $this->previewOnOpen() ) {
523 $this->formtype
= 'preview';
525 $this->formtype
= 'initial';
529 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
531 wfDebug( __METHOD__
. ": User can't edit\n" );
532 // Auto-block user's IP if the account was "hard" blocked
534 DeferredUpdates
::addCallableUpdate( function() use ( $user ) {
535 $user->spreadAnyEditBlock();
538 $this->displayPermissionsError( $permErrors );
543 $revision = $this->mArticle
->getRevisionFetched();
544 // Disallow editing revisions with content models different from the current one
545 if ( $revision && $revision->getContentModel() !== $this->contentModel
) {
546 $this->displayViewSourcePage(
547 $this->getContentObject(),
549 'contentmodelediterror',
550 $revision->getContentModel(),
557 $this->isConflict
= false;
558 // css / js subpages of user pages get a special treatment
559 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
560 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
561 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
562 // @todo FIXME: Silly assignment.
563 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
565 # Show applicable editing introductions
566 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
570 # Attempt submission here. This will check for edit conflicts,
571 # and redundantly check for locked database, blocked IPs, etc.
572 # that edit() already checked just in case someone tries to sneak
573 # in the back door with a hand-edited submission URL.
575 if ( 'save' == $this->formtype
) {
576 $resultDetails = null;
577 $status = $this->attemptSave( $resultDetails );
578 if ( !$this->handleStatus( $status, $resultDetails ) ) {
583 # First time through: get contents, set time for conflict
585 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
586 if ( $this->initialiseForm() === false ) {
587 $this->noSuchSectionPage();
591 if ( !$this->mTitle
->getArticleID() ) {
592 Hooks
::run( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
594 Hooks
::run( 'EditFormInitialText', array( $this ) );
599 $this->showEditForm();
603 * @param string $rigor Same format as Title::getUserPermissionErrors()
606 protected function getEditPermissionErrors( $rigor = 'secure' ) {
609 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
610 # Can this title be created?
611 if ( !$this->mTitle
->exists() ) {
612 $permErrors = array_merge(
615 $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
620 # Ignore some permissions errors when a user is just previewing/viewing diffs
622 foreach ( $permErrors as $error ) {
623 if ( ( $this->preview ||
$this->diff
)
624 && ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' )
629 $permErrors = wfArrayDiff2( $permErrors, $remove );
635 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
636 * but with the following differences:
637 * - If redlink=1, the user will be redirected to the page
638 * - If there is content to display or the error occurs while either saving,
639 * previewing or showing the difference, it will be a
640 * "View source for ..." page displaying the source code after the error message.
643 * @param array $permErrors Array of permissions errors, as returned by
644 * Title::getUserPermissionsErrors().
645 * @throws PermissionsError
647 protected function displayPermissionsError( array $permErrors ) {
648 global $wgRequest, $wgOut;
650 if ( $wgRequest->getBool( 'redlink' ) ) {
651 // The edit page was reached via a red link.
652 // Redirect to the article page and let them click the edit tab if
653 // they really want a permission error.
654 $wgOut->redirect( $this->mTitle
->getFullURL() );
658 $content = $this->getContentObject();
660 # Use the normal message if there's nothing to display
661 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
662 $action = $this->mTitle
->exists() ?
'edit' :
663 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
664 throw new PermissionsError( $action, $permErrors );
667 $this->displayViewSourcePage(
669 $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' )
674 * Display a read-only View Source page
675 * @param Content $content content object
676 * @param string $errorMessage additional wikitext error message to display
678 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
681 Hooks
::run( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
683 $wgOut->setRobotPolicy( 'noindex,nofollow' );
684 $wgOut->setPageTitle( wfMessage(
686 $this->getContextTitle()->getPrefixedText()
688 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
689 $wgOut->addHTML( $this->editFormPageTop
);
690 $wgOut->addHTML( $this->editFormTextTop
);
692 if ( $errorMessage !== '' ) {
693 $wgOut->addWikiText( $errorMessage );
694 $wgOut->addHTML( "<hr />\n" );
697 # If the user made changes, preserve them when showing the markup
698 # (This happens when a user is blocked during edit, for instance)
699 if ( !$this->firsttime
) {
700 $text = $this->textbox1
;
701 $wgOut->addWikiMsg( 'viewyourtext' );
704 $text = $this->toEditText( $content );
705 } catch ( MWException
$e ) {
706 # Serialize using the default format if the content model is not supported
707 # (e.g. for an old revision with a different model)
708 $text = $content->serialize();
710 $wgOut->addWikiMsg( 'viewsourcetext' );
713 $wgOut->addHTML( $this->editFormTextBeforeContent
);
714 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
715 $wgOut->addHTML( $this->editFormTextAfterContent
);
717 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
718 Linker
::formatTemplates( $this->getTemplates() ) ) );
720 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
722 $wgOut->addHTML( $this->editFormTextBottom
);
723 if ( $this->mTitle
->exists() ) {
724 $wgOut->returnToMain( null, $this->mTitle
);
729 * Should we show a preview when the edit form is first shown?
733 protected function previewOnOpen() {
734 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
735 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
736 // Explicit override from request
738 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
739 // Explicit override from request
741 } elseif ( $this->section
== 'new' ) {
742 // Nothing *to* preview for new sections
744 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
745 && $wgUser->getOption( 'previewonfirst' )
747 // Standard preference behavior
749 } elseif ( !$this->mTitle
->exists()
750 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
751 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
753 // Categories are special
761 * Checks whether the user entered a skin name in uppercase,
762 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
766 protected function isWrongCaseCssJsPage() {
767 if ( $this->mTitle
->isCssJsSubpage() ) {
768 $name = $this->mTitle
->getSkinFromCssJsSubpage();
769 $skins = array_merge(
770 array_keys( Skin
::getSkinNames() ),
773 return !in_array( $name, $skins )
774 && in_array( strtolower( $name ), $skins );
781 * Returns whether section editing is supported for the current page.
782 * Subclasses may override this to replace the default behavior, which is
783 * to check ContentHandler::supportsSections.
785 * @return bool True if this edit page supports sections, false otherwise.
787 protected function isSectionEditSupported() {
788 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
789 return $contentHandler->supportsSections();
793 * This function collects the form data and uses it to populate various member variables.
794 * @param WebRequest $request
795 * @throws ErrorPageError
797 function importFormData( &$request ) {
798 global $wgContLang, $wgUser;
800 # Section edit can come from either the form or a link
801 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
803 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
804 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
807 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
809 if ( $request->wasPosted() ) {
810 # These fields need to be checked for encoding.
811 # Also remove trailing whitespace, but don't remove _initial_
812 # whitespace from the text boxes. This may be significant formatting.
813 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
814 if ( !$request->getCheck( 'wpTextbox2' ) ) {
815 // Skip this if wpTextbox2 has input, it indicates that we came
816 // from a conflict page with raw page text, not a custom form
817 // modified by subclasses
818 $textbox1 = $this->importContentFormData( $request );
819 if ( $textbox1 !== null ) {
820 $this->textbox1
= $textbox1;
824 # Truncate for whole multibyte characters
825 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
827 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
828 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
830 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
832 # Treat sectiontitle the same way as summary.
833 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
834 # currently doing double duty as both edit summary and section title. Right now this
835 # is just to allow API edits to work around this limitation, but this should be
836 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
837 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
838 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
840 $this->edittime
= $request->getVal( 'wpEdittime' );
841 $this->starttime
= $request->getVal( 'wpStarttime' );
843 $undidRev = $request->getInt( 'wpUndidRevision' );
845 $this->undidRev
= $undidRev;
848 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
850 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
851 // wpTextbox1 field is missing, possibly due to being "too big"
852 // according to some filter rules such as Suhosin's setting for
853 // suhosin.request.max_value_length (d'oh)
854 $this->incompleteForm
= true;
856 // If we receive the last parameter of the request, we can fairly
857 // claim the POST request has not been truncated.
859 // TODO: softened the check for cutover. Once we determine
860 // that it is safe, we should complete the transition by
861 // removing the "edittime" clause.
862 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
863 && is_null( $this->edittime
) );
865 if ( $this->incompleteForm
) {
866 # If the form is incomplete, force to preview.
867 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
868 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
869 $this->preview
= true;
871 $this->preview
= $request->getCheck( 'wpPreview' );
872 $this->diff
= $request->getCheck( 'wpDiff' );
874 // Remember whether a save was requested, so we can indicate
875 // if we forced preview due to session failure.
876 $this->mTriedSave
= !$this->preview
;
878 if ( $this->tokenOk( $request ) ) {
879 # Some browsers will not report any submit button
880 # if the user hits enter in the comment box.
881 # The unmarked state will be assumed to be a save,
882 # if the form seems otherwise complete.
883 wfDebug( __METHOD__
. ": Passed token check.\n" );
884 } elseif ( $this->diff
) {
885 # Failed token check, but only requested "Show Changes".
886 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
888 # Page might be a hack attempt posted from
889 # an external site. Preview instead of saving.
890 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
891 $this->preview
= true;
894 $this->save
= !$this->preview
&& !$this->diff
;
895 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
896 $this->edittime
= null;
899 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
900 $this->starttime
= null;
903 $this->recreate
= $request->getCheck( 'wpRecreate' );
905 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
906 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
908 # Don't force edit summaries when a user is editing their own user or talk page
909 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
910 && $this->mTitle
->getText() == $wgUser->getName()
912 $this->allowBlankSummary
= true;
914 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
915 ||
!$wgUser->getOption( 'forceeditsummary' );
918 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
920 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
921 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
923 $changeTags = $request->getVal( 'wpChangeTags' );
924 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
925 $this->changeTags
= array();
927 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
931 # Not a posted form? Start with nothing.
932 wfDebug( __METHOD__
. ": Not a posted form.\n" );
933 $this->textbox1
= '';
935 $this->sectiontitle
= '';
936 $this->edittime
= '';
937 $this->starttime
= wfTimestampNow();
939 $this->preview
= false;
942 $this->minoredit
= false;
943 // Watch may be overridden by request parameters
944 $this->watchthis
= $request->getBool( 'watchthis', false );
945 $this->recreate
= false;
947 // When creating a new section, we can preload a section title by passing it as the
948 // preloadtitle parameter in the URL (Bug 13100)
949 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
950 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
951 // Once wpSummary isn't being use for setting section titles, we should delete this.
952 $this->summary
= $request->getVal( 'preloadtitle' );
953 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
954 $this->summary
= $request->getText( 'summary' );
955 if ( $this->summary
!== '' ) {
956 $this->hasPresetSummary
= true;
960 if ( $request->getVal( 'minor' ) ) {
961 $this->minoredit
= true;
965 $this->oldid
= $request->getInt( 'oldid' );
966 $this->parentRevId
= $request->getInt( 'parentRevId' );
968 $this->bot
= $request->getBool( 'bot', true );
969 $this->nosummary
= $request->getBool( 'nosummary' );
971 // May be overridden by revision.
972 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
973 // May be overridden by revision.
974 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
976 if ( !ContentHandler
::getForModelID( $this->contentModel
)
977 ->isSupportedFormat( $this->contentFormat
)
979 throw new ErrorPageError(
980 'editpage-notsupportedcontentformat-title',
981 'editpage-notsupportedcontentformat-text',
982 array( $this->contentFormat
, ContentHandler
::getLocalizedName( $this->contentModel
) )
987 * @todo Check if the desired model is allowed in this namespace, and if
988 * a transition from the page's current model to the new model is
992 $this->editintro
= $request->getText( 'editintro',
993 // Custom edit intro for new sections
994 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
996 // Allow extensions to modify form data
997 Hooks
::run( 'EditPage::importFormData', array( $this, $request ) );
1002 * Subpage overridable method for extracting the page content data from the
1003 * posted form to be placed in $this->textbox1, if using customized input
1004 * this method should be overridden and return the page text that will be used
1005 * for saving, preview parsing and so on...
1007 * @param WebRequest $request
1008 * @return string|null
1010 protected function importContentFormData( &$request ) {
1011 return; // Don't do anything, EditPage already extracted wpTextbox1
1015 * Initialise form fields in the object
1016 * Called on the first invocation, e.g. when a user clicks an edit link
1017 * @return bool If the requested section is valid
1019 function initialiseForm() {
1021 $this->edittime
= $this->page
->getTimestamp();
1023 $content = $this->getContentObject( false ); # TODO: track content object?!
1024 if ( $content === false ) {
1027 $this->textbox1
= $this->toEditText( $content );
1029 // activate checkboxes if user wants them to be always active
1030 # Sort out the "watch" checkbox
1031 if ( $wgUser->getOption( 'watchdefault' ) ) {
1033 $this->watchthis
= true;
1034 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1036 $this->watchthis
= true;
1037 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
1039 $this->watchthis
= true;
1041 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
1042 $this->minoredit
= true;
1044 if ( $this->textbox1
=== false ) {
1051 * @param Content|null $def_content The default value to return
1053 * @return Content|null Content on success, $def_content for invalid sections
1057 protected function getContentObject( $def_content = null ) {
1058 global $wgOut, $wgRequest, $wgUser, $wgContLang;
1062 // For message page not locally set, use the i18n message.
1063 // For other non-existent articles, use preload text if any.
1064 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1065 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1066 # If this is a system message, get the default text.
1067 $msg = $this->mTitle
->getDefaultMessageText();
1069 $content = $this->toEditContent( $msg );
1071 if ( $content === false ) {
1072 # If requested, preload some text.
1073 $preload = $wgRequest->getVal( 'preload',
1074 // Custom preload text for new sections
1075 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1076 $params = $wgRequest->getArray( 'preloadparams', array() );
1078 $content = $this->getPreloadedContent( $preload, $params );
1080 // For existing pages, get text based on "undo" or section parameters.
1082 if ( $this->section
!= '' ) {
1083 // Get section edit text (returns $def_text for invalid sections)
1084 $orig = $this->getOriginalContent( $wgUser );
1085 $content = $orig ?
$orig->getSection( $this->section
) : null;
1088 $content = $def_content;
1091 $undoafter = $wgRequest->getInt( 'undoafter' );
1092 $undo = $wgRequest->getInt( 'undo' );
1094 if ( $undo > 0 && $undoafter > 0 ) {
1095 $undorev = Revision
::newFromId( $undo );
1096 $oldrev = Revision
::newFromId( $undoafter );
1098 # Sanity check, make sure it's the right page,
1099 # the revisions exist and they were not deleted.
1100 # Otherwise, $content will be left as-is.
1101 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1102 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1103 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1105 $content = $this->page
->getUndoContent( $undorev, $oldrev );
1107 if ( $content === false ) {
1108 # Warn the user that something went wrong
1109 $undoMsg = 'failure';
1111 $oldContent = $this->page
->getContent( Revision
::RAW
);
1112 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
1113 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
1115 if ( $newContent->equals( $oldContent ) ) {
1116 # Tell the user that the undo results in no change,
1117 # i.e. the revisions were already undone.
1118 $undoMsg = 'nochange';
1121 # Inform the user of our success and set an automatic edit summary
1122 $undoMsg = 'success';
1124 # If we just undid one rev, use an autosummary
1125 $firstrev = $oldrev->getNext();
1126 if ( $firstrev && $firstrev->getId() == $undo ) {
1127 $userText = $undorev->getUserText();
1128 if ( $userText === '' ) {
1129 $undoSummary = wfMessage(
1130 'undo-summary-username-hidden',
1132 )->inContentLanguage()->text();
1134 $undoSummary = wfMessage(
1138 )->inContentLanguage()->text();
1140 if ( $this->summary
=== '' ) {
1141 $this->summary
= $undoSummary;
1143 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
1144 ->inContentLanguage()->text() . $this->summary
;
1146 $this->undidRev
= $undo;
1148 $this->formtype
= 'diff';
1152 // Failed basic sanity checks.
1153 // Older revisions may have been removed since the link
1154 // was created, or we may simply have got bogus input.
1158 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1159 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1160 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
1161 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1164 if ( $content === false ) {
1165 $content = $this->getOriginalContent( $wgUser );
1174 * Get the content of the wanted revision, without section extraction.
1176 * The result of this function can be used to compare user's input with
1177 * section replaced in its context (using WikiPage::replaceSection())
1178 * to the original text of the edit.
1180 * This differs from Article::getContent() that when a missing revision is
1181 * encountered the result will be null and not the
1182 * 'missing-revision' message.
1185 * @param User $user The user to get the revision for
1186 * @return Content|null
1188 private function getOriginalContent( User
$user ) {
1189 if ( $this->section
== 'new' ) {
1190 return $this->getCurrentContent();
1192 $revision = $this->mArticle
->getRevisionFetched();
1193 if ( $revision === null ) {
1194 if ( !$this->contentModel
) {
1195 $this->contentModel
= $this->getTitle()->getContentModel();
1197 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1199 return $handler->makeEmptyContent();
1201 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1206 * Get the current content of the page. This is basically similar to
1207 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1208 * content object is returned instead of null.
1213 protected function getCurrentContent() {
1214 $rev = $this->page
->getRevision();
1215 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1217 if ( $content === false ||
$content === null ) {
1218 if ( !$this->contentModel
) {
1219 $this->contentModel
= $this->getTitle()->getContentModel();
1221 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1223 return $handler->makeEmptyContent();
1225 # nasty side-effect, but needed for consistency
1226 $this->contentModel
= $rev->getContentModel();
1227 $this->contentFormat
= $rev->getContentFormat();
1234 * Use this method before edit() to preload some content into the edit box
1236 * @param Content $content
1240 public function setPreloadedContent( Content
$content ) {
1241 $this->mPreloadContent
= $content;
1245 * Get the contents to be preloaded into the box, either set by
1246 * an earlier setPreloadText() or by loading the given page.
1248 * @param string $preload Representing the title to preload from.
1249 * @param array $params Parameters to use (interface-message style) in the preloaded text
1255 protected function getPreloadedContent( $preload, $params = array() ) {
1258 if ( !empty( $this->mPreloadContent
) ) {
1259 return $this->mPreloadContent
;
1262 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1264 if ( $preload === '' ) {
1265 return $handler->makeEmptyContent();
1268 $title = Title
::newFromText( $preload );
1269 # Check for existence to avoid getting MediaWiki:Noarticletext
1270 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1271 // TODO: somehow show a warning to the user!
1272 return $handler->makeEmptyContent();
1275 $page = WikiPage
::factory( $title );
1276 if ( $page->isRedirect() ) {
1277 $title = $page->getRedirectTarget();
1279 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1280 // TODO: somehow show a warning to the user!
1281 return $handler->makeEmptyContent();
1283 $page = WikiPage
::factory( $title );
1286 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1287 $content = $page->getContent( Revision
::RAW
);
1290 // TODO: somehow show a warning to the user!
1291 return $handler->makeEmptyContent();
1294 if ( $content->getModel() !== $handler->getModelID() ) {
1295 $converted = $content->convert( $handler->getModelID() );
1297 if ( !$converted ) {
1298 // TODO: somehow show a warning to the user!
1299 wfDebug( "Attempt to preload incompatible content: " .
1300 "can't convert " . $content->getModel() .
1301 " to " . $handler->getModelID() );
1303 return $handler->makeEmptyContent();
1306 $content = $converted;
1309 return $content->preloadTransform( $title, $parserOptions, $params );
1313 * Make sure the form isn't faking a user's credentials.
1315 * @param WebRequest $request
1319 function tokenOk( &$request ) {
1321 $token = $request->getVal( 'wpEditToken' );
1322 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1323 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1324 return $this->mTokenOk
;
1328 * Sets post-edit cookie indicating the user just saved a particular revision.
1330 * This uses a temporary cookie for each revision ID so separate saves will never
1331 * interfere with each other.
1333 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1334 * the redirect. It must be clearable by JavaScript code, so it must not be
1335 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1338 * If the variable were set on the server, it would be cached, which is unwanted
1339 * since the post-edit state should only apply to the load right after the save.
1341 * @param int $statusValue The status value (to check for new article status)
1343 protected function setPostEditCookie( $statusValue ) {
1344 $revisionId = $this->page
->getLatest();
1345 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1348 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1350 } elseif ( $this->oldid
) {
1354 $response = RequestContext
::getMain()->getRequest()->response();
1355 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
, array(
1356 'httpOnly' => false,
1361 * Attempt submission
1362 * @param array $resultDetails See docs for $result in internalAttemptSave
1363 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1364 * @return Status The resulting status object.
1366 public function attemptSave( &$resultDetails = false ) {
1369 # Allow bots to exempt some edits from bot flagging
1370 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1371 $status = $this->internalAttemptSave( $resultDetails, $bot );
1373 Hooks
::run( 'EditPage::attemptSave:after', array( $this, $status, $resultDetails ) );
1379 * Handle status, such as after attempt save
1381 * @param Status $status
1382 * @param array|bool $resultDetails
1384 * @throws ErrorPageError
1385 * @return bool False, if output is done, true if rest of the form should be displayed
1387 private function handleStatus( Status
$status, $resultDetails ) {
1388 global $wgUser, $wgOut;
1391 * @todo FIXME: once the interface for internalAttemptSave() is made
1392 * nicer, this should use the message in $status
1394 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1395 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1397 $this->didSave
= true;
1398 if ( !$resultDetails['nullEdit'] ) {
1399 $this->setPostEditCookie( $status->value
);
1403 switch ( $status->value
) {
1404 case self
::AS_HOOK_ERROR_EXPECTED
:
1405 case self
::AS_CONTENT_TOO_BIG
:
1406 case self
::AS_ARTICLE_WAS_DELETED
:
1407 case self
::AS_CONFLICT_DETECTED
:
1408 case self
::AS_SUMMARY_NEEDED
:
1409 case self
::AS_TEXTBOX_EMPTY
:
1410 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1412 case self
::AS_BLANK_ARTICLE
:
1413 case self
::AS_SELF_REDIRECT
:
1416 case self
::AS_HOOK_ERROR
:
1419 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1420 case self
::AS_PARSE_ERROR
:
1421 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1424 case self
::AS_SUCCESS_NEW_ARTICLE
:
1425 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1426 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1427 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1430 case self
::AS_SUCCESS_UPDATE
:
1432 $sectionanchor = $resultDetails['sectionanchor'];
1434 // Give extensions a chance to modify URL query on update
1436 'ArticleUpdateBeforeRedirect',
1437 array( $this->mArticle
, &$sectionanchor, &$extraQuery )
1440 if ( $resultDetails['redirect'] ) {
1441 if ( $extraQuery == '' ) {
1442 $extraQuery = 'redirect=no';
1444 $extraQuery = 'redirect=no&' . $extraQuery;
1447 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1450 case self
::AS_SPAM_ERROR
:
1451 $this->spamPageWithContent( $resultDetails['spam'] );
1454 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1455 throw new UserBlockedError( $wgUser->getBlock() );
1457 case self
::AS_IMAGE_REDIRECT_ANON
:
1458 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1459 throw new PermissionsError( 'upload' );
1461 case self
::AS_READ_ONLY_PAGE_ANON
:
1462 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1463 throw new PermissionsError( 'edit' );
1465 case self
::AS_READ_ONLY_PAGE
:
1466 throw new ReadOnlyError
;
1468 case self
::AS_RATE_LIMITED
:
1469 throw new ThrottledError();
1471 case self
::AS_NO_CREATE_PERMISSION
:
1472 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1473 throw new PermissionsError( $permission );
1475 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1476 throw new PermissionsError( 'editcontentmodel' );
1479 // We don't recognize $status->value. The only way that can happen
1480 // is if an extension hook aborted from inside ArticleSave.
1481 // Render the status object into $this->hookError
1482 // FIXME this sucks, we should just use the Status object throughout
1483 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1490 * Run hooks that can filter edits just before they get saved.
1492 * @param Content $content The Content to filter.
1493 * @param Status $status For reporting the outcome to the caller
1494 * @param User $user The user performing the edit
1498 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1499 // Run old style post-section-merge edit filter
1500 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1501 array( $this, $content, &$this->hookError
, $this->summary
) )
1503 # Error messages etc. could be handled within the hook...
1504 $status->fatal( 'hookaborted' );
1505 $status->value
= self
::AS_HOOK_ERROR
;
1507 } elseif ( $this->hookError
!= '' ) {
1508 # ...or the hook could be expecting us to produce an error
1509 $status->fatal( 'hookaborted' );
1510 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1514 // Run new style post-section-merge edit filter
1515 if ( !Hooks
::run( 'EditFilterMergedContent',
1516 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1517 $user, $this->minoredit
) )
1519 # Error messages etc. could be handled within the hook...
1520 if ( $status->isGood() ) {
1521 $status->fatal( 'hookaborted' );
1522 // Not setting $this->hookError here is a hack to allow the hook
1523 // to cause a return to the edit page without $this->hookError
1524 // being set. This is used by ConfirmEdit to display a captcha
1525 // without any error message cruft.
1527 $this->hookError
= $status->getWikiText();
1529 // Use the existing $status->value if the hook set it
1530 if ( !$status->value
) {
1531 $status->value
= self
::AS_HOOK_ERROR
;
1534 } elseif ( !$status->isOK() ) {
1535 # ...or the hook could be expecting us to produce an error
1536 // FIXME this sucks, we should just use the Status object throughout
1537 $this->hookError
= $status->getWikiText();
1538 $status->fatal( 'hookaborted' );
1539 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1547 * Return the summary to be used for a new section.
1549 * @param string $sectionanchor Set to the section anchor text
1552 private function newSectionSummary( &$sectionanchor = null ) {
1555 if ( $this->sectiontitle
!== '' ) {
1556 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1557 // If no edit summary was specified, create one automatically from the section
1558 // title and have it link to the new section. Otherwise, respect the summary as
1560 if ( $this->summary
=== '' ) {
1561 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1562 return wfMessage( 'newsectionsummary' )
1563 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1565 } elseif ( $this->summary
!== '' ) {
1566 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1567 # This is a new section, so create a link to the new section
1568 # in the revision summary.
1569 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1570 return wfMessage( 'newsectionsummary' )
1571 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1573 return $this->summary
;
1577 * Attempt submission (no UI)
1579 * @param array $result Array to add statuses to, currently with the
1581 * - spam (string): Spam string from content if any spam is detected by
1583 * - sectionanchor (string): Section anchor for a section save.
1584 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1586 * - redirect (bool): Set if doEditContent is OK. True if resulting
1587 * revision is a redirect.
1588 * @param bool $bot True if edit is being made under the bot right.
1590 * @return Status Status object, possibly with a message, but always with
1591 * one of the AS_* constants in $status->value,
1593 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1594 * various error display idiosyncrasies. There are also lots of cases
1595 * where error metadata is set in the object and retrieved later instead
1596 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1597 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1600 function internalAttemptSave( &$result, $bot = false ) {
1601 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1602 global $wgContentHandlerUseDB;
1604 $status = Status
::newGood();
1606 if ( !Hooks
::run( 'EditPage::attemptSave', array( $this ) ) ) {
1607 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1608 $status->fatal( 'hookaborted' );
1609 $status->value
= self
::AS_HOOK_ERROR
;
1613 $spam = $wgRequest->getText( 'wpAntispam' );
1614 if ( $spam !== '' ) {
1617 $wgUser->getName() .
1619 $this->mTitle
->getPrefixedText() .
1620 '" submitted bogus field "' .
1624 $status->fatal( 'spamprotectionmatch', false );
1625 $status->value
= self
::AS_SPAM_ERROR
;
1630 # Construct Content object
1631 $textbox_content = $this->toEditContent( $this->textbox1
);
1632 } catch ( MWContentSerializationException
$ex ) {
1634 'content-failed-to-parse',
1635 $this->contentModel
,
1636 $this->contentFormat
,
1639 $status->value
= self
::AS_PARSE_ERROR
;
1643 # Check image redirect
1644 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1645 $textbox_content->isRedirect() &&
1646 !$wgUser->isAllowed( 'upload' )
1648 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1649 $status->setResult( false, $code );
1655 $match = self
::matchSummarySpamRegex( $this->summary
);
1656 if ( $match === false && $this->section
== 'new' ) {
1657 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1658 # regular summaries, it is added to the actual wikitext.
1659 if ( $this->sectiontitle
!== '' ) {
1660 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1661 $match = self
::matchSpamRegex( $this->sectiontitle
);
1663 # This branch is taken when the "Add Topic" user interface is used, or the API
1664 # is used with the 'summary' parameter.
1665 $match = self
::matchSpamRegex( $this->summary
);
1668 if ( $match === false ) {
1669 $match = self
::matchSpamRegex( $this->textbox1
);
1671 if ( $match !== false ) {
1672 $result['spam'] = $match;
1673 $ip = $wgRequest->getIP();
1674 $pdbk = $this->mTitle
->getPrefixedDBkey();
1675 $match = str_replace( "\n", '', $match );
1676 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1677 $status->fatal( 'spamprotectionmatch', $match );
1678 $status->value
= self
::AS_SPAM_ERROR
;
1683 array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) )
1685 # Error messages etc. could be handled within the hook...
1686 $status->fatal( 'hookaborted' );
1687 $status->value
= self
::AS_HOOK_ERROR
;
1689 } elseif ( $this->hookError
!= '' ) {
1690 # ...or the hook could be expecting us to produce an error
1691 $status->fatal( 'hookaborted' );
1692 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1696 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1697 // Auto-block user's IP if the account was "hard" blocked
1698 $wgUser->spreadAnyEditBlock();
1699 # Check block state against master, thus 'false'.
1700 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1704 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1705 if ( $this->kblength
> $wgMaxArticleSize ) {
1706 // Error will be displayed by showEditForm()
1707 $this->tooBig
= true;
1708 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1712 if ( !$wgUser->isAllowed( 'edit' ) ) {
1713 if ( $wgUser->isAnon() ) {
1714 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1717 $status->fatal( 'readonlytext' );
1718 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1723 $changingContentModel = false;
1724 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1725 if ( !$wgContentHandlerUseDB ) {
1726 $status->fatal( 'editpage-cannot-use-custom-model' );
1727 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1729 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1730 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1734 $changingContentModel = true;
1735 $oldContentModel = $this->mTitle
->getContentModel();
1738 if ( $this->changeTags
) {
1739 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1740 $this->changeTags
, $wgUser );
1741 if ( !$changeTagsStatus->isOK() ) {
1742 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1743 return $changeTagsStatus;
1747 if ( wfReadOnly() ) {
1748 $status->fatal( 'readonlytext' );
1749 $status->value
= self
::AS_READ_ONLY_PAGE
;
1752 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1753 $status->fatal( 'actionthrottledtext' );
1754 $status->value
= self
::AS_RATE_LIMITED
;
1758 # If the article has been deleted while editing, don't save it without
1760 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1761 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1765 # Load the page data from the master. If anything changes in the meantime,
1766 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1767 $this->page
->loadPageData( 'fromdbmaster' );
1768 $new = !$this->page
->exists();
1771 // Late check for create permission, just in case *PARANOIA*
1772 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1773 $status->fatal( 'nocreatetext' );
1774 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1775 wfDebug( __METHOD__
. ": no create permission\n" );
1779 // Don't save a new page if it's blank or if it's a MediaWiki:
1780 // message with content equivalent to default (allow empty pages
1781 // in this case to disable messages, see bug 50124)
1782 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1783 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1784 $defaultText = $defaultMessageText;
1789 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1790 $this->blankArticle
= true;
1791 $status->fatal( 'blankarticle' );
1792 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1796 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1800 $content = $textbox_content;
1802 $result['sectionanchor'] = '';
1803 if ( $this->section
== 'new' ) {
1804 if ( $this->sectiontitle
!== '' ) {
1805 // Insert the section title above the content.
1806 $content = $content->addSectionHeader( $this->sectiontitle
);
1807 } elseif ( $this->summary
!== '' ) {
1808 // Insert the section title above the content.
1809 $content = $content->addSectionHeader( $this->summary
);
1811 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1814 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1818 # Article exists. Check for edit conflict.
1820 $this->page
->clear(); # Force reload of dates, etc.
1821 $timestamp = $this->page
->getTimestamp();
1823 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1825 if ( $timestamp != $this->edittime
) {
1826 $this->isConflict
= true;
1827 if ( $this->section
== 'new' ) {
1828 if ( $this->page
->getUserText() == $wgUser->getName() &&
1829 $this->page
->getComment() == $this->newSectionSummary()
1831 // Probably a duplicate submission of a new comment.
1832 // This can happen when squid resends a request after
1833 // a timeout but the first one actually went through.
1835 . ": duplicate new section submission; trigger edit conflict!\n" );
1837 // New comment; suppress conflict.
1838 $this->isConflict
= false;
1839 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1841 } elseif ( $this->section
== ''
1842 && Revision
::userWasLastToEdit(
1843 DB_MASTER
, $this->mTitle
->getArticleID(),
1844 $wgUser->getId(), $this->edittime
1847 # Suppress edit conflict with self, except for section edits where merging is required.
1848 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1849 $this->isConflict
= false;
1853 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1854 if ( $this->sectiontitle
!== '' ) {
1855 $sectionTitle = $this->sectiontitle
;
1857 $sectionTitle = $this->summary
;
1862 if ( $this->isConflict
) {
1864 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1865 . " (article time '{$timestamp}')\n" );
1867 $content = $this->page
->replaceSectionContent(
1874 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1875 $content = $this->page
->replaceSectionContent(
1882 if ( is_null( $content ) ) {
1883 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1884 $this->isConflict
= true;
1885 $content = $textbox_content; // do not try to merge here!
1886 } elseif ( $this->isConflict
) {
1888 if ( $this->mergeChangesIntoContent( $content ) ) {
1889 // Successful merge! Maybe we should tell the user the good news?
1890 $this->isConflict
= false;
1891 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1893 $this->section
= '';
1894 $this->textbox1
= ContentHandler
::getContentText( $content );
1895 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1899 if ( $this->isConflict
) {
1900 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1904 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1908 if ( $this->section
== 'new' ) {
1909 // Handle the user preference to force summaries here
1910 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1911 $this->missingSummary
= true;
1912 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1913 $status->value
= self
::AS_SUMMARY_NEEDED
;
1917 // Do not allow the user to post an empty comment
1918 if ( $this->textbox1
== '' ) {
1919 $this->missingComment
= true;
1920 $status->fatal( 'missingcommenttext' );
1921 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1924 } elseif ( !$this->allowBlankSummary
1925 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1926 && !$content->isRedirect()
1927 && md5( $this->summary
) == $this->autoSumm
1929 $this->missingSummary
= true;
1930 $status->fatal( 'missingsummary' );
1931 $status->value
= self
::AS_SUMMARY_NEEDED
;
1936 $sectionanchor = '';
1937 if ( $this->section
== 'new' ) {
1938 $this->summary
= $this->newSectionSummary( $sectionanchor );
1939 } elseif ( $this->section
!= '' ) {
1940 # Try to get a section anchor from the section source, redirect
1941 # to edited section if header found.
1942 # XXX: Might be better to integrate this into Article::replaceSection
1943 # for duplicate heading checking and maybe parsing.
1944 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1945 # We can't deal with anchors, includes, html etc in the header for now,
1946 # headline would need to be parsed to improve this.
1947 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1948 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1951 $result['sectionanchor'] = $sectionanchor;
1953 // Save errors may fall down to the edit form, but we've now
1954 // merged the section into full text. Clear the section field
1955 // so that later submission of conflict forms won't try to
1956 // replace that into a duplicated mess.
1957 $this->textbox1
= $this->toEditText( $content );
1958 $this->section
= '';
1960 $status->value
= self
::AS_SUCCESS_UPDATE
;
1963 if ( !$this->allowSelfRedirect
1964 && $content->isRedirect()
1965 && $content->getRedirectTarget()->equals( $this->getTitle() )
1967 // If the page already redirects to itself, don't warn.
1968 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
1969 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
1970 $this->selfRedirect
= true;
1971 $status->fatal( 'selfredirect' );
1972 $status->value
= self
::AS_SELF_REDIRECT
;
1977 // Check for length errors again now that the section is merged in
1978 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1979 if ( $this->kblength
> $wgMaxArticleSize ) {
1980 $this->tooBig
= true;
1981 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1985 $flags = EDIT_AUTOSUMMARY |
1986 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1987 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1988 ( $bot ? EDIT_FORCE_BOT
: 0 );
1990 $doEditStatus = $this->page
->doEditContent(
1996 $content->getDefaultFormat()
1999 if ( !$doEditStatus->isOK() ) {
2000 // Failure from doEdit()
2001 // Show the edit conflict page for certain recognized errors from doEdit(),
2002 // but don't show it for errors from extension hooks
2003 $errors = $doEditStatus->getErrorsArray();
2004 if ( in_array( $errors[0][0],
2005 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
2007 $this->isConflict
= true;
2008 // Destroys data doEdit() put in $status->value but who cares
2009 $doEditStatus->value
= self
::AS_END
;
2011 return $doEditStatus;
2014 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2015 if ( $result['nullEdit'] ) {
2016 // We don't know if it was a null edit until now, so increment here
2017 $wgUser->pingLimiter( 'linkpurge' );
2019 $result['redirect'] = $content->isRedirect();
2021 $this->updateWatchlist();
2023 if ( $this->changeTags
&& isset( $doEditStatus->value
['revision'] ) ) {
2024 // If a revision was created, apply any change tags that were requested
2025 $addTags = $this->changeTags
;
2026 $revId = $doEditStatus->value
['revision']->getId();
2027 // Defer this both for performance and so that addTags() sees the rc_id
2028 // since the recentchange entry addition is deferred first (bug T100248)
2029 DeferredUpdates
::addCallableUpdate( function() use ( $addTags, $revId ) {
2030 ChangeTags
::addTags( $addTags, null, $revId );
2034 // If the content model changed, add a log entry
2035 if ( $changingContentModel ) {
2036 $this->addContentModelChangeLogEntry(
2039 $this->contentModel
,
2049 * @param string $oldModel
2050 * @param string $newModel
2051 * @param string $reason
2053 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2054 $log = new ManualLogEntry( 'contentmodel', 'change' );
2055 $log->setPerformer( $user );
2056 $log->setTarget( $this->mTitle
);
2057 $log->setComment( $reason );
2058 $log->setParameters( array(
2059 '4::oldmodel' => $oldModel,
2060 '5::newmodel' => $newModel
2062 $logid = $log->insert();
2063 $log->publish( $logid );
2067 * Register the change of watch status
2069 protected function updateWatchlist() {
2072 if ( !$wgUser->isLoggedIn() ) {
2077 $title = $this->mTitle
;
2078 $watch = $this->watchthis
;
2079 // Do this in its own transaction to reduce contention...
2080 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2081 if ( $watch == $user->isWatched( $title, WatchedItem
::IGNORE_USER_RIGHTS
) ) {
2082 return; // nothing to change
2084 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2089 * Attempts to do 3-way merge of edit content with a base revision
2090 * and current content, in case of edit conflict, in whichever way appropriate
2091 * for the content type.
2095 * @param Content $editContent
2099 private function mergeChangesIntoContent( &$editContent ) {
2101 $db = wfGetDB( DB_MASTER
);
2103 // This is the revision the editor started from
2104 $baseRevision = $this->getBaseRevision();
2105 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2107 if ( is_null( $baseContent ) ) {
2111 // The current state, we want to merge updates into it
2112 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2113 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2115 if ( is_null( $currentContent ) ) {
2119 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2121 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2124 $editContent = $result;
2134 function getBaseRevision() {
2135 if ( !$this->mBaseRevision
) {
2136 $db = wfGetDB( DB_MASTER
);
2137 $this->mBaseRevision
= Revision
::loadFromTimestamp(
2138 $db, $this->mTitle
, $this->edittime
);
2140 return $this->mBaseRevision
;
2144 * Check given input text against $wgSpamRegex, and return the text of the first match.
2146 * @param string $text
2148 * @return string|bool Matching string or false
2150 public static function matchSpamRegex( $text ) {
2151 global $wgSpamRegex;
2152 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2153 $regexes = (array)$wgSpamRegex;
2154 return self
::matchSpamRegexInternal( $text, $regexes );
2158 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2160 * @param string $text
2162 * @return string|bool Matching string or false
2164 public static function matchSummarySpamRegex( $text ) {
2165 global $wgSummarySpamRegex;
2166 $regexes = (array)$wgSummarySpamRegex;
2167 return self
::matchSpamRegexInternal( $text, $regexes );
2171 * @param string $text
2172 * @param array $regexes
2173 * @return bool|string
2175 protected static function matchSpamRegexInternal( $text, $regexes ) {
2176 foreach ( $regexes as $regex ) {
2178 if ( preg_match( $regex, $text, $matches ) ) {
2185 function setHeaders() {
2186 global $wgOut, $wgUser, $wgAjaxEditStash;
2188 $wgOut->addModules( 'mediawiki.action.edit' );
2189 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2191 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2192 // The addition of default buttons is handled by getEditToolbar() which
2193 // has its own dependency on this module. The call here ensures the module
2194 // is loaded in time (it has position "top") for other modules to register
2195 // buttons (e.g. extensions, gadgets, user scripts).
2196 $wgOut->addModules( 'mediawiki.toolbar' );
2199 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2200 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2203 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2204 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2207 if ( $wgAjaxEditStash ) {
2208 $wgOut->addModules( 'mediawiki.action.edit.stash' );
2211 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2213 # Enabled article-related sidebar, toplinks, etc.
2214 $wgOut->setArticleRelated( true );
2216 $contextTitle = $this->getContextTitle();
2217 if ( $this->isConflict
) {
2218 $msg = 'editconflict';
2219 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2220 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2222 $msg = $contextTitle->exists()
2223 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2224 && $contextTitle->getDefaultMessageText() !== false
2230 # Use the title defined by DISPLAYTITLE magic word when present
2231 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2232 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2233 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2234 if ( $displayTitle === false ) {
2235 $displayTitle = $contextTitle->getPrefixedText();
2237 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2238 # Transmit the name of the message to JavaScript for live preview
2239 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2240 $wgOut->addJsConfigVars( 'wgEditMessage', $msg );
2244 * Show all applicable editing introductions
2246 protected function showIntro() {
2247 global $wgOut, $wgUser;
2248 if ( $this->suppressIntro
) {
2252 $namespace = $this->mTitle
->getNamespace();
2254 if ( $namespace == NS_MEDIAWIKI
) {
2255 # Show a warning if editing an interface message
2256 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2257 # If this is a default message (but not css or js),
2258 # show a hint that it is translatable on translatewiki.net
2259 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2260 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2262 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2263 if ( $defaultMessageText !== false ) {
2264 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2265 'translateinterface' );
2268 } elseif ( $namespace == NS_FILE
) {
2269 # Show a hint to shared repo
2270 $file = wfFindFile( $this->mTitle
);
2271 if ( $file && !$file->isLocal() ) {
2272 $descUrl = $file->getDescriptionUrl();
2273 # there must be a description url to show a hint to shared repo
2275 if ( !$this->mTitle
->exists() ) {
2276 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2277 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2280 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2281 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2288 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2289 # Show log extract when the user is currently blocked
2290 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2291 $parts = explode( '/', $this->mTitle
->getText(), 2 );
2292 $username = $parts[0];
2293 $user = User
::newFromName( $username, false /* allow IP users*/ );
2294 $ip = User
::isIP( $username );
2295 $block = Block
::newFromTarget( $user, $user );
2296 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2297 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2298 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2299 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2300 # Show log extract if the user is currently blocked
2301 LogEventsList
::showLogExtract(
2304 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2308 'showIfEmpty' => false,
2310 'blocked-notice-logextract',
2311 $user->getName() # Support GENDER in notice
2317 # Try to add a custom edit intro, or use the standard one if this is not possible.
2318 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2319 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2320 wfMessage( 'helppage' )->inContentLanguage()->text()
2322 if ( $wgUser->isLoggedIn() ) {
2323 $wgOut->wrapWikiMsg(
2324 // Suppress the external link icon, consider the help url an internal one
2325 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2332 $wgOut->wrapWikiMsg(
2333 // Suppress the external link icon, consider the help url an internal one
2334 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2336 'newarticletextanon',
2342 # Give a notice if the user is editing a deleted/moved page...
2343 if ( !$this->mTitle
->exists() ) {
2344 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
2348 'conds' => array( "log_action != 'revision'" ),
2349 'showIfEmpty' => false,
2350 'msgKey' => array( 'recreate-moveddeleted-warn' )
2357 * Attempt to show a custom editing introduction, if supplied
2361 protected function showCustomIntro() {
2362 if ( $this->editintro
) {
2363 $title = Title
::newFromText( $this->editintro
);
2364 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2366 // Added using template syntax, to take <noinclude>'s into account.
2367 $wgOut->addWikiTextTitleTidy(
2368 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2378 * Gets an editable textual representation of $content.
2379 * The textual representation can be turned by into a Content object by the
2380 * toEditContent() method.
2382 * If $content is null or false or a string, $content is returned unchanged.
2384 * If the given Content object is not of a type that can be edited using
2385 * the text base EditPage, an exception will be raised. Set
2386 * $this->allowNonTextContent to true to allow editing of non-textual
2389 * @param Content|null|bool|string $content
2390 * @return string The editable text form of the content.
2392 * @throws MWException If $content is not an instance of TextContent and
2393 * $this->allowNonTextContent is not true.
2395 protected function toEditText( $content ) {
2396 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2400 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2401 throw new MWException( 'This content model is not supported: '
2402 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2405 return $content->serialize( $this->contentFormat
);
2409 * Turns the given text into a Content object by unserializing it.
2411 * If the resulting Content object is not of a type that can be edited using
2412 * the text base EditPage, an exception will be raised. Set
2413 * $this->allowNonTextContent to true to allow editing of non-textual
2416 * @param string|null|bool $text Text to unserialize
2417 * @return Content The content object created from $text. If $text was false
2418 * or null, false resp. null will be returned instead.
2420 * @throws MWException If unserializing the text results in a Content
2421 * object that is not an instance of TextContent and
2422 * $this->allowNonTextContent is not true.
2424 protected function toEditContent( $text ) {
2425 if ( $text === false ||
$text === null ) {
2429 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2430 $this->contentModel
, $this->contentFormat
);
2432 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2433 throw new MWException( 'This content model is not supported: '
2434 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2441 * Send the edit form and related headers to $wgOut
2442 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2443 * during form output near the top, for captchas and the like.
2445 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2446 * use the EditPage::showEditForm:fields hook instead.
2448 function showEditForm( $formCallback = null ) {
2449 global $wgOut, $wgUser;
2451 # need to parse the preview early so that we know which templates are used,
2452 # otherwise users with "show preview after edit box" will get a blank list
2453 # we parse this near the beginning so that setHeaders can do the title
2454 # setting work instead of leaving it in getPreviewText
2455 $previewOutput = '';
2456 if ( $this->formtype
== 'preview' ) {
2457 $previewOutput = $this->getPreviewText();
2460 Hooks
::run( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2462 $this->setHeaders();
2464 if ( $this->showHeader() === false ) {
2468 $wgOut->addHTML( $this->editFormPageTop
);
2470 if ( $wgUser->getOption( 'previewontop' ) ) {
2471 $this->displayPreviewArea( $previewOutput, true );
2474 $wgOut->addHTML( $this->editFormTextTop
);
2476 $showToolbar = true;
2477 if ( $this->wasDeletedSinceLastEdit() ) {
2478 if ( $this->formtype
== 'save' ) {
2479 // Hide the toolbar and edit area, user can click preview to get it back
2480 // Add an confirmation checkbox and explanation.
2481 $showToolbar = false;
2483 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2484 'deletedwhileediting' );
2488 // @todo add EditForm plugin interface and use it here!
2489 // search for textarea1 and textares2, and allow EditForm to override all uses.
2490 $wgOut->addHTML( Html
::openElement(
2493 'id' => self
::EDITFORM_ID
,
2494 'name' => self
::EDITFORM_ID
,
2496 'action' => $this->getActionURL( $this->getContextTitle() ),
2497 'enctype' => 'multipart/form-data'
2501 if ( is_callable( $formCallback ) ) {
2502 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2503 call_user_func_array( $formCallback, array( &$wgOut ) );
2506 // Add an empty field to trip up spambots
2508 Xml
::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2511 array( 'for' => 'wpAntiSpam' ),
2512 wfMessage( 'simpleantispam-label' )->parse()
2518 'name' => 'wpAntispam',
2519 'id' => 'wpAntispam',
2523 . Xml
::closeElement( 'div' )
2526 Hooks
::run( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2528 // Put these up at the top to ensure they aren't lost on early form submission
2529 $this->showFormBeforeText();
2531 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2532 $username = $this->lastDelete
->user_name
;
2533 $comment = $this->lastDelete
->log_comment
;
2535 // It is better to not parse the comment at all than to have templates expanded in the middle
2536 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2537 $key = $comment === ''
2538 ?
'confirmrecreate-noreason'
2539 : 'confirmrecreate';
2541 '<div class="mw-confirm-recreate">' .
2542 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2543 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2544 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2550 # When the summary is hidden, also hide them on preview/show changes
2551 if ( $this->nosummary
) {
2552 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2555 # If a blank edit summary was previously provided, and the appropriate
2556 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2557 # user being bounced back more than once in the event that a summary
2560 # For a bit more sophisticated detection of blank summaries, hash the
2561 # automatic one and pass that in the hidden field wpAutoSummary.
2562 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2563 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2566 if ( $this->undidRev
) {
2567 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2570 if ( $this->selfRedirect
) {
2571 $wgOut->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2574 if ( $this->hasPresetSummary
) {
2575 // If a summary has been preset using &summary= we don't want to prompt for
2576 // a different summary. Only prompt for a summary if the summary is blanked.
2578 $this->autoSumm
= md5( '' );
2581 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2582 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2584 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2585 $wgOut->addHTML( Html
::hidden( 'parentRevId',
2586 $this->parentRevId ?
: $this->mArticle
->getRevIdFetched() ) );
2588 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2589 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2591 if ( $this->section
== 'new' ) {
2592 $this->showSummaryInput( true, $this->summary
);
2593 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2596 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2598 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2599 $wgOut->addHTML( EditPage
::getEditToolbar( $this->mTitle
) );
2602 if ( $this->blankArticle
) {
2603 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2606 if ( $this->isConflict
) {
2607 // In an edit conflict bypass the overridable content form method
2608 // and fallback to the raw wpTextbox1 since editconflicts can't be
2609 // resolved between page source edits and custom ui edits using the
2611 $this->textbox2
= $this->textbox1
;
2613 $content = $this->getCurrentContent();
2614 $this->textbox1
= $this->toEditText( $content );
2616 $this->showTextbox1();
2618 $this->showContentForm();
2621 $wgOut->addHTML( $this->editFormTextAfterContent
);
2623 $this->showStandardInputs();
2625 $this->showFormAfterText();
2627 $this->showTosSummary();
2629 $this->showEditTools();
2631 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2633 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2634 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2636 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2637 Linker
::formatHiddenCategories( $this->page
->getHiddenCategories() ) ) );
2639 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'limitreport' ),
2640 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2642 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2644 if ( $this->isConflict
) {
2646 $this->showConflict();
2647 } catch ( MWContentSerializationException
$ex ) {
2648 // this can't really happen, but be nice if it does.
2650 'content-failed-to-parse',
2651 $this->contentModel
,
2652 $this->contentFormat
,
2655 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2659 // Marker for detecting truncated form data. This must be the last
2660 // parameter sent in order to be of use, so do not move me.
2661 $wgOut->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2662 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2664 if ( !$wgUser->getOption( 'previewontop' ) ) {
2665 $this->displayPreviewArea( $previewOutput, false );
2671 * Extract the section title from current section text, if any.
2673 * @param string $text
2674 * @return string|bool String or false
2676 public static function extractSectionTitle( $text ) {
2677 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2678 if ( !empty( $matches[2] ) ) {
2680 return $wgParser->stripSectionName( trim( $matches[2] ) );
2689 protected function showHeader() {
2690 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2691 global $wgAllowUserCss, $wgAllowUserJs;
2693 if ( $this->mTitle
->isTalkPage() ) {
2694 $wgOut->addWikiMsg( 'talkpagetext' );
2698 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
2699 if ( count( $editNotices ) ) {
2700 $wgOut->addHTML( implode( "\n", $editNotices ) );
2702 $msg = wfMessage( 'editnotice-notext' );
2703 if ( !$msg->isDisabled() ) {
2705 '<div class="mw-editnotice-notext">'
2706 . $msg->parseAsBlock()
2712 if ( $this->isConflict
) {
2713 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2714 $this->edittime
= $this->page
->getTimestamp();
2716 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2717 // We use $this->section to much before this and getVal('wgSection') directly in other places
2718 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2719 // Someone is welcome to try refactoring though
2720 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2724 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2725 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2726 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2727 if ( $sectionTitle !== false ) {
2728 $this->summary
= "/* $sectionTitle */ ";
2733 if ( $this->missingComment
) {
2734 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2737 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2738 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2741 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2742 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2745 if ( $this->blankArticle
) {
2746 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2749 if ( $this->selfRedirect
) {
2750 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2753 if ( $this->hookError
!== '' ) {
2754 $wgOut->addWikiText( $this->hookError
);
2757 if ( !$this->checkUnicodeCompliantBrowser() ) {
2758 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2761 if ( $this->section
!= 'new' ) {
2762 $revision = $this->mArticle
->getRevisionFetched();
2764 // Let sysop know that this will make private content public if saved
2766 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2767 $wgOut->wrapWikiMsg(
2768 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2769 'rev-deleted-text-permission'
2771 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2772 $wgOut->wrapWikiMsg(
2773 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2774 'rev-deleted-text-view'
2778 if ( !$revision->isCurrent() ) {
2779 $this->mArticle
->setOldSubtitle( $revision->getId() );
2780 $wgOut->addWikiMsg( 'editingold' );
2782 } elseif ( $this->mTitle
->exists() ) {
2783 // Something went wrong
2785 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2786 array( 'missing-revision', $this->oldid
) );
2791 if ( wfReadOnly() ) {
2792 $wgOut->wrapWikiMsg(
2793 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2794 array( 'readonlywarning', wfReadOnlyReason() )
2796 } elseif ( $wgUser->isAnon() ) {
2797 if ( $this->formtype
!= 'preview' ) {
2798 $wgOut->wrapWikiMsg(
2799 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2800 array( 'anoneditwarning',
2802 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2804 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2807 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2808 'anonpreviewwarning'
2812 if ( $this->isCssJsSubpage
) {
2813 # Check the skin exists
2814 if ( $this->isWrongCaseCssJsPage
) {
2815 $wgOut->wrapWikiMsg(
2816 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2817 array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() )
2820 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
2821 if ( $this->formtype
!== 'preview' ) {
2822 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
2823 $wgOut->wrapWikiMsg(
2824 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2825 array( 'usercssyoucanpreview' )
2829 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
2830 $wgOut->wrapWikiMsg(
2831 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2832 array( 'userjsyoucanpreview' )
2840 if ( $this->mTitle
->isProtected( 'edit' ) &&
2841 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2843 # Is the title semi-protected?
2844 if ( $this->mTitle
->isSemiProtected() ) {
2845 $noticeMsg = 'semiprotectedpagewarning';
2847 # Then it must be protected based on static groups (regular)
2848 $noticeMsg = 'protectedpagewarning';
2850 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2851 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2853 if ( $this->mTitle
->isCascadeProtected() ) {
2854 # Is this page under cascading protection from some source pages?
2855 /** @var Title[] $cascadeSources */
2856 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2857 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2858 $cascadeSourcesCount = count( $cascadeSources );
2859 if ( $cascadeSourcesCount > 0 ) {
2860 # Explain, and list the titles responsible
2861 foreach ( $cascadeSources as $page ) {
2862 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2865 $notice .= '</div>';
2866 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2868 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2869 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2871 'showIfEmpty' => false,
2872 'msgKey' => array( 'titleprotectedwarning' ),
2873 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2876 if ( $this->kblength
=== false ) {
2877 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2880 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2881 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2884 $wgLang->formatNum( $this->kblength
),
2885 $wgLang->formatNum( $wgMaxArticleSize )
2889 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2890 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2893 $wgLang->formatSize( strlen( $this->textbox1
) ),
2894 strlen( $this->textbox1
)
2899 # Add header copyright warning
2900 $this->showHeaderCopyrightWarning();
2906 * Standard summary input and label (wgSummary), abstracted so EditPage
2907 * subclasses may reorganize the form.
2908 * Note that you do not need to worry about the label's for=, it will be
2909 * inferred by the id given to the input. You can remove them both by
2910 * passing array( 'id' => false ) to $userInputAttrs.
2912 * @param string $summary The value of the summary input
2913 * @param string $labelText The html to place inside the label
2914 * @param array $inputAttrs Array of attrs to use on the input
2915 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2917 * @return array An array in the format array( $label, $input )
2919 function getSummaryInput( $summary = "", $labelText = null,
2920 $inputAttrs = null, $spanLabelAttrs = null
2922 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2923 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2924 'id' => 'wpSummary',
2925 'maxlength' => '200',
2928 'spellcheck' => 'true',
2929 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2931 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2932 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2933 'id' => "wpSummaryLabel"
2940 $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null,
2943 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2946 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2948 return array( $label, $input );
2952 * @param bool $isSubjectPreview True if this is the section subject/title
2953 * up top, or false if this is the comment summary
2954 * down below the textarea
2955 * @param string $summary The text of the summary to display
2957 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2958 global $wgOut, $wgContLang;
2959 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2960 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2961 if ( $isSubjectPreview ) {
2962 if ( $this->nosummary
) {
2966 if ( !$this->mShowSummaryField
) {
2970 $summary = $wgContLang->recodeForEdit( $summary );
2971 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2972 list( $label, $input ) = $this->getSummaryInput(
2975 array( 'class' => $summaryClass ),
2978 $wgOut->addHTML( "{$label} {$input}" );
2982 * @param bool $isSubjectPreview True if this is the section subject/title
2983 * up top, or false if this is the comment summary
2984 * down below the textarea
2985 * @param string $summary The text of the summary to display
2988 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2989 // avoid spaces in preview, gets always trimmed on save
2990 $summary = trim( $summary );
2991 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2997 if ( $isSubjectPreview ) {
2998 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2999 ->inContentLanguage()->text();
3002 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3004 $summary = wfMessage( $message )->parse()
3005 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3006 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
3009 protected function showFormBeforeText() {
3011 $section = htmlspecialchars( $this->section
);
3012 $wgOut->addHTML( <<<HTML
3013 <input type='hidden' value="{$section}" name="wpSection"/>
3014 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
3015 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
3016 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
3020 if ( !$this->checkUnicodeCompliantBrowser() ) {
3021 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
3025 protected function showFormAfterText() {
3026 global $wgOut, $wgUser;
3028 * To make it harder for someone to slip a user a page
3029 * which submits an edit form to the wiki without their
3030 * knowledge, a random token is associated with the login
3031 * session. If it's not passed back with the submission,
3032 * we won't save the page, or render user JavaScript and
3035 * For anon editors, who may not have a session, we just
3036 * include the constant suffix to prevent editing from
3037 * broken text-mangling proxies.
3039 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
3043 * Subpage overridable method for printing the form for page content editing
3044 * By default this simply outputs wpTextbox1
3045 * Subclasses can override this to provide a custom UI for editing;
3046 * be it a form, or simply wpTextbox1 with a modified content that will be
3047 * reverse modified when extracted from the post data.
3048 * Note that this is basically the inverse for importContentFormData
3050 protected function showContentForm() {
3051 $this->showTextbox1();
3055 * Method to output wpTextbox1
3056 * The $textoverride method can be used by subclasses overriding showContentForm
3057 * to pass back to this method.
3059 * @param array $customAttribs Array of html attributes to use in the textarea
3060 * @param string $textoverride Optional text to override $this->textarea1 with
3062 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3063 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3064 $attribs = array( 'style' => 'display:none;' );
3066 $classes = array(); // Textarea CSS
3067 if ( $this->mTitle
->isProtected( 'edit' ) &&
3068 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
3070 # Is the title semi-protected?
3071 if ( $this->mTitle
->isSemiProtected() ) {
3072 $classes[] = 'mw-textarea-sprotected';
3074 # Then it must be protected based on static groups (regular)
3075 $classes[] = 'mw-textarea-protected';
3077 # Is the title cascade-protected?
3078 if ( $this->mTitle
->isCascadeProtected() ) {
3079 $classes[] = 'mw-textarea-cprotected';
3083 $attribs = array( 'tabindex' => 1 );
3085 if ( is_array( $customAttribs ) ) {
3086 $attribs +
= $customAttribs;
3089 if ( count( $classes ) ) {
3090 if ( isset( $attribs['class'] ) ) {
3091 $classes[] = $attribs['class'];
3093 $attribs['class'] = implode( ' ', $classes );
3098 $textoverride !== null ?
$textoverride : $this->textbox1
,
3104 protected function showTextbox2() {
3105 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
3108 protected function showTextbox( $text, $name, $customAttribs = array() ) {
3109 global $wgOut, $wgUser;
3111 $wikitext = $this->safeUnicodeOutput( $text );
3112 if ( strval( $wikitext ) !== '' ) {
3113 // Ensure there's a newline at the end, otherwise adding lines
3115 // But don't add a newline if the ext is empty, or Firefox in XHTML
3116 // mode will show an extra newline. A bit annoying.
3120 $attribs = $customAttribs +
array(
3123 'cols' => $wgUser->getIntOption( 'cols' ),
3124 'rows' => $wgUser->getIntOption( 'rows' ),
3125 // Avoid PHP notices when appending preferences
3126 // (appending allows customAttribs['style'] to still work).
3130 $pageLang = $this->mTitle
->getPageLanguage();
3131 $attribs['lang'] = $pageLang->getHtmlCode();
3132 $attribs['dir'] = $pageLang->getDir();
3134 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3137 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3141 $classes[] = 'ontop';
3144 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3146 if ( $this->formtype
!= 'preview' ) {
3147 $attribs['style'] = 'display: none;';
3150 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
3152 if ( $this->formtype
== 'preview' ) {
3153 $this->showPreview( $previewOutput );
3155 // Empty content container for LivePreview
3156 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3157 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3158 'class' => 'mw-content-' . $pageViewLang->getDir() );
3159 $wgOut->addHTML( Html
::rawElement( 'div', $attribs ) );
3162 $wgOut->addHTML( '</div>' );
3164 if ( $this->formtype
== 'diff' ) {
3167 } catch ( MWContentSerializationException
$ex ) {
3169 'content-failed-to-parse',
3170 $this->contentModel
,
3171 $this->contentFormat
,
3174 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3180 * Append preview output to $wgOut.
3181 * Includes category rendering if this is a category page.
3183 * @param string $text The HTML to be output for the preview.
3185 protected function showPreview( $text ) {
3187 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3188 $this->mArticle
->openShowCategory();
3190 # This hook seems slightly odd here, but makes things more
3191 # consistent for extensions.
3192 Hooks
::run( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3193 $wgOut->addHTML( $text );
3194 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3195 $this->mArticle
->closeShowCategory();
3200 * Get a diff between the current contents of the edit box and the
3201 * version of the page we're editing from.
3203 * If this is a section edit, we'll replace the section as for final
3204 * save and then make a comparison.
3206 function showDiff() {
3207 global $wgUser, $wgContLang, $wgOut;
3209 $oldtitlemsg = 'currentrev';
3210 # if message does not exist, show diff against the preloaded default
3211 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3212 $oldtext = $this->mTitle
->getDefaultMessageText();
3213 if ( $oldtext !== false ) {
3214 $oldtitlemsg = 'defaultmessagetext';
3215 $oldContent = $this->toEditContent( $oldtext );
3220 $oldContent = $this->getCurrentContent();
3223 $textboxContent = $this->toEditContent( $this->textbox1
);
3225 $newContent = $this->page
->replaceSectionContent(
3226 $this->section
, $textboxContent,
3227 $this->summary
, $this->edittime
);
3229 if ( $newContent ) {
3230 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3231 Hooks
::run( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3233 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
3234 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
3237 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3238 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3239 $newtitle = wfMessage( 'yourtext' )->parse();
3241 if ( !$oldContent ) {
3242 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3245 if ( !$newContent ) {
3246 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3249 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3250 $de->setContent( $oldContent, $newContent );
3252 $difftext = $de->getDiff( $oldtitle, $newtitle );
3253 $de->showDiffStyle();
3258 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3262 * Show the header copyright warning.
3264 protected function showHeaderCopyrightWarning() {
3265 $msg = 'editpage-head-copy-warn';
3266 if ( !wfMessage( $msg )->isDisabled() ) {
3268 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3269 'editpage-head-copy-warn' );
3274 * Give a chance for site and per-namespace customizations of
3275 * terms of service summary link that might exist separately
3276 * from the copyright notice.
3278 * This will display between the save button and the edit tools,
3279 * so should remain short!
3281 protected function showTosSummary() {
3282 $msg = 'editpage-tos-summary';
3283 Hooks
::run( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
3284 if ( !wfMessage( $msg )->isDisabled() ) {
3286 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3287 $wgOut->addWikiMsg( $msg );
3288 $wgOut->addHTML( '</div>' );
3292 protected function showEditTools() {
3294 $wgOut->addHTML( '<div class="mw-editTools">' .
3295 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3300 * Get the copyright warning
3302 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3305 protected function getCopywarn() {
3306 return self
::getCopyrightWarning( $this->mTitle
);
3310 * Get the copyright warning, by default returns wikitext
3312 * @param Title $title
3313 * @param string $format Output format, valid values are any function of a Message object
3316 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3317 global $wgRightsText;
3318 if ( $wgRightsText ) {
3319 $copywarnMsg = array( 'copyrightwarning',
3320 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3323 $copywarnMsg = array( 'copyrightwarning2',
3324 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3326 // Allow for site and per-namespace customization of contribution/copyright notice.
3327 Hooks
::run( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3329 return "<div id=\"editpage-copywarn\">\n" .
3330 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3334 * Get the Limit report for page previews
3337 * @param ParserOutput $output ParserOutput object from the parse
3338 * @return string HTML
3340 public static function getPreviewLimitReport( $output ) {
3341 if ( !$output ||
!$output->getLimitReportData() ) {
3345 $limitReport = Html
::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3346 wfMessage( 'limitreport-title' )->parseAsBlock()
3349 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3350 $limitReport .= Html
::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3352 $limitReport .= Html
::openElement( 'table', array(
3353 'class' => 'preview-limit-report wikitable'
3355 Html
::openElement( 'tbody' );
3357 foreach ( $output->getLimitReportData() as $key => $value ) {
3358 if ( Hooks
::run( 'ParserLimitReportFormat',
3359 array( $key, &$value, &$limitReport, true, true )
3361 $keyMsg = wfMessage( $key );
3362 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3363 if ( !$valueMsg->exists() ) {
3364 $valueMsg = new RawMessage( '$1' );
3366 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3367 $limitReport .= Html
::openElement( 'tr' ) .
3368 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3369 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3370 Html
::closeElement( 'tr' );
3375 $limitReport .= Html
::closeElement( 'tbody' ) .
3376 Html
::closeElement( 'table' ) .
3377 Html
::closeElement( 'div' );
3379 return $limitReport;
3382 protected function showStandardInputs( &$tabindex = 2 ) {
3384 $wgOut->addHTML( "<div class='editOptions'>\n" );
3386 if ( $this->section
!= 'new' ) {
3387 $this->showSummaryInput( false, $this->summary
);
3388 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3391 $checkboxes = $this->getCheckboxes( $tabindex,
3392 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
3393 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3395 // Show copyright warning.
3396 $wgOut->addWikiText( $this->getCopywarn() );
3397 $wgOut->addHTML( $this->editFormTextAfterWarn
);
3399 $wgOut->addHTML( "<div class='editButtons'>\n" );
3400 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3402 $cancel = $this->getCancelLink();
3403 if ( $cancel !== '' ) {
3404 $cancel .= Html
::element( 'span',
3405 array( 'class' => 'mw-editButtons-pipe-separator' ),
3406 wfMessage( 'pipe-separator' )->text() );
3409 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3410 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3412 'target' => 'helpwindow',
3413 'href' => $edithelpurl,
3415 $edithelp = Html
::linkButton( wfMessage( 'edithelp' )->text(),
3416 $attrs, array( 'mw-ui-quiet' ) ) .
3417 wfMessage( 'word-separator' )->escaped() .
3418 wfMessage( 'newwindow' )->parse();
3420 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3421 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3422 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3424 Hooks
::run( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3426 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3430 * Show an edit conflict. textbox1 is already shown in showEditForm().
3431 * If you want to use another entry point to this function, be careful.
3433 protected function showConflict() {
3436 if ( Hooks
::run( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3437 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3439 $content1 = $this->toEditContent( $this->textbox1
);
3440 $content2 = $this->toEditContent( $this->textbox2
);
3442 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3443 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3444 $de->setContent( $content2, $content1 );
3446 wfMessage( 'yourtext' )->parse(),
3447 wfMessage( 'storedversion' )->text()
3450 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3451 $this->showTextbox2();
3458 public function getCancelLink() {
3459 $cancelParams = array();
3460 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3461 $cancelParams['oldid'] = $this->oldid
;
3463 $attrs = array( 'id' => 'mw-editform-cancel' );
3465 return Linker
::linkKnown(
3466 $this->getContextTitle(),
3467 wfMessage( 'cancel' )->parse(),
3468 Html
::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3474 * Returns the URL to use in the form's action attribute.
3475 * This is used by EditPage subclasses when simply customizing the action
3476 * variable in the constructor is not enough. This can be used when the
3477 * EditPage lives inside of a Special page rather than a custom page action.
3479 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3482 protected function getActionURL( Title
$title ) {
3483 return $title->getLocalURL( array( 'action' => $this->action
) );
3487 * Check if a page was deleted while the user was editing it, before submit.
3488 * Note that we rely on the logging table, which hasn't been always there,
3489 * but that doesn't matter, because this only applies to brand new
3493 protected function wasDeletedSinceLastEdit() {
3494 if ( $this->deletedSinceEdit
!== null ) {
3495 return $this->deletedSinceEdit
;
3498 $this->deletedSinceEdit
= false;
3500 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3501 $this->lastDelete
= $this->getLastDelete();
3502 if ( $this->lastDelete
) {
3503 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3504 if ( $deleteTime > $this->starttime
) {
3505 $this->deletedSinceEdit
= true;
3510 return $this->deletedSinceEdit
;
3514 * @return bool|stdClass
3516 protected function getLastDelete() {
3517 $dbr = wfGetDB( DB_SLAVE
);
3518 $data = $dbr->selectRow(
3519 array( 'logging', 'user' ),
3532 'log_namespace' => $this->mTitle
->getNamespace(),
3533 'log_title' => $this->mTitle
->getDBkey(),
3534 'log_type' => 'delete',
3535 'log_action' => 'delete',
3539 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3541 // Quick paranoid permission checks...
3542 if ( is_object( $data ) ) {
3543 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3544 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
3547 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3548 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
3556 * Get the rendered text for previewing.
3557 * @throws MWException
3560 function getPreviewText() {
3561 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3562 global $wgAllowUserCss, $wgAllowUserJs;
3564 $stats = $wgOut->getContext()->getStats();
3566 if ( $wgRawHtml && !$this->mTokenOk
) {
3567 // Could be an offsite preview attempt. This is very unsafe if
3568 // HTML is enabled, as it could be an attack.
3570 if ( $this->textbox1
!== '' ) {
3571 // Do not put big scary notice, if previewing the empty
3572 // string, which happens when you initially edit
3573 // a category page, due to automatic preview-on-open.
3574 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3575 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3577 $stats->increment( 'edit.failures.session_loss' );
3584 $content = $this->toEditContent( $this->textbox1
);
3588 'AlternateEditPreview',
3589 array( $this, &$content, &$previewHTML, &$this->mParserOutput
) )
3591 return $previewHTML;
3594 # provide a anchor link to the editform
3595 $continueEditing = '<span class="mw-continue-editing">' .
3596 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3597 wfMessage( 'continue-editing' )->text() . ']]</span>';
3598 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3599 if ( $this->mTokenOkExceptSuffix
) {
3600 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3601 $stats->increment( 'edit.failures.bad_token' );
3603 $note = wfMessage( 'session_fail_preview' )->plain();
3604 $stats->increment( 'edit.failures.session_loss' );
3606 } elseif ( $this->incompleteForm
) {
3607 $note = wfMessage( 'edit_form_incomplete' )->plain();
3608 if ( $this->mTriedSave
) {
3609 $stats->increment( 'edit.failures.incomplete_form' );
3612 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3615 $parserOptions = $this->page
->makeParserOptions( $this->mArticle
->getContext() );
3616 $parserOptions->setIsPreview( true );
3617 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3619 # don't parse non-wikitext pages, show message about preview
3620 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3621 if ( $this->mTitle
->isCssJsSubpage() ) {
3623 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3629 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3631 if ( $level === 'user' && !$wgAllowUserCss ) {
3634 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3636 if ( $level === 'user' && !$wgAllowUserJs ) {
3643 # Used messages to make sure grep find them:
3644 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3645 if ( $level && $format ) {
3646 $note = "<div id='mw-{$level}{$format}preview'>" .
3647 wfMessage( "{$level}{$format}preview" )->text() .
3648 ' ' . $continueEditing . "</div>";
3652 # If we're adding a comment, we need to show the
3653 # summary as the headline
3654 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3655 $content = $content->addSectionHeader( $this->summary
);
3658 $hook_args = array( $this, &$content );
3659 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3660 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3662 $parserOptions->enableLimitReport();
3664 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3665 # But it's now deprecated, so never mind
3667 $pstContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3668 $scopedCallback = $parserOptions->setupFakeRevision(
3669 $this->mTitle
, $pstContent, $wgUser );
3670 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3672 # Try to stash the edit for the final submission step
3673 # @todo: different date format preferences cause cache misses
3674 ApiStashEdit
::stashEditFromPreview(
3675 $this->getArticle(), $content, $pstContent,
3676 $parserOutput, $parserOptions, $parserOptions, wfTimestampNow()
3679 $parserOutput->setEditSectionTokens( false ); // no section edit links
3680 $previewHTML = $parserOutput->getText();
3681 $this->mParserOutput
= $parserOutput;
3682 $wgOut->addParserOutputMetadata( $parserOutput );
3684 if ( count( $parserOutput->getWarnings() ) ) {
3685 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3688 ScopedCallback
::consume( $scopedCallback );
3689 } catch ( MWContentSerializationException
$ex ) {
3691 'content-failed-to-parse',
3692 $this->contentModel
,
3693 $this->contentFormat
,
3696 $note .= "\n\n" . $m->parse();
3700 if ( $this->isConflict
) {
3701 $conflict = '<h2 id="mw-previewconflict">'
3702 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3704 $conflict = '<hr />';
3707 $previewhead = "<div class='previewnote'>\n" .
3708 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3709 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3711 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3712 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3713 'class' => 'mw-content-' . $pageViewLang->getDir() );
3714 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3716 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3722 function getTemplates() {
3723 if ( $this->preview ||
$this->section
!= '' ) {
3724 $templates = array();
3725 if ( !isset( $this->mParserOutput
) ) {
3728 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3729 foreach ( array_keys( $template ) as $dbk ) {
3730 $templates[] = Title
::makeTitle( $ns, $dbk );
3735 return $this->mTitle
->getTemplateLinksFrom();
3740 * Shows a bulletin board style toolbar for common editing functions.
3741 * It can be disabled in the user preferences.
3743 * @param $title Title object for the page being edited (optional)
3746 static function getEditToolbar( $title = null ) {
3747 global $wgContLang, $wgOut;
3748 global $wgEnableUploads, $wgForeignFileRepos;
3750 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3751 $showSignature = true;
3753 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
3757 * $toolarray is an array of arrays each of which includes the
3758 * opening tag, the closing tag, optionally a sample text that is
3759 * inserted between the two when no selection is highlighted
3760 * and. The tip text is shown when the user moves the mouse
3763 * Images are defined in ResourceLoaderEditToolbarModule.
3767 'id' => 'mw-editbutton-bold',
3769 'close' => '\'\'\'',
3770 'sample' => wfMessage( 'bold_sample' )->text(),
3771 'tip' => wfMessage( 'bold_tip' )->text(),
3774 'id' => 'mw-editbutton-italic',
3777 'sample' => wfMessage( 'italic_sample' )->text(),
3778 'tip' => wfMessage( 'italic_tip' )->text(),
3781 'id' => 'mw-editbutton-link',
3784 'sample' => wfMessage( 'link_sample' )->text(),
3785 'tip' => wfMessage( 'link_tip' )->text(),
3788 'id' => 'mw-editbutton-extlink',
3791 'sample' => wfMessage( 'extlink_sample' )->text(),
3792 'tip' => wfMessage( 'extlink_tip' )->text(),
3795 'id' => 'mw-editbutton-headline',
3798 'sample' => wfMessage( 'headline_sample' )->text(),
3799 'tip' => wfMessage( 'headline_tip' )->text(),
3801 $imagesAvailable ?
array(
3802 'id' => 'mw-editbutton-image',
3803 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3805 'sample' => wfMessage( 'image_sample' )->text(),
3806 'tip' => wfMessage( 'image_tip' )->text(),
3808 $imagesAvailable ?
array(
3809 'id' => 'mw-editbutton-media',
3810 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3812 'sample' => wfMessage( 'media_sample' )->text(),
3813 'tip' => wfMessage( 'media_tip' )->text(),
3816 'id' => 'mw-editbutton-nowiki',
3817 'open' => "<nowiki>",
3818 'close' => "</nowiki>",
3819 'sample' => wfMessage( 'nowiki_sample' )->text(),
3820 'tip' => wfMessage( 'nowiki_tip' )->text(),
3822 $showSignature ?
array(
3823 'id' => 'mw-editbutton-signature',
3827 'tip' => wfMessage( 'sig_tip' )->text(),
3830 'id' => 'mw-editbutton-hr',
3831 'open' => "\n----\n",
3834 'tip' => wfMessage( 'hr_tip' )->text(),
3838 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3839 foreach ( $toolarray as $tool ) {
3845 // Images are defined in ResourceLoaderEditToolbarModule
3847 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3848 // Older browsers show a "speedtip" type message only for ALT.
3849 // Ideally these should be different, realistically they
3850 // probably don't need to be.
3858 $script .= Xml
::encodeJsCall(
3859 'mw.toolbar.addButton',
3861 ResourceLoader
::inDebugMode()
3866 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
3868 $toolbar = '<div id="toolbar"></div>';
3870 Hooks
::run( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3876 * Returns an array of html code of the following checkboxes:
3879 * @param int $tabindex Current tabindex
3880 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3881 * status of the checkbox
3885 public function getCheckboxes( &$tabindex, $checked ) {
3886 global $wgUser, $wgUseMediaWikiUIEverywhere;
3888 $checkboxes = array();
3890 // don't show the minor edit checkbox if it's a new page or section
3891 if ( !$this->isNew
) {
3892 $checkboxes['minor'] = '';
3893 $minorLabel = wfMessage( 'minoredit' )->parse();
3894 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3896 'tabindex' => ++
$tabindex,
3897 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3898 'id' => 'wpMinoredit',
3901 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3902 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3903 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3904 ">{$minorLabel}</label>";
3906 if ( $wgUseMediaWikiUIEverywhere ) {
3907 $checkboxes['minor'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3909 Html
::closeElement( 'div' );
3911 $checkboxes['minor'] = $minorEditHtml;
3916 $watchLabel = wfMessage( 'watchthis' )->parse();
3917 $checkboxes['watch'] = '';
3918 if ( $wgUser->isLoggedIn() ) {
3920 'tabindex' => ++
$tabindex,
3921 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3922 'id' => 'wpWatchthis',
3925 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3926 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3927 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3928 ">{$watchLabel}</label>";
3929 if ( $wgUseMediaWikiUIEverywhere ) {
3930 $checkboxes['watch'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3932 Html
::closeElement( 'div' );
3934 $checkboxes['watch'] = $watchThisHtml;
3937 Hooks
::run( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3942 * Returns an array of html code of the following buttons:
3943 * save, diff, preview and live
3945 * @param int $tabindex Current tabindex
3949 public function getEditButtons( &$tabindex ) {
3955 'tabindex' => ++
$tabindex,
3956 ) + Linker
::tooltipAndAccesskeyAttribs( 'save' );
3957 $buttons['save'] = Html
::submitButton( wfMessage( 'savearticle' )->text(),
3958 $attribs, array( 'mw-ui-constructive' ) );
3960 ++
$tabindex; // use the same for preview and live preview
3962 'id' => 'wpPreview',
3963 'name' => 'wpPreview',
3964 'tabindex' => $tabindex,
3965 ) + Linker
::tooltipAndAccesskeyAttribs( 'preview' );
3966 $buttons['preview'] = Html
::submitButton( wfMessage( 'showpreview' )->text(),
3968 $buttons['live'] = '';
3973 'tabindex' => ++
$tabindex,
3974 ) + Linker
::tooltipAndAccesskeyAttribs( 'diff' );
3975 $buttons['diff'] = Html
::submitButton( wfMessage( 'showdiff' )->text(),
3978 Hooks
::run( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3983 * Creates a basic error page which informs the user that
3984 * they have attempted to edit a nonexistent section.
3986 function noSuchSectionPage() {
3989 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3991 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3992 Hooks
::run( 'EditPageNoSuchSection', array( &$this, &$res ) );
3993 $wgOut->addHTML( $res );
3995 $wgOut->returnToMain( false, $this->mTitle
);
3999 * Show "your edit contains spam" page with your diff and text
4001 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4003 public function spamPageWithContent( $match = false ) {
4004 global $wgOut, $wgLang;
4005 $this->textbox2
= $this->textbox1
;
4007 if ( is_array( $match ) ) {
4008 $match = $wgLang->listToText( $match );
4010 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
4012 $wgOut->addHTML( '<div id="spamprotected">' );
4013 $wgOut->addWikiMsg( 'spamprotectiontext' );
4015 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4017 $wgOut->addHTML( '</div>' );
4019 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4022 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4023 $this->showTextbox2();
4025 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
4029 * Check if the browser is on a blacklist of user-agents known to
4030 * mangle UTF-8 data on form submission. Returns true if Unicode
4031 * should make it through, false if it's known to be a problem.
4034 private function checkUnicodeCompliantBrowser() {
4035 global $wgBrowserBlackList, $wgRequest;
4037 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
4038 if ( $currentbrowser === false ) {
4039 // No User-Agent header sent? Trust it by default...
4043 foreach ( $wgBrowserBlackList as $browser ) {
4044 if ( preg_match( $browser, $currentbrowser ) ) {
4052 * Filter an input field through a Unicode de-armoring process if it
4053 * came from an old browser with known broken Unicode editing issues.
4055 * @param WebRequest $request
4056 * @param string $field
4059 protected function safeUnicodeInput( $request, $field ) {
4060 $text = rtrim( $request->getText( $field ) );
4061 return $request->getBool( 'safemode' )
4062 ?
$this->unmakeSafe( $text )
4067 * Filter an output field through a Unicode armoring process if it is
4068 * going to an old browser with known broken Unicode editing issues.
4070 * @param string $text
4073 protected function safeUnicodeOutput( $text ) {
4075 $codedText = $wgContLang->recodeForEdit( $text );
4076 return $this->checkUnicodeCompliantBrowser()
4078 : $this->makeSafe( $codedText );
4082 * A number of web browsers are known to corrupt non-ASCII characters
4083 * in a UTF-8 text editing environment. To protect against this,
4084 * detected browsers will be served an armored version of the text,
4085 * with non-ASCII chars converted to numeric HTML character references.
4087 * Preexisting such character references will have a 0 added to them
4088 * to ensure that round-trips do not alter the original data.
4090 * @param string $invalue
4093 private function makeSafe( $invalue ) {
4094 // Armor existing references for reversibility.
4095 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
4100 $valueLength = strlen( $invalue );
4101 for ( $i = 0; $i < $valueLength; $i++
) {
4102 $bytevalue = ord( $invalue[$i] );
4103 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4104 $result .= chr( $bytevalue );
4106 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4107 $working = $working << 6;
4108 $working +
= ( $bytevalue & 0x3F );
4110 if ( $bytesleft <= 0 ) {
4111 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4113 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4114 $working = $bytevalue & 0x1F;
4116 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4117 $working = $bytevalue & 0x0F;
4119 } else { // 1111 0xxx
4120 $working = $bytevalue & 0x07;
4128 * Reverse the previously applied transliteration of non-ASCII characters
4129 * back to UTF-8. Used to protect data from corruption by broken web browsers
4130 * as listed in $wgBrowserBlackList.
4132 * @param string $invalue
4135 private function unmakeSafe( $invalue ) {
4137 $valueLength = strlen( $invalue );
4138 for ( $i = 0; $i < $valueLength; $i++
) {
4139 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4143 $hexstring .= $invalue[$i];
4145 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4147 // Do some sanity checks. These aren't needed for reversibility,
4148 // but should help keep the breakage down if the editor
4149 // breaks one of the entities whilst editing.
4150 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4151 $codepoint = hexdec( $hexstring );
4152 $result .= UtfNormal\Utils
::codepointToUtf8( $codepoint );
4154 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4157 $result .= substr( $invalue, $i, 1 );
4160 // reverse the transform that we made for reversibility reasons.
4161 return strtr( $result, array( "�" => "&#x" ) );