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;
208 /** @var null|Title */
209 private $mContextTitle = null;
212 public $action = 'submit';
215 public $isConflict = false;
218 public $isCssJsSubpage = false;
221 public $isCssSubpage = false;
224 public $isJsSubpage = false;
227 public $isWrongCaseCssJsPage = false;
229 /** @var bool New page or new section */
230 public $isNew = false;
233 public $deletedSinceEdit;
241 /** @var bool|stdClass */
245 public $mTokenOk = false;
248 public $mTokenOkExceptSuffix = false;
251 public $mTriedSave = false;
254 public $incompleteForm = false;
257 public $tooBig = false;
260 public $kblength = false;
263 public $missingComment = false;
266 public $missingSummary = false;
269 public $allowBlankSummary = false;
272 protected $blankArticle = false;
275 protected $allowBlankArticle = false;
278 protected $selfRedirect = false;
281 protected $allowSelfRedirect = false;
284 public $autoSumm = '';
287 public $hookError = '';
289 /** @var ParserOutput */
290 public $mParserOutput;
292 /** @var bool Has a summary been preset using GET parameter &summary= ? */
293 public $hasPresetSummary = false;
296 public $mBaseRevision = false;
299 public $mShowSummaryField = true;
304 public $save = false;
307 public $preview = false;
310 public $diff = false;
313 public $minoredit = false;
316 public $watchthis = false;
319 public $recreate = false;
322 public $textbox1 = '';
325 public $textbox2 = '';
328 public $summary = '';
331 public $nosummary = false;
334 public $edittime = '';
337 public $section = '';
340 public $sectiontitle = '';
343 public $starttime = '';
349 public $parentRevId = 0;
352 public $editintro = '';
355 public $scrolltop = null;
360 /** @var null|string */
361 public $contentModel = null;
363 /** @var null|string */
364 public $contentFormat = null;
366 /** @var null|array */
367 public $changeTags = null;
369 # Placeholders for text injection by hooks (must be HTML)
370 # extensions should take care to _append_ to the present value
372 /** @var string Before even the preview */
373 public $editFormPageTop = '';
374 public $editFormTextTop = '';
375 public $editFormTextBeforeContent = '';
376 public $editFormTextAfterWarn = '';
377 public $editFormTextAfterTools = '';
378 public $editFormTextBottom = '';
379 public $editFormTextAfterContent = '';
380 public $previewTextAfterContent = '';
381 public $mPreloadContent = null;
383 /* $didSave should be set to true whenever an article was successfully altered. */
384 public $didSave = false;
385 public $undidRev = 0;
387 public $suppressIntro = false;
393 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
395 private $enableApiEditOverride = false;
398 * @param Article $article
400 public function __construct( Article
$article ) {
401 $this->mArticle
= $article;
402 $this->mTitle
= $article->getTitle();
404 $this->contentModel
= $this->mTitle
->getContentModel();
406 $handler = ContentHandler
::getForModelID( $this->contentModel
);
407 $this->contentFormat
= $handler->getDefaultFormat();
413 public function getArticle() {
414 return $this->mArticle
;
421 public function getTitle() {
422 return $this->mTitle
;
426 * Set the context Title object
428 * @param Title|null $title Title object or null
430 public function setContextTitle( $title ) {
431 $this->mContextTitle
= $title;
435 * Get the context title object.
436 * If not set, $wgTitle will be returned. This behavior might change in
437 * the future to return $this->mTitle instead.
441 public function getContextTitle() {
442 if ( is_null( $this->mContextTitle
) ) {
446 return $this->mContextTitle
;
451 * Returns if the given content model is editable.
453 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
455 * @throws MWException If $modelId has no known handler
457 public function isSupportedContentModel( $modelId ) {
458 return $this->enableApiEditOverride
=== true ||
459 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
463 * Allow editing of content that supports API direct editing, but not general
464 * direct editing. Set to false by default.
466 * @param bool $enableOverride
468 public function setApiEditOverride( $enableOverride ) {
469 $this->enableApiEditOverride
= $enableOverride;
477 * This is the function that gets called for "action=edit". It
478 * sets up various member variables, then passes execution to
479 * another function, usually showEditForm()
481 * The edit form is self-submitting, so that when things like
482 * preview and edit conflicts occur, we get the same form back
483 * with the extra stuff added. Only when the final submission
484 * is made and all is well do we actually save and redirect to
485 * the newly-edited page.
488 global $wgOut, $wgRequest, $wgUser;
489 // Allow extensions to modify/prevent this form or submission
490 if ( !Hooks
::run( 'AlternateEdit', array( $this ) ) ) {
494 wfDebug( __METHOD__
. ": enter\n" );
496 // If they used redlink=1 and the page exists, redirect to the main article
497 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
498 $wgOut->redirect( $this->mTitle
->getFullURL() );
502 $this->importFormData( $wgRequest );
503 $this->firsttime
= false;
505 if ( wfReadOnly() && $this->save
) {
508 $this->preview
= true;
512 $this->formtype
= 'save';
513 } elseif ( $this->preview
) {
514 $this->formtype
= 'preview';
515 } elseif ( $this->diff
) {
516 $this->formtype
= 'diff';
517 } else { # First time through
518 $this->firsttime
= true;
519 if ( $this->previewOnOpen() ) {
520 $this->formtype
= 'preview';
522 $this->formtype
= 'initial';
526 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
528 wfDebug( __METHOD__
. ": User can't edit\n" );
529 // Auto-block user's IP if the account was "hard" blocked
531 DeferredUpdates
::addCallableUpdate( function() use ( $user ) {
532 $user->spreadAnyEditBlock();
535 $this->displayPermissionsError( $permErrors );
540 $revision = $this->mArticle
->getRevisionFetched();
541 // Disallow editing revisions with content models different from the current one
542 if ( $revision && $revision->getContentModel() !== $this->contentModel
) {
543 $this->displayViewSourcePage(
544 $this->getContentObject(),
546 'contentmodelediterror',
547 $revision->getContentModel(),
554 $this->isConflict
= false;
555 // css / js subpages of user pages get a special treatment
556 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
557 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
558 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
559 // @todo FIXME: Silly assignment.
560 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
562 # Show applicable editing introductions
563 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
567 # Attempt submission here. This will check for edit conflicts,
568 # and redundantly check for locked database, blocked IPs, etc.
569 # that edit() already checked just in case someone tries to sneak
570 # in the back door with a hand-edited submission URL.
572 if ( 'save' == $this->formtype
) {
573 $resultDetails = null;
574 $status = $this->attemptSave( $resultDetails );
575 if ( !$this->handleStatus( $status, $resultDetails ) ) {
580 # First time through: get contents, set time for conflict
582 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
583 if ( $this->initialiseForm() === false ) {
584 $this->noSuchSectionPage();
588 if ( !$this->mTitle
->getArticleID() ) {
589 Hooks
::run( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
591 Hooks
::run( 'EditFormInitialText', array( $this ) );
596 $this->showEditForm();
600 * @param string $rigor Same format as Title::getUserPermissionErrors()
603 protected function getEditPermissionErrors( $rigor = 'secure' ) {
606 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
607 # Can this title be created?
608 if ( !$this->mTitle
->exists() ) {
609 $permErrors = array_merge(
612 $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
617 # Ignore some permissions errors when a user is just previewing/viewing diffs
619 foreach ( $permErrors as $error ) {
620 if ( ( $this->preview ||
$this->diff
)
621 && ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' )
626 $permErrors = wfArrayDiff2( $permErrors, $remove );
632 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
633 * but with the following differences:
634 * - If redlink=1, the user will be redirected to the page
635 * - If there is content to display or the error occurs while either saving,
636 * previewing or showing the difference, it will be a
637 * "View source for ..." page displaying the source code after the error message.
640 * @param array $permErrors Array of permissions errors, as returned by
641 * Title::getUserPermissionsErrors().
642 * @throws PermissionsError
644 protected function displayPermissionsError( array $permErrors ) {
645 global $wgRequest, $wgOut;
647 if ( $wgRequest->getBool( 'redlink' ) ) {
648 // The edit page was reached via a red link.
649 // Redirect to the article page and let them click the edit tab if
650 // they really want a permission error.
651 $wgOut->redirect( $this->mTitle
->getFullURL() );
655 $content = $this->getContentObject();
657 # Use the normal message if there's nothing to display
658 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
659 $action = $this->mTitle
->exists() ?
'edit' :
660 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
661 throw new PermissionsError( $action, $permErrors );
664 $this->displayViewSourcePage(
666 $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' )
671 * Display a read-only View Source page
672 * @param Content $content content object
673 * @param string $errorMessage additional wikitext error message to display
675 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
678 Hooks
::run( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
680 $wgOut->setRobotPolicy( 'noindex,nofollow' );
681 $wgOut->setPageTitle( wfMessage(
683 $this->getContextTitle()->getPrefixedText()
685 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
686 $wgOut->addHTML( $this->editFormPageTop
);
687 $wgOut->addHTML( $this->editFormTextTop
);
689 if ( $errorMessage !== '' ) {
690 $wgOut->addWikiText( $errorMessage );
691 $wgOut->addHTML( "<hr />\n" );
694 # If the user made changes, preserve them when showing the markup
695 # (This happens when a user is blocked during edit, for instance)
696 if ( !$this->firsttime
) {
697 $text = $this->textbox1
;
698 $wgOut->addWikiMsg( 'viewyourtext' );
701 $text = $this->toEditText( $content );
702 } catch ( MWException
$e ) {
703 # Serialize using the default format if the content model is not supported
704 # (e.g. for an old revision with a different model)
705 $text = $content->serialize();
707 $wgOut->addWikiMsg( 'viewsourcetext' );
710 $wgOut->addHTML( $this->editFormTextBeforeContent
);
711 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
712 $wgOut->addHTML( $this->editFormTextAfterContent
);
714 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
715 Linker
::formatTemplates( $this->getTemplates() ) ) );
717 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
719 $wgOut->addHTML( $this->editFormTextBottom
);
720 if ( $this->mTitle
->exists() ) {
721 $wgOut->returnToMain( null, $this->mTitle
);
726 * Should we show a preview when the edit form is first shown?
730 protected function previewOnOpen() {
731 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
732 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
733 // Explicit override from request
735 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
736 // Explicit override from request
738 } elseif ( $this->section
== 'new' ) {
739 // Nothing *to* preview for new sections
741 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
742 && $wgUser->getOption( 'previewonfirst' )
744 // Standard preference behavior
746 } elseif ( !$this->mTitle
->exists()
747 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
748 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
750 // Categories are special
758 * Checks whether the user entered a skin name in uppercase,
759 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
763 protected function isWrongCaseCssJsPage() {
764 if ( $this->mTitle
->isCssJsSubpage() ) {
765 $name = $this->mTitle
->getSkinFromCssJsSubpage();
766 $skins = array_merge(
767 array_keys( Skin
::getSkinNames() ),
770 return !in_array( $name, $skins )
771 && in_array( strtolower( $name ), $skins );
778 * Returns whether section editing is supported for the current page.
779 * Subclasses may override this to replace the default behavior, which is
780 * to check ContentHandler::supportsSections.
782 * @return bool True if this edit page supports sections, false otherwise.
784 protected function isSectionEditSupported() {
785 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
786 return $contentHandler->supportsSections();
790 * This function collects the form data and uses it to populate various member variables.
791 * @param WebRequest $request
792 * @throws ErrorPageError
794 function importFormData( &$request ) {
795 global $wgContLang, $wgUser;
797 # Section edit can come from either the form or a link
798 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
800 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
801 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
804 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
806 if ( $request->wasPosted() ) {
807 # These fields need to be checked for encoding.
808 # Also remove trailing whitespace, but don't remove _initial_
809 # whitespace from the text boxes. This may be significant formatting.
810 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
811 if ( !$request->getCheck( 'wpTextbox2' ) ) {
812 // Skip this if wpTextbox2 has input, it indicates that we came
813 // from a conflict page with raw page text, not a custom form
814 // modified by subclasses
815 $textbox1 = $this->importContentFormData( $request );
816 if ( $textbox1 !== null ) {
817 $this->textbox1
= $textbox1;
821 # Truncate for whole multibyte characters
822 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
824 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
825 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
827 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
829 # Treat sectiontitle the same way as summary.
830 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
831 # currently doing double duty as both edit summary and section title. Right now this
832 # is just to allow API edits to work around this limitation, but this should be
833 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
834 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
835 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
837 $this->edittime
= $request->getVal( 'wpEdittime' );
838 $this->starttime
= $request->getVal( 'wpStarttime' );
840 $undidRev = $request->getInt( 'wpUndidRevision' );
842 $this->undidRev
= $undidRev;
845 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
847 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
848 // wpTextbox1 field is missing, possibly due to being "too big"
849 // according to some filter rules such as Suhosin's setting for
850 // suhosin.request.max_value_length (d'oh)
851 $this->incompleteForm
= true;
853 // If we receive the last parameter of the request, we can fairly
854 // claim the POST request has not been truncated.
856 // TODO: softened the check for cutover. Once we determine
857 // that it is safe, we should complete the transition by
858 // removing the "edittime" clause.
859 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
860 && is_null( $this->edittime
) );
862 if ( $this->incompleteForm
) {
863 # If the form is incomplete, force to preview.
864 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
865 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
866 $this->preview
= true;
868 $this->preview
= $request->getCheck( 'wpPreview' );
869 $this->diff
= $request->getCheck( 'wpDiff' );
871 // Remember whether a save was requested, so we can indicate
872 // if we forced preview due to session failure.
873 $this->mTriedSave
= !$this->preview
;
875 if ( $this->tokenOk( $request ) ) {
876 # Some browsers will not report any submit button
877 # if the user hits enter in the comment box.
878 # The unmarked state will be assumed to be a save,
879 # if the form seems otherwise complete.
880 wfDebug( __METHOD__
. ": Passed token check.\n" );
881 } elseif ( $this->diff
) {
882 # Failed token check, but only requested "Show Changes".
883 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
885 # Page might be a hack attempt posted from
886 # an external site. Preview instead of saving.
887 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
888 $this->preview
= true;
891 $this->save
= !$this->preview
&& !$this->diff
;
892 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
893 $this->edittime
= null;
896 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
897 $this->starttime
= null;
900 $this->recreate
= $request->getCheck( 'wpRecreate' );
902 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
903 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
905 # Don't force edit summaries when a user is editing their own user or talk page
906 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
907 && $this->mTitle
->getText() == $wgUser->getName()
909 $this->allowBlankSummary
= true;
911 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
912 ||
!$wgUser->getOption( 'forceeditsummary' );
915 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
917 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
918 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
920 $changeTags = $request->getVal( 'wpChangeTags' );
921 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
922 $this->changeTags
= array();
924 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
928 # Not a posted form? Start with nothing.
929 wfDebug( __METHOD__
. ": Not a posted form.\n" );
930 $this->textbox1
= '';
932 $this->sectiontitle
= '';
933 $this->edittime
= '';
934 $this->starttime
= wfTimestampNow();
936 $this->preview
= false;
939 $this->minoredit
= false;
940 // Watch may be overridden by request parameters
941 $this->watchthis
= $request->getBool( 'watchthis', false );
942 $this->recreate
= false;
944 // When creating a new section, we can preload a section title by passing it as the
945 // preloadtitle parameter in the URL (Bug 13100)
946 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
947 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
948 // Once wpSummary isn't being use for setting section titles, we should delete this.
949 $this->summary
= $request->getVal( 'preloadtitle' );
950 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
951 $this->summary
= $request->getText( 'summary' );
952 if ( $this->summary
!== '' ) {
953 $this->hasPresetSummary
= true;
957 if ( $request->getVal( 'minor' ) ) {
958 $this->minoredit
= true;
962 $this->oldid
= $request->getInt( 'oldid' );
963 $this->parentRevId
= $request->getInt( 'parentRevId' );
965 $this->bot
= $request->getBool( 'bot', true );
966 $this->nosummary
= $request->getBool( 'nosummary' );
968 // May be overridden by revision.
969 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
970 // May be overridden by revision.
971 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
973 if ( !ContentHandler
::getForModelID( $this->contentModel
)
974 ->isSupportedFormat( $this->contentFormat
)
976 throw new ErrorPageError(
977 'editpage-notsupportedcontentformat-title',
978 'editpage-notsupportedcontentformat-text',
979 array( $this->contentFormat
, ContentHandler
::getLocalizedName( $this->contentModel
) )
984 * @todo Check if the desired model is allowed in this namespace, and if
985 * a transition from the page's current model to the new model is
989 $this->editintro
= $request->getText( 'editintro',
990 // Custom edit intro for new sections
991 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
993 // Allow extensions to modify form data
994 Hooks
::run( 'EditPage::importFormData', array( $this, $request ) );
999 * Subpage overridable method for extracting the page content data from the
1000 * posted form to be placed in $this->textbox1, if using customized input
1001 * this method should be overridden and return the page text that will be used
1002 * for saving, preview parsing and so on...
1004 * @param WebRequest $request
1006 protected function importContentFormData( &$request ) {
1007 return; // Don't do anything, EditPage already extracted wpTextbox1
1011 * Initialise form fields in the object
1012 * Called on the first invocation, e.g. when a user clicks an edit link
1013 * @return bool If the requested section is valid
1015 function initialiseForm() {
1017 $this->edittime
= $this->mArticle
->getTimestamp();
1019 $content = $this->getContentObject( false ); # TODO: track content object?!
1020 if ( $content === false ) {
1023 $this->textbox1
= $this->toEditText( $content );
1025 // activate checkboxes if user wants them to be always active
1026 # Sort out the "watch" checkbox
1027 if ( $wgUser->getOption( 'watchdefault' ) ) {
1029 $this->watchthis
= true;
1030 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1032 $this->watchthis
= true;
1033 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
1035 $this->watchthis
= true;
1037 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
1038 $this->minoredit
= true;
1040 if ( $this->textbox1
=== false ) {
1047 * @param Content|null $def_content The default value to return
1049 * @return Content|null Content on success, $def_content for invalid sections
1053 protected function getContentObject( $def_content = null ) {
1054 global $wgOut, $wgRequest, $wgUser, $wgContLang;
1058 // For message page not locally set, use the i18n message.
1059 // For other non-existent articles, use preload text if any.
1060 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1061 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1062 # If this is a system message, get the default text.
1063 $msg = $this->mTitle
->getDefaultMessageText();
1065 $content = $this->toEditContent( $msg );
1067 if ( $content === false ) {
1068 # If requested, preload some text.
1069 $preload = $wgRequest->getVal( 'preload',
1070 // Custom preload text for new sections
1071 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1072 $params = $wgRequest->getArray( 'preloadparams', array() );
1074 $content = $this->getPreloadedContent( $preload, $params );
1076 // For existing pages, get text based on "undo" or section parameters.
1078 if ( $this->section
!= '' ) {
1079 // Get section edit text (returns $def_text for invalid sections)
1080 $orig = $this->getOriginalContent( $wgUser );
1081 $content = $orig ?
$orig->getSection( $this->section
) : null;
1084 $content = $def_content;
1087 $undoafter = $wgRequest->getInt( 'undoafter' );
1088 $undo = $wgRequest->getInt( 'undo' );
1090 if ( $undo > 0 && $undoafter > 0 ) {
1091 $undorev = Revision
::newFromId( $undo );
1092 $oldrev = Revision
::newFromId( $undoafter );
1094 # Sanity check, make sure it's the right page,
1095 # the revisions exist and they were not deleted.
1096 # Otherwise, $content will be left as-is.
1097 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1098 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1099 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1101 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
1103 if ( $content === false ) {
1104 # Warn the user that something went wrong
1105 $undoMsg = 'failure';
1107 $oldContent = $this->mArticle
->getPage()->getContent( Revision
::RAW
);
1108 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
1109 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
1111 if ( $newContent->equals( $oldContent ) ) {
1112 # Tell the user that the undo results in no change,
1113 # i.e. the revisions were already undone.
1114 $undoMsg = 'nochange';
1117 # Inform the user of our success and set an automatic edit summary
1118 $undoMsg = 'success';
1120 # If we just undid one rev, use an autosummary
1121 $firstrev = $oldrev->getNext();
1122 if ( $firstrev && $firstrev->getId() == $undo ) {
1123 $userText = $undorev->getUserText();
1124 if ( $userText === '' ) {
1125 $undoSummary = wfMessage(
1126 'undo-summary-username-hidden',
1128 )->inContentLanguage()->text();
1130 $undoSummary = wfMessage(
1134 )->inContentLanguage()->text();
1136 if ( $this->summary
=== '' ) {
1137 $this->summary
= $undoSummary;
1139 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
1140 ->inContentLanguage()->text() . $this->summary
;
1142 $this->undidRev
= $undo;
1144 $this->formtype
= 'diff';
1148 // Failed basic sanity checks.
1149 // Older revisions may have been removed since the link
1150 // was created, or we may simply have got bogus input.
1154 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1155 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1156 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
1157 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1160 if ( $content === false ) {
1161 $content = $this->getOriginalContent( $wgUser );
1170 * Get the content of the wanted revision, without section extraction.
1172 * The result of this function can be used to compare user's input with
1173 * section replaced in its context (using WikiPage::replaceSection())
1174 * to the original text of the edit.
1176 * This differs from Article::getContent() that when a missing revision is
1177 * encountered the result will be null and not the
1178 * 'missing-revision' message.
1181 * @param User $user The user to get the revision for
1182 * @return Content|null
1184 private function getOriginalContent( User
$user ) {
1185 if ( $this->section
== 'new' ) {
1186 return $this->getCurrentContent();
1188 $revision = $this->mArticle
->getRevisionFetched();
1189 if ( $revision === null ) {
1190 if ( !$this->contentModel
) {
1191 $this->contentModel
= $this->getTitle()->getContentModel();
1193 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1195 return $handler->makeEmptyContent();
1197 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1202 * Get the current content of the page. This is basically similar to
1203 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1204 * content object is returned instead of null.
1209 protected function getCurrentContent() {
1210 $rev = $this->mArticle
->getRevision();
1211 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1213 if ( $content === false ||
$content === null ) {
1214 if ( !$this->contentModel
) {
1215 $this->contentModel
= $this->getTitle()->getContentModel();
1217 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1219 return $handler->makeEmptyContent();
1221 # nasty side-effect, but needed for consistency
1222 $this->contentModel
= $rev->getContentModel();
1223 $this->contentFormat
= $rev->getContentFormat();
1230 * Use this method before edit() to preload some content into the edit box
1232 * @param Content $content
1236 public function setPreloadedContent( Content
$content ) {
1237 $this->mPreloadContent
= $content;
1241 * Get the contents to be preloaded into the box, either set by
1242 * an earlier setPreloadText() or by loading the given page.
1244 * @param string $preload Representing the title to preload from.
1245 * @param array $params Parameters to use (interface-message style) in the preloaded text
1251 protected function getPreloadedContent( $preload, $params = array() ) {
1254 if ( !empty( $this->mPreloadContent
) ) {
1255 return $this->mPreloadContent
;
1258 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1260 if ( $preload === '' ) {
1261 return $handler->makeEmptyContent();
1264 $title = Title
::newFromText( $preload );
1265 # Check for existence to avoid getting MediaWiki:Noarticletext
1266 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1267 // TODO: somehow show a warning to the user!
1268 return $handler->makeEmptyContent();
1271 $page = WikiPage
::factory( $title );
1272 if ( $page->isRedirect() ) {
1273 $title = $page->getRedirectTarget();
1275 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1276 // TODO: somehow show a warning to the user!
1277 return $handler->makeEmptyContent();
1279 $page = WikiPage
::factory( $title );
1282 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1283 $content = $page->getContent( Revision
::RAW
);
1286 // TODO: somehow show a warning to the user!
1287 return $handler->makeEmptyContent();
1290 if ( $content->getModel() !== $handler->getModelID() ) {
1291 $converted = $content->convert( $handler->getModelID() );
1293 if ( !$converted ) {
1294 // TODO: somehow show a warning to the user!
1295 wfDebug( "Attempt to preload incompatible content: " .
1296 "can't convert " . $content->getModel() .
1297 " to " . $handler->getModelID() );
1299 return $handler->makeEmptyContent();
1302 $content = $converted;
1305 return $content->preloadTransform( $title, $parserOptions, $params );
1309 * Make sure the form isn't faking a user's credentials.
1311 * @param WebRequest $request
1315 function tokenOk( &$request ) {
1317 $token = $request->getVal( 'wpEditToken' );
1318 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1319 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1320 return $this->mTokenOk
;
1324 * Sets post-edit cookie indicating the user just saved a particular revision.
1326 * This uses a temporary cookie for each revision ID so separate saves will never
1327 * interfere with each other.
1329 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1330 * the redirect. It must be clearable by JavaScript code, so it must not be
1331 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1334 * If the variable were set on the server, it would be cached, which is unwanted
1335 * since the post-edit state should only apply to the load right after the save.
1337 * @param int $statusValue The status value (to check for new article status)
1339 protected function setPostEditCookie( $statusValue ) {
1340 $revisionId = $this->mArticle
->getLatest();
1341 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1344 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1346 } elseif ( $this->oldid
) {
1350 $response = RequestContext
::getMain()->getRequest()->response();
1351 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
, array(
1352 'httpOnly' => false,
1357 * Attempt submission
1358 * @param array $resultDetails See docs for $result in internalAttemptSave
1359 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1360 * @return Status The resulting status object.
1362 public function attemptSave( &$resultDetails = false ) {
1365 # Allow bots to exempt some edits from bot flagging
1366 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1367 $status = $this->internalAttemptSave( $resultDetails, $bot );
1369 Hooks
::run( 'EditPage::attemptSave:after', array( $this, $status, $resultDetails ) );
1375 * Handle status, such as after attempt save
1377 * @param Status $status
1378 * @param array|bool $resultDetails
1380 * @throws ErrorPageError
1381 * @return bool False, if output is done, true if rest of the form should be displayed
1383 private function handleStatus( Status
$status, $resultDetails ) {
1384 global $wgUser, $wgOut;
1387 * @todo FIXME: once the interface for internalAttemptSave() is made
1388 * nicer, this should use the message in $status
1390 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1391 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1393 $this->didSave
= true;
1394 if ( !$resultDetails['nullEdit'] ) {
1395 $this->setPostEditCookie( $status->value
);
1399 switch ( $status->value
) {
1400 case self
::AS_HOOK_ERROR_EXPECTED
:
1401 case self
::AS_CONTENT_TOO_BIG
:
1402 case self
::AS_ARTICLE_WAS_DELETED
:
1403 case self
::AS_CONFLICT_DETECTED
:
1404 case self
::AS_SUMMARY_NEEDED
:
1405 case self
::AS_TEXTBOX_EMPTY
:
1406 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1408 case self
::AS_BLANK_ARTICLE
:
1409 case self
::AS_SELF_REDIRECT
:
1412 case self
::AS_HOOK_ERROR
:
1415 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1416 case self
::AS_PARSE_ERROR
:
1417 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1420 case self
::AS_SUCCESS_NEW_ARTICLE
:
1421 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1422 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1423 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1426 case self
::AS_SUCCESS_UPDATE
:
1428 $sectionanchor = $resultDetails['sectionanchor'];
1430 // Give extensions a chance to modify URL query on update
1432 'ArticleUpdateBeforeRedirect',
1433 array( $this->mArticle
, &$sectionanchor, &$extraQuery )
1436 if ( $resultDetails['redirect'] ) {
1437 if ( $extraQuery == '' ) {
1438 $extraQuery = 'redirect=no';
1440 $extraQuery = 'redirect=no&' . $extraQuery;
1443 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1446 case self
::AS_SPAM_ERROR
:
1447 $this->spamPageWithContent( $resultDetails['spam'] );
1450 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1451 throw new UserBlockedError( $wgUser->getBlock() );
1453 case self
::AS_IMAGE_REDIRECT_ANON
:
1454 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1455 throw new PermissionsError( 'upload' );
1457 case self
::AS_READ_ONLY_PAGE_ANON
:
1458 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1459 throw new PermissionsError( 'edit' );
1461 case self
::AS_READ_ONLY_PAGE
:
1462 throw new ReadOnlyError
;
1464 case self
::AS_RATE_LIMITED
:
1465 throw new ThrottledError();
1467 case self
::AS_NO_CREATE_PERMISSION
:
1468 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1469 throw new PermissionsError( $permission );
1471 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1472 throw new PermissionsError( 'editcontentmodel' );
1475 // We don't recognize $status->value. The only way that can happen
1476 // is if an extension hook aborted from inside ArticleSave.
1477 // Render the status object into $this->hookError
1478 // FIXME this sucks, we should just use the Status object throughout
1479 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1486 * Run hooks that can filter edits just before they get saved.
1488 * @param Content $content The Content to filter.
1489 * @param Status $status For reporting the outcome to the caller
1490 * @param User $user The user performing the edit
1494 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1495 // Run old style post-section-merge edit filter
1496 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1497 array( $this, $content, &$this->hookError
, $this->summary
) )
1499 # Error messages etc. could be handled within the hook...
1500 $status->fatal( 'hookaborted' );
1501 $status->value
= self
::AS_HOOK_ERROR
;
1503 } elseif ( $this->hookError
!= '' ) {
1504 # ...or the hook could be expecting us to produce an error
1505 $status->fatal( 'hookaborted' );
1506 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1510 // Run new style post-section-merge edit filter
1511 if ( !Hooks
::run( 'EditFilterMergedContent',
1512 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1513 $user, $this->minoredit
) )
1515 # Error messages etc. could be handled within the hook...
1516 if ( $status->isGood() ) {
1517 $status->fatal( 'hookaborted' );
1518 // Not setting $this->hookError here is a hack to allow the hook
1519 // to cause a return to the edit page without $this->hookError
1520 // being set. This is used by ConfirmEdit to display a captcha
1521 // without any error message cruft.
1523 $this->hookError
= $status->getWikiText();
1525 // Use the existing $status->value if the hook set it
1526 if ( !$status->value
) {
1527 $status->value
= self
::AS_HOOK_ERROR
;
1530 } elseif ( !$status->isOK() ) {
1531 # ...or the hook could be expecting us to produce an error
1532 // FIXME this sucks, we should just use the Status object throughout
1533 $this->hookError
= $status->getWikiText();
1534 $status->fatal( 'hookaborted' );
1535 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1543 * Return the summary to be used for a new section.
1545 * @param string $sectionanchor Set to the section anchor text
1548 private function newSectionSummary( &$sectionanchor = null ) {
1551 if ( $this->sectiontitle
!== '' ) {
1552 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1553 // If no edit summary was specified, create one automatically from the section
1554 // title and have it link to the new section. Otherwise, respect the summary as
1556 if ( $this->summary
=== '' ) {
1557 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1558 return wfMessage( 'newsectionsummary' )
1559 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1561 } elseif ( $this->summary
!== '' ) {
1562 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1563 # This is a new section, so create a link to the new section
1564 # in the revision summary.
1565 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1566 return wfMessage( 'newsectionsummary' )
1567 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1569 return $this->summary
;
1573 * Attempt submission (no UI)
1575 * @param array $result Array to add statuses to, currently with the
1577 * - spam (string): Spam string from content if any spam is detected by
1579 * - sectionanchor (string): Section anchor for a section save.
1580 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1582 * - redirect (bool): Set if doEditContent is OK. True if resulting
1583 * revision is a redirect.
1584 * @param bool $bot True if edit is being made under the bot right.
1586 * @return Status Status object, possibly with a message, but always with
1587 * one of the AS_* constants in $status->value,
1589 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1590 * various error display idiosyncrasies. There are also lots of cases
1591 * where error metadata is set in the object and retrieved later instead
1592 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1593 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1596 function internalAttemptSave( &$result, $bot = false ) {
1597 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1598 global $wgContentHandlerUseDB;
1600 $status = Status
::newGood();
1602 if ( !Hooks
::run( 'EditPage::attemptSave', array( $this ) ) ) {
1603 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1604 $status->fatal( 'hookaborted' );
1605 $status->value
= self
::AS_HOOK_ERROR
;
1609 $spam = $wgRequest->getText( 'wpAntispam' );
1610 if ( $spam !== '' ) {
1613 $wgUser->getName() .
1615 $this->mTitle
->getPrefixedText() .
1616 '" submitted bogus field "' .
1620 $status->fatal( 'spamprotectionmatch', false );
1621 $status->value
= self
::AS_SPAM_ERROR
;
1626 # Construct Content object
1627 $textbox_content = $this->toEditContent( $this->textbox1
);
1628 } catch ( MWContentSerializationException
$ex ) {
1630 'content-failed-to-parse',
1631 $this->contentModel
,
1632 $this->contentFormat
,
1635 $status->value
= self
::AS_PARSE_ERROR
;
1639 # Check image redirect
1640 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1641 $textbox_content->isRedirect() &&
1642 !$wgUser->isAllowed( 'upload' )
1644 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1645 $status->setResult( false, $code );
1651 $match = self
::matchSummarySpamRegex( $this->summary
);
1652 if ( $match === false && $this->section
== 'new' ) {
1653 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1654 # regular summaries, it is added to the actual wikitext.
1655 if ( $this->sectiontitle
!== '' ) {
1656 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1657 $match = self
::matchSpamRegex( $this->sectiontitle
);
1659 # This branch is taken when the "Add Topic" user interface is used, or the API
1660 # is used with the 'summary' parameter.
1661 $match = self
::matchSpamRegex( $this->summary
);
1664 if ( $match === false ) {
1665 $match = self
::matchSpamRegex( $this->textbox1
);
1667 if ( $match !== false ) {
1668 $result['spam'] = $match;
1669 $ip = $wgRequest->getIP();
1670 $pdbk = $this->mTitle
->getPrefixedDBkey();
1671 $match = str_replace( "\n", '', $match );
1672 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1673 $status->fatal( 'spamprotectionmatch', $match );
1674 $status->value
= self
::AS_SPAM_ERROR
;
1679 array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) )
1681 # Error messages etc. could be handled within the hook...
1682 $status->fatal( 'hookaborted' );
1683 $status->value
= self
::AS_HOOK_ERROR
;
1685 } elseif ( $this->hookError
!= '' ) {
1686 # ...or the hook could be expecting us to produce an error
1687 $status->fatal( 'hookaborted' );
1688 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1692 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1693 // Auto-block user's IP if the account was "hard" blocked
1694 $wgUser->spreadAnyEditBlock();
1695 # Check block state against master, thus 'false'.
1696 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1700 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1701 if ( $this->kblength
> $wgMaxArticleSize ) {
1702 // Error will be displayed by showEditForm()
1703 $this->tooBig
= true;
1704 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1708 if ( !$wgUser->isAllowed( 'edit' ) ) {
1709 if ( $wgUser->isAnon() ) {
1710 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1713 $status->fatal( 'readonlytext' );
1714 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1719 $changingContentModel = false;
1720 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1721 if ( !$wgContentHandlerUseDB ) {
1722 $status->fatal( 'editpage-cannot-use-custom-model' );
1723 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1725 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1726 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1730 $changingContentModel = true;
1731 $oldContentModel = $this->mTitle
->getContentModel();
1734 if ( $this->changeTags
) {
1735 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1736 $this->changeTags
, $wgUser );
1737 if ( !$changeTagsStatus->isOK() ) {
1738 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1739 return $changeTagsStatus;
1743 if ( wfReadOnly() ) {
1744 $status->fatal( 'readonlytext' );
1745 $status->value
= self
::AS_READ_ONLY_PAGE
;
1748 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1749 $status->fatal( 'actionthrottledtext' );
1750 $status->value
= self
::AS_RATE_LIMITED
;
1754 # If the article has been deleted while editing, don't save it without
1756 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1757 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1761 # Load the page data from the master. If anything changes in the meantime,
1762 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1763 $this->mArticle
->loadPageData( 'fromdbmaster' );
1764 $new = !$this->mArticle
->exists();
1767 // Late check for create permission, just in case *PARANOIA*
1768 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1769 $status->fatal( 'nocreatetext' );
1770 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1771 wfDebug( __METHOD__
. ": no create permission\n" );
1775 // Don't save a new page if it's blank or if it's a MediaWiki:
1776 // message with content equivalent to default (allow empty pages
1777 // in this case to disable messages, see bug 50124)
1778 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1779 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1780 $defaultText = $defaultMessageText;
1785 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1786 $this->blankArticle
= true;
1787 $status->fatal( 'blankarticle' );
1788 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1792 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1796 $content = $textbox_content;
1798 $result['sectionanchor'] = '';
1799 if ( $this->section
== 'new' ) {
1800 if ( $this->sectiontitle
!== '' ) {
1801 // Insert the section title above the content.
1802 $content = $content->addSectionHeader( $this->sectiontitle
);
1803 } elseif ( $this->summary
!== '' ) {
1804 // Insert the section title above the content.
1805 $content = $content->addSectionHeader( $this->summary
);
1807 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1810 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1814 # Article exists. Check for edit conflict.
1816 $this->mArticle
->clear(); # Force reload of dates, etc.
1817 $timestamp = $this->mArticle
->getTimestamp();
1819 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1821 if ( $timestamp != $this->edittime
) {
1822 $this->isConflict
= true;
1823 if ( $this->section
== 'new' ) {
1824 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1825 $this->mArticle
->getComment() == $this->newSectionSummary()
1827 // Probably a duplicate submission of a new comment.
1828 // This can happen when squid resends a request after
1829 // a timeout but the first one actually went through.
1831 . ": duplicate new section submission; trigger edit conflict!\n" );
1833 // New comment; suppress conflict.
1834 $this->isConflict
= false;
1835 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1837 } elseif ( $this->section
== ''
1838 && Revision
::userWasLastToEdit(
1839 DB_MASTER
, $this->mTitle
->getArticleID(),
1840 $wgUser->getId(), $this->edittime
1843 # Suppress edit conflict with self, except for section edits where merging is required.
1844 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1845 $this->isConflict
= false;
1849 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1850 if ( $this->sectiontitle
!== '' ) {
1851 $sectionTitle = $this->sectiontitle
;
1853 $sectionTitle = $this->summary
;
1858 if ( $this->isConflict
) {
1860 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1861 . " (article time '{$timestamp}')\n" );
1863 $content = $this->mArticle
->replaceSectionContent(
1870 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1871 $content = $this->mArticle
->replaceSectionContent(
1878 if ( is_null( $content ) ) {
1879 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1880 $this->isConflict
= true;
1881 $content = $textbox_content; // do not try to merge here!
1882 } elseif ( $this->isConflict
) {
1884 if ( $this->mergeChangesIntoContent( $content ) ) {
1885 // Successful merge! Maybe we should tell the user the good news?
1886 $this->isConflict
= false;
1887 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1889 $this->section
= '';
1890 $this->textbox1
= ContentHandler
::getContentText( $content );
1891 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1895 if ( $this->isConflict
) {
1896 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1900 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1904 if ( $this->section
== 'new' ) {
1905 // Handle the user preference to force summaries here
1906 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1907 $this->missingSummary
= true;
1908 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1909 $status->value
= self
::AS_SUMMARY_NEEDED
;
1913 // Do not allow the user to post an empty comment
1914 if ( $this->textbox1
== '' ) {
1915 $this->missingComment
= true;
1916 $status->fatal( 'missingcommenttext' );
1917 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1920 } elseif ( !$this->allowBlankSummary
1921 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1922 && !$content->isRedirect()
1923 && md5( $this->summary
) == $this->autoSumm
1925 $this->missingSummary
= true;
1926 $status->fatal( 'missingsummary' );
1927 $status->value
= self
::AS_SUMMARY_NEEDED
;
1932 $sectionanchor = '';
1933 if ( $this->section
== 'new' ) {
1934 $this->summary
= $this->newSectionSummary( $sectionanchor );
1935 } elseif ( $this->section
!= '' ) {
1936 # Try to get a section anchor from the section source, redirect
1937 # to edited section if header found.
1938 # XXX: Might be better to integrate this into Article::replaceSection
1939 # for duplicate heading checking and maybe parsing.
1940 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1941 # We can't deal with anchors, includes, html etc in the header for now,
1942 # headline would need to be parsed to improve this.
1943 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1944 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1947 $result['sectionanchor'] = $sectionanchor;
1949 // Save errors may fall down to the edit form, but we've now
1950 // merged the section into full text. Clear the section field
1951 // so that later submission of conflict forms won't try to
1952 // replace that into a duplicated mess.
1953 $this->textbox1
= $this->toEditText( $content );
1954 $this->section
= '';
1956 $status->value
= self
::AS_SUCCESS_UPDATE
;
1959 if ( !$this->allowSelfRedirect
1960 && $content->isRedirect()
1961 && $content->getRedirectTarget()->equals( $this->getTitle() )
1963 // If the page already redirects to itself, don't warn.
1964 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
1965 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
1966 $this->selfRedirect
= true;
1967 $status->fatal( 'selfredirect' );
1968 $status->value
= self
::AS_SELF_REDIRECT
;
1973 // Check for length errors again now that the section is merged in
1974 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1975 if ( $this->kblength
> $wgMaxArticleSize ) {
1976 $this->tooBig
= true;
1977 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1981 $flags = EDIT_AUTOSUMMARY |
1982 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1983 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1984 ( $bot ? EDIT_FORCE_BOT
: 0 );
1986 $doEditStatus = $this->mArticle
->doEditContent(
1992 $content->getDefaultFormat()
1995 if ( !$doEditStatus->isOK() ) {
1996 // Failure from doEdit()
1997 // Show the edit conflict page for certain recognized errors from doEdit(),
1998 // but don't show it for errors from extension hooks
1999 $errors = $doEditStatus->getErrorsArray();
2000 if ( in_array( $errors[0][0],
2001 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
2003 $this->isConflict
= true;
2004 // Destroys data doEdit() put in $status->value but who cares
2005 $doEditStatus->value
= self
::AS_END
;
2007 return $doEditStatus;
2010 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2011 if ( $result['nullEdit'] ) {
2012 // We don't know if it was a null edit until now, so increment here
2013 $wgUser->pingLimiter( 'linkpurge' );
2015 $result['redirect'] = $content->isRedirect();
2017 $this->updateWatchlist();
2019 if ( $this->changeTags
&& isset( $doEditStatus->value
['revision'] ) ) {
2020 // If a revision was created, apply any change tags that were requested
2021 $addTags = $this->changeTags
;
2022 $revId = $doEditStatus->value
['revision']->getId();
2023 // Defer this both for performance and so that addTags() sees the rc_id
2024 // since the recentchange entry addition is deferred first (bug T100248)
2025 DeferredUpdates
::addCallableUpdate( function() use ( $addTags, $revId ) {
2026 ChangeTags
::addTags( $addTags, null, $revId );
2030 // If the content model changed, add a log entry
2031 if ( $changingContentModel ) {
2032 $this->addContentModelChangeLogEntry(
2035 $this->contentModel
,
2045 * @param string $oldModel
2046 * @param string $newModel
2047 * @param string $reason
2049 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2050 $log = new ManualLogEntry( 'contentmodel', 'change' );
2051 $log->setPerformer( $user );
2052 $log->setTarget( $this->mTitle
);
2053 $log->setComment( $reason );
2054 $log->setParameters( array(
2055 '4::oldmodel' => $oldModel,
2056 '5::newmodel' => $newModel
2058 $logid = $log->insert();
2059 $log->publish( $logid );
2063 * Register the change of watch status
2065 protected function updateWatchlist() {
2068 if ( !$wgUser->isLoggedIn() ) {
2073 $title = $this->mTitle
;
2074 $watch = $this->watchthis
;
2075 // Do this in its own transaction to reduce contention...
2076 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2077 if ( $watch == $user->isWatched( $title, WatchedItem
::IGNORE_USER_RIGHTS
) ) {
2078 return; // nothing to change
2080 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2085 * Attempts to do 3-way merge of edit content with a base revision
2086 * and current content, in case of edit conflict, in whichever way appropriate
2087 * for the content type.
2091 * @param Content $editContent
2095 private function mergeChangesIntoContent( &$editContent ) {
2097 $db = wfGetDB( DB_MASTER
);
2099 // This is the revision the editor started from
2100 $baseRevision = $this->getBaseRevision();
2101 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2103 if ( is_null( $baseContent ) ) {
2107 // The current state, we want to merge updates into it
2108 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2109 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2111 if ( is_null( $currentContent ) ) {
2115 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2117 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2120 $editContent = $result;
2130 function getBaseRevision() {
2131 if ( !$this->mBaseRevision
) {
2132 $db = wfGetDB( DB_MASTER
);
2133 $this->mBaseRevision
= Revision
::loadFromTimestamp(
2134 $db, $this->mTitle
, $this->edittime
);
2136 return $this->mBaseRevision
;
2140 * Check given input text against $wgSpamRegex, and return the text of the first match.
2142 * @param string $text
2144 * @return string|bool Matching string or false
2146 public static function matchSpamRegex( $text ) {
2147 global $wgSpamRegex;
2148 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2149 $regexes = (array)$wgSpamRegex;
2150 return self
::matchSpamRegexInternal( $text, $regexes );
2154 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2156 * @param string $text
2158 * @return string|bool Matching string or false
2160 public static function matchSummarySpamRegex( $text ) {
2161 global $wgSummarySpamRegex;
2162 $regexes = (array)$wgSummarySpamRegex;
2163 return self
::matchSpamRegexInternal( $text, $regexes );
2167 * @param string $text
2168 * @param array $regexes
2169 * @return bool|string
2171 protected static function matchSpamRegexInternal( $text, $regexes ) {
2172 foreach ( $regexes as $regex ) {
2174 if ( preg_match( $regex, $text, $matches ) ) {
2181 function setHeaders() {
2182 global $wgOut, $wgUser, $wgAjaxEditStash;
2184 $wgOut->addModules( 'mediawiki.action.edit' );
2185 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2187 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2188 // The addition of default buttons is handled by getEditToolbar() which
2189 // has its own dependency on this module. The call here ensures the module
2190 // is loaded in time (it has position "top") for other modules to register
2191 // buttons (e.g. extensions, gadgets, user scripts).
2192 $wgOut->addModules( 'mediawiki.toolbar' );
2195 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2196 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2199 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2200 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2203 if ( $wgAjaxEditStash ) {
2204 $wgOut->addModules( 'mediawiki.action.edit.stash' );
2207 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2209 # Enabled article-related sidebar, toplinks, etc.
2210 $wgOut->setArticleRelated( true );
2212 $contextTitle = $this->getContextTitle();
2213 if ( $this->isConflict
) {
2214 $msg = 'editconflict';
2215 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2216 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2218 $msg = $contextTitle->exists()
2219 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2220 && $contextTitle->getDefaultMessageText() !== false
2226 # Use the title defined by DISPLAYTITLE magic word when present
2227 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2228 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2229 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2230 if ( $displayTitle === false ) {
2231 $displayTitle = $contextTitle->getPrefixedText();
2233 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2234 # Transmit the name of the message to JavaScript for live preview
2235 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2236 $wgOut->addJsConfigVars( 'wgEditMessage', $msg );
2240 * Show all applicable editing introductions
2242 protected function showIntro() {
2243 global $wgOut, $wgUser;
2244 if ( $this->suppressIntro
) {
2248 $namespace = $this->mTitle
->getNamespace();
2250 if ( $namespace == NS_MEDIAWIKI
) {
2251 # Show a warning if editing an interface message
2252 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2253 # If this is a default message (but not css or js),
2254 # show a hint that it is translatable on translatewiki.net
2255 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2256 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2258 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2259 if ( $defaultMessageText !== false ) {
2260 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2261 'translateinterface' );
2264 } elseif ( $namespace == NS_FILE
) {
2265 # Show a hint to shared repo
2266 $file = wfFindFile( $this->mTitle
);
2267 if ( $file && !$file->isLocal() ) {
2268 $descUrl = $file->getDescriptionUrl();
2269 # there must be a description url to show a hint to shared repo
2271 if ( !$this->mTitle
->exists() ) {
2272 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2273 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2276 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2277 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2284 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2285 # Show log extract when the user is currently blocked
2286 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2287 $parts = explode( '/', $this->mTitle
->getText(), 2 );
2288 $username = $parts[0];
2289 $user = User
::newFromName( $username, false /* allow IP users*/ );
2290 $ip = User
::isIP( $username );
2291 $block = Block
::newFromTarget( $user, $user );
2292 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2293 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2294 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2295 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2296 # Show log extract if the user is currently blocked
2297 LogEventsList
::showLogExtract(
2300 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2304 'showIfEmpty' => false,
2306 'blocked-notice-logextract',
2307 $user->getName() # Support GENDER in notice
2313 # Try to add a custom edit intro, or use the standard one if this is not possible.
2314 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2315 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2316 wfMessage( 'helppage' )->inContentLanguage()->text()
2318 if ( $wgUser->isLoggedIn() ) {
2319 $wgOut->wrapWikiMsg(
2320 // Suppress the external link icon, consider the help url an internal one
2321 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2328 $wgOut->wrapWikiMsg(
2329 // Suppress the external link icon, consider the help url an internal one
2330 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2332 'newarticletextanon',
2338 # Give a notice if the user is editing a deleted/moved page...
2339 if ( !$this->mTitle
->exists() ) {
2340 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
2344 'conds' => array( "log_action != 'revision'" ),
2345 'showIfEmpty' => false,
2346 'msgKey' => array( 'recreate-moveddeleted-warn' )
2353 * Attempt to show a custom editing introduction, if supplied
2357 protected function showCustomIntro() {
2358 if ( $this->editintro
) {
2359 $title = Title
::newFromText( $this->editintro
);
2360 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2362 // Added using template syntax, to take <noinclude>'s into account.
2363 $wgOut->addWikiTextTitleTidy(
2364 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2374 * Gets an editable textual representation of $content.
2375 * The textual representation can be turned by into a Content object by the
2376 * toEditContent() method.
2378 * If $content is null or false or a string, $content is returned unchanged.
2380 * If the given Content object is not of a type that can be edited using
2381 * the text base EditPage, an exception will be raised. Set
2382 * $this->allowNonTextContent to true to allow editing of non-textual
2385 * @param Content|null|bool|string $content
2386 * @return string The editable text form of the content.
2388 * @throws MWException If $content is not an instance of TextContent and
2389 * $this->allowNonTextContent is not true.
2391 protected function toEditText( $content ) {
2392 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2396 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2397 throw new MWException( 'This content model is not supported: '
2398 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2401 return $content->serialize( $this->contentFormat
);
2405 * Turns the given text into a Content object by unserializing it.
2407 * If the resulting Content object is not of a type that can be edited using
2408 * the text base EditPage, an exception will be raised. Set
2409 * $this->allowNonTextContent to true to allow editing of non-textual
2412 * @param string|null|bool $text Text to unserialize
2413 * @return Content The content object created from $text. If $text was false
2414 * or null, false resp. null will be returned instead.
2416 * @throws MWException If unserializing the text results in a Content
2417 * object that is not an instance of TextContent and
2418 * $this->allowNonTextContent is not true.
2420 protected function toEditContent( $text ) {
2421 if ( $text === false ||
$text === null ) {
2425 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2426 $this->contentModel
, $this->contentFormat
);
2428 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2429 throw new MWException( 'This content model is not supported: '
2430 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2437 * Send the edit form and related headers to $wgOut
2438 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2439 * during form output near the top, for captchas and the like.
2441 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2442 * use the EditPage::showEditForm:fields hook instead.
2444 function showEditForm( $formCallback = null ) {
2445 global $wgOut, $wgUser;
2447 # need to parse the preview early so that we know which templates are used,
2448 # otherwise users with "show preview after edit box" will get a blank list
2449 # we parse this near the beginning so that setHeaders can do the title
2450 # setting work instead of leaving it in getPreviewText
2451 $previewOutput = '';
2452 if ( $this->formtype
== 'preview' ) {
2453 $previewOutput = $this->getPreviewText();
2456 Hooks
::run( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2458 $this->setHeaders();
2460 if ( $this->showHeader() === false ) {
2464 $wgOut->addHTML( $this->editFormPageTop
);
2466 if ( $wgUser->getOption( 'previewontop' ) ) {
2467 $this->displayPreviewArea( $previewOutput, true );
2470 $wgOut->addHTML( $this->editFormTextTop
);
2472 $showToolbar = true;
2473 if ( $this->wasDeletedSinceLastEdit() ) {
2474 if ( $this->formtype
== 'save' ) {
2475 // Hide the toolbar and edit area, user can click preview to get it back
2476 // Add an confirmation checkbox and explanation.
2477 $showToolbar = false;
2479 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2480 'deletedwhileediting' );
2484 // @todo add EditForm plugin interface and use it here!
2485 // search for textarea1 and textares2, and allow EditForm to override all uses.
2486 $wgOut->addHTML( Html
::openElement(
2489 'id' => self
::EDITFORM_ID
,
2490 'name' => self
::EDITFORM_ID
,
2492 'action' => $this->getActionURL( $this->getContextTitle() ),
2493 'enctype' => 'multipart/form-data'
2497 if ( is_callable( $formCallback ) ) {
2498 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2499 call_user_func_array( $formCallback, array( &$wgOut ) );
2502 // Add an empty field to trip up spambots
2504 Xml
::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2507 array( 'for' => 'wpAntiSpam' ),
2508 wfMessage( 'simpleantispam-label' )->parse()
2514 'name' => 'wpAntispam',
2515 'id' => 'wpAntispam',
2519 . Xml
::closeElement( 'div' )
2522 Hooks
::run( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2524 // Put these up at the top to ensure they aren't lost on early form submission
2525 $this->showFormBeforeText();
2527 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2528 $username = $this->lastDelete
->user_name
;
2529 $comment = $this->lastDelete
->log_comment
;
2531 // It is better to not parse the comment at all than to have templates expanded in the middle
2532 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2533 $key = $comment === ''
2534 ?
'confirmrecreate-noreason'
2535 : 'confirmrecreate';
2537 '<div class="mw-confirm-recreate">' .
2538 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2539 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2540 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2546 # When the summary is hidden, also hide them on preview/show changes
2547 if ( $this->nosummary
) {
2548 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2551 # If a blank edit summary was previously provided, and the appropriate
2552 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2553 # user being bounced back more than once in the event that a summary
2556 # For a bit more sophisticated detection of blank summaries, hash the
2557 # automatic one and pass that in the hidden field wpAutoSummary.
2558 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2559 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2562 if ( $this->undidRev
) {
2563 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2566 if ( $this->selfRedirect
) {
2567 $wgOut->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2570 if ( $this->hasPresetSummary
) {
2571 // If a summary has been preset using &summary= we don't want to prompt for
2572 // a different summary. Only prompt for a summary if the summary is blanked.
2574 $this->autoSumm
= md5( '' );
2577 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2578 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2580 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2581 $wgOut->addHTML( Html
::hidden( 'parentRevId',
2582 $this->parentRevId ?
: $this->mArticle
->getRevIdFetched() ) );
2584 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2585 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2587 if ( $this->section
== 'new' ) {
2588 $this->showSummaryInput( true, $this->summary
);
2589 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2592 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2594 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2595 $wgOut->addHTML( EditPage
::getEditToolbar( $this->mTitle
) );
2598 if ( $this->blankArticle
) {
2599 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2602 if ( $this->isConflict
) {
2603 // In an edit conflict bypass the overridable content form method
2604 // and fallback to the raw wpTextbox1 since editconflicts can't be
2605 // resolved between page source edits and custom ui edits using the
2607 $this->textbox2
= $this->textbox1
;
2609 $content = $this->getCurrentContent();
2610 $this->textbox1
= $this->toEditText( $content );
2612 $this->showTextbox1();
2614 $this->showContentForm();
2617 $wgOut->addHTML( $this->editFormTextAfterContent
);
2619 $this->showStandardInputs();
2621 $this->showFormAfterText();
2623 $this->showTosSummary();
2625 $this->showEditTools();
2627 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2629 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2630 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2632 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2633 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2635 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'limitreport' ),
2636 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2638 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2640 if ( $this->isConflict
) {
2642 $this->showConflict();
2643 } catch ( MWContentSerializationException
$ex ) {
2644 // this can't really happen, but be nice if it does.
2646 'content-failed-to-parse',
2647 $this->contentModel
,
2648 $this->contentFormat
,
2651 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2655 // Marker for detecting truncated form data. This must be the last
2656 // parameter sent in order to be of use, so do not move me.
2657 $wgOut->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2658 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2660 if ( !$wgUser->getOption( 'previewontop' ) ) {
2661 $this->displayPreviewArea( $previewOutput, false );
2667 * Extract the section title from current section text, if any.
2669 * @param string $text
2670 * @return string|bool String or false
2672 public static function extractSectionTitle( $text ) {
2673 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2674 if ( !empty( $matches[2] ) ) {
2676 return $wgParser->stripSectionName( trim( $matches[2] ) );
2685 protected function showHeader() {
2686 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2687 global $wgAllowUserCss, $wgAllowUserJs;
2689 if ( $this->mTitle
->isTalkPage() ) {
2690 $wgOut->addWikiMsg( 'talkpagetext' );
2694 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
2695 if ( count( $editNotices ) ) {
2696 $wgOut->addHTML( implode( "\n", $editNotices ) );
2698 $msg = wfMessage( 'editnotice-notext' );
2699 if ( !$msg->isDisabled() ) {
2701 '<div class="mw-editnotice-notext">'
2702 . $msg->parseAsBlock()
2708 if ( $this->isConflict
) {
2709 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2710 $this->edittime
= $this->mArticle
->getTimestamp();
2712 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2713 // We use $this->section to much before this and getVal('wgSection') directly in other places
2714 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2715 // Someone is welcome to try refactoring though
2716 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2720 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2721 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2722 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2723 if ( $sectionTitle !== false ) {
2724 $this->summary
= "/* $sectionTitle */ ";
2729 if ( $this->missingComment
) {
2730 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2733 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2734 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2737 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2738 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2741 if ( $this->blankArticle
) {
2742 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2745 if ( $this->selfRedirect
) {
2746 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2749 if ( $this->hookError
!== '' ) {
2750 $wgOut->addWikiText( $this->hookError
);
2753 if ( !$this->checkUnicodeCompliantBrowser() ) {
2754 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2757 if ( $this->section
!= 'new' ) {
2758 $revision = $this->mArticle
->getRevisionFetched();
2760 // Let sysop know that this will make private content public if saved
2762 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2763 $wgOut->wrapWikiMsg(
2764 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2765 'rev-deleted-text-permission'
2767 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2768 $wgOut->wrapWikiMsg(
2769 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2770 'rev-deleted-text-view'
2774 if ( !$revision->isCurrent() ) {
2775 $this->mArticle
->setOldSubtitle( $revision->getId() );
2776 $wgOut->addWikiMsg( 'editingold' );
2778 } elseif ( $this->mTitle
->exists() ) {
2779 // Something went wrong
2781 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2782 array( 'missing-revision', $this->oldid
) );
2787 if ( wfReadOnly() ) {
2788 $wgOut->wrapWikiMsg(
2789 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2790 array( 'readonlywarning', wfReadOnlyReason() )
2792 } elseif ( $wgUser->isAnon() ) {
2793 if ( $this->formtype
!= 'preview' ) {
2794 $wgOut->wrapWikiMsg(
2795 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2796 array( 'anoneditwarning',
2798 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2800 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2803 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2804 'anonpreviewwarning'
2808 if ( $this->isCssJsSubpage
) {
2809 # Check the skin exists
2810 if ( $this->isWrongCaseCssJsPage
) {
2811 $wgOut->wrapWikiMsg(
2812 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2813 array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() )
2816 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
2817 if ( $this->formtype
!== 'preview' ) {
2818 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
2819 $wgOut->wrapWikiMsg(
2820 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2821 array( 'usercssyoucanpreview' )
2825 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
2826 $wgOut->wrapWikiMsg(
2827 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2828 array( 'userjsyoucanpreview' )
2836 if ( $this->mTitle
->isProtected( 'edit' ) &&
2837 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2839 # Is the title semi-protected?
2840 if ( $this->mTitle
->isSemiProtected() ) {
2841 $noticeMsg = 'semiprotectedpagewarning';
2843 # Then it must be protected based on static groups (regular)
2844 $noticeMsg = 'protectedpagewarning';
2846 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2847 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2849 if ( $this->mTitle
->isCascadeProtected() ) {
2850 # Is this page under cascading protection from some source pages?
2851 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2852 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2853 $cascadeSourcesCount = count( $cascadeSources );
2854 if ( $cascadeSourcesCount > 0 ) {
2855 # Explain, and list the titles responsible
2856 foreach ( $cascadeSources as $page ) {
2857 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2860 $notice .= '</div>';
2861 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2863 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2864 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2866 'showIfEmpty' => false,
2867 'msgKey' => array( 'titleprotectedwarning' ),
2868 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2871 if ( $this->kblength
=== false ) {
2872 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2875 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2876 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2879 $wgLang->formatNum( $this->kblength
),
2880 $wgLang->formatNum( $wgMaxArticleSize )
2884 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2885 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2888 $wgLang->formatSize( strlen( $this->textbox1
) ),
2889 strlen( $this->textbox1
)
2894 # Add header copyright warning
2895 $this->showHeaderCopyrightWarning();
2901 * Standard summary input and label (wgSummary), abstracted so EditPage
2902 * subclasses may reorganize the form.
2903 * Note that you do not need to worry about the label's for=, it will be
2904 * inferred by the id given to the input. You can remove them both by
2905 * passing array( 'id' => false ) to $userInputAttrs.
2907 * @param string $summary The value of the summary input
2908 * @param string $labelText The html to place inside the label
2909 * @param array $inputAttrs Array of attrs to use on the input
2910 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2912 * @return array An array in the format array( $label, $input )
2914 function getSummaryInput( $summary = "", $labelText = null,
2915 $inputAttrs = null, $spanLabelAttrs = null
2917 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2918 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2919 'id' => 'wpSummary',
2920 'maxlength' => '200',
2923 'spellcheck' => 'true',
2924 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2926 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2927 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2928 'id' => "wpSummaryLabel"
2935 $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null,
2938 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2941 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2943 return array( $label, $input );
2947 * @param bool $isSubjectPreview True if this is the section subject/title
2948 * up top, or false if this is the comment summary
2949 * down below the textarea
2950 * @param string $summary The text of the summary to display
2952 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2953 global $wgOut, $wgContLang;
2954 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2955 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2956 if ( $isSubjectPreview ) {
2957 if ( $this->nosummary
) {
2961 if ( !$this->mShowSummaryField
) {
2965 $summary = $wgContLang->recodeForEdit( $summary );
2966 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2967 list( $label, $input ) = $this->getSummaryInput(
2970 array( 'class' => $summaryClass ),
2973 $wgOut->addHTML( "{$label} {$input}" );
2977 * @param bool $isSubjectPreview True if this is the section subject/title
2978 * up top, or false if this is the comment summary
2979 * down below the textarea
2980 * @param string $summary The text of the summary to display
2983 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2984 // avoid spaces in preview, gets always trimmed on save
2985 $summary = trim( $summary );
2986 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2992 if ( $isSubjectPreview ) {
2993 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2994 ->inContentLanguage()->text();
2997 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2999 $summary = wfMessage( $message )->parse()
3000 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3001 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
3004 protected function showFormBeforeText() {
3006 $section = htmlspecialchars( $this->section
);
3007 $wgOut->addHTML( <<<HTML
3008 <input type='hidden' value="{$section}" name="wpSection"/>
3009 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
3010 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
3011 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
3015 if ( !$this->checkUnicodeCompliantBrowser() ) {
3016 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
3020 protected function showFormAfterText() {
3021 global $wgOut, $wgUser;
3023 * To make it harder for someone to slip a user a page
3024 * which submits an edit form to the wiki without their
3025 * knowledge, a random token is associated with the login
3026 * session. If it's not passed back with the submission,
3027 * we won't save the page, or render user JavaScript and
3030 * For anon editors, who may not have a session, we just
3031 * include the constant suffix to prevent editing from
3032 * broken text-mangling proxies.
3034 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
3038 * Subpage overridable method for printing the form for page content editing
3039 * By default this simply outputs wpTextbox1
3040 * Subclasses can override this to provide a custom UI for editing;
3041 * be it a form, or simply wpTextbox1 with a modified content that will be
3042 * reverse modified when extracted from the post data.
3043 * Note that this is basically the inverse for importContentFormData
3045 protected function showContentForm() {
3046 $this->showTextbox1();
3050 * Method to output wpTextbox1
3051 * The $textoverride method can be used by subclasses overriding showContentForm
3052 * to pass back to this method.
3054 * @param array $customAttribs Array of html attributes to use in the textarea
3055 * @param string $textoverride Optional text to override $this->textarea1 with
3057 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3058 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3059 $attribs = array( 'style' => 'display:none;' );
3061 $classes = array(); // Textarea CSS
3062 if ( $this->mTitle
->isProtected( 'edit' ) &&
3063 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
3065 # Is the title semi-protected?
3066 if ( $this->mTitle
->isSemiProtected() ) {
3067 $classes[] = 'mw-textarea-sprotected';
3069 # Then it must be protected based on static groups (regular)
3070 $classes[] = 'mw-textarea-protected';
3072 # Is the title cascade-protected?
3073 if ( $this->mTitle
->isCascadeProtected() ) {
3074 $classes[] = 'mw-textarea-cprotected';
3078 $attribs = array( 'tabindex' => 1 );
3080 if ( is_array( $customAttribs ) ) {
3081 $attribs +
= $customAttribs;
3084 if ( count( $classes ) ) {
3085 if ( isset( $attribs['class'] ) ) {
3086 $classes[] = $attribs['class'];
3088 $attribs['class'] = implode( ' ', $classes );
3093 $textoverride !== null ?
$textoverride : $this->textbox1
,
3099 protected function showTextbox2() {
3100 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
3103 protected function showTextbox( $text, $name, $customAttribs = array() ) {
3104 global $wgOut, $wgUser;
3106 $wikitext = $this->safeUnicodeOutput( $text );
3107 if ( strval( $wikitext ) !== '' ) {
3108 // Ensure there's a newline at the end, otherwise adding lines
3110 // But don't add a newline if the ext is empty, or Firefox in XHTML
3111 // mode will show an extra newline. A bit annoying.
3115 $attribs = $customAttribs +
array(
3118 'cols' => $wgUser->getIntOption( 'cols' ),
3119 'rows' => $wgUser->getIntOption( 'rows' ),
3120 // Avoid PHP notices when appending preferences
3121 // (appending allows customAttribs['style'] to still work).
3125 $pageLang = $this->mTitle
->getPageLanguage();
3126 $attribs['lang'] = $pageLang->getHtmlCode();
3127 $attribs['dir'] = $pageLang->getDir();
3129 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3132 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3136 $classes[] = 'ontop';
3139 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3141 if ( $this->formtype
!= 'preview' ) {
3142 $attribs['style'] = 'display: none;';
3145 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
3147 if ( $this->formtype
== 'preview' ) {
3148 $this->showPreview( $previewOutput );
3150 // Empty content container for LivePreview
3151 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3152 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3153 'class' => 'mw-content-' . $pageViewLang->getDir() );
3154 $wgOut->addHTML( Html
::rawElement( 'div', $attribs ) );
3157 $wgOut->addHTML( '</div>' );
3159 if ( $this->formtype
== 'diff' ) {
3162 } catch ( MWContentSerializationException
$ex ) {
3164 'content-failed-to-parse',
3165 $this->contentModel
,
3166 $this->contentFormat
,
3169 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3175 * Append preview output to $wgOut.
3176 * Includes category rendering if this is a category page.
3178 * @param string $text The HTML to be output for the preview.
3180 protected function showPreview( $text ) {
3182 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3183 $this->mArticle
->openShowCategory();
3185 # This hook seems slightly odd here, but makes things more
3186 # consistent for extensions.
3187 Hooks
::run( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3188 $wgOut->addHTML( $text );
3189 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3190 $this->mArticle
->closeShowCategory();
3195 * Get a diff between the current contents of the edit box and the
3196 * version of the page we're editing from.
3198 * If this is a section edit, we'll replace the section as for final
3199 * save and then make a comparison.
3201 function showDiff() {
3202 global $wgUser, $wgContLang, $wgOut;
3204 $oldtitlemsg = 'currentrev';
3205 # if message does not exist, show diff against the preloaded default
3206 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3207 $oldtext = $this->mTitle
->getDefaultMessageText();
3208 if ( $oldtext !== false ) {
3209 $oldtitlemsg = 'defaultmessagetext';
3210 $oldContent = $this->toEditContent( $oldtext );
3215 $oldContent = $this->getCurrentContent();
3218 $textboxContent = $this->toEditContent( $this->textbox1
);
3220 $newContent = $this->mArticle
->replaceSectionContent(
3221 $this->section
, $textboxContent,
3222 $this->summary
, $this->edittime
);
3224 if ( $newContent ) {
3225 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3226 Hooks
::run( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3228 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
3229 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
3232 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3233 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3234 $newtitle = wfMessage( 'yourtext' )->parse();
3236 if ( !$oldContent ) {
3237 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3240 if ( !$newContent ) {
3241 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3244 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3245 $de->setContent( $oldContent, $newContent );
3247 $difftext = $de->getDiff( $oldtitle, $newtitle );
3248 $de->showDiffStyle();
3253 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3257 * Show the header copyright warning.
3259 protected function showHeaderCopyrightWarning() {
3260 $msg = 'editpage-head-copy-warn';
3261 if ( !wfMessage( $msg )->isDisabled() ) {
3263 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3264 'editpage-head-copy-warn' );
3269 * Give a chance for site and per-namespace customizations of
3270 * terms of service summary link that might exist separately
3271 * from the copyright notice.
3273 * This will display between the save button and the edit tools,
3274 * so should remain short!
3276 protected function showTosSummary() {
3277 $msg = 'editpage-tos-summary';
3278 Hooks
::run( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
3279 if ( !wfMessage( $msg )->isDisabled() ) {
3281 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3282 $wgOut->addWikiMsg( $msg );
3283 $wgOut->addHTML( '</div>' );
3287 protected function showEditTools() {
3289 $wgOut->addHTML( '<div class="mw-editTools">' .
3290 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3295 * Get the copyright warning
3297 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3300 protected function getCopywarn() {
3301 return self
::getCopyrightWarning( $this->mTitle
);
3305 * Get the copyright warning, by default returns wikitext
3307 * @param Title $title
3308 * @param string $format Output format, valid values are any function of a Message object
3311 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3312 global $wgRightsText;
3313 if ( $wgRightsText ) {
3314 $copywarnMsg = array( 'copyrightwarning',
3315 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3318 $copywarnMsg = array( 'copyrightwarning2',
3319 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3321 // Allow for site and per-namespace customization of contribution/copyright notice.
3322 Hooks
::run( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3324 return "<div id=\"editpage-copywarn\">\n" .
3325 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3329 * Get the Limit report for page previews
3332 * @param ParserOutput $output ParserOutput object from the parse
3333 * @return string HTML
3335 public static function getPreviewLimitReport( $output ) {
3336 if ( !$output ||
!$output->getLimitReportData() ) {
3340 $limitReport = Html
::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3341 wfMessage( 'limitreport-title' )->parseAsBlock()
3344 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3345 $limitReport .= Html
::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3347 $limitReport .= Html
::openElement( 'table', array(
3348 'class' => 'preview-limit-report wikitable'
3350 Html
::openElement( 'tbody' );
3352 foreach ( $output->getLimitReportData() as $key => $value ) {
3353 if ( Hooks
::run( 'ParserLimitReportFormat',
3354 array( $key, &$value, &$limitReport, true, true )
3356 $keyMsg = wfMessage( $key );
3357 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3358 if ( !$valueMsg->exists() ) {
3359 $valueMsg = new RawMessage( '$1' );
3361 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3362 $limitReport .= Html
::openElement( 'tr' ) .
3363 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3364 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3365 Html
::closeElement( 'tr' );
3370 $limitReport .= Html
::closeElement( 'tbody' ) .
3371 Html
::closeElement( 'table' ) .
3372 Html
::closeElement( 'div' );
3374 return $limitReport;
3377 protected function showStandardInputs( &$tabindex = 2 ) {
3379 $wgOut->addHTML( "<div class='editOptions'>\n" );
3381 if ( $this->section
!= 'new' ) {
3382 $this->showSummaryInput( false, $this->summary
);
3383 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3386 $checkboxes = $this->getCheckboxes( $tabindex,
3387 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
3388 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3390 // Show copyright warning.
3391 $wgOut->addWikiText( $this->getCopywarn() );
3392 $wgOut->addHTML( $this->editFormTextAfterWarn
);
3394 $wgOut->addHTML( "<div class='editButtons'>\n" );
3395 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3397 $cancel = $this->getCancelLink();
3398 if ( $cancel !== '' ) {
3399 $cancel .= Html
::element( 'span',
3400 array( 'class' => 'mw-editButtons-pipe-separator' ),
3401 wfMessage( 'pipe-separator' )->text() );
3404 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3405 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3407 'target' => 'helpwindow',
3408 'href' => $edithelpurl,
3410 $edithelp = Html
::linkButton( wfMessage( 'edithelp' )->text(),
3411 $attrs, array( 'mw-ui-quiet' ) ) .
3412 wfMessage( 'word-separator' )->escaped() .
3413 wfMessage( 'newwindow' )->parse();
3415 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3416 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3417 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3419 Hooks
::run( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3421 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3425 * Show an edit conflict. textbox1 is already shown in showEditForm().
3426 * If you want to use another entry point to this function, be careful.
3428 protected function showConflict() {
3431 if ( Hooks
::run( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3432 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3434 $content1 = $this->toEditContent( $this->textbox1
);
3435 $content2 = $this->toEditContent( $this->textbox2
);
3437 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3438 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3439 $de->setContent( $content2, $content1 );
3441 wfMessage( 'yourtext' )->parse(),
3442 wfMessage( 'storedversion' )->text()
3445 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3446 $this->showTextbox2();
3453 public function getCancelLink() {
3454 $cancelParams = array();
3455 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3456 $cancelParams['oldid'] = $this->oldid
;
3458 $attrs = array( 'id' => 'mw-editform-cancel' );
3460 return Linker
::linkKnown(
3461 $this->getContextTitle(),
3462 wfMessage( 'cancel' )->parse(),
3463 Html
::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3469 * Returns the URL to use in the form's action attribute.
3470 * This is used by EditPage subclasses when simply customizing the action
3471 * variable in the constructor is not enough. This can be used when the
3472 * EditPage lives inside of a Special page rather than a custom page action.
3474 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3477 protected function getActionURL( Title
$title ) {
3478 return $title->getLocalURL( array( 'action' => $this->action
) );
3482 * Check if a page was deleted while the user was editing it, before submit.
3483 * Note that we rely on the logging table, which hasn't been always there,
3484 * but that doesn't matter, because this only applies to brand new
3488 protected function wasDeletedSinceLastEdit() {
3489 if ( $this->deletedSinceEdit
!== null ) {
3490 return $this->deletedSinceEdit
;
3493 $this->deletedSinceEdit
= false;
3495 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3496 $this->lastDelete
= $this->getLastDelete();
3497 if ( $this->lastDelete
) {
3498 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3499 if ( $deleteTime > $this->starttime
) {
3500 $this->deletedSinceEdit
= true;
3505 return $this->deletedSinceEdit
;
3509 * @return bool|stdClass
3511 protected function getLastDelete() {
3512 $dbr = wfGetDB( DB_SLAVE
);
3513 $data = $dbr->selectRow(
3514 array( 'logging', 'user' ),
3527 'log_namespace' => $this->mTitle
->getNamespace(),
3528 'log_title' => $this->mTitle
->getDBkey(),
3529 'log_type' => 'delete',
3530 'log_action' => 'delete',
3534 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3536 // Quick paranoid permission checks...
3537 if ( is_object( $data ) ) {
3538 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3539 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
3542 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3543 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
3551 * Get the rendered text for previewing.
3552 * @throws MWException
3555 function getPreviewText() {
3556 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3557 global $wgAllowUserCss, $wgAllowUserJs;
3559 $stats = $wgOut->getContext()->getStats();
3561 if ( $wgRawHtml && !$this->mTokenOk
) {
3562 // Could be an offsite preview attempt. This is very unsafe if
3563 // HTML is enabled, as it could be an attack.
3565 if ( $this->textbox1
!== '' ) {
3566 // Do not put big scary notice, if previewing the empty
3567 // string, which happens when you initially edit
3568 // a category page, due to automatic preview-on-open.
3569 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3570 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3572 $stats->increment( 'edit.failures.session_loss' );
3579 $content = $this->toEditContent( $this->textbox1
);
3583 'AlternateEditPreview',
3584 array( $this, &$content, &$previewHTML, &$this->mParserOutput
) )
3586 return $previewHTML;
3589 # provide a anchor link to the editform
3590 $continueEditing = '<span class="mw-continue-editing">' .
3591 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3592 wfMessage( 'continue-editing' )->text() . ']]</span>';
3593 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3594 if ( $this->mTokenOkExceptSuffix
) {
3595 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3596 $stats->increment( 'edit.failures.bad_token' );
3598 $note = wfMessage( 'session_fail_preview' )->plain();
3599 $stats->increment( 'edit.failures.session_loss' );
3601 } elseif ( $this->incompleteForm
) {
3602 $note = wfMessage( 'edit_form_incomplete' )->plain();
3603 if ( $this->mTriedSave
) {
3604 $stats->increment( 'edit.failures.incomplete_form' );
3607 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3610 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
3611 $parserOptions->setIsPreview( true );
3612 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3614 # don't parse non-wikitext pages, show message about preview
3615 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3616 if ( $this->mTitle
->isCssJsSubpage() ) {
3618 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3624 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3626 if ( $level === 'user' && !$wgAllowUserCss ) {
3629 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3631 if ( $level === 'user' && !$wgAllowUserJs ) {
3638 # Used messages to make sure grep find them:
3639 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3640 if ( $level && $format ) {
3641 $note = "<div id='mw-{$level}{$format}preview'>" .
3642 wfMessage( "{$level}{$format}preview" )->text() .
3643 ' ' . $continueEditing . "</div>";
3647 # If we're adding a comment, we need to show the
3648 # summary as the headline
3649 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3650 $content = $content->addSectionHeader( $this->summary
);
3653 $hook_args = array( $this, &$content );
3654 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3655 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3657 $parserOptions->enableLimitReport();
3659 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3660 # But it's now deprecated, so never mind
3662 $pstContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3663 $scopedCallback = $parserOptions->setupFakeRevision(
3664 $this->mTitle
, $pstContent, $wgUser );
3665 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3667 # Try to stash the edit for the final submission step
3668 # @todo: different date format preferences cause cache misses
3669 ApiStashEdit
::stashEditFromPreview(
3670 $this->getArticle(), $content, $pstContent,
3671 $parserOutput, $parserOptions, $parserOptions, wfTimestampNow()
3674 $parserOutput->setEditSectionTokens( false ); // no section edit links
3675 $previewHTML = $parserOutput->getText();
3676 $this->mParserOutput
= $parserOutput;
3677 $wgOut->addParserOutputMetadata( $parserOutput );
3679 if ( count( $parserOutput->getWarnings() ) ) {
3680 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3682 } catch ( MWContentSerializationException
$ex ) {
3684 'content-failed-to-parse',
3685 $this->contentModel
,
3686 $this->contentFormat
,
3689 $note .= "\n\n" . $m->parse();
3693 if ( $this->isConflict
) {
3694 $conflict = '<h2 id="mw-previewconflict">'
3695 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3697 $conflict = '<hr />';
3700 $previewhead = "<div class='previewnote'>\n" .
3701 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3702 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3704 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3705 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3706 'class' => 'mw-content-' . $pageViewLang->getDir() );
3707 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3709 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3715 function getTemplates() {
3716 if ( $this->preview ||
$this->section
!= '' ) {
3717 $templates = array();
3718 if ( !isset( $this->mParserOutput
) ) {
3721 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3722 foreach ( array_keys( $template ) as $dbk ) {
3723 $templates[] = Title
::makeTitle( $ns, $dbk );
3728 return $this->mTitle
->getTemplateLinksFrom();
3733 * Shows a bulletin board style toolbar for common editing functions.
3734 * It can be disabled in the user preferences.
3736 * @param $title Title object for the page being edited (optional)
3739 static function getEditToolbar( $title = null ) {
3740 global $wgContLang, $wgOut;
3741 global $wgEnableUploads, $wgForeignFileRepos;
3743 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3744 $showSignature = true;
3746 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
3750 * $toolarray is an array of arrays each of which includes the
3751 * opening tag, the closing tag, optionally a sample text that is
3752 * inserted between the two when no selection is highlighted
3753 * and. The tip text is shown when the user moves the mouse
3756 * Images are defined in ResourceLoaderEditToolbarModule.
3760 'id' => 'mw-editbutton-bold',
3762 'close' => '\'\'\'',
3763 'sample' => wfMessage( 'bold_sample' )->text(),
3764 'tip' => wfMessage( 'bold_tip' )->text(),
3767 'id' => 'mw-editbutton-italic',
3770 'sample' => wfMessage( 'italic_sample' )->text(),
3771 'tip' => wfMessage( 'italic_tip' )->text(),
3774 'id' => 'mw-editbutton-link',
3777 'sample' => wfMessage( 'link_sample' )->text(),
3778 'tip' => wfMessage( 'link_tip' )->text(),
3781 'id' => 'mw-editbutton-extlink',
3784 'sample' => wfMessage( 'extlink_sample' )->text(),
3785 'tip' => wfMessage( 'extlink_tip' )->text(),
3788 'id' => 'mw-editbutton-headline',
3791 'sample' => wfMessage( 'headline_sample' )->text(),
3792 'tip' => wfMessage( 'headline_tip' )->text(),
3794 $imagesAvailable ?
array(
3795 'id' => 'mw-editbutton-image',
3796 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3798 'sample' => wfMessage( 'image_sample' )->text(),
3799 'tip' => wfMessage( 'image_tip' )->text(),
3801 $imagesAvailable ?
array(
3802 'id' => 'mw-editbutton-media',
3803 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3805 'sample' => wfMessage( 'media_sample' )->text(),
3806 'tip' => wfMessage( 'media_tip' )->text(),
3809 'id' => 'mw-editbutton-nowiki',
3810 'open' => "<nowiki>",
3811 'close' => "</nowiki>",
3812 'sample' => wfMessage( 'nowiki_sample' )->text(),
3813 'tip' => wfMessage( 'nowiki_tip' )->text(),
3815 $showSignature ?
array(
3816 'id' => 'mw-editbutton-signature',
3820 'tip' => wfMessage( 'sig_tip' )->text(),
3823 'id' => 'mw-editbutton-hr',
3824 'open' => "\n----\n",
3827 'tip' => wfMessage( 'hr_tip' )->text(),
3831 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3832 foreach ( $toolarray as $tool ) {
3838 // Images are defined in ResourceLoaderEditToolbarModule
3840 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3841 // Older browsers show a "speedtip" type message only for ALT.
3842 // Ideally these should be different, realistically they
3843 // probably don't need to be.
3851 $script .= Xml
::encodeJsCall(
3852 'mw.toolbar.addButton',
3854 ResourceLoader
::inDebugMode()
3859 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
3861 $toolbar = '<div id="toolbar"></div>';
3863 Hooks
::run( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3869 * Returns an array of html code of the following checkboxes:
3872 * @param int $tabindex Current tabindex
3873 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3874 * status of the checkbox
3878 public function getCheckboxes( &$tabindex, $checked ) {
3879 global $wgUser, $wgUseMediaWikiUIEverywhere;
3881 $checkboxes = array();
3883 // don't show the minor edit checkbox if it's a new page or section
3884 if ( !$this->isNew
) {
3885 $checkboxes['minor'] = '';
3886 $minorLabel = wfMessage( 'minoredit' )->parse();
3887 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3889 'tabindex' => ++
$tabindex,
3890 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3891 'id' => 'wpMinoredit',
3894 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3895 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3896 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3897 ">{$minorLabel}</label>";
3899 if ( $wgUseMediaWikiUIEverywhere ) {
3900 $checkboxes['minor'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3902 Html
::closeElement( 'div' );
3904 $checkboxes['minor'] = $minorEditHtml;
3909 $watchLabel = wfMessage( 'watchthis' )->parse();
3910 $checkboxes['watch'] = '';
3911 if ( $wgUser->isLoggedIn() ) {
3913 'tabindex' => ++
$tabindex,
3914 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3915 'id' => 'wpWatchthis',
3918 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3919 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3920 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3921 ">{$watchLabel}</label>";
3922 if ( $wgUseMediaWikiUIEverywhere ) {
3923 $checkboxes['watch'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3925 Html
::closeElement( 'div' );
3927 $checkboxes['watch'] = $watchThisHtml;
3930 Hooks
::run( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3935 * Returns an array of html code of the following buttons:
3936 * save, diff, preview and live
3938 * @param int $tabindex Current tabindex
3942 public function getEditButtons( &$tabindex ) {
3948 'tabindex' => ++
$tabindex,
3949 ) + Linker
::tooltipAndAccesskeyAttribs( 'save' );
3950 $buttons['save'] = Html
::submitButton( wfMessage( 'savearticle' )->text(),
3951 $attribs, array( 'mw-ui-constructive' ) );
3953 ++
$tabindex; // use the same for preview and live preview
3955 'id' => 'wpPreview',
3956 'name' => 'wpPreview',
3957 'tabindex' => $tabindex,
3958 ) + Linker
::tooltipAndAccesskeyAttribs( 'preview' );
3959 $buttons['preview'] = Html
::submitButton( wfMessage( 'showpreview' )->text(),
3961 $buttons['live'] = '';
3966 'tabindex' => ++
$tabindex,
3967 ) + Linker
::tooltipAndAccesskeyAttribs( 'diff' );
3968 $buttons['diff'] = Html
::submitButton( wfMessage( 'showdiff' )->text(),
3971 Hooks
::run( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3976 * Creates a basic error page which informs the user that
3977 * they have attempted to edit a nonexistent section.
3979 function noSuchSectionPage() {
3982 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3984 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3985 Hooks
::run( 'EditPageNoSuchSection', array( &$this, &$res ) );
3986 $wgOut->addHTML( $res );
3988 $wgOut->returnToMain( false, $this->mTitle
);
3992 * Show "your edit contains spam" page with your diff and text
3994 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3996 public function spamPageWithContent( $match = false ) {
3997 global $wgOut, $wgLang;
3998 $this->textbox2
= $this->textbox1
;
4000 if ( is_array( $match ) ) {
4001 $match = $wgLang->listToText( $match );
4003 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
4005 $wgOut->addHTML( '<div id="spamprotected">' );
4006 $wgOut->addWikiMsg( 'spamprotectiontext' );
4008 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4010 $wgOut->addHTML( '</div>' );
4012 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4015 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4016 $this->showTextbox2();
4018 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
4022 * Check if the browser is on a blacklist of user-agents known to
4023 * mangle UTF-8 data on form submission. Returns true if Unicode
4024 * should make it through, false if it's known to be a problem.
4027 private function checkUnicodeCompliantBrowser() {
4028 global $wgBrowserBlackList, $wgRequest;
4030 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
4031 if ( $currentbrowser === false ) {
4032 // No User-Agent header sent? Trust it by default...
4036 foreach ( $wgBrowserBlackList as $browser ) {
4037 if ( preg_match( $browser, $currentbrowser ) ) {
4045 * Filter an input field through a Unicode de-armoring process if it
4046 * came from an old browser with known broken Unicode editing issues.
4048 * @param WebRequest $request
4049 * @param string $field
4052 protected function safeUnicodeInput( $request, $field ) {
4053 $text = rtrim( $request->getText( $field ) );
4054 return $request->getBool( 'safemode' )
4055 ?
$this->unmakeSafe( $text )
4060 * Filter an output field through a Unicode armoring process if it is
4061 * going to an old browser with known broken Unicode editing issues.
4063 * @param string $text
4066 protected function safeUnicodeOutput( $text ) {
4068 $codedText = $wgContLang->recodeForEdit( $text );
4069 return $this->checkUnicodeCompliantBrowser()
4071 : $this->makeSafe( $codedText );
4075 * A number of web browsers are known to corrupt non-ASCII characters
4076 * in a UTF-8 text editing environment. To protect against this,
4077 * detected browsers will be served an armored version of the text,
4078 * with non-ASCII chars converted to numeric HTML character references.
4080 * Preexisting such character references will have a 0 added to them
4081 * to ensure that round-trips do not alter the original data.
4083 * @param string $invalue
4086 private function makeSafe( $invalue ) {
4087 // Armor existing references for reversibility.
4088 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
4093 $valueLength = strlen( $invalue );
4094 for ( $i = 0; $i < $valueLength; $i++
) {
4095 $bytevalue = ord( $invalue[$i] );
4096 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4097 $result .= chr( $bytevalue );
4099 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4100 $working = $working << 6;
4101 $working +
= ( $bytevalue & 0x3F );
4103 if ( $bytesleft <= 0 ) {
4104 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4106 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4107 $working = $bytevalue & 0x1F;
4109 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4110 $working = $bytevalue & 0x0F;
4112 } else { // 1111 0xxx
4113 $working = $bytevalue & 0x07;
4121 * Reverse the previously applied transliteration of non-ASCII characters
4122 * back to UTF-8. Used to protect data from corruption by broken web browsers
4123 * as listed in $wgBrowserBlackList.
4125 * @param string $invalue
4128 private function unmakeSafe( $invalue ) {
4130 $valueLength = strlen( $invalue );
4131 for ( $i = 0; $i < $valueLength; $i++
) {
4132 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4136 $hexstring .= $invalue[$i];
4138 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4140 // Do some sanity checks. These aren't needed for reversibility,
4141 // but should help keep the breakage down if the editor
4142 // breaks one of the entities whilst editing.
4143 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4144 $codepoint = hexdec( $hexstring );
4145 $result .= UtfNormal\Utils
::codepointToUtf8( $codepoint );
4147 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4150 $result .= substr( $invalue, $i, 1 );
4153 // reverse the transform that we made for reversibility reasons.
4154 return strtr( $result, array( "�" => "&#x" ) );