3 * Contains the EditPage class
8 * The edit page/HTML interface (split from Article)
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
13 * EditPage cares about two distinct titles:
14 * $this->mContextTitle is the page that forms submit to, links point to,
15 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
16 * page in the database that is actually being edited. These are
17 * usually the same, but they are now allowed to be different.
19 * Surgeon General's Warning: prolonged exposure to this class is known to cause
20 * headaches, which may be fatal.
25 * Status: Article successfully updated
27 const AS_SUCCESS_UPDATE
= 200;
30 * Status: Article successfully created
32 const AS_SUCCESS_NEW_ARTICLE
= 201;
35 * Status: Article update aborted by a hook function
37 const AS_HOOK_ERROR
= 210;
40 * Status: The filter function set in $wgFilterCallback returned true (= block it)
42 const AS_FILTERING
= 211;
45 * Status: A hook function returned an error
47 const AS_HOOK_ERROR_EXPECTED
= 212;
50 * Status: User is blocked from editting this page
52 const AS_BLOCKED_PAGE_FOR_USER
= 215;
55 * Status: Content too big (> $wgMaxArticleSize)
57 const AS_CONTENT_TOO_BIG
= 216;
60 * Status: User cannot edit? (not used)
62 const AS_USER_CANNOT_EDIT
= 217;
65 * Status: this anonymous user is not allowed to edit this page
67 const AS_READ_ONLY_PAGE_ANON
= 218;
70 * Status: this logged in user is not allowed to edit this page
72 const AS_READ_ONLY_PAGE_LOGGED
= 219;
75 * Status: wiki is in readonly mode (wfReadOnly() == true)
77 const AS_READ_ONLY_PAGE
= 220;
80 * Status: rate limiter for action 'edit' was tripped
82 const AS_RATE_LIMITED
= 221;
85 * Status: article was deleted while editting and param wpRecreate == false or form
88 const AS_ARTICLE_WAS_DELETED
= 222;
91 * Status: user tried to create this page, but is not allowed to do that
92 * ( Title->usercan('create') == false )
94 const AS_NO_CREATE_PERMISSION
= 223;
97 * Status: user tried to create a blank page
99 const AS_BLANK_ARTICLE
= 224;
102 * Status: (non-resolvable) edit conflict
104 const AS_CONFLICT_DETECTED
= 225;
107 * Status: no edit summary given and the user has forceeditsummary set and the user is not
108 * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
110 const AS_SUMMARY_NEEDED
= 226;
113 * Status: user tried to create a new section without content
115 const AS_TEXTBOX_EMPTY
= 228;
118 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
120 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
128 * Status: WikiPage::doEdit() was unsuccessfull
133 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
135 const AS_SPAM_ERROR
= 232;
138 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
140 const AS_IMAGE_REDIRECT_ANON
= 233;
143 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
145 const AS_IMAGE_REDIRECT_LOGGED
= 234;
156 private $mContextTitle = null;
157 var $action = 'submit';
158 var $isConflict = false;
159 var $isCssJsSubpage = false;
160 var $isCssSubpage = false;
161 var $isJsSubpage = false;
162 var $isWrongCaseCssJsPage = false;
163 var $isNew = false; // new page or new section
164 var $deletedSinceEdit;
168 var $mTokenOk = false;
169 var $mTokenOkExceptSuffix = false;
170 var $mTriedSave = false;
171 var $incompleteForm = false;
173 var $kblength = false;
174 var $missingComment = false;
175 var $missingSummary = false;
176 var $allowBlankSummary = false;
179 #var $mPreviewTemplates;
186 var $mBaseRevision = false;
187 var $mShowSummaryField = true;
190 var $save = false, $preview = false, $diff = false;
191 var $minoredit = false, $watchthis = false, $recreate = false;
192 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
193 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
194 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
195 var $content_model = null, $content_format = null;
197 # Placeholders for text injection by hooks (must be HTML)
198 # extensions should take care to _append_ to the present value
199 public $editFormPageTop = ''; // Before even the preview
200 public $editFormTextTop = '';
201 public $editFormTextBeforeContent = '';
202 public $editFormTextAfterWarn = '';
203 public $editFormTextAfterTools = '';
204 public $editFormTextBottom = '';
205 public $editFormTextAfterContent = '';
206 public $previewTextAfterContent = '';
207 public $mPreloadContent = null;
209 /* $didSave should be set to true whenever an article was succesfully altered. */
210 public $didSave = false;
211 public $undidRev = 0;
213 public $suppressIntro = false;
216 * @param $article Article
218 public function __construct( Article
$article ) {
219 $this->mArticle
= $article;
220 $this->mTitle
= $article->getTitle();
222 $this->content_model
= $this->mTitle
->getContentModelName();
224 $handler = ContentHandler
::getForModelName( $this->content_model
);
225 $this->content_format
= $handler->getDefaultFormat(); #NOTE: should be overridden by format of actual revision
231 public function getArticle() {
232 return $this->mArticle
;
239 public function getTitle() {
240 return $this->mTitle
;
244 * Set the context Title object
246 * @param $title Title object or null
248 public function setContextTitle( $title ) {
249 $this->mContextTitle
= $title;
253 * Get the context title object.
254 * If not set, $wgTitle will be returned. This behavior might changed in
255 * the future to return $this->mTitle instead.
257 * @return Title object
259 public function getContextTitle() {
260 if ( is_null( $this->mContextTitle
) ) {
264 return $this->mContextTitle
;
273 * This is the function that gets called for "action=edit". It
274 * sets up various member variables, then passes execution to
275 * another function, usually showEditForm()
277 * The edit form is self-submitting, so that when things like
278 * preview and edit conflicts occur, we get the same form back
279 * with the extra stuff added. Only when the final submission
280 * is made and all is well do we actually save and redirect to
281 * the newly-edited page.
284 global $wgOut, $wgRequest, $wgUser;
285 // Allow extensions to modify/prevent this form or submission
286 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
290 wfProfileIn( __METHOD__
);
291 wfDebug( __METHOD__
.": enter\n" );
293 // If they used redlink=1 and the page exists, redirect to the main article
294 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
295 $wgOut->redirect( $this->mTitle
->getFullURL() );
296 wfProfileOut( __METHOD__
);
300 $this->importFormData( $wgRequest );
301 $this->firsttime
= false;
304 $this->livePreview();
305 wfProfileOut( __METHOD__
);
309 if ( wfReadOnly() && $this->save
) {
312 $this->preview
= true;
316 $this->formtype
= 'save';
317 } elseif ( $this->preview
) {
318 $this->formtype
= 'preview';
319 } elseif ( $this->diff
) {
320 $this->formtype
= 'diff';
321 } else { # First time through
322 $this->firsttime
= true;
323 if ( $this->previewOnOpen() ) {
324 $this->formtype
= 'preview';
326 $this->formtype
= 'initial';
330 $permErrors = $this->getEditPermissionErrors();
332 wfDebug( __METHOD__
. ": User can't edit\n" );
333 // Auto-block user's IP if the account was "hard" blocked
334 $wgUser->spreadAnyEditBlock();
336 $this->displayPermissionsError( $permErrors );
338 wfProfileOut( __METHOD__
);
342 wfProfileIn( __METHOD__
."-business-end" );
344 $this->isConflict
= false;
345 // css / js subpages of user pages get a special treatment
346 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
347 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
348 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
349 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
350 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
352 # Show applicable editing introductions
353 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
357 # Attempt submission here. This will check for edit conflicts,
358 # and redundantly check for locked database, blocked IPs, etc.
359 # that edit() already checked just in case someone tries to sneak
360 # in the back door with a hand-edited submission URL.
362 if ( 'save' == $this->formtype
) {
363 if ( !$this->attemptSave() ) {
364 wfProfileOut( __METHOD__
."-business-end" );
365 wfProfileOut( __METHOD__
);
370 # First time through: get contents, set time for conflict
372 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
373 if ( $this->initialiseForm() === false ) {
374 $this->noSuchSectionPage();
375 wfProfileOut( __METHOD__
."-business-end" );
376 wfProfileOut( __METHOD__
);
379 if ( !$this->mTitle
->getArticleId() )
380 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
382 wfRunHooks( 'EditFormInitialText', array( $this ) );
385 $this->showEditForm();
386 wfProfileOut( __METHOD__
."-business-end" );
387 wfProfileOut( __METHOD__
);
393 protected function getEditPermissionErrors() {
395 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
396 # Can this title be created?
397 if ( !$this->mTitle
->exists() ) {
398 $permErrors = array_merge( $permErrors,
399 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
401 # Ignore some permissions errors when a user is just previewing/viewing diffs
403 foreach( $permErrors as $error ) {
404 if ( ( $this->preview ||
$this->diff
) &&
405 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
410 $permErrors = wfArrayDiff2( $permErrors, $remove );
415 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
416 * but with the following differences:
417 * - If redlink=1, the user will be redirected to the page
418 * - If there is content to display or the error occurs while either saving,
419 * previewing or showing the difference, it will be a
420 * "View source for ..." page displaying the source code after the error message.
423 * @param $permErrors Array of permissions errors, as returned by
424 * Title::getUserPermissionsErrors().
426 protected function displayPermissionsError( array $permErrors ) {
427 global $wgRequest, $wgOut;
429 if ( $wgRequest->getBool( 'redlink' ) ) {
430 // The edit page was reached via a red link.
431 // Redirect to the article page and let them click the edit tab if
432 // they really want a permission error.
433 $wgOut->redirect( $this->mTitle
->getFullUrl() );
437 $content = $this->getContentObject();
439 # Use the normal message if there's nothing to display
440 if ( $this->firsttime
&& $content->isEmpty() ) {
441 $action = $this->mTitle
->exists() ?
'edit' :
442 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
443 throw new PermissionsError( $action, $permErrors );
446 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
447 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
448 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
449 $wgOut->addHTML( "<hr />\n" );
451 # If the user made changes, preserve them when showing the markup
452 # (This happens when a user is blocked during edit, for instance)
453 if ( !$this->firsttime
) {
454 $handler = ContentHandler
::getForModelName( $this->content_model
);
456 if ( empty( $this->textbox1
) ) $content = $handler->emptyContent();
457 else $content = $handler->unserialize( $this->textbox1
);
459 $wgOut->addWikiMsg( 'viewyourtext' );
461 $wgOut->addWikiMsg( 'viewsourcetext' );
464 $text = $content->serialize( $this->content_format
);
465 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
467 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
468 Linker
::formatTemplates( $this->getTemplates() ) ) );
470 if ( $this->mTitle
->exists() ) {
471 $wgOut->returnToMain( null, $this->mTitle
);
476 * Show a read-only error
477 * Parameters are the same as OutputPage:readOnlyPage()
478 * Redirect to the article page if redlink=1
479 * @deprecated in 1.19; use displayPermissionsError() instead
481 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
482 wfDeprecated( __METHOD__
, '1.19' );
484 global $wgRequest, $wgOut;
485 if ( $wgRequest->getBool( 'redlink' ) ) {
486 // The edit page was reached via a red link.
487 // Redirect to the article page and let them click the edit tab if
488 // they really want a permission error.
489 $wgOut->redirect( $this->mTitle
->getFullUrl() );
491 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
496 * Should we show a preview when the edit form is first shown?
500 protected function previewOnOpen() {
501 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
502 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
503 // Explicit override from request
505 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
506 // Explicit override from request
508 } elseif ( $this->section
== 'new' ) {
509 // Nothing *to* preview for new sections
511 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
512 // Standard preference behaviour
514 } elseif ( !$this->mTitle
->exists() &&
515 isset($wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]) &&
516 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
518 // Categories are special
526 * Checks whether the user entered a skin name in uppercase,
527 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
531 protected function isWrongCaseCssJsPage() {
532 if( $this->mTitle
->isCssJsSubpage() ) {
533 $name = $this->mTitle
->getSkinFromCssJsSubpage();
534 $skins = array_merge(
535 array_keys( Skin
::getSkinNames() ),
538 return !in_array( $name, $skins )
539 && in_array( strtolower( $name ), $skins );
546 * Does this EditPage class support section editing?
547 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
551 protected function isSectionEditSupported() {
556 * This function collects the form data and uses it to populate various member variables.
557 * @param $request WebRequest
559 function importFormData( &$request ) {
560 global $wgLang, $wgUser;
562 wfProfileIn( __METHOD__
);
564 # Section edit can come from either the form or a link
565 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
567 if ( $request->wasPosted() ) {
568 # These fields need to be checked for encoding.
569 # Also remove trailing whitespace, but don't remove _initial_
570 # whitespace from the text boxes. This may be significant formatting.
571 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
572 if ( !$request->getCheck('wpTextbox2') ) {
573 // Skip this if wpTextbox2 has input, it indicates that we came
574 // from a conflict page with raw page text, not a custom form
575 // modified by subclasses
576 wfProfileIn( get_class($this)."::importContentFormData" );
577 $textbox1 = $this->importContentFormData( $request ); #FIXME: what should this return??
578 if ( isset($textbox1) )
579 $this->textbox1
= $textbox1; #XXX: unserialize to Content-object... when?
580 wfProfileOut( get_class($this)."::importContentFormData" );
583 # Truncate for whole multibyte characters. +5 bytes for ellipsis
584 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
586 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
587 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
589 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
591 # Treat sectiontitle the same way as summary.
592 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
593 # currently doing double duty as both edit summary and section title. Right now this
594 # is just to allow API edits to work around this limitation, but this should be
595 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
596 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 250 );
597 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
599 $this->edittime
= $request->getVal( 'wpEdittime' );
600 $this->starttime
= $request->getVal( 'wpStarttime' );
602 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
604 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
605 // wpTextbox1 field is missing, possibly due to being "too big"
606 // according to some filter rules such as Suhosin's setting for
607 // suhosin.request.max_value_length (d'oh)
608 $this->incompleteForm
= true;
610 // edittime should be one of our last fields; if it's missing,
611 // the submission probably broke somewhere in the middle.
612 $this->incompleteForm
= is_null( $this->edittime
);
614 if ( $this->incompleteForm
) {
615 # If the form is incomplete, force to preview.
616 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
617 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
618 $this->preview
= true;
620 /* Fallback for live preview */
621 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
622 $this->diff
= $request->getCheck( 'wpDiff' );
624 // Remember whether a save was requested, so we can indicate
625 // if we forced preview due to session failure.
626 $this->mTriedSave
= !$this->preview
;
628 if ( $this->tokenOk( $request ) ) {
629 # Some browsers will not report any submit button
630 # if the user hits enter in the comment box.
631 # The unmarked state will be assumed to be a save,
632 # if the form seems otherwise complete.
633 wfDebug( __METHOD__
. ": Passed token check.\n" );
634 } elseif ( $this->diff
) {
635 # Failed token check, but only requested "Show Changes".
636 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
638 # Page might be a hack attempt posted from
639 # an external site. Preview instead of saving.
640 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
641 $this->preview
= true;
644 $this->save
= !$this->preview
&& !$this->diff
;
645 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
646 $this->edittime
= null;
649 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
650 $this->starttime
= null;
653 $this->recreate
= $request->getCheck( 'wpRecreate' );
655 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
656 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
658 # Don't force edit summaries when a user is editing their own user or talk page
659 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
660 $this->mTitle
->getText() == $wgUser->getName() )
662 $this->allowBlankSummary
= true;
664 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
667 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
669 # Not a posted form? Start with nothing.
670 wfDebug( __METHOD__
. ": Not a posted form.\n" );
671 $this->textbox1
= ''; #FIXME: track content object
673 $this->sectiontitle
= '';
674 $this->edittime
= '';
675 $this->starttime
= wfTimestampNow();
677 $this->preview
= false;
680 $this->minoredit
= false;
681 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
682 $this->recreate
= false;
684 // When creating a new section, we can preload a section title by passing it as the
685 // preloadtitle parameter in the URL (Bug 13100)
686 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
687 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
688 // Once wpSummary isn't being use for setting section titles, we should delete this.
689 $this->summary
= $request->getVal( 'preloadtitle' );
691 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
692 $this->summary
= $request->getText( 'summary' );
695 if ( $request->getVal( 'minor' ) ) {
696 $this->minoredit
= true;
700 $this->oldid
= $request->getInt( 'oldid' );
702 $this->bot
= $request->getBool( 'bot', true );
703 $this->nosummary
= $request->getBool( 'nosummary' );
705 $content_handler = ContentHandler
::getForTitle( $this->mTitle
);
706 $this->content_model
= $request->getText( 'model', $content_handler->getModelName() ); #may be overridden by revision
707 $this->content_format
= $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
709 $this->live
= $request->getCheck( 'live' );
710 $this->editintro
= $request->getText( 'editintro',
711 // Custom edit intro for new sections
712 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
714 // Allow extensions to modify form data
715 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
717 wfProfileOut( __METHOD__
);
721 * Subpage overridable method for extracting the page content data from the
722 * posted form to be placed in $this->textbox1, if using customized input
723 * this method should be overrided and return the page text that will be used
724 * for saving, preview parsing and so on...
726 * @param $request WebRequest
728 protected function importContentFormData( &$request ) {
729 return; // Don't do anything, EditPage already extracted wpTextbox1
733 * Initialise form fields in the object
734 * Called on the first invocation, e.g. when a user clicks an edit link
735 * @return bool -- if the requested section is valid
737 function initialiseForm() {
739 $this->edittime
= $this->mArticle
->getTimestamp();
741 $content = $this->getContentObject( false ); #TODO: track content object?!
742 $this->textbox1
= $content->serialize( $this->content_format
);
744 // activate checkboxes if user wants them to be always active
745 # Sort out the "watch" checkbox
746 if ( $wgUser->getOption( 'watchdefault' ) ) {
748 $this->watchthis
= true;
749 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
751 $this->watchthis
= true;
752 } elseif ( $this->mTitle
->userIsWatching() ) {
754 $this->watchthis
= true;
756 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
757 $this->minoredit
= true;
759 if ( $this->textbox1
=== false ) {
767 * Fetch initial editing page content.
769 * @param $def_text string
770 * @return mixed string on success, $def_text for invalid sections
772 * @deprecated since 1.20
774 function getContent( $def_text = false ) { #FIXME: deprecated, replace usage!
775 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
776 $def_content = ContentHandler
::makeContent( $def_text, $this->getTitle() );
778 $def_content = false;
781 $content = $this->getContentObject( $def_content );
783 return $content->serialize( $this->content_format
); #XXX: really use serialized form? use ContentHandler::getContentText() instead?
786 private function getContentObject( $def_content = null ) { #FIXME: use this!
787 global $wgOut, $wgRequest;
789 wfProfileIn( __METHOD__
);
793 // For message page not locally set, use the i18n message.
794 // For other non-existent articles, use preload text if any.
795 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
796 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
797 # If this is a system message, get the default text.
798 $msg = $this->mTitle
->getDefaultMessageText();
800 $content = new WikitextContent($msg); //XXX: really hardcode wikitext here?
802 if ( $content === false ) {
803 # If requested, preload some text.
804 $preload = $wgRequest->getVal( 'preload',
805 // Custom preload text for new sections
806 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
808 $content = $this->getPreloadedContent( $preload );
810 // For existing pages, get text based on "undo" or section parameters.
812 if ( $this->section
!= '' ) {
813 // Get section edit text (returns $def_text for invalid sections)
814 $orig = $this->getOriginalContent();
815 $content = $orig ?
$orig->getSection( $this->section
) : null;
817 if ( !$content ) $content = $def_content;
819 $undoafter = $wgRequest->getInt( 'undoafter' );
820 $undo = $wgRequest->getInt( 'undo' );
822 if ( $undo > 0 && $undoafter > 0 ) {
823 if ( $undo < $undoafter ) {
824 # If they got undoafter and undo round the wrong way, switch them
825 list( $undo, $undoafter ) = array( $undoafter, $undo );
828 $undorev = Revision
::newFromId( $undo );
829 $oldrev = Revision
::newFromId( $undoafter );
831 # Sanity check, make sure it's the right page,
832 # the revisions exist and they were not deleted.
833 # Otherwise, $content will be left as-is.
834 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
835 $undorev->getPage() == $oldrev->getPage() &&
836 $undorev->getPage() == $this->mTitle
->getArticleId() &&
837 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
838 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
840 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
842 if ( $content === false ) {
843 # Warn the user that something went wrong
844 $undoMsg = 'failure';
846 # Inform the user of our success and set an automatic edit summary
847 $undoMsg = 'success';
849 # If we just undid one rev, use an autosummary
850 $firstrev = $oldrev->getNext();
851 if ( $firstrev->getId() == $undo ) {
852 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
853 if ( $this->summary
=== '' ) {
854 $this->summary
= $undoSummary;
856 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
858 $this->undidRev
= $undo;
860 $this->formtype
= 'diff';
863 // Failed basic sanity checks.
864 // Older revisions may have been removed since the link
865 // was created, or we may simply have got bogus input.
869 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"error mw-undo-{$undoMsg}\">" .
870 wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
873 if ( $content === false ) {
874 $content = $this->getOriginalContent();
879 wfProfileOut( __METHOD__
);
884 * Get the content of the wanted revision, without section extraction.
886 * The result of this function can be used to compare user's input with
887 * section replaced in its context (using WikiPage::replaceSection())
888 * to the original text of the edit.
890 * This difers from Article::getContent() that when a missing revision is
891 * encountered the result will be an empty string and not the
892 * 'missing-article' message.
897 private function getOriginalContent() { #FIXME: use Content! set content_model and content_format!
898 if ( $this->section
== 'new' ) {
899 return $this->getCurrentContent();
901 $revision = $this->mArticle
->getRevisionFetched();
902 if ( $revision === null ) {
903 if ( !$this->content_model
) $this->content_model
= $this->getTitle()->getContentModelName();
904 $handler = ContentHandler
::getForModelName( $this->content_model
);
906 return $handler->emptyContent();
909 $content = $this->mArticle
->getContentObject();
914 * Get the current content of the page. This is basically similar to
915 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
916 * content object is returned instead of null.
921 private function getCurrentContent() {
922 $rev = $this->mArticle
->getRevision();
923 $content = $rev->getContentObject( Revision
::RAW
);
925 if ( $content === false ||
$content === null ) {
926 if ( !$this->content_model
) $this->content_model
= $this->getTitle()->getContentModelName();
927 $handler = ContentHandler
::getForModelName( $this->content_model
);
929 return $handler->emptyContent();
931 #FIXME: nasty side-effect!
932 $this->content_model
= $rev->getContentModelName();
933 $this->content_format
= $rev->getContentFormat();
940 * Use this method before edit() to preload some text into the edit box
942 * @param $text string
943 * @deprecated since 1.20
945 public function setPreloadedText( $text ) { #FIXME: deprecated, use setPreloadedContent()
946 wfDeprecated( __METHOD__
, "1.20" );
948 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
950 $this->setPreloadedContent( $content );
954 * Use this method before edit() to preload some content into the edit box
956 * @param $content Content
958 public function setPreloadedContent( Content
$content ) { #FIXME: use this!
959 $this->mPreloadedContent
= $content;
963 * Get the contents to be preloaded into the box, either set by
964 * an earlier setPreloadText() or by loading the given page.
966 * @param $preload String: representing the title to preload from.
968 * @deprecated since 1.20
970 protected function getPreloadedText( $preload ) { #FIXME: B/C only, replace usage!
971 wfDeprecated( __METHOD__
, "1.20" );
973 $content = $this->getPreloadedContent( $preload );
974 $text = $content->serialize( $this->content_format
); #XXX: really use serialized form? use ContentHandler::getContentText() instead?!
979 protected function getPreloadedContent( $preload ) { #FIXME: use this!
982 if ( !empty( $this->mPreloadContent
) ) {
983 return $this->mPreloadContent
;
986 $handler = ContentHandler
::getForTitle( $this->getTitle() );
988 if ( $preload === '' ) {
989 return $handler->emptyContent();
992 $title = Title
::newFromText( $preload );
993 # Check for existence to avoid getting MediaWiki:Noarticletext
994 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
995 return $handler->emptyContent();
998 $page = WikiPage
::factory( $title );
999 if ( $page->isRedirect() ) {
1000 $title = $page->getRedirectTarget();
1002 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
1003 return $handler->emptyContent();
1005 $page = WikiPage
::factory( $title );
1008 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1009 $content = $page->getContent( Revision
::RAW
);
1011 return $content->preloadTransform( $title, $parserOptions );
1015 * Make sure the form isn't faking a user's credentials.
1017 * @param $request WebRequest
1021 function tokenOk( &$request ) {
1023 $token = $request->getVal( 'wpEditToken' );
1024 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1025 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1026 return $this->mTokenOk
;
1030 * Attempt submission
1031 * @return bool false if output is done, true if the rest of the form should be displayed
1033 function attemptSave() {
1034 global $wgUser, $wgOut;
1036 $resultDetails = false;
1037 # Allow bots to exempt some edits from bot flagging
1038 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1039 $status = $this->internalAttemptSave( $resultDetails, $bot );
1040 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1042 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1043 $this->didSave
= true;
1046 switch ( $status->value
) {
1047 case self
::AS_HOOK_ERROR_EXPECTED
:
1048 case self
::AS_CONTENT_TOO_BIG
:
1049 case self
::AS_ARTICLE_WAS_DELETED
:
1050 case self
::AS_CONFLICT_DETECTED
:
1051 case self
::AS_SUMMARY_NEEDED
:
1052 case self
::AS_TEXTBOX_EMPTY
:
1053 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1057 case self
::AS_HOOK_ERROR
:
1058 case self
::AS_FILTERING
:
1061 case self
::AS_SUCCESS_NEW_ARTICLE
:
1062 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1063 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1064 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1067 case self
::AS_SUCCESS_UPDATE
:
1069 $sectionanchor = $resultDetails['sectionanchor'];
1071 // Give extensions a chance to modify URL query on update
1072 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1074 if ( $resultDetails['redirect'] ) {
1075 if ( $extraQuery == '' ) {
1076 $extraQuery = 'redirect=no';
1078 $extraQuery = 'redirect=no&' . $extraQuery;
1081 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1084 case self
::AS_BLANK_ARTICLE
:
1085 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1088 case self
::AS_SPAM_ERROR
:
1089 $this->spamPageWithContent( $resultDetails['spam'] );
1092 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1093 throw new UserBlockedError( $wgUser->mBlock
);
1095 case self
::AS_IMAGE_REDIRECT_ANON
:
1096 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1097 throw new PermissionsError( 'upload' );
1099 case self
::AS_READ_ONLY_PAGE_ANON
:
1100 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1101 throw new PermissionsError( 'edit' );
1103 case self
::AS_READ_ONLY_PAGE
:
1104 throw new ReadOnlyError
;
1106 case self
::AS_RATE_LIMITED
:
1107 throw new ThrottledError();
1109 case self
::AS_NO_CREATE_PERMISSION
:
1110 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1111 throw new PermissionsError( $permission );
1118 * Attempt submission (no UI)
1123 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1125 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1126 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1127 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1129 function internalAttemptSave( &$result, $bot = false ) {
1130 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
1131 global $wgMaxArticleSize;
1133 $status = Status
::newGood();
1135 wfProfileIn( __METHOD__
);
1136 wfProfileIn( __METHOD__
. '-checks' );
1138 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1139 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1140 $status->fatal( 'hookaborted' );
1141 $status->value
= self
::AS_HOOK_ERROR
;
1142 wfProfileOut( __METHOD__
. '-checks' );
1143 wfProfileOut( __METHOD__
);
1147 # Check image redirect
1148 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1149 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
1150 !$wgUser->isAllowed( 'upload' ) ) {
1151 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1152 $status->setResult( false, $code );
1154 wfProfileOut( __METHOD__
. '-checks' );
1155 wfProfileOut( __METHOD__
);
1161 $match = self
::matchSummarySpamRegex( $this->summary
);
1162 if ( $match === false ) {
1163 $match = self
::matchSpamRegex( $this->textbox1
);
1165 if ( $match !== false ) {
1166 $result['spam'] = $match;
1167 $ip = $wgRequest->getIP();
1168 $pdbk = $this->mTitle
->getPrefixedDBkey();
1169 $match = str_replace( "\n", '', $match );
1170 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1171 $status->fatal( 'spamprotectionmatch', $match );
1172 $status->value
= self
::AS_SPAM_ERROR
;
1173 wfProfileOut( __METHOD__
. '-checks' );
1174 wfProfileOut( __METHOD__
);
1177 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
1178 # Error messages or other handling should be performed by the filter function
1179 $status->setResult( false, self
::AS_FILTERING
);
1180 wfProfileOut( __METHOD__
. '-checks' );
1181 wfProfileOut( __METHOD__
);
1184 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1185 # Error messages etc. could be handled within the hook...
1186 $status->fatal( 'hookaborted' );
1187 $status->value
= self
::AS_HOOK_ERROR
;
1188 wfProfileOut( __METHOD__
. '-checks' );
1189 wfProfileOut( __METHOD__
);
1191 } elseif ( $this->hookError
!= '' ) {
1192 # ...or the hook could be expecting us to produce an error
1193 $status->fatal( 'hookaborted' );
1194 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1195 wfProfileOut( __METHOD__
. '-checks' );
1196 wfProfileOut( __METHOD__
);
1200 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1201 // Auto-block user's IP if the account was "hard" blocked
1202 $wgUser->spreadAnyEditBlock();
1203 # Check block state against master, thus 'false'.
1204 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1205 wfProfileOut( __METHOD__
. '-checks' );
1206 wfProfileOut( __METHOD__
);
1210 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1211 if ( $this->kblength
> $wgMaxArticleSize ) {
1212 // Error will be displayed by showEditForm()
1213 $this->tooBig
= true;
1214 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1215 wfProfileOut( __METHOD__
. '-checks' );
1216 wfProfileOut( __METHOD__
);
1220 if ( !$wgUser->isAllowed( 'edit' ) ) {
1221 if ( $wgUser->isAnon() ) {
1222 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1223 wfProfileOut( __METHOD__
. '-checks' );
1224 wfProfileOut( __METHOD__
);
1227 $status->fatal( 'readonlytext' );
1228 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1229 wfProfileOut( __METHOD__
. '-checks' );
1230 wfProfileOut( __METHOD__
);
1235 if ( wfReadOnly() ) {
1236 $status->fatal( 'readonlytext' );
1237 $status->value
= self
::AS_READ_ONLY_PAGE
;
1238 wfProfileOut( __METHOD__
. '-checks' );
1239 wfProfileOut( __METHOD__
);
1242 if ( $wgUser->pingLimiter() ) {
1243 $status->fatal( 'actionthrottledtext' );
1244 $status->value
= self
::AS_RATE_LIMITED
;
1245 wfProfileOut( __METHOD__
. '-checks' );
1246 wfProfileOut( __METHOD__
);
1250 # If the article has been deleted while editing, don't save it without
1252 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1253 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1254 wfProfileOut( __METHOD__
. '-checks' );
1255 wfProfileOut( __METHOD__
);
1259 wfProfileOut( __METHOD__
. '-checks' );
1261 # If article is new, insert it.
1262 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1263 $new = ( $aid == 0 );
1266 // Late check for create permission, just in case *PARANOIA*
1267 if ( !$this->mTitle
->userCan( 'create' ) ) {
1268 $status->fatal( 'nocreatetext' );
1269 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1270 wfDebug( __METHOD__
. ": no create permission\n" );
1271 wfProfileOut( __METHOD__
);
1275 # Don't save a new article if it's blank.
1276 if ( $this->textbox1
== '' ) {
1277 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1278 wfProfileOut( __METHOD__
);
1282 // Run post-section-merge edit filter
1283 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1284 # Error messages etc. could be handled within the hook...
1285 $status->fatal( 'hookaborted' );
1286 $status->value
= self
::AS_HOOK_ERROR
;
1287 wfProfileOut( __METHOD__
);
1289 } elseif ( $this->hookError
!= '' ) {
1290 # ...or the hook could be expecting us to produce an error
1291 $status->fatal( 'hookaborted' );
1292 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1293 wfProfileOut( __METHOD__
);
1297 # Handle the user preference to force summaries here. Check if it's not a redirect.
1298 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
1299 if ( md5( $this->summary
) == $this->autoSumm
) {
1300 $this->missingSummary
= true;
1301 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1302 $status->value
= self
::AS_SUMMARY_NEEDED
;
1303 wfProfileOut( __METHOD__
);
1308 $content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
);
1310 $result['sectionanchor'] = '';
1311 if ( $this->section
== 'new' ) {
1312 .........FIXME
...............
1313 if ( $this->sectiontitle
!== '' ) {
1314 // Insert the section title above the content.
1315 $T_E_X_T = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle
) . "\n\n" . $T_E_X_T;
1317 // Jump to the new section
1318 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1320 // If no edit summary was specified, create one automatically from the section
1321 // title and have it link to the new section. Otherwise, respect the summary as
1323 if ( $this->summary
=== '' ) {
1324 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1325 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1327 } elseif ( $this->summary
!== '' ) {
1328 // Insert the section title above the content.
1329 $T_E_X_T = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $T_E_X_T;
1331 // Jump to the new section
1332 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1334 // Create a link to the new section from the edit summary.
1335 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1336 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1340 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1344 # Article exists. Check for edit conflict.
1346 $this->mArticle
->clear(); # Force reload of dates, etc.
1347 $timestamp = $this->mArticle
->getTimestamp();
1349 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1351 if ( $timestamp != $this->edittime
) {
1352 $this->isConflict
= true;
1353 if ( $this->section
== 'new' ) {
1354 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1355 $this->mArticle
->getComment() == $this->summary
) {
1356 // Probably a duplicate submission of a new comment.
1357 // This can happen when squid resends a request after
1358 // a timeout but the first one actually went through.
1359 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1361 // New comment; suppress conflict.
1362 $this->isConflict
= false;
1363 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1365 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1366 # Suppress edit conflict with self, except for section edits where merging is required.
1367 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1368 $this->isConflict
= false;
1372 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1373 // backwards compatibility with old forms/bots).
1374 if ( $this->sectiontitle
!== '' ) {
1375 $sectionTitle = $this->sectiontitle
;
1377 $sectionTitle = $this->summary
;
1380 if ( $this->isConflict
) {
1381 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1382 $T_E_X_T = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle, $this->edittime
); #FIXME: use Content object throughout, make edit form aware of content model and serialization format
1384 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1385 $T_E_X_T = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle ); #FIXME: use Content object throughout, make edit form aware of content model and serialization format
1387 if ( is_null( $T_E_X_T ) ) {
1388 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1389 $this->isConflict
= true;
1390 $T_E_X_T = $this->textbox1
; // do not try to merge here! #FIXME: unserialize Content
1391 } elseif ( $this->isConflict
) {
1393 if ( $this->mergeChangesInto( $T_E_X_T ) ) { #FIXME: passe/receive Content object
1394 // Successful merge! Maybe we should tell the user the good news?
1395 $this->isConflict
= false;
1396 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1398 $this->section
= '';
1399 $this->textbox1
= $T_E_X_T;
1400 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1404 if ( $this->isConflict
) {
1405 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1406 wfProfileOut( __METHOD__
);
1410 // Run post-section-merge edit filter
1411 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $T_E_X_T, &$this->hookError
, $this->summary
) ) ) {
1412 # Error messages etc. could be handled within the hook...
1413 $status->fatal( 'hookaborted' );
1414 $status->value
= self
::AS_HOOK_ERROR
;
1415 wfProfileOut( __METHOD__
);
1417 } elseif ( $this->hookError
!= '' ) {
1418 # ...or the hook could be expecting us to produce an error
1419 $status->fatal( 'hookaborted' );
1420 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1421 wfProfileOut( __METHOD__
);
1425 # Handle the user preference to force summaries here, but not for null edits
1426 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1427 && $this->getOriginalContent()... != $T_E_X_T
1428 && !Title
::newFromRedirect( $T_E_X_T ) ) # check if it's not a redirect
1430 if ( md5( $this->summary
) == $this->autoSumm
) {
1431 $this->missingSummary
= true;
1432 $status->fatal( 'missingsummary' );
1433 $status->value
= self
::AS_SUMMARY_NEEDED
;
1434 wfProfileOut( __METHOD__
);
1439 # And a similar thing for new sections
1440 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1441 if ( trim( $this->summary
) == '' ) {
1442 $this->missingSummary
= true;
1443 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1444 $status->value
= self
::AS_SUMMARY_NEEDED
;
1445 wfProfileOut( __METHOD__
);
1451 wfProfileIn( __METHOD__
. '-sectionanchor' );
1452 $sectionanchor = '';
1453 if ( $this->section
== 'new' ) {
1454 if ( $this->textbox1
== '' ) {
1455 $this->missingComment
= true;
1456 $status->fatal( 'missingcommenttext' );
1457 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1458 wfProfileOut( __METHOD__
. '-sectionanchor' );
1459 wfProfileOut( __METHOD__
);
1462 if ( $this->sectiontitle
!== '' ) {
1463 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1464 // If no edit summary was specified, create one automatically from the section
1465 // title and have it link to the new section. Otherwise, respect the summary as
1467 if ( $this->summary
=== '' ) {
1468 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1469 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1471 } elseif ( $this->summary
!== '' ) {
1472 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1473 # This is a new section, so create a link to the new section
1474 # in the revision summary.
1475 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1476 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1478 } elseif ( $this->section
!= '' ) {
1479 # Try to get a section anchor from the section source, redirect to edited section if header found
1480 # XXX: might be better to integrate this into Article::replaceSection
1481 # for duplicate heading checking and maybe parsing
1482 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1483 # we can't deal with anchors, includes, html etc in the header for now,
1484 # headline would need to be parsed to improve this
1485 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1486 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1489 $result['sectionanchor'] = $sectionanchor;
1490 wfProfileOut( __METHOD__
. '-sectionanchor' );
1492 // Save errors may fall down to the edit form, but we've now
1493 // merged the section into full text. Clear the section field
1494 // so that later submission of conflict forms won't try to
1495 // replace that into a duplicated mess.
1496 $this->textbox1
= $T_E_X_T;
1497 $this->section
= '';
1499 $status->value
= self
::AS_SUCCESS_UPDATE
;
1502 // Check for length errors again now that the section is merged in
1503 $this->kblength
= (int)( strlen( $T_E_X_T ) / 1024 );
1504 if ( $this->kblength
> $wgMaxArticleSize ) {
1505 $this->tooBig
= true;
1506 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1507 wfProfileOut( __METHOD__
);
1511 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1512 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1513 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1514 ( $bot ? EDIT_FORCE_BOT
: 0 );
1516 $doEditStatus = $this->mArticle
->doEdit( $T_E_X_T, $this->summary
, $flags ); # FIXME: use WikiPage::doEditContent()
1518 if ( $doEditStatus->isOK() ) {
1519 $result['redirect'] = Title
::newFromRedirect( $T_E_X_T ) !== null;
1520 $this->commitWatch();
1521 wfProfileOut( __METHOD__
);
1524 $this->isConflict
= true;
1525 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1526 wfProfileOut( __METHOD__
);
1527 return $doEditStatus;
1532 * Commit the change of watch status
1534 protected function commitWatch() {
1536 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1537 $dbw = wfGetDB( DB_MASTER
);
1539 if ( $this->watchthis
) {
1540 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1542 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1549 * Check if no edits were made by other users since
1550 * the time a user started editing the page. Limit to
1551 * 50 revisions for the sake of performance.
1554 * @param $edittime string
1558 protected function userWasLastToEdit( $id, $edittime ) {
1559 if( !$id ) return false;
1560 $dbw = wfGetDB( DB_MASTER
);
1561 $res = $dbw->select( 'revision',
1564 'rev_page' => $this->mTitle
->getArticleId(),
1565 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1568 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1569 foreach ( $res as $row ) {
1570 if( $row->rev_user
!= $id ) {
1581 * @parma $editText string
1585 function mergeChangesInto( &$editText ){
1586 wfProfileIn( __METHOD__
);
1588 $db = wfGetDB( DB_MASTER
);
1590 // This is the revision the editor started from
1591 $baseRevision = $this->getBaseRevision();
1592 if ( is_null( $baseRevision ) ) {
1593 wfProfileOut( __METHOD__
);
1596 $baseContent = $baseRevision->getContent();
1598 // The current state, we want to merge updates into it
1599 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1600 if ( is_null( $currentRevision ) ) {
1601 wfProfileOut( __METHOD__
);
1604 $currentContent = $currentRevision->getContent();
1606 $handler = ContentHandler
::getForModelName( $baseContent->getModelName() );
1607 $editContent = $handler->unserialize( $editText, $this->content_format
); #FIXME: supply serialization fomrat from edit form!
1609 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1611 $editText = ContentHandler
::getContentText($result, $this->content_format
); #FIXME: supply serialization fomrat from edit form!
1612 wfProfileOut( __METHOD__
);
1615 wfProfileOut( __METHOD__
);
1623 function getBaseRevision() {
1624 if ( !$this->mBaseRevision
) {
1625 $db = wfGetDB( DB_MASTER
);
1626 $baseRevision = Revision
::loadFromTimestamp(
1627 $db, $this->mTitle
, $this->edittime
);
1628 return $this->mBaseRevision
= $baseRevision;
1630 return $this->mBaseRevision
;
1635 * Check given input text against $wgSpamRegex, and return the text of the first match.
1637 * @param $text string
1639 * @return string|false matching string or false
1641 public static function matchSpamRegex( $text ) {
1642 global $wgSpamRegex;
1643 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1644 $regexes = (array)$wgSpamRegex;
1645 return self
::matchSpamRegexInternal( $text, $regexes );
1649 * Check given input text against $wgSpamRegex, and return the text of the first match.
1651 * @parma $text string
1653 * @return string|false matching string or false
1655 public static function matchSummarySpamRegex( $text ) {
1656 global $wgSummarySpamRegex;
1657 $regexes = (array)$wgSummarySpamRegex;
1658 return self
::matchSpamRegexInternal( $text, $regexes );
1662 * @param $text string
1663 * @param $regexes array
1664 * @return bool|string
1666 protected static function matchSpamRegexInternal( $text, $regexes ) {
1667 foreach( $regexes as $regex ) {
1669 if( preg_match( $regex, $text, $matches ) ) {
1676 function setHeaders() {
1677 global $wgOut, $wgUser;
1679 $wgOut->addModules( 'mediawiki.action.edit' );
1681 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1682 $wgOut->addModules( 'mediawiki.legacy.preview' );
1684 // Bug #19334: textarea jumps when editing articles in IE8
1685 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1687 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1689 # Enabled article-related sidebar, toplinks, etc.
1690 $wgOut->setArticleRelated( true );
1692 if ( $this->isConflict
) {
1693 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1694 } elseif ( $this->section
!= '' ) {
1695 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1696 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1698 # Use the title defined by DISPLAYTITLE magic word when present
1699 if ( isset( $this->mParserOutput
)
1700 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1703 $title = $this->getContextTitle()->getPrefixedText();
1705 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1710 * Show all applicable editing introductions
1712 protected function showIntro() {
1713 global $wgOut, $wgUser;
1714 if ( $this->suppressIntro
) {
1718 $namespace = $this->mTitle
->getNamespace();
1720 if ( $namespace == NS_MEDIAWIKI
) {
1721 # Show a warning if editing an interface message
1722 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1725 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1726 # Show log extract when the user is currently blocked
1727 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1728 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1729 $username = $parts[0];
1730 $user = User
::newFromName( $username, false /* allow IP users*/ );
1731 $ip = User
::isIP( $username );
1732 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1733 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1734 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1735 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1736 LogEventsList
::showLogExtract(
1739 $user->getUserPage(),
1743 'showIfEmpty' => false,
1745 'blocked-notice-logextract',
1746 $user->getName() # Support GENDER in notice
1752 # Try to add a custom edit intro, or use the standard one if this is not possible.
1753 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1754 if ( $wgUser->isLoggedIn() ) {
1755 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1757 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1760 # Give a notice if the user is editing a deleted/moved page...
1761 if ( !$this->mTitle
->exists() ) {
1762 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1763 '', array( 'lim' => 10,
1764 'conds' => array( "log_action != 'revision'" ),
1765 'showIfEmpty' => false,
1766 'msgKey' => array( 'recreate-moveddeleted-warn') )
1772 * Attempt to show a custom editing introduction, if supplied
1776 protected function showCustomIntro() {
1777 if ( $this->editintro
) {
1778 $title = Title
::newFromText( $this->editintro
);
1779 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1781 // Added using template syntax, to take <noinclude>'s into account.
1782 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1793 * Send the edit form and related headers to $wgOut
1794 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1795 * during form output near the top, for captchas and the like.
1797 function showEditForm( $formCallback = null ) {
1798 global $wgOut, $wgUser;
1800 wfProfileIn( __METHOD__
);
1802 #need to parse the preview early so that we know which templates are used,
1803 #otherwise users with "show preview after edit box" will get a blank list
1804 #we parse this near the beginning so that setHeaders can do the title
1805 #setting work instead of leaving it in getPreviewText
1806 $previewOutput = '';
1807 if ( $this->formtype
== 'preview' ) {
1808 $previewOutput = $this->getPreviewText();
1811 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1813 $this->setHeaders();
1815 if ( $this->showHeader() === false ) {
1816 wfProfileOut( __METHOD__
);
1820 $wgOut->addHTML( $this->editFormPageTop
);
1822 if ( $wgUser->getOption( 'previewontop' ) ) {
1823 $this->displayPreviewArea( $previewOutput, true );
1826 $wgOut->addHTML( $this->editFormTextTop
);
1828 $showToolbar = true;
1829 if ( $this->wasDeletedSinceLastEdit() ) {
1830 if ( $this->formtype
== 'save' ) {
1831 // Hide the toolbar and edit area, user can click preview to get it back
1832 // Add an confirmation checkbox and explanation.
1833 $showToolbar = false;
1835 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1836 'deletedwhileediting' );
1840 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
1841 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1842 'enctype' => 'multipart/form-data' ) ) );
1844 if ( is_callable( $formCallback ) ) {
1845 call_user_func_array( $formCallback, array( &$wgOut ) );
1848 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1850 // Put these up at the top to ensure they aren't lost on early form submission
1851 $this->showFormBeforeText();
1853 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1854 $username = $this->lastDelete
->user_name
;
1855 $comment = $this->lastDelete
->log_comment
;
1857 // It is better to not parse the comment at all than to have templates expanded in the middle
1858 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1859 $key = $comment === ''
1860 ?
'confirmrecreate-noreason'
1861 : 'confirmrecreate';
1863 '<div class="mw-confirm-recreate">' .
1864 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1865 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1866 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1872 # If a blank edit summary was previously provided, and the appropriate
1873 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1874 # user being bounced back more than once in the event that a summary
1877 # For a bit more sophisticated detection of blank summaries, hash the
1878 # automatic one and pass that in the hidden field wpAutoSummary.
1879 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
1880 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1883 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1884 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1886 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
1888 if ( $this->section
== 'new' ) {
1889 $this->showSummaryInput( true, $this->summary
);
1890 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1893 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1895 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1896 $wgOut->addHTML( EditPage
::getEditToolbar() );
1899 if ( $this->isConflict
) {
1900 // In an edit conflict bypass the overrideable content form method
1901 // and fallback to the raw wpTextbox1 since editconflicts can't be
1902 // resolved between page source edits and custom ui edits using the
1904 $this->textbox2
= $this->textbox1
;
1906 $content = $this->getCurrentContent();
1907 $this->textbox1
= $content->serialize( $this->content_format
);
1909 $this->showTextbox1();
1911 $this->showContentForm();
1914 $wgOut->addHTML( $this->editFormTextAfterContent
);
1916 $wgOut->addWikiText( $this->getCopywarn() );
1918 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1920 $this->showStandardInputs();
1922 $this->showFormAfterText();
1924 $this->showTosSummary();
1926 $this->showEditTools();
1928 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
1930 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
1931 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
1933 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
1934 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
1936 if ( $this->isConflict
) {
1937 $this->showConflict();
1940 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
1942 if ( !$wgUser->getOption( 'previewontop' ) ) {
1943 $this->displayPreviewArea( $previewOutput, false );
1946 wfProfileOut( __METHOD__
);
1950 * Extract the section title from current section text, if any.
1952 * @param string $text
1953 * @return Mixed|string or false
1955 public static function extractSectionTitle( $text ) {
1956 preg_match( "/^(=+)(.+)\\1(\n|$)/i", $text, $matches );
1957 if ( !empty( $matches[2] ) ) {
1959 return $wgParser->stripSectionName(trim($matches[2]));
1965 protected function showHeader() {
1966 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1968 if ( $this->mTitle
->isTalkPage() ) {
1969 $wgOut->addWikiMsg( 'talkpagetext' );
1972 # Optional notices on a per-namespace and per-page basis
1973 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
1974 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
1975 if ( $editnotice_ns_message->exists() ) {
1976 $wgOut->addWikiText( $editnotice_ns_message->plain() );
1978 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
1979 $parts = explode( '/', $this->mTitle
->getDBkey() );
1980 $editnotice_base = $editnotice_ns;
1981 while ( count( $parts ) > 0 ) {
1982 $editnotice_base .= '-'.array_shift( $parts );
1983 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
1984 if ( $editnotice_base_msg->exists() ) {
1985 $wgOut->addWikiText( $editnotice_base_msg->plain() );
1989 # Even if there are no subpages in namespace, we still don't want / in MW ns.
1990 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
1991 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
1992 if ( $editnoticeMsg->exists() ) {
1993 $wgOut->addWikiText( $editnoticeMsg->plain() );
1997 if ( $this->isConflict
) {
1998 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1999 $this->edittime
= $this->mArticle
->getTimestamp();
2001 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2002 // We use $this->section to much before this and getVal('wgSection') directly in other places
2003 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2004 // Someone is welcome to try refactoring though
2005 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2009 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2010 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2011 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
2012 if ( $sectionTitle !== false ) {
2013 $this->summary
= "/* $sectionTitle */ ";
2018 if ( $this->missingComment
) {
2019 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2022 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2023 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2026 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2027 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2030 if ( $this->hookError
!== '' ) {
2031 $wgOut->addWikiText( $this->hookError
);
2034 if ( !$this->checkUnicodeCompliantBrowser() ) {
2035 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2038 if ( $this->section
!= 'new' ) {
2039 $revision = $this->mArticle
->getRevisionFetched();
2041 // Let sysop know that this will make private content public if saved
2043 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
2044 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2045 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2046 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2049 if ( !$revision->isCurrent() ) {
2050 $this->mArticle
->setOldSubtitle( $revision->getId() );
2051 $wgOut->addWikiMsg( 'editingold' );
2053 } elseif ( $this->mTitle
->exists() ) {
2054 // Something went wrong
2056 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2057 array( 'missing-article', $this->mTitle
->getPrefixedText(),
2058 wfMsgNoTrans( 'missingarticle-rev', $this->oldid
) ) );
2063 if ( wfReadOnly() ) {
2064 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2065 } elseif ( $wgUser->isAnon() ) {
2066 if ( $this->formtype
!= 'preview' ) {
2067 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2069 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2072 if ( $this->isCssJsSubpage
) {
2073 # Check the skin exists
2074 if ( $this->isWrongCaseCssJsPage
) {
2075 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2077 if ( $this->formtype
!== 'preview' ) {
2078 if ( $this->isCssSubpage
)
2079 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2080 if ( $this->isJsSubpage
)
2081 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2086 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2087 # Is the title semi-protected?
2088 if ( $this->mTitle
->isSemiProtected() ) {
2089 $noticeMsg = 'semiprotectedpagewarning';
2091 # Then it must be protected based on static groups (regular)
2092 $noticeMsg = 'protectedpagewarning';
2094 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2095 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2097 if ( $this->mTitle
->isCascadeProtected() ) {
2098 # Is this page under cascading protection from some source pages?
2099 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
2100 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2101 $cascadeSourcesCount = count( $cascadeSources );
2102 if ( $cascadeSourcesCount > 0 ) {
2103 # Explain, and list the titles responsible
2104 foreach( $cascadeSources as $page ) {
2105 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2108 $notice .= '</div>';
2109 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2111 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2112 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2114 'showIfEmpty' => false,
2115 'msgKey' => array( 'titleprotectedwarning' ),
2116 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2119 if ( $this->kblength
=== false ) {
2120 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2123 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2124 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2125 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2127 if( !wfMessage('longpage-hint')->isDisabled() ) {
2128 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2129 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2136 * Standard summary input and label (wgSummary), abstracted so EditPage
2137 * subclasses may reorganize the form.
2138 * Note that you do not need to worry about the label's for=, it will be
2139 * inferred by the id given to the input. You can remove them both by
2140 * passing array( 'id' => false ) to $userInputAttrs.
2142 * @param $summary string The value of the summary input
2143 * @param $labelText string The html to place inside the label
2144 * @param $inputAttrs array of attrs to use on the input
2145 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2147 * @return array An array in the format array( $label, $input )
2149 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
2150 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
2151 $inputAttrs = ( is_array($inputAttrs) ?
$inputAttrs : array() ) +
array(
2152 'id' => 'wpSummary',
2153 'maxlength' => '200',
2156 'spellcheck' => 'true',
2157 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2159 $spanLabelAttrs = ( is_array($spanLabelAttrs) ?
$spanLabelAttrs : array() ) +
array(
2160 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2161 'id' => "wpSummaryLabel"
2166 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2167 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2170 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2172 return array( $label, $input );
2176 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2177 * up top, or false if this is the comment summary
2178 * down below the textarea
2179 * @param $summary String: The text of the summary to display
2182 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2183 global $wgOut, $wgContLang;
2184 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2185 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2186 if ( $isSubjectPreview ) {
2187 if ( $this->nosummary
) {
2191 if ( !$this->mShowSummaryField
) {
2195 $summary = $wgContLang->recodeForEdit( $summary );
2196 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
2197 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
2198 $wgOut->addHTML("{$label} {$input}");
2202 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2203 * up top, or false if this is the comment summary
2204 * down below the textarea
2205 * @param $summary String: the text of the summary to display
2208 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2209 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2214 if ( $isSubjectPreview )
2215 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2217 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2219 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2220 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2223 protected function showFormBeforeText() {
2225 $section = htmlspecialchars( $this->section
);
2226 $wgOut->addHTML( <<<HTML
2227 <input type='hidden' value="{$section}" name="wpSection" />
2228 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2229 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2230 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2234 if ( !$this->checkUnicodeCompliantBrowser() )
2235 $wgOut->addHTML(Html
::hidden( 'safemode', '1' ));
2238 protected function showFormAfterText() {
2239 global $wgOut, $wgUser;
2241 * To make it harder for someone to slip a user a page
2242 * which submits an edit form to the wiki without their
2243 * knowledge, a random token is associated with the login
2244 * session. If it's not passed back with the submission,
2245 * we won't save the page, or render user JavaScript and
2248 * For anon editors, who may not have a session, we just
2249 * include the constant suffix to prevent editing from
2250 * broken text-mangling proxies.
2252 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2256 * Subpage overridable method for printing the form for page content editing
2257 * By default this simply outputs wpTextbox1
2258 * Subclasses can override this to provide a custom UI for editing;
2259 * be it a form, or simply wpTextbox1 with a modified content that will be
2260 * reverse modified when extracted from the post data.
2261 * Note that this is basically the inverse for importContentFormData
2263 protected function showContentForm() {
2264 $this->showTextbox1();
2268 * Method to output wpTextbox1
2269 * The $textoverride method can be used by subclasses overriding showContentForm
2270 * to pass back to this method.
2272 * @param $customAttribs An array of html attributes to use in the textarea
2273 * @param $textoverride String: optional text to override $this->textarea1 with
2275 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2276 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2277 $attribs = array( 'style' => 'display:none;' );
2279 $classes = array(); // Textarea CSS
2280 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2281 # Is the title semi-protected?
2282 if ( $this->mTitle
->isSemiProtected() ) {
2283 $classes[] = 'mw-textarea-sprotected';
2285 # Then it must be protected based on static groups (regular)
2286 $classes[] = 'mw-textarea-protected';
2288 # Is the title cascade-protected?
2289 if ( $this->mTitle
->isCascadeProtected() ) {
2290 $classes[] = 'mw-textarea-cprotected';
2294 $attribs = array( 'tabindex' => 1 );
2296 if ( is_array( $customAttribs ) ) {
2297 $attribs +
= $customAttribs;
2300 if ( count( $classes ) ) {
2301 if ( isset( $attribs['class'] ) ) {
2302 $classes[] = $attribs['class'];
2304 $attribs['class'] = implode( ' ', $classes );
2308 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2311 protected function showTextbox2() {
2312 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2315 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2316 global $wgOut, $wgUser;
2318 $wikitext = $this->safeUnicodeOutput( $text );
2319 if ( strval($wikitext) !== '' ) {
2320 // Ensure there's a newline at the end, otherwise adding lines
2322 // But don't add a newline if the ext is empty, or Firefox in XHTML
2323 // mode will show an extra newline. A bit annoying.
2327 $attribs = $customAttribs +
array(
2330 'cols' => $wgUser->getIntOption( 'cols' ),
2331 'rows' => $wgUser->getIntOption( 'rows' ),
2332 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2335 $pageLang = $this->mTitle
->getPageLanguage();
2336 $attribs['lang'] = $pageLang->getCode();
2337 $attribs['dir'] = $pageLang->getDir();
2339 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2342 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2346 $classes[] = 'ontop';
2348 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2350 if ( $this->formtype
!= 'preview' )
2351 $attribs['style'] = 'display: none;';
2353 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2355 if ( $this->formtype
== 'preview' ) {
2356 $this->showPreview( $previewOutput );
2359 $wgOut->addHTML( '</div>' );
2361 if ( $this->formtype
== 'diff') {
2367 * Append preview output to $wgOut.
2368 * Includes category rendering if this is a category page.
2370 * @param $text String: the HTML to be output for the preview.
2372 protected function showPreview( $text ) {
2374 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2375 $this->mArticle
->openShowCategory();
2377 # This hook seems slightly odd here, but makes things more
2378 # consistent for extensions.
2379 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
2380 $wgOut->addHTML( $text );
2381 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2382 $this->mArticle
->closeShowCategory();
2387 * Get a diff between the current contents of the edit box and the
2388 * version of the page we're editing from.
2390 * If this is a section edit, we'll replace the section as for final
2391 * save and then make a comparison.
2393 function showDiff() {
2394 global $wgUser, $wgContLang, $wgOut;
2396 $oldContent = $this->getOriginalContent();
2398 $textboxContent = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(),
2399 $this->content_model
, $this->content_format
);
2401 $newContent = $this->mArticle
->replaceSectionContent(
2402 $this->section
, $textboxContent,
2403 $this->summary
, $this->edittime
);
2405 # hanlde legacy text-based hook
2406 $newtext_orig = $newContent->serialize( $this->content_format
);
2407 $newtext = $newtext_orig; #clone
2408 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2410 if ( $newtext != $newtext_orig ) {
2411 #if the hook changed the text, create a new Content object accordingly.
2412 $newContent = ContentHandler
::makeContent( $newtext, $this->getTitle(), $newContent->getModelName() );
2415 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) ); #FIXME: document new hook
2417 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2418 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2420 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2421 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2422 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2424 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2425 $de->setText( $oldContent, $newContent ); #FIXME: content-based diff!
2426 $difftext = $de->getDiff( $oldtitle, $newtitle );
2427 $de->showDiffStyle();
2432 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2436 * Give a chance for site and per-namespace customizations of
2437 * terms of service summary link that might exist separately
2438 * from the copyright notice.
2440 * This will display between the save button and the edit tools,
2441 * so should remain short!
2443 protected function showTosSummary() {
2444 $msg = 'editpage-tos-summary';
2445 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2446 if( !wfMessage( $msg )->isDisabled() ) {
2448 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2449 $wgOut->addWikiMsg( $msg );
2450 $wgOut->addHTML( '</div>' );
2454 protected function showEditTools() {
2456 $wgOut->addHTML( '<div class="mw-editTools">' .
2457 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2461 protected function getCopywarn() {
2462 global $wgRightsText;
2463 if ( $wgRightsText ) {
2464 $copywarnMsg = array( 'copyrightwarning',
2465 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2468 $copywarnMsg = array( 'copyrightwarning2',
2469 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2471 // Allow for site and per-namespace customization of contribution/copyright notice.
2472 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2474 return "<div id=\"editpage-copywarn\">\n" .
2475 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
2478 protected function showStandardInputs( &$tabindex = 2 ) {
2480 $wgOut->addHTML( "<div class='editOptions'>\n" );
2482 if ( $this->section
!= 'new' ) {
2483 $this->showSummaryInput( false, $this->summary
);
2484 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2487 $checkboxes = $this->getCheckboxes( $tabindex,
2488 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2489 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2490 $wgOut->addHTML( "<div class='editButtons'>\n" );
2491 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2493 $cancel = $this->getCancelLink();
2494 if ( $cancel !== '' ) {
2495 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2497 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2498 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
2499 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
2500 htmlspecialchars( wfMsg( 'newwindow' ) );
2501 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2502 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2506 * Show an edit conflict. textbox1 is already shown in showEditForm().
2507 * If you want to use another entry point to this function, be careful.
2509 protected function showConflict() {
2512 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2513 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2515 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2516 $de->setText( $this->textbox2
, $this->textbox1
);
2517 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2519 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2520 $this->showTextbox2();
2527 public function getCancelLink() {
2528 $cancelParams = array();
2529 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2530 $cancelParams['oldid'] = $this->oldid
;
2533 return Linker
::linkKnown(
2534 $this->getContextTitle(),
2535 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2536 array( 'id' => 'mw-editform-cancel' ),
2542 * Returns the URL to use in the form's action attribute.
2543 * This is used by EditPage subclasses when simply customizing the action
2544 * variable in the constructor is not enough. This can be used when the
2545 * EditPage lives inside of a Special page rather than a custom page action.
2547 * @param $title Title object for which is being edited (where we go to for &action= links)
2550 protected function getActionURL( Title
$title ) {
2551 return $title->getLocalURL( array( 'action' => $this->action
) );
2555 * Check if a page was deleted while the user was editing it, before submit.
2556 * Note that we rely on the logging table, which hasn't been always there,
2557 * but that doesn't matter, because this only applies to brand new
2560 protected function wasDeletedSinceLastEdit() {
2561 if ( $this->deletedSinceEdit
!== null ) {
2562 return $this->deletedSinceEdit
;
2565 $this->deletedSinceEdit
= false;
2567 if ( $this->mTitle
->isDeletedQuick() ) {
2568 $this->lastDelete
= $this->getLastDelete();
2569 if ( $this->lastDelete
) {
2570 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2571 if ( $deleteTime > $this->starttime
) {
2572 $this->deletedSinceEdit
= true;
2577 return $this->deletedSinceEdit
;
2580 protected function getLastDelete() {
2581 $dbr = wfGetDB( DB_SLAVE
);
2582 $data = $dbr->selectRow(
2583 array( 'logging', 'user' ),
2594 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2595 'log_title' => $this->mTitle
->getDBkey(),
2596 'log_type' => 'delete',
2597 'log_action' => 'delete',
2598 'user_id=log_user' ),
2600 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2602 // Quick paranoid permission checks...
2603 if( is_object( $data ) ) {
2604 if( $data->log_deleted
& LogPage
::DELETED_USER
)
2605 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2606 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2607 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2613 * Get the rendered text for previewing.
2616 function getPreviewText() {
2617 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2619 wfProfileIn( __METHOD__
);
2621 if ( $wgRawHtml && !$this->mTokenOk
) {
2622 // Could be an offsite preview attempt. This is very unsafe if
2623 // HTML is enabled, as it could be an attack.
2625 if ( $this->textbox1
!== '' ) {
2626 // Do not put big scary notice, if previewing the empty
2627 // string, which happens when you initially edit
2628 // a category page, due to automatic preview-on-open.
2629 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2630 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2632 wfProfileOut( __METHOD__
);
2636 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2637 if ( $this->mTokenOkExceptSuffix
) {
2638 $note = wfMsg( 'token_suffix_mismatch' );
2640 $note = wfMsg( 'session_fail_preview' );
2642 } elseif ( $this->incompleteForm
) {
2643 $note = wfMsg( 'edit_form_incomplete' );
2645 $note = wfMsg( 'previewnote' );
2648 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2649 $parserOptions->setEditSection( false );
2650 $parserOptions->setTidy( true );
2651 $parserOptions->setIsPreview( true );
2652 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2654 # don't parse non-wikitext pages, show message about preview
2655 # XXX: stupid php bug won't let us use $this->getContextTitle()->isCssJsSubpage() here -- This note has been there since r3530. Sure the bug was fixed time ago?
2657 #FIXME: get appropriate content handler!
2658 if ( $this->isCssJsSubpage ||
!$this->mTitle
->isWikitextPage() ) {
2659 if( $this->mTitle
->isCssJsSubpage() ) {
2661 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2667 # Used messages to make sure grep find them:
2668 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2670 #FIXME: move this crud into ContentHandler class!
2671 if (preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2672 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2673 $class = "mw-code mw-css";
2674 } elseif (preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2675 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2676 $class = "mw-code mw-js";
2678 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2682 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2683 $previewHTML = $parserOutput->mText
;
2684 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2686 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2688 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2690 $toparse = $this->textbox1
;
2692 # If we're adding a comment, we need to show the
2693 # summary as the headline
2694 if ( $this->section
== "new" && $this->summary
!= "" ) {
2695 $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $toparse;
2698 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2700 $parserOptions->enableLimitReport();
2702 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle
, $wgUser, $parserOptions );
2703 $parserOutput = $wgParser->parse( $toparse, $this->mTitle
, $parserOptions );
2705 $previewHTML = $parserOutput->getText();
2706 $this->mParserOutput
= $parserOutput;
2707 $wgOut->addParserOutputNoText( $parserOutput );
2709 if ( count( $parserOutput->getWarnings() ) ) {
2710 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2715 if( $this->isConflict
) {
2716 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2718 $conflict = '<hr />';
2721 $previewhead = "<div class='previewnote'>\n" .
2722 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2723 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2725 $pageLang = $this->mTitle
->getPageLanguage();
2726 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2727 'class' => 'mw-content-'.$pageLang->getDir() );
2728 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2730 wfProfileOut( __METHOD__
);
2731 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2737 function getTemplates() {
2738 if ( $this->preview ||
$this->section
!= '' ) {
2739 $templates = array();
2740 if ( !isset( $this->mParserOutput
) ) {
2743 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
2744 foreach( array_keys( $template ) as $dbk ) {
2745 $templates[] = Title
::makeTitle($ns, $dbk);
2750 return $this->mTitle
->getTemplateLinksFrom();
2755 * Shows a bulletin board style toolbar for common editing functions.
2756 * It can be disabled in the user preferences.
2757 * The necessary JavaScript code can be found in skins/common/edit.js.
2761 static function getEditToolbar() {
2762 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2763 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2765 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2768 * $toolarray is an array of arrays each of which includes the
2769 * filename of the button image (without path), the opening
2770 * tag, the closing tag, optionally a sample text that is
2771 * inserted between the two when no selection is highlighted
2772 * and. The tip text is shown when the user moves the mouse
2775 * Also here: accesskeys (key), which are not used yet until
2776 * someone can figure out a way to make them work in
2777 * IE. However, we should make sure these keys are not defined
2782 'image' => $wgLang->getImageFile( 'button-bold' ),
2783 'id' => 'mw-editbutton-bold',
2785 'close' => '\'\'\'',
2786 'sample' => wfMsg( 'bold_sample' ),
2787 'tip' => wfMsg( 'bold_tip' ),
2791 'image' => $wgLang->getImageFile( 'button-italic' ),
2792 'id' => 'mw-editbutton-italic',
2795 'sample' => wfMsg( 'italic_sample' ),
2796 'tip' => wfMsg( 'italic_tip' ),
2800 'image' => $wgLang->getImageFile( 'button-link' ),
2801 'id' => 'mw-editbutton-link',
2804 'sample' => wfMsg( 'link_sample' ),
2805 'tip' => wfMsg( 'link_tip' ),
2809 'image' => $wgLang->getImageFile( 'button-extlink' ),
2810 'id' => 'mw-editbutton-extlink',
2813 'sample' => wfMsg( 'extlink_sample' ),
2814 'tip' => wfMsg( 'extlink_tip' ),
2818 'image' => $wgLang->getImageFile( 'button-headline' ),
2819 'id' => 'mw-editbutton-headline',
2822 'sample' => wfMsg( 'headline_sample' ),
2823 'tip' => wfMsg( 'headline_tip' ),
2826 $imagesAvailable ?
array(
2827 'image' => $wgLang->getImageFile( 'button-image' ),
2828 'id' => 'mw-editbutton-image',
2829 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2831 'sample' => wfMsg( 'image_sample' ),
2832 'tip' => wfMsg( 'image_tip' ),
2835 $imagesAvailable ?
array(
2836 'image' => $wgLang->getImageFile( 'button-media' ),
2837 'id' => 'mw-editbutton-media',
2838 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2840 'sample' => wfMsg( 'media_sample' ),
2841 'tip' => wfMsg( 'media_tip' ),
2845 'image' => $wgLang->getImageFile( 'button-math' ),
2846 'id' => 'mw-editbutton-math',
2848 'close' => "</math>",
2849 'sample' => wfMsg( 'math_sample' ),
2850 'tip' => wfMsg( 'math_tip' ),
2854 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2855 'id' => 'mw-editbutton-nowiki',
2856 'open' => "<nowiki>",
2857 'close' => "</nowiki>",
2858 'sample' => wfMsg( 'nowiki_sample' ),
2859 'tip' => wfMsg( 'nowiki_tip' ),
2863 'image' => $wgLang->getImageFile( 'button-sig' ),
2864 'id' => 'mw-editbutton-signature',
2868 'tip' => wfMsg( 'sig_tip' ),
2872 'image' => $wgLang->getImageFile( 'button-hr' ),
2873 'id' => 'mw-editbutton-hr',
2874 'open' => "\n----\n",
2877 'tip' => wfMsg( 'hr_tip' ),
2882 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
2883 foreach ( $toolarray as $tool ) {
2889 $image = $wgStylePath . '/common/images/' . $tool['image'],
2890 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2891 // Older browsers show a "speedtip" type message only for ALT.
2892 // Ideally these should be different, realistically they
2893 // probably don't need to be.
2894 $tip = $tool['tip'],
2895 $open = $tool['open'],
2896 $close = $tool['close'],
2897 $sample = $tool['sample'],
2898 $cssId = $tool['id'],
2901 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2904 // This used to be called on DOMReady from mediawiki.action.edit, which
2905 // ended up causing race conditions with the setup code above.
2907 "// Create button bar\n" .
2908 "$(function() { mw.toolbar.init(); } );\n";
2911 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2913 $toolbar = '<div id="toolbar"></div>';
2915 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2921 * Returns an array of html code of the following checkboxes:
2924 * @param $tabindex Current tabindex
2925 * @param $checked Array of checkbox => bool, where bool indicates the checked
2926 * status of the checkbox
2930 public function getCheckboxes( &$tabindex, $checked ) {
2933 $checkboxes = array();
2935 // don't show the minor edit checkbox if it's a new page or section
2936 if ( !$this->isNew
) {
2937 $checkboxes['minor'] = '';
2938 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2939 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2941 'tabindex' => ++
$tabindex,
2942 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2943 'id' => 'wpMinoredit',
2945 $checkboxes['minor'] =
2946 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2947 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2948 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2949 ">{$minorLabel}</label>";
2953 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2954 $checkboxes['watch'] = '';
2955 if ( $wgUser->isLoggedIn() ) {
2957 'tabindex' => ++
$tabindex,
2958 'accesskey' => wfMsg( 'accesskey-watch' ),
2959 'id' => 'wpWatchthis',
2961 $checkboxes['watch'] =
2962 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2963 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2964 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2965 ">{$watchLabel}</label>";
2967 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2972 * Returns an array of html code of the following buttons:
2973 * save, diff, preview and live
2975 * @param $tabindex Current tabindex
2979 public function getEditButtons( &$tabindex ) {
2986 'tabindex' => ++
$tabindex,
2987 'value' => wfMsg( 'savearticle' ),
2988 'accesskey' => wfMsg( 'accesskey-save' ),
2989 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2991 $buttons['save'] = Xml
::element('input', $temp, '');
2993 ++
$tabindex; // use the same for preview and live preview
2995 'id' => 'wpPreview',
2996 'name' => 'wpPreview',
2998 'tabindex' => $tabindex,
2999 'value' => wfMsg( 'showpreview' ),
3000 'accesskey' => wfMsg( 'accesskey-preview' ),
3001 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
3003 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3004 $buttons['live'] = '';
3010 'tabindex' => ++
$tabindex,
3011 'value' => wfMsg( 'showdiff' ),
3012 'accesskey' => wfMsg( 'accesskey-diff' ),
3013 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
3015 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3017 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3022 * Output preview text only. This can be sucked into the edit page
3023 * via JavaScript, and saves the server time rendering the skin as
3024 * well as theoretically being more robust on the client (doesn't
3025 * disturb the edit box's undo history, won't eat your text on
3028 * @todo This doesn't include category or interlanguage links.
3029 * Would need to enhance it a bit, <s>maybe wrap them in XML
3030 * or something...</s> that might also require more skin
3031 * initialization, so check whether that's a problem.
3033 function livePreview() {
3036 header( 'Content-type: text/xml; charset=utf-8' );
3037 header( 'Cache-control: no-cache' );
3039 $previewText = $this->getPreviewText();
3040 #$categories = $skin->getCategoryLinks();
3043 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3044 Xml
::tags( 'livepreview', null,
3045 Xml
::element( 'preview', null, $previewText )
3046 #. Xml::element( 'category', null, $categories )
3052 * Call the stock "user is blocked" page
3054 * @deprecated in 1.19; throw an exception directly instead
3056 function blockedPage() {
3057 wfDeprecated( __METHOD__
, '1.19' );
3060 throw new UserBlockedError( $wgUser->mBlock
);
3064 * Produce the stock "please login to edit pages" page
3066 * @deprecated in 1.19; throw an exception directly instead
3068 function userNotLoggedInPage() {
3069 wfDeprecated( __METHOD__
, '1.19' );
3070 throw new PermissionsError( 'edit' );
3074 * Show an error page saying to the user that he has insufficient permissions
3075 * to create a new page
3077 * @deprecated in 1.19; throw an exception directly instead
3079 function noCreatePermission() {
3080 wfDeprecated( __METHOD__
, '1.19' );
3081 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3082 throw new PermissionsError( $permission );
3086 * Creates a basic error page which informs the user that
3087 * they have attempted to edit a nonexistent section.
3089 function noSuchSectionPage() {
3092 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3094 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
3095 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3096 $wgOut->addHTML( $res );
3098 $wgOut->returnToMain( false, $this->mTitle
);
3102 * Produce the stock "your edit contains spam" page
3104 * @param $match Text which triggered one or more filters
3105 * @deprecated since 1.17 Use method spamPageWithContent() instead
3107 static function spamPage( $match = false ) {
3108 wfDeprecated( __METHOD__
, '1.17' );
3110 global $wgOut, $wgTitle;
3112 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3114 $wgOut->addHTML( '<div id="spamprotected">' );
3115 $wgOut->addWikiMsg( 'spamprotectiontext' );
3117 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3119 $wgOut->addHTML( '</div>' );
3121 $wgOut->returnToMain( false, $wgTitle );
3125 * Show "your edit contains spam" page with your diff and text
3127 * @param $match Text which triggered one or more filters
3129 public function spamPageWithContent( $match = false ) {
3131 $this->textbox2
= $this->textbox1
;
3133 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3135 $wgOut->addHTML( '<div id="spamprotected">' );
3136 $wgOut->addWikiMsg( 'spamprotectiontext' );
3138 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3140 $wgOut->addHTML( '</div>' );
3142 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3143 $de = new DifferenceEngine( $this->mArticle
->getContext() ); #FIXME: get from content handler!
3145 $de->setText( $this->getCurrentText(), $this->textbox2
); #FIXME: make Content based
3147 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
3149 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3150 $this->showTextbox2();
3152 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3156 * Format an anchor fragment as it would appear for a given section name
3157 * @param $text String
3161 function sectionAnchor( $text ) {
3163 return $wgParser->guessSectionNameFromWikiText( $text );
3167 * Check if the browser is on a blacklist of user-agents known to
3168 * mangle UTF-8 data on form submission. Returns true if Unicode
3169 * should make it through, false if it's known to be a problem.
3173 function checkUnicodeCompliantBrowser() {
3174 global $wgBrowserBlackList;
3175 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
3176 // No User-Agent header sent? Trust it by default...
3179 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
3180 foreach ( $wgBrowserBlackList as $browser ) {
3181 if ( preg_match($browser, $currentbrowser) ) {
3189 * Filter an input field through a Unicode de-armoring process if it
3190 * came from an old browser with known broken Unicode editing issues.
3192 * @param $request WebRequest
3193 * @param $field String
3197 function safeUnicodeInput( $request, $field ) {
3198 $text = rtrim( $request->getText( $field ) );
3199 return $request->getBool( 'safemode' )
3200 ?
$this->unmakesafe( $text )
3205 * @param $request WebRequest
3206 * @param $text string
3209 function safeUnicodeText( $request, $text ) {
3210 $text = rtrim( $text );
3211 return $request->getBool( 'safemode' )
3212 ?
$this->unmakesafe( $text )
3217 * Filter an output field through a Unicode armoring process if it is
3218 * going to an old browser with known broken Unicode editing issues.
3220 * @param $text String
3224 function safeUnicodeOutput( $text ) {
3226 $codedText = $wgContLang->recodeForEdit( $text );
3227 return $this->checkUnicodeCompliantBrowser()
3229 : $this->makesafe( $codedText );
3233 * A number of web browsers are known to corrupt non-ASCII characters
3234 * in a UTF-8 text editing environment. To protect against this,
3235 * detected browsers will be served an armored version of the text,
3236 * with non-ASCII chars converted to numeric HTML character references.
3238 * Preexisting such character references will have a 0 added to them
3239 * to ensure that round-trips do not alter the original data.
3241 * @param $invalue String
3245 function makesafe( $invalue ) {
3246 // Armor existing references for reversability.
3247 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3252 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3253 $bytevalue = ord( $invalue[$i] );
3254 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
3255 $result .= chr( $bytevalue );
3257 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
3258 $working = $working << 6;
3259 $working +
= ($bytevalue & 0x3F);
3261 if ( $bytesleft <= 0 ) {
3262 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3264 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
3265 $working = $bytevalue & 0x1F;
3267 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
3268 $working = $bytevalue & 0x0F;
3270 } else { //1111 0xxx
3271 $working = $bytevalue & 0x07;
3279 * Reverse the previously applied transliteration of non-ASCII characters
3280 * back to UTF-8. Used to protect data from corruption by broken web browsers
3281 * as listed in $wgBrowserBlackList.
3283 * @param $invalue String
3287 function unmakesafe( $invalue ) {
3289 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3290 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+
3] != '0' ) ) {
3294 $hexstring .= $invalue[$i];
3296 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3298 // Do some sanity checks. These aren't needed for reversability,
3299 // but should help keep the breakage down if the editor
3300 // breaks one of the entities whilst editing.
3301 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
3302 $codepoint = hexdec($hexstring);
3303 $result .= codepointToUtf8( $codepoint );
3305 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3308 $result .= substr( $invalue, $i, 1 );
3311 // reverse the transform that we made for reversability reasons.
3312 return strtr( $result, array( "�" => "&#x" ) );