3 * Page edition user interface.
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.
41 * Status: Article successfully updated
43 const AS_SUCCESS_UPDATE
= 200;
46 * Status: Article successfully created
48 const AS_SUCCESS_NEW_ARTICLE
= 201;
51 * Status: Article update aborted by a hook function
53 const AS_HOOK_ERROR
= 210;
56 * Status: A hook function returned an error
58 const AS_HOOK_ERROR_EXPECTED
= 212;
61 * Status: User is blocked from editing this page
63 const AS_BLOCKED_PAGE_FOR_USER
= 215;
66 * Status: Content too big (> $wgMaxArticleSize)
68 const AS_CONTENT_TOO_BIG
= 216;
71 * Status: User cannot edit? (not used)
73 const AS_USER_CANNOT_EDIT
= 217;
76 * Status: this anonymous user is not allowed to edit this page
78 const AS_READ_ONLY_PAGE_ANON
= 218;
81 * Status: this logged in user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_LOGGED
= 219;
86 * Status: wiki is in readonly mode (wfReadOnly() == true)
88 const AS_READ_ONLY_PAGE
= 220;
91 * Status: rate limiter for action 'edit' was tripped
93 const AS_RATE_LIMITED
= 221;
96 * Status: article was deleted while editing and param wpRecreate == false or form
99 const AS_ARTICLE_WAS_DELETED
= 222;
102 * Status: user tried to create this page, but is not allowed to do that
103 * ( Title->userCan('create') == false )
105 const AS_NO_CREATE_PERMISSION
= 223;
108 * Status: user tried to create a blank page
110 const AS_BLANK_ARTICLE
= 224;
113 * Status: (non-resolvable) edit conflict
115 const AS_CONFLICT_DETECTED
= 225;
118 * Status: no edit summary given and the user has forceeditsummary set and the user is not
119 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
121 const AS_SUMMARY_NEEDED
= 226;
124 * Status: user tried to create a new section without content
126 const AS_TEXTBOX_EMPTY
= 228;
129 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
131 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
139 * Status: WikiPage::doEdit() was unsuccessful
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
146 const AS_SPAM_ERROR
= 232;
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
151 const AS_IMAGE_REDIRECT_ANON
= 233;
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
156 const AS_IMAGE_REDIRECT_LOGGED
= 234;
159 * Status: can't parse content
161 const AS_PARSE_ERROR
= 240;
164 * HTML id and name for the beginning of the edit form.
166 const EDITFORM_ID
= 'editform';
169 * Prefix of key for cookie used to pass post-edit state.
170 * The revision id edited is added after this
172 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
175 * Duration of PostEdit cookie, in seconds.
176 * The cookie will be removed instantly if the JavaScript runs.
178 * Otherwise, though, we don't want the cookies to accumulate.
179 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible limit of only 20 cookies per domain.
180 * This still applies at least to some versions of IE without full updates:
181 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
183 * A value of 20 minutes should be enough to take into account slow loads and minor
184 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
186 const POST_EDIT_COOKIE_DURATION
= 1200;
197 private $mContextTitle = null;
198 var $action = 'submit';
199 var $isConflict = false;
200 var $isCssJsSubpage = false;
201 var $isCssSubpage = false;
202 var $isJsSubpage = false;
203 var $isWrongCaseCssJsPage = false;
204 var $isNew = false; // new page or new section
205 var $deletedSinceEdit;
209 var $mTokenOk = false;
210 var $mTokenOkExceptSuffix = false;
211 var $mTriedSave = false;
212 var $incompleteForm = false;
214 var $kblength = false;
215 var $missingComment = false;
216 var $missingSummary = false;
217 var $allowBlankSummary = false;
220 #var $mPreviewTemplates;
228 * Has a summary been preset using GET parameter &summary= ?
231 var $hasPresetSummary = false;
233 var $mBaseRevision = false;
234 var $mShowSummaryField = true;
237 var $save = false, $preview = false, $diff = false;
238 var $minoredit = false, $watchthis = false, $recreate = false;
239 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
240 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
241 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
242 var $contentModel = null, $contentFormat = null;
244 # Placeholders for text injection by hooks (must be HTML)
245 # extensions should take care to _append_ to the present value
246 public $editFormPageTop = ''; // Before even the preview
247 public $editFormTextTop = '';
248 public $editFormTextBeforeContent = '';
249 public $editFormTextAfterWarn = '';
250 public $editFormTextAfterTools = '';
251 public $editFormTextBottom = '';
252 public $editFormTextAfterContent = '';
253 public $previewTextAfterContent = '';
254 public $mPreloadContent = null;
256 /* $didSave should be set to true whenever an article was successfully altered. */
257 public $didSave = false;
258 public $undidRev = 0;
260 public $suppressIntro = false;
263 * Set to true to allow editing of non-text content types.
267 public $allowNonTextContent = false;
270 * @param $article Article
272 public function __construct( Article
$article ) {
273 $this->mArticle
= $article;
274 $this->mTitle
= $article->getTitle();
276 $this->contentModel
= $this->mTitle
->getContentModel();
278 $handler = ContentHandler
::getForModelID( $this->contentModel
);
279 $this->contentFormat
= $handler->getDefaultFormat();
285 public function getArticle() {
286 return $this->mArticle
;
293 public function getTitle() {
294 return $this->mTitle
;
298 * Set the context Title object
300 * @param $title Title object or null
302 public function setContextTitle( $title ) {
303 $this->mContextTitle
= $title;
307 * Get the context title object.
308 * If not set, $wgTitle will be returned. This behavior might change in
309 * the future to return $this->mTitle instead.
311 * @return Title object
313 public function getContextTitle() {
314 if ( is_null( $this->mContextTitle
) ) {
318 return $this->mContextTitle
;
323 * Returns if the given content model is editable.
325 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
327 * @throws MWException if $modelId has no known handler
329 public function isSupportedContentModel( $modelId ) {
330 return $this->allowNonTextContent ||
331 ContentHandler
::getForModelID( $modelId ) instanceof TextContentHandler
;
339 * This is the function that gets called for "action=edit". It
340 * sets up various member variables, then passes execution to
341 * another function, usually showEditForm()
343 * The edit form is self-submitting, so that when things like
344 * preview and edit conflicts occur, we get the same form back
345 * with the extra stuff added. Only when the final submission
346 * is made and all is well do we actually save and redirect to
347 * the newly-edited page.
350 global $wgOut, $wgRequest, $wgUser;
351 // Allow extensions to modify/prevent this form or submission
352 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
356 wfProfileIn( __METHOD__
);
357 wfDebug( __METHOD__
. ": enter\n" );
359 // If they used redlink=1 and the page exists, redirect to the main article
360 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
361 $wgOut->redirect( $this->mTitle
->getFullURL() );
362 wfProfileOut( __METHOD__
);
366 $this->importFormData( $wgRequest );
367 $this->firsttime
= false;
370 $this->livePreview();
371 wfProfileOut( __METHOD__
);
375 if ( wfReadOnly() && $this->save
) {
378 $this->preview
= true;
382 $this->formtype
= 'save';
383 } elseif ( $this->preview
) {
384 $this->formtype
= 'preview';
385 } elseif ( $this->diff
) {
386 $this->formtype
= 'diff';
387 } else { # First time through
388 $this->firsttime
= true;
389 if ( $this->previewOnOpen() ) {
390 $this->formtype
= 'preview';
392 $this->formtype
= 'initial';
396 $permErrors = $this->getEditPermissionErrors();
398 wfDebug( __METHOD__
. ": User can't edit\n" );
399 // Auto-block user's IP if the account was "hard" blocked
400 $wgUser->spreadAnyEditBlock();
402 $this->displayPermissionsError( $permErrors );
404 wfProfileOut( __METHOD__
);
408 wfProfileIn( __METHOD__
. "-business-end" );
410 $this->isConflict
= false;
411 // css / js subpages of user pages get a special treatment
412 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
413 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
414 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
415 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
417 # Show applicable editing introductions
418 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
422 # Attempt submission here. This will check for edit conflicts,
423 # and redundantly check for locked database, blocked IPs, etc.
424 # that edit() already checked just in case someone tries to sneak
425 # in the back door with a hand-edited submission URL.
427 if ( 'save' == $this->formtype
) {
428 if ( !$this->attemptSave() ) {
429 wfProfileOut( __METHOD__
. "-business-end" );
430 wfProfileOut( __METHOD__
);
435 # First time through: get contents, set time for conflict
437 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
438 if ( $this->initialiseForm() === false ) {
439 $this->noSuchSectionPage();
440 wfProfileOut( __METHOD__
. "-business-end" );
441 wfProfileOut( __METHOD__
);
445 if ( !$this->mTitle
->getArticleID() ) {
446 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
448 wfRunHooks( 'EditFormInitialText', array( $this ) );
453 $this->showEditForm();
454 wfProfileOut( __METHOD__
. "-business-end" );
455 wfProfileOut( __METHOD__
);
461 protected function getEditPermissionErrors() {
463 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
464 # Can this title be created?
465 if ( !$this->mTitle
->exists() ) {
466 $permErrors = array_merge( $permErrors,
467 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
469 # Ignore some permissions errors when a user is just previewing/viewing diffs
471 foreach ( $permErrors as $error ) {
472 if ( ( $this->preview ||
$this->diff
)
473 && ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' )
478 $permErrors = wfArrayDiff2( $permErrors, $remove );
483 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
484 * but with the following differences:
485 * - If redlink=1, the user will be redirected to the page
486 * - If there is content to display or the error occurs while either saving,
487 * previewing or showing the difference, it will be a
488 * "View source for ..." page displaying the source code after the error message.
491 * @param array $permErrors of permissions errors, as returned by
492 * Title::getUserPermissionsErrors().
493 * @throws PermissionsError
495 protected function displayPermissionsError( array $permErrors ) {
496 global $wgRequest, $wgOut;
498 if ( $wgRequest->getBool( 'redlink' ) ) {
499 // The edit page was reached via a red link.
500 // Redirect to the article page and let them click the edit tab if
501 // they really want a permission error.
502 $wgOut->redirect( $this->mTitle
->getFullURL() );
506 $content = $this->getContentObject();
508 # Use the normal message if there's nothing to display
509 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
510 $action = $this->mTitle
->exists() ?
'edit' :
511 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
512 throw new PermissionsError( $action, $permErrors );
515 $wgOut->setRobotPolicy( 'noindex,nofollow' );
516 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
517 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
518 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
519 $wgOut->addHTML( "<hr />\n" );
521 # If the user made changes, preserve them when showing the markup
522 # (This happens when a user is blocked during edit, for instance)
523 if ( !$this->firsttime
) {
524 $text = $this->textbox1
;
525 $wgOut->addWikiMsg( 'viewyourtext' );
527 $text = $this->toEditText( $content );
528 $wgOut->addWikiMsg( 'viewsourcetext' );
531 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
533 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
534 Linker
::formatTemplates( $this->getTemplates() ) ) );
536 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
538 if ( $this->mTitle
->exists() ) {
539 $wgOut->returnToMain( null, $this->mTitle
);
544 * Show a read-only error
545 * Parameters are the same as OutputPage:readOnlyPage()
546 * Redirect to the article page if redlink=1
547 * @deprecated in 1.19; use displayPermissionsError() instead
549 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
550 wfDeprecated( __METHOD__
, '1.19' );
552 global $wgRequest, $wgOut;
553 if ( $wgRequest->getBool( 'redlink' ) ) {
554 // The edit page was reached via a red link.
555 // Redirect to the article page and let them click the edit tab if
556 // they really want a permission error.
557 $wgOut->redirect( $this->mTitle
->getFullURL() );
559 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
564 * Should we show a preview when the edit form is first shown?
568 protected function previewOnOpen() {
569 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
570 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
571 // Explicit override from request
573 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
574 // Explicit override from request
576 } elseif ( $this->section
== 'new' ) {
577 // Nothing *to* preview for new sections
579 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
580 // Standard preference behavior
582 } elseif ( !$this->mTitle
->exists()
583 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
584 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
586 // Categories are special
594 * Checks whether the user entered a skin name in uppercase,
595 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
599 protected function isWrongCaseCssJsPage() {
600 if ( $this->mTitle
->isCssJsSubpage() ) {
601 $name = $this->mTitle
->getSkinFromCssJsSubpage();
602 $skins = array_merge(
603 array_keys( Skin
::getSkinNames() ),
606 return !in_array( $name, $skins )
607 && in_array( strtolower( $name ), $skins );
614 * Returns whether section editing is supported for the current page.
615 * Subclasses may override this to replace the default behavior, which is
616 * to check ContentHandler::supportsSections.
618 * @return bool true if this edit page supports sections, false otherwise.
620 protected function isSectionEditSupported() {
621 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
622 return $contentHandler->supportsSections();
626 * This function collects the form data and uses it to populate various member variables.
627 * @param $request WebRequest
628 * @throws ErrorPageError
630 function importFormData( &$request ) {
631 global $wgContLang, $wgUser;
633 wfProfileIn( __METHOD__
);
635 # Section edit can come from either the form or a link
636 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
638 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
639 wfProfileOut( __METHOD__
);
640 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
643 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
645 if ( $request->wasPosted() ) {
646 # These fields need to be checked for encoding.
647 # Also remove trailing whitespace, but don't remove _initial_
648 # whitespace from the text boxes. This may be significant formatting.
649 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
650 if ( !$request->getCheck( 'wpTextbox2' ) ) {
651 // Skip this if wpTextbox2 has input, it indicates that we came
652 // from a conflict page with raw page text, not a custom form
653 // modified by subclasses
654 wfProfileIn( get_class( $this ) . "::importContentFormData" );
655 $textbox1 = $this->importContentFormData( $request );
656 if ( $textbox1 !== null ) {
657 $this->textbox1
= $textbox1;
660 wfProfileOut( get_class( $this ) . "::importContentFormData" );
663 # Truncate for whole multibyte characters
664 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
666 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
667 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
669 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
671 # Treat sectiontitle the same way as summary.
672 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
673 # currently doing double duty as both edit summary and section title. Right now this
674 # is just to allow API edits to work around this limitation, but this should be
675 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
676 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
677 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
679 $this->edittime
= $request->getVal( 'wpEdittime' );
680 $this->starttime
= $request->getVal( 'wpStarttime' );
682 $undidRev = $request->getInt( 'wpUndidRevision' );
684 $this->undidRev
= $undidRev;
687 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
689 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
690 // wpTextbox1 field is missing, possibly due to being "too big"
691 // according to some filter rules such as Suhosin's setting for
692 // suhosin.request.max_value_length (d'oh)
693 $this->incompleteForm
= true;
695 // edittime should be one of our last fields; if it's missing,
696 // the submission probably broke somewhere in the middle.
697 $this->incompleteForm
= is_null( $this->edittime
);
699 if ( $this->incompleteForm
) {
700 # If the form is incomplete, force to preview.
701 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
702 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
703 $this->preview
= true;
705 /* Fallback for live preview */
706 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
707 $this->diff
= $request->getCheck( 'wpDiff' );
709 // Remember whether a save was requested, so we can indicate
710 // if we forced preview due to session failure.
711 $this->mTriedSave
= !$this->preview
;
713 if ( $this->tokenOk( $request ) ) {
714 # Some browsers will not report any submit button
715 # if the user hits enter in the comment box.
716 # The unmarked state will be assumed to be a save,
717 # if the form seems otherwise complete.
718 wfDebug( __METHOD__
. ": Passed token check.\n" );
719 } elseif ( $this->diff
) {
720 # Failed token check, but only requested "Show Changes".
721 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
723 # Page might be a hack attempt posted from
724 # an external site. Preview instead of saving.
725 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
726 $this->preview
= true;
729 $this->save
= !$this->preview
&& !$this->diff
;
730 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
731 $this->edittime
= null;
734 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
735 $this->starttime
= null;
738 $this->recreate
= $request->getCheck( 'wpRecreate' );
740 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
741 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
743 # Don't force edit summaries when a user is editing their own user or talk page
744 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
745 && $this->mTitle
->getText() == $wgUser->getName()
747 $this->allowBlankSummary
= true;
749 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary' );
752 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
754 # Not a posted form? Start with nothing.
755 wfDebug( __METHOD__
. ": Not a posted form.\n" );
756 $this->textbox1
= '';
758 $this->sectiontitle
= '';
759 $this->edittime
= '';
760 $this->starttime
= wfTimestampNow();
762 $this->preview
= false;
765 $this->minoredit
= false;
766 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overridden by request parameters
767 $this->recreate
= false;
769 // When creating a new section, we can preload a section title by passing it as the
770 // preloadtitle parameter in the URL (Bug 13100)
771 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
772 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
773 // Once wpSummary isn't being use for setting section titles, we should delete this.
774 $this->summary
= $request->getVal( 'preloadtitle' );
776 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
777 $this->summary
= $request->getText( 'summary' );
778 if ( $this->summary
!== '' ) {
779 $this->hasPresetSummary
= true;
783 if ( $request->getVal( 'minor' ) ) {
784 $this->minoredit
= true;
788 $this->oldid
= $request->getInt( 'oldid' );
790 $this->bot
= $request->getBool( 'bot', true );
791 $this->nosummary
= $request->getBool( 'nosummary' );
793 $this->contentModel
= $request->getText( 'model', $this->contentModel
); #may be overridden by revision
794 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
); #may be overridden by revision
796 if ( !ContentHandler
::getForModelID( $this->contentModel
)->isSupportedFormat( $this->contentFormat
) ) {
797 throw new ErrorPageError(
798 'editpage-notsupportedcontentformat-title',
799 'editpage-notsupportedcontentformat-text',
800 array( $this->contentFormat
, ContentHandler
::getLocalizedName( $this->contentModel
) )
803 #TODO: check if the desired model is allowed in this namespace, and if a transition from the page's current model to the new model is allowed
805 $this->live
= $request->getCheck( 'live' );
806 $this->editintro
= $request->getText( 'editintro',
807 // Custom edit intro for new sections
808 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
810 // Allow extensions to modify form data
811 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
813 wfProfileOut( __METHOD__
);
817 * Subpage overridable method for extracting the page content data from the
818 * posted form to be placed in $this->textbox1, if using customized input
819 * this method should be overridden and return the page text that will be used
820 * for saving, preview parsing and so on...
822 * @param $request WebRequest
824 protected function importContentFormData( &$request ) {
825 return; // Don't do anything, EditPage already extracted wpTextbox1
829 * Initialise form fields in the object
830 * Called on the first invocation, e.g. when a user clicks an edit link
831 * @return bool -- if the requested section is valid
833 function initialiseForm() {
835 $this->edittime
= $this->mArticle
->getTimestamp();
837 $content = $this->getContentObject( false ); #TODO: track content object?!
838 if ( $content === false ) {
841 $this->textbox1
= $this->toEditText( $content );
843 // activate checkboxes if user wants them to be always active
844 # Sort out the "watch" checkbox
845 if ( $wgUser->getOption( 'watchdefault' ) ) {
847 $this->watchthis
= true;
848 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
850 $this->watchthis
= true;
851 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
853 $this->watchthis
= true;
855 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
856 $this->minoredit
= true;
858 if ( $this->textbox1
=== false ) {
865 * Fetch initial editing page content.
867 * @param $def_text string|bool
868 * @return mixed string on success, $def_text for invalid sections
870 * @deprecated since 1.21, get WikiPage::getContent() instead.
872 function getContent( $def_text = false ) {
873 ContentHandler
::deprecated( __METHOD__
, '1.21' );
875 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
876 $def_content = $this->toEditContent( $def_text );
878 $def_content = false;
881 $content = $this->getContentObject( $def_content );
883 // Note: EditPage should only be used with text based content anyway.
884 return $this->toEditText( $content );
888 * @param Content|null $def_content The default value to return
890 * @return mixed Content on success, $def_content for invalid sections
894 protected function getContentObject( $def_content = null ) {
895 global $wgOut, $wgRequest, $wgUser, $wgContLang;
897 wfProfileIn( __METHOD__
);
901 // For message page not locally set, use the i18n message.
902 // For other non-existent articles, use preload text if any.
903 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
904 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
905 # If this is a system message, get the default text.
906 $msg = $this->mTitle
->getDefaultMessageText();
908 $content = $this->toEditContent( $msg );
910 if ( $content === false ) {
911 # If requested, preload some text.
912 $preload = $wgRequest->getVal( 'preload',
913 // Custom preload text for new sections
914 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
916 $content = $this->getPreloadedContent( $preload );
918 // For existing pages, get text based on "undo" or section parameters.
920 if ( $this->section
!= '' ) {
921 // Get section edit text (returns $def_text for invalid sections)
922 $orig = $this->getOriginalContent();
923 $content = $orig ?
$orig->getSection( $this->section
) : null;
926 $content = $def_content;
929 $undoafter = $wgRequest->getInt( 'undoafter' );
930 $undo = $wgRequest->getInt( 'undo' );
932 if ( $undo > 0 && $undoafter > 0 ) {
934 $undorev = Revision
::newFromId( $undo );
935 $oldrev = Revision
::newFromId( $undoafter );
937 # Sanity check, make sure it's the right page,
938 # the revisions exist and they were not deleted.
939 # Otherwise, $content will be left as-is.
940 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
941 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
942 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
944 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
946 if ( $content === false ) {
947 # Warn the user that something went wrong
948 $undoMsg = 'failure';
950 $oldContent = $this->mArticle
->getPage()->getContent( Revision
::RAW
);
951 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
952 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
954 if ( $newContent->equals( $oldContent ) ) {
955 # Tell the user that the undo results in no change,
956 # i.e. the revisions were already undone.
957 $undoMsg = 'nochange';
960 # Inform the user of our success and set an automatic edit summary
961 $undoMsg = 'success';
963 # If we just undid one rev, use an autosummary
964 $firstrev = $oldrev->getNext();
965 if ( $firstrev && $firstrev->getId() == $undo ) {
966 $userText = $undorev->getUserText();
967 if ( $userText === '' ) {
968 $undoSummary = wfMessage(
969 'undo-summary-username-hidden',
971 )->inContentLanguage()->text();
973 $undoSummary = wfMessage(
977 )->inContentLanguage()->text();
979 if ( $this->summary
=== '' ) {
980 $this->summary
= $undoSummary;
982 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
983 ->inContentLanguage()->text() . $this->summary
;
985 $this->undidRev
= $undo;
987 $this->formtype
= 'diff';
991 // Failed basic sanity checks.
992 // Older revisions may have been removed since the link
993 // was created, or we may simply have got bogus input.
997 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
998 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
999 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
1000 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1003 if ( $content === false ) {
1004 $content = $this->getOriginalContent();
1009 wfProfileOut( __METHOD__
);
1014 * Get the content of the wanted revision, without section extraction.
1016 * The result of this function can be used to compare user's input with
1017 * section replaced in its context (using WikiPage::replaceSection())
1018 * to the original text of the edit.
1020 * This differs from Article::getContent() that when a missing revision is
1021 * encountered the result will be null and not the
1022 * 'missing-revision' message.
1025 * @return Content|null
1027 private function getOriginalContent() {
1028 if ( $this->section
== 'new' ) {
1029 return $this->getCurrentContent();
1031 $revision = $this->mArticle
->getRevisionFetched();
1032 if ( $revision === null ) {
1033 if ( !$this->contentModel
) {
1034 $this->contentModel
= $this->getTitle()->getContentModel();
1036 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1038 return $handler->makeEmptyContent();
1040 $content = $revision->getContent();
1045 * Get the current content of the page. This is basically similar to
1046 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1047 * content object is returned instead of null.
1052 protected function getCurrentContent() {
1053 $rev = $this->mArticle
->getRevision();
1054 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1056 if ( $content === false ||
$content === null ) {
1057 if ( !$this->contentModel
) {
1058 $this->contentModel
= $this->getTitle()->getContentModel();
1060 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1062 return $handler->makeEmptyContent();
1064 # nasty side-effect, but needed for consistency
1065 $this->contentModel
= $rev->getContentModel();
1066 $this->contentFormat
= $rev->getContentFormat();
1073 * Use this method before edit() to preload some text into the edit box
1075 * @param $text string
1076 * @deprecated since 1.21, use setPreloadedContent() instead.
1078 public function setPreloadedText( $text ) {
1079 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1081 $content = $this->toEditContent( $text );
1083 $this->setPreloadedContent( $content );
1087 * Use this method before edit() to preload some content into the edit box
1089 * @param $content Content
1093 public function setPreloadedContent( Content
$content ) {
1094 $this->mPreloadContent
= $content;
1098 * Get the contents to be preloaded into the box, either set by
1099 * an earlier setPreloadText() or by loading the given page.
1101 * @param string $preload representing the title to preload from.
1105 * @deprecated since 1.21, use getPreloadedContent() instead
1107 protected function getPreloadedText( $preload ) {
1108 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1110 $content = $this->getPreloadedContent( $preload );
1111 $text = $this->toEditText( $content );
1117 * Get the contents to be preloaded into the box, either set by
1118 * an earlier setPreloadText() or by loading the given page.
1120 * @param string $preload representing the title to preload from.
1126 protected function getPreloadedContent( $preload ) {
1129 if ( !empty( $this->mPreloadContent
) ) {
1130 return $this->mPreloadContent
;
1133 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1135 if ( $preload === '' ) {
1136 return $handler->makeEmptyContent();
1139 $title = Title
::newFromText( $preload );
1140 # Check for existence to avoid getting MediaWiki:Noarticletext
1141 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1142 //TODO: somehow show a warning to the user!
1143 return $handler->makeEmptyContent();
1146 $page = WikiPage
::factory( $title );
1147 if ( $page->isRedirect() ) {
1148 $title = $page->getRedirectTarget();
1150 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1151 //TODO: somehow show a warning to the user!
1152 return $handler->makeEmptyContent();
1154 $page = WikiPage
::factory( $title );
1157 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1158 $content = $page->getContent( Revision
::RAW
);
1161 //TODO: somehow show a warning to the user!
1162 return $handler->makeEmptyContent();
1165 if ( $content->getModel() !== $handler->getModelID() ) {
1166 $converted = $content->convert( $handler->getModelID() );
1168 if ( !$converted ) {
1169 //TODO: somehow show a warning to the user!
1170 wfDebug( "Attempt to preload incompatible content: "
1171 . "can't convert " . $content->getModel()
1172 . " to " . $handler->getModelID() );
1174 return $handler->makeEmptyContent();
1177 $content = $converted;
1180 return $content->preloadTransform( $title, $parserOptions );
1184 * Make sure the form isn't faking a user's credentials.
1186 * @param $request WebRequest
1190 function tokenOk( &$request ) {
1192 $token = $request->getVal( 'wpEditToken' );
1193 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1194 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1195 return $this->mTokenOk
;
1199 * Sets post-edit cookie indicating the user just saved a particular revision.
1201 * This uses a temporary cookie for each revision ID so separate saves will never
1202 * interfere with each other.
1204 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1205 * the redirect. It must be clearable by JavaScript code, so it must not be
1206 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1209 * We use a path of '/' since wgCookiePath is not exposed to JS
1211 * If the variable were set on the server, it would be cached, which is unwanted
1212 * since the post-edit state should only apply to the load right after the save.
1214 protected function setPostEditCookie() {
1215 $revisionId = $this->mArticle
->getLatest();
1216 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1218 $response = RequestContext
::getMain()->getRequest()->response();
1219 $response->setcookie( $postEditKey, '1', time() + self
::POST_EDIT_COOKIE_DURATION
, array(
1221 'httpOnly' => false,
1226 * Attempt submission
1227 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1228 * @return bool false if output is done, true if the rest of the form should be displayed
1230 public function attemptSave() {
1233 $resultDetails = false;
1234 # Allow bots to exempt some edits from bot flagging
1235 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1236 $status = $this->internalAttemptSave( $resultDetails, $bot );
1238 return $this->handleStatus( $status, $resultDetails );
1242 * Handle status, such as after attempt save
1244 * @param Status $status
1245 * @param array|bool $resultDetails
1247 * @throws ErrorPageError
1248 * return bool false, if output is done, true if rest of the form should be displayed
1250 private function handleStatus( Status
$status, $resultDetails ) {
1251 global $wgUser, $wgOut;
1253 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1254 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1255 $this->didSave
= true;
1256 if ( !$resultDetails['nullEdit'] ) {
1257 $this->setPostEditCookie();
1261 switch ( $status->value
) {
1262 case self
::AS_HOOK_ERROR_EXPECTED
:
1263 case self
::AS_CONTENT_TOO_BIG
:
1264 case self
::AS_ARTICLE_WAS_DELETED
:
1265 case self
::AS_CONFLICT_DETECTED
:
1266 case self
::AS_SUMMARY_NEEDED
:
1267 case self
::AS_TEXTBOX_EMPTY
:
1268 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1272 case self
::AS_HOOK_ERROR
:
1275 case self
::AS_PARSE_ERROR
:
1276 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1279 case self
::AS_SUCCESS_NEW_ARTICLE
:
1280 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1281 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1282 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1285 case self
::AS_SUCCESS_UPDATE
:
1287 $sectionanchor = $resultDetails['sectionanchor'];
1289 // Give extensions a chance to modify URL query on update
1290 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1292 if ( $resultDetails['redirect'] ) {
1293 if ( $extraQuery == '' ) {
1294 $extraQuery = 'redirect=no';
1296 $extraQuery = 'redirect=no&' . $extraQuery;
1299 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1302 case self
::AS_BLANK_ARTICLE
:
1303 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1306 case self
::AS_SPAM_ERROR
:
1307 $this->spamPageWithContent( $resultDetails['spam'] );
1310 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1311 throw new UserBlockedError( $wgUser->getBlock() );
1313 case self
::AS_IMAGE_REDIRECT_ANON
:
1314 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1315 throw new PermissionsError( 'upload' );
1317 case self
::AS_READ_ONLY_PAGE_ANON
:
1318 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1319 throw new PermissionsError( 'edit' );
1321 case self
::AS_READ_ONLY_PAGE
:
1322 throw new ReadOnlyError
;
1324 case self
::AS_RATE_LIMITED
:
1325 throw new ThrottledError();
1327 case self
::AS_NO_CREATE_PERMISSION
:
1328 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1329 throw new PermissionsError( $permission );
1332 // We don't recognize $status->value. The only way that can happen
1333 // is if an extension hook aborted from inside ArticleSave.
1334 // Render the status object into $this->hookError
1335 // FIXME this sucks, we should just use the Status object throughout
1336 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1343 * Run hooks that can filter edits just before they get saved.
1345 * @param Content $content the Content to filter.
1346 * @param Status $status for reporting the outcome to the caller
1347 * @param User $user the user performing the edit
1351 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1352 // Run old style post-section-merge edit filter
1353 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1354 array( $this, $content, &$this->hookError
, $this->summary
) ) ) {
1356 # Error messages etc. could be handled within the hook...
1357 $status->fatal( 'hookaborted' );
1358 $status->value
= self
::AS_HOOK_ERROR
;
1360 } elseif ( $this->hookError
!= '' ) {
1361 # ...or the hook could be expecting us to produce an error
1362 $status->fatal( 'hookaborted' );
1363 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1367 // Run new style post-section-merge edit filter
1368 if ( !wfRunHooks( 'EditFilterMergedContent',
1369 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1370 $user, $this->minoredit
) ) ) {
1372 # Error messages etc. could be handled within the hook...
1373 // XXX: $status->value may already be something informative...
1374 $this->hookError
= $status->getWikiText();
1375 $status->fatal( 'hookaborted' );
1376 $status->value
= self
::AS_HOOK_ERROR
;
1378 } elseif ( !$status->isOK() ) {
1379 # ...or the hook could be expecting us to produce an error
1380 // FIXME this sucks, we should just use the Status object throughout
1381 $this->hookError
= $status->getWikiText();
1382 $status->fatal( 'hookaborted' );
1383 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1391 * Attempt submission (no UI)
1393 * @param array $result array to add statuses to, currently with the possible keys:
1394 * spam - string - Spam string from content if any spam is detected by matchSpamRegex
1395 * sectionanchor - string - Section anchor for a section save
1396 * nullEdit - boolean - Set if doEditContent is OK. True if null edit, false otherwise.
1397 * redirect - boolean - Set if doEditContent is OK. True if resulting revision is a redirect
1398 * @param bool $bot True if edit is being made under the bot right.
1400 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1402 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1403 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1404 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1406 function internalAttemptSave( &$result, $bot = false ) {
1407 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1409 $status = Status
::newGood();
1411 wfProfileIn( __METHOD__
);
1412 wfProfileIn( __METHOD__
. '-checks' );
1414 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1415 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1416 $status->fatal( 'hookaborted' );
1417 $status->value
= self
::AS_HOOK_ERROR
;
1418 wfProfileOut( __METHOD__
. '-checks' );
1419 wfProfileOut( __METHOD__
);
1423 $spam = $wgRequest->getText( 'wpAntispam' );
1424 if ( $spam !== '' ) {
1427 $wgUser->getName() .
1429 $this->mTitle
->getPrefixedText() .
1430 '" submitted bogus field "' .
1434 $status->fatal( 'spamprotectionmatch', false );
1435 $status->value
= self
::AS_SPAM_ERROR
;
1436 wfProfileOut( __METHOD__
. '-checks' );
1437 wfProfileOut( __METHOD__
);
1442 # Construct Content object
1443 $textbox_content = $this->toEditContent( $this->textbox1
);
1444 } catch ( MWContentSerializationException
$ex ) {
1445 $status->fatal( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
1446 $status->value
= self
::AS_PARSE_ERROR
;
1447 wfProfileOut( __METHOD__
. '-checks' );
1448 wfProfileOut( __METHOD__
);
1452 # Check image redirect
1453 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1454 $textbox_content->isRedirect() &&
1455 !$wgUser->isAllowed( 'upload' ) ) {
1456 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1457 $status->setResult( false, $code );
1459 wfProfileOut( __METHOD__
. '-checks' );
1460 wfProfileOut( __METHOD__
);
1466 $match = self
::matchSummarySpamRegex( $this->summary
);
1467 if ( $match === false && $this->section
== 'new' ) {
1468 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1469 # regular summaries, it is added to the actual wikitext.
1470 if ( $this->sectiontitle
!== '' ) {
1471 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1472 $match = self
::matchSpamRegex( $this->sectiontitle
);
1474 # This branch is taken when the "Add Topic" user interface is used, or the API
1475 # is used with the 'summary' parameter.
1476 $match = self
::matchSpamRegex( $this->summary
);
1479 if ( $match === false ) {
1480 $match = self
::matchSpamRegex( $this->textbox1
);
1482 if ( $match !== false ) {
1483 $result['spam'] = $match;
1484 $ip = $wgRequest->getIP();
1485 $pdbk = $this->mTitle
->getPrefixedDBkey();
1486 $match = str_replace( "\n", '', $match );
1487 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1488 $status->fatal( 'spamprotectionmatch', $match );
1489 $status->value
= self
::AS_SPAM_ERROR
;
1490 wfProfileOut( __METHOD__
. '-checks' );
1491 wfProfileOut( __METHOD__
);
1494 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1495 # Error messages etc. could be handled within the hook...
1496 $status->fatal( 'hookaborted' );
1497 $status->value
= self
::AS_HOOK_ERROR
;
1498 wfProfileOut( __METHOD__
. '-checks' );
1499 wfProfileOut( __METHOD__
);
1501 } elseif ( $this->hookError
!= '' ) {
1502 # ...or the hook could be expecting us to produce an error
1503 $status->fatal( 'hookaborted' );
1504 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1505 wfProfileOut( __METHOD__
. '-checks' );
1506 wfProfileOut( __METHOD__
);
1510 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1511 // Auto-block user's IP if the account was "hard" blocked
1512 $wgUser->spreadAnyEditBlock();
1513 # Check block state against master, thus 'false'.
1514 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1515 wfProfileOut( __METHOD__
. '-checks' );
1516 wfProfileOut( __METHOD__
);
1520 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1521 if ( $this->kblength
> $wgMaxArticleSize ) {
1522 // Error will be displayed by showEditForm()
1523 $this->tooBig
= true;
1524 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1525 wfProfileOut( __METHOD__
. '-checks' );
1526 wfProfileOut( __METHOD__
);
1530 if ( !$wgUser->isAllowed( 'edit' ) ) {
1531 if ( $wgUser->isAnon() ) {
1532 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1533 wfProfileOut( __METHOD__
. '-checks' );
1534 wfProfileOut( __METHOD__
);
1537 $status->fatal( 'readonlytext' );
1538 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1539 wfProfileOut( __METHOD__
. '-checks' );
1540 wfProfileOut( __METHOD__
);
1545 if ( wfReadOnly() ) {
1546 $status->fatal( 'readonlytext' );
1547 $status->value
= self
::AS_READ_ONLY_PAGE
;
1548 wfProfileOut( __METHOD__
. '-checks' );
1549 wfProfileOut( __METHOD__
);
1552 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1553 $status->fatal( 'actionthrottledtext' );
1554 $status->value
= self
::AS_RATE_LIMITED
;
1555 wfProfileOut( __METHOD__
. '-checks' );
1556 wfProfileOut( __METHOD__
);
1560 # If the article has been deleted while editing, don't save it without
1562 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1563 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1564 wfProfileOut( __METHOD__
. '-checks' );
1565 wfProfileOut( __METHOD__
);
1569 wfProfileOut( __METHOD__
. '-checks' );
1571 # Load the page data from the master. If anything changes in the meantime,
1572 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1573 $this->mArticle
->loadPageData( 'fromdbmaster' );
1574 $new = !$this->mArticle
->exists();
1577 // Late check for create permission, just in case *PARANOIA*
1578 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1579 $status->fatal( 'nocreatetext' );
1580 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1581 wfDebug( __METHOD__
. ": no create permission\n" );
1582 wfProfileOut( __METHOD__
);
1586 // Don't save a new page if it's blank or if it's a MediaWiki:
1587 // message with content equivalent to default (allow empty pages
1588 // in this case to disable messages, see bug 50124)
1589 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1590 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1591 $defaultText = $defaultMessageText;
1596 if ( $this->textbox1
=== $defaultText ) {
1597 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1598 wfProfileOut( __METHOD__
);
1602 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1603 wfProfileOut( __METHOD__
);
1607 $content = $textbox_content;
1609 $result['sectionanchor'] = '';
1610 if ( $this->section
== 'new' ) {
1611 if ( $this->sectiontitle
!== '' ) {
1612 // Insert the section title above the content.
1613 $content = $content->addSectionHeader( $this->sectiontitle
);
1615 // Jump to the new section
1616 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1618 // If no edit summary was specified, create one automatically from the section
1619 // title and have it link to the new section. Otherwise, respect the summary as
1621 if ( $this->summary
=== '' ) {
1622 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1623 $this->summary
= wfMessage( 'newsectionsummary' )
1624 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1626 } elseif ( $this->summary
!== '' ) {
1627 // Insert the section title above the content.
1628 $content = $content->addSectionHeader( $this->summary
);
1630 // Jump to the new section
1631 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1633 // Create a link to the new section from the edit summary.
1634 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1635 $this->summary
= wfMessage( 'newsectionsummary' )
1636 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1640 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1644 # Article exists. Check for edit conflict.
1646 $this->mArticle
->clear(); # Force reload of dates, etc.
1647 $timestamp = $this->mArticle
->getTimestamp();
1649 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1651 if ( $timestamp != $this->edittime
) {
1652 $this->isConflict
= true;
1653 if ( $this->section
== 'new' ) {
1654 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1655 $this->mArticle
->getComment() == $this->summary
) {
1656 // Probably a duplicate submission of a new comment.
1657 // This can happen when squid resends a request after
1658 // a timeout but the first one actually went through.
1659 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1661 // New comment; suppress conflict.
1662 $this->isConflict
= false;
1663 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1665 } elseif ( $this->section
== '' && Revision
::userWasLastToEdit( DB_MASTER
, $this->mTitle
->getArticleID(),
1666 $wgUser->getId(), $this->edittime
) ) {
1667 # Suppress edit conflict with self, except for section edits where merging is required.
1668 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1669 $this->isConflict
= false;
1673 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1674 if ( $this->sectiontitle
!== '' ) {
1675 $sectionTitle = $this->sectiontitle
;
1677 $sectionTitle = $this->summary
;
1682 if ( $this->isConflict
) {
1683 wfDebug( __METHOD__
. ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1684 . " (article time '{$timestamp}')\n" );
1686 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1688 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1689 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1692 if ( is_null( $content ) ) {
1693 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1694 $this->isConflict
= true;
1695 $content = $textbox_content; // do not try to merge here!
1696 } elseif ( $this->isConflict
) {
1698 if ( $this->mergeChangesIntoContent( $content ) ) {
1699 // Successful merge! Maybe we should tell the user the good news?
1700 $this->isConflict
= false;
1701 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1703 $this->section
= '';
1704 $this->textbox1
= ContentHandler
::getContentText( $content );
1705 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1709 if ( $this->isConflict
) {
1710 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1711 wfProfileOut( __METHOD__
);
1715 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1716 wfProfileOut( __METHOD__
);
1720 if ( $this->section
== 'new' ) {
1721 // Handle the user preference to force summaries here
1722 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1723 $this->missingSummary
= true;
1724 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1725 $status->value
= self
::AS_SUMMARY_NEEDED
;
1726 wfProfileOut( __METHOD__
);
1730 // Do not allow the user to post an empty comment
1731 if ( $this->textbox1
== '' ) {
1732 $this->missingComment
= true;
1733 $status->fatal( 'missingcommenttext' );
1734 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1735 wfProfileOut( __METHOD__
);
1738 } elseif ( !$this->allowBlankSummary
1739 && !$content->equals( $this->getOriginalContent() )
1740 && !$content->isRedirect()
1741 && md5( $this->summary
) == $this->autoSumm
1743 $this->missingSummary
= true;
1744 $status->fatal( 'missingsummary' );
1745 $status->value
= self
::AS_SUMMARY_NEEDED
;
1746 wfProfileOut( __METHOD__
);
1751 wfProfileIn( __METHOD__
. '-sectionanchor' );
1752 $sectionanchor = '';
1753 if ( $this->section
== 'new' ) {
1754 if ( $this->sectiontitle
!== '' ) {
1755 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1756 // If no edit summary was specified, create one automatically from the section
1757 // title and have it link to the new section. Otherwise, respect the summary as
1759 if ( $this->summary
=== '' ) {
1760 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1761 $this->summary
= wfMessage( 'newsectionsummary' )
1762 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1764 } elseif ( $this->summary
!== '' ) {
1765 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1766 # This is a new section, so create a link to the new section
1767 # in the revision summary.
1768 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1769 $this->summary
= wfMessage( 'newsectionsummary' )
1770 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1772 } elseif ( $this->section
!= '' ) {
1773 # Try to get a section anchor from the section source, redirect to edited section if header found
1774 # XXX: might be better to integrate this into Article::replaceSection
1775 # for duplicate heading checking and maybe parsing
1776 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1777 # we can't deal with anchors, includes, html etc in the header for now,
1778 # headline would need to be parsed to improve this
1779 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1780 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1783 $result['sectionanchor'] = $sectionanchor;
1784 wfProfileOut( __METHOD__
. '-sectionanchor' );
1786 // Save errors may fall down to the edit form, but we've now
1787 // merged the section into full text. Clear the section field
1788 // so that later submission of conflict forms won't try to
1789 // replace that into a duplicated mess.
1790 $this->textbox1
= $this->toEditText( $content );
1791 $this->section
= '';
1793 $status->value
= self
::AS_SUCCESS_UPDATE
;
1796 // Check for length errors again now that the section is merged in
1797 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1798 if ( $this->kblength
> $wgMaxArticleSize ) {
1799 $this->tooBig
= true;
1800 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1801 wfProfileOut( __METHOD__
);
1805 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1806 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1807 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1808 ( $bot ? EDIT_FORCE_BOT
: 0 );
1810 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags,
1811 false, null, $this->contentFormat
);
1813 if ( !$doEditStatus->isOK() ) {
1814 // Failure from doEdit()
1815 // Show the edit conflict page for certain recognized errors from doEdit(),
1816 // but don't show it for errors from extension hooks
1817 $errors = $doEditStatus->getErrorsArray();
1818 if ( in_array( $errors[0][0],
1819 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1821 $this->isConflict
= true;
1822 // Destroys data doEdit() put in $status->value but who cares
1823 $doEditStatus->value
= self
::AS_END
;
1825 wfProfileOut( __METHOD__
);
1826 return $doEditStatus;
1829 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1830 if ( $result['nullEdit'] ) {
1831 // We don't know if it was a null edit until now, so increment here
1832 $wgUser->pingLimiter( 'linkpurge' );
1834 $result['redirect'] = $content->isRedirect();
1835 $this->updateWatchlist();
1836 wfProfileOut( __METHOD__
);
1841 * Register the change of watch status
1843 protected function updateWatchlist() {
1846 if ( $wgUser->isLoggedIn()
1847 && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
, WatchedItem
::IGNORE_USER_RIGHTS
)
1849 $fname = __METHOD__
;
1850 $title = $this->mTitle
;
1851 $watch = $this->watchthis
;
1853 // Do this in its own transaction to reduce contention...
1854 $dbw = wfGetDB( DB_MASTER
);
1855 $dbw->onTransactionIdle( function() use ( $dbw, $title, $watch, $wgUser, $fname ) {
1856 $dbw->begin( $fname );
1857 WatchAction
::doWatchOrUnwatch( $watch, $title, $wgUser );
1858 $dbw->commit( $fname );
1864 * Attempts to merge text content with base and current revisions
1866 * @param $editText string
1869 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1871 function mergeChangesInto( &$editText ) {
1872 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1874 $editContent = $this->toEditContent( $editText );
1876 $ok = $this->mergeChangesIntoContent( $editContent );
1879 $editText = $this->toEditText( $editContent );
1886 * Attempts to do 3-way merge of edit content with a base revision
1887 * and current content, in case of edit conflict, in whichever way appropriate
1888 * for the content type.
1892 * @param $editContent
1896 private function mergeChangesIntoContent( &$editContent ) {
1897 wfProfileIn( __METHOD__
);
1899 $db = wfGetDB( DB_MASTER
);
1901 // This is the revision the editor started from
1902 $baseRevision = $this->getBaseRevision();
1903 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
1905 if ( is_null( $baseContent ) ) {
1906 wfProfileOut( __METHOD__
);
1910 // The current state, we want to merge updates into it
1911 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1912 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
1914 if ( is_null( $currentContent ) ) {
1915 wfProfileOut( __METHOD__
);
1919 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
1921 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1924 $editContent = $result;
1925 wfProfileOut( __METHOD__
);
1929 wfProfileOut( __METHOD__
);
1936 function getBaseRevision() {
1937 if ( !$this->mBaseRevision
) {
1938 $db = wfGetDB( DB_MASTER
);
1939 $this->mBaseRevision
= Revision
::loadFromTimestamp(
1940 $db, $this->mTitle
, $this->edittime
);
1942 return $this->mBaseRevision
;
1946 * Check given input text against $wgSpamRegex, and return the text of the first match.
1948 * @param $text string
1950 * @return string|bool matching string or false
1952 public static function matchSpamRegex( $text ) {
1953 global $wgSpamRegex;
1954 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1955 $regexes = (array)$wgSpamRegex;
1956 return self
::matchSpamRegexInternal( $text, $regexes );
1960 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
1962 * @param $text string
1964 * @return string|bool matching string or false
1966 public static function matchSummarySpamRegex( $text ) {
1967 global $wgSummarySpamRegex;
1968 $regexes = (array)$wgSummarySpamRegex;
1969 return self
::matchSpamRegexInternal( $text, $regexes );
1973 * @param $text string
1974 * @param $regexes array
1975 * @return bool|string
1977 protected static function matchSpamRegexInternal( $text, $regexes ) {
1978 foreach ( $regexes as $regex ) {
1980 if ( preg_match( $regex, $text, $matches ) ) {
1987 function setHeaders() {
1988 global $wgOut, $wgUser;
1990 $wgOut->addModules( 'mediawiki.action.edit' );
1991 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
1993 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1994 $wgOut->addModules( 'mediawiki.action.edit.preview' );
1997 if ( $wgUser->getOption( 'useeditwarning', false ) ) {
1998 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2001 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2003 # Enabled article-related sidebar, toplinks, etc.
2004 $wgOut->setArticleRelated( true );
2006 $contextTitle = $this->getContextTitle();
2007 if ( $this->isConflict
) {
2008 $msg = 'editconflict';
2009 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2010 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2012 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
2013 'editing' : 'creating';
2015 # Use the title defined by DISPLAYTITLE magic word when present
2016 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2017 if ( $displayTitle === false ) {
2018 $displayTitle = $contextTitle->getPrefixedText();
2020 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2024 * Show all applicable editing introductions
2026 protected function showIntro() {
2027 global $wgOut, $wgUser;
2028 if ( $this->suppressIntro
) {
2032 $namespace = $this->mTitle
->getNamespace();
2034 if ( $namespace == NS_MEDIAWIKI
) {
2035 # Show a warning if editing an interface message
2036 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2037 } elseif ( $namespace == NS_FILE
) {
2038 # Show a hint to shared repo
2039 $file = wfFindFile( $this->mTitle
);
2040 if ( $file && !$file->isLocal() ) {
2041 $descUrl = $file->getDescriptionUrl();
2042 # there must be a description url to show a hint to shared repo
2044 if ( !$this->mTitle
->exists() ) {
2045 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2046 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2049 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2050 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2057 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2058 # Show log extract when the user is currently blocked
2059 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2060 $parts = explode( '/', $this->mTitle
->getText(), 2 );
2061 $username = $parts[0];
2062 $user = User
::newFromName( $username, false /* allow IP users*/ );
2063 $ip = User
::isIP( $username );
2064 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2065 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2066 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2067 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
2068 LogEventsList
::showLogExtract(
2071 $user->getUserPage(),
2075 'showIfEmpty' => false,
2077 'blocked-notice-logextract',
2078 $user->getName() # Support GENDER in notice
2084 # Try to add a custom edit intro, or use the standard one if this is not possible.
2085 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2086 if ( $wgUser->isLoggedIn() ) {
2087 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
2089 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
2092 # Give a notice if the user is editing a deleted/moved page...
2093 if ( !$this->mTitle
->exists() ) {
2094 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
2098 'conds' => array( "log_action != 'revision'" ),
2099 'showIfEmpty' => false,
2100 'msgKey' => array( 'recreate-moveddeleted-warn' )
2107 * Attempt to show a custom editing introduction, if supplied
2111 protected function showCustomIntro() {
2112 if ( $this->editintro
) {
2113 $title = Title
::newFromText( $this->editintro
);
2114 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2116 // Added using template syntax, to take <noinclude>'s into account.
2117 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
2125 * Gets an editable textual representation of $content.
2126 * The textual representation can be turned by into a Content object by the
2127 * toEditContent() method.
2129 * If $content is null or false or a string, $content is returned unchanged.
2131 * If the given Content object is not of a type that can be edited using the text base EditPage,
2132 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2135 * @param Content|null|bool|string $content
2136 * @return String the editable text form of the content.
2138 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
2140 protected function toEditText( $content ) {
2141 if ( $content === null ||
$content === false ) {
2145 if ( is_string( $content ) ) {
2149 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2150 throw new MWException( 'This content model is not supported: '
2151 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2154 return $content->serialize( $this->contentFormat
);
2158 * Turns the given text into a Content object by unserializing it.
2160 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
2161 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2164 * @param string|null|bool $text Text to unserialize
2165 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
2168 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
2169 * and $this->allowNonTextContent is not true.
2171 protected function toEditContent( $text ) {
2172 if ( $text === false ||
$text === null ) {
2176 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2177 $this->contentModel
, $this->contentFormat
);
2179 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2180 throw new MWException( 'This content model is not supported: '
2181 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2188 * Send the edit form and related headers to $wgOut
2189 * @param $formCallback Callback|null that takes an OutputPage parameter; will be called
2190 * during form output near the top, for captchas and the like.
2192 function showEditForm( $formCallback = null ) {
2193 global $wgOut, $wgUser;
2195 wfProfileIn( __METHOD__
);
2197 # need to parse the preview early so that we know which templates are used,
2198 # otherwise users with "show preview after edit box" will get a blank list
2199 # we parse this near the beginning so that setHeaders can do the title
2200 # setting work instead of leaving it in getPreviewText
2201 $previewOutput = '';
2202 if ( $this->formtype
== 'preview' ) {
2203 $previewOutput = $this->getPreviewText();
2206 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2208 $this->setHeaders();
2210 if ( $this->showHeader() === false ) {
2211 wfProfileOut( __METHOD__
);
2215 $wgOut->addHTML( $this->editFormPageTop
);
2217 if ( $wgUser->getOption( 'previewontop' ) ) {
2218 $this->displayPreviewArea( $previewOutput, true );
2221 $wgOut->addHTML( $this->editFormTextTop
);
2223 $showToolbar = true;
2224 if ( $this->wasDeletedSinceLastEdit() ) {
2225 if ( $this->formtype
== 'save' ) {
2226 // Hide the toolbar and edit area, user can click preview to get it back
2227 // Add an confirmation checkbox and explanation.
2228 $showToolbar = false;
2230 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2231 'deletedwhileediting' );
2235 // @todo add EditForm plugin interface and use it here!
2236 // search for textarea1 and textares2, and allow EditForm to override all uses.
2237 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => self
::EDITFORM_ID
, 'name' => self
::EDITFORM_ID
,
2238 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
2239 'enctype' => 'multipart/form-data' ) ) );
2241 if ( is_callable( $formCallback ) ) {
2242 call_user_func_array( $formCallback, array( &$wgOut ) );
2245 // Add an empty field to trip up spambots
2247 Xml
::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2248 . Html
::rawElement( 'label', array( 'for' => 'wpAntiSpam' ), wfMessage( 'simpleantispam-label' )->parse() )
2249 . Xml
::element( 'input', array( 'type' => 'text', 'name' => 'wpAntispam', 'id' => 'wpAntispam', 'value' => '' ) )
2250 . Xml
::closeElement( 'div' )
2253 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2255 // Put these up at the top to ensure they aren't lost on early form submission
2256 $this->showFormBeforeText();
2258 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2259 $username = $this->lastDelete
->user_name
;
2260 $comment = $this->lastDelete
->log_comment
;
2262 // It is better to not parse the comment at all than to have templates expanded in the middle
2263 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2264 $key = $comment === ''
2265 ?
'confirmrecreate-noreason'
2266 : 'confirmrecreate';
2268 '<div class="mw-confirm-recreate">' .
2269 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2270 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2271 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2277 # When the summary is hidden, also hide them on preview/show changes
2278 if ( $this->nosummary
) {
2279 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2282 # If a blank edit summary was previously provided, and the appropriate
2283 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2284 # user being bounced back more than once in the event that a summary
2287 # For a bit more sophisticated detection of blank summaries, hash the
2288 # automatic one and pass that in the hidden field wpAutoSummary.
2289 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2290 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2293 if ( $this->undidRev
) {
2294 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2297 if ( $this->hasPresetSummary
) {
2298 // If a summary has been preset using &summary= we don't want to prompt for
2299 // a different summary. Only prompt for a summary if the summary is blanked.
2301 $this->autoSumm
= md5( '' );
2304 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2305 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2307 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2309 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2310 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2312 if ( $this->section
== 'new' ) {
2313 $this->showSummaryInput( true, $this->summary
);
2314 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2317 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2319 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2320 $wgOut->addHTML( EditPage
::getEditToolbar() );
2323 if ( $this->isConflict
) {
2324 // In an edit conflict bypass the overridable content form method
2325 // and fallback to the raw wpTextbox1 since editconflicts can't be
2326 // resolved between page source edits and custom ui edits using the
2328 $this->textbox2
= $this->textbox1
;
2330 $content = $this->getCurrentContent();
2331 $this->textbox1
= $this->toEditText( $content );
2333 $this->showTextbox1();
2335 $this->showContentForm();
2338 $wgOut->addHTML( $this->editFormTextAfterContent
);
2340 $this->showStandardInputs();
2342 $this->showFormAfterText();
2344 $this->showTosSummary();
2346 $this->showEditTools();
2348 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2350 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2351 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2353 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2354 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2356 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'limitreport' ),
2357 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2359 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2361 if ( $this->isConflict
) {
2363 $this->showConflict();
2364 } catch ( MWContentSerializationException
$ex ) {
2365 // this can't really happen, but be nice if it does.
2366 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2367 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2371 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2373 if ( !$wgUser->getOption( 'previewontop' ) ) {
2374 $this->displayPreviewArea( $previewOutput, false );
2377 wfProfileOut( __METHOD__
);
2381 * Extract the section title from current section text, if any.
2383 * @param string $text
2384 * @return Mixed|string or false
2386 public static function extractSectionTitle( $text ) {
2387 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2388 if ( !empty( $matches[2] ) ) {
2390 return $wgParser->stripSectionName( trim( $matches[2] ) );
2396 protected function showHeader() {
2397 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2399 if ( $this->mTitle
->isTalkPage() ) {
2400 $wgOut->addWikiMsg( 'talkpagetext' );
2404 $wgOut->addHTML( implode( "\n", $this->mTitle
->getEditNotices( $this->oldid
) ) );
2406 if ( $this->isConflict
) {
2407 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2408 $this->edittime
= $this->mArticle
->getTimestamp();
2410 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2411 // We use $this->section to much before this and getVal('wgSection') directly in other places
2412 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2413 // Someone is welcome to try refactoring though
2414 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2418 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2419 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2420 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2421 if ( $sectionTitle !== false ) {
2422 $this->summary
= "/* $sectionTitle */ ";
2427 if ( $this->missingComment
) {
2428 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2431 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2432 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2435 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2436 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2439 if ( $this->hookError
!== '' ) {
2440 $wgOut->addWikiText( $this->hookError
);
2443 if ( !$this->checkUnicodeCompliantBrowser() ) {
2444 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2447 if ( $this->section
!= 'new' ) {
2448 $revision = $this->mArticle
->getRevisionFetched();
2450 // Let sysop know that this will make private content public if saved
2452 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2453 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2454 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2455 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2458 if ( !$revision->isCurrent() ) {
2459 $this->mArticle
->setOldSubtitle( $revision->getId() );
2460 $wgOut->addWikiMsg( 'editingold' );
2462 } elseif ( $this->mTitle
->exists() ) {
2463 // Something went wrong
2465 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2466 array( 'missing-revision', $this->oldid
) );
2471 if ( wfReadOnly() ) {
2472 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2473 } elseif ( $wgUser->isAnon() ) {
2474 if ( $this->formtype
!= 'preview' ) {
2475 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2477 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2480 if ( $this->isCssJsSubpage
) {
2481 # Check the skin exists
2482 if ( $this->isWrongCaseCssJsPage
) {
2483 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2485 if ( $this->formtype
!== 'preview' ) {
2486 if ( $this->isCssSubpage
) {
2487 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2490 if ( $this->isJsSubpage
) {
2491 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2497 if ( $this->mTitle
->isProtected( 'edit' ) &&
2498 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2500 # Is the title semi-protected?
2501 if ( $this->mTitle
->isSemiProtected() ) {
2502 $noticeMsg = 'semiprotectedpagewarning';
2504 # Then it must be protected based on static groups (regular)
2505 $noticeMsg = 'protectedpagewarning';
2507 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2508 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2510 if ( $this->mTitle
->isCascadeProtected() ) {
2511 # Is this page under cascading protection from some source pages?
2512 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2513 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2514 $cascadeSourcesCount = count( $cascadeSources );
2515 if ( $cascadeSourcesCount > 0 ) {
2516 # Explain, and list the titles responsible
2517 foreach ( $cascadeSources as $page ) {
2518 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2521 $notice .= '</div>';
2522 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2524 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2525 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2527 'showIfEmpty' => false,
2528 'msgKey' => array( 'titleprotectedwarning' ),
2529 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2532 if ( $this->kblength
=== false ) {
2533 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2536 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2537 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2538 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2540 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2541 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2542 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2546 # Add header copyright warning
2547 $this->showHeaderCopyrightWarning();
2551 * Standard summary input and label (wgSummary), abstracted so EditPage
2552 * subclasses may reorganize the form.
2553 * Note that you do not need to worry about the label's for=, it will be
2554 * inferred by the id given to the input. You can remove them both by
2555 * passing array( 'id' => false ) to $userInputAttrs.
2557 * @param string $summary The value of the summary input
2558 * @param string $labelText The html to place inside the label
2559 * @param array $inputAttrs of attrs to use on the input
2560 * @param array $spanLabelAttrs of attrs to use on the span inside the label
2562 * @return array An array in the format array( $label, $input )
2564 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2565 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2566 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2567 'id' => 'wpSummary',
2568 'maxlength' => '200',
2571 'spellcheck' => 'true',
2572 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2574 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2575 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2576 'id' => "wpSummaryLabel"
2581 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2582 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2585 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2587 return array( $label, $input );
2591 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2592 * up top, or false if this is the comment summary
2593 * down below the textarea
2594 * @param string $summary The text of the summary to display
2597 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2598 global $wgOut, $wgContLang;
2599 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2600 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2601 if ( $isSubjectPreview ) {
2602 if ( $this->nosummary
) {
2606 if ( !$this->mShowSummaryField
) {
2610 $summary = $wgContLang->recodeForEdit( $summary );
2611 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2612 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2613 $wgOut->addHTML( "{$label} {$input}" );
2617 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2618 * up top, or false if this is the comment summary
2619 * down below the textarea
2620 * @param string $summary the text of the summary to display
2623 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2624 // avoid spaces in preview, gets always trimmed on save
2625 $summary = trim( $summary );
2626 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2632 if ( $isSubjectPreview ) {
2633 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2634 ->inContentLanguage()->text();
2637 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2639 $summary = wfMessage( $message )->parse() . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2640 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2643 protected function showFormBeforeText() {
2645 $section = htmlspecialchars( $this->section
);
2646 $wgOut->addHTML( <<<HTML
2647 <input type='hidden' value="{$section}" name="wpSection" />
2648 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2649 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2650 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2654 if ( !$this->checkUnicodeCompliantBrowser() ) {
2655 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2659 protected function showFormAfterText() {
2660 global $wgOut, $wgUser;
2662 * To make it harder for someone to slip a user a page
2663 * which submits an edit form to the wiki without their
2664 * knowledge, a random token is associated with the login
2665 * session. If it's not passed back with the submission,
2666 * we won't save the page, or render user JavaScript and
2669 * For anon editors, who may not have a session, we just
2670 * include the constant suffix to prevent editing from
2671 * broken text-mangling proxies.
2673 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2677 * Subpage overridable method for printing the form for page content editing
2678 * By default this simply outputs wpTextbox1
2679 * Subclasses can override this to provide a custom UI for editing;
2680 * be it a form, or simply wpTextbox1 with a modified content that will be
2681 * reverse modified when extracted from the post data.
2682 * Note that this is basically the inverse for importContentFormData
2684 protected function showContentForm() {
2685 $this->showTextbox1();
2689 * Method to output wpTextbox1
2690 * The $textoverride method can be used by subclasses overriding showContentForm
2691 * to pass back to this method.
2693 * @param array $customAttribs of html attributes to use in the textarea
2694 * @param string $textoverride optional text to override $this->textarea1 with
2696 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2697 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2698 $attribs = array( 'style' => 'display:none;' );
2700 $classes = array(); // Textarea CSS
2701 if ( $this->mTitle
->isProtected( 'edit' ) &&
2702 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2704 # Is the title semi-protected?
2705 if ( $this->mTitle
->isSemiProtected() ) {
2706 $classes[] = 'mw-textarea-sprotected';
2708 # Then it must be protected based on static groups (regular)
2709 $classes[] = 'mw-textarea-protected';
2711 # Is the title cascade-protected?
2712 if ( $this->mTitle
->isCascadeProtected() ) {
2713 $classes[] = 'mw-textarea-cprotected';
2717 $attribs = array( 'tabindex' => 1 );
2719 if ( is_array( $customAttribs ) ) {
2720 $attribs +
= $customAttribs;
2723 if ( count( $classes ) ) {
2724 if ( isset( $attribs['class'] ) ) {
2725 $classes[] = $attribs['class'];
2727 $attribs['class'] = implode( ' ', $classes );
2731 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2734 protected function showTextbox2() {
2735 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2738 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2739 global $wgOut, $wgUser;
2741 $wikitext = $this->safeUnicodeOutput( $text );
2742 if ( strval( $wikitext ) !== '' ) {
2743 // Ensure there's a newline at the end, otherwise adding lines
2745 // But don't add a newline if the ext is empty, or Firefox in XHTML
2746 // mode will show an extra newline. A bit annoying.
2750 $attribs = $customAttribs +
array(
2753 'cols' => $wgUser->getIntOption( 'cols' ),
2754 'rows' => $wgUser->getIntOption( 'rows' ),
2755 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2758 $pageLang = $this->mTitle
->getPageLanguage();
2759 $attribs['lang'] = $pageLang->getCode();
2760 $attribs['dir'] = $pageLang->getDir();
2762 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2765 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2769 $classes[] = 'ontop';
2772 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2774 if ( $this->formtype
!= 'preview' ) {
2775 $attribs['style'] = 'display: none;';
2778 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2780 if ( $this->formtype
== 'preview' ) {
2781 $this->showPreview( $previewOutput );
2784 $wgOut->addHTML( '</div>' );
2786 if ( $this->formtype
== 'diff' ) {
2789 } catch ( MWContentSerializationException
$ex ) {
2790 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2791 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2797 * Append preview output to $wgOut.
2798 * Includes category rendering if this is a category page.
2800 * @param string $text the HTML to be output for the preview.
2802 protected function showPreview( $text ) {
2804 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2805 $this->mArticle
->openShowCategory();
2807 # This hook seems slightly odd here, but makes things more
2808 # consistent for extensions.
2809 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2810 $wgOut->addHTML( $text );
2811 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2812 $this->mArticle
->closeShowCategory();
2817 * Get a diff between the current contents of the edit box and the
2818 * version of the page we're editing from.
2820 * If this is a section edit, we'll replace the section as for final
2821 * save and then make a comparison.
2823 function showDiff() {
2824 global $wgUser, $wgContLang, $wgOut;
2826 $oldtitlemsg = 'currentrev';
2827 # if message does not exist, show diff against the preloaded default
2828 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2829 $oldtext = $this->mTitle
->getDefaultMessageText();
2830 if ( $oldtext !== false ) {
2831 $oldtitlemsg = 'defaultmessagetext';
2832 $oldContent = $this->toEditContent( $oldtext );
2837 $oldContent = $this->getCurrentContent();
2840 $textboxContent = $this->toEditContent( $this->textbox1
);
2842 $newContent = $this->mArticle
->replaceSectionContent(
2843 $this->section
, $textboxContent,
2844 $this->summary
, $this->edittime
);
2846 if ( $newContent ) {
2847 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2848 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2850 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2851 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2854 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2855 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2856 $newtitle = wfMessage( 'yourtext' )->parse();
2858 if ( !$oldContent ) {
2859 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
2862 if ( !$newContent ) {
2863 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
2866 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
2867 $de->setContent( $oldContent, $newContent );
2869 $difftext = $de->getDiff( $oldtitle, $newtitle );
2870 $de->showDiffStyle();
2875 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2879 * Show the header copyright warning.
2881 protected function showHeaderCopyrightWarning() {
2882 $msg = 'editpage-head-copy-warn';
2883 if ( !wfMessage( $msg )->isDisabled() ) {
2885 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2886 'editpage-head-copy-warn' );
2891 * Give a chance for site and per-namespace customizations of
2892 * terms of service summary link that might exist separately
2893 * from the copyright notice.
2895 * This will display between the save button and the edit tools,
2896 * so should remain short!
2898 protected function showTosSummary() {
2899 $msg = 'editpage-tos-summary';
2900 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2901 if ( !wfMessage( $msg )->isDisabled() ) {
2903 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2904 $wgOut->addWikiMsg( $msg );
2905 $wgOut->addHTML( '</div>' );
2909 protected function showEditTools() {
2911 $wgOut->addHTML( '<div class="mw-editTools">' .
2912 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2917 * Get the copyright warning
2919 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2921 protected function getCopywarn() {
2922 return self
::getCopyrightWarning( $this->mTitle
);
2926 * Get the copyright warning, by default returns wikitext
2928 * @param Title $title
2929 * @param string $format output format, valid values are any function of
2933 public static function getCopyrightWarning( $title, $format = 'plain' ) {
2934 global $wgRightsText;
2935 if ( $wgRightsText ) {
2936 $copywarnMsg = array( 'copyrightwarning',
2937 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2940 $copywarnMsg = array( 'copyrightwarning2',
2941 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2943 // Allow for site and per-namespace customization of contribution/copyright notice.
2944 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2946 return "<div id=\"editpage-copywarn\">\n" .
2947 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
2951 * Get the Limit report for page previews
2954 * @param ParserOutput $output ParserOutput object from the parse
2955 * @return string HTML
2957 public static function getPreviewLimitReport( $output ) {
2958 if ( !$output ||
!$output->getLimitReportData() ) {
2962 wfProfileIn( __METHOD__
);
2964 $limitReport = Html
::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
2965 wfMessage( 'limitreport-title' )->parseAsBlock()
2968 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
2969 $limitReport .= Html
::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
2971 $limitReport .= Html
::openElement( 'table', array(
2972 'class' => 'preview-limit-report wikitable'
2974 Html
::openElement( 'tbody' );
2976 foreach ( $output->getLimitReportData() as $key => $value ) {
2977 if ( wfRunHooks( 'ParserLimitReportFormat',
2978 array( $key, &$value, &$limitReport, true, true )
2980 $keyMsg = wfMessage( $key );
2981 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
2982 if ( !$valueMsg->exists() ) {
2983 $valueMsg = new RawMessage( '$1' );
2985 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
2986 $limitReport .= Html
::openElement( 'tr' ) .
2987 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
2988 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
2989 Html
::closeElement( 'tr' );
2994 $limitReport .= Html
::closeElement( 'tbody' ) .
2995 Html
::closeElement( 'table' ) .
2996 Html
::closeElement( 'div' );
2998 wfProfileOut( __METHOD__
);
3000 return $limitReport;
3003 protected function showStandardInputs( &$tabindex = 2 ) {
3005 $wgOut->addHTML( "<div class='editOptions'>\n" );
3007 if ( $this->section
!= 'new' ) {
3008 $this->showSummaryInput( false, $this->summary
);
3009 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3012 $checkboxes = $this->getCheckboxes( $tabindex,
3013 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
3014 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3016 // Show copyright warning.
3017 $wgOut->addWikiText( $this->getCopywarn() );
3018 $wgOut->addHTML( $this->editFormTextAfterWarn
);
3020 $wgOut->addHTML( "<div class='editButtons'>\n" );
3021 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3023 $cancel = $this->getCancelLink();
3024 if ( $cancel !== '' ) {
3025 $cancel .= Html
::element( 'span',
3026 array( 'class' => 'mw-editButtons-pipe-separator' ),
3027 wfMessage( 'pipe-separator' )->text() );
3029 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
3030 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
3031 wfMessage( 'edithelp' )->escaped() . '</a> ' .
3032 wfMessage( 'newwindow' )->parse();
3033 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3034 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3035 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3036 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3037 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3041 * Show an edit conflict. textbox1 is already shown in showEditForm().
3042 * If you want to use another entry point to this function, be careful.
3044 protected function showConflict() {
3047 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3048 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3050 $content1 = $this->toEditContent( $this->textbox1
);
3051 $content2 = $this->toEditContent( $this->textbox2
);
3053 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3054 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3055 $de->setContent( $content2, $content1 );
3057 wfMessage( 'yourtext' )->parse(),
3058 wfMessage( 'storedversion' )->text()
3061 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3062 $this->showTextbox2();
3069 public function getCancelLink() {
3070 $cancelParams = array();
3071 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3072 $cancelParams['oldid'] = $this->oldid
;
3075 return Linker
::linkKnown(
3076 $this->getContextTitle(),
3077 wfMessage( 'cancel' )->parse(),
3078 array( 'id' => 'mw-editform-cancel' ),
3084 * Returns the URL to use in the form's action attribute.
3085 * This is used by EditPage subclasses when simply customizing the action
3086 * variable in the constructor is not enough. This can be used when the
3087 * EditPage lives inside of a Special page rather than a custom page action.
3089 * @param $title Title object for which is being edited (where we go to for &action= links)
3092 protected function getActionURL( Title
$title ) {
3093 return $title->getLocalURL( array( 'action' => $this->action
) );
3097 * Check if a page was deleted while the user was editing it, before submit.
3098 * Note that we rely on the logging table, which hasn't been always there,
3099 * but that doesn't matter, because this only applies to brand new
3102 protected function wasDeletedSinceLastEdit() {
3103 if ( $this->deletedSinceEdit
!== null ) {
3104 return $this->deletedSinceEdit
;
3107 $this->deletedSinceEdit
= false;
3109 if ( $this->mTitle
->isDeletedQuick() ) {
3110 $this->lastDelete
= $this->getLastDelete();
3111 if ( $this->lastDelete
) {
3112 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3113 if ( $deleteTime > $this->starttime
) {
3114 $this->deletedSinceEdit
= true;
3119 return $this->deletedSinceEdit
;
3122 protected function getLastDelete() {
3123 $dbr = wfGetDB( DB_SLAVE
);
3124 $data = $dbr->selectRow(
3125 array( 'logging', 'user' ),
3138 'log_namespace' => $this->mTitle
->getNamespace(),
3139 'log_title' => $this->mTitle
->getDBkey(),
3140 'log_type' => 'delete',
3141 'log_action' => 'delete',
3145 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3147 // Quick paranoid permission checks...
3148 if ( is_object( $data ) ) {
3149 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3150 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
3153 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3154 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
3161 * Get the rendered text for previewing.
3162 * @throws MWException
3165 function getPreviewText() {
3166 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3168 wfProfileIn( __METHOD__
);
3170 if ( $wgRawHtml && !$this->mTokenOk
) {
3171 // Could be an offsite preview attempt. This is very unsafe if
3172 // HTML is enabled, as it could be an attack.
3174 if ( $this->textbox1
!== '' ) {
3175 // Do not put big scary notice, if previewing the empty
3176 // string, which happens when you initially edit
3177 // a category page, due to automatic preview-on-open.
3178 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3179 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3181 wfProfileOut( __METHOD__
);
3188 $content = $this->toEditContent( $this->textbox1
);
3191 if ( !wfRunHooks( 'AlternateEditPreview', array( $this, &$content, &$previewHTML, &$this->mParserOutput
) ) ) {
3192 wfProfileOut( __METHOD__
);
3193 return $previewHTML;
3196 # provide a anchor link to the editform
3197 $continueEditing = '<span class="mw-continue-editing">' .
3198 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3199 wfMessage( 'continue-editing' )->text() . ']]</span>';
3200 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3201 if ( $this->mTokenOkExceptSuffix
) {
3202 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3205 $note = wfMessage( 'session_fail_preview' )->plain();
3207 } elseif ( $this->incompleteForm
) {
3208 $note = wfMessage( 'edit_form_incomplete' )->plain();
3210 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3213 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
3214 $parserOptions->setEditSection( false );
3215 $parserOptions->setIsPreview( true );
3216 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3218 # don't parse non-wikitext pages, show message about preview
3219 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3220 if ( $this->mTitle
->isCssJsSubpage() ) {
3222 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3228 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3230 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3236 # Used messages to make sure grep find them:
3237 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3238 if ( $level && $format ) {
3239 $note = "<div id='mw-{$level}{$format}preview'>" .
3240 wfMessage( "{$level}{$format}preview" )->text() .
3241 ' ' . $continueEditing . "</div>";
3245 # If we're adding a comment, we need to show the
3246 # summary as the headline
3247 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3248 $content = $content->addSectionHeader( $this->summary
);
3251 $hook_args = array( $this, &$content );
3252 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3253 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3255 $parserOptions->enableLimitReport();
3257 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3258 # But it's now deprecated, so never mind
3260 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3261 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
3263 $previewHTML = $parserOutput->getText();
3264 $this->mParserOutput
= $parserOutput;
3265 $wgOut->addParserOutputNoText( $parserOutput );
3267 if ( count( $parserOutput->getWarnings() ) ) {
3268 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3270 } catch ( MWContentSerializationException
$ex ) {
3271 $m = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
3272 $note .= "\n\n" . $m->parse();
3276 if ( $this->isConflict
) {
3277 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3279 $conflict = '<hr />';
3282 $previewhead = "<div class='previewnote'>\n" .
3283 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3284 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3286 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3287 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3288 'class' => 'mw-content-' . $pageViewLang->getDir() );
3289 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3291 wfProfileOut( __METHOD__
);
3292 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3298 function getTemplates() {
3299 if ( $this->preview ||
$this->section
!= '' ) {
3300 $templates = array();
3301 if ( !isset( $this->mParserOutput
) ) {
3304 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3305 foreach ( array_keys( $template ) as $dbk ) {
3306 $templates[] = Title
::makeTitle( $ns, $dbk );
3311 return $this->mTitle
->getTemplateLinksFrom();
3316 * Shows a bulletin board style toolbar for common editing functions.
3317 * It can be disabled in the user preferences.
3318 * The necessary JavaScript code can be found in skins/common/edit.js.
3322 static function getEditToolbar() {
3323 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3324 global $wgEnableUploads, $wgForeignFileRepos;
3326 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3329 * $toolarray is an array of arrays each of which includes the
3330 * filename of the button image (without path), the opening
3331 * tag, the closing tag, optionally a sample text that is
3332 * inserted between the two when no selection is highlighted
3333 * and. The tip text is shown when the user moves the mouse
3336 * Also here: accesskeys (key), which are not used yet until
3337 * someone can figure out a way to make them work in
3338 * IE. However, we should make sure these keys are not defined
3343 'image' => $wgLang->getImageFile( 'button-bold' ),
3344 'id' => 'mw-editbutton-bold',
3346 'close' => '\'\'\'',
3347 'sample' => wfMessage( 'bold_sample' )->text(),
3348 'tip' => wfMessage( 'bold_tip' )->text(),
3352 'image' => $wgLang->getImageFile( 'button-italic' ),
3353 'id' => 'mw-editbutton-italic',
3356 'sample' => wfMessage( 'italic_sample' )->text(),
3357 'tip' => wfMessage( 'italic_tip' )->text(),
3361 'image' => $wgLang->getImageFile( 'button-link' ),
3362 'id' => 'mw-editbutton-link',
3365 'sample' => wfMessage( 'link_sample' )->text(),
3366 'tip' => wfMessage( 'link_tip' )->text(),
3370 'image' => $wgLang->getImageFile( 'button-extlink' ),
3371 'id' => 'mw-editbutton-extlink',
3374 'sample' => wfMessage( 'extlink_sample' )->text(),
3375 'tip' => wfMessage( 'extlink_tip' )->text(),
3379 'image' => $wgLang->getImageFile( 'button-headline' ),
3380 'id' => 'mw-editbutton-headline',
3383 'sample' => wfMessage( 'headline_sample' )->text(),
3384 'tip' => wfMessage( 'headline_tip' )->text(),
3387 $imagesAvailable ?
array(
3388 'image' => $wgLang->getImageFile( 'button-image' ),
3389 'id' => 'mw-editbutton-image',
3390 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3392 'sample' => wfMessage( 'image_sample' )->text(),
3393 'tip' => wfMessage( 'image_tip' )->text(),
3396 $imagesAvailable ?
array(
3397 'image' => $wgLang->getImageFile( 'button-media' ),
3398 'id' => 'mw-editbutton-media',
3399 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3401 'sample' => wfMessage( 'media_sample' )->text(),
3402 'tip' => wfMessage( 'media_tip' )->text(),
3405 class_exists( 'MathRenderer' ) ?
array(
3406 'image' => $wgLang->getImageFile( 'button-math' ),
3407 'id' => 'mw-editbutton-math',
3409 'close' => "</math>",
3410 'sample' => wfMessage( 'math_sample' )->text(),
3411 'tip' => wfMessage( 'math_tip' )->text(),
3415 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3416 'id' => 'mw-editbutton-nowiki',
3417 'open' => "<nowiki>",
3418 'close' => "</nowiki>",
3419 'sample' => wfMessage( 'nowiki_sample' )->text(),
3420 'tip' => wfMessage( 'nowiki_tip' )->text(),
3424 'image' => $wgLang->getImageFile( 'button-sig' ),
3425 'id' => 'mw-editbutton-signature',
3429 'tip' => wfMessage( 'sig_tip' )->text(),
3433 'image' => $wgLang->getImageFile( 'button-hr' ),
3434 'id' => 'mw-editbutton-hr',
3435 'open' => "\n----\n",
3438 'tip' => wfMessage( 'hr_tip' )->text(),
3443 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3444 foreach ( $toolarray as $tool ) {
3450 $image = $wgStylePath . '/common/images/' . $tool['image'],
3451 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3452 // Older browsers show a "speedtip" type message only for ALT.
3453 // Ideally these should be different, realistically they
3454 // probably don't need to be.
3455 $tip = $tool['tip'],
3456 $open = $tool['open'],
3457 $close = $tool['close'],
3458 $sample = $tool['sample'],
3459 $cssId = $tool['id'],
3462 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3465 // This used to be called on DOMReady from mediawiki.action.edit, which
3466 // ended up causing race conditions with the setup code above.
3468 "// Create button bar\n" .
3469 "$(function() { mw.toolbar.init(); } );\n";
3472 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3474 $toolbar = '<div id="toolbar"></div>';
3476 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3482 * Returns an array of html code of the following checkboxes:
3485 * @param int $tabindex Current tabindex
3486 * @param array $checked of checkbox => bool, where bool indicates the checked
3487 * status of the checkbox
3491 public function getCheckboxes( &$tabindex, $checked ) {
3494 $checkboxes = array();
3496 // don't show the minor edit checkbox if it's a new page or section
3497 if ( !$this->isNew
) {
3498 $checkboxes['minor'] = '';
3499 $minorLabel = wfMessage( 'minoredit' )->parse();
3500 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3502 'tabindex' => ++
$tabindex,
3503 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3504 'id' => 'wpMinoredit',
3506 $checkboxes['minor'] =
3507 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3508 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3509 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3510 ">{$minorLabel}</label>";
3514 $watchLabel = wfMessage( 'watchthis' )->parse();
3515 $checkboxes['watch'] = '';
3516 if ( $wgUser->isLoggedIn() ) {
3518 'tabindex' => ++
$tabindex,
3519 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3520 'id' => 'wpWatchthis',
3522 $checkboxes['watch'] =
3523 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3524 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3525 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3526 ">{$watchLabel}</label>";
3528 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3533 * Returns an array of html code of the following buttons:
3534 * save, diff, preview and live
3536 * @param int $tabindex Current tabindex
3540 public function getEditButtons( &$tabindex ) {
3547 'tabindex' => ++
$tabindex,
3548 'value' => wfMessage( 'savearticle' )->text(),
3549 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3550 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3552 $buttons['save'] = Xml
::element( 'input', $temp, '' );
3554 ++
$tabindex; // use the same for preview and live preview
3556 'id' => 'wpPreview',
3557 'name' => 'wpPreview',
3559 'tabindex' => $tabindex,
3560 'value' => wfMessage( 'showpreview' )->text(),
3561 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3562 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3564 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3565 $buttons['live'] = '';
3571 'tabindex' => ++
$tabindex,
3572 'value' => wfMessage( 'showdiff' )->text(),
3573 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3574 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3576 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3578 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3583 * Output preview text only. This can be sucked into the edit page
3584 * via JavaScript, and saves the server time rendering the skin as
3585 * well as theoretically being more robust on the client (doesn't
3586 * disturb the edit box's undo history, won't eat your text on
3589 * @todo This doesn't include category or interlanguage links.
3590 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3591 * or something...</s>" that might also require more skin
3592 * initialization, so check whether that's a problem.
3594 function livePreview() {
3597 header( 'Content-type: text/xml; charset=utf-8' );
3598 header( 'Cache-control: no-cache' );
3600 $previewText = $this->getPreviewText();
3601 #$categories = $skin->getCategoryLinks();
3604 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3605 Xml
::tags( 'livepreview', null,
3606 Xml
::element( 'preview', null, $previewText )
3607 #. Xml::element( 'category', null, $categories )
3613 * Call the stock "user is blocked" page
3615 * @deprecated in 1.19; throw an exception directly instead
3617 function blockedPage() {
3618 wfDeprecated( __METHOD__
, '1.19' );
3621 throw new UserBlockedError( $wgUser->getBlock() );
3625 * Produce the stock "please login to edit pages" page
3627 * @deprecated in 1.19; throw an exception directly instead
3629 function userNotLoggedInPage() {
3630 wfDeprecated( __METHOD__
, '1.19' );
3631 throw new PermissionsError( 'edit' );
3635 * Show an error page saying to the user that he has insufficient permissions
3636 * to create a new page
3638 * @deprecated in 1.19; throw an exception directly instead
3640 function noCreatePermission() {
3641 wfDeprecated( __METHOD__
, '1.19' );
3642 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3643 throw new PermissionsError( $permission );
3647 * Creates a basic error page which informs the user that
3648 * they have attempted to edit a nonexistent section.
3650 function noSuchSectionPage() {
3653 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3655 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3656 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3657 $wgOut->addHTML( $res );
3659 $wgOut->returnToMain( false, $this->mTitle
);
3663 * Show "your edit contains spam" page with your diff and text
3665 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3667 public function spamPageWithContent( $match = false ) {
3668 global $wgOut, $wgLang;
3669 $this->textbox2
= $this->textbox1
;
3671 if ( is_array( $match ) ) {
3672 $match = $wgLang->listToText( $match );
3674 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3676 $wgOut->addHTML( '<div id="spamprotected">' );
3677 $wgOut->addWikiMsg( 'spamprotectiontext' );
3679 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3681 $wgOut->addHTML( '</div>' );
3683 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3686 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3687 $this->showTextbox2();
3689 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3693 * Format an anchor fragment as it would appear for a given section name
3694 * @param $text String
3698 function sectionAnchor( $text ) {
3700 return $wgParser->guessSectionNameFromWikiText( $text );
3704 * Check if the browser is on a blacklist of user-agents known to
3705 * mangle UTF-8 data on form submission. Returns true if Unicode
3706 * should make it through, false if it's known to be a problem.
3710 function checkUnicodeCompliantBrowser() {
3711 global $wgBrowserBlackList, $wgRequest;
3713 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3714 if ( $currentbrowser === false ) {
3715 // No User-Agent header sent? Trust it by default...
3719 foreach ( $wgBrowserBlackList as $browser ) {
3720 if ( preg_match( $browser, $currentbrowser ) ) {
3728 * Filter an input field through a Unicode de-armoring process if it
3729 * came from an old browser with known broken Unicode editing issues.
3731 * @param $request WebRequest
3732 * @param $field String
3736 function safeUnicodeInput( $request, $field ) {
3737 $text = rtrim( $request->getText( $field ) );
3738 return $request->getBool( 'safemode' )
3739 ?
$this->unmakesafe( $text )
3744 * @param $request WebRequest
3745 * @param $text string
3748 function safeUnicodeText( $request, $text ) {
3749 $text = rtrim( $text );
3750 return $request->getBool( 'safemode' )
3751 ?
$this->unmakesafe( $text )
3756 * Filter an output field through a Unicode armoring process if it is
3757 * going to an old browser with known broken Unicode editing issues.
3759 * @param $text String
3763 function safeUnicodeOutput( $text ) {
3765 $codedText = $wgContLang->recodeForEdit( $text );
3766 return $this->checkUnicodeCompliantBrowser()
3768 : $this->makesafe( $codedText );
3772 * A number of web browsers are known to corrupt non-ASCII characters
3773 * in a UTF-8 text editing environment. To protect against this,
3774 * detected browsers will be served an armored version of the text,
3775 * with non-ASCII chars converted to numeric HTML character references.
3777 * Preexisting such character references will have a 0 added to them
3778 * to ensure that round-trips do not alter the original data.
3780 * @param $invalue String
3784 function makesafe( $invalue ) {
3785 // Armor existing references for reversibility.
3786 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3791 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3792 $bytevalue = ord( $invalue[$i] );
3793 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3794 $result .= chr( $bytevalue );
3796 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3797 $working = $working << 6;
3798 $working +
= ( $bytevalue & 0x3F );
3800 if ( $bytesleft <= 0 ) {
3801 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3803 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3804 $working = $bytevalue & 0x1F;
3806 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3807 $working = $bytevalue & 0x0F;
3809 } else { // 1111 0xxx
3810 $working = $bytevalue & 0x07;
3818 * Reverse the previously applied transliteration of non-ASCII characters
3819 * back to UTF-8. Used to protect data from corruption by broken web browsers
3820 * as listed in $wgBrowserBlackList.
3822 * @param $invalue String
3826 function unmakesafe( $invalue ) {
3828 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3829 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3833 $hexstring .= $invalue[$i];
3835 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3837 // Do some sanity checks. These aren't needed for reversibility,
3838 // but should help keep the breakage down if the editor
3839 // breaks one of the entities whilst editing.
3840 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3841 $codepoint = hexdec( $hexstring );
3842 $result .= codepointToUtf8( $codepoint );
3844 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3847 $result .= substr( $invalue, $i, 1 );
3850 // reverse the transform that we made for reversibility reasons.
3851 return strtr( $result, array( "�" => "&#x" ) );