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;
148 * Status: can't parse content
150 const AS_PARSE_ERROR
= 240;
161 private $mContextTitle = null;
162 var $action = 'submit';
163 var $isConflict = false;
164 var $isCssJsSubpage = false;
165 var $isCssSubpage = false;
166 var $isJsSubpage = false;
167 var $isWrongCaseCssJsPage = false;
168 var $isNew = false; // new page or new section
169 var $deletedSinceEdit;
173 var $mTokenOk = false;
174 var $mTokenOkExceptSuffix = false;
175 var $mTriedSave = false;
176 var $incompleteForm = false;
178 var $kblength = false;
179 var $missingComment = false;
180 var $missingSummary = false;
181 var $allowBlankSummary = false;
184 #var $mPreviewTemplates;
191 var $mBaseRevision = false;
192 var $mShowSummaryField = true;
195 var $save = false, $preview = false, $diff = false;
196 var $minoredit = false, $watchthis = false, $recreate = false;
197 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
198 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
199 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
200 var $content_model = null, $content_format = null;
202 # Placeholders for text injection by hooks (must be HTML)
203 # extensions should take care to _append_ to the present value
204 public $editFormPageTop = ''; // Before even the preview
205 public $editFormTextTop = '';
206 public $editFormTextBeforeContent = '';
207 public $editFormTextAfterWarn = '';
208 public $editFormTextAfterTools = '';
209 public $editFormTextBottom = '';
210 public $editFormTextAfterContent = '';
211 public $previewTextAfterContent = '';
212 public $mPreloadContent = null;
214 /* $didSave should be set to true whenever an article was succesfully altered. */
215 public $didSave = false;
216 public $undidRev = 0;
218 public $suppressIntro = false;
221 * @param $article Article
223 public function __construct( Article
$article ) {
224 $this->mArticle
= $article;
225 $this->mTitle
= $article->getTitle();
227 $this->content_model
= $this->mTitle
->getContentModelName();
229 $handler = ContentHandler
::getForModelName( $this->content_model
);
230 $this->content_format
= $handler->getDefaultFormat(); #NOTE: should be overridden by format of actual revision
236 public function getArticle() {
237 return $this->mArticle
;
244 public function getTitle() {
245 return $this->mTitle
;
249 * Set the context Title object
251 * @param $title Title object or null
253 public function setContextTitle( $title ) {
254 $this->mContextTitle
= $title;
258 * Get the context title object.
259 * If not set, $wgTitle will be returned. This behavior might changed in
260 * the future to return $this->mTitle instead.
262 * @return Title object
264 public function getContextTitle() {
265 if ( is_null( $this->mContextTitle
) ) {
269 return $this->mContextTitle
;
278 * This is the function that gets called for "action=edit". It
279 * sets up various member variables, then passes execution to
280 * another function, usually showEditForm()
282 * The edit form is self-submitting, so that when things like
283 * preview and edit conflicts occur, we get the same form back
284 * with the extra stuff added. Only when the final submission
285 * is made and all is well do we actually save and redirect to
286 * the newly-edited page.
289 global $wgOut, $wgRequest, $wgUser;
290 // Allow extensions to modify/prevent this form or submission
291 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
295 wfProfileIn( __METHOD__
);
296 wfDebug( __METHOD__
.": enter\n" );
298 // If they used redlink=1 and the page exists, redirect to the main article
299 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
300 $wgOut->redirect( $this->mTitle
->getFullURL() );
301 wfProfileOut( __METHOD__
);
305 $this->importFormData( $wgRequest );
306 $this->firsttime
= false;
309 $this->livePreview();
310 wfProfileOut( __METHOD__
);
314 if ( wfReadOnly() && $this->save
) {
317 $this->preview
= true;
321 $this->formtype
= 'save';
322 } elseif ( $this->preview
) {
323 $this->formtype
= 'preview';
324 } elseif ( $this->diff
) {
325 $this->formtype
= 'diff';
326 } else { # First time through
327 $this->firsttime
= true;
328 if ( $this->previewOnOpen() ) {
329 $this->formtype
= 'preview';
331 $this->formtype
= 'initial';
335 $permErrors = $this->getEditPermissionErrors();
337 wfDebug( __METHOD__
. ": User can't edit\n" );
338 // Auto-block user's IP if the account was "hard" blocked
339 $wgUser->spreadAnyEditBlock();
341 $this->displayPermissionsError( $permErrors );
343 wfProfileOut( __METHOD__
);
347 wfProfileIn( __METHOD__
."-business-end" );
349 $this->isConflict
= false;
350 // css / js subpages of user pages get a special treatment
351 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
352 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
353 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
354 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
355 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
357 # Show applicable editing introductions
358 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
362 # Attempt submission here. This will check for edit conflicts,
363 # and redundantly check for locked database, blocked IPs, etc.
364 # that edit() already checked just in case someone tries to sneak
365 # in the back door with a hand-edited submission URL.
367 if ( 'save' == $this->formtype
) {
368 if ( !$this->attemptSave() ) {
369 wfProfileOut( __METHOD__
."-business-end" );
370 wfProfileOut( __METHOD__
);
375 # First time through: get contents, set time for conflict
377 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
378 if ( $this->initialiseForm() === false ) {
379 $this->noSuchSectionPage();
380 wfProfileOut( __METHOD__
."-business-end" );
381 wfProfileOut( __METHOD__
);
384 if ( !$this->mTitle
->getArticleId() )
385 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
387 wfRunHooks( 'EditFormInitialText', array( $this ) );
390 $this->showEditForm();
391 wfProfileOut( __METHOD__
."-business-end" );
392 wfProfileOut( __METHOD__
);
398 protected function getEditPermissionErrors() {
400 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
401 # Can this title be created?
402 if ( !$this->mTitle
->exists() ) {
403 $permErrors = array_merge( $permErrors,
404 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
406 # Ignore some permissions errors when a user is just previewing/viewing diffs
408 foreach( $permErrors as $error ) {
409 if ( ( $this->preview ||
$this->diff
) &&
410 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
415 $permErrors = wfArrayDiff2( $permErrors, $remove );
420 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
421 * but with the following differences:
422 * - If redlink=1, the user will be redirected to the page
423 * - If there is content to display or the error occurs while either saving,
424 * previewing or showing the difference, it will be a
425 * "View source for ..." page displaying the source code after the error message.
428 * @param $permErrors Array of permissions errors, as returned by
429 * Title::getUserPermissionsErrors().
431 protected function displayPermissionsError( array $permErrors ) {
432 global $wgRequest, $wgOut;
434 if ( $wgRequest->getBool( 'redlink' ) ) {
435 // The edit page was reached via a red link.
436 // Redirect to the article page and let them click the edit tab if
437 // they really want a permission error.
438 $wgOut->redirect( $this->mTitle
->getFullUrl() );
442 $content = $this->getContentObject();
444 # Use the normal message if there's nothing to display
445 if ( $this->firsttime
&& $content->isEmpty() ) {
446 $action = $this->mTitle
->exists() ?
'edit' :
447 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
448 throw new PermissionsError( $action, $permErrors );
451 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
452 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
453 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
454 $wgOut->addHTML( "<hr />\n" );
456 # If the user made changes, preserve them when showing the markup
457 # (This happens when a user is blocked during edit, for instance)
458 if ( !$this->firsttime
) {
459 $text = $this->textbox1
;
460 $wgOut->addWikiMsg( 'viewyourtext' );
462 $text = $content->serialize( $this->content_format
);
463 $wgOut->addWikiMsg( 'viewsourcetext' );
466 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
468 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
469 Linker
::formatTemplates( $this->getTemplates() ) ) );
471 if ( $this->mTitle
->exists() ) {
472 $wgOut->returnToMain( null, $this->mTitle
);
477 * Show a read-only error
478 * Parameters are the same as OutputPage:readOnlyPage()
479 * Redirect to the article page if redlink=1
480 * @deprecated in 1.19; use displayPermissionsError() instead
482 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
483 wfDeprecated( __METHOD__
, '1.19' );
485 global $wgRequest, $wgOut;
486 if ( $wgRequest->getBool( 'redlink' ) ) {
487 // The edit page was reached via a red link.
488 // Redirect to the article page and let them click the edit tab if
489 // they really want a permission error.
490 $wgOut->redirect( $this->mTitle
->getFullUrl() );
492 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
497 * Should we show a preview when the edit form is first shown?
501 protected function previewOnOpen() {
502 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
503 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
504 // Explicit override from request
506 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
507 // Explicit override from request
509 } elseif ( $this->section
== 'new' ) {
510 // Nothing *to* preview for new sections
512 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
513 // Standard preference behaviour
515 } elseif ( !$this->mTitle
->exists() &&
516 isset($wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]) &&
517 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
519 // Categories are special
527 * Checks whether the user entered a skin name in uppercase,
528 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
532 protected function isWrongCaseCssJsPage() {
533 if( $this->mTitle
->isCssJsSubpage() ) {
534 $name = $this->mTitle
->getSkinFromCssJsSubpage();
535 $skins = array_merge(
536 array_keys( Skin
::getSkinNames() ),
539 return !in_array( $name, $skins )
540 && in_array( strtolower( $name ), $skins );
547 * Does this EditPage class support section editing?
548 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
552 protected function isSectionEditSupported() {
557 * This function collects the form data and uses it to populate various member variables.
558 * @param $request WebRequest
560 function importFormData( &$request ) {
561 global $wgLang, $wgUser;
563 wfProfileIn( __METHOD__
);
565 # Section edit can come from either the form or a link
566 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
568 if ( $request->wasPosted() ) {
569 # These fields need to be checked for encoding.
570 # Also remove trailing whitespace, but don't remove _initial_
571 # whitespace from the text boxes. This may be significant formatting.
572 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
573 if ( !$request->getCheck('wpTextbox2') ) {
574 // Skip this if wpTextbox2 has input, it indicates that we came
575 // from a conflict page with raw page text, not a custom form
576 // modified by subclasses
577 wfProfileIn( get_class($this)."::importContentFormData" );
578 $textbox1 = $this->importContentFormData( $request ); #FIXME: what should this return??
579 if ( isset($textbox1) )
580 $this->textbox1
= $textbox1;
581 wfProfileOut( get_class($this)."::importContentFormData" );
584 # Truncate for whole multibyte characters. +5 bytes for ellipsis
585 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
587 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
588 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
590 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
592 # Treat sectiontitle the same way as summary.
593 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
594 # currently doing double duty as both edit summary and section title. Right now this
595 # is just to allow API edits to work around this limitation, but this should be
596 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
597 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 250 );
598 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
600 $this->edittime
= $request->getVal( 'wpEdittime' );
601 $this->starttime
= $request->getVal( 'wpStarttime' );
603 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
605 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
606 // wpTextbox1 field is missing, possibly due to being "too big"
607 // according to some filter rules such as Suhosin's setting for
608 // suhosin.request.max_value_length (d'oh)
609 $this->incompleteForm
= true;
611 // edittime should be one of our last fields; if it's missing,
612 // the submission probably broke somewhere in the middle.
613 $this->incompleteForm
= is_null( $this->edittime
);
615 if ( $this->incompleteForm
) {
616 # If the form is incomplete, force to preview.
617 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
618 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
619 $this->preview
= true;
621 /* Fallback for live preview */
622 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
623 $this->diff
= $request->getCheck( 'wpDiff' );
625 // Remember whether a save was requested, so we can indicate
626 // if we forced preview due to session failure.
627 $this->mTriedSave
= !$this->preview
;
629 if ( $this->tokenOk( $request ) ) {
630 # Some browsers will not report any submit button
631 # if the user hits enter in the comment box.
632 # The unmarked state will be assumed to be a save,
633 # if the form seems otherwise complete.
634 wfDebug( __METHOD__
. ": Passed token check.\n" );
635 } elseif ( $this->diff
) {
636 # Failed token check, but only requested "Show Changes".
637 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
639 # Page might be a hack attempt posted from
640 # an external site. Preview instead of saving.
641 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
642 $this->preview
= true;
645 $this->save
= !$this->preview
&& !$this->diff
;
646 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
647 $this->edittime
= null;
650 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
651 $this->starttime
= null;
654 $this->recreate
= $request->getCheck( 'wpRecreate' );
656 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
657 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
659 # Don't force edit summaries when a user is editing their own user or talk page
660 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
661 $this->mTitle
->getText() == $wgUser->getName() )
663 $this->allowBlankSummary
= true;
665 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
668 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
670 # Not a posted form? Start with nothing.
671 wfDebug( __METHOD__
. ": Not a posted form.\n" );
672 $this->textbox1
= ''; #FIXME: track content object
674 $this->sectiontitle
= '';
675 $this->edittime
= '';
676 $this->starttime
= wfTimestampNow();
678 $this->preview
= false;
681 $this->minoredit
= false;
682 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
683 $this->recreate
= false;
685 // When creating a new section, we can preload a section title by passing it as the
686 // preloadtitle parameter in the URL (Bug 13100)
687 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
688 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
689 // Once wpSummary isn't being use for setting section titles, we should delete this.
690 $this->summary
= $request->getVal( 'preloadtitle' );
692 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
693 $this->summary
= $request->getText( 'summary' );
696 if ( $request->getVal( 'minor' ) ) {
697 $this->minoredit
= true;
701 $this->oldid
= $request->getInt( 'oldid' );
703 $this->bot
= $request->getBool( 'bot', true );
704 $this->nosummary
= $request->getBool( 'nosummary' );
706 $content_handler = ContentHandler
::getForTitle( $this->mTitle
);
707 $this->content_model
= $request->getText( 'model', $content_handler->getModelName() ); #may be overridden by revision
708 $this->content_format
= $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
710 #TODO: check if the desired model is allowed in this namespace, and if a transition from the page's current model to the new model is allowed
711 #TODO: check if the desired content model supports the given content format!
713 $this->live
= $request->getCheck( 'live' );
714 $this->editintro
= $request->getText( 'editintro',
715 // Custom edit intro for new sections
716 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
718 // Allow extensions to modify form data
719 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
721 wfProfileOut( __METHOD__
);
725 * Subpage overridable method for extracting the page content data from the
726 * posted form to be placed in $this->textbox1, if using customized input
727 * this method should be overrided and return the page text that will be used
728 * for saving, preview parsing and so on...
730 * @param $request WebRequest
732 protected function importContentFormData( &$request ) {
733 return; // Don't do anything, EditPage already extracted wpTextbox1
737 * Initialise form fields in the object
738 * Called on the first invocation, e.g. when a user clicks an edit link
739 * @return bool -- if the requested section is valid
741 function initialiseForm() {
743 $this->edittime
= $this->mArticle
->getTimestamp();
745 $content = $this->getContentObject( false ); #TODO: track content object?!
746 $this->textbox1
= $content->serialize( $this->content_format
);
748 // activate checkboxes if user wants them to be always active
749 # Sort out the "watch" checkbox
750 if ( $wgUser->getOption( 'watchdefault' ) ) {
752 $this->watchthis
= true;
753 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
755 $this->watchthis
= true;
756 } elseif ( $this->mTitle
->userIsWatching() ) {
758 $this->watchthis
= true;
760 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
761 $this->minoredit
= true;
763 if ( $this->textbox1
=== false ) {
771 * Fetch initial editing page content.
773 * @param $def_text string
774 * @return mixed string on success, $def_text for invalid sections
776 * @deprecated since 1.20
778 function getContent( $def_text = false ) { #FIXME: deprecated, replace usage!
779 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
780 $def_content = ContentHandler
::makeContent( $def_text, $this->getTitle() );
782 $def_content = false;
785 $content = $this->getContentObject( $def_content );
787 return $content->serialize( $this->content_format
); #XXX: really use serialized form? use ContentHandler::getContentText() instead?
790 private function getContentObject( $def_content = null ) { #FIXME: use this!
791 global $wgOut, $wgRequest;
793 wfProfileIn( __METHOD__
);
797 // For message page not locally set, use the i18n message.
798 // For other non-existent articles, use preload text if any.
799 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
800 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
801 # If this is a system message, get the default text.
802 $msg = $this->mTitle
->getDefaultMessageText();
804 $content = new WikitextContent($msg); //XXX: really hardcode wikitext here?
806 if ( $content === false ) {
807 # If requested, preload some text.
808 $preload = $wgRequest->getVal( 'preload',
809 // Custom preload text for new sections
810 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
812 $content = $this->getPreloadedContent( $preload );
814 // For existing pages, get text based on "undo" or section parameters.
816 if ( $this->section
!= '' ) {
817 // Get section edit text (returns $def_text for invalid sections)
818 $orig = $this->getOriginalContent();
819 $content = $orig ?
$orig->getSection( $this->section
) : null;
821 if ( !$content ) $content = $def_content;
823 $undoafter = $wgRequest->getInt( 'undoafter' );
824 $undo = $wgRequest->getInt( 'undo' );
826 if ( $undo > 0 && $undoafter > 0 ) {
827 if ( $undo < $undoafter ) {
828 # If they got undoafter and undo round the wrong way, switch them
829 list( $undo, $undoafter ) = array( $undoafter, $undo );
832 $undorev = Revision
::newFromId( $undo );
833 $oldrev = Revision
::newFromId( $undoafter );
835 # Sanity check, make sure it's the right page,
836 # the revisions exist and they were not deleted.
837 # Otherwise, $content will be left as-is.
838 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
839 $undorev->getPage() == $oldrev->getPage() &&
840 $undorev->getPage() == $this->mTitle
->getArticleId() &&
841 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
842 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
844 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
846 if ( $content === false ) {
847 # Warn the user that something went wrong
848 $undoMsg = 'failure';
850 # Inform the user of our success and set an automatic edit summary
851 $undoMsg = 'success';
853 # If we just undid one rev, use an autosummary
854 $firstrev = $oldrev->getNext();
855 if ( $firstrev->getId() == $undo ) {
856 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
857 if ( $this->summary
=== '' ) {
858 $this->summary
= $undoSummary;
860 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
862 $this->undidRev
= $undo;
864 $this->formtype
= 'diff';
867 // Failed basic sanity checks.
868 // Older revisions may have been removed since the link
869 // was created, or we may simply have got bogus input.
873 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"error mw-undo-{$undoMsg}\">" .
874 wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
877 if ( $content === false ) {
878 $content = $this->getOriginalContent();
883 wfProfileOut( __METHOD__
);
888 * Get the content of the wanted revision, without section extraction.
890 * The result of this function can be used to compare user's input with
891 * section replaced in its context (using WikiPage::replaceSection())
892 * to the original text of the edit.
894 * This difers from Article::getContent() that when a missing revision is
895 * encountered the result will be an empty string and not the
896 * 'missing-article' message.
901 private function getOriginalContent() { #FIXME: use Content! set content_model and content_format!
902 if ( $this->section
== 'new' ) {
903 return $this->getCurrentContent();
905 $revision = $this->mArticle
->getRevisionFetched();
906 if ( $revision === null ) {
907 if ( !$this->content_model
) $this->content_model
= $this->getTitle()->getContentModelName();
908 $handler = ContentHandler
::getForModelName( $this->content_model
);
910 return $handler->emptyContent();
913 $content = $this->mArticle
->getContentObject();
918 * Get the current content of the page. This is basically similar to
919 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
920 * content object is returned instead of null.
925 private function getCurrentContent() {
926 $rev = $this->mArticle
->getRevision();
927 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
929 if ( $content === false ||
$content === null ) {
930 if ( !$this->content_model
) $this->content_model
= $this->getTitle()->getContentModelName();
931 $handler = ContentHandler
::getForModelName( $this->content_model
);
933 return $handler->emptyContent();
935 #FIXME: nasty side-effect!
936 $this->content_model
= $rev->getContentModelName();
937 $this->content_format
= $rev->getContentFormat();
944 * Use this method before edit() to preload some text into the edit box
946 * @param $text string
947 * @deprecated since 1.20
949 public function setPreloadedText( $text ) { #FIXME: deprecated, use setPreloadedContent()
950 wfDeprecated( __METHOD__
, "1.20" );
952 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
954 $this->setPreloadedContent( $content );
958 * Use this method before edit() to preload some content into the edit box
960 * @param $content Content
962 public function setPreloadedContent( Content
$content ) { #FIXME: use this!
963 $this->mPreloadedContent
= $content;
967 * Get the contents to be preloaded into the box, either set by
968 * an earlier setPreloadText() or by loading the given page.
970 * @param $preload String: representing the title to preload from.
972 * @deprecated since 1.20
974 protected function getPreloadedText( $preload ) { #FIXME: B/C only, replace usage!
975 wfDeprecated( __METHOD__
, "1.20" );
977 $content = $this->getPreloadedContent( $preload );
978 $text = $content->serialize( $this->content_format
); #XXX: really use serialized form? use ContentHandler::getContentText() instead?!
983 protected function getPreloadedContent( $preload ) { #FIXME: use this!
986 if ( !empty( $this->mPreloadContent
) ) {
987 return $this->mPreloadContent
;
990 $handler = ContentHandler
::getForTitle( $this->getTitle() );
992 if ( $preload === '' ) {
993 return $handler->emptyContent();
996 $title = Title
::newFromText( $preload );
997 # Check for existence to avoid getting MediaWiki:Noarticletext
998 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
999 return $handler->emptyContent();
1002 $page = WikiPage
::factory( $title );
1003 if ( $page->isRedirect() ) {
1004 $title = $page->getRedirectTarget();
1006 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
1007 return $handler->emptyContent();
1009 $page = WikiPage
::factory( $title );
1012 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1013 $content = $page->getContent( Revision
::RAW
);
1015 return $content->preloadTransform( $title, $parserOptions );
1019 * Make sure the form isn't faking a user's credentials.
1021 * @param $request WebRequest
1025 function tokenOk( &$request ) {
1027 $token = $request->getVal( 'wpEditToken' );
1028 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1029 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1030 return $this->mTokenOk
;
1034 * Attempt submission
1035 * @return bool false if output is done, true if the rest of the form should be displayed
1037 function attemptSave() {
1038 global $wgUser, $wgOut;
1040 $resultDetails = false;
1041 # Allow bots to exempt some edits from bot flagging
1042 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1043 $status = $this->internalAttemptSave( $resultDetails, $bot );
1044 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1046 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1047 $this->didSave
= true;
1050 switch ( $status->value
) {
1051 case self
::AS_HOOK_ERROR_EXPECTED
:
1052 case self
::AS_CONTENT_TOO_BIG
:
1053 case self
::AS_ARTICLE_WAS_DELETED
:
1054 case self
::AS_CONFLICT_DETECTED
:
1055 case self
::AS_SUMMARY_NEEDED
:
1056 case self
::AS_TEXTBOX_EMPTY
:
1057 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1061 case self
::AS_HOOK_ERROR
:
1062 case self
::AS_FILTERING
:
1065 case self
::AS_PARSE_ERROR
:
1066 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>');
1067 #FIXME: cause editform to be shown again, not just an error!
1070 case self
::AS_SUCCESS_NEW_ARTICLE
:
1071 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1072 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1073 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1076 case self
::AS_SUCCESS_UPDATE
:
1078 $sectionanchor = $resultDetails['sectionanchor'];
1080 // Give extensions a chance to modify URL query on update
1081 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1083 if ( $resultDetails['redirect'] ) {
1084 if ( $extraQuery == '' ) {
1085 $extraQuery = 'redirect=no';
1087 $extraQuery = 'redirect=no&' . $extraQuery;
1090 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1093 case self
::AS_BLANK_ARTICLE
:
1094 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1097 case self
::AS_SPAM_ERROR
:
1098 $this->spamPageWithContent( $resultDetails['spam'] );
1101 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1102 throw new UserBlockedError( $wgUser->mBlock
);
1104 case self
::AS_IMAGE_REDIRECT_ANON
:
1105 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1106 throw new PermissionsError( 'upload' );
1108 case self
::AS_READ_ONLY_PAGE_ANON
:
1109 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1110 throw new PermissionsError( 'edit' );
1112 case self
::AS_READ_ONLY_PAGE
:
1113 throw new ReadOnlyError
;
1115 case self
::AS_RATE_LIMITED
:
1116 throw new ThrottledError();
1118 case self
::AS_NO_CREATE_PERMISSION
:
1119 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1120 throw new PermissionsError( $permission );
1127 * Attempt submission (no UI)
1132 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1134 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1135 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1136 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1138 function internalAttemptSave( &$result, $bot = false ) {
1139 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
1140 global $wgMaxArticleSize;
1142 $status = Status
::newGood();
1144 wfProfileIn( __METHOD__
);
1145 wfProfileIn( __METHOD__
. '-checks' );
1147 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1148 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1149 $status->fatal( 'hookaborted' );
1150 $status->value
= self
::AS_HOOK_ERROR
;
1151 wfProfileOut( __METHOD__
. '-checks' );
1152 wfProfileOut( __METHOD__
);
1156 # Check image redirect
1157 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1158 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&& #FIXME: use content handler to check for redirect
1159 !$wgUser->isAllowed( 'upload' ) ) {
1160 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1161 $status->setResult( false, $code );
1163 wfProfileOut( __METHOD__
. '-checks' );
1164 wfProfileOut( __METHOD__
);
1170 $match = self
::matchSummarySpamRegex( $this->summary
);
1171 if ( $match === false ) {
1172 $match = self
::matchSpamRegex( $this->textbox1
);
1174 if ( $match !== false ) {
1175 $result['spam'] = $match;
1176 $ip = $wgRequest->getIP();
1177 $pdbk = $this->mTitle
->getPrefixedDBkey();
1178 $match = str_replace( "\n", '', $match );
1179 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1180 $status->fatal( 'spamprotectionmatch', $match );
1181 $status->value
= self
::AS_SPAM_ERROR
;
1182 wfProfileOut( __METHOD__
. '-checks' );
1183 wfProfileOut( __METHOD__
);
1186 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
1187 # Error messages or other handling should be performed by the filter function
1188 $status->setResult( false, self
::AS_FILTERING
);
1189 wfProfileOut( __METHOD__
. '-checks' );
1190 wfProfileOut( __METHOD__
);
1193 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1194 # Error messages etc. could be handled within the hook...
1195 $status->fatal( 'hookaborted' );
1196 $status->value
= self
::AS_HOOK_ERROR
;
1197 wfProfileOut( __METHOD__
. '-checks' );
1198 wfProfileOut( __METHOD__
);
1200 } elseif ( $this->hookError
!= '' ) {
1201 # ...or the hook could be expecting us to produce an error
1202 $status->fatal( 'hookaborted' );
1203 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1204 wfProfileOut( __METHOD__
. '-checks' );
1205 wfProfileOut( __METHOD__
);
1209 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1210 // Auto-block user's IP if the account was "hard" blocked
1211 $wgUser->spreadAnyEditBlock();
1212 # Check block state against master, thus 'false'.
1213 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1214 wfProfileOut( __METHOD__
. '-checks' );
1215 wfProfileOut( __METHOD__
);
1219 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1220 if ( $this->kblength
> $wgMaxArticleSize ) {
1221 // Error will be displayed by showEditForm()
1222 $this->tooBig
= true;
1223 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1224 wfProfileOut( __METHOD__
. '-checks' );
1225 wfProfileOut( __METHOD__
);
1229 if ( !$wgUser->isAllowed( 'edit' ) ) {
1230 if ( $wgUser->isAnon() ) {
1231 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1232 wfProfileOut( __METHOD__
. '-checks' );
1233 wfProfileOut( __METHOD__
);
1236 $status->fatal( 'readonlytext' );
1237 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1238 wfProfileOut( __METHOD__
. '-checks' );
1239 wfProfileOut( __METHOD__
);
1244 if ( wfReadOnly() ) {
1245 $status->fatal( 'readonlytext' );
1246 $status->value
= self
::AS_READ_ONLY_PAGE
;
1247 wfProfileOut( __METHOD__
. '-checks' );
1248 wfProfileOut( __METHOD__
);
1251 if ( $wgUser->pingLimiter() ) {
1252 $status->fatal( 'actionthrottledtext' );
1253 $status->value
= self
::AS_RATE_LIMITED
;
1254 wfProfileOut( __METHOD__
. '-checks' );
1255 wfProfileOut( __METHOD__
);
1259 # If the article has been deleted while editing, don't save it without
1261 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1262 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1263 wfProfileOut( __METHOD__
. '-checks' );
1264 wfProfileOut( __METHOD__
);
1268 wfProfileOut( __METHOD__
. '-checks' );
1270 # If article is new, insert it.
1271 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1272 $new = ( $aid == 0 );
1276 // Late check for create permission, just in case *PARANOIA*
1277 if ( !$this->mTitle
->userCan( 'create' ) ) {
1278 $status->fatal( 'nocreatetext' );
1279 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1280 wfDebug( __METHOD__
. ": no create permission\n" );
1281 wfProfileOut( __METHOD__
);
1285 # Don't save a new article if it's blank.
1286 if ( $this->textbox1
== '' ) {
1287 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1288 wfProfileOut( __METHOD__
);
1292 // Run post-section-merge edit filter
1293 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1294 # Error messages etc. could be handled within the hook...
1295 $status->fatal( 'hookaborted' );
1296 $status->value
= self
::AS_HOOK_ERROR
;
1297 wfProfileOut( __METHOD__
);
1299 } elseif ( $this->hookError
!= '' ) {
1300 # ...or the hook could be expecting us to produce an error
1301 $status->fatal( 'hookaborted' );
1302 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1303 wfProfileOut( __METHOD__
);
1307 $content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
);
1309 # Handle the user preference to force summaries here. Check if it's not a redirect.
1310 if ( !$this->allowBlankSummary
&& !$content->isRedirect() ) {
1311 if ( md5( $this->summary
) == $this->autoSumm
) {
1312 $this->missingSummary
= true;
1313 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1314 $status->value
= self
::AS_SUMMARY_NEEDED
;
1315 wfProfileOut( __METHOD__
);
1320 $result['sectionanchor'] = '';
1321 if ( $this->section
== 'new' ) {
1322 if ( $this->sectiontitle
!== '' ) {
1323 // Insert the section title above the content.
1324 $content = $content->addSectionHeader( $this->sectiontitle
);
1326 // Jump to the new section
1327 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1329 // If no edit summary was specified, create one automatically from the section
1330 // title and have it link to the new section. Otherwise, respect the summary as
1332 if ( $this->summary
=== '' ) {
1333 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1334 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1336 } elseif ( $this->summary
!== '' ) {
1337 // Insert the section title above the content.
1338 $content = $content->addSectionHeader( $this->sectiontitle
);
1340 // Jump to the new section
1341 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1343 // Create a link to the new section from the edit summary.
1344 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1345 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1349 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1353 # Article exists. Check for edit conflict.
1355 $this->mArticle
->clear(); # Force reload of dates, etc.
1356 $timestamp = $this->mArticle
->getTimestamp();
1358 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1360 if ( $timestamp != $this->edittime
) {
1361 $this->isConflict
= true;
1362 if ( $this->section
== 'new' ) {
1363 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1364 $this->mArticle
->getComment() == $this->summary
) {
1365 // Probably a duplicate submission of a new comment.
1366 // This can happen when squid resends a request after
1367 // a timeout but the first one actually went through.
1368 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1370 // New comment; suppress conflict.
1371 $this->isConflict
= false;
1372 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1374 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1375 # Suppress edit conflict with self, except for section edits where merging is required.
1376 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1377 $this->isConflict
= false;
1381 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1382 // backwards compatibility with old forms/bots).
1383 if ( $this->sectiontitle
!== '' ) {
1384 $sectionTitle = $this->sectiontitle
;
1386 $sectionTitle = $this->summary
;
1389 $textbox_content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
);
1392 if ( $this->isConflict
) {
1393 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1395 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1397 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1399 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1402 if ( is_null( $content ) ) {
1403 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1404 $this->isConflict
= true;
1405 $content = $textbox_content; // do not try to merge here!
1406 } elseif ( $this->isConflict
) {
1408 if ( $this->mergeChangesIntoContent( $textbox_content ) ) {
1409 // Successful merge! Maybe we should tell the user the good news?
1410 $content = $textbox_content;
1411 $this->isConflict
= false;
1412 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1414 $this->section
= '';
1415 #$this->textbox1 = $text; #redundant, nothing to do here?
1416 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1420 if ( $this->isConflict
) {
1421 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1422 wfProfileOut( __METHOD__
);
1426 // Run post-section-merge edit filter
1427 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $content->serialize( $this->content_format
), &$this->hookError
, $this->summary
) )
1428 ||
!wfRunHooks( 'EditFilterMergedContent', array( $this, $content, &$this->hookError
, $this->summary
) ) ) { #FIXME: document new hook
1429 # Error messages etc. could be handled within the hook...
1430 $status->fatal( 'hookaborted' );
1431 $status->value
= self
::AS_HOOK_ERROR
;
1432 wfProfileOut( __METHOD__
);
1434 } elseif ( $this->hookError
!= '' ) {
1435 # ...or the hook could be expecting us to produce an error
1436 $status->fatal( 'hookaborted' );
1437 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1438 wfProfileOut( __METHOD__
);
1442 # Handle the user preference to force summaries here, but not for null edits
1443 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1444 && !$content->equals( $this->getOriginalContent() )
1445 && !$content->isRedirect() ) # check if it's not a redirect
1447 if ( md5( $this->summary
) == $this->autoSumm
) {
1448 $this->missingSummary
= true;
1449 $status->fatal( 'missingsummary' );
1450 $status->value
= self
::AS_SUMMARY_NEEDED
;
1451 wfProfileOut( __METHOD__
);
1456 # And a similar thing for new sections
1457 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1458 if ( trim( $this->summary
) == '' ) {
1459 $this->missingSummary
= true;
1460 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1461 $status->value
= self
::AS_SUMMARY_NEEDED
;
1462 wfProfileOut( __METHOD__
);
1468 wfProfileIn( __METHOD__
. '-sectionanchor' );
1469 $sectionanchor = '';
1470 if ( $this->section
== 'new' ) {
1471 if ( $this->textbox1
== '' ) {
1472 $this->missingComment
= true;
1473 $status->fatal( 'missingcommenttext' );
1474 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1475 wfProfileOut( __METHOD__
. '-sectionanchor' );
1476 wfProfileOut( __METHOD__
);
1479 if ( $this->sectiontitle
!== '' ) {
1480 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1481 // If no edit summary was specified, create one automatically from the section
1482 // title and have it link to the new section. Otherwise, respect the summary as
1484 if ( $this->summary
=== '' ) {
1485 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1486 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1488 } elseif ( $this->summary
!== '' ) {
1489 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1490 # This is a new section, so create a link to the new section
1491 # in the revision summary.
1492 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1493 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1495 } elseif ( $this->section
!= '' ) {
1496 # Try to get a section anchor from the section source, redirect to edited section if header found
1497 # XXX: might be better to integrate this into Article::replaceSection
1498 # for duplicate heading checking and maybe parsing
1499 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1500 # we can't deal with anchors, includes, html etc in the header for now,
1501 # headline would need to be parsed to improve this
1502 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1503 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1506 $result['sectionanchor'] = $sectionanchor;
1507 wfProfileOut( __METHOD__
. '-sectionanchor' );
1509 // Save errors may fall down to the edit form, but we've now
1510 // merged the section into full text. Clear the section field
1511 // so that later submission of conflict forms won't try to
1512 // replace that into a duplicated mess.
1513 $this->textbox1
= $content->serialize( $this->content_format
);
1514 $this->section
= '';
1516 $status->value
= self
::AS_SUCCESS_UPDATE
;
1519 // Check for length errors again now that the section is merged in
1520 $this->kblength
= (int)( strlen( $content->serialize( $this->content_format
) ) / 1024 );
1521 if ( $this->kblength
> $wgMaxArticleSize ) {
1522 $this->tooBig
= true;
1523 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1524 wfProfileOut( __METHOD__
);
1528 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1529 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1530 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1531 ( $bot ? EDIT_FORCE_BOT
: 0 );
1533 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags, false, null, $this->content_format
);
1535 if ( $doEditStatus->isOK() ) {
1536 $result['redirect'] = $content->isRedirect();
1537 $this->commitWatch();
1538 wfProfileOut( __METHOD__
);
1541 $this->isConflict
= true;
1542 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1543 wfProfileOut( __METHOD__
);
1544 return $doEditStatus;
1546 } catch (MWContentSerializationException
$ex) {
1547 $status->fatal( 'content-failed-to-parse', $this->content_model
, $this->content_format
, $ex->getMessage() );
1548 $status->value
= self
::AS_PARSE_ERROR
;
1549 wfProfileOut( __METHOD__
);
1555 * Commit the change of watch status
1557 protected function commitWatch() {
1559 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1560 $dbw = wfGetDB( DB_MASTER
);
1562 if ( $this->watchthis
) {
1563 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1565 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1572 * Check if no edits were made by other users since
1573 * the time a user started editing the page. Limit to
1574 * 50 revisions for the sake of performance.
1577 * @param $edittime string
1581 protected function userWasLastToEdit( $id, $edittime ) {
1582 if( !$id ) return false;
1583 $dbw = wfGetDB( DB_MASTER
);
1584 $res = $dbw->select( 'revision',
1587 'rev_page' => $this->mTitle
->getArticleId(),
1588 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1591 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1592 foreach ( $res as $row ) {
1593 if( $row->rev_user
!= $id ) {
1604 * @parma $editText string
1607 * @deprecated since 1.20
1609 function mergeChangesInto( &$editText ){
1610 wfDebug( __METHOD__
, "1.20" );
1612 $editContent = ContentHandler
::makeContent( $editText, $this->getTitle(), $this->content_model
, $this->content_format
);
1614 $ok = $this->mergeChangesIntoContent( $editContent );
1617 $editText = $editContent->serialize( $this->content_format
); #XXX: really serialize?!
1628 * @parma $editText string
1633 private function mergeChangesIntoContent( &$editContent ){
1634 wfProfileIn( __METHOD__
);
1636 $db = wfGetDB( DB_MASTER
);
1638 // This is the revision the editor started from
1639 $baseRevision = $this->getBaseRevision();
1640 if ( is_null( $baseRevision ) ) {
1641 wfProfileOut( __METHOD__
);
1644 $baseContent = $baseRevision->getContent();
1646 // The current state, we want to merge updates into it
1647 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1648 if ( is_null( $currentRevision ) ) {
1649 wfProfileOut( __METHOD__
);
1652 $currentContent = $currentRevision->getContent();
1654 $handler = ContentHandler
::getForModelName( $baseContent->getModelName() );
1656 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1659 $editContent = $result;
1660 wfProfileOut( __METHOD__
);
1663 wfProfileOut( __METHOD__
);
1671 function getBaseRevision() {
1672 if ( !$this->mBaseRevision
) {
1673 $db = wfGetDB( DB_MASTER
);
1674 $baseRevision = Revision
::loadFromTimestamp(
1675 $db, $this->mTitle
, $this->edittime
);
1676 return $this->mBaseRevision
= $baseRevision;
1678 return $this->mBaseRevision
;
1683 * Check given input text against $wgSpamRegex, and return the text of the first match.
1685 * @param $text string
1687 * @return string|false matching string or false
1689 public static function matchSpamRegex( $text ) {
1690 global $wgSpamRegex;
1691 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1692 $regexes = (array)$wgSpamRegex;
1693 return self
::matchSpamRegexInternal( $text, $regexes );
1697 * Check given input text against $wgSpamRegex, and return the text of the first match.
1699 * @parma $text string
1701 * @return string|false matching string or false
1703 public static function matchSummarySpamRegex( $text ) {
1704 global $wgSummarySpamRegex;
1705 $regexes = (array)$wgSummarySpamRegex;
1706 return self
::matchSpamRegexInternal( $text, $regexes );
1710 * @param $text string
1711 * @param $regexes array
1712 * @return bool|string
1714 protected static function matchSpamRegexInternal( $text, $regexes ) {
1715 foreach( $regexes as $regex ) {
1717 if( preg_match( $regex, $text, $matches ) ) {
1724 function setHeaders() {
1725 global $wgOut, $wgUser;
1727 $wgOut->addModules( 'mediawiki.action.edit' );
1729 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1730 $wgOut->addModules( 'mediawiki.legacy.preview' );
1732 // Bug #19334: textarea jumps when editing articles in IE8
1733 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1735 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1737 # Enabled article-related sidebar, toplinks, etc.
1738 $wgOut->setArticleRelated( true );
1740 if ( $this->isConflict
) {
1741 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1742 } elseif ( $this->section
!= '' ) {
1743 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1744 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1746 # Use the title defined by DISPLAYTITLE magic word when present
1747 if ( isset( $this->mParserOutput
)
1748 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1751 $title = $this->getContextTitle()->getPrefixedText();
1753 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1758 * Show all applicable editing introductions
1760 protected function showIntro() {
1761 global $wgOut, $wgUser;
1762 if ( $this->suppressIntro
) {
1766 $namespace = $this->mTitle
->getNamespace();
1768 if ( $namespace == NS_MEDIAWIKI
) {
1769 # Show a warning if editing an interface message
1770 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1773 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1774 # Show log extract when the user is currently blocked
1775 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1776 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1777 $username = $parts[0];
1778 $user = User
::newFromName( $username, false /* allow IP users*/ );
1779 $ip = User
::isIP( $username );
1780 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1781 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1782 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1783 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1784 LogEventsList
::showLogExtract(
1787 $user->getUserPage(),
1791 'showIfEmpty' => false,
1793 'blocked-notice-logextract',
1794 $user->getName() # Support GENDER in notice
1800 # Try to add a custom edit intro, or use the standard one if this is not possible.
1801 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1802 if ( $wgUser->isLoggedIn() ) {
1803 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1805 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1808 # Give a notice if the user is editing a deleted/moved page...
1809 if ( !$this->mTitle
->exists() ) {
1810 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1811 '', array( 'lim' => 10,
1812 'conds' => array( "log_action != 'revision'" ),
1813 'showIfEmpty' => false,
1814 'msgKey' => array( 'recreate-moveddeleted-warn') )
1820 * Attempt to show a custom editing introduction, if supplied
1824 protected function showCustomIntro() {
1825 if ( $this->editintro
) {
1826 $title = Title
::newFromText( $this->editintro
);
1827 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1829 // Added using template syntax, to take <noinclude>'s into account.
1830 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1841 * Send the edit form and related headers to $wgOut
1842 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1843 * during form output near the top, for captchas and the like.
1845 function showEditForm( $formCallback = null ) {
1846 global $wgOut, $wgUser;
1848 wfProfileIn( __METHOD__
);
1850 #need to parse the preview early so that we know which templates are used,
1851 #otherwise users with "show preview after edit box" will get a blank list
1852 #we parse this near the beginning so that setHeaders can do the title
1853 #setting work instead of leaving it in getPreviewText
1854 $previewOutput = '';
1855 if ( $this->formtype
== 'preview' ) {
1856 $previewOutput = $this->getPreviewText();
1859 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1861 $this->setHeaders();
1863 if ( $this->showHeader() === false ) {
1864 wfProfileOut( __METHOD__
);
1868 $wgOut->addHTML( $this->editFormPageTop
);
1870 if ( $wgUser->getOption( 'previewontop' ) ) {
1871 $this->displayPreviewArea( $previewOutput, true );
1874 $wgOut->addHTML( $this->editFormTextTop
);
1876 $showToolbar = true;
1877 if ( $this->wasDeletedSinceLastEdit() ) {
1878 if ( $this->formtype
== 'save' ) {
1879 // Hide the toolbar and edit area, user can click preview to get it back
1880 // Add an confirmation checkbox and explanation.
1881 $showToolbar = false;
1883 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1884 'deletedwhileediting' );
1888 #FIXME: add EditForm plugin interface and use it here! #FIXME: search for textarea1 and textares2, and allow EditForm to override all uses.
1889 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
1890 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1891 'enctype' => 'multipart/form-data' ) ) );
1893 if ( is_callable( $formCallback ) ) {
1894 call_user_func_array( $formCallback, array( &$wgOut ) );
1897 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1899 // Put these up at the top to ensure they aren't lost on early form submission
1900 $this->showFormBeforeText();
1902 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1903 $username = $this->lastDelete
->user_name
;
1904 $comment = $this->lastDelete
->log_comment
;
1906 // It is better to not parse the comment at all than to have templates expanded in the middle
1907 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1908 $key = $comment === ''
1909 ?
'confirmrecreate-noreason'
1910 : 'confirmrecreate';
1912 '<div class="mw-confirm-recreate">' .
1913 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1914 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1915 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1921 # If a blank edit summary was previously provided, and the appropriate
1922 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1923 # user being bounced back more than once in the event that a summary
1926 # For a bit more sophisticated detection of blank summaries, hash the
1927 # automatic one and pass that in the hidden field wpAutoSummary.
1928 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
1929 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1932 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1933 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1935 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
1937 $wgOut->addHTML( Html
::hidden( 'format', $this->content_format
) );
1938 $wgOut->addHTML( Html
::hidden( 'model', $this->content_model
) );
1940 if ( $this->section
== 'new' ) {
1941 $this->showSummaryInput( true, $this->summary
);
1942 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1945 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1947 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1948 $wgOut->addHTML( EditPage
::getEditToolbar() );
1951 if ( $this->isConflict
) {
1952 // In an edit conflict bypass the overrideable content form method
1953 // and fallback to the raw wpTextbox1 since editconflicts can't be
1954 // resolved between page source edits and custom ui edits using the
1956 $this->textbox2
= $this->textbox1
;
1958 $content = $this->getCurrentContent();
1959 $this->textbox1
= $content->serialize( $this->content_format
);
1961 $this->showTextbox1();
1963 $this->showContentForm();
1966 $wgOut->addHTML( $this->editFormTextAfterContent
);
1968 $wgOut->addWikiText( $this->getCopywarn() );
1970 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1972 $this->showStandardInputs();
1974 $this->showFormAfterText();
1976 $this->showTosSummary();
1978 $this->showEditTools();
1980 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
1982 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
1983 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
1985 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
1986 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
1988 if ( $this->isConflict
) {
1989 $this->showConflict();
1992 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
1994 if ( !$wgUser->getOption( 'previewontop' ) ) {
1995 $this->displayPreviewArea( $previewOutput, false );
1998 wfProfileOut( __METHOD__
);
2002 * Extract the section title from current section text, if any.
2004 * @param string $text
2005 * @return Mixed|string or false
2007 public static function extractSectionTitle( $text ) {
2008 preg_match( "/^(=+)(.+)\\1(\n|$)/i", $text, $matches );
2009 if ( !empty( $matches[2] ) ) {
2011 return $wgParser->stripSectionName(trim($matches[2]));
2017 protected function showHeader() {
2018 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2020 if ( $this->mTitle
->isTalkPage() ) {
2021 $wgOut->addWikiMsg( 'talkpagetext' );
2024 # Optional notices on a per-namespace and per-page basis
2025 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
2026 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
2027 if ( $editnotice_ns_message->exists() ) {
2028 $wgOut->addWikiText( $editnotice_ns_message->plain() );
2030 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
2031 $parts = explode( '/', $this->mTitle
->getDBkey() );
2032 $editnotice_base = $editnotice_ns;
2033 while ( count( $parts ) > 0 ) {
2034 $editnotice_base .= '-'.array_shift( $parts );
2035 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
2036 if ( $editnotice_base_msg->exists() ) {
2037 $wgOut->addWikiText( $editnotice_base_msg->plain() );
2041 # Even if there are no subpages in namespace, we still don't want / in MW ns.
2042 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
2043 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
2044 if ( $editnoticeMsg->exists() ) {
2045 $wgOut->addWikiText( $editnoticeMsg->plain() );
2049 if ( $this->isConflict
) {
2050 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2051 $this->edittime
= $this->mArticle
->getTimestamp();
2053 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2054 // We use $this->section to much before this and getVal('wgSection') directly in other places
2055 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2056 // Someone is welcome to try refactoring though
2057 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2061 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2062 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2063 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
2064 if ( $sectionTitle !== false ) {
2065 $this->summary
= "/* $sectionTitle */ ";
2070 if ( $this->missingComment
) {
2071 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2074 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2075 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2078 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2079 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2082 if ( $this->hookError
!== '' ) {
2083 $wgOut->addWikiText( $this->hookError
);
2086 if ( !$this->checkUnicodeCompliantBrowser() ) {
2087 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2090 if ( $this->section
!= 'new' ) {
2091 $revision = $this->mArticle
->getRevisionFetched();
2093 // Let sysop know that this will make private content public if saved
2095 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
2096 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2097 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2098 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2101 if ( !$revision->isCurrent() ) {
2102 $this->mArticle
->setOldSubtitle( $revision->getId() );
2103 $wgOut->addWikiMsg( 'editingold' );
2105 } elseif ( $this->mTitle
->exists() ) {
2106 // Something went wrong
2108 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2109 array( 'missing-article', $this->mTitle
->getPrefixedText(),
2110 wfMsgNoTrans( 'missingarticle-rev', $this->oldid
) ) );
2115 if ( wfReadOnly() ) {
2116 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2117 } elseif ( $wgUser->isAnon() ) {
2118 if ( $this->formtype
!= 'preview' ) {
2119 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2121 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2124 if ( $this->isCssJsSubpage
) {
2125 # Check the skin exists
2126 if ( $this->isWrongCaseCssJsPage
) {
2127 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2129 if ( $this->formtype
!== 'preview' ) {
2130 if ( $this->isCssSubpage
)
2131 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2132 if ( $this->isJsSubpage
)
2133 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2138 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2139 # Is the title semi-protected?
2140 if ( $this->mTitle
->isSemiProtected() ) {
2141 $noticeMsg = 'semiprotectedpagewarning';
2143 # Then it must be protected based on static groups (regular)
2144 $noticeMsg = 'protectedpagewarning';
2146 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2147 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2149 if ( $this->mTitle
->isCascadeProtected() ) {
2150 # Is this page under cascading protection from some source pages?
2151 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
2152 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2153 $cascadeSourcesCount = count( $cascadeSources );
2154 if ( $cascadeSourcesCount > 0 ) {
2155 # Explain, and list the titles responsible
2156 foreach( $cascadeSources as $page ) {
2157 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2160 $notice .= '</div>';
2161 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2163 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2164 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2166 'showIfEmpty' => false,
2167 'msgKey' => array( 'titleprotectedwarning' ),
2168 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2171 if ( $this->kblength
=== false ) {
2172 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2175 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2176 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2177 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2179 if( !wfMessage('longpage-hint')->isDisabled() ) {
2180 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2181 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2188 * Standard summary input and label (wgSummary), abstracted so EditPage
2189 * subclasses may reorganize the form.
2190 * Note that you do not need to worry about the label's for=, it will be
2191 * inferred by the id given to the input. You can remove them both by
2192 * passing array( 'id' => false ) to $userInputAttrs.
2194 * @param $summary string The value of the summary input
2195 * @param $labelText string The html to place inside the label
2196 * @param $inputAttrs array of attrs to use on the input
2197 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2199 * @return array An array in the format array( $label, $input )
2201 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
2202 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
2203 $inputAttrs = ( is_array($inputAttrs) ?
$inputAttrs : array() ) +
array(
2204 'id' => 'wpSummary',
2205 'maxlength' => '200',
2208 'spellcheck' => 'true',
2209 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2211 $spanLabelAttrs = ( is_array($spanLabelAttrs) ?
$spanLabelAttrs : array() ) +
array(
2212 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2213 'id' => "wpSummaryLabel"
2218 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2219 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2222 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2224 return array( $label, $input );
2228 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2229 * up top, or false if this is the comment summary
2230 * down below the textarea
2231 * @param $summary String: The text of the summary to display
2234 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2235 global $wgOut, $wgContLang;
2236 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2237 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2238 if ( $isSubjectPreview ) {
2239 if ( $this->nosummary
) {
2243 if ( !$this->mShowSummaryField
) {
2247 $summary = $wgContLang->recodeForEdit( $summary );
2248 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
2249 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
2250 $wgOut->addHTML("{$label} {$input}");
2254 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2255 * up top, or false if this is the comment summary
2256 * down below the textarea
2257 * @param $summary String: the text of the summary to display
2260 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2261 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2266 if ( $isSubjectPreview )
2267 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2269 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2271 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2272 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2275 protected function showFormBeforeText() {
2277 $section = htmlspecialchars( $this->section
);
2278 $wgOut->addHTML( <<<HTML
2279 <input type='hidden' value="{$section}" name="wpSection" />
2280 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2281 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2282 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2286 if ( !$this->checkUnicodeCompliantBrowser() )
2287 $wgOut->addHTML(Html
::hidden( 'safemode', '1' ));
2290 protected function showFormAfterText() {
2291 global $wgOut, $wgUser;
2293 * To make it harder for someone to slip a user a page
2294 * which submits an edit form to the wiki without their
2295 * knowledge, a random token is associated with the login
2296 * session. If it's not passed back with the submission,
2297 * we won't save the page, or render user JavaScript and
2300 * For anon editors, who may not have a session, we just
2301 * include the constant suffix to prevent editing from
2302 * broken text-mangling proxies.
2304 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2308 * Subpage overridable method for printing the form for page content editing
2309 * By default this simply outputs wpTextbox1
2310 * Subclasses can override this to provide a custom UI for editing;
2311 * be it a form, or simply wpTextbox1 with a modified content that will be
2312 * reverse modified when extracted from the post data.
2313 * Note that this is basically the inverse for importContentFormData
2315 protected function showContentForm() {
2316 $this->showTextbox1();
2320 * Method to output wpTextbox1
2321 * The $textoverride method can be used by subclasses overriding showContentForm
2322 * to pass back to this method.
2324 * @param $customAttribs An array of html attributes to use in the textarea
2325 * @param $textoverride String: optional text to override $this->textarea1 with
2327 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2328 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2329 $attribs = array( 'style' => 'display:none;' );
2331 $classes = array(); // Textarea CSS
2332 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2333 # Is the title semi-protected?
2334 if ( $this->mTitle
->isSemiProtected() ) {
2335 $classes[] = 'mw-textarea-sprotected';
2337 # Then it must be protected based on static groups (regular)
2338 $classes[] = 'mw-textarea-protected';
2340 # Is the title cascade-protected?
2341 if ( $this->mTitle
->isCascadeProtected() ) {
2342 $classes[] = 'mw-textarea-cprotected';
2346 $attribs = array( 'tabindex' => 1 );
2348 if ( is_array( $customAttribs ) ) {
2349 $attribs +
= $customAttribs;
2352 if ( count( $classes ) ) {
2353 if ( isset( $attribs['class'] ) ) {
2354 $classes[] = $attribs['class'];
2356 $attribs['class'] = implode( ' ', $classes );
2360 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2363 protected function showTextbox2() {
2364 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2367 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2368 global $wgOut, $wgUser;
2370 $wikitext = $this->safeUnicodeOutput( $text );
2371 if ( strval($wikitext) !== '' ) {
2372 // Ensure there's a newline at the end, otherwise adding lines
2374 // But don't add a newline if the ext is empty, or Firefox in XHTML
2375 // mode will show an extra newline. A bit annoying.
2379 $attribs = $customAttribs +
array(
2382 'cols' => $wgUser->getIntOption( 'cols' ),
2383 'rows' => $wgUser->getIntOption( 'rows' ),
2384 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2387 $pageLang = $this->mTitle
->getPageLanguage();
2388 $attribs['lang'] = $pageLang->getCode();
2389 $attribs['dir'] = $pageLang->getDir();
2391 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2394 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2398 $classes[] = 'ontop';
2400 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2402 if ( $this->formtype
!= 'preview' )
2403 $attribs['style'] = 'display: none;';
2405 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2407 if ( $this->formtype
== 'preview' ) {
2408 $this->showPreview( $previewOutput );
2411 $wgOut->addHTML( '</div>' );
2413 if ( $this->formtype
== 'diff') {
2419 * Append preview output to $wgOut.
2420 * Includes category rendering if this is a category page.
2422 * @param $text String: the HTML to be output for the preview.
2424 protected function showPreview( $text ) {
2426 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2427 $this->mArticle
->openShowCategory();
2429 # This hook seems slightly odd here, but makes things more
2430 # consistent for extensions.
2431 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
2432 $wgOut->addHTML( $text );
2433 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2434 $this->mArticle
->closeShowCategory();
2439 * Get a diff between the current contents of the edit box and the
2440 * version of the page we're editing from.
2442 * If this is a section edit, we'll replace the section as for final
2443 * save and then make a comparison.
2445 function showDiff() {
2446 global $wgUser, $wgContLang, $wgOut;
2448 $oldContent = $this->getOriginalContent();
2450 $textboxContent = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(),
2451 $this->content_model
, $this->content_format
); #XXX: handle parse errors ?
2453 $newContent = $this->mArticle
->replaceSectionContent(
2454 $this->section
, $textboxContent,
2455 $this->summary
, $this->edittime
);
2457 # hanlde legacy text-based hook
2458 $newtext_orig = $newContent->serialize( $this->content_format
);
2459 $newtext = $newtext_orig; #clone
2460 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2462 if ( $newtext != $newtext_orig ) {
2463 #if the hook changed the text, create a new Content object accordingly.
2464 $newContent = ContentHandler
::makeContent( $newtext, $this->getTitle(), $newContent->getModelName() ); #XXX: handle parse errors ?
2467 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) ); #FIXME: document new hook
2469 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2470 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2472 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2473 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2474 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2476 $de = $oldContent->getContentHandler()->getDifferenceEngine( $this->mArticle
->getContext() );
2477 $de->setContent( $oldContent, $newContent );
2479 $difftext = $de->getDiff( $oldtitle, $newtitle );
2480 $de->showDiffStyle();
2485 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2489 * Give a chance for site and per-namespace customizations of
2490 * terms of service summary link that might exist separately
2491 * from the copyright notice.
2493 * This will display between the save button and the edit tools,
2494 * so should remain short!
2496 protected function showTosSummary() {
2497 $msg = 'editpage-tos-summary';
2498 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2499 if( !wfMessage( $msg )->isDisabled() ) {
2501 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2502 $wgOut->addWikiMsg( $msg );
2503 $wgOut->addHTML( '</div>' );
2507 protected function showEditTools() {
2509 $wgOut->addHTML( '<div class="mw-editTools">' .
2510 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2514 protected function getCopywarn() {
2515 global $wgRightsText;
2516 if ( $wgRightsText ) {
2517 $copywarnMsg = array( 'copyrightwarning',
2518 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2521 $copywarnMsg = array( 'copyrightwarning2',
2522 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2524 // Allow for site and per-namespace customization of contribution/copyright notice.
2525 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2527 return "<div id=\"editpage-copywarn\">\n" .
2528 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
2531 protected function showStandardInputs( &$tabindex = 2 ) {
2533 $wgOut->addHTML( "<div class='editOptions'>\n" );
2535 if ( $this->section
!= 'new' ) {
2536 $this->showSummaryInput( false, $this->summary
);
2537 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2540 $checkboxes = $this->getCheckboxes( $tabindex,
2541 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2542 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2543 $wgOut->addHTML( "<div class='editButtons'>\n" );
2544 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2546 $cancel = $this->getCancelLink();
2547 if ( $cancel !== '' ) {
2548 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2550 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2551 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
2552 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
2553 htmlspecialchars( wfMsg( 'newwindow' ) );
2554 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2555 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2559 * Show an edit conflict. textbox1 is already shown in showEditForm().
2560 * If you want to use another entry point to this function, be careful.
2562 protected function showConflict() {
2565 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2566 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2568 $content1 = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
); #XXX: handle parse errors?
2569 $content2 = ContentHandler
::makeContent( $this->textbox2
, $this->getTitle(), $this->content_model
, $this->content_format
); #XXX: handle parse errors?
2571 $handler = ContentHandler
::getForModelName( $this->content_model
);
2572 $de = $handler->getDifferenceEngine( $this->mArticle
->getContext() );
2573 $de->setContent( $content2, $content1 );
2574 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2576 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2577 $this->showTextbox2();
2584 public function getCancelLink() {
2585 $cancelParams = array();
2586 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2587 $cancelParams['oldid'] = $this->oldid
;
2590 return Linker
::linkKnown(
2591 $this->getContextTitle(),
2592 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2593 array( 'id' => 'mw-editform-cancel' ),
2599 * Returns the URL to use in the form's action attribute.
2600 * This is used by EditPage subclasses when simply customizing the action
2601 * variable in the constructor is not enough. This can be used when the
2602 * EditPage lives inside of a Special page rather than a custom page action.
2604 * @param $title Title object for which is being edited (where we go to for &action= links)
2607 protected function getActionURL( Title
$title ) {
2608 return $title->getLocalURL( array( 'action' => $this->action
) );
2612 * Check if a page was deleted while the user was editing it, before submit.
2613 * Note that we rely on the logging table, which hasn't been always there,
2614 * but that doesn't matter, because this only applies to brand new
2617 protected function wasDeletedSinceLastEdit() {
2618 if ( $this->deletedSinceEdit
!== null ) {
2619 return $this->deletedSinceEdit
;
2622 $this->deletedSinceEdit
= false;
2624 if ( $this->mTitle
->isDeletedQuick() ) {
2625 $this->lastDelete
= $this->getLastDelete();
2626 if ( $this->lastDelete
) {
2627 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2628 if ( $deleteTime > $this->starttime
) {
2629 $this->deletedSinceEdit
= true;
2634 return $this->deletedSinceEdit
;
2637 protected function getLastDelete() {
2638 $dbr = wfGetDB( DB_SLAVE
);
2639 $data = $dbr->selectRow(
2640 array( 'logging', 'user' ),
2651 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2652 'log_title' => $this->mTitle
->getDBkey(),
2653 'log_type' => 'delete',
2654 'log_action' => 'delete',
2655 'user_id=log_user' ),
2657 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2659 // Quick paranoid permission checks...
2660 if( is_object( $data ) ) {
2661 if( $data->log_deleted
& LogPage
::DELETED_USER
)
2662 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2663 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2664 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2670 * Get the rendered text for previewing.
2673 function getPreviewText() {
2674 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2676 wfProfileIn( __METHOD__
);
2678 if ( $wgRawHtml && !$this->mTokenOk
) {
2679 // Could be an offsite preview attempt. This is very unsafe if
2680 // HTML is enabled, as it could be an attack.
2682 if ( $this->textbox1
!== '' ) {
2683 // Do not put big scary notice, if previewing the empty
2684 // string, which happens when you initially edit
2685 // a category page, due to automatic preview-on-open.
2686 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2687 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2689 wfProfileOut( __METHOD__
);
2694 $content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
);
2696 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2697 if ( $this->mTokenOkExceptSuffix
) {
2698 $note = wfMsg( 'token_suffix_mismatch' );
2700 $note = wfMsg( 'session_fail_preview' );
2702 } elseif ( $this->incompleteForm
) {
2703 $note = wfMsg( 'edit_form_incomplete' );
2704 } elseif ( $this->isCssJsSubpage ||
$this->mTitle
->isCssOrJsPage() ) {
2705 # if this is a CSS or JS page used in the UI, show a special notice
2706 # 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?
2708 if( $this->mTitle
->isCssJsSubpage() ) {
2710 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2716 if ( $content->getModelName() == CONTENT_MODEL_CSS
) {
2718 } elseif ( $content->getModelName() == CONTENT_MODEL_JAVASCRIPT
) {
2724 # Used messages to make sure grep find them:
2725 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2726 if( $level && $format ) {
2727 $note = "<div id='mw-{$level}{$format}preview'>" . wfMsg( "{$level}{$format}preview" ) . "</div>";
2729 $note = wfMsg( 'previewnote' );
2732 $note = wfMsg( 'previewnote' );
2735 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2736 $parserOptions->setEditSection( false );
2737 $parserOptions->setTidy( true );
2738 $parserOptions->setIsPreview( true );
2739 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2741 $rt = $content->getRedirectChain();
2744 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2747 # If we're adding a comment, we need to show the
2748 # summary as the headline
2749 if ( $this->section
== "new" && $this->summary
!= "" ) {
2750 $content = $content->addSectionHeader( $this->summary
);
2753 $toparse_orig = $content->serialize( $this->content_format
);
2754 $toparse = $toparse_orig;
2755 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2757 if ( $toparse !== $toparse_orig ) {
2758 #hook changed the text, create new Content object
2759 $content = ContentHandler
::makeContent( $toparse, $this->getTitle(), $this->content_model
, $this->content_format
);
2762 wfRunHooks( 'EditPageGetPreviewContent', array( $this, &$content ) ); # FIXME: document new hook
2764 $parserOptions->enableLimitReport();
2766 #XXX: For CSS/JS pages, we should have called the ShowRawCssJs hook here. But it's now deprecated, so never mind
2767 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
2768 $parserOutput = $content->getParserOutput( $this->mTitle
, null, $parserOptions );
2770 $previewHTML = $parserOutput->getText();
2771 $this->mParserOutput
= $parserOutput;
2772 $wgOut->addParserOutputNoText( $parserOutput );
2774 if ( count( $parserOutput->getWarnings() ) ) {
2775 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2778 } catch (MWContentSerializationException
$ex) {
2779 $note .= "\n\n" . wfMsg('content-failed-to-parse', $this->content_model
, $this->content_format
, $ex->getMessage() );
2783 if( $this->isConflict
) {
2784 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2786 $conflict = '<hr />';
2789 $previewhead = "<div class='previewnote'>\n" .
2790 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2791 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2793 $pageLang = $this->mTitle
->getPageLanguage();
2794 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2795 'class' => 'mw-content-'.$pageLang->getDir() );
2796 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2798 wfProfileOut( __METHOD__
);
2799 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2805 function getTemplates() {
2806 if ( $this->preview ||
$this->section
!= '' ) {
2807 $templates = array();
2808 if ( !isset( $this->mParserOutput
) ) {
2811 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
2812 foreach( array_keys( $template ) as $dbk ) {
2813 $templates[] = Title
::makeTitle($ns, $dbk);
2818 return $this->mTitle
->getTemplateLinksFrom();
2823 * Shows a bulletin board style toolbar for common editing functions.
2824 * It can be disabled in the user preferences.
2825 * The necessary JavaScript code can be found in skins/common/edit.js.
2829 static function getEditToolbar() {
2830 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2831 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2833 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2836 * $toolarray is an array of arrays each of which includes the
2837 * filename of the button image (without path), the opening
2838 * tag, the closing tag, optionally a sample text that is
2839 * inserted between the two when no selection is highlighted
2840 * and. The tip text is shown when the user moves the mouse
2843 * Also here: accesskeys (key), which are not used yet until
2844 * someone can figure out a way to make them work in
2845 * IE. However, we should make sure these keys are not defined
2850 'image' => $wgLang->getImageFile( 'button-bold' ),
2851 'id' => 'mw-editbutton-bold',
2853 'close' => '\'\'\'',
2854 'sample' => wfMsg( 'bold_sample' ),
2855 'tip' => wfMsg( 'bold_tip' ),
2859 'image' => $wgLang->getImageFile( 'button-italic' ),
2860 'id' => 'mw-editbutton-italic',
2863 'sample' => wfMsg( 'italic_sample' ),
2864 'tip' => wfMsg( 'italic_tip' ),
2868 'image' => $wgLang->getImageFile( 'button-link' ),
2869 'id' => 'mw-editbutton-link',
2872 'sample' => wfMsg( 'link_sample' ),
2873 'tip' => wfMsg( 'link_tip' ),
2877 'image' => $wgLang->getImageFile( 'button-extlink' ),
2878 'id' => 'mw-editbutton-extlink',
2881 'sample' => wfMsg( 'extlink_sample' ),
2882 'tip' => wfMsg( 'extlink_tip' ),
2886 'image' => $wgLang->getImageFile( 'button-headline' ),
2887 'id' => 'mw-editbutton-headline',
2890 'sample' => wfMsg( 'headline_sample' ),
2891 'tip' => wfMsg( 'headline_tip' ),
2894 $imagesAvailable ?
array(
2895 'image' => $wgLang->getImageFile( 'button-image' ),
2896 'id' => 'mw-editbutton-image',
2897 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2899 'sample' => wfMsg( 'image_sample' ),
2900 'tip' => wfMsg( 'image_tip' ),
2903 $imagesAvailable ?
array(
2904 'image' => $wgLang->getImageFile( 'button-media' ),
2905 'id' => 'mw-editbutton-media',
2906 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2908 'sample' => wfMsg( 'media_sample' ),
2909 'tip' => wfMsg( 'media_tip' ),
2913 'image' => $wgLang->getImageFile( 'button-math' ),
2914 'id' => 'mw-editbutton-math',
2916 'close' => "</math>",
2917 'sample' => wfMsg( 'math_sample' ),
2918 'tip' => wfMsg( 'math_tip' ),
2922 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2923 'id' => 'mw-editbutton-nowiki',
2924 'open' => "<nowiki>",
2925 'close' => "</nowiki>",
2926 'sample' => wfMsg( 'nowiki_sample' ),
2927 'tip' => wfMsg( 'nowiki_tip' ),
2931 'image' => $wgLang->getImageFile( 'button-sig' ),
2932 'id' => 'mw-editbutton-signature',
2936 'tip' => wfMsg( 'sig_tip' ),
2940 'image' => $wgLang->getImageFile( 'button-hr' ),
2941 'id' => 'mw-editbutton-hr',
2942 'open' => "\n----\n",
2945 'tip' => wfMsg( 'hr_tip' ),
2950 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
2951 foreach ( $toolarray as $tool ) {
2957 $image = $wgStylePath . '/common/images/' . $tool['image'],
2958 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2959 // Older browsers show a "speedtip" type message only for ALT.
2960 // Ideally these should be different, realistically they
2961 // probably don't need to be.
2962 $tip = $tool['tip'],
2963 $open = $tool['open'],
2964 $close = $tool['close'],
2965 $sample = $tool['sample'],
2966 $cssId = $tool['id'],
2969 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2972 // This used to be called on DOMReady from mediawiki.action.edit, which
2973 // ended up causing race conditions with the setup code above.
2975 "// Create button bar\n" .
2976 "$(function() { mw.toolbar.init(); } );\n";
2979 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2981 $toolbar = '<div id="toolbar"></div>';
2983 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2989 * Returns an array of html code of the following checkboxes:
2992 * @param $tabindex Current tabindex
2993 * @param $checked Array of checkbox => bool, where bool indicates the checked
2994 * status of the checkbox
2998 public function getCheckboxes( &$tabindex, $checked ) {
3001 $checkboxes = array();
3003 // don't show the minor edit checkbox if it's a new page or section
3004 if ( !$this->isNew
) {
3005 $checkboxes['minor'] = '';
3006 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
3007 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3009 'tabindex' => ++
$tabindex,
3010 'accesskey' => wfMsg( 'accesskey-minoredit' ),
3011 'id' => 'wpMinoredit',
3013 $checkboxes['minor'] =
3014 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3015 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3016 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3017 ">{$minorLabel}</label>";
3021 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
3022 $checkboxes['watch'] = '';
3023 if ( $wgUser->isLoggedIn() ) {
3025 'tabindex' => ++
$tabindex,
3026 'accesskey' => wfMsg( 'accesskey-watch' ),
3027 'id' => 'wpWatchthis',
3029 $checkboxes['watch'] =
3030 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3031 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3032 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3033 ">{$watchLabel}</label>";
3035 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3040 * Returns an array of html code of the following buttons:
3041 * save, diff, preview and live
3043 * @param $tabindex Current tabindex
3047 public function getEditButtons( &$tabindex ) {
3054 'tabindex' => ++
$tabindex,
3055 'value' => wfMsg( 'savearticle' ),
3056 'accesskey' => wfMsg( 'accesskey-save' ),
3057 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
3059 $buttons['save'] = Xml
::element('input', $temp, '');
3061 ++
$tabindex; // use the same for preview and live preview
3063 'id' => 'wpPreview',
3064 'name' => 'wpPreview',
3066 'tabindex' => $tabindex,
3067 'value' => wfMsg( 'showpreview' ),
3068 'accesskey' => wfMsg( 'accesskey-preview' ),
3069 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
3071 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3072 $buttons['live'] = '';
3078 'tabindex' => ++
$tabindex,
3079 'value' => wfMsg( 'showdiff' ),
3080 'accesskey' => wfMsg( 'accesskey-diff' ),
3081 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
3083 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3085 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3090 * Output preview text only. This can be sucked into the edit page
3091 * via JavaScript, and saves the server time rendering the skin as
3092 * well as theoretically being more robust on the client (doesn't
3093 * disturb the edit box's undo history, won't eat your text on
3096 * @todo This doesn't include category or interlanguage links.
3097 * Would need to enhance it a bit, <s>maybe wrap them in XML
3098 * or something...</s> that might also require more skin
3099 * initialization, so check whether that's a problem.
3101 function livePreview() {
3104 header( 'Content-type: text/xml; charset=utf-8' );
3105 header( 'Cache-control: no-cache' );
3107 $previewText = $this->getPreviewText();
3108 #$categories = $skin->getCategoryLinks();
3111 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3112 Xml
::tags( 'livepreview', null,
3113 Xml
::element( 'preview', null, $previewText )
3114 #. Xml::element( 'category', null, $categories )
3120 * Call the stock "user is blocked" page
3122 * @deprecated in 1.19; throw an exception directly instead
3124 function blockedPage() {
3125 wfDeprecated( __METHOD__
, '1.19' );
3128 throw new UserBlockedError( $wgUser->mBlock
);
3132 * Produce the stock "please login to edit pages" page
3134 * @deprecated in 1.19; throw an exception directly instead
3136 function userNotLoggedInPage() {
3137 wfDeprecated( __METHOD__
, '1.19' );
3138 throw new PermissionsError( 'edit' );
3142 * Show an error page saying to the user that he has insufficient permissions
3143 * to create a new page
3145 * @deprecated in 1.19; throw an exception directly instead
3147 function noCreatePermission() {
3148 wfDeprecated( __METHOD__
, '1.19' );
3149 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3150 throw new PermissionsError( $permission );
3154 * Creates a basic error page which informs the user that
3155 * they have attempted to edit a nonexistent section.
3157 function noSuchSectionPage() {
3160 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3162 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
3163 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3164 $wgOut->addHTML( $res );
3166 $wgOut->returnToMain( false, $this->mTitle
);
3170 * Produce the stock "your edit contains spam" page
3172 * @param $match Text which triggered one or more filters
3173 * @deprecated since 1.17 Use method spamPageWithContent() instead
3175 static function spamPage( $match = false ) {
3176 wfDeprecated( __METHOD__
, '1.17' );
3178 global $wgOut, $wgTitle;
3180 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3182 $wgOut->addHTML( '<div id="spamprotected">' );
3183 $wgOut->addWikiMsg( 'spamprotectiontext' );
3185 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3187 $wgOut->addHTML( '</div>' );
3189 $wgOut->returnToMain( false, $wgTitle );
3193 * Show "your edit contains spam" page with your diff and text
3195 * @param $match Text which triggered one or more filters
3197 public function spamPageWithContent( $match = false ) {
3199 $this->textbox2
= $this->textbox1
;
3201 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3203 $wgOut->addHTML( '<div id="spamprotected">' );
3204 $wgOut->addWikiMsg( 'spamprotectiontext' );
3206 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3208 $wgOut->addHTML( '</div>' );
3210 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3212 $handler = ContentHandler
::getForTitle( $this->getTitle() );
3213 $de = $handler->getDifferenceEngine( $this->mArticle
->getContext() );
3215 $content2 = ContentHandler
::makeContent( $this->textbox2
, $this->getTitle(), $this->content_model
, $this->content_format
); #XXX: handle parse errors?
3216 $de->setContent( $this->getCurrentContent(), $content2 );
3218 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
3220 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3221 $this->showTextbox2();
3223 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3227 * Format an anchor fragment as it would appear for a given section name
3228 * @param $text String
3232 function sectionAnchor( $text ) {
3234 return $wgParser->guessSectionNameFromWikiText( $text );
3238 * Check if the browser is on a blacklist of user-agents known to
3239 * mangle UTF-8 data on form submission. Returns true if Unicode
3240 * should make it through, false if it's known to be a problem.
3244 function checkUnicodeCompliantBrowser() {
3245 global $wgBrowserBlackList;
3246 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
3247 // No User-Agent header sent? Trust it by default...
3250 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
3251 foreach ( $wgBrowserBlackList as $browser ) {
3252 if ( preg_match($browser, $currentbrowser) ) {
3260 * Filter an input field through a Unicode de-armoring process if it
3261 * came from an old browser with known broken Unicode editing issues.
3263 * @param $request WebRequest
3264 * @param $field String
3268 function safeUnicodeInput( $request, $field ) {
3269 $text = rtrim( $request->getText( $field ) );
3270 return $request->getBool( 'safemode' )
3271 ?
$this->unmakesafe( $text )
3276 * @param $request WebRequest
3277 * @param $text string
3280 function safeUnicodeText( $request, $text ) {
3281 $text = rtrim( $text );
3282 return $request->getBool( 'safemode' )
3283 ?
$this->unmakesafe( $text )
3288 * Filter an output field through a Unicode armoring process if it is
3289 * going to an old browser with known broken Unicode editing issues.
3291 * @param $text String
3295 function safeUnicodeOutput( $text ) {
3297 $codedText = $wgContLang->recodeForEdit( $text );
3298 return $this->checkUnicodeCompliantBrowser()
3300 : $this->makesafe( $codedText );
3304 * A number of web browsers are known to corrupt non-ASCII characters
3305 * in a UTF-8 text editing environment. To protect against this,
3306 * detected browsers will be served an armored version of the text,
3307 * with non-ASCII chars converted to numeric HTML character references.
3309 * Preexisting such character references will have a 0 added to them
3310 * to ensure that round-trips do not alter the original data.
3312 * @param $invalue String
3316 function makesafe( $invalue ) {
3317 // Armor existing references for reversability.
3318 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3323 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3324 $bytevalue = ord( $invalue[$i] );
3325 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
3326 $result .= chr( $bytevalue );
3328 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
3329 $working = $working << 6;
3330 $working +
= ($bytevalue & 0x3F);
3332 if ( $bytesleft <= 0 ) {
3333 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3335 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
3336 $working = $bytevalue & 0x1F;
3338 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
3339 $working = $bytevalue & 0x0F;
3341 } else { //1111 0xxx
3342 $working = $bytevalue & 0x07;
3350 * Reverse the previously applied transliteration of non-ASCII characters
3351 * back to UTF-8. Used to protect data from corruption by broken web browsers
3352 * as listed in $wgBrowserBlackList.
3354 * @param $invalue String
3358 function unmakesafe( $invalue ) {
3360 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3361 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+
3] != '0' ) ) {
3365 $hexstring .= $invalue[$i];
3367 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3369 // Do some sanity checks. These aren't needed for reversability,
3370 // but should help keep the breakage down if the editor
3371 // breaks one of the entities whilst editing.
3372 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
3373 $codepoint = hexdec($hexstring);
3374 $result .= codepointToUtf8( $codepoint );
3376 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3379 $result .= substr( $invalue, $i, 1 );
3382 // reverse the transform that we made for reversability reasons.
3383 return strtr( $result, array( "�" => "&#x" ) );