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 current content of the page. This is basically similar to
1141 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1142 * content object is returned instead of null.
1147 protected function getCurrentContent() {
1148 $rev = $this->mArticle
->getRevision();
1149 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1151 if ( $content === false ||
$content === null ) {
1152 if ( !$this->contentModel
) {
1153 $this->contentModel
= $this->getTitle()->getContentModel();
1155 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1157 return $handler->makeEmptyContent();
1159 # nasty side-effect, but needed for consistency
1160 $this->contentModel
= $rev->getContentModel();
1161 $this->contentFormat
= $rev->getContentFormat();
1168 * Use this method before edit() to preload some content into the edit box
1170 * @param Content $content
1174 public function setPreloadedContent( Content
$content ) {
1175 $this->mPreloadContent
= $content;
1179 * Get the contents to be preloaded into the box, either set by
1180 * an earlier setPreloadText() or by loading the given page.
1182 * @param string $preload Representing the title to preload from.
1183 * @param array $params Parameters to use (interface-message style) in the preloaded text
1189 protected function getPreloadedContent( $preload, $params = array() ) {
1192 if ( !empty( $this->mPreloadContent
) ) {
1193 return $this->mPreloadContent
;
1196 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1198 if ( $preload === '' ) {
1199 return $handler->makeEmptyContent();
1202 $title = Title
::newFromText( $preload );
1203 # Check for existence to avoid getting MediaWiki:Noarticletext
1204 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1205 //TODO: somehow show a warning to the user!
1206 return $handler->makeEmptyContent();
1209 $page = WikiPage
::factory( $title );
1210 if ( $page->isRedirect() ) {
1211 $title = $page->getRedirectTarget();
1213 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1214 //TODO: somehow show a warning to the user!
1215 return $handler->makeEmptyContent();
1217 $page = WikiPage
::factory( $title );
1220 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1221 $content = $page->getContent( Revision
::RAW
);
1224 //TODO: somehow show a warning to the user!
1225 return $handler->makeEmptyContent();
1228 if ( $content->getModel() !== $handler->getModelID() ) {
1229 $converted = $content->convert( $handler->getModelID() );
1231 if ( !$converted ) {
1232 //TODO: somehow show a warning to the user!
1233 wfDebug( "Attempt to preload incompatible content: "
1234 . "can't convert " . $content->getModel()
1235 . " to " . $handler->getModelID() );
1237 return $handler->makeEmptyContent();
1240 $content = $converted;
1243 return $content->preloadTransform( $title, $parserOptions, $params );
1247 * Make sure the form isn't faking a user's credentials.
1249 * @param WebRequest $request
1253 function tokenOk( &$request ) {
1255 $token = $request->getVal( 'wpEditToken' );
1256 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1257 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1258 return $this->mTokenOk
;
1262 * Sets post-edit cookie indicating the user just saved a particular revision.
1264 * This uses a temporary cookie for each revision ID so separate saves will never
1265 * interfere with each other.
1267 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1268 * the redirect. It must be clearable by JavaScript code, so it must not be
1269 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1272 * If the variable were set on the server, it would be cached, which is unwanted
1273 * since the post-edit state should only apply to the load right after the save.
1275 * @param int $statusValue The status value (to check for new article status)
1277 protected function setPostEditCookie( $statusValue ) {
1278 $revisionId = $this->mArticle
->getLatest();
1279 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1282 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1284 } elseif ( $this->oldid
) {
1288 $response = RequestContext
::getMain()->getRequest()->response();
1289 $response->setcookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
, array(
1290 'httpOnly' => false,
1295 * Attempt submission
1296 * @param array $resultDetails See docs for $result in internalAttemptSave
1297 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1298 * @return Status The resulting status object.
1300 public function attemptSave( &$resultDetails = false ) {
1303 # Allow bots to exempt some edits from bot flagging
1304 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1305 $status = $this->internalAttemptSave( $resultDetails, $bot );
1307 Hooks
::run( 'EditPage::attemptSave:after', array( $this, $status, $resultDetails ) );
1313 * Handle status, such as after attempt save
1315 * @param Status $status
1316 * @param array|bool $resultDetails
1318 * @throws ErrorPageError
1319 * @return bool False, if output is done, true if rest of the form should be displayed
1321 private function handleStatus( Status
$status, $resultDetails ) {
1322 global $wgUser, $wgOut;
1325 * @todo FIXME: once the interface for internalAttemptSave() is made
1326 * nicer, this should use the message in $status
1328 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1329 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1331 $this->didSave
= true;
1332 if ( !$resultDetails['nullEdit'] ) {
1333 $this->setPostEditCookie( $status->value
);
1337 switch ( $status->value
) {
1338 case self
::AS_HOOK_ERROR_EXPECTED
:
1339 case self
::AS_CONTENT_TOO_BIG
:
1340 case self
::AS_ARTICLE_WAS_DELETED
:
1341 case self
::AS_CONFLICT_DETECTED
:
1342 case self
::AS_SUMMARY_NEEDED
:
1343 case self
::AS_TEXTBOX_EMPTY
:
1344 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1346 case self
::AS_BLANK_ARTICLE
:
1347 case self
::AS_SELF_REDIRECT
:
1350 case self
::AS_HOOK_ERROR
:
1353 case self
::AS_PARSE_ERROR
:
1354 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1357 case self
::AS_SUCCESS_NEW_ARTICLE
:
1358 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1359 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1360 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1363 case self
::AS_SUCCESS_UPDATE
:
1365 $sectionanchor = $resultDetails['sectionanchor'];
1367 // Give extensions a chance to modify URL query on update
1369 'ArticleUpdateBeforeRedirect',
1370 array( $this->mArticle
, &$sectionanchor, &$extraQuery )
1373 if ( $resultDetails['redirect'] ) {
1374 if ( $extraQuery == '' ) {
1375 $extraQuery = 'redirect=no';
1377 $extraQuery = 'redirect=no&' . $extraQuery;
1380 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1383 case self
::AS_SPAM_ERROR
:
1384 $this->spamPageWithContent( $resultDetails['spam'] );
1387 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1388 throw new UserBlockedError( $wgUser->getBlock() );
1390 case self
::AS_IMAGE_REDIRECT_ANON
:
1391 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1392 throw new PermissionsError( 'upload' );
1394 case self
::AS_READ_ONLY_PAGE_ANON
:
1395 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1396 throw new PermissionsError( 'edit' );
1398 case self
::AS_READ_ONLY_PAGE
:
1399 throw new ReadOnlyError
;
1401 case self
::AS_RATE_LIMITED
:
1402 throw new ThrottledError();
1404 case self
::AS_NO_CREATE_PERMISSION
:
1405 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1406 throw new PermissionsError( $permission );
1408 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1409 throw new PermissionsError( 'editcontentmodel' );
1412 // We don't recognize $status->value. The only way that can happen
1413 // is if an extension hook aborted from inside ArticleSave.
1414 // Render the status object into $this->hookError
1415 // FIXME this sucks, we should just use the Status object throughout
1416 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1423 * Run hooks that can filter edits just before they get saved.
1425 * @param Content $content The Content to filter.
1426 * @param Status $status For reporting the outcome to the caller
1427 * @param User $user The user performing the edit
1431 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1432 // Run old style post-section-merge edit filter
1433 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1434 array( $this, $content, &$this->hookError
, $this->summary
) )
1436 # Error messages etc. could be handled within the hook...
1437 $status->fatal( 'hookaborted' );
1438 $status->value
= self
::AS_HOOK_ERROR
;
1440 } elseif ( $this->hookError
!= '' ) {
1441 # ...or the hook could be expecting us to produce an error
1442 $status->fatal( 'hookaborted' );
1443 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1447 // Run new style post-section-merge edit filter
1448 if ( !Hooks
::run( 'EditFilterMergedContent',
1449 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1450 $user, $this->minoredit
) )
1452 # Error messages etc. could be handled within the hook...
1453 if ( $status->isGood() ) {
1454 $status->fatal( 'hookaborted' );
1455 // Not setting $this->hookError here is a hack to allow the hook
1456 // to cause a return to the edit page without $this->hookError
1457 // being set. This is used by ConfirmEdit to display a captcha
1458 // without any error message cruft.
1460 $this->hookError
= $status->getWikiText();
1462 // Use the existing $status->value if the hook set it
1463 if ( !$status->value
) {
1464 $status->value
= self
::AS_HOOK_ERROR
;
1467 } elseif ( !$status->isOK() ) {
1468 # ...or the hook could be expecting us to produce an error
1469 // FIXME this sucks, we should just use the Status object throughout
1470 $this->hookError
= $status->getWikiText();
1471 $status->fatal( 'hookaborted' );
1472 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1480 * Return the summary to be used for a new section.
1482 * @param string $sectionanchor Set to the section anchor text
1485 private function newSectionSummary( &$sectionanchor = null ) {
1488 if ( $this->sectiontitle
!== '' ) {
1489 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1490 // If no edit summary was specified, create one automatically from the section
1491 // title and have it link to the new section. Otherwise, respect the summary as
1493 if ( $this->summary
=== '' ) {
1494 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1495 return wfMessage( 'newsectionsummary' )
1496 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1498 } elseif ( $this->summary
!== '' ) {
1499 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1500 # This is a new section, so create a link to the new section
1501 # in the revision summary.
1502 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1503 return wfMessage( 'newsectionsummary' )
1504 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1506 return $this->summary
;
1510 * Attempt submission (no UI)
1512 * @param array $result Array to add statuses to, currently with the
1514 * - spam (string): Spam string from content if any spam is detected by
1516 * - sectionanchor (string): Section anchor for a section save.
1517 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1519 * - redirect (bool): Set if doEditContent is OK. True if resulting
1520 * revision is a redirect.
1521 * @param bool $bot True if edit is being made under the bot right.
1523 * @return Status Status object, possibly with a message, but always with
1524 * one of the AS_* constants in $status->value,
1526 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1527 * various error display idiosyncrasies. There are also lots of cases
1528 * where error metadata is set in the object and retrieved later instead
1529 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1530 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1533 function internalAttemptSave( &$result, $bot = false ) {
1534 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1536 $status = Status
::newGood();
1538 if ( !Hooks
::run( 'EditPage::attemptSave', array( $this ) ) ) {
1539 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1540 $status->fatal( 'hookaborted' );
1541 $status->value
= self
::AS_HOOK_ERROR
;
1545 $spam = $wgRequest->getText( 'wpAntispam' );
1546 if ( $spam !== '' ) {
1549 $wgUser->getName() .
1551 $this->mTitle
->getPrefixedText() .
1552 '" submitted bogus field "' .
1556 $status->fatal( 'spamprotectionmatch', false );
1557 $status->value
= self
::AS_SPAM_ERROR
;
1562 # Construct Content object
1563 $textbox_content = $this->toEditContent( $this->textbox1
);
1564 } catch ( MWContentSerializationException
$ex ) {
1566 'content-failed-to-parse',
1567 $this->contentModel
,
1568 $this->contentFormat
,
1571 $status->value
= self
::AS_PARSE_ERROR
;
1575 # Check image redirect
1576 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1577 $textbox_content->isRedirect() &&
1578 !$wgUser->isAllowed( 'upload' )
1580 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1581 $status->setResult( false, $code );
1587 $match = self
::matchSummarySpamRegex( $this->summary
);
1588 if ( $match === false && $this->section
== 'new' ) {
1589 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1590 # regular summaries, it is added to the actual wikitext.
1591 if ( $this->sectiontitle
!== '' ) {
1592 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1593 $match = self
::matchSpamRegex( $this->sectiontitle
);
1595 # This branch is taken when the "Add Topic" user interface is used, or the API
1596 # is used with the 'summary' parameter.
1597 $match = self
::matchSpamRegex( $this->summary
);
1600 if ( $match === false ) {
1601 $match = self
::matchSpamRegex( $this->textbox1
);
1603 if ( $match !== false ) {
1604 $result['spam'] = $match;
1605 $ip = $wgRequest->getIP();
1606 $pdbk = $this->mTitle
->getPrefixedDBkey();
1607 $match = str_replace( "\n", '', $match );
1608 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1609 $status->fatal( 'spamprotectionmatch', $match );
1610 $status->value
= self
::AS_SPAM_ERROR
;
1615 array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) )
1617 # Error messages etc. could be handled within the hook...
1618 $status->fatal( 'hookaborted' );
1619 $status->value
= self
::AS_HOOK_ERROR
;
1621 } elseif ( $this->hookError
!= '' ) {
1622 # ...or the hook could be expecting us to produce an error
1623 $status->fatal( 'hookaborted' );
1624 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1628 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1629 // Auto-block user's IP if the account was "hard" blocked
1630 $wgUser->spreadAnyEditBlock();
1631 # Check block state against master, thus 'false'.
1632 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1636 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1637 if ( $this->kblength
> $wgMaxArticleSize ) {
1638 // Error will be displayed by showEditForm()
1639 $this->tooBig
= true;
1640 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1644 if ( !$wgUser->isAllowed( 'edit' ) ) {
1645 if ( $wgUser->isAnon() ) {
1646 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1649 $status->fatal( 'readonlytext' );
1650 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1655 if ( $this->contentModel
!== $this->mTitle
->getContentModel()
1656 && !$wgUser->isAllowed( 'editcontentmodel' )
1658 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1662 if ( $this->changeTags
) {
1663 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1664 $this->changeTags
, $wgUser );
1665 if ( !$changeTagsStatus->isOK() ) {
1666 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1667 return $changeTagsStatus;
1671 if ( wfReadOnly() ) {
1672 $status->fatal( 'readonlytext' );
1673 $status->value
= self
::AS_READ_ONLY_PAGE
;
1676 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1677 $status->fatal( 'actionthrottledtext' );
1678 $status->value
= self
::AS_RATE_LIMITED
;
1682 # If the article has been deleted while editing, don't save it without
1684 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1685 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1689 # Load the page data from the master. If anything changes in the meantime,
1690 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1691 $this->mArticle
->loadPageData( 'fromdbmaster' );
1692 $new = !$this->mArticle
->exists();
1695 // Late check for create permission, just in case *PARANOIA*
1696 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1697 $status->fatal( 'nocreatetext' );
1698 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1699 wfDebug( __METHOD__
. ": no create permission\n" );
1703 // Don't save a new page if it's blank or if it's a MediaWiki:
1704 // message with content equivalent to default (allow empty pages
1705 // in this case to disable messages, see bug 50124)
1706 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1707 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1708 $defaultText = $defaultMessageText;
1713 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1714 $this->blankArticle
= true;
1715 $status->fatal( 'blankarticle' );
1716 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1720 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1724 $content = $textbox_content;
1726 $result['sectionanchor'] = '';
1727 if ( $this->section
== 'new' ) {
1728 if ( $this->sectiontitle
!== '' ) {
1729 // Insert the section title above the content.
1730 $content = $content->addSectionHeader( $this->sectiontitle
);
1731 } elseif ( $this->summary
!== '' ) {
1732 // Insert the section title above the content.
1733 $content = $content->addSectionHeader( $this->summary
);
1735 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1738 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1742 # Article exists. Check for edit conflict.
1744 $this->mArticle
->clear(); # Force reload of dates, etc.
1745 $timestamp = $this->mArticle
->getTimestamp();
1747 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1749 if ( $timestamp != $this->edittime
) {
1750 $this->isConflict
= true;
1751 if ( $this->section
== 'new' ) {
1752 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1753 $this->mArticle
->getComment() == $this->newSectionSummary()
1755 // Probably a duplicate submission of a new comment.
1756 // This can happen when squid resends a request after
1757 // a timeout but the first one actually went through.
1759 . ": duplicate new section submission; trigger edit conflict!\n" );
1761 // New comment; suppress conflict.
1762 $this->isConflict
= false;
1763 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1765 } elseif ( $this->section
== ''
1766 && Revision
::userWasLastToEdit(
1767 DB_MASTER
, $this->mTitle
->getArticleID(),
1768 $wgUser->getId(), $this->edittime
1771 # Suppress edit conflict with self, except for section edits where merging is required.
1772 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1773 $this->isConflict
= false;
1777 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1778 if ( $this->sectiontitle
!== '' ) {
1779 $sectionTitle = $this->sectiontitle
;
1781 $sectionTitle = $this->summary
;
1786 if ( $this->isConflict
) {
1788 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1789 . " (article time '{$timestamp}')\n" );
1791 $content = $this->mArticle
->replaceSectionContent(
1798 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1799 $content = $this->mArticle
->replaceSectionContent(
1806 if ( is_null( $content ) ) {
1807 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1808 $this->isConflict
= true;
1809 $content = $textbox_content; // do not try to merge here!
1810 } elseif ( $this->isConflict
) {
1812 if ( $this->mergeChangesIntoContent( $content ) ) {
1813 // Successful merge! Maybe we should tell the user the good news?
1814 $this->isConflict
= false;
1815 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1817 $this->section
= '';
1818 $this->textbox1
= ContentHandler
::getContentText( $content );
1819 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1823 if ( $this->isConflict
) {
1824 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1828 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1832 if ( $this->section
== 'new' ) {
1833 // Handle the user preference to force summaries here
1834 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1835 $this->missingSummary
= true;
1836 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1837 $status->value
= self
::AS_SUMMARY_NEEDED
;
1841 // Do not allow the user to post an empty comment
1842 if ( $this->textbox1
== '' ) {
1843 $this->missingComment
= true;
1844 $status->fatal( 'missingcommenttext' );
1845 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1848 } elseif ( !$this->allowBlankSummary
1849 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1850 && !$content->isRedirect()
1851 && md5( $this->summary
) == $this->autoSumm
1853 $this->missingSummary
= true;
1854 $status->fatal( 'missingsummary' );
1855 $status->value
= self
::AS_SUMMARY_NEEDED
;
1860 $sectionanchor = '';
1861 if ( $this->section
== 'new' ) {
1862 $this->summary
= $this->newSectionSummary( $sectionanchor );
1863 } elseif ( $this->section
!= '' ) {
1864 # Try to get a section anchor from the section source, redirect
1865 # to edited section if header found.
1866 # XXX: Might be better to integrate this into Article::replaceSection
1867 # for duplicate heading checking and maybe parsing.
1868 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1869 # We can't deal with anchors, includes, html etc in the header for now,
1870 # headline would need to be parsed to improve this.
1871 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1872 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1875 $result['sectionanchor'] = $sectionanchor;
1877 // Save errors may fall down to the edit form, but we've now
1878 // merged the section into full text. Clear the section field
1879 // so that later submission of conflict forms won't try to
1880 // replace that into a duplicated mess.
1881 $this->textbox1
= $this->toEditText( $content );
1882 $this->section
= '';
1884 $status->value
= self
::AS_SUCCESS_UPDATE
;
1887 if ( !$this->allowSelfRedirect
1888 && $content->isRedirect()
1889 && $content->getRedirectTarget()->equals( $this->getTitle() )
1891 // If the page already redirects to itself, don't warn.
1892 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
1893 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
1894 $this->selfRedirect
= true;
1895 $status->fatal( 'selfredirect' );
1896 $status->value
= self
::AS_SELF_REDIRECT
;
1901 // Check for length errors again now that the section is merged in
1902 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1903 if ( $this->kblength
> $wgMaxArticleSize ) {
1904 $this->tooBig
= true;
1905 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1909 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1910 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1911 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1912 ( $bot ? EDIT_FORCE_BOT
: 0 );
1914 $doEditStatus = $this->mArticle
->doEditContent(
1920 $content->getDefaultFormat()
1923 if ( !$doEditStatus->isOK() ) {
1924 // Failure from doEdit()
1925 // Show the edit conflict page for certain recognized errors from doEdit(),
1926 // but don't show it for errors from extension hooks
1927 $errors = $doEditStatus->getErrorsArray();
1928 if ( in_array( $errors[0][0],
1929 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1931 $this->isConflict
= true;
1932 // Destroys data doEdit() put in $status->value but who cares
1933 $doEditStatus->value
= self
::AS_END
;
1935 return $doEditStatus;
1938 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1939 if ( $result['nullEdit'] ) {
1940 // We don't know if it was a null edit until now, so increment here
1941 $wgUser->pingLimiter( 'linkpurge' );
1943 $result['redirect'] = $content->isRedirect();
1945 $this->updateWatchlist();
1947 if ( $this->changeTags
&& isset( $doEditStatus->value
['revision'] ) ) {
1948 // If a revision was created, apply any change tags that were requested
1949 ChangeTags
::addTags(
1951 isset( $doEditStatus->value
['rc'] ) ?
$doEditStatus->value
['rc']->mAttribs
['rc_id'] : null,
1952 $doEditStatus->value
['revision']->getId()
1960 * Register the change of watch status
1962 protected function updateWatchlist() {
1965 if ( $wgUser->isLoggedIn()
1966 && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
, WatchedItem
::IGNORE_USER_RIGHTS
)
1968 $fname = __METHOD__
;
1969 $title = $this->mTitle
;
1970 $watch = $this->watchthis
;
1972 // Do this in its own transaction to reduce contention...
1973 $dbw = wfGetDB( DB_MASTER
);
1974 $dbw->onTransactionIdle( function () use ( $dbw, $title, $watch, $wgUser, $fname ) {
1975 WatchAction
::doWatchOrUnwatch( $watch, $title, $wgUser );
1981 * Attempts to do 3-way merge of edit content with a base revision
1982 * and current content, in case of edit conflict, in whichever way appropriate
1983 * for the content type.
1987 * @param Content $editContent
1991 private function mergeChangesIntoContent( &$editContent ) {
1993 $db = wfGetDB( DB_MASTER
);
1995 // This is the revision the editor started from
1996 $baseRevision = $this->getBaseRevision();
1997 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
1999 if ( is_null( $baseContent ) ) {
2003 // The current state, we want to merge updates into it
2004 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2005 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2007 if ( is_null( $currentContent ) ) {
2011 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2013 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2016 $editContent = $result;
2026 function getBaseRevision() {
2027 if ( !$this->mBaseRevision
) {
2028 $db = wfGetDB( DB_MASTER
);
2029 $this->mBaseRevision
= Revision
::loadFromTimestamp(
2030 $db, $this->mTitle
, $this->edittime
);
2032 return $this->mBaseRevision
;
2036 * Check given input text against $wgSpamRegex, and return the text of the first match.
2038 * @param string $text
2040 * @return string|bool Matching string or false
2042 public static function matchSpamRegex( $text ) {
2043 global $wgSpamRegex;
2044 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2045 $regexes = (array)$wgSpamRegex;
2046 return self
::matchSpamRegexInternal( $text, $regexes );
2050 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2052 * @param string $text
2054 * @return string|bool Matching string or false
2056 public static function matchSummarySpamRegex( $text ) {
2057 global $wgSummarySpamRegex;
2058 $regexes = (array)$wgSummarySpamRegex;
2059 return self
::matchSpamRegexInternal( $text, $regexes );
2063 * @param string $text
2064 * @param array $regexes
2065 * @return bool|string
2067 protected static function matchSpamRegexInternal( $text, $regexes ) {
2068 foreach ( $regexes as $regex ) {
2070 if ( preg_match( $regex, $text, $matches ) ) {
2077 function setHeaders() {
2078 global $wgOut, $wgUser, $wgAjaxEditStash;
2080 $wgOut->addModules( 'mediawiki.action.edit' );
2081 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2083 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2084 // The addition of default buttons is handled by getEditToolbar() which
2085 // has its own dependency on this module. The call here ensures the module
2086 // is loaded in time (it has position "top") for other modules to register
2087 // buttons (e.g. extensions, gadgets, user scripts).
2088 $wgOut->addModules( 'mediawiki.toolbar' );
2091 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2092 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2095 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2096 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2099 if ( $wgAjaxEditStash ) {
2100 $wgOut->addModules( 'mediawiki.action.edit.stash' );
2103 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2105 # Enabled article-related sidebar, toplinks, etc.
2106 $wgOut->setArticleRelated( true );
2108 $contextTitle = $this->getContextTitle();
2109 if ( $this->isConflict
) {
2110 $msg = 'editconflict';
2111 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2112 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2114 $msg = $contextTitle->exists()
2115 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2116 && $contextTitle->getDefaultMessageText() !== false
2122 # Use the title defined by DISPLAYTITLE magic word when present
2123 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2124 if ( $displayTitle === false ) {
2125 $displayTitle = $contextTitle->getPrefixedText();
2127 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2128 # Transmit the name of the message to JavaScript for live preview
2129 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2130 $wgOut->addJsConfigVars( 'wgEditMessage', $msg );
2134 * Show all applicable editing introductions
2136 protected function showIntro() {
2137 global $wgOut, $wgUser;
2138 if ( $this->suppressIntro
) {
2142 $namespace = $this->mTitle
->getNamespace();
2144 if ( $namespace == NS_MEDIAWIKI
) {
2145 # Show a warning if editing an interface message
2146 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2147 # If this is a default message (but not css or js),
2148 # show a hint that it is translatable on translatewiki.net
2149 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2150 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2152 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2153 if ( $defaultMessageText !== false ) {
2154 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2155 'translateinterface' );
2158 } elseif ( $namespace == NS_FILE
) {
2159 # Show a hint to shared repo
2160 $file = wfFindFile( $this->mTitle
);
2161 if ( $file && !$file->isLocal() ) {
2162 $descUrl = $file->getDescriptionUrl();
2163 # there must be a description url to show a hint to shared repo
2165 if ( !$this->mTitle
->exists() ) {
2166 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2167 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2170 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2171 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2178 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2179 # Show log extract when the user is currently blocked
2180 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2181 $parts = explode( '/', $this->mTitle
->getText(), 2 );
2182 $username = $parts[0];
2183 $user = User
::newFromName( $username, false /* allow IP users*/ );
2184 $ip = User
::isIP( $username );
2185 $block = Block
::newFromTarget( $user, $user );
2186 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2187 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2188 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2189 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2190 # Show log extract if the user is currently blocked
2191 LogEventsList
::showLogExtract(
2194 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2198 'showIfEmpty' => false,
2200 'blocked-notice-logextract',
2201 $user->getName() # Support GENDER in notice
2207 # Try to add a custom edit intro, or use the standard one if this is not possible.
2208 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2209 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2210 wfMessage( 'helppage' )->inContentLanguage()->text()
2212 if ( $wgUser->isLoggedIn() ) {
2213 $wgOut->wrapWikiMsg(
2214 // Suppress the external link icon, consider the help url an internal one
2215 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2222 $wgOut->wrapWikiMsg(
2223 // Suppress the external link icon, consider the help url an internal one
2224 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2226 'newarticletextanon',
2232 # Give a notice if the user is editing a deleted/moved page...
2233 if ( !$this->mTitle
->exists() ) {
2234 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
2238 'conds' => array( "log_action != 'revision'" ),
2239 'showIfEmpty' => false,
2240 'msgKey' => array( 'recreate-moveddeleted-warn' )
2247 * Attempt to show a custom editing introduction, if supplied
2251 protected function showCustomIntro() {
2252 if ( $this->editintro
) {
2253 $title = Title
::newFromText( $this->editintro
);
2254 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2256 // Added using template syntax, to take <noinclude>'s into account.
2257 $wgOut->addWikiTextTitleTidy(
2258 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2268 * Gets an editable textual representation of $content.
2269 * The textual representation can be turned by into a Content object by the
2270 * toEditContent() method.
2272 * If $content is null or false or a string, $content is returned unchanged.
2274 * If the given Content object is not of a type that can be edited using
2275 * the text base EditPage, an exception will be raised. Set
2276 * $this->allowNonTextContent to true to allow editing of non-textual
2279 * @param Content|null|bool|string $content
2280 * @return string The editable text form of the content.
2282 * @throws MWException If $content is not an instance of TextContent and
2283 * $this->allowNonTextContent is not true.
2285 protected function toEditText( $content ) {
2286 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2290 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2291 throw new MWException( 'This content model is not supported: '
2292 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2295 return $content->serialize( $this->contentFormat
);
2299 * Turns the given text into a Content object by unserializing it.
2301 * If the resulting Content object is not of a type that can be edited using
2302 * the text base EditPage, an exception will be raised. Set
2303 * $this->allowNonTextContent to true to allow editing of non-textual
2306 * @param string|null|bool $text Text to unserialize
2307 * @return Content The content object created from $text. If $text was false
2308 * or null, false resp. null will be returned instead.
2310 * @throws MWException If unserializing the text results in a Content
2311 * object that is not an instance of TextContent and
2312 * $this->allowNonTextContent is not true.
2314 protected function toEditContent( $text ) {
2315 if ( $text === false ||
$text === null ) {
2319 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2320 $this->contentModel
, $this->contentFormat
);
2322 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2323 throw new MWException( 'This content model is not supported: '
2324 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2331 * Send the edit form and related headers to $wgOut
2332 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2333 * during form output near the top, for captchas and the like.
2335 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2336 * use the EditPage::showEditForm:fields hook instead.
2338 function showEditForm( $formCallback = null ) {
2339 global $wgOut, $wgUser;
2341 # need to parse the preview early so that we know which templates are used,
2342 # otherwise users with "show preview after edit box" will get a blank list
2343 # we parse this near the beginning so that setHeaders can do the title
2344 # setting work instead of leaving it in getPreviewText
2345 $previewOutput = '';
2346 if ( $this->formtype
== 'preview' ) {
2347 $previewOutput = $this->getPreviewText();
2350 Hooks
::run( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2352 $this->setHeaders();
2354 if ( $this->showHeader() === false ) {
2358 $wgOut->addHTML( $this->editFormPageTop
);
2360 if ( $wgUser->getOption( 'previewontop' ) ) {
2361 $this->displayPreviewArea( $previewOutput, true );
2364 $wgOut->addHTML( $this->editFormTextTop
);
2366 $showToolbar = true;
2367 if ( $this->wasDeletedSinceLastEdit() ) {
2368 if ( $this->formtype
== 'save' ) {
2369 // Hide the toolbar and edit area, user can click preview to get it back
2370 // Add an confirmation checkbox and explanation.
2371 $showToolbar = false;
2373 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2374 'deletedwhileediting' );
2378 // @todo add EditForm plugin interface and use it here!
2379 // search for textarea1 and textares2, and allow EditForm to override all uses.
2380 $wgOut->addHTML( Html
::openElement(
2383 'id' => self
::EDITFORM_ID
,
2384 'name' => self
::EDITFORM_ID
,
2386 'action' => $this->getActionURL( $this->getContextTitle() ),
2387 'enctype' => 'multipart/form-data'
2391 if ( is_callable( $formCallback ) ) {
2392 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2393 call_user_func_array( $formCallback, array( &$wgOut ) );
2396 // Add an empty field to trip up spambots
2398 Xml
::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2401 array( 'for' => 'wpAntiSpam' ),
2402 wfMessage( 'simpleantispam-label' )->parse()
2408 'name' => 'wpAntispam',
2409 'id' => 'wpAntispam',
2413 . Xml
::closeElement( 'div' )
2416 Hooks
::run( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2418 // Put these up at the top to ensure they aren't lost on early form submission
2419 $this->showFormBeforeText();
2421 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2422 $username = $this->lastDelete
->user_name
;
2423 $comment = $this->lastDelete
->log_comment
;
2425 // It is better to not parse the comment at all than to have templates expanded in the middle
2426 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2427 $key = $comment === ''
2428 ?
'confirmrecreate-noreason'
2429 : 'confirmrecreate';
2431 '<div class="mw-confirm-recreate">' .
2432 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2433 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2434 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2440 # When the summary is hidden, also hide them on preview/show changes
2441 if ( $this->nosummary
) {
2442 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2445 # If a blank edit summary was previously provided, and the appropriate
2446 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2447 # user being bounced back more than once in the event that a summary
2450 # For a bit more sophisticated detection of blank summaries, hash the
2451 # automatic one and pass that in the hidden field wpAutoSummary.
2452 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2453 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2456 if ( $this->undidRev
) {
2457 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2460 if ( $this->selfRedirect
) {
2461 $wgOut->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2464 if ( $this->hasPresetSummary
) {
2465 // If a summary has been preset using &summary= we don't want to prompt for
2466 // a different summary. Only prompt for a summary if the summary is blanked.
2468 $this->autoSumm
= md5( '' );
2471 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2472 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2474 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2475 $wgOut->addHTML( Html
::hidden( 'parentRevId',
2476 $this->parentRevId ?
: $this->mArticle
->getRevIdFetched() ) );
2478 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2479 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2481 if ( $this->section
== 'new' ) {
2482 $this->showSummaryInput( true, $this->summary
);
2483 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2486 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2488 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2489 $wgOut->addHTML( EditPage
::getEditToolbar() );
2492 if ( $this->blankArticle
) {
2493 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2496 if ( $this->isConflict
) {
2497 // In an edit conflict bypass the overridable content form method
2498 // and fallback to the raw wpTextbox1 since editconflicts can't be
2499 // resolved between page source edits and custom ui edits using the
2501 $this->textbox2
= $this->textbox1
;
2503 $content = $this->getCurrentContent();
2504 $this->textbox1
= $this->toEditText( $content );
2506 $this->showTextbox1();
2508 $this->showContentForm();
2511 $wgOut->addHTML( $this->editFormTextAfterContent
);
2513 $this->showStandardInputs();
2515 $this->showFormAfterText();
2517 $this->showTosSummary();
2519 $this->showEditTools();
2521 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2523 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2524 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2526 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2527 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2529 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'limitreport' ),
2530 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2532 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2534 if ( $this->isConflict
) {
2536 $this->showConflict();
2537 } catch ( MWContentSerializationException
$ex ) {
2538 // this can't really happen, but be nice if it does.
2540 'content-failed-to-parse',
2541 $this->contentModel
,
2542 $this->contentFormat
,
2545 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2549 // Marker for detecting truncated form data. This must be the last
2550 // parameter sent in order to be of use, so do not move me.
2551 $wgOut->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2552 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2554 if ( !$wgUser->getOption( 'previewontop' ) ) {
2555 $this->displayPreviewArea( $previewOutput, false );
2561 * Extract the section title from current section text, if any.
2563 * @param string $text
2564 * @return string|bool String or false
2566 public static function extractSectionTitle( $text ) {
2567 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2568 if ( !empty( $matches[2] ) ) {
2570 return $wgParser->stripSectionName( trim( $matches[2] ) );
2579 protected function showHeader() {
2580 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2581 global $wgAllowUserCss, $wgAllowUserJs;
2583 if ( $this->mTitle
->isTalkPage() ) {
2584 $wgOut->addWikiMsg( 'talkpagetext' );
2588 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
2589 if ( count( $editNotices ) ) {
2590 $wgOut->addHTML( implode( "\n", $editNotices ) );
2592 $msg = wfMessage( 'editnotice-notext' );
2593 if ( !$msg->isDisabled() ) {
2595 '<div class="mw-editnotice-notext">'
2596 . $msg->parseAsBlock()
2602 if ( $this->isConflict
) {
2603 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2604 $this->edittime
= $this->mArticle
->getTimestamp();
2606 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2607 // We use $this->section to much before this and getVal('wgSection') directly in other places
2608 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2609 // Someone is welcome to try refactoring though
2610 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2614 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2615 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2616 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2617 if ( $sectionTitle !== false ) {
2618 $this->summary
= "/* $sectionTitle */ ";
2623 if ( $this->missingComment
) {
2624 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2627 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2628 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2631 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2632 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2635 if ( $this->blankArticle
) {
2636 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2639 if ( $this->selfRedirect
) {
2640 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2643 if ( $this->hookError
!== '' ) {
2644 $wgOut->addWikiText( $this->hookError
);
2647 if ( !$this->checkUnicodeCompliantBrowser() ) {
2648 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2651 if ( $this->section
!= 'new' ) {
2652 $revision = $this->mArticle
->getRevisionFetched();
2654 // Let sysop know that this will make private content public if saved
2656 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2657 $wgOut->wrapWikiMsg(
2658 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2659 'rev-deleted-text-permission'
2661 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2662 $wgOut->wrapWikiMsg(
2663 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2664 'rev-deleted-text-view'
2668 if ( !$revision->isCurrent() ) {
2669 $this->mArticle
->setOldSubtitle( $revision->getId() );
2670 $wgOut->addWikiMsg( 'editingold' );
2672 } elseif ( $this->mTitle
->exists() ) {
2673 // Something went wrong
2675 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2676 array( 'missing-revision', $this->oldid
) );
2681 if ( wfReadOnly() ) {
2682 $wgOut->wrapWikiMsg(
2683 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2684 array( 'readonlywarning', wfReadOnlyReason() )
2686 } elseif ( $wgUser->isAnon() ) {
2687 if ( $this->formtype
!= 'preview' ) {
2688 $wgOut->wrapWikiMsg(
2689 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2690 array( 'anoneditwarning',
2692 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2694 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2697 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2698 'anonpreviewwarning'
2702 if ( $this->isCssJsSubpage
) {
2703 # Check the skin exists
2704 if ( $this->isWrongCaseCssJsPage
) {
2705 $wgOut->wrapWikiMsg(
2706 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2707 array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() )
2710 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
2711 if ( $this->formtype
!== 'preview' ) {
2712 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
2713 $wgOut->wrapWikiMsg(
2714 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2715 array( 'usercssyoucanpreview' )
2719 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
2720 $wgOut->wrapWikiMsg(
2721 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2722 array( 'userjsyoucanpreview' )
2730 if ( $this->mTitle
->isProtected( 'edit' ) &&
2731 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2733 # Is the title semi-protected?
2734 if ( $this->mTitle
->isSemiProtected() ) {
2735 $noticeMsg = 'semiprotectedpagewarning';
2737 # Then it must be protected based on static groups (regular)
2738 $noticeMsg = 'protectedpagewarning';
2740 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2741 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2743 if ( $this->mTitle
->isCascadeProtected() ) {
2744 # Is this page under cascading protection from some source pages?
2745 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2746 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2747 $cascadeSourcesCount = count( $cascadeSources );
2748 if ( $cascadeSourcesCount > 0 ) {
2749 # Explain, and list the titles responsible
2750 foreach ( $cascadeSources as $page ) {
2751 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2754 $notice .= '</div>';
2755 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2757 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2758 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2760 'showIfEmpty' => false,
2761 'msgKey' => array( 'titleprotectedwarning' ),
2762 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2765 if ( $this->kblength
=== false ) {
2766 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2769 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2770 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2773 $wgLang->formatNum( $this->kblength
),
2774 $wgLang->formatNum( $wgMaxArticleSize )
2778 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2779 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2782 $wgLang->formatSize( strlen( $this->textbox1
) ),
2783 strlen( $this->textbox1
)
2788 # Add header copyright warning
2789 $this->showHeaderCopyrightWarning();
2795 * Standard summary input and label (wgSummary), abstracted so EditPage
2796 * subclasses may reorganize the form.
2797 * Note that you do not need to worry about the label's for=, it will be
2798 * inferred by the id given to the input. You can remove them both by
2799 * passing array( 'id' => false ) to $userInputAttrs.
2801 * @param string $summary The value of the summary input
2802 * @param string $labelText The html to place inside the label
2803 * @param array $inputAttrs Array of attrs to use on the input
2804 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2806 * @return array An array in the format array( $label, $input )
2808 function getSummaryInput( $summary = "", $labelText = null,
2809 $inputAttrs = null, $spanLabelAttrs = null
2811 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2812 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2813 'id' => 'wpSummary',
2814 'maxlength' => '200',
2817 'spellcheck' => 'true',
2818 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2820 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2821 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2822 'id' => "wpSummaryLabel"
2829 $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null,
2832 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2835 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2837 return array( $label, $input );
2841 * @param bool $isSubjectPreview True if this is the section subject/title
2842 * up top, or false if this is the comment summary
2843 * down below the textarea
2844 * @param string $summary The text of the summary to display
2846 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2847 global $wgOut, $wgContLang;
2848 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2849 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2850 if ( $isSubjectPreview ) {
2851 if ( $this->nosummary
) {
2855 if ( !$this->mShowSummaryField
) {
2859 $summary = $wgContLang->recodeForEdit( $summary );
2860 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2861 list( $label, $input ) = $this->getSummaryInput(
2864 array( 'class' => $summaryClass ),
2867 $wgOut->addHTML( "{$label} {$input}" );
2871 * @param bool $isSubjectPreview True if this is the section subject/title
2872 * up top, or false if this is the comment summary
2873 * down below the textarea
2874 * @param string $summary The text of the summary to display
2877 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2878 // avoid spaces in preview, gets always trimmed on save
2879 $summary = trim( $summary );
2880 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2886 if ( $isSubjectPreview ) {
2887 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2888 ->inContentLanguage()->text();
2891 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2893 $summary = wfMessage( $message )->parse()
2894 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2895 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2898 protected function showFormBeforeText() {
2900 $section = htmlspecialchars( $this->section
);
2901 $wgOut->addHTML( <<<HTML
2902 <input type='hidden' value="{$section}" name="wpSection"/>
2903 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2904 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2905 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2909 if ( !$this->checkUnicodeCompliantBrowser() ) {
2910 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2914 protected function showFormAfterText() {
2915 global $wgOut, $wgUser;
2917 * To make it harder for someone to slip a user a page
2918 * which submits an edit form to the wiki without their
2919 * knowledge, a random token is associated with the login
2920 * session. If it's not passed back with the submission,
2921 * we won't save the page, or render user JavaScript and
2924 * For anon editors, who may not have a session, we just
2925 * include the constant suffix to prevent editing from
2926 * broken text-mangling proxies.
2928 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2932 * Subpage overridable method for printing the form for page content editing
2933 * By default this simply outputs wpTextbox1
2934 * Subclasses can override this to provide a custom UI for editing;
2935 * be it a form, or simply wpTextbox1 with a modified content that will be
2936 * reverse modified when extracted from the post data.
2937 * Note that this is basically the inverse for importContentFormData
2939 protected function showContentForm() {
2940 $this->showTextbox1();
2944 * Method to output wpTextbox1
2945 * The $textoverride method can be used by subclasses overriding showContentForm
2946 * to pass back to this method.
2948 * @param array $customAttribs Array of html attributes to use in the textarea
2949 * @param string $textoverride Optional text to override $this->textarea1 with
2951 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2952 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2953 $attribs = array( 'style' => 'display:none;' );
2955 $classes = array(); // Textarea CSS
2956 if ( $this->mTitle
->isProtected( 'edit' ) &&
2957 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2959 # Is the title semi-protected?
2960 if ( $this->mTitle
->isSemiProtected() ) {
2961 $classes[] = 'mw-textarea-sprotected';
2963 # Then it must be protected based on static groups (regular)
2964 $classes[] = 'mw-textarea-protected';
2966 # Is the title cascade-protected?
2967 if ( $this->mTitle
->isCascadeProtected() ) {
2968 $classes[] = 'mw-textarea-cprotected';
2972 $attribs = array( 'tabindex' => 1 );
2974 if ( is_array( $customAttribs ) ) {
2975 $attribs +
= $customAttribs;
2978 if ( count( $classes ) ) {
2979 if ( isset( $attribs['class'] ) ) {
2980 $classes[] = $attribs['class'];
2982 $attribs['class'] = implode( ' ', $classes );
2987 $textoverride !== null ?
$textoverride : $this->textbox1
,
2993 protected function showTextbox2() {
2994 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2997 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2998 global $wgOut, $wgUser;
3000 $wikitext = $this->safeUnicodeOutput( $text );
3001 if ( strval( $wikitext ) !== '' ) {
3002 // Ensure there's a newline at the end, otherwise adding lines
3004 // But don't add a newline if the ext is empty, or Firefox in XHTML
3005 // mode will show an extra newline. A bit annoying.
3009 $attribs = $customAttribs +
array(
3012 'cols' => $wgUser->getIntOption( 'cols' ),
3013 'rows' => $wgUser->getIntOption( 'rows' ),
3014 // Avoid PHP notices when appending preferences
3015 // (appending allows customAttribs['style'] to still work).
3019 $pageLang = $this->mTitle
->getPageLanguage();
3020 $attribs['lang'] = $pageLang->getHtmlCode();
3021 $attribs['dir'] = $pageLang->getDir();
3023 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3026 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3030 $classes[] = 'ontop';
3033 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3035 if ( $this->formtype
!= 'preview' ) {
3036 $attribs['style'] = 'display: none;';
3039 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
3041 if ( $this->formtype
== 'preview' ) {
3042 $this->showPreview( $previewOutput );
3044 // Empty content container for LivePreview
3045 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3046 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3047 'class' => 'mw-content-' . $pageViewLang->getDir() );
3048 $wgOut->addHTML( Html
::rawElement( 'div', $attribs ) );
3051 $wgOut->addHTML( '</div>' );
3053 if ( $this->formtype
== 'diff' ) {
3056 } catch ( MWContentSerializationException
$ex ) {
3058 'content-failed-to-parse',
3059 $this->contentModel
,
3060 $this->contentFormat
,
3063 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3069 * Append preview output to $wgOut.
3070 * Includes category rendering if this is a category page.
3072 * @param string $text The HTML to be output for the preview.
3074 protected function showPreview( $text ) {
3076 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3077 $this->mArticle
->openShowCategory();
3079 # This hook seems slightly odd here, but makes things more
3080 # consistent for extensions.
3081 Hooks
::run( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3082 $wgOut->addHTML( $text );
3083 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3084 $this->mArticle
->closeShowCategory();
3089 * Get a diff between the current contents of the edit box and the
3090 * version of the page we're editing from.
3092 * If this is a section edit, we'll replace the section as for final
3093 * save and then make a comparison.
3095 function showDiff() {
3096 global $wgUser, $wgContLang, $wgOut;
3098 $oldtitlemsg = 'currentrev';
3099 # if message does not exist, show diff against the preloaded default
3100 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3101 $oldtext = $this->mTitle
->getDefaultMessageText();
3102 if ( $oldtext !== false ) {
3103 $oldtitlemsg = 'defaultmessagetext';
3104 $oldContent = $this->toEditContent( $oldtext );
3109 $oldContent = $this->getCurrentContent();
3112 $textboxContent = $this->toEditContent( $this->textbox1
);
3114 $newContent = $this->mArticle
->replaceSectionContent(
3115 $this->section
, $textboxContent,
3116 $this->summary
, $this->edittime
);
3118 if ( $newContent ) {
3119 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3120 Hooks
::run( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3122 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
3123 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
3126 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3127 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3128 $newtitle = wfMessage( 'yourtext' )->parse();
3130 if ( !$oldContent ) {
3131 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3134 if ( !$newContent ) {
3135 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3138 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3139 $de->setContent( $oldContent, $newContent );
3141 $difftext = $de->getDiff( $oldtitle, $newtitle );
3142 $de->showDiffStyle();
3147 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3151 * Show the header copyright warning.
3153 protected function showHeaderCopyrightWarning() {
3154 $msg = 'editpage-head-copy-warn';
3155 if ( !wfMessage( $msg )->isDisabled() ) {
3157 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3158 'editpage-head-copy-warn' );
3163 * Give a chance for site and per-namespace customizations of
3164 * terms of service summary link that might exist separately
3165 * from the copyright notice.
3167 * This will display between the save button and the edit tools,
3168 * so should remain short!
3170 protected function showTosSummary() {
3171 $msg = 'editpage-tos-summary';
3172 Hooks
::run( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
3173 if ( !wfMessage( $msg )->isDisabled() ) {
3175 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3176 $wgOut->addWikiMsg( $msg );
3177 $wgOut->addHTML( '</div>' );
3181 protected function showEditTools() {
3183 $wgOut->addHTML( '<div class="mw-editTools">' .
3184 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3189 * Get the copyright warning
3191 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3194 protected function getCopywarn() {
3195 return self
::getCopyrightWarning( $this->mTitle
);
3199 * Get the copyright warning, by default returns wikitext
3201 * @param Title $title
3202 * @param string $format Output format, valid values are any function of a Message object
3205 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3206 global $wgRightsText;
3207 if ( $wgRightsText ) {
3208 $copywarnMsg = array( 'copyrightwarning',
3209 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3212 $copywarnMsg = array( 'copyrightwarning2',
3213 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3215 // Allow for site and per-namespace customization of contribution/copyright notice.
3216 Hooks
::run( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3218 return "<div id=\"editpage-copywarn\">\n" .
3219 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3223 * Get the Limit report for page previews
3226 * @param ParserOutput $output ParserOutput object from the parse
3227 * @return string HTML
3229 public static function getPreviewLimitReport( $output ) {
3230 if ( !$output ||
!$output->getLimitReportData() ) {
3234 $limitReport = Html
::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3235 wfMessage( 'limitreport-title' )->parseAsBlock()
3238 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3239 $limitReport .= Html
::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3241 $limitReport .= Html
::openElement( 'table', array(
3242 'class' => 'preview-limit-report wikitable'
3244 Html
::openElement( 'tbody' );
3246 foreach ( $output->getLimitReportData() as $key => $value ) {
3247 if ( Hooks
::run( 'ParserLimitReportFormat',
3248 array( $key, &$value, &$limitReport, true, true )
3250 $keyMsg = wfMessage( $key );
3251 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3252 if ( !$valueMsg->exists() ) {
3253 $valueMsg = new RawMessage( '$1' );
3255 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3256 $limitReport .= Html
::openElement( 'tr' ) .
3257 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3258 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3259 Html
::closeElement( 'tr' );
3264 $limitReport .= Html
::closeElement( 'tbody' ) .
3265 Html
::closeElement( 'table' ) .
3266 Html
::closeElement( 'div' );
3268 return $limitReport;
3271 protected function showStandardInputs( &$tabindex = 2 ) {
3273 $wgOut->addHTML( "<div class='editOptions'>\n" );
3275 if ( $this->section
!= 'new' ) {
3276 $this->showSummaryInput( false, $this->summary
);
3277 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3280 $checkboxes = $this->getCheckboxes( $tabindex,
3281 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
3282 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3284 // Show copyright warning.
3285 $wgOut->addWikiText( $this->getCopywarn() );
3286 $wgOut->addHTML( $this->editFormTextAfterWarn
);
3288 $wgOut->addHTML( "<div class='editButtons'>\n" );
3289 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3291 $cancel = $this->getCancelLink();
3292 if ( $cancel !== '' ) {
3293 $cancel .= Html
::element( 'span',
3294 array( 'class' => 'mw-editButtons-pipe-separator' ),
3295 wfMessage( 'pipe-separator' )->text() );
3298 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3299 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3301 'target' => 'helpwindow',
3302 'href' => $edithelpurl,
3304 $edithelp = Html
::linkButton( wfMessage( 'edithelp' )->text(),
3305 $attrs, array( 'mw-ui-quiet' ) ) .
3306 wfMessage( 'word-separator' )->escaped() .
3307 wfMessage( 'newwindow' )->parse();
3309 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3310 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3311 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3313 Hooks
::run( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3315 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3319 * Show an edit conflict. textbox1 is already shown in showEditForm().
3320 * If you want to use another entry point to this function, be careful.
3322 protected function showConflict() {
3325 if ( Hooks
::run( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3326 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3328 $content1 = $this->toEditContent( $this->textbox1
);
3329 $content2 = $this->toEditContent( $this->textbox2
);
3331 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3332 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3333 $de->setContent( $content2, $content1 );
3335 wfMessage( 'yourtext' )->parse(),
3336 wfMessage( 'storedversion' )->text()
3339 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3340 $this->showTextbox2();
3347 public function getCancelLink() {
3348 $cancelParams = array();
3349 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3350 $cancelParams['oldid'] = $this->oldid
;
3352 $attrs = array( 'id' => 'mw-editform-cancel' );
3354 return Linker
::linkKnown(
3355 $this->getContextTitle(),
3356 wfMessage( 'cancel' )->parse(),
3357 Html
::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3363 * Returns the URL to use in the form's action attribute.
3364 * This is used by EditPage subclasses when simply customizing the action
3365 * variable in the constructor is not enough. This can be used when the
3366 * EditPage lives inside of a Special page rather than a custom page action.
3368 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3371 protected function getActionURL( Title
$title ) {
3372 return $title->getLocalURL( array( 'action' => $this->action
) );
3376 * Check if a page was deleted while the user was editing it, before submit.
3377 * Note that we rely on the logging table, which hasn't been always there,
3378 * but that doesn't matter, because this only applies to brand new
3382 protected function wasDeletedSinceLastEdit() {
3383 if ( $this->deletedSinceEdit
!== null ) {
3384 return $this->deletedSinceEdit
;
3387 $this->deletedSinceEdit
= false;
3389 if ( $this->mTitle
->isDeletedQuick() ) {
3390 $this->lastDelete
= $this->getLastDelete();
3391 if ( $this->lastDelete
) {
3392 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3393 if ( $deleteTime > $this->starttime
) {
3394 $this->deletedSinceEdit
= true;
3399 return $this->deletedSinceEdit
;
3403 * @return bool|stdClass
3405 protected function getLastDelete() {
3406 $dbr = wfGetDB( DB_SLAVE
);
3407 $data = $dbr->selectRow(
3408 array( 'logging', 'user' ),
3421 'log_namespace' => $this->mTitle
->getNamespace(),
3422 'log_title' => $this->mTitle
->getDBkey(),
3423 'log_type' => 'delete',
3424 'log_action' => 'delete',
3428 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3430 // Quick paranoid permission checks...
3431 if ( is_object( $data ) ) {
3432 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3433 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
3436 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3437 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
3445 * Get the rendered text for previewing.
3446 * @throws MWException
3449 function getPreviewText() {
3450 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3451 global $wgAllowUserCss, $wgAllowUserJs;
3453 if ( $wgRawHtml && !$this->mTokenOk
) {
3454 // Could be an offsite preview attempt. This is very unsafe if
3455 // HTML is enabled, as it could be an attack.
3457 if ( $this->textbox1
!== '' ) {
3458 // Do not put big scary notice, if previewing the empty
3459 // string, which happens when you initially edit
3460 // a category page, due to automatic preview-on-open.
3461 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3462 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3470 $content = $this->toEditContent( $this->textbox1
);
3474 'AlternateEditPreview',
3475 array( $this, &$content, &$previewHTML, &$this->mParserOutput
) )
3477 return $previewHTML;
3480 # provide a anchor link to the editform
3481 $continueEditing = '<span class="mw-continue-editing">' .
3482 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3483 wfMessage( 'continue-editing' )->text() . ']]</span>';
3484 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3485 if ( $this->mTokenOkExceptSuffix
) {
3486 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3488 $note = wfMessage( 'session_fail_preview' )->plain();
3490 } elseif ( $this->incompleteForm
) {
3491 $note = wfMessage( 'edit_form_incomplete' )->plain();
3493 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3496 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
3497 $parserOptions->setIsPreview( true );
3498 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3500 # don't parse non-wikitext pages, show message about preview
3501 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3502 if ( $this->mTitle
->isCssJsSubpage() ) {
3504 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3510 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3512 if ( $level === 'user' && !$wgAllowUserCss ) {
3515 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3517 if ( $level === 'user' && !$wgAllowUserJs ) {
3524 # Used messages to make sure grep find them:
3525 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3526 if ( $level && $format ) {
3527 $note = "<div id='mw-{$level}{$format}preview'>" .
3528 wfMessage( "{$level}{$format}preview" )->text() .
3529 ' ' . $continueEditing . "</div>";
3533 # If we're adding a comment, we need to show the
3534 # summary as the headline
3535 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3536 $content = $content->addSectionHeader( $this->summary
);
3539 $hook_args = array( $this, &$content );
3540 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3541 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3543 $parserOptions->enableLimitReport();
3545 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3546 # But it's now deprecated, so never mind
3548 $pstContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3549 $scopedCallback = $parserOptions->setupFakeRevision(
3550 $this->mTitle
, $pstContent, $wgUser );
3551 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3553 # Try to stash the edit for the final submission step
3554 # @todo: different date format preferences cause cache misses
3555 ApiStashEdit
::stashEditFromPreview(
3556 $this->getArticle(), $content, $pstContent,
3557 $parserOutput, $parserOptions, $parserOptions, wfTimestampNow()
3560 $parserOutput->setEditSectionTokens( false ); // no section edit links
3561 $previewHTML = $parserOutput->getText();
3562 $this->mParserOutput
= $parserOutput;
3563 $wgOut->addParserOutputMetadata( $parserOutput );
3565 if ( count( $parserOutput->getWarnings() ) ) {
3566 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3568 } catch ( MWContentSerializationException
$ex ) {
3570 'content-failed-to-parse',
3571 $this->contentModel
,
3572 $this->contentFormat
,
3575 $note .= "\n\n" . $m->parse();
3579 if ( $this->isConflict
) {
3580 $conflict = '<h2 id="mw-previewconflict">'
3581 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3583 $conflict = '<hr />';
3586 $previewhead = "<div class='previewnote'>\n" .
3587 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3588 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3590 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3591 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3592 'class' => 'mw-content-' . $pageViewLang->getDir() );
3593 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3595 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3601 function getTemplates() {
3602 if ( $this->preview ||
$this->section
!= '' ) {
3603 $templates = array();
3604 if ( !isset( $this->mParserOutput
) ) {
3607 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3608 foreach ( array_keys( $template ) as $dbk ) {
3609 $templates[] = Title
::makeTitle( $ns, $dbk );
3614 return $this->mTitle
->getTemplateLinksFrom();
3619 * Shows a bulletin board style toolbar for common editing functions.
3620 * It can be disabled in the user preferences.
3624 static function getEditToolbar() {
3625 global $wgContLang, $wgOut;
3626 global $wgEnableUploads, $wgForeignFileRepos;
3628 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3631 * $toolarray is an array of arrays each of which includes the
3632 * opening tag, the closing tag, optionally a sample text that is
3633 * inserted between the two when no selection is highlighted
3634 * and. The tip text is shown when the user moves the mouse
3637 * Images are defined in ResourceLoaderEditToolbarModule.
3641 'id' => 'mw-editbutton-bold',
3643 'close' => '\'\'\'',
3644 'sample' => wfMessage( 'bold_sample' )->text(),
3645 'tip' => wfMessage( 'bold_tip' )->text(),
3648 'id' => 'mw-editbutton-italic',
3651 'sample' => wfMessage( 'italic_sample' )->text(),
3652 'tip' => wfMessage( 'italic_tip' )->text(),
3655 'id' => 'mw-editbutton-link',
3658 'sample' => wfMessage( 'link_sample' )->text(),
3659 'tip' => wfMessage( 'link_tip' )->text(),
3662 'id' => 'mw-editbutton-extlink',
3665 'sample' => wfMessage( 'extlink_sample' )->text(),
3666 'tip' => wfMessage( 'extlink_tip' )->text(),
3669 'id' => 'mw-editbutton-headline',
3672 'sample' => wfMessage( 'headline_sample' )->text(),
3673 'tip' => wfMessage( 'headline_tip' )->text(),
3675 $imagesAvailable ?
array(
3676 'id' => 'mw-editbutton-image',
3677 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3679 'sample' => wfMessage( 'image_sample' )->text(),
3680 'tip' => wfMessage( 'image_tip' )->text(),
3682 $imagesAvailable ?
array(
3683 'id' => 'mw-editbutton-media',
3684 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3686 'sample' => wfMessage( 'media_sample' )->text(),
3687 'tip' => wfMessage( 'media_tip' )->text(),
3690 'id' => 'mw-editbutton-nowiki',
3691 'open' => "<nowiki>",
3692 'close' => "</nowiki>",
3693 'sample' => wfMessage( 'nowiki_sample' )->text(),
3694 'tip' => wfMessage( 'nowiki_tip' )->text(),
3697 'id' => 'mw-editbutton-signature',
3701 'tip' => wfMessage( 'sig_tip' )->text(),
3704 'id' => 'mw-editbutton-hr',
3705 'open' => "\n----\n",
3708 'tip' => wfMessage( 'hr_tip' )->text(),
3712 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3713 foreach ( $toolarray as $tool ) {
3719 // Images are defined in ResourceLoaderEditToolbarModule
3721 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3722 // Older browsers show a "speedtip" type message only for ALT.
3723 // Ideally these should be different, realistically they
3724 // probably don't need to be.
3732 $script .= Xml
::encodeJsCall(
3733 'mw.toolbar.addButton',
3735 ResourceLoader
::inDebugMode()
3740 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3742 $toolbar = '<div id="toolbar"></div>';
3744 Hooks
::run( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3750 * Returns an array of html code of the following checkboxes:
3753 * @param int $tabindex Current tabindex
3754 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3755 * status of the checkbox
3759 public function getCheckboxes( &$tabindex, $checked ) {
3760 global $wgUser, $wgUseMediaWikiUIEverywhere;
3762 $checkboxes = array();
3764 // don't show the minor edit checkbox if it's a new page or section
3765 if ( !$this->isNew
) {
3766 $checkboxes['minor'] = '';
3767 $minorLabel = wfMessage( 'minoredit' )->parse();
3768 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3770 'tabindex' => ++
$tabindex,
3771 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3772 'id' => 'wpMinoredit',
3775 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3776 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3777 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3778 ">{$minorLabel}</label>";
3780 if ( $wgUseMediaWikiUIEverywhere ) {
3781 $checkboxes['minor'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3783 Html
::closeElement( 'div' );
3785 $checkboxes['minor'] = $minorEditHtml;
3790 $watchLabel = wfMessage( 'watchthis' )->parse();
3791 $checkboxes['watch'] = '';
3792 if ( $wgUser->isLoggedIn() ) {
3794 'tabindex' => ++
$tabindex,
3795 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3796 'id' => 'wpWatchthis',
3799 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3800 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3801 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3802 ">{$watchLabel}</label>";
3803 if ( $wgUseMediaWikiUIEverywhere ) {
3804 $checkboxes['watch'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3806 Html
::closeElement( 'div' );
3808 $checkboxes['watch'] = $watchThisHtml;
3811 Hooks
::run( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3816 * Returns an array of html code of the following buttons:
3817 * save, diff, preview and live
3819 * @param int $tabindex Current tabindex
3823 public function getEditButtons( &$tabindex ) {
3829 'tabindex' => ++
$tabindex,
3830 ) + Linker
::tooltipAndAccesskeyAttribs( 'save' );
3831 $buttons['save'] = Html
::submitButton( wfMessage( 'savearticle' )->text(),
3832 $attribs, array( 'mw-ui-constructive' ) );
3834 ++
$tabindex; // use the same for preview and live preview
3836 'id' => 'wpPreview',
3837 'name' => 'wpPreview',
3838 'tabindex' => $tabindex,
3839 ) + Linker
::tooltipAndAccesskeyAttribs( 'preview' );
3840 $buttons['preview'] = Html
::submitButton( wfMessage( 'showpreview' )->text(),
3842 $buttons['live'] = '';
3847 'tabindex' => ++
$tabindex,
3848 ) + Linker
::tooltipAndAccesskeyAttribs( 'diff' );
3849 $buttons['diff'] = Html
::submitButton( wfMessage( 'showdiff' )->text(),
3852 Hooks
::run( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3857 * Creates a basic error page which informs the user that
3858 * they have attempted to edit a nonexistent section.
3860 function noSuchSectionPage() {
3863 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3865 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3866 Hooks
::run( 'EditPageNoSuchSection', array( &$this, &$res ) );
3867 $wgOut->addHTML( $res );
3869 $wgOut->returnToMain( false, $this->mTitle
);
3873 * Show "your edit contains spam" page with your diff and text
3875 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3877 public function spamPageWithContent( $match = false ) {
3878 global $wgOut, $wgLang;
3879 $this->textbox2
= $this->textbox1
;
3881 if ( is_array( $match ) ) {
3882 $match = $wgLang->listToText( $match );
3884 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3886 $wgOut->addHTML( '<div id="spamprotected">' );
3887 $wgOut->addWikiMsg( 'spamprotectiontext' );
3889 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3891 $wgOut->addHTML( '</div>' );
3893 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3896 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3897 $this->showTextbox2();
3899 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3903 * Check if the browser is on a blacklist of user-agents known to
3904 * mangle UTF-8 data on form submission. Returns true if Unicode
3905 * should make it through, false if it's known to be a problem.
3908 private function checkUnicodeCompliantBrowser() {
3909 global $wgBrowserBlackList, $wgRequest;
3911 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3912 if ( $currentbrowser === false ) {
3913 // No User-Agent header sent? Trust it by default...
3917 foreach ( $wgBrowserBlackList as $browser ) {
3918 if ( preg_match( $browser, $currentbrowser ) ) {
3926 * Filter an input field through a Unicode de-armoring process if it
3927 * came from an old browser with known broken Unicode editing issues.
3929 * @param WebRequest $request
3930 * @param string $field
3933 protected function safeUnicodeInput( $request, $field ) {
3934 $text = rtrim( $request->getText( $field ) );
3935 return $request->getBool( 'safemode' )
3936 ?
$this->unmakeSafe( $text )
3941 * Filter an output field through a Unicode armoring process if it is
3942 * going to an old browser with known broken Unicode editing issues.
3944 * @param string $text
3947 protected function safeUnicodeOutput( $text ) {
3949 $codedText = $wgContLang->recodeForEdit( $text );
3950 return $this->checkUnicodeCompliantBrowser()
3952 : $this->makeSafe( $codedText );
3956 * A number of web browsers are known to corrupt non-ASCII characters
3957 * in a UTF-8 text editing environment. To protect against this,
3958 * detected browsers will be served an armored version of the text,
3959 * with non-ASCII chars converted to numeric HTML character references.
3961 * Preexisting such character references will have a 0 added to them
3962 * to ensure that round-trips do not alter the original data.
3964 * @param string $invalue
3967 private function makeSafe( $invalue ) {
3968 // Armor existing references for reversibility.
3969 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3974 $valueLength = strlen( $invalue );
3975 for ( $i = 0; $i < $valueLength; $i++
) {
3976 $bytevalue = ord( $invalue[$i] );
3977 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3978 $result .= chr( $bytevalue );
3980 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3981 $working = $working << 6;
3982 $working +
= ( $bytevalue & 0x3F );
3984 if ( $bytesleft <= 0 ) {
3985 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3987 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3988 $working = $bytevalue & 0x1F;
3990 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3991 $working = $bytevalue & 0x0F;
3993 } else { // 1111 0xxx
3994 $working = $bytevalue & 0x07;
4002 * Reverse the previously applied transliteration of non-ASCII characters
4003 * back to UTF-8. Used to protect data from corruption by broken web browsers
4004 * as listed in $wgBrowserBlackList.
4006 * @param string $invalue
4009 private function unmakeSafe( $invalue ) {
4011 $valueLength = strlen( $invalue );
4012 for ( $i = 0; $i < $valueLength; $i++
) {
4013 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4017 $hexstring .= $invalue[$i];
4019 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4021 // Do some sanity checks. These aren't needed for reversibility,
4022 // but should help keep the breakage down if the editor
4023 // breaks one of the entities whilst editing.
4024 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4025 $codepoint = hexdec( $hexstring );
4026 $result .= UtfNormal\Utils
::codepointToUtf8( $codepoint );
4028 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4031 $result .= substr( $invalue, $i, 1 );
4034 // reverse the transform that we made for reversibility reasons.
4035 return strtr( $result, array( "�" => "&#x" ) );