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 * HTML id and name for the beginning of the edit form.
173 const EDITFORM_ID
= 'editform';
176 * Prefix of key for cookie used to pass post-edit state.
177 * The revision id edited is added after this
179 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
182 * Duration of PostEdit cookie, in seconds.
183 * The cookie will be removed instantly if the JavaScript runs.
185 * Otherwise, though, we don't want the cookies to accumulate.
186 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
187 * limit of only 20 cookies per domain. This still applies at least to some
188 * versions of IE without full updates:
189 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
191 * A value of 20 minutes should be enough to take into account slow loads and minor
192 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
194 const POST_EDIT_COOKIE_DURATION
= 1200;
202 /** @var null|Title */
203 private $mContextTitle = null;
206 public $action = 'submit';
209 public $isConflict = false;
212 public $isCssJsSubpage = false;
215 public $isCssSubpage = false;
218 public $isJsSubpage = false;
221 public $isWrongCaseCssJsPage = false;
223 /** @var bool New page or new section */
224 public $isNew = false;
227 public $deletedSinceEdit;
235 /** @var bool|stdClass */
239 public $mTokenOk = false;
242 public $mTokenOkExceptSuffix = false;
245 public $mTriedSave = false;
248 public $incompleteForm = false;
251 public $tooBig = false;
254 public $kblength = false;
257 public $missingComment = false;
260 public $missingSummary = false;
263 public $allowBlankSummary = false;
266 protected $blankArticle = false;
269 protected $allowBlankArticle = false;
272 protected $selfRedirect = false;
275 protected $allowSelfRedirect = false;
278 public $autoSumm = '';
281 public $hookError = '';
283 /** @var ParserOutput */
284 public $mParserOutput;
286 /** @var bool Has a summary been preset using GET parameter &summary= ? */
287 public $hasPresetSummary = false;
290 public $mBaseRevision = false;
293 public $mShowSummaryField = true;
298 public $save = false;
301 public $preview = false;
304 public $diff = false;
307 public $minoredit = false;
310 public $watchthis = false;
313 public $recreate = false;
316 public $textbox1 = '';
319 public $textbox2 = '';
322 public $summary = '';
325 public $nosummary = false;
328 public $edittime = '';
331 public $section = '';
334 public $sectiontitle = '';
337 public $starttime = '';
343 public $parentRevId = 0;
346 public $editintro = '';
349 public $scrolltop = null;
354 /** @var null|string */
355 public $contentModel = null;
357 /** @var null|string */
358 public $contentFormat = null;
360 /** @var null|array */
361 public $changeTags = null;
363 # Placeholders for text injection by hooks (must be HTML)
364 # extensions should take care to _append_ to the present value
366 /** @var string Before even the preview */
367 public $editFormPageTop = '';
368 public $editFormTextTop = '';
369 public $editFormTextBeforeContent = '';
370 public $editFormTextAfterWarn = '';
371 public $editFormTextAfterTools = '';
372 public $editFormTextBottom = '';
373 public $editFormTextAfterContent = '';
374 public $previewTextAfterContent = '';
375 public $mPreloadContent = null;
377 /* $didSave should be set to true whenever an article was successfully altered. */
378 public $didSave = false;
379 public $undidRev = 0;
381 public $suppressIntro = false;
383 /** @var bool Set to true to allow editing of non-text content types. */
384 public $allowNonTextContent = false;
390 * @param Article $article
392 public function __construct( Article
$article ) {
393 $this->mArticle
= $article;
394 $this->mTitle
= $article->getTitle();
396 $this->contentModel
= $this->mTitle
->getContentModel();
398 $handler = ContentHandler
::getForModelID( $this->contentModel
);
399 $this->contentFormat
= $handler->getDefaultFormat();
405 public function getArticle() {
406 return $this->mArticle
;
413 public function getTitle() {
414 return $this->mTitle
;
418 * Set the context Title object
420 * @param Title|null $title Title object or null
422 public function setContextTitle( $title ) {
423 $this->mContextTitle
= $title;
427 * Get the context title object.
428 * If not set, $wgTitle will be returned. This behavior might change in
429 * the future to return $this->mTitle instead.
433 public function getContextTitle() {
434 if ( is_null( $this->mContextTitle
) ) {
438 return $this->mContextTitle
;
443 * Returns if the given content model is editable.
445 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
447 * @throws MWException If $modelId has no known handler
449 public function isSupportedContentModel( $modelId ) {
450 return $this->allowNonTextContent ||
451 ContentHandler
::getForModelID( $modelId ) instanceof TextContentHandler
;
459 * This is the function that gets called for "action=edit". It
460 * sets up various member variables, then passes execution to
461 * another function, usually showEditForm()
463 * The edit form is self-submitting, so that when things like
464 * preview and edit conflicts occur, we get the same form back
465 * with the extra stuff added. Only when the final submission
466 * is made and all is well do we actually save and redirect to
467 * the newly-edited page.
470 global $wgOut, $wgRequest, $wgUser;
471 // Allow extensions to modify/prevent this form or submission
472 if ( !Hooks
::run( 'AlternateEdit', array( $this ) ) ) {
476 wfDebug( __METHOD__
. ": enter\n" );
478 // If they used redlink=1 and the page exists, redirect to the main article
479 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
480 $wgOut->redirect( $this->mTitle
->getFullURL() );
484 $this->importFormData( $wgRequest );
485 $this->firsttime
= false;
487 if ( wfReadOnly() && $this->save
) {
490 $this->preview
= true;
494 $this->formtype
= 'save';
495 } elseif ( $this->preview
) {
496 $this->formtype
= 'preview';
497 } elseif ( $this->diff
) {
498 $this->formtype
= 'diff';
499 } else { # First time through
500 $this->firsttime
= true;
501 if ( $this->previewOnOpen() ) {
502 $this->formtype
= 'preview';
504 $this->formtype
= 'initial';
508 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
510 wfDebug( __METHOD__
. ": User can't edit\n" );
511 // Auto-block user's IP if the account was "hard" blocked
512 $wgUser->spreadAnyEditBlock();
514 $this->displayPermissionsError( $permErrors );
519 $this->isConflict
= false;
520 // css / js subpages of user pages get a special treatment
521 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
522 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
523 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
524 // @todo FIXME: Silly assignment.
525 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
527 # Show applicable editing introductions
528 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
532 # Attempt submission here. This will check for edit conflicts,
533 # and redundantly check for locked database, blocked IPs, etc.
534 # that edit() already checked just in case someone tries to sneak
535 # in the back door with a hand-edited submission URL.
537 if ( 'save' == $this->formtype
) {
538 $resultDetails = null;
539 $status = $this->attemptSave( $resultDetails );
540 if ( !$this->handleStatus( $status, $resultDetails ) ) {
545 # First time through: get contents, set time for conflict
547 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
548 if ( $this->initialiseForm() === false ) {
549 $this->noSuchSectionPage();
553 if ( !$this->mTitle
->getArticleID() ) {
554 Hooks
::run( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
556 Hooks
::run( 'EditFormInitialText', array( $this ) );
561 $this->showEditForm();
565 * @param string $rigor Same format as Title::getUserPermissionErrors()
568 protected function getEditPermissionErrors( $rigor = 'secure' ) {
571 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
572 # Can this title be created?
573 if ( !$this->mTitle
->exists() ) {
574 $permErrors = array_merge(
577 $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
582 # Ignore some permissions errors when a user is just previewing/viewing diffs
584 foreach ( $permErrors as $error ) {
585 if ( ( $this->preview ||
$this->diff
)
586 && ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' )
591 $permErrors = wfArrayDiff2( $permErrors, $remove );
597 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
598 * but with the following differences:
599 * - If redlink=1, the user will be redirected to the page
600 * - If there is content to display or the error occurs while either saving,
601 * previewing or showing the difference, it will be a
602 * "View source for ..." page displaying the source code after the error message.
605 * @param array $permErrors Array of permissions errors, as returned by
606 * Title::getUserPermissionsErrors().
607 * @throws PermissionsError
609 protected function displayPermissionsError( array $permErrors ) {
610 global $wgRequest, $wgOut;
612 if ( $wgRequest->getBool( 'redlink' ) ) {
613 // The edit page was reached via a red link.
614 // Redirect to the article page and let them click the edit tab if
615 // they really want a permission error.
616 $wgOut->redirect( $this->mTitle
->getFullURL() );
620 $content = $this->getContentObject();
622 # Use the normal message if there's nothing to display
623 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
624 $action = $this->mTitle
->exists() ?
'edit' :
625 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
626 throw new PermissionsError( $action, $permErrors );
629 Hooks
::run( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
631 $wgOut->setRobotPolicy( 'noindex,nofollow' );
632 $wgOut->setPageTitle( wfMessage(
634 $this->getContextTitle()->getPrefixedText()
636 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
637 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
638 $wgOut->addHTML( "<hr />\n" );
640 # If the user made changes, preserve them when showing the markup
641 # (This happens when a user is blocked during edit, for instance)
642 if ( !$this->firsttime
) {
643 $text = $this->textbox1
;
644 $wgOut->addWikiMsg( 'viewyourtext' );
646 $text = $this->toEditText( $content );
647 $wgOut->addWikiMsg( 'viewsourcetext' );
650 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
652 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
653 Linker
::formatTemplates( $this->getTemplates() ) ) );
655 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
657 if ( $this->mTitle
->exists() ) {
658 $wgOut->returnToMain( null, $this->mTitle
);
663 * Should we show a preview when the edit form is first shown?
667 protected function previewOnOpen() {
668 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
669 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
670 // Explicit override from request
672 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
673 // Explicit override from request
675 } elseif ( $this->section
== 'new' ) {
676 // Nothing *to* preview for new sections
678 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
679 && $wgUser->getOption( 'previewonfirst' )
681 // Standard preference behavior
683 } elseif ( !$this->mTitle
->exists()
684 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
685 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
687 // Categories are special
695 * Checks whether the user entered a skin name in uppercase,
696 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
700 protected function isWrongCaseCssJsPage() {
701 if ( $this->mTitle
->isCssJsSubpage() ) {
702 $name = $this->mTitle
->getSkinFromCssJsSubpage();
703 $skins = array_merge(
704 array_keys( Skin
::getSkinNames() ),
707 return !in_array( $name, $skins )
708 && in_array( strtolower( $name ), $skins );
715 * Returns whether section editing is supported for the current page.
716 * Subclasses may override this to replace the default behavior, which is
717 * to check ContentHandler::supportsSections.
719 * @return bool True if this edit page supports sections, false otherwise.
721 protected function isSectionEditSupported() {
722 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
723 return $contentHandler->supportsSections();
727 * This function collects the form data and uses it to populate various member variables.
728 * @param WebRequest $request
729 * @throws ErrorPageError
731 function importFormData( &$request ) {
732 global $wgContLang, $wgUser;
734 # Section edit can come from either the form or a link
735 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
737 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
738 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
741 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
743 if ( $request->wasPosted() ) {
744 # These fields need to be checked for encoding.
745 # Also remove trailing whitespace, but don't remove _initial_
746 # whitespace from the text boxes. This may be significant formatting.
747 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
748 if ( !$request->getCheck( 'wpTextbox2' ) ) {
749 // Skip this if wpTextbox2 has input, it indicates that we came
750 // from a conflict page with raw page text, not a custom form
751 // modified by subclasses
752 $textbox1 = $this->importContentFormData( $request );
753 if ( $textbox1 !== null ) {
754 $this->textbox1
= $textbox1;
758 # Truncate for whole multibyte characters
759 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
761 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
762 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
764 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
766 # Treat sectiontitle the same way as summary.
767 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
768 # currently doing double duty as both edit summary and section title. Right now this
769 # is just to allow API edits to work around this limitation, but this should be
770 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
771 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
772 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
774 $this->edittime
= $request->getVal( 'wpEdittime' );
775 $this->starttime
= $request->getVal( 'wpStarttime' );
777 $undidRev = $request->getInt( 'wpUndidRevision' );
779 $this->undidRev
= $undidRev;
782 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
784 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
785 // wpTextbox1 field is missing, possibly due to being "too big"
786 // according to some filter rules such as Suhosin's setting for
787 // suhosin.request.max_value_length (d'oh)
788 $this->incompleteForm
= true;
790 // If we receive the last parameter of the request, we can fairly
791 // claim the POST request has not been truncated.
793 // TODO: softened the check for cutover. Once we determine
794 // that it is safe, we should complete the transition by
795 // removing the "edittime" clause.
796 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
797 && is_null( $this->edittime
) );
799 if ( $this->incompleteForm
) {
800 # If the form is incomplete, force to preview.
801 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
802 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
803 $this->preview
= true;
805 $this->preview
= $request->getCheck( 'wpPreview' );
806 $this->diff
= $request->getCheck( 'wpDiff' );
808 // Remember whether a save was requested, so we can indicate
809 // if we forced preview due to session failure.
810 $this->mTriedSave
= !$this->preview
;
812 if ( $this->tokenOk( $request ) ) {
813 # Some browsers will not report any submit button
814 # if the user hits enter in the comment box.
815 # The unmarked state will be assumed to be a save,
816 # if the form seems otherwise complete.
817 wfDebug( __METHOD__
. ": Passed token check.\n" );
818 } elseif ( $this->diff
) {
819 # Failed token check, but only requested "Show Changes".
820 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
822 # Page might be a hack attempt posted from
823 # an external site. Preview instead of saving.
824 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
825 $this->preview
= true;
828 $this->save
= !$this->preview
&& !$this->diff
;
829 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
830 $this->edittime
= null;
833 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
834 $this->starttime
= null;
837 $this->recreate
= $request->getCheck( 'wpRecreate' );
839 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
840 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
842 # Don't force edit summaries when a user is editing their own user or talk page
843 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
844 && $this->mTitle
->getText() == $wgUser->getName()
846 $this->allowBlankSummary
= true;
848 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
849 ||
!$wgUser->getOption( 'forceeditsummary' );
852 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
854 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
855 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
857 $changeTags = $request->getVal( 'wpChangeTags' );
858 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
859 $this->changeTags
= array();
861 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
865 # Not a posted form? Start with nothing.
866 wfDebug( __METHOD__
. ": Not a posted form.\n" );
867 $this->textbox1
= '';
869 $this->sectiontitle
= '';
870 $this->edittime
= '';
871 $this->starttime
= wfTimestampNow();
873 $this->preview
= false;
876 $this->minoredit
= false;
877 // Watch may be overridden by request parameters
878 $this->watchthis
= $request->getBool( 'watchthis', false );
879 $this->recreate
= false;
881 // When creating a new section, we can preload a section title by passing it as the
882 // preloadtitle parameter in the URL (Bug 13100)
883 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
884 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
885 // Once wpSummary isn't being use for setting section titles, we should delete this.
886 $this->summary
= $request->getVal( 'preloadtitle' );
887 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
888 $this->summary
= $request->getText( 'summary' );
889 if ( $this->summary
!== '' ) {
890 $this->hasPresetSummary
= true;
894 if ( $request->getVal( 'minor' ) ) {
895 $this->minoredit
= true;
899 $this->oldid
= $request->getInt( 'oldid' );
900 $this->parentRevId
= $request->getInt( 'parentRevId' );
902 $this->bot
= $request->getBool( 'bot', true );
903 $this->nosummary
= $request->getBool( 'nosummary' );
905 // May be overridden by revision.
906 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
907 // May be overridden by revision.
908 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
910 if ( !ContentHandler
::getForModelID( $this->contentModel
)
911 ->isSupportedFormat( $this->contentFormat
)
913 throw new ErrorPageError(
914 'editpage-notsupportedcontentformat-title',
915 'editpage-notsupportedcontentformat-text',
916 array( $this->contentFormat
, ContentHandler
::getLocalizedName( $this->contentModel
) )
921 * @todo Check if the desired model is allowed in this namespace, and if
922 * a transition from the page's current model to the new model is
926 $this->editintro
= $request->getText( 'editintro',
927 // Custom edit intro for new sections
928 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
930 // Allow extensions to modify form data
931 Hooks
::run( 'EditPage::importFormData', array( $this, $request ) );
936 * Subpage overridable method for extracting the page content data from the
937 * posted form to be placed in $this->textbox1, if using customized input
938 * this method should be overridden and return the page text that will be used
939 * for saving, preview parsing and so on...
941 * @param WebRequest $request
943 protected function importContentFormData( &$request ) {
944 return; // Don't do anything, EditPage already extracted wpTextbox1
948 * Initialise form fields in the object
949 * Called on the first invocation, e.g. when a user clicks an edit link
950 * @return bool If the requested section is valid
952 function initialiseForm() {
954 $this->edittime
= $this->mArticle
->getTimestamp();
956 $content = $this->getContentObject( false ); #TODO: track content object?!
957 if ( $content === false ) {
960 $this->textbox1
= $this->toEditText( $content );
962 // activate checkboxes if user wants them to be always active
963 # Sort out the "watch" checkbox
964 if ( $wgUser->getOption( 'watchdefault' ) ) {
966 $this->watchthis
= true;
967 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
969 $this->watchthis
= true;
970 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
972 $this->watchthis
= true;
974 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
975 $this->minoredit
= true;
977 if ( $this->textbox1
=== false ) {
984 * @param Content|null $def_content The default value to return
986 * @return Content|null Content on success, $def_content for invalid sections
990 protected function getContentObject( $def_content = null ) {
991 global $wgOut, $wgRequest, $wgUser, $wgContLang;
995 // For message page not locally set, use the i18n message.
996 // For other non-existent articles, use preload text if any.
997 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
998 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
999 # If this is a system message, get the default text.
1000 $msg = $this->mTitle
->getDefaultMessageText();
1002 $content = $this->toEditContent( $msg );
1004 if ( $content === false ) {
1005 # If requested, preload some text.
1006 $preload = $wgRequest->getVal( 'preload',
1007 // Custom preload text for new sections
1008 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1009 $params = $wgRequest->getArray( 'preloadparams', array() );
1011 $content = $this->getPreloadedContent( $preload, $params );
1013 // For existing pages, get text based on "undo" or section parameters.
1015 if ( $this->section
!= '' ) {
1016 // Get section edit text (returns $def_text for invalid sections)
1017 $orig = $this->getOriginalContent( $wgUser );
1018 $content = $orig ?
$orig->getSection( $this->section
) : null;
1021 $content = $def_content;
1024 $undoafter = $wgRequest->getInt( 'undoafter' );
1025 $undo = $wgRequest->getInt( 'undo' );
1027 if ( $undo > 0 && $undoafter > 0 ) {
1029 $undorev = Revision
::newFromId( $undo );
1030 $oldrev = Revision
::newFromId( $undoafter );
1032 # Sanity check, make sure it's the right page,
1033 # the revisions exist and they were not deleted.
1034 # Otherwise, $content will be left as-is.
1035 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1036 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1037 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
1039 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
1041 if ( $content === false ) {
1042 # Warn the user that something went wrong
1043 $undoMsg = 'failure';
1045 $oldContent = $this->mArticle
->getPage()->getContent( Revision
::RAW
);
1046 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
1047 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
1049 if ( $newContent->equals( $oldContent ) ) {
1050 # Tell the user that the undo results in no change,
1051 # i.e. the revisions were already undone.
1052 $undoMsg = 'nochange';
1055 # Inform the user of our success and set an automatic edit summary
1056 $undoMsg = 'success';
1058 # If we just undid one rev, use an autosummary
1059 $firstrev = $oldrev->getNext();
1060 if ( $firstrev && $firstrev->getId() == $undo ) {
1061 $userText = $undorev->getUserText();
1062 if ( $userText === '' ) {
1063 $undoSummary = wfMessage(
1064 'undo-summary-username-hidden',
1066 )->inContentLanguage()->text();
1068 $undoSummary = wfMessage(
1072 )->inContentLanguage()->text();
1074 if ( $this->summary
=== '' ) {
1075 $this->summary
= $undoSummary;
1077 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
1078 ->inContentLanguage()->text() . $this->summary
;
1080 $this->undidRev
= $undo;
1082 $this->formtype
= 'diff';
1086 // Failed basic sanity checks.
1087 // Older revisions may have been removed since the link
1088 // was created, or we may simply have got bogus input.
1092 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1093 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1094 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
1095 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1098 if ( $content === false ) {
1099 $content = $this->getOriginalContent( $wgUser );
1108 * Get the content of the wanted revision, without section extraction.
1110 * The result of this function can be used to compare user's input with
1111 * section replaced in its context (using WikiPage::replaceSection())
1112 * to the original text of the edit.
1114 * This differs from Article::getContent() that when a missing revision is
1115 * encountered the result will be null and not the
1116 * 'missing-revision' message.
1119 * @param User $user The user to get the revision for
1120 * @return Content|null
1122 private function getOriginalContent( User
$user ) {
1123 if ( $this->section
== 'new' ) {
1124 return $this->getCurrentContent();
1126 $revision = $this->mArticle
->getRevisionFetched();
1127 if ( $revision === null ) {
1128 if ( !$this->contentModel
) {
1129 $this->contentModel
= $this->getTitle()->getContentModel();
1131 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1133 return $handler->makeEmptyContent();
1135 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1140 * Get the edit's parent revision ID
1142 * The "parent" revision is the ancestor that should be recorded in this
1143 * page's revision history. It is either the revision ID of the in-memory
1144 * article content, or in the case of a 3-way merge in order to rebase
1145 * across a recoverable edit conflict, the ID of the newer revision to
1146 * which we have rebased this page.
1149 * @return int Revision ID
1151 public function getParentRevId() {
1152 if ( $this->parentRevId
) {
1153 return $this->parentRevId
;
1155 return $this->mArticle
->getRevIdFetched();
1160 * Get the current content of the page. This is basically similar to
1161 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1162 * content object is returned instead of null.
1167 protected function getCurrentContent() {
1168 $rev = $this->mArticle
->getRevision();
1169 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1171 if ( $content === false ||
$content === null ) {
1172 if ( !$this->contentModel
) {
1173 $this->contentModel
= $this->getTitle()->getContentModel();
1175 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1177 return $handler->makeEmptyContent();
1179 # nasty side-effect, but needed for consistency
1180 $this->contentModel
= $rev->getContentModel();
1181 $this->contentFormat
= $rev->getContentFormat();
1188 * Use this method before edit() to preload some content into the edit box
1190 * @param Content $content
1194 public function setPreloadedContent( Content
$content ) {
1195 $this->mPreloadContent
= $content;
1199 * Get the contents to be preloaded into the box, either set by
1200 * an earlier setPreloadText() or by loading the given page.
1202 * @param string $preload Representing the title to preload from.
1203 * @param array $params Parameters to use (interface-message style) in the preloaded text
1209 protected function getPreloadedContent( $preload, $params = array() ) {
1212 if ( !empty( $this->mPreloadContent
) ) {
1213 return $this->mPreloadContent
;
1216 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1218 if ( $preload === '' ) {
1219 return $handler->makeEmptyContent();
1222 $title = Title
::newFromText( $preload );
1223 # Check for existence to avoid getting MediaWiki:Noarticletext
1224 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1225 //TODO: somehow show a warning to the user!
1226 return $handler->makeEmptyContent();
1229 $page = WikiPage
::factory( $title );
1230 if ( $page->isRedirect() ) {
1231 $title = $page->getRedirectTarget();
1233 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1234 //TODO: somehow show a warning to the user!
1235 return $handler->makeEmptyContent();
1237 $page = WikiPage
::factory( $title );
1240 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1241 $content = $page->getContent( Revision
::RAW
);
1244 //TODO: somehow show a warning to the user!
1245 return $handler->makeEmptyContent();
1248 if ( $content->getModel() !== $handler->getModelID() ) {
1249 $converted = $content->convert( $handler->getModelID() );
1251 if ( !$converted ) {
1252 //TODO: somehow show a warning to the user!
1253 wfDebug( "Attempt to preload incompatible content: "
1254 . "can't convert " . $content->getModel()
1255 . " to " . $handler->getModelID() );
1257 return $handler->makeEmptyContent();
1260 $content = $converted;
1263 return $content->preloadTransform( $title, $parserOptions, $params );
1267 * Make sure the form isn't faking a user's credentials.
1269 * @param WebRequest $request
1273 function tokenOk( &$request ) {
1275 $token = $request->getVal( 'wpEditToken' );
1276 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1277 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1278 return $this->mTokenOk
;
1282 * Sets post-edit cookie indicating the user just saved a particular revision.
1284 * This uses a temporary cookie for each revision ID so separate saves will never
1285 * interfere with each other.
1287 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1288 * the redirect. It must be clearable by JavaScript code, so it must not be
1289 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1292 * If the variable were set on the server, it would be cached, which is unwanted
1293 * since the post-edit state should only apply to the load right after the save.
1295 * @param int $statusValue The status value (to check for new article status)
1297 protected function setPostEditCookie( $statusValue ) {
1298 $revisionId = $this->mArticle
->getLatest();
1299 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1302 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1304 } elseif ( $this->oldid
) {
1308 $response = RequestContext
::getMain()->getRequest()->response();
1309 $response->setcookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
, array(
1310 'httpOnly' => false,
1315 * Attempt submission
1316 * @param array $resultDetails See docs for $result in internalAttemptSave
1317 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1318 * @return Status The resulting status object.
1320 public function attemptSave( &$resultDetails = false ) {
1323 # Allow bots to exempt some edits from bot flagging
1324 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1325 $status = $this->internalAttemptSave( $resultDetails, $bot );
1327 Hooks
::run( 'EditPage::attemptSave:after', array( $this, $status, $resultDetails ) );
1333 * Handle status, such as after attempt save
1335 * @param Status $status
1336 * @param array|bool $resultDetails
1338 * @throws ErrorPageError
1339 * @return bool False, if output is done, true if rest of the form should be displayed
1341 private function handleStatus( Status
$status, $resultDetails ) {
1342 global $wgUser, $wgOut;
1345 * @todo FIXME: once the interface for internalAttemptSave() is made
1346 * nicer, this should use the message in $status
1348 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1349 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1351 $this->didSave
= true;
1352 if ( !$resultDetails['nullEdit'] ) {
1353 $this->setPostEditCookie( $status->value
);
1357 switch ( $status->value
) {
1358 case self
::AS_HOOK_ERROR_EXPECTED
:
1359 case self
::AS_CONTENT_TOO_BIG
:
1360 case self
::AS_ARTICLE_WAS_DELETED
:
1361 case self
::AS_CONFLICT_DETECTED
:
1362 case self
::AS_SUMMARY_NEEDED
:
1363 case self
::AS_TEXTBOX_EMPTY
:
1364 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1366 case self
::AS_BLANK_ARTICLE
:
1367 case self
::AS_SELF_REDIRECT
:
1370 case self
::AS_HOOK_ERROR
:
1373 case self
::AS_PARSE_ERROR
:
1374 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1377 case self
::AS_SUCCESS_NEW_ARTICLE
:
1378 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1379 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1380 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1383 case self
::AS_SUCCESS_UPDATE
:
1385 $sectionanchor = $resultDetails['sectionanchor'];
1387 // Give extensions a chance to modify URL query on update
1389 'ArticleUpdateBeforeRedirect',
1390 array( $this->mArticle
, &$sectionanchor, &$extraQuery )
1393 if ( $resultDetails['redirect'] ) {
1394 if ( $extraQuery == '' ) {
1395 $extraQuery = 'redirect=no';
1397 $extraQuery = 'redirect=no&' . $extraQuery;
1400 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1403 case self
::AS_SPAM_ERROR
:
1404 $this->spamPageWithContent( $resultDetails['spam'] );
1407 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1408 throw new UserBlockedError( $wgUser->getBlock() );
1410 case self
::AS_IMAGE_REDIRECT_ANON
:
1411 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1412 throw new PermissionsError( 'upload' );
1414 case self
::AS_READ_ONLY_PAGE_ANON
:
1415 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1416 throw new PermissionsError( 'edit' );
1418 case self
::AS_READ_ONLY_PAGE
:
1419 throw new ReadOnlyError
;
1421 case self
::AS_RATE_LIMITED
:
1422 throw new ThrottledError();
1424 case self
::AS_NO_CREATE_PERMISSION
:
1425 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1426 throw new PermissionsError( $permission );
1428 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1429 throw new PermissionsError( 'editcontentmodel' );
1432 // We don't recognize $status->value. The only way that can happen
1433 // is if an extension hook aborted from inside ArticleSave.
1434 // Render the status object into $this->hookError
1435 // FIXME this sucks, we should just use the Status object throughout
1436 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1443 * Run hooks that can filter edits just before they get saved.
1445 * @param Content $content The Content to filter.
1446 * @param Status $status For reporting the outcome to the caller
1447 * @param User $user The user performing the edit
1451 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1452 // Run old style post-section-merge edit filter
1453 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1454 array( $this, $content, &$this->hookError
, $this->summary
) )
1456 # Error messages etc. could be handled within the hook...
1457 $status->fatal( 'hookaborted' );
1458 $status->value
= self
::AS_HOOK_ERROR
;
1460 } elseif ( $this->hookError
!= '' ) {
1461 # ...or the hook could be expecting us to produce an error
1462 $status->fatal( 'hookaborted' );
1463 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1467 // Run new style post-section-merge edit filter
1468 if ( !Hooks
::run( 'EditFilterMergedContent',
1469 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1470 $user, $this->minoredit
) )
1472 # Error messages etc. could be handled within the hook...
1473 if ( $status->isGood() ) {
1474 $status->fatal( 'hookaborted' );
1475 // Not setting $this->hookError here is a hack to allow the hook
1476 // to cause a return to the edit page without $this->hookError
1477 // being set. This is used by ConfirmEdit to display a captcha
1478 // without any error message cruft.
1480 $this->hookError
= $status->getWikiText();
1482 // Use the existing $status->value if the hook set it
1483 if ( !$status->value
) {
1484 $status->value
= self
::AS_HOOK_ERROR
;
1487 } elseif ( !$status->isOK() ) {
1488 # ...or the hook could be expecting us to produce an error
1489 // FIXME this sucks, we should just use the Status object throughout
1490 $this->hookError
= $status->getWikiText();
1491 $status->fatal( 'hookaborted' );
1492 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1500 * Return the summary to be used for a new section.
1502 * @param string $sectionanchor Set to the section anchor text
1505 private function newSectionSummary( &$sectionanchor = null ) {
1508 if ( $this->sectiontitle
!== '' ) {
1509 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1510 // If no edit summary was specified, create one automatically from the section
1511 // title and have it link to the new section. Otherwise, respect the summary as
1513 if ( $this->summary
=== '' ) {
1514 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1515 return wfMessage( 'newsectionsummary' )
1516 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1518 } elseif ( $this->summary
!== '' ) {
1519 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1520 # This is a new section, so create a link to the new section
1521 # in the revision summary.
1522 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1523 return wfMessage( 'newsectionsummary' )
1524 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1526 return $this->summary
;
1530 * Attempt submission (no UI)
1532 * @param array $result Array to add statuses to, currently with the
1534 * - spam (string): Spam string from content if any spam is detected by
1536 * - sectionanchor (string): Section anchor for a section save.
1537 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1539 * - redirect (bool): Set if doEditContent is OK. True if resulting
1540 * revision is a redirect.
1541 * @param bool $bot True if edit is being made under the bot right.
1543 * @return Status Status object, possibly with a message, but always with
1544 * one of the AS_* constants in $status->value,
1546 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1547 * various error display idiosyncrasies. There are also lots of cases
1548 * where error metadata is set in the object and retrieved later instead
1549 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1550 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1553 function internalAttemptSave( &$result, $bot = false ) {
1554 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1556 $status = Status
::newGood();
1558 if ( !Hooks
::run( 'EditPage::attemptSave', array( $this ) ) ) {
1559 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1560 $status->fatal( 'hookaborted' );
1561 $status->value
= self
::AS_HOOK_ERROR
;
1565 $spam = $wgRequest->getText( 'wpAntispam' );
1566 if ( $spam !== '' ) {
1569 $wgUser->getName() .
1571 $this->mTitle
->getPrefixedText() .
1572 '" submitted bogus field "' .
1576 $status->fatal( 'spamprotectionmatch', false );
1577 $status->value
= self
::AS_SPAM_ERROR
;
1582 # Construct Content object
1583 $textbox_content = $this->toEditContent( $this->textbox1
);
1584 } catch ( MWContentSerializationException
$ex ) {
1586 'content-failed-to-parse',
1587 $this->contentModel
,
1588 $this->contentFormat
,
1591 $status->value
= self
::AS_PARSE_ERROR
;
1595 # Check image redirect
1596 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1597 $textbox_content->isRedirect() &&
1598 !$wgUser->isAllowed( 'upload' )
1600 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1601 $status->setResult( false, $code );
1607 $match = self
::matchSummarySpamRegex( $this->summary
);
1608 if ( $match === false && $this->section
== 'new' ) {
1609 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1610 # regular summaries, it is added to the actual wikitext.
1611 if ( $this->sectiontitle
!== '' ) {
1612 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1613 $match = self
::matchSpamRegex( $this->sectiontitle
);
1615 # This branch is taken when the "Add Topic" user interface is used, or the API
1616 # is used with the 'summary' parameter.
1617 $match = self
::matchSpamRegex( $this->summary
);
1620 if ( $match === false ) {
1621 $match = self
::matchSpamRegex( $this->textbox1
);
1623 if ( $match !== false ) {
1624 $result['spam'] = $match;
1625 $ip = $wgRequest->getIP();
1626 $pdbk = $this->mTitle
->getPrefixedDBkey();
1627 $match = str_replace( "\n", '', $match );
1628 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1629 $status->fatal( 'spamprotectionmatch', $match );
1630 $status->value
= self
::AS_SPAM_ERROR
;
1635 array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) )
1637 # Error messages etc. could be handled within the hook...
1638 $status->fatal( 'hookaborted' );
1639 $status->value
= self
::AS_HOOK_ERROR
;
1641 } elseif ( $this->hookError
!= '' ) {
1642 # ...or the hook could be expecting us to produce an error
1643 $status->fatal( 'hookaborted' );
1644 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1648 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1649 // Auto-block user's IP if the account was "hard" blocked
1650 $wgUser->spreadAnyEditBlock();
1651 # Check block state against master, thus 'false'.
1652 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1656 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1657 if ( $this->kblength
> $wgMaxArticleSize ) {
1658 // Error will be displayed by showEditForm()
1659 $this->tooBig
= true;
1660 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1664 if ( !$wgUser->isAllowed( 'edit' ) ) {
1665 if ( $wgUser->isAnon() ) {
1666 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1669 $status->fatal( 'readonlytext' );
1670 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1675 if ( $this->contentModel
!== $this->mTitle
->getContentModel()
1676 && !$wgUser->isAllowed( 'editcontentmodel' )
1678 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1682 if ( $this->changeTags
) {
1683 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1684 $this->changeTags
, $wgUser );
1685 if ( !$changeTagsStatus->isOK() ) {
1686 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1687 return $changeTagsStatus;
1691 if ( wfReadOnly() ) {
1692 $status->fatal( 'readonlytext' );
1693 $status->value
= self
::AS_READ_ONLY_PAGE
;
1696 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1697 $status->fatal( 'actionthrottledtext' );
1698 $status->value
= self
::AS_RATE_LIMITED
;
1702 # If the article has been deleted while editing, don't save it without
1704 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1705 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1709 # Load the page data from the master. If anything changes in the meantime,
1710 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1711 $this->mArticle
->loadPageData( 'fromdbmaster' );
1712 $new = !$this->mArticle
->exists();
1715 // Late check for create permission, just in case *PARANOIA*
1716 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1717 $status->fatal( 'nocreatetext' );
1718 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1719 wfDebug( __METHOD__
. ": no create permission\n" );
1723 // Don't save a new page if it's blank or if it's a MediaWiki:
1724 // message with content equivalent to default (allow empty pages
1725 // in this case to disable messages, see bug 50124)
1726 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1727 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1728 $defaultText = $defaultMessageText;
1733 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1734 $this->blankArticle
= true;
1735 $status->fatal( 'blankarticle' );
1736 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1740 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1744 $content = $textbox_content;
1746 $result['sectionanchor'] = '';
1747 if ( $this->section
== 'new' ) {
1748 if ( $this->sectiontitle
!== '' ) {
1749 // Insert the section title above the content.
1750 $content = $content->addSectionHeader( $this->sectiontitle
);
1751 } elseif ( $this->summary
!== '' ) {
1752 // Insert the section title above the content.
1753 $content = $content->addSectionHeader( $this->summary
);
1755 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1758 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1762 # Article exists. Check for edit conflict.
1764 $this->mArticle
->clear(); # Force reload of dates, etc.
1765 $timestamp = $this->mArticle
->getTimestamp();
1767 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1769 if ( $timestamp != $this->edittime
) {
1770 $this->isConflict
= true;
1771 if ( $this->section
== 'new' ) {
1772 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1773 $this->mArticle
->getComment() == $this->newSectionSummary()
1775 // Probably a duplicate submission of a new comment.
1776 // This can happen when squid resends a request after
1777 // a timeout but the first one actually went through.
1779 . ": duplicate new section submission; trigger edit conflict!\n" );
1781 // New comment; suppress conflict.
1782 $this->isConflict
= false;
1783 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1785 } elseif ( $this->section
== ''
1786 && Revision
::userWasLastToEdit(
1787 DB_MASTER
, $this->mTitle
->getArticleID(),
1788 $wgUser->getId(), $this->edittime
1791 # Suppress edit conflict with self, except for section edits where merging is required.
1792 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1793 $this->isConflict
= false;
1797 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1798 if ( $this->sectiontitle
!== '' ) {
1799 $sectionTitle = $this->sectiontitle
;
1801 $sectionTitle = $this->summary
;
1806 if ( $this->isConflict
) {
1808 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1809 . " (article time '{$timestamp}')\n" );
1811 $content = $this->mArticle
->replaceSectionContent(
1818 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1819 $content = $this->mArticle
->replaceSectionContent(
1826 if ( is_null( $content ) ) {
1827 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1828 $this->isConflict
= true;
1829 $content = $textbox_content; // do not try to merge here!
1830 } elseif ( $this->isConflict
) {
1832 if ( $this->mergeChangesIntoContent( $content ) ) {
1833 // Successful merge! Maybe we should tell the user the good news?
1834 $this->isConflict
= false;
1835 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1837 $this->section
= '';
1838 $this->textbox1
= ContentHandler
::getContentText( $content );
1839 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1843 if ( $this->isConflict
) {
1844 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1848 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1852 if ( $this->section
== 'new' ) {
1853 // Handle the user preference to force summaries here
1854 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1855 $this->missingSummary
= true;
1856 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1857 $status->value
= self
::AS_SUMMARY_NEEDED
;
1861 // Do not allow the user to post an empty comment
1862 if ( $this->textbox1
== '' ) {
1863 $this->missingComment
= true;
1864 $status->fatal( 'missingcommenttext' );
1865 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1868 } elseif ( !$this->allowBlankSummary
1869 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1870 && !$content->isRedirect()
1871 && md5( $this->summary
) == $this->autoSumm
1873 $this->missingSummary
= true;
1874 $status->fatal( 'missingsummary' );
1875 $status->value
= self
::AS_SUMMARY_NEEDED
;
1880 $sectionanchor = '';
1881 if ( $this->section
== 'new' ) {
1882 $this->summary
= $this->newSectionSummary( $sectionanchor );
1883 } elseif ( $this->section
!= '' ) {
1884 # Try to get a section anchor from the section source, redirect
1885 # to edited section if header found.
1886 # XXX: Might be better to integrate this into Article::replaceSection
1887 # for duplicate heading checking and maybe parsing.
1888 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1889 # We can't deal with anchors, includes, html etc in the header for now,
1890 # headline would need to be parsed to improve this.
1891 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1892 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1895 $result['sectionanchor'] = $sectionanchor;
1897 // Save errors may fall down to the edit form, but we've now
1898 // merged the section into full text. Clear the section field
1899 // so that later submission of conflict forms won't try to
1900 // replace that into a duplicated mess.
1901 $this->textbox1
= $this->toEditText( $content );
1902 $this->section
= '';
1904 $status->value
= self
::AS_SUCCESS_UPDATE
;
1907 if ( !$this->allowSelfRedirect
1908 && $content->isRedirect()
1909 && $content->getRedirectTarget()->equals( $this->getTitle() )
1911 // If the page already redirects to itself, don't warn.
1912 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
1913 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
1914 $this->selfRedirect
= true;
1915 $status->fatal( 'selfredirect' );
1916 $status->value
= self
::AS_SELF_REDIRECT
;
1921 // Check for length errors again now that the section is merged in
1922 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1923 if ( $this->kblength
> $wgMaxArticleSize ) {
1924 $this->tooBig
= true;
1925 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1929 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1930 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1931 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1932 ( $bot ? EDIT_FORCE_BOT
: 0 );
1934 $doEditStatus = $this->mArticle
->doEditContent(
1940 $content->getDefaultFormat()
1943 if ( !$doEditStatus->isOK() ) {
1944 // Failure from doEdit()
1945 // Show the edit conflict page for certain recognized errors from doEdit(),
1946 // but don't show it for errors from extension hooks
1947 $errors = $doEditStatus->getErrorsArray();
1948 if ( in_array( $errors[0][0],
1949 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1951 $this->isConflict
= true;
1952 // Destroys data doEdit() put in $status->value but who cares
1953 $doEditStatus->value
= self
::AS_END
;
1955 return $doEditStatus;
1958 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1959 if ( $result['nullEdit'] ) {
1960 // We don't know if it was a null edit until now, so increment here
1961 $wgUser->pingLimiter( 'linkpurge' );
1963 $result['redirect'] = $content->isRedirect();
1965 $this->updateWatchlist();
1967 if ( $this->changeTags
&& isset( $doEditStatus->value
['revision'] ) ) {
1968 // If a revision was created, apply any change tags that were requested
1969 ChangeTags
::addTags(
1971 isset( $doEditStatus->value
['rc'] ) ?
$doEditStatus->value
['rc']->mAttribs
['rc_id'] : null,
1972 $doEditStatus->value
['revision']->getId()
1980 * Register the change of watch status
1982 protected function updateWatchlist() {
1985 if ( $wgUser->isLoggedIn()
1986 && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
, WatchedItem
::IGNORE_USER_RIGHTS
)
1988 $fname = __METHOD__
;
1989 $title = $this->mTitle
;
1990 $watch = $this->watchthis
;
1992 // Do this in its own transaction to reduce contention...
1993 $dbw = wfGetDB( DB_MASTER
);
1994 $dbw->onTransactionIdle( function () use ( $dbw, $title, $watch, $wgUser, $fname ) {
1995 WatchAction
::doWatchOrUnwatch( $watch, $title, $wgUser );
2001 * Attempts to do 3-way merge of edit content with a base revision
2002 * and current content, in case of edit conflict, in whichever way appropriate
2003 * for the content type.
2007 * @param Content $editContent
2011 private function mergeChangesIntoContent( &$editContent ) {
2013 $db = wfGetDB( DB_MASTER
);
2015 // This is the revision the editor started from
2016 $baseRevision = $this->getBaseRevision();
2017 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2019 if ( is_null( $baseContent ) ) {
2023 // The current state, we want to merge updates into it
2024 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2025 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2027 if ( is_null( $currentContent ) ) {
2031 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2033 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2036 $editContent = $result;
2037 // Update parentRevId to what we just merged.
2038 $this->parentRevId
= $currentRevision->getId();
2048 function getBaseRevision() {
2049 if ( !$this->mBaseRevision
) {
2050 $db = wfGetDB( DB_MASTER
);
2051 $this->mBaseRevision
= Revision
::loadFromTimestamp(
2052 $db, $this->mTitle
, $this->edittime
);
2054 return $this->mBaseRevision
;
2058 * Check given input text against $wgSpamRegex, and return the text of the first match.
2060 * @param string $text
2062 * @return string|bool Matching string or false
2064 public static function matchSpamRegex( $text ) {
2065 global $wgSpamRegex;
2066 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2067 $regexes = (array)$wgSpamRegex;
2068 return self
::matchSpamRegexInternal( $text, $regexes );
2072 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2074 * @param string $text
2076 * @return string|bool Matching string or false
2078 public static function matchSummarySpamRegex( $text ) {
2079 global $wgSummarySpamRegex;
2080 $regexes = (array)$wgSummarySpamRegex;
2081 return self
::matchSpamRegexInternal( $text, $regexes );
2085 * @param string $text
2086 * @param array $regexes
2087 * @return bool|string
2089 protected static function matchSpamRegexInternal( $text, $regexes ) {
2090 foreach ( $regexes as $regex ) {
2092 if ( preg_match( $regex, $text, $matches ) ) {
2099 function setHeaders() {
2100 global $wgOut, $wgUser, $wgAjaxEditStash;
2102 $wgOut->addModules( 'mediawiki.action.edit' );
2103 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2105 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2106 // The addition of default buttons is handled by getEditToolbar() which
2107 // has its own dependency on this module. The call here ensures the module
2108 // is loaded in time (it has position "top") for other modules to register
2109 // buttons (e.g. extensions, gadgets, user scripts).
2110 $wgOut->addModules( 'mediawiki.toolbar' );
2113 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2114 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2117 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2118 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2121 if ( $wgAjaxEditStash ) {
2122 $wgOut->addModules( 'mediawiki.action.edit.stash' );
2125 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2127 # Enabled article-related sidebar, toplinks, etc.
2128 $wgOut->setArticleRelated( true );
2130 $contextTitle = $this->getContextTitle();
2131 if ( $this->isConflict
) {
2132 $msg = 'editconflict';
2133 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2134 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2136 $msg = $contextTitle->exists()
2137 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2138 && $contextTitle->getDefaultMessageText() !== false
2144 # Use the title defined by DISPLAYTITLE magic word when present
2145 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2146 if ( $displayTitle === false ) {
2147 $displayTitle = $contextTitle->getPrefixedText();
2149 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2150 # Transmit the name of the message to JavaScript for live preview
2151 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2152 $wgOut->addJsConfigVars( 'wgEditMessage', $msg );
2156 * Show all applicable editing introductions
2158 protected function showIntro() {
2159 global $wgOut, $wgUser;
2160 if ( $this->suppressIntro
) {
2164 $namespace = $this->mTitle
->getNamespace();
2166 if ( $namespace == NS_MEDIAWIKI
) {
2167 # Show a warning if editing an interface message
2168 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2169 # If this is a default message (but not css or js),
2170 # show a hint that it is translatable on translatewiki.net
2171 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2172 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2174 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2175 if ( $defaultMessageText !== false ) {
2176 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2177 'translateinterface' );
2180 } elseif ( $namespace == NS_FILE
) {
2181 # Show a hint to shared repo
2182 $file = wfFindFile( $this->mTitle
);
2183 if ( $file && !$file->isLocal() ) {
2184 $descUrl = $file->getDescriptionUrl();
2185 # there must be a description url to show a hint to shared repo
2187 if ( !$this->mTitle
->exists() ) {
2188 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2189 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2192 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2193 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2200 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2201 # Show log extract when the user is currently blocked
2202 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2203 $parts = explode( '/', $this->mTitle
->getText(), 2 );
2204 $username = $parts[0];
2205 $user = User
::newFromName( $username, false /* allow IP users*/ );
2206 $ip = User
::isIP( $username );
2207 $block = Block
::newFromTarget( $user, $user );
2208 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2209 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2210 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2211 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2212 # Show log extract if the user is currently blocked
2213 LogEventsList
::showLogExtract(
2216 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2220 'showIfEmpty' => false,
2222 'blocked-notice-logextract',
2223 $user->getName() # Support GENDER in notice
2229 # Try to add a custom edit intro, or use the standard one if this is not possible.
2230 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2231 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2232 wfMessage( 'helppage' )->inContentLanguage()->text()
2234 if ( $wgUser->isLoggedIn() ) {
2235 $wgOut->wrapWikiMsg(
2236 // Suppress the external link icon, consider the help url an internal one
2237 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2244 $wgOut->wrapWikiMsg(
2245 // Suppress the external link icon, consider the help url an internal one
2246 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2248 'newarticletextanon',
2254 # Give a notice if the user is editing a deleted/moved page...
2255 if ( !$this->mTitle
->exists() ) {
2256 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
2260 'conds' => array( "log_action != 'revision'" ),
2261 'showIfEmpty' => false,
2262 'msgKey' => array( 'recreate-moveddeleted-warn' )
2269 * Attempt to show a custom editing introduction, if supplied
2273 protected function showCustomIntro() {
2274 if ( $this->editintro
) {
2275 $title = Title
::newFromText( $this->editintro
);
2276 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2278 // Added using template syntax, to take <noinclude>'s into account.
2279 $wgOut->addWikiTextTitleTidy(
2280 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2290 * Gets an editable textual representation of $content.
2291 * The textual representation can be turned by into a Content object by the
2292 * toEditContent() method.
2294 * If $content is null or false or a string, $content is returned unchanged.
2296 * If the given Content object is not of a type that can be edited using
2297 * the text base EditPage, an exception will be raised. Set
2298 * $this->allowNonTextContent to true to allow editing of non-textual
2301 * @param Content|null|bool|string $content
2302 * @return string The editable text form of the content.
2304 * @throws MWException If $content is not an instance of TextContent and
2305 * $this->allowNonTextContent is not true.
2307 protected function toEditText( $content ) {
2308 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2312 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2313 throw new MWException( 'This content model is not supported: '
2314 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2317 return $content->serialize( $this->contentFormat
);
2321 * Turns the given text into a Content object by unserializing it.
2323 * If the resulting Content object is not of a type that can be edited using
2324 * the text base EditPage, an exception will be raised. Set
2325 * $this->allowNonTextContent to true to allow editing of non-textual
2328 * @param string|null|bool $text Text to unserialize
2329 * @return Content The content object created from $text. If $text was false
2330 * or null, false resp. null will be returned instead.
2332 * @throws MWException If unserializing the text results in a Content
2333 * object that is not an instance of TextContent and
2334 * $this->allowNonTextContent is not true.
2336 protected function toEditContent( $text ) {
2337 if ( $text === false ||
$text === null ) {
2341 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2342 $this->contentModel
, $this->contentFormat
);
2344 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2345 throw new MWException( 'This content model is not supported: '
2346 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2353 * Send the edit form and related headers to $wgOut
2354 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2355 * during form output near the top, for captchas and the like.
2357 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2358 * use the EditPage::showEditForm:fields hook instead.
2360 function showEditForm( $formCallback = null ) {
2361 global $wgOut, $wgUser;
2363 # need to parse the preview early so that we know which templates are used,
2364 # otherwise users with "show preview after edit box" will get a blank list
2365 # we parse this near the beginning so that setHeaders can do the title
2366 # setting work instead of leaving it in getPreviewText
2367 $previewOutput = '';
2368 if ( $this->formtype
== 'preview' ) {
2369 $previewOutput = $this->getPreviewText();
2372 Hooks
::run( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2374 $this->setHeaders();
2376 if ( $this->showHeader() === false ) {
2380 $wgOut->addHTML( $this->editFormPageTop
);
2382 if ( $wgUser->getOption( 'previewontop' ) ) {
2383 $this->displayPreviewArea( $previewOutput, true );
2386 $wgOut->addHTML( $this->editFormTextTop
);
2388 $showToolbar = true;
2389 if ( $this->wasDeletedSinceLastEdit() ) {
2390 if ( $this->formtype
== 'save' ) {
2391 // Hide the toolbar and edit area, user can click preview to get it back
2392 // Add an confirmation checkbox and explanation.
2393 $showToolbar = false;
2395 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2396 'deletedwhileediting' );
2400 // @todo add EditForm plugin interface and use it here!
2401 // search for textarea1 and textares2, and allow EditForm to override all uses.
2402 $wgOut->addHTML( Html
::openElement(
2405 'id' => self
::EDITFORM_ID
,
2406 'name' => self
::EDITFORM_ID
,
2408 'action' => $this->getActionURL( $this->getContextTitle() ),
2409 'enctype' => 'multipart/form-data'
2413 if ( is_callable( $formCallback ) ) {
2414 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2415 call_user_func_array( $formCallback, array( &$wgOut ) );
2418 // Add an empty field to trip up spambots
2420 Xml
::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2423 array( 'for' => 'wpAntiSpam' ),
2424 wfMessage( 'simpleantispam-label' )->parse()
2430 'name' => 'wpAntispam',
2431 'id' => 'wpAntispam',
2435 . Xml
::closeElement( 'div' )
2438 Hooks
::run( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2440 // Put these up at the top to ensure they aren't lost on early form submission
2441 $this->showFormBeforeText();
2443 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2444 $username = $this->lastDelete
->user_name
;
2445 $comment = $this->lastDelete
->log_comment
;
2447 // It is better to not parse the comment at all than to have templates expanded in the middle
2448 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2449 $key = $comment === ''
2450 ?
'confirmrecreate-noreason'
2451 : 'confirmrecreate';
2453 '<div class="mw-confirm-recreate">' .
2454 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2455 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2456 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2462 # When the summary is hidden, also hide them on preview/show changes
2463 if ( $this->nosummary
) {
2464 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2467 # If a blank edit summary was previously provided, and the appropriate
2468 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2469 # user being bounced back more than once in the event that a summary
2472 # For a bit more sophisticated detection of blank summaries, hash the
2473 # automatic one and pass that in the hidden field wpAutoSummary.
2474 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2475 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2478 if ( $this->undidRev
) {
2479 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2482 if ( $this->selfRedirect
) {
2483 $wgOut->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2486 if ( $this->hasPresetSummary
) {
2487 // If a summary has been preset using &summary= we don't want to prompt for
2488 // a different summary. Only prompt for a summary if the summary is blanked.
2490 $this->autoSumm
= md5( '' );
2493 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2494 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2496 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2497 $wgOut->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2499 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2500 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2502 if ( $this->section
== 'new' ) {
2503 $this->showSummaryInput( true, $this->summary
);
2504 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2507 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2509 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2510 $wgOut->addHTML( EditPage
::getEditToolbar() );
2513 if ( $this->blankArticle
) {
2514 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2517 if ( $this->isConflict
) {
2518 // In an edit conflict bypass the overridable content form method
2519 // and fallback to the raw wpTextbox1 since editconflicts can't be
2520 // resolved between page source edits and custom ui edits using the
2522 $this->textbox2
= $this->textbox1
;
2524 $content = $this->getCurrentContent();
2525 $this->textbox1
= $this->toEditText( $content );
2527 $this->showTextbox1();
2529 $this->showContentForm();
2532 $wgOut->addHTML( $this->editFormTextAfterContent
);
2534 $this->showStandardInputs();
2536 $this->showFormAfterText();
2538 $this->showTosSummary();
2540 $this->showEditTools();
2542 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2544 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2545 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2547 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2548 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2550 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'limitreport' ),
2551 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2553 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2555 if ( $this->isConflict
) {
2557 $this->showConflict();
2558 } catch ( MWContentSerializationException
$ex ) {
2559 // this can't really happen, but be nice if it does.
2561 'content-failed-to-parse',
2562 $this->contentModel
,
2563 $this->contentFormat
,
2566 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2570 // Marker for detecting truncated form data. This must be the last
2571 // parameter sent in order to be of use, so do not move me.
2572 $wgOut->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2573 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2575 if ( !$wgUser->getOption( 'previewontop' ) ) {
2576 $this->displayPreviewArea( $previewOutput, false );
2582 * Extract the section title from current section text, if any.
2584 * @param string $text
2585 * @return string|bool String or false
2587 public static function extractSectionTitle( $text ) {
2588 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2589 if ( !empty( $matches[2] ) ) {
2591 return $wgParser->stripSectionName( trim( $matches[2] ) );
2600 protected function showHeader() {
2601 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2602 global $wgAllowUserCss, $wgAllowUserJs;
2604 if ( $this->mTitle
->isTalkPage() ) {
2605 $wgOut->addWikiMsg( 'talkpagetext' );
2609 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
2610 if ( count( $editNotices ) ) {
2611 $wgOut->addHTML( implode( "\n", $editNotices ) );
2613 $msg = wfMessage( 'editnotice-notext' );
2614 if ( !$msg->isDisabled() ) {
2616 '<div class="mw-editnotice-notext">'
2617 . $msg->parseAsBlock()
2623 if ( $this->isConflict
) {
2624 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2625 $this->edittime
= $this->mArticle
->getTimestamp();
2627 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2628 // We use $this->section to much before this and getVal('wgSection') directly in other places
2629 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2630 // Someone is welcome to try refactoring though
2631 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2635 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2636 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2637 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2638 if ( $sectionTitle !== false ) {
2639 $this->summary
= "/* $sectionTitle */ ";
2644 if ( $this->missingComment
) {
2645 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2648 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2649 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2652 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2653 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2656 if ( $this->blankArticle
) {
2657 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2660 if ( $this->selfRedirect
) {
2661 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2664 if ( $this->hookError
!== '' ) {
2665 $wgOut->addWikiText( $this->hookError
);
2668 if ( !$this->checkUnicodeCompliantBrowser() ) {
2669 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2672 if ( $this->section
!= 'new' ) {
2673 $revision = $this->mArticle
->getRevisionFetched();
2675 // Let sysop know that this will make private content public if saved
2677 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2678 $wgOut->wrapWikiMsg(
2679 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2680 'rev-deleted-text-permission'
2682 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2683 $wgOut->wrapWikiMsg(
2684 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2685 'rev-deleted-text-view'
2689 if ( !$revision->isCurrent() ) {
2690 $this->mArticle
->setOldSubtitle( $revision->getId() );
2691 $wgOut->addWikiMsg( 'editingold' );
2693 } elseif ( $this->mTitle
->exists() ) {
2694 // Something went wrong
2696 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2697 array( 'missing-revision', $this->oldid
) );
2702 if ( wfReadOnly() ) {
2703 $wgOut->wrapWikiMsg(
2704 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2705 array( 'readonlywarning', wfReadOnlyReason() )
2707 } elseif ( $wgUser->isAnon() ) {
2708 if ( $this->formtype
!= 'preview' ) {
2709 $wgOut->wrapWikiMsg(
2710 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2711 array( 'anoneditwarning',
2713 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2715 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2718 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2719 'anonpreviewwarning'
2723 if ( $this->isCssJsSubpage
) {
2724 # Check the skin exists
2725 if ( $this->isWrongCaseCssJsPage
) {
2726 $wgOut->wrapWikiMsg(
2727 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2728 array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() )
2731 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
2732 if ( $this->formtype
!== 'preview' ) {
2733 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
2734 $wgOut->wrapWikiMsg(
2735 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2736 array( 'usercssyoucanpreview' )
2740 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
2741 $wgOut->wrapWikiMsg(
2742 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2743 array( 'userjsyoucanpreview' )
2751 if ( $this->mTitle
->isProtected( 'edit' ) &&
2752 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2754 # Is the title semi-protected?
2755 if ( $this->mTitle
->isSemiProtected() ) {
2756 $noticeMsg = 'semiprotectedpagewarning';
2758 # Then it must be protected based on static groups (regular)
2759 $noticeMsg = 'protectedpagewarning';
2761 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2762 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2764 if ( $this->mTitle
->isCascadeProtected() ) {
2765 # Is this page under cascading protection from some source pages?
2766 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2767 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2768 $cascadeSourcesCount = count( $cascadeSources );
2769 if ( $cascadeSourcesCount > 0 ) {
2770 # Explain, and list the titles responsible
2771 foreach ( $cascadeSources as $page ) {
2772 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2775 $notice .= '</div>';
2776 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2778 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2779 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2781 'showIfEmpty' => false,
2782 'msgKey' => array( 'titleprotectedwarning' ),
2783 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2786 if ( $this->kblength
=== false ) {
2787 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2790 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2791 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2794 $wgLang->formatNum( $this->kblength
),
2795 $wgLang->formatNum( $wgMaxArticleSize )
2799 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2800 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2803 $wgLang->formatSize( strlen( $this->textbox1
) ),
2804 strlen( $this->textbox1
)
2809 # Add header copyright warning
2810 $this->showHeaderCopyrightWarning();
2816 * Standard summary input and label (wgSummary), abstracted so EditPage
2817 * subclasses may reorganize the form.
2818 * Note that you do not need to worry about the label's for=, it will be
2819 * inferred by the id given to the input. You can remove them both by
2820 * passing array( 'id' => false ) to $userInputAttrs.
2822 * @param string $summary The value of the summary input
2823 * @param string $labelText The html to place inside the label
2824 * @param array $inputAttrs Array of attrs to use on the input
2825 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2827 * @return array An array in the format array( $label, $input )
2829 function getSummaryInput( $summary = "", $labelText = null,
2830 $inputAttrs = null, $spanLabelAttrs = null
2832 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2833 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2834 'id' => 'wpSummary',
2835 'maxlength' => '200',
2838 'spellcheck' => 'true',
2839 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2841 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2842 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2843 'id' => "wpSummaryLabel"
2850 $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null,
2853 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2856 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2858 return array( $label, $input );
2862 * @param bool $isSubjectPreview True if this is the section subject/title
2863 * up top, or false if this is the comment summary
2864 * down below the textarea
2865 * @param string $summary The text of the summary to display
2867 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2868 global $wgOut, $wgContLang;
2869 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2870 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2871 if ( $isSubjectPreview ) {
2872 if ( $this->nosummary
) {
2876 if ( !$this->mShowSummaryField
) {
2880 $summary = $wgContLang->recodeForEdit( $summary );
2881 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2882 list( $label, $input ) = $this->getSummaryInput(
2885 array( 'class' => $summaryClass ),
2888 $wgOut->addHTML( "{$label} {$input}" );
2892 * @param bool $isSubjectPreview True if this is the section subject/title
2893 * up top, or false if this is the comment summary
2894 * down below the textarea
2895 * @param string $summary The text of the summary to display
2898 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2899 // avoid spaces in preview, gets always trimmed on save
2900 $summary = trim( $summary );
2901 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2907 if ( $isSubjectPreview ) {
2908 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2909 ->inContentLanguage()->text();
2912 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2914 $summary = wfMessage( $message )->parse()
2915 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2916 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2919 protected function showFormBeforeText() {
2921 $section = htmlspecialchars( $this->section
);
2922 $wgOut->addHTML( <<<HTML
2923 <input type='hidden' value="{$section}" name="wpSection"/>
2924 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2925 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2926 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2930 if ( !$this->checkUnicodeCompliantBrowser() ) {
2931 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2935 protected function showFormAfterText() {
2936 global $wgOut, $wgUser;
2938 * To make it harder for someone to slip a user a page
2939 * which submits an edit form to the wiki without their
2940 * knowledge, a random token is associated with the login
2941 * session. If it's not passed back with the submission,
2942 * we won't save the page, or render user JavaScript and
2945 * For anon editors, who may not have a session, we just
2946 * include the constant suffix to prevent editing from
2947 * broken text-mangling proxies.
2949 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2953 * Subpage overridable method for printing the form for page content editing
2954 * By default this simply outputs wpTextbox1
2955 * Subclasses can override this to provide a custom UI for editing;
2956 * be it a form, or simply wpTextbox1 with a modified content that will be
2957 * reverse modified when extracted from the post data.
2958 * Note that this is basically the inverse for importContentFormData
2960 protected function showContentForm() {
2961 $this->showTextbox1();
2965 * Method to output wpTextbox1
2966 * The $textoverride method can be used by subclasses overriding showContentForm
2967 * to pass back to this method.
2969 * @param array $customAttribs Array of html attributes to use in the textarea
2970 * @param string $textoverride Optional text to override $this->textarea1 with
2972 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2973 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2974 $attribs = array( 'style' => 'display:none;' );
2976 $classes = array(); // Textarea CSS
2977 if ( $this->mTitle
->isProtected( 'edit' ) &&
2978 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2980 # Is the title semi-protected?
2981 if ( $this->mTitle
->isSemiProtected() ) {
2982 $classes[] = 'mw-textarea-sprotected';
2984 # Then it must be protected based on static groups (regular)
2985 $classes[] = 'mw-textarea-protected';
2987 # Is the title cascade-protected?
2988 if ( $this->mTitle
->isCascadeProtected() ) {
2989 $classes[] = 'mw-textarea-cprotected';
2993 $attribs = array( 'tabindex' => 1 );
2995 if ( is_array( $customAttribs ) ) {
2996 $attribs +
= $customAttribs;
2999 if ( count( $classes ) ) {
3000 if ( isset( $attribs['class'] ) ) {
3001 $classes[] = $attribs['class'];
3003 $attribs['class'] = implode( ' ', $classes );
3008 $textoverride !== null ?
$textoverride : $this->textbox1
,
3014 protected function showTextbox2() {
3015 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
3018 protected function showTextbox( $text, $name, $customAttribs = array() ) {
3019 global $wgOut, $wgUser;
3021 $wikitext = $this->safeUnicodeOutput( $text );
3022 if ( strval( $wikitext ) !== '' ) {
3023 // Ensure there's a newline at the end, otherwise adding lines
3025 // But don't add a newline if the ext is empty, or Firefox in XHTML
3026 // mode will show an extra newline. A bit annoying.
3030 $attribs = $customAttribs +
array(
3033 'cols' => $wgUser->getIntOption( 'cols' ),
3034 'rows' => $wgUser->getIntOption( 'rows' ),
3035 // Avoid PHP notices when appending preferences
3036 // (appending allows customAttribs['style'] to still work).
3040 $pageLang = $this->mTitle
->getPageLanguage();
3041 $attribs['lang'] = $pageLang->getHtmlCode();
3042 $attribs['dir'] = $pageLang->getDir();
3044 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3047 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3051 $classes[] = 'ontop';
3054 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3056 if ( $this->formtype
!= 'preview' ) {
3057 $attribs['style'] = 'display: none;';
3060 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
3062 if ( $this->formtype
== 'preview' ) {
3063 $this->showPreview( $previewOutput );
3065 // Empty content container for LivePreview
3066 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3067 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3068 'class' => 'mw-content-' . $pageViewLang->getDir() );
3069 $wgOut->addHTML( Html
::rawElement( 'div', $attribs ) );
3072 $wgOut->addHTML( '</div>' );
3074 if ( $this->formtype
== 'diff' ) {
3077 } catch ( MWContentSerializationException
$ex ) {
3079 'content-failed-to-parse',
3080 $this->contentModel
,
3081 $this->contentFormat
,
3084 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3090 * Append preview output to $wgOut.
3091 * Includes category rendering if this is a category page.
3093 * @param string $text The HTML to be output for the preview.
3095 protected function showPreview( $text ) {
3097 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3098 $this->mArticle
->openShowCategory();
3100 # This hook seems slightly odd here, but makes things more
3101 # consistent for extensions.
3102 Hooks
::run( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3103 $wgOut->addHTML( $text );
3104 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3105 $this->mArticle
->closeShowCategory();
3110 * Get a diff between the current contents of the edit box and the
3111 * version of the page we're editing from.
3113 * If this is a section edit, we'll replace the section as for final
3114 * save and then make a comparison.
3116 function showDiff() {
3117 global $wgUser, $wgContLang, $wgOut;
3119 $oldtitlemsg = 'currentrev';
3120 # if message does not exist, show diff against the preloaded default
3121 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3122 $oldtext = $this->mTitle
->getDefaultMessageText();
3123 if ( $oldtext !== false ) {
3124 $oldtitlemsg = 'defaultmessagetext';
3125 $oldContent = $this->toEditContent( $oldtext );
3130 $oldContent = $this->getCurrentContent();
3133 $textboxContent = $this->toEditContent( $this->textbox1
);
3135 $newContent = $this->mArticle
->replaceSectionContent(
3136 $this->section
, $textboxContent,
3137 $this->summary
, $this->edittime
);
3139 if ( $newContent ) {
3140 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3141 Hooks
::run( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3143 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
3144 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
3147 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3148 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3149 $newtitle = wfMessage( 'yourtext' )->parse();
3151 if ( !$oldContent ) {
3152 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3155 if ( !$newContent ) {
3156 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3159 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3160 $de->setContent( $oldContent, $newContent );
3162 $difftext = $de->getDiff( $oldtitle, $newtitle );
3163 $de->showDiffStyle();
3168 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3172 * Show the header copyright warning.
3174 protected function showHeaderCopyrightWarning() {
3175 $msg = 'editpage-head-copy-warn';
3176 if ( !wfMessage( $msg )->isDisabled() ) {
3178 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3179 'editpage-head-copy-warn' );
3184 * Give a chance for site and per-namespace customizations of
3185 * terms of service summary link that might exist separately
3186 * from the copyright notice.
3188 * This will display between the save button and the edit tools,
3189 * so should remain short!
3191 protected function showTosSummary() {
3192 $msg = 'editpage-tos-summary';
3193 Hooks
::run( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
3194 if ( !wfMessage( $msg )->isDisabled() ) {
3196 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3197 $wgOut->addWikiMsg( $msg );
3198 $wgOut->addHTML( '</div>' );
3202 protected function showEditTools() {
3204 $wgOut->addHTML( '<div class="mw-editTools">' .
3205 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3210 * Get the copyright warning
3212 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3215 protected function getCopywarn() {
3216 return self
::getCopyrightWarning( $this->mTitle
);
3220 * Get the copyright warning, by default returns wikitext
3222 * @param Title $title
3223 * @param string $format Output format, valid values are any function of a Message object
3226 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3227 global $wgRightsText;
3228 if ( $wgRightsText ) {
3229 $copywarnMsg = array( 'copyrightwarning',
3230 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3233 $copywarnMsg = array( 'copyrightwarning2',
3234 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3236 // Allow for site and per-namespace customization of contribution/copyright notice.
3237 Hooks
::run( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3239 return "<div id=\"editpage-copywarn\">\n" .
3240 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3244 * Get the Limit report for page previews
3247 * @param ParserOutput $output ParserOutput object from the parse
3248 * @return string HTML
3250 public static function getPreviewLimitReport( $output ) {
3251 if ( !$output ||
!$output->getLimitReportData() ) {
3255 $limitReport = Html
::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3256 wfMessage( 'limitreport-title' )->parseAsBlock()
3259 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3260 $limitReport .= Html
::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3262 $limitReport .= Html
::openElement( 'table', array(
3263 'class' => 'preview-limit-report wikitable'
3265 Html
::openElement( 'tbody' );
3267 foreach ( $output->getLimitReportData() as $key => $value ) {
3268 if ( Hooks
::run( 'ParserLimitReportFormat',
3269 array( $key, &$value, &$limitReport, true, true )
3271 $keyMsg = wfMessage( $key );
3272 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3273 if ( !$valueMsg->exists() ) {
3274 $valueMsg = new RawMessage( '$1' );
3276 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3277 $limitReport .= Html
::openElement( 'tr' ) .
3278 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3279 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3280 Html
::closeElement( 'tr' );
3285 $limitReport .= Html
::closeElement( 'tbody' ) .
3286 Html
::closeElement( 'table' ) .
3287 Html
::closeElement( 'div' );
3289 return $limitReport;
3292 protected function showStandardInputs( &$tabindex = 2 ) {
3294 $wgOut->addHTML( "<div class='editOptions'>\n" );
3296 if ( $this->section
!= 'new' ) {
3297 $this->showSummaryInput( false, $this->summary
);
3298 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3301 $checkboxes = $this->getCheckboxes( $tabindex,
3302 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
3303 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3305 // Show copyright warning.
3306 $wgOut->addWikiText( $this->getCopywarn() );
3307 $wgOut->addHTML( $this->editFormTextAfterWarn
);
3309 $wgOut->addHTML( "<div class='editButtons'>\n" );
3310 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3312 $cancel = $this->getCancelLink();
3313 if ( $cancel !== '' ) {
3314 $cancel .= Html
::element( 'span',
3315 array( 'class' => 'mw-editButtons-pipe-separator' ),
3316 wfMessage( 'pipe-separator' )->text() );
3319 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3320 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3322 'target' => 'helpwindow',
3323 'href' => $edithelpurl,
3325 $edithelp = Html
::linkButton( wfMessage( 'edithelp' )->text(),
3326 $attrs, array( 'mw-ui-quiet' ) ) .
3327 wfMessage( 'word-separator' )->escaped() .
3328 wfMessage( 'newwindow' )->parse();
3330 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3331 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3332 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3334 Hooks
::run( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3336 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3340 * Show an edit conflict. textbox1 is already shown in showEditForm().
3341 * If you want to use another entry point to this function, be careful.
3343 protected function showConflict() {
3346 if ( Hooks
::run( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3347 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3349 $content1 = $this->toEditContent( $this->textbox1
);
3350 $content2 = $this->toEditContent( $this->textbox2
);
3352 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3353 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3354 $de->setContent( $content2, $content1 );
3356 wfMessage( 'yourtext' )->parse(),
3357 wfMessage( 'storedversion' )->text()
3360 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3361 $this->showTextbox2();
3368 public function getCancelLink() {
3369 $cancelParams = array();
3370 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3371 $cancelParams['oldid'] = $this->oldid
;
3373 $attrs = array( 'id' => 'mw-editform-cancel' );
3375 return Linker
::linkKnown(
3376 $this->getContextTitle(),
3377 wfMessage( 'cancel' )->parse(),
3378 Html
::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3384 * Returns the URL to use in the form's action attribute.
3385 * This is used by EditPage subclasses when simply customizing the action
3386 * variable in the constructor is not enough. This can be used when the
3387 * EditPage lives inside of a Special page rather than a custom page action.
3389 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3392 protected function getActionURL( Title
$title ) {
3393 return $title->getLocalURL( array( 'action' => $this->action
) );
3397 * Check if a page was deleted while the user was editing it, before submit.
3398 * Note that we rely on the logging table, which hasn't been always there,
3399 * but that doesn't matter, because this only applies to brand new
3403 protected function wasDeletedSinceLastEdit() {
3404 if ( $this->deletedSinceEdit
!== null ) {
3405 return $this->deletedSinceEdit
;
3408 $this->deletedSinceEdit
= false;
3410 if ( $this->mTitle
->isDeletedQuick() ) {
3411 $this->lastDelete
= $this->getLastDelete();
3412 if ( $this->lastDelete
) {
3413 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3414 if ( $deleteTime > $this->starttime
) {
3415 $this->deletedSinceEdit
= true;
3420 return $this->deletedSinceEdit
;
3424 * @return bool|stdClass
3426 protected function getLastDelete() {
3427 $dbr = wfGetDB( DB_SLAVE
);
3428 $data = $dbr->selectRow(
3429 array( 'logging', 'user' ),
3442 'log_namespace' => $this->mTitle
->getNamespace(),
3443 'log_title' => $this->mTitle
->getDBkey(),
3444 'log_type' => 'delete',
3445 'log_action' => 'delete',
3449 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3451 // Quick paranoid permission checks...
3452 if ( is_object( $data ) ) {
3453 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3454 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
3457 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3458 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
3466 * Get the rendered text for previewing.
3467 * @throws MWException
3470 function getPreviewText() {
3471 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3472 global $wgAllowUserCss, $wgAllowUserJs;
3474 if ( $wgRawHtml && !$this->mTokenOk
) {
3475 // Could be an offsite preview attempt. This is very unsafe if
3476 // HTML is enabled, as it could be an attack.
3478 if ( $this->textbox1
!== '' ) {
3479 // Do not put big scary notice, if previewing the empty
3480 // string, which happens when you initially edit
3481 // a category page, due to automatic preview-on-open.
3482 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3483 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3491 $content = $this->toEditContent( $this->textbox1
);
3495 'AlternateEditPreview',
3496 array( $this, &$content, &$previewHTML, &$this->mParserOutput
) )
3498 return $previewHTML;
3501 # provide a anchor link to the editform
3502 $continueEditing = '<span class="mw-continue-editing">' .
3503 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3504 wfMessage( 'continue-editing' )->text() . ']]</span>';
3505 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3506 if ( $this->mTokenOkExceptSuffix
) {
3507 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3509 $note = wfMessage( 'session_fail_preview' )->plain();
3511 } elseif ( $this->incompleteForm
) {
3512 $note = wfMessage( 'edit_form_incomplete' )->plain();
3514 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3517 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
3518 $parserOptions->setIsPreview( true );
3519 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3521 # don't parse non-wikitext pages, show message about preview
3522 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3523 if ( $this->mTitle
->isCssJsSubpage() ) {
3525 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3531 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3533 if ( $level === 'user' && !$wgAllowUserCss ) {
3536 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3538 if ( $level === 'user' && !$wgAllowUserJs ) {
3545 # Used messages to make sure grep find them:
3546 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3547 if ( $level && $format ) {
3548 $note = "<div id='mw-{$level}{$format}preview'>" .
3549 wfMessage( "{$level}{$format}preview" )->text() .
3550 ' ' . $continueEditing . "</div>";
3554 # If we're adding a comment, we need to show the
3555 # summary as the headline
3556 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3557 $content = $content->addSectionHeader( $this->summary
);
3560 $hook_args = array( $this, &$content );
3561 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3562 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3564 $parserOptions->enableLimitReport();
3566 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3567 # But it's now deprecated, so never mind
3569 $pstContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3570 $scopedCallback = $parserOptions->setupFakeRevision(
3571 $this->mTitle
, $pstContent, $wgUser );
3572 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3574 # Try to stash the edit for the final submission step
3575 # @todo: different date format preferences cause cache misses
3576 ApiStashEdit
::stashEditFromPreview(
3577 $this->getArticle(), $content, $pstContent,
3578 $parserOutput, $parserOptions, $parserOptions, wfTimestampNow()
3581 $parserOutput->setEditSectionTokens( false ); // no section edit links
3582 $previewHTML = $parserOutput->getText();
3583 $this->mParserOutput
= $parserOutput;
3584 $wgOut->addParserOutputMetadata( $parserOutput );
3586 if ( count( $parserOutput->getWarnings() ) ) {
3587 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3589 } catch ( MWContentSerializationException
$ex ) {
3591 'content-failed-to-parse',
3592 $this->contentModel
,
3593 $this->contentFormat
,
3596 $note .= "\n\n" . $m->parse();
3600 if ( $this->isConflict
) {
3601 $conflict = '<h2 id="mw-previewconflict">'
3602 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3604 $conflict = '<hr />';
3607 $previewhead = "<div class='previewnote'>\n" .
3608 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3609 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3611 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3612 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3613 'class' => 'mw-content-' . $pageViewLang->getDir() );
3614 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3616 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3622 function getTemplates() {
3623 if ( $this->preview ||
$this->section
!= '' ) {
3624 $templates = array();
3625 if ( !isset( $this->mParserOutput
) ) {
3628 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3629 foreach ( array_keys( $template ) as $dbk ) {
3630 $templates[] = Title
::makeTitle( $ns, $dbk );
3635 return $this->mTitle
->getTemplateLinksFrom();
3640 * Shows a bulletin board style toolbar for common editing functions.
3641 * It can be disabled in the user preferences.
3645 static function getEditToolbar() {
3646 global $wgContLang, $wgOut;
3647 global $wgEnableUploads, $wgForeignFileRepos;
3649 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3652 * $toolarray is an array of arrays each of which includes the
3653 * opening tag, the closing tag, optionally a sample text that is
3654 * inserted between the two when no selection is highlighted
3655 * and. The tip text is shown when the user moves the mouse
3658 * Images are defined in ResourceLoaderEditToolbarModule.
3662 'id' => 'mw-editbutton-bold',
3664 'close' => '\'\'\'',
3665 'sample' => wfMessage( 'bold_sample' )->text(),
3666 'tip' => wfMessage( 'bold_tip' )->text(),
3669 'id' => 'mw-editbutton-italic',
3672 'sample' => wfMessage( 'italic_sample' )->text(),
3673 'tip' => wfMessage( 'italic_tip' )->text(),
3676 'id' => 'mw-editbutton-link',
3679 'sample' => wfMessage( 'link_sample' )->text(),
3680 'tip' => wfMessage( 'link_tip' )->text(),
3683 'id' => 'mw-editbutton-extlink',
3686 'sample' => wfMessage( 'extlink_sample' )->text(),
3687 'tip' => wfMessage( 'extlink_tip' )->text(),
3690 'id' => 'mw-editbutton-headline',
3693 'sample' => wfMessage( 'headline_sample' )->text(),
3694 'tip' => wfMessage( 'headline_tip' )->text(),
3696 $imagesAvailable ?
array(
3697 'id' => 'mw-editbutton-image',
3698 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3700 'sample' => wfMessage( 'image_sample' )->text(),
3701 'tip' => wfMessage( 'image_tip' )->text(),
3703 $imagesAvailable ?
array(
3704 'id' => 'mw-editbutton-media',
3705 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3707 'sample' => wfMessage( 'media_sample' )->text(),
3708 'tip' => wfMessage( 'media_tip' )->text(),
3711 'id' => 'mw-editbutton-nowiki',
3712 'open' => "<nowiki>",
3713 'close' => "</nowiki>",
3714 'sample' => wfMessage( 'nowiki_sample' )->text(),
3715 'tip' => wfMessage( 'nowiki_tip' )->text(),
3718 'id' => 'mw-editbutton-signature',
3722 'tip' => wfMessage( 'sig_tip' )->text(),
3725 'id' => 'mw-editbutton-hr',
3726 'open' => "\n----\n",
3729 'tip' => wfMessage( 'hr_tip' )->text(),
3733 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3734 foreach ( $toolarray as $tool ) {
3740 // Images are defined in ResourceLoaderEditToolbarModule
3742 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3743 // Older browsers show a "speedtip" type message only for ALT.
3744 // Ideally these should be different, realistically they
3745 // probably don't need to be.
3753 $script .= Xml
::encodeJsCall(
3754 'mw.toolbar.addButton',
3756 ResourceLoader
::inDebugMode()
3761 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3763 $toolbar = '<div id="toolbar"></div>';
3765 Hooks
::run( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3771 * Returns an array of html code of the following checkboxes:
3774 * @param int $tabindex Current tabindex
3775 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3776 * status of the checkbox
3780 public function getCheckboxes( &$tabindex, $checked ) {
3781 global $wgUser, $wgUseMediaWikiUIEverywhere;
3783 $checkboxes = array();
3785 // don't show the minor edit checkbox if it's a new page or section
3786 if ( !$this->isNew
) {
3787 $checkboxes['minor'] = '';
3788 $minorLabel = wfMessage( 'minoredit' )->parse();
3789 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3791 'tabindex' => ++
$tabindex,
3792 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3793 'id' => 'wpMinoredit',
3796 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3797 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3798 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3799 ">{$minorLabel}</label>";
3801 if ( $wgUseMediaWikiUIEverywhere ) {
3802 $checkboxes['minor'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3804 Html
::closeElement( 'div' );
3806 $checkboxes['minor'] = $minorEditHtml;
3811 $watchLabel = wfMessage( 'watchthis' )->parse();
3812 $checkboxes['watch'] = '';
3813 if ( $wgUser->isLoggedIn() ) {
3815 'tabindex' => ++
$tabindex,
3816 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3817 'id' => 'wpWatchthis',
3820 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3821 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3822 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3823 ">{$watchLabel}</label>";
3824 if ( $wgUseMediaWikiUIEverywhere ) {
3825 $checkboxes['watch'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3827 Html
::closeElement( 'div' );
3829 $checkboxes['watch'] = $watchThisHtml;
3832 Hooks
::run( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3837 * Returns an array of html code of the following buttons:
3838 * save, diff, preview and live
3840 * @param int $tabindex Current tabindex
3844 public function getEditButtons( &$tabindex ) {
3850 'tabindex' => ++
$tabindex,
3851 ) + Linker
::tooltipAndAccesskeyAttribs( 'save' );
3852 $buttons['save'] = Html
::submitButton( wfMessage( 'savearticle' )->text(),
3853 $attribs, array( 'mw-ui-constructive' ) );
3855 ++
$tabindex; // use the same for preview and live preview
3857 'id' => 'wpPreview',
3858 'name' => 'wpPreview',
3859 'tabindex' => $tabindex,
3860 ) + Linker
::tooltipAndAccesskeyAttribs( 'preview' );
3861 $buttons['preview'] = Html
::submitButton( wfMessage( 'showpreview' )->text(),
3863 $buttons['live'] = '';
3868 'tabindex' => ++
$tabindex,
3869 ) + Linker
::tooltipAndAccesskeyAttribs( 'diff' );
3870 $buttons['diff'] = Html
::submitButton( wfMessage( 'showdiff' )->text(),
3873 Hooks
::run( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3878 * Creates a basic error page which informs the user that
3879 * they have attempted to edit a nonexistent section.
3881 function noSuchSectionPage() {
3884 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3886 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3887 Hooks
::run( 'EditPageNoSuchSection', array( &$this, &$res ) );
3888 $wgOut->addHTML( $res );
3890 $wgOut->returnToMain( false, $this->mTitle
);
3894 * Show "your edit contains spam" page with your diff and text
3896 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3898 public function spamPageWithContent( $match = false ) {
3899 global $wgOut, $wgLang;
3900 $this->textbox2
= $this->textbox1
;
3902 if ( is_array( $match ) ) {
3903 $match = $wgLang->listToText( $match );
3905 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3907 $wgOut->addHTML( '<div id="spamprotected">' );
3908 $wgOut->addWikiMsg( 'spamprotectiontext' );
3910 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3912 $wgOut->addHTML( '</div>' );
3914 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3917 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3918 $this->showTextbox2();
3920 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3924 * Check if the browser is on a blacklist of user-agents known to
3925 * mangle UTF-8 data on form submission. Returns true if Unicode
3926 * should make it through, false if it's known to be a problem.
3929 private function checkUnicodeCompliantBrowser() {
3930 global $wgBrowserBlackList, $wgRequest;
3932 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3933 if ( $currentbrowser === false ) {
3934 // No User-Agent header sent? Trust it by default...
3938 foreach ( $wgBrowserBlackList as $browser ) {
3939 if ( preg_match( $browser, $currentbrowser ) ) {
3947 * Filter an input field through a Unicode de-armoring process if it
3948 * came from an old browser with known broken Unicode editing issues.
3950 * @param WebRequest $request
3951 * @param string $field
3954 protected function safeUnicodeInput( $request, $field ) {
3955 $text = rtrim( $request->getText( $field ) );
3956 return $request->getBool( 'safemode' )
3957 ?
$this->unmakeSafe( $text )
3962 * Filter an output field through a Unicode armoring process if it is
3963 * going to an old browser with known broken Unicode editing issues.
3965 * @param string $text
3968 protected function safeUnicodeOutput( $text ) {
3970 $codedText = $wgContLang->recodeForEdit( $text );
3971 return $this->checkUnicodeCompliantBrowser()
3973 : $this->makeSafe( $codedText );
3977 * A number of web browsers are known to corrupt non-ASCII characters
3978 * in a UTF-8 text editing environment. To protect against this,
3979 * detected browsers will be served an armored version of the text,
3980 * with non-ASCII chars converted to numeric HTML character references.
3982 * Preexisting such character references will have a 0 added to them
3983 * to ensure that round-trips do not alter the original data.
3985 * @param string $invalue
3988 private function makeSafe( $invalue ) {
3989 // Armor existing references for reversibility.
3990 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3995 $valueLength = strlen( $invalue );
3996 for ( $i = 0; $i < $valueLength; $i++
) {
3997 $bytevalue = ord( $invalue[$i] );
3998 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3999 $result .= chr( $bytevalue );
4001 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4002 $working = $working << 6;
4003 $working +
= ( $bytevalue & 0x3F );
4005 if ( $bytesleft <= 0 ) {
4006 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4008 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4009 $working = $bytevalue & 0x1F;
4011 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4012 $working = $bytevalue & 0x0F;
4014 } else { // 1111 0xxx
4015 $working = $bytevalue & 0x07;
4023 * Reverse the previously applied transliteration of non-ASCII characters
4024 * back to UTF-8. Used to protect data from corruption by broken web browsers
4025 * as listed in $wgBrowserBlackList.
4027 * @param string $invalue
4030 private function unmakeSafe( $invalue ) {
4032 $valueLength = strlen( $invalue );
4033 for ( $i = 0; $i < $valueLength; $i++
) {
4034 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4038 $hexstring .= $invalue[$i];
4040 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4042 // Do some sanity checks. These aren't needed for reversibility,
4043 // but should help keep the breakage down if the editor
4044 // breaks one of the entities whilst editing.
4045 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4046 $codepoint = hexdec( $hexstring );
4047 $result .= UtfNormal\Utils
::codepointToUtf8( $codepoint );
4049 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4052 $result .= substr( $invalue, $i, 1 );
4055 // reverse the transform that we made for reversibility reasons.
4056 return strtr( $result, array( "�" => "&#x" ) );