3 * Contains the EditPage class
8 * The edit page/HTML interface (split from Article)
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
13 * EditPage cares about two distinct titles:
14 * $this->mContextTitle is the page that forms submit to, links point to,
15 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
16 * page in the database that is actually being edited. These are
17 * usually the same, but they are now allowed to be different.
19 * Surgeon General's Warning: prolonged exposure to this class is known to cause
20 * headaches, which may be fatal.
25 * Status: Article successfully updated
27 const AS_SUCCESS_UPDATE
= 200;
30 * Status: Article successfully created
32 const AS_SUCCESS_NEW_ARTICLE
= 201;
35 * Status: Article update aborted by a hook function
37 const AS_HOOK_ERROR
= 210;
40 * Status: The filter function set in $wgFilterCallback returned true (= block it)
42 const AS_FILTERING
= 211;
45 * Status: A hook function returned an error
47 const AS_HOOK_ERROR_EXPECTED
= 212;
50 * Status: User is blocked from editting this page
52 const AS_BLOCKED_PAGE_FOR_USER
= 215;
55 * Status: Content too big (> $wgMaxArticleSize)
57 const AS_CONTENT_TOO_BIG
= 216;
60 * Status: User cannot edit? (not used)
62 const AS_USER_CANNOT_EDIT
= 217;
65 * Status: this anonymous user is not allowed to edit this page
67 const AS_READ_ONLY_PAGE_ANON
= 218;
70 * Status: this logged in user is not allowed to edit this page
72 const AS_READ_ONLY_PAGE_LOGGED
= 219;
75 * Status: wiki is in readonly mode (wfReadOnly() == true)
77 const AS_READ_ONLY_PAGE
= 220;
80 * Status: rate limiter for action 'edit' was tripped
82 const AS_RATE_LIMITED
= 221;
85 * Status: article was deleted while editting and param wpRecreate == false or form
88 const AS_ARTICLE_WAS_DELETED
= 222;
91 * Status: user tried to create this page, but is not allowed to do that
92 * ( Title->usercan('create') == false )
94 const AS_NO_CREATE_PERMISSION
= 223;
97 * Status: user tried to create a blank page
99 const AS_BLANK_ARTICLE
= 224;
102 * Status: (non-resolvable) edit conflict
104 const AS_CONFLICT_DETECTED
= 225;
107 * Status: no edit summary given and the user has forceeditsummary set and the user is not
108 * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
110 const AS_SUMMARY_NEEDED
= 226;
113 * Status: user tried to create a new section without content
115 const AS_TEXTBOX_EMPTY
= 228;
118 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
120 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
128 * Status: WikiPage::doEdit() was unsuccessfull
133 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
135 const AS_SPAM_ERROR
= 232;
138 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
140 const AS_IMAGE_REDIRECT_ANON
= 233;
143 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
145 const AS_IMAGE_REDIRECT_LOGGED
= 234;
156 private $mContextTitle = null;
157 var $action = 'submit';
158 var $isConflict = false;
159 var $isCssJsSubpage = false;
160 var $isCssSubpage = false;
161 var $isJsSubpage = false;
162 var $isWrongCaseCssJsPage = false;
163 var $isNew = false; // new page or new section
164 var $deletedSinceEdit;
168 var $mTokenOk = false;
169 var $mTokenOkExceptSuffix = false;
170 var $mTriedSave = false;
171 var $incompleteForm = false;
173 var $kblength = false;
174 var $missingComment = false;
175 var $missingSummary = false;
176 var $allowBlankSummary = false;
179 #var $mPreviewTemplates;
186 var $mBaseRevision = false;
187 var $mShowSummaryField = true;
190 var $save = false, $preview = false, $diff = false;
191 var $minoredit = false, $watchthis = false, $recreate = false;
192 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
193 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
194 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
195 var $content_model = null, $content_format = null;
197 # Placeholders for text injection by hooks (must be HTML)
198 # extensions should take care to _append_ to the present value
199 public $editFormPageTop = ''; // Before even the preview
200 public $editFormTextTop = '';
201 public $editFormTextBeforeContent = '';
202 public $editFormTextAfterWarn = '';
203 public $editFormTextAfterTools = '';
204 public $editFormTextBottom = '';
205 public $editFormTextAfterContent = '';
206 public $previewTextAfterContent = '';
207 public $mPreloadContent = null;
209 /* $didSave should be set to true whenever an article was succesfully altered. */
210 public $didSave = false;
211 public $undidRev = 0;
213 public $suppressIntro = false;
216 * @param $article Article
218 public function __construct( Article
$article ) {
219 $this->mArticle
= $article;
220 $this->mTitle
= $article->getTitle();
222 $this->content_model
= $this->mTitle
->getContentModelName();
224 $handler = ContentHandler
::getForModelName( $this->content_model
);
225 $this->content_format
= $handler->getDefaultFormat(); #NOTE: should be overridden by format of actual revision
231 public function getArticle() {
232 return $this->mArticle
;
239 public function getTitle() {
240 return $this->mTitle
;
244 * Set the context Title object
246 * @param $title Title object or null
248 public function setContextTitle( $title ) {
249 $this->mContextTitle
= $title;
253 * Get the context title object.
254 * If not set, $wgTitle will be returned. This behavior might changed in
255 * the future to return $this->mTitle instead.
257 * @return Title object
259 public function getContextTitle() {
260 if ( is_null( $this->mContextTitle
) ) {
264 return $this->mContextTitle
;
273 * This is the function that gets called for "action=edit". It
274 * sets up various member variables, then passes execution to
275 * another function, usually showEditForm()
277 * The edit form is self-submitting, so that when things like
278 * preview and edit conflicts occur, we get the same form back
279 * with the extra stuff added. Only when the final submission
280 * is made and all is well do we actually save and redirect to
281 * the newly-edited page.
284 global $wgOut, $wgRequest, $wgUser;
285 // Allow extensions to modify/prevent this form or submission
286 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
290 wfProfileIn( __METHOD__
);
291 wfDebug( __METHOD__
.": enter\n" );
293 // If they used redlink=1 and the page exists, redirect to the main article
294 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
295 $wgOut->redirect( $this->mTitle
->getFullURL() );
296 wfProfileOut( __METHOD__
);
300 $this->importFormData( $wgRequest );
301 $this->firsttime
= false;
304 $this->livePreview();
305 wfProfileOut( __METHOD__
);
309 if ( wfReadOnly() && $this->save
) {
312 $this->preview
= true;
316 $this->formtype
= 'save';
317 } elseif ( $this->preview
) {
318 $this->formtype
= 'preview';
319 } elseif ( $this->diff
) {
320 $this->formtype
= 'diff';
321 } else { # First time through
322 $this->firsttime
= true;
323 if ( $this->previewOnOpen() ) {
324 $this->formtype
= 'preview';
326 $this->formtype
= 'initial';
330 $permErrors = $this->getEditPermissionErrors();
332 wfDebug( __METHOD__
. ": User can't edit\n" );
333 // Auto-block user's IP if the account was "hard" blocked
334 $wgUser->spreadAnyEditBlock();
336 $this->displayPermissionsError( $permErrors );
338 wfProfileOut( __METHOD__
);
342 wfProfileIn( __METHOD__
."-business-end" );
344 $this->isConflict
= false;
345 // css / js subpages of user pages get a special treatment
346 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
347 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
348 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
349 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
350 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
352 # Show applicable editing introductions
353 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
357 # Attempt submission here. This will check for edit conflicts,
358 # and redundantly check for locked database, blocked IPs, etc.
359 # that edit() already checked just in case someone tries to sneak
360 # in the back door with a hand-edited submission URL.
362 if ( 'save' == $this->formtype
) {
363 if ( !$this->attemptSave() ) {
364 wfProfileOut( __METHOD__
."-business-end" );
365 wfProfileOut( __METHOD__
);
370 # First time through: get contents, set time for conflict
372 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
373 if ( $this->initialiseForm() === false ) {
374 $this->noSuchSectionPage();
375 wfProfileOut( __METHOD__
."-business-end" );
376 wfProfileOut( __METHOD__
);
379 if ( !$this->mTitle
->getArticleId() )
380 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
382 wfRunHooks( 'EditFormInitialText', array( $this ) );
385 $this->showEditForm();
386 wfProfileOut( __METHOD__
."-business-end" );
387 wfProfileOut( __METHOD__
);
393 protected function getEditPermissionErrors() {
395 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
396 # Can this title be created?
397 if ( !$this->mTitle
->exists() ) {
398 $permErrors = array_merge( $permErrors,
399 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
401 # Ignore some permissions errors when a user is just previewing/viewing diffs
403 foreach( $permErrors as $error ) {
404 if ( ( $this->preview ||
$this->diff
) &&
405 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
410 $permErrors = wfArrayDiff2( $permErrors, $remove );
415 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
416 * but with the following differences:
417 * - If redlink=1, the user will be redirected to the page
418 * - If there is content to display or the error occurs while either saving,
419 * previewing or showing the difference, it will be a
420 * "View source for ..." page displaying the source code after the error message.
423 * @param $permErrors Array of permissions errors, as returned by
424 * Title::getUserPermissionsErrors().
426 protected function displayPermissionsError( array $permErrors ) {
427 global $wgRequest, $wgOut;
429 if ( $wgRequest->getBool( 'redlink' ) ) {
430 // The edit page was reached via a red link.
431 // Redirect to the article page and let them click the edit tab if
432 // they really want a permission error.
433 $wgOut->redirect( $this->mTitle
->getFullUrl() );
437 $content = $this->getContentObject();
439 # Use the normal message if there's nothing to display
440 if ( $this->firsttime
&& $content->isEmpty() ) {
441 $action = $this->mTitle
->exists() ?
'edit' :
442 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
443 throw new PermissionsError( $action, $permErrors );
446 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
447 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
448 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
449 $wgOut->addHTML( "<hr />\n" );
451 # If the user made changes, preserve them when showing the markup
452 # (This happens when a user is blocked during edit, for instance)
453 if ( !$this->firsttime
) {
454 $text = $this->textbox1
;
455 $wgOut->addWikiMsg( 'viewyourtext' );
457 $text = $content->serialize( $this->content_format
);
458 $wgOut->addWikiMsg( 'viewsourcetext' );
461 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
463 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
464 Linker
::formatTemplates( $this->getTemplates() ) ) );
466 if ( $this->mTitle
->exists() ) {
467 $wgOut->returnToMain( null, $this->mTitle
);
472 * Show a read-only error
473 * Parameters are the same as OutputPage:readOnlyPage()
474 * Redirect to the article page if redlink=1
475 * @deprecated in 1.19; use displayPermissionsError() instead
477 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
478 wfDeprecated( __METHOD__
, '1.19' );
480 global $wgRequest, $wgOut;
481 if ( $wgRequest->getBool( 'redlink' ) ) {
482 // The edit page was reached via a red link.
483 // Redirect to the article page and let them click the edit tab if
484 // they really want a permission error.
485 $wgOut->redirect( $this->mTitle
->getFullUrl() );
487 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
492 * Should we show a preview when the edit form is first shown?
496 protected function previewOnOpen() {
497 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
498 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
499 // Explicit override from request
501 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
502 // Explicit override from request
504 } elseif ( $this->section
== 'new' ) {
505 // Nothing *to* preview for new sections
507 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
508 // Standard preference behaviour
510 } elseif ( !$this->mTitle
->exists() &&
511 isset($wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]) &&
512 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
514 // Categories are special
522 * Checks whether the user entered a skin name in uppercase,
523 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
527 protected function isWrongCaseCssJsPage() {
528 if( $this->mTitle
->isCssJsSubpage() ) {
529 $name = $this->mTitle
->getSkinFromCssJsSubpage();
530 $skins = array_merge(
531 array_keys( Skin
::getSkinNames() ),
534 return !in_array( $name, $skins )
535 && in_array( strtolower( $name ), $skins );
542 * Does this EditPage class support section editing?
543 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
547 protected function isSectionEditSupported() {
552 * This function collects the form data and uses it to populate various member variables.
553 * @param $request WebRequest
555 function importFormData( &$request ) {
556 global $wgLang, $wgUser;
558 wfProfileIn( __METHOD__
);
560 # Section edit can come from either the form or a link
561 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
563 if ( $request->wasPosted() ) {
564 # These fields need to be checked for encoding.
565 # Also remove trailing whitespace, but don't remove _initial_
566 # whitespace from the text boxes. This may be significant formatting.
567 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
568 if ( !$request->getCheck('wpTextbox2') ) {
569 // Skip this if wpTextbox2 has input, it indicates that we came
570 // from a conflict page with raw page text, not a custom form
571 // modified by subclasses
572 wfProfileIn( get_class($this)."::importContentFormData" );
573 $textbox1 = $this->importContentFormData( $request ); #FIXME: what should this return??
574 if ( isset($textbox1) )
575 $this->textbox1
= $textbox1;
576 wfProfileOut( get_class($this)."::importContentFormData" );
579 # Truncate for whole multibyte characters. +5 bytes for ellipsis
580 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
582 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
583 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
585 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
587 # Treat sectiontitle the same way as summary.
588 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
589 # currently doing double duty as both edit summary and section title. Right now this
590 # is just to allow API edits to work around this limitation, but this should be
591 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
592 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 250 );
593 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
595 $this->edittime
= $request->getVal( 'wpEdittime' );
596 $this->starttime
= $request->getVal( 'wpStarttime' );
598 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
600 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
601 // wpTextbox1 field is missing, possibly due to being "too big"
602 // according to some filter rules such as Suhosin's setting for
603 // suhosin.request.max_value_length (d'oh)
604 $this->incompleteForm
= true;
606 // edittime should be one of our last fields; if it's missing,
607 // the submission probably broke somewhere in the middle.
608 $this->incompleteForm
= is_null( $this->edittime
);
610 if ( $this->incompleteForm
) {
611 # If the form is incomplete, force to preview.
612 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
613 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
614 $this->preview
= true;
616 /* Fallback for live preview */
617 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
618 $this->diff
= $request->getCheck( 'wpDiff' );
620 // Remember whether a save was requested, so we can indicate
621 // if we forced preview due to session failure.
622 $this->mTriedSave
= !$this->preview
;
624 if ( $this->tokenOk( $request ) ) {
625 # Some browsers will not report any submit button
626 # if the user hits enter in the comment box.
627 # The unmarked state will be assumed to be a save,
628 # if the form seems otherwise complete.
629 wfDebug( __METHOD__
. ": Passed token check.\n" );
630 } elseif ( $this->diff
) {
631 # Failed token check, but only requested "Show Changes".
632 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
634 # Page might be a hack attempt posted from
635 # an external site. Preview instead of saving.
636 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
637 $this->preview
= true;
640 $this->save
= !$this->preview
&& !$this->diff
;
641 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
642 $this->edittime
= null;
645 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
646 $this->starttime
= null;
649 $this->recreate
= $request->getCheck( 'wpRecreate' );
651 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
652 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
654 # Don't force edit summaries when a user is editing their own user or talk page
655 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
656 $this->mTitle
->getText() == $wgUser->getName() )
658 $this->allowBlankSummary
= true;
660 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
663 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
665 # Not a posted form? Start with nothing.
666 wfDebug( __METHOD__
. ": Not a posted form.\n" );
667 $this->textbox1
= ''; #FIXME: track content object
669 $this->sectiontitle
= '';
670 $this->edittime
= '';
671 $this->starttime
= wfTimestampNow();
673 $this->preview
= false;
676 $this->minoredit
= false;
677 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
678 $this->recreate
= false;
680 // When creating a new section, we can preload a section title by passing it as the
681 // preloadtitle parameter in the URL (Bug 13100)
682 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
683 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
684 // Once wpSummary isn't being use for setting section titles, we should delete this.
685 $this->summary
= $request->getVal( 'preloadtitle' );
687 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
688 $this->summary
= $request->getText( 'summary' );
691 if ( $request->getVal( 'minor' ) ) {
692 $this->minoredit
= true;
696 $this->oldid
= $request->getInt( 'oldid' );
698 $this->bot
= $request->getBool( 'bot', true );
699 $this->nosummary
= $request->getBool( 'nosummary' );
701 $content_handler = ContentHandler
::getForTitle( $this->mTitle
);
702 $this->content_model
= $request->getText( 'model', $content_handler->getModelName() ); #may be overridden by revision
703 $this->content_format
= $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
705 #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
706 #TODO: check if the desired content model supports the given content format!
708 $this->live
= $request->getCheck( 'live' );
709 $this->editintro
= $request->getText( 'editintro',
710 // Custom edit intro for new sections
711 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
713 // Allow extensions to modify form data
714 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
716 wfProfileOut( __METHOD__
);
720 * Subpage overridable method for extracting the page content data from the
721 * posted form to be placed in $this->textbox1, if using customized input
722 * this method should be overrided and return the page text that will be used
723 * for saving, preview parsing and so on...
725 * @param $request WebRequest
727 protected function importContentFormData( &$request ) {
728 return; // Don't do anything, EditPage already extracted wpTextbox1
732 * Initialise form fields in the object
733 * Called on the first invocation, e.g. when a user clicks an edit link
734 * @return bool -- if the requested section is valid
736 function initialiseForm() {
738 $this->edittime
= $this->mArticle
->getTimestamp();
740 $content = $this->getContentObject( false ); #TODO: track content object?!
741 $this->textbox1
= $content->serialize( $this->content_format
);
743 // activate checkboxes if user wants them to be always active
744 # Sort out the "watch" checkbox
745 if ( $wgUser->getOption( 'watchdefault' ) ) {
747 $this->watchthis
= true;
748 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
750 $this->watchthis
= true;
751 } elseif ( $this->mTitle
->userIsWatching() ) {
753 $this->watchthis
= true;
755 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
756 $this->minoredit
= true;
758 if ( $this->textbox1
=== false ) {
766 * Fetch initial editing page content.
768 * @param $def_text string
769 * @return mixed string on success, $def_text for invalid sections
771 * @deprecated since 1.20
773 function getContent( $def_text = false ) { #FIXME: deprecated, replace usage!
774 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
775 $def_content = ContentHandler
::makeContent( $def_text, $this->getTitle() );
777 $def_content = false;
780 $content = $this->getContentObject( $def_content );
782 return $content->serialize( $this->content_format
); #XXX: really use serialized form? use ContentHandler::getContentText() instead?
785 private function getContentObject( $def_content = null ) { #FIXME: use this!
786 global $wgOut, $wgRequest;
788 wfProfileIn( __METHOD__
);
792 // For message page not locally set, use the i18n message.
793 // For other non-existent articles, use preload text if any.
794 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
795 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
796 # If this is a system message, get the default text.
797 $msg = $this->mTitle
->getDefaultMessageText();
799 $content = new WikitextContent($msg); //XXX: really hardcode wikitext here?
801 if ( $content === false ) {
802 # If requested, preload some text.
803 $preload = $wgRequest->getVal( 'preload',
804 // Custom preload text for new sections
805 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
807 $content = $this->getPreloadedContent( $preload );
809 // For existing pages, get text based on "undo" or section parameters.
811 if ( $this->section
!= '' ) {
812 // Get section edit text (returns $def_text for invalid sections)
813 $orig = $this->getOriginalContent();
814 $content = $orig ?
$orig->getSection( $this->section
) : null;
816 if ( !$content ) $content = $def_content;
818 $undoafter = $wgRequest->getInt( 'undoafter' );
819 $undo = $wgRequest->getInt( 'undo' );
821 if ( $undo > 0 && $undoafter > 0 ) {
822 if ( $undo < $undoafter ) {
823 # If they got undoafter and undo round the wrong way, switch them
824 list( $undo, $undoafter ) = array( $undoafter, $undo );
827 $undorev = Revision
::newFromId( $undo );
828 $oldrev = Revision
::newFromId( $undoafter );
830 # Sanity check, make sure it's the right page,
831 # the revisions exist and they were not deleted.
832 # Otherwise, $content will be left as-is.
833 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
834 $undorev->getPage() == $oldrev->getPage() &&
835 $undorev->getPage() == $this->mTitle
->getArticleId() &&
836 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
837 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
839 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
841 if ( $content === false ) {
842 # Warn the user that something went wrong
843 $undoMsg = 'failure';
845 # Inform the user of our success and set an automatic edit summary
846 $undoMsg = 'success';
848 # If we just undid one rev, use an autosummary
849 $firstrev = $oldrev->getNext();
850 if ( $firstrev->getId() == $undo ) {
851 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
852 if ( $this->summary
=== '' ) {
853 $this->summary
= $undoSummary;
855 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
857 $this->undidRev
= $undo;
859 $this->formtype
= 'diff';
862 // Failed basic sanity checks.
863 // Older revisions may have been removed since the link
864 // was created, or we may simply have got bogus input.
868 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"error mw-undo-{$undoMsg}\">" .
869 wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
872 if ( $content === false ) {
873 $content = $this->getOriginalContent();
878 wfProfileOut( __METHOD__
);
883 * Get the content of the wanted revision, without section extraction.
885 * The result of this function can be used to compare user's input with
886 * section replaced in its context (using WikiPage::replaceSection())
887 * to the original text of the edit.
889 * This difers from Article::getContent() that when a missing revision is
890 * encountered the result will be an empty string and not the
891 * 'missing-article' message.
896 private function getOriginalContent() { #FIXME: use Content! set content_model and content_format!
897 if ( $this->section
== 'new' ) {
898 return $this->getCurrentContent();
900 $revision = $this->mArticle
->getRevisionFetched();
901 if ( $revision === null ) {
902 if ( !$this->content_model
) $this->content_model
= $this->getTitle()->getContentModelName();
903 $handler = ContentHandler
::getForModelName( $this->content_model
);
905 return $handler->emptyContent();
908 $content = $this->mArticle
->getContentObject();
913 * Get the current content of the page. This is basically similar to
914 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
915 * content object is returned instead of null.
920 private function getCurrentContent() {
921 $rev = $this->mArticle
->getRevision();
922 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
924 if ( $content === false ||
$content === null ) {
925 if ( !$this->content_model
) $this->content_model
= $this->getTitle()->getContentModelName();
926 $handler = ContentHandler
::getForModelName( $this->content_model
);
928 return $handler->emptyContent();
930 #FIXME: nasty side-effect!
931 $this->content_model
= $rev->getContentModelName();
932 $this->content_format
= $rev->getContentFormat();
939 * Use this method before edit() to preload some text into the edit box
941 * @param $text string
942 * @deprecated since 1.20
944 public function setPreloadedText( $text ) { #FIXME: deprecated, use setPreloadedContent()
945 wfDeprecated( __METHOD__
, "1.20" );
947 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
949 $this->setPreloadedContent( $content );
953 * Use this method before edit() to preload some content into the edit box
955 * @param $content Content
957 public function setPreloadedContent( Content
$content ) { #FIXME: use this!
958 $this->mPreloadedContent
= $content;
962 * Get the contents to be preloaded into the box, either set by
963 * an earlier setPreloadText() or by loading the given page.
965 * @param $preload String: representing the title to preload from.
967 * @deprecated since 1.20
969 protected function getPreloadedText( $preload ) { #FIXME: B/C only, replace usage!
970 wfDeprecated( __METHOD__
, "1.20" );
972 $content = $this->getPreloadedContent( $preload );
973 $text = $content->serialize( $this->content_format
); #XXX: really use serialized form? use ContentHandler::getContentText() instead?!
978 protected function getPreloadedContent( $preload ) { #FIXME: use this!
981 if ( !empty( $this->mPreloadContent
) ) {
982 return $this->mPreloadContent
;
985 $handler = ContentHandler
::getForTitle( $this->getTitle() );
987 if ( $preload === '' ) {
988 return $handler->emptyContent();
991 $title = Title
::newFromText( $preload );
992 # Check for existence to avoid getting MediaWiki:Noarticletext
993 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
994 return $handler->emptyContent();
997 $page = WikiPage
::factory( $title );
998 if ( $page->isRedirect() ) {
999 $title = $page->getRedirectTarget();
1001 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
1002 return $handler->emptyContent();
1004 $page = WikiPage
::factory( $title );
1007 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1008 $content = $page->getContent( Revision
::RAW
);
1010 return $content->preloadTransform( $title, $parserOptions );
1014 * Make sure the form isn't faking a user's credentials.
1016 * @param $request WebRequest
1020 function tokenOk( &$request ) {
1022 $token = $request->getVal( 'wpEditToken' );
1023 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1024 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1025 return $this->mTokenOk
;
1029 * Attempt submission
1030 * @return bool false if output is done, true if the rest of the form should be displayed
1032 function attemptSave() {
1033 global $wgUser, $wgOut;
1035 $resultDetails = false;
1036 # Allow bots to exempt some edits from bot flagging
1037 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1038 $status = $this->internalAttemptSave( $resultDetails, $bot );
1039 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1041 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1042 $this->didSave
= true;
1045 switch ( $status->value
) {
1046 case self
::AS_HOOK_ERROR_EXPECTED
:
1047 case self
::AS_CONTENT_TOO_BIG
:
1048 case self
::AS_ARTICLE_WAS_DELETED
:
1049 case self
::AS_CONFLICT_DETECTED
:
1050 case self
::AS_SUMMARY_NEEDED
:
1051 case self
::AS_TEXTBOX_EMPTY
:
1052 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1056 case self
::AS_HOOK_ERROR
:
1057 case self
::AS_FILTERING
:
1060 case self
::AS_SUCCESS_NEW_ARTICLE
:
1061 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1062 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1063 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1066 case self
::AS_SUCCESS_UPDATE
:
1068 $sectionanchor = $resultDetails['sectionanchor'];
1070 // Give extensions a chance to modify URL query on update
1071 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1073 if ( $resultDetails['redirect'] ) {
1074 if ( $extraQuery == '' ) {
1075 $extraQuery = 'redirect=no';
1077 $extraQuery = 'redirect=no&' . $extraQuery;
1080 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1083 case self
::AS_BLANK_ARTICLE
:
1084 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1087 case self
::AS_SPAM_ERROR
:
1088 $this->spamPageWithContent( $resultDetails['spam'] );
1091 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1092 throw new UserBlockedError( $wgUser->mBlock
);
1094 case self
::AS_IMAGE_REDIRECT_ANON
:
1095 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1096 throw new PermissionsError( 'upload' );
1098 case self
::AS_READ_ONLY_PAGE_ANON
:
1099 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1100 throw new PermissionsError( 'edit' );
1102 case self
::AS_READ_ONLY_PAGE
:
1103 throw new ReadOnlyError
;
1105 case self
::AS_RATE_LIMITED
:
1106 throw new ThrottledError();
1108 case self
::AS_NO_CREATE_PERMISSION
:
1109 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1110 throw new PermissionsError( $permission );
1117 * Attempt submission (no UI)
1122 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1124 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1125 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1126 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1128 function internalAttemptSave( &$result, $bot = false ) {
1129 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
1130 global $wgMaxArticleSize;
1132 $status = Status
::newGood();
1134 wfProfileIn( __METHOD__
);
1135 wfProfileIn( __METHOD__
. '-checks' );
1137 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1138 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1139 $status->fatal( 'hookaborted' );
1140 $status->value
= self
::AS_HOOK_ERROR
;
1141 wfProfileOut( __METHOD__
. '-checks' );
1142 wfProfileOut( __METHOD__
);
1146 # Check image redirect
1147 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1148 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
1149 !$wgUser->isAllowed( 'upload' ) ) {
1150 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1151 $status->setResult( false, $code );
1153 wfProfileOut( __METHOD__
. '-checks' );
1154 wfProfileOut( __METHOD__
);
1160 $match = self
::matchSummarySpamRegex( $this->summary
);
1161 if ( $match === false ) {
1162 $match = self
::matchSpamRegex( $this->textbox1
);
1164 if ( $match !== false ) {
1165 $result['spam'] = $match;
1166 $ip = $wgRequest->getIP();
1167 $pdbk = $this->mTitle
->getPrefixedDBkey();
1168 $match = str_replace( "\n", '', $match );
1169 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1170 $status->fatal( 'spamprotectionmatch', $match );
1171 $status->value
= self
::AS_SPAM_ERROR
;
1172 wfProfileOut( __METHOD__
. '-checks' );
1173 wfProfileOut( __METHOD__
);
1176 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
1177 # Error messages or other handling should be performed by the filter function
1178 $status->setResult( false, self
::AS_FILTERING
);
1179 wfProfileOut( __METHOD__
. '-checks' );
1180 wfProfileOut( __METHOD__
);
1183 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1184 # Error messages etc. could be handled within the hook...
1185 $status->fatal( 'hookaborted' );
1186 $status->value
= self
::AS_HOOK_ERROR
;
1187 wfProfileOut( __METHOD__
. '-checks' );
1188 wfProfileOut( __METHOD__
);
1190 } elseif ( $this->hookError
!= '' ) {
1191 # ...or the hook could be expecting us to produce an error
1192 $status->fatal( 'hookaborted' );
1193 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1194 wfProfileOut( __METHOD__
. '-checks' );
1195 wfProfileOut( __METHOD__
);
1199 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1200 // Auto-block user's IP if the account was "hard" blocked
1201 $wgUser->spreadAnyEditBlock();
1202 # Check block state against master, thus 'false'.
1203 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1204 wfProfileOut( __METHOD__
. '-checks' );
1205 wfProfileOut( __METHOD__
);
1209 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1210 if ( $this->kblength
> $wgMaxArticleSize ) {
1211 // Error will be displayed by showEditForm()
1212 $this->tooBig
= true;
1213 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1214 wfProfileOut( __METHOD__
. '-checks' );
1215 wfProfileOut( __METHOD__
);
1219 if ( !$wgUser->isAllowed( 'edit' ) ) {
1220 if ( $wgUser->isAnon() ) {
1221 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1222 wfProfileOut( __METHOD__
. '-checks' );
1223 wfProfileOut( __METHOD__
);
1226 $status->fatal( 'readonlytext' );
1227 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1228 wfProfileOut( __METHOD__
. '-checks' );
1229 wfProfileOut( __METHOD__
);
1234 if ( wfReadOnly() ) {
1235 $status->fatal( 'readonlytext' );
1236 $status->value
= self
::AS_READ_ONLY_PAGE
;
1237 wfProfileOut( __METHOD__
. '-checks' );
1238 wfProfileOut( __METHOD__
);
1241 if ( $wgUser->pingLimiter() ) {
1242 $status->fatal( 'actionthrottledtext' );
1243 $status->value
= self
::AS_RATE_LIMITED
;
1244 wfProfileOut( __METHOD__
. '-checks' );
1245 wfProfileOut( __METHOD__
);
1249 # If the article has been deleted while editing, don't save it without
1251 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1252 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1253 wfProfileOut( __METHOD__
. '-checks' );
1254 wfProfileOut( __METHOD__
);
1258 wfProfileOut( __METHOD__
. '-checks' );
1260 # If article is new, insert it.
1261 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1262 $new = ( $aid == 0 );
1265 // Late check for create permission, just in case *PARANOIA*
1266 if ( !$this->mTitle
->userCan( 'create' ) ) {
1267 $status->fatal( 'nocreatetext' );
1268 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1269 wfDebug( __METHOD__
. ": no create permission\n" );
1270 wfProfileOut( __METHOD__
);
1274 # Don't save a new article if it's blank.
1275 if ( $this->textbox1
== '' ) {
1276 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1277 wfProfileOut( __METHOD__
);
1281 // Run post-section-merge edit filter
1282 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1283 # Error messages etc. could be handled within the hook...
1284 $status->fatal( 'hookaborted' );
1285 $status->value
= self
::AS_HOOK_ERROR
;
1286 wfProfileOut( __METHOD__
);
1288 } elseif ( $this->hookError
!= '' ) {
1289 # ...or the hook could be expecting us to produce an error
1290 $status->fatal( 'hookaborted' );
1291 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1292 wfProfileOut( __METHOD__
);
1296 # Handle the user preference to force summaries here. Check if it's not a redirect.
1297 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
1298 if ( md5( $this->summary
) == $this->autoSumm
) {
1299 $this->missingSummary
= true;
1300 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1301 $status->value
= self
::AS_SUMMARY_NEEDED
;
1302 wfProfileOut( __METHOD__
);
1307 $content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
); #FIXME: handle parse errors
1309 $result['sectionanchor'] = '';
1310 if ( $this->section
== 'new' ) {
1311 if ( $this->sectiontitle
!== '' ) {
1312 // Insert the section title above the content.
1313 $content = $content->addSectionHeader( $this->sectiontitle
);
1315 // Jump to the new section
1316 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1318 // If no edit summary was specified, create one automatically from the section
1319 // title and have it link to the new section. Otherwise, respect the summary as
1321 if ( $this->summary
=== '' ) {
1322 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1323 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1325 } elseif ( $this->summary
!== '' ) {
1326 // Insert the section title above the content.
1327 $content = $content->addSectionHeader( $this->sectiontitle
);
1329 // Jump to the new section
1330 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1332 // Create a link to the new section from the edit summary.
1333 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1334 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1338 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1342 # Article exists. Check for edit conflict.
1344 $this->mArticle
->clear(); # Force reload of dates, etc.
1345 $timestamp = $this->mArticle
->getTimestamp();
1347 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1349 if ( $timestamp != $this->edittime
) {
1350 $this->isConflict
= true;
1351 if ( $this->section
== 'new' ) {
1352 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1353 $this->mArticle
->getComment() == $this->summary
) {
1354 // Probably a duplicate submission of a new comment.
1355 // This can happen when squid resends a request after
1356 // a timeout but the first one actually went through.
1357 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1359 // New comment; suppress conflict.
1360 $this->isConflict
= false;
1361 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1363 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1364 # Suppress edit conflict with self, except for section edits where merging is required.
1365 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1366 $this->isConflict
= false;
1370 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1371 // backwards compatibility with old forms/bots).
1372 if ( $this->sectiontitle
!== '' ) {
1373 $sectionTitle = $this->sectiontitle
;
1375 $sectionTitle = $this->summary
;
1378 $textbox_content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
); #FIXME: handle parse errors
1381 if ( $this->isConflict
) {
1382 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1384 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1386 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1388 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1391 if ( is_null( $content ) ) {
1392 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1393 $this->isConflict
= true;
1394 $content = $textbox_content; // do not try to merge here!
1395 } elseif ( $this->isConflict
) {
1397 if ( $this->mergeChangesIntoContent( $textbox_content ) ) {
1398 // Successful merge! Maybe we should tell the user the good news?
1399 $content = $textbox_content;
1400 $this->isConflict
= false;
1401 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1403 $this->section
= '';
1404 #$this->textbox1 = $text; #redundant, nothing to do here?
1405 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1409 if ( $this->isConflict
) {
1410 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1411 wfProfileOut( __METHOD__
);
1415 // Run post-section-merge edit filter
1416 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $content->serialize( $this->content_format
), &$this->hookError
, $this->summary
) )
1417 ||
!wfRunHooks( 'EditFilterMergedContent', array( $this, $content, &$this->hookError
, $this->summary
) ) ) { #FIXME: document new hook
1418 # Error messages etc. could be handled within the hook...
1419 $status->fatal( 'hookaborted' );
1420 $status->value
= self
::AS_HOOK_ERROR
;
1421 wfProfileOut( __METHOD__
);
1423 } elseif ( $this->hookError
!= '' ) {
1424 # ...or the hook could be expecting us to produce an error
1425 $status->fatal( 'hookaborted' );
1426 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1427 wfProfileOut( __METHOD__
);
1431 # Handle the user preference to force summaries here, but not for null edits
1432 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1433 && !$content->equals( $this->getOriginalContent() )
1434 && !$content->isRedirect() ) # check if it's not a redirect
1436 if ( md5( $this->summary
) == $this->autoSumm
) {
1437 $this->missingSummary
= true;
1438 $status->fatal( 'missingsummary' );
1439 $status->value
= self
::AS_SUMMARY_NEEDED
;
1440 wfProfileOut( __METHOD__
);
1445 # And a similar thing for new sections
1446 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1447 if ( trim( $this->summary
) == '' ) {
1448 $this->missingSummary
= true;
1449 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1450 $status->value
= self
::AS_SUMMARY_NEEDED
;
1451 wfProfileOut( __METHOD__
);
1457 wfProfileIn( __METHOD__
. '-sectionanchor' );
1458 $sectionanchor = '';
1459 if ( $this->section
== 'new' ) {
1460 if ( $this->textbox1
== '' ) {
1461 $this->missingComment
= true;
1462 $status->fatal( 'missingcommenttext' );
1463 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1464 wfProfileOut( __METHOD__
. '-sectionanchor' );
1465 wfProfileOut( __METHOD__
);
1468 if ( $this->sectiontitle
!== '' ) {
1469 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1470 // If no edit summary was specified, create one automatically from the section
1471 // title and have it link to the new section. Otherwise, respect the summary as
1473 if ( $this->summary
=== '' ) {
1474 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1475 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1477 } elseif ( $this->summary
!== '' ) {
1478 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1479 # This is a new section, so create a link to the new section
1480 # in the revision summary.
1481 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1482 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1484 } elseif ( $this->section
!= '' ) {
1485 # Try to get a section anchor from the section source, redirect to edited section if header found
1486 # XXX: might be better to integrate this into Article::replaceSection
1487 # for duplicate heading checking and maybe parsing
1488 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1489 # we can't deal with anchors, includes, html etc in the header for now,
1490 # headline would need to be parsed to improve this
1491 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1492 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1495 $result['sectionanchor'] = $sectionanchor;
1496 wfProfileOut( __METHOD__
. '-sectionanchor' );
1498 // Save errors may fall down to the edit form, but we've now
1499 // merged the section into full text. Clear the section field
1500 // so that later submission of conflict forms won't try to
1501 // replace that into a duplicated mess.
1502 $this->textbox1
= $content->serialize( $this->content_format
);
1503 $this->section
= '';
1505 $status->value
= self
::AS_SUCCESS_UPDATE
;
1508 // Check for length errors again now that the section is merged in
1509 $this->kblength
= (int)( strlen( $content->serialize( $this->content_format
) ) / 1024 );
1510 if ( $this->kblength
> $wgMaxArticleSize ) {
1511 $this->tooBig
= true;
1512 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1513 wfProfileOut( __METHOD__
);
1517 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1518 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1519 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1520 ( $bot ? EDIT_FORCE_BOT
: 0 );
1522 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags, false, null, $this->content_format
);
1524 if ( $doEditStatus->isOK() ) {
1525 $result['redirect'] = $content->isRedirect();
1526 $this->commitWatch();
1527 wfProfileOut( __METHOD__
);
1530 $this->isConflict
= true;
1531 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1532 wfProfileOut( __METHOD__
);
1533 return $doEditStatus;
1538 * Commit the change of watch status
1540 protected function commitWatch() {
1542 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1543 $dbw = wfGetDB( DB_MASTER
);
1545 if ( $this->watchthis
) {
1546 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1548 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1555 * Check if no edits were made by other users since
1556 * the time a user started editing the page. Limit to
1557 * 50 revisions for the sake of performance.
1560 * @param $edittime string
1564 protected function userWasLastToEdit( $id, $edittime ) {
1565 if( !$id ) return false;
1566 $dbw = wfGetDB( DB_MASTER
);
1567 $res = $dbw->select( 'revision',
1570 'rev_page' => $this->mTitle
->getArticleId(),
1571 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1574 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1575 foreach ( $res as $row ) {
1576 if( $row->rev_user
!= $id ) {
1587 * @parma $editText string
1590 * @deprecated since 1.20
1592 function mergeChangesInto( &$editText ){
1593 wfDebug( __METHOD__
, "1.20" );
1595 $editContent = ContentHandler
::makeContent( $editText, $this->getTitle(), $this->content_model
, $this->content_format
);
1597 $ok = $this->mergeChangesIntoContent( $editContent );
1600 $editText = $editContent->serialize( $this->content_format
); #XXX: really serialize?!
1611 * @parma $editText string
1616 private function mergeChangesIntoContent( &$editContent ){
1617 wfProfileIn( __METHOD__
);
1619 $db = wfGetDB( DB_MASTER
);
1621 // This is the revision the editor started from
1622 $baseRevision = $this->getBaseRevision();
1623 if ( is_null( $baseRevision ) ) {
1624 wfProfileOut( __METHOD__
);
1627 $baseContent = $baseRevision->getContent();
1629 // The current state, we want to merge updates into it
1630 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1631 if ( is_null( $currentRevision ) ) {
1632 wfProfileOut( __METHOD__
);
1635 $currentContent = $currentRevision->getContent();
1637 $handler = ContentHandler
::getForModelName( $baseContent->getModelName() );
1639 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1642 $editContent = $result;
1643 wfProfileOut( __METHOD__
);
1646 wfProfileOut( __METHOD__
);
1654 function getBaseRevision() {
1655 if ( !$this->mBaseRevision
) {
1656 $db = wfGetDB( DB_MASTER
);
1657 $baseRevision = Revision
::loadFromTimestamp(
1658 $db, $this->mTitle
, $this->edittime
);
1659 return $this->mBaseRevision
= $baseRevision;
1661 return $this->mBaseRevision
;
1666 * Check given input text against $wgSpamRegex, and return the text of the first match.
1668 * @param $text string
1670 * @return string|false matching string or false
1672 public static function matchSpamRegex( $text ) {
1673 global $wgSpamRegex;
1674 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1675 $regexes = (array)$wgSpamRegex;
1676 return self
::matchSpamRegexInternal( $text, $regexes );
1680 * Check given input text against $wgSpamRegex, and return the text of the first match.
1682 * @parma $text string
1684 * @return string|false matching string or false
1686 public static function matchSummarySpamRegex( $text ) {
1687 global $wgSummarySpamRegex;
1688 $regexes = (array)$wgSummarySpamRegex;
1689 return self
::matchSpamRegexInternal( $text, $regexes );
1693 * @param $text string
1694 * @param $regexes array
1695 * @return bool|string
1697 protected static function matchSpamRegexInternal( $text, $regexes ) {
1698 foreach( $regexes as $regex ) {
1700 if( preg_match( $regex, $text, $matches ) ) {
1707 function setHeaders() {
1708 global $wgOut, $wgUser;
1710 $wgOut->addModules( 'mediawiki.action.edit' );
1712 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1713 $wgOut->addModules( 'mediawiki.legacy.preview' );
1715 // Bug #19334: textarea jumps when editing articles in IE8
1716 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1718 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1720 # Enabled article-related sidebar, toplinks, etc.
1721 $wgOut->setArticleRelated( true );
1723 if ( $this->isConflict
) {
1724 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1725 } elseif ( $this->section
!= '' ) {
1726 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1727 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1729 # Use the title defined by DISPLAYTITLE magic word when present
1730 if ( isset( $this->mParserOutput
)
1731 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1734 $title = $this->getContextTitle()->getPrefixedText();
1736 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1741 * Show all applicable editing introductions
1743 protected function showIntro() {
1744 global $wgOut, $wgUser;
1745 if ( $this->suppressIntro
) {
1749 $namespace = $this->mTitle
->getNamespace();
1751 if ( $namespace == NS_MEDIAWIKI
) {
1752 # Show a warning if editing an interface message
1753 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1756 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1757 # Show log extract when the user is currently blocked
1758 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1759 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1760 $username = $parts[0];
1761 $user = User
::newFromName( $username, false /* allow IP users*/ );
1762 $ip = User
::isIP( $username );
1763 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1764 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1765 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1766 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1767 LogEventsList
::showLogExtract(
1770 $user->getUserPage(),
1774 'showIfEmpty' => false,
1776 'blocked-notice-logextract',
1777 $user->getName() # Support GENDER in notice
1783 # Try to add a custom edit intro, or use the standard one if this is not possible.
1784 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1785 if ( $wgUser->isLoggedIn() ) {
1786 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1788 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1791 # Give a notice if the user is editing a deleted/moved page...
1792 if ( !$this->mTitle
->exists() ) {
1793 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1794 '', array( 'lim' => 10,
1795 'conds' => array( "log_action != 'revision'" ),
1796 'showIfEmpty' => false,
1797 'msgKey' => array( 'recreate-moveddeleted-warn') )
1803 * Attempt to show a custom editing introduction, if supplied
1807 protected function showCustomIntro() {
1808 if ( $this->editintro
) {
1809 $title = Title
::newFromText( $this->editintro
);
1810 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1812 // Added using template syntax, to take <noinclude>'s into account.
1813 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1824 * Send the edit form and related headers to $wgOut
1825 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1826 * during form output near the top, for captchas and the like.
1828 function showEditForm( $formCallback = null ) {
1829 global $wgOut, $wgUser;
1831 wfProfileIn( __METHOD__
);
1833 #need to parse the preview early so that we know which templates are used,
1834 #otherwise users with "show preview after edit box" will get a blank list
1835 #we parse this near the beginning so that setHeaders can do the title
1836 #setting work instead of leaving it in getPreviewText
1837 $previewOutput = '';
1838 if ( $this->formtype
== 'preview' ) {
1839 $previewOutput = $this->getPreviewText();
1842 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1844 $this->setHeaders();
1846 if ( $this->showHeader() === false ) {
1847 wfProfileOut( __METHOD__
);
1851 $wgOut->addHTML( $this->editFormPageTop
);
1853 if ( $wgUser->getOption( 'previewontop' ) ) {
1854 $this->displayPreviewArea( $previewOutput, true );
1857 $wgOut->addHTML( $this->editFormTextTop
);
1859 $showToolbar = true;
1860 if ( $this->wasDeletedSinceLastEdit() ) {
1861 if ( $this->formtype
== 'save' ) {
1862 // Hide the toolbar and edit area, user can click preview to get it back
1863 // Add an confirmation checkbox and explanation.
1864 $showToolbar = false;
1866 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1867 'deletedwhileediting' );
1871 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
1872 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1873 'enctype' => 'multipart/form-data' ) ) );
1875 if ( is_callable( $formCallback ) ) {
1876 call_user_func_array( $formCallback, array( &$wgOut ) );
1879 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1881 // Put these up at the top to ensure they aren't lost on early form submission
1882 $this->showFormBeforeText();
1884 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1885 $username = $this->lastDelete
->user_name
;
1886 $comment = $this->lastDelete
->log_comment
;
1888 // It is better to not parse the comment at all than to have templates expanded in the middle
1889 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1890 $key = $comment === ''
1891 ?
'confirmrecreate-noreason'
1892 : 'confirmrecreate';
1894 '<div class="mw-confirm-recreate">' .
1895 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1896 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1897 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1903 # If a blank edit summary was previously provided, and the appropriate
1904 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1905 # user being bounced back more than once in the event that a summary
1908 # For a bit more sophisticated detection of blank summaries, hash the
1909 # automatic one and pass that in the hidden field wpAutoSummary.
1910 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
1911 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1914 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1915 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1917 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
1919 $wgOut->addHTML( Html
::hidden( 'format', $this->content_format
) );
1920 $wgOut->addHTML( Html
::hidden( 'model', $this->content_model
) );
1922 if ( $this->section
== 'new' ) {
1923 $this->showSummaryInput( true, $this->summary
);
1924 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1927 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1929 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1930 $wgOut->addHTML( EditPage
::getEditToolbar() );
1933 if ( $this->isConflict
) {
1934 // In an edit conflict bypass the overrideable content form method
1935 // and fallback to the raw wpTextbox1 since editconflicts can't be
1936 // resolved between page source edits and custom ui edits using the
1938 $this->textbox2
= $this->textbox1
;
1940 $content = $this->getCurrentContent();
1941 $this->textbox1
= $content->serialize( $this->content_format
);
1943 $this->showTextbox1();
1945 $this->showContentForm();
1948 $wgOut->addHTML( $this->editFormTextAfterContent
);
1950 $wgOut->addWikiText( $this->getCopywarn() );
1952 $wgOut->addHTML( Html
::element( 'p', null, "model: " . $this->content_model
) ); #FIXME: content handler debug stuff, DELETE!
1953 $wgOut->addHTML( Html
::element( 'p', null, "format: " . $this->content_format
) ); #FIXME: content handler debug stuff, DELETE!
1955 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1957 $this->showStandardInputs();
1959 $this->showFormAfterText();
1961 $this->showTosSummary();
1963 $this->showEditTools();
1965 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
1967 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
1968 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
1970 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
1971 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
1973 if ( $this->isConflict
) {
1974 $this->showConflict();
1977 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
1979 if ( !$wgUser->getOption( 'previewontop' ) ) {
1980 $this->displayPreviewArea( $previewOutput, false );
1983 wfProfileOut( __METHOD__
);
1987 * Extract the section title from current section text, if any.
1989 * @param string $text
1990 * @return Mixed|string or false
1992 public static function extractSectionTitle( $text ) {
1993 preg_match( "/^(=+)(.+)\\1(\n|$)/i", $text, $matches );
1994 if ( !empty( $matches[2] ) ) {
1996 return $wgParser->stripSectionName(trim($matches[2]));
2002 protected function showHeader() {
2003 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2005 if ( $this->mTitle
->isTalkPage() ) {
2006 $wgOut->addWikiMsg( 'talkpagetext' );
2009 # Optional notices on a per-namespace and per-page basis
2010 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
2011 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
2012 if ( $editnotice_ns_message->exists() ) {
2013 $wgOut->addWikiText( $editnotice_ns_message->plain() );
2015 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
2016 $parts = explode( '/', $this->mTitle
->getDBkey() );
2017 $editnotice_base = $editnotice_ns;
2018 while ( count( $parts ) > 0 ) {
2019 $editnotice_base .= '-'.array_shift( $parts );
2020 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
2021 if ( $editnotice_base_msg->exists() ) {
2022 $wgOut->addWikiText( $editnotice_base_msg->plain() );
2026 # Even if there are no subpages in namespace, we still don't want / in MW ns.
2027 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
2028 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
2029 if ( $editnoticeMsg->exists() ) {
2030 $wgOut->addWikiText( $editnoticeMsg->plain() );
2034 if ( $this->isConflict
) {
2035 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2036 $this->edittime
= $this->mArticle
->getTimestamp();
2038 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2039 // We use $this->section to much before this and getVal('wgSection') directly in other places
2040 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2041 // Someone is welcome to try refactoring though
2042 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2046 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2047 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2048 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
2049 if ( $sectionTitle !== false ) {
2050 $this->summary
= "/* $sectionTitle */ ";
2055 if ( $this->missingComment
) {
2056 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2059 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2060 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2063 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2064 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2067 if ( $this->hookError
!== '' ) {
2068 $wgOut->addWikiText( $this->hookError
);
2071 if ( !$this->checkUnicodeCompliantBrowser() ) {
2072 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2075 if ( $this->section
!= 'new' ) {
2076 $revision = $this->mArticle
->getRevisionFetched();
2078 // Let sysop know that this will make private content public if saved
2080 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
2081 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2082 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2083 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2086 if ( !$revision->isCurrent() ) {
2087 $this->mArticle
->setOldSubtitle( $revision->getId() );
2088 $wgOut->addWikiMsg( 'editingold' );
2090 } elseif ( $this->mTitle
->exists() ) {
2091 // Something went wrong
2093 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2094 array( 'missing-article', $this->mTitle
->getPrefixedText(),
2095 wfMsgNoTrans( 'missingarticle-rev', $this->oldid
) ) );
2100 if ( wfReadOnly() ) {
2101 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2102 } elseif ( $wgUser->isAnon() ) {
2103 if ( $this->formtype
!= 'preview' ) {
2104 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2106 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2109 if ( $this->isCssJsSubpage
) {
2110 # Check the skin exists
2111 if ( $this->isWrongCaseCssJsPage
) {
2112 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2114 if ( $this->formtype
!== 'preview' ) {
2115 if ( $this->isCssSubpage
)
2116 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2117 if ( $this->isJsSubpage
)
2118 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2123 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2124 # Is the title semi-protected?
2125 if ( $this->mTitle
->isSemiProtected() ) {
2126 $noticeMsg = 'semiprotectedpagewarning';
2128 # Then it must be protected based on static groups (regular)
2129 $noticeMsg = 'protectedpagewarning';
2131 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2132 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2134 if ( $this->mTitle
->isCascadeProtected() ) {
2135 # Is this page under cascading protection from some source pages?
2136 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
2137 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2138 $cascadeSourcesCount = count( $cascadeSources );
2139 if ( $cascadeSourcesCount > 0 ) {
2140 # Explain, and list the titles responsible
2141 foreach( $cascadeSources as $page ) {
2142 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2145 $notice .= '</div>';
2146 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2148 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2149 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2151 'showIfEmpty' => false,
2152 'msgKey' => array( 'titleprotectedwarning' ),
2153 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2156 if ( $this->kblength
=== false ) {
2157 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2160 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2161 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2162 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2164 if( !wfMessage('longpage-hint')->isDisabled() ) {
2165 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2166 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2173 * Standard summary input and label (wgSummary), abstracted so EditPage
2174 * subclasses may reorganize the form.
2175 * Note that you do not need to worry about the label's for=, it will be
2176 * inferred by the id given to the input. You can remove them both by
2177 * passing array( 'id' => false ) to $userInputAttrs.
2179 * @param $summary string The value of the summary input
2180 * @param $labelText string The html to place inside the label
2181 * @param $inputAttrs array of attrs to use on the input
2182 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2184 * @return array An array in the format array( $label, $input )
2186 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
2187 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
2188 $inputAttrs = ( is_array($inputAttrs) ?
$inputAttrs : array() ) +
array(
2189 'id' => 'wpSummary',
2190 'maxlength' => '200',
2193 'spellcheck' => 'true',
2194 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2196 $spanLabelAttrs = ( is_array($spanLabelAttrs) ?
$spanLabelAttrs : array() ) +
array(
2197 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2198 'id' => "wpSummaryLabel"
2203 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2204 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2207 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2209 return array( $label, $input );
2213 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2214 * up top, or false if this is the comment summary
2215 * down below the textarea
2216 * @param $summary String: The text of the summary to display
2219 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2220 global $wgOut, $wgContLang;
2221 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2222 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2223 if ( $isSubjectPreview ) {
2224 if ( $this->nosummary
) {
2228 if ( !$this->mShowSummaryField
) {
2232 $summary = $wgContLang->recodeForEdit( $summary );
2233 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
2234 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
2235 $wgOut->addHTML("{$label} {$input}");
2239 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2240 * up top, or false if this is the comment summary
2241 * down below the textarea
2242 * @param $summary String: the text of the summary to display
2245 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2246 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2251 if ( $isSubjectPreview )
2252 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2254 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2256 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2257 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2260 protected function showFormBeforeText() {
2262 $section = htmlspecialchars( $this->section
);
2263 $wgOut->addHTML( <<<HTML
2264 <input type='hidden' value="{$section}" name="wpSection" />
2265 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2266 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2267 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2271 if ( !$this->checkUnicodeCompliantBrowser() )
2272 $wgOut->addHTML(Html
::hidden( 'safemode', '1' ));
2275 protected function showFormAfterText() {
2276 global $wgOut, $wgUser;
2278 * To make it harder for someone to slip a user a page
2279 * which submits an edit form to the wiki without their
2280 * knowledge, a random token is associated with the login
2281 * session. If it's not passed back with the submission,
2282 * we won't save the page, or render user JavaScript and
2285 * For anon editors, who may not have a session, we just
2286 * include the constant suffix to prevent editing from
2287 * broken text-mangling proxies.
2289 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2293 * Subpage overridable method for printing the form for page content editing
2294 * By default this simply outputs wpTextbox1
2295 * Subclasses can override this to provide a custom UI for editing;
2296 * be it a form, or simply wpTextbox1 with a modified content that will be
2297 * reverse modified when extracted from the post data.
2298 * Note that this is basically the inverse for importContentFormData
2300 protected function showContentForm() {
2301 $this->showTextbox1();
2305 * Method to output wpTextbox1
2306 * The $textoverride method can be used by subclasses overriding showContentForm
2307 * to pass back to this method.
2309 * @param $customAttribs An array of html attributes to use in the textarea
2310 * @param $textoverride String: optional text to override $this->textarea1 with
2312 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2313 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2314 $attribs = array( 'style' => 'display:none;' );
2316 $classes = array(); // Textarea CSS
2317 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2318 # Is the title semi-protected?
2319 if ( $this->mTitle
->isSemiProtected() ) {
2320 $classes[] = 'mw-textarea-sprotected';
2322 # Then it must be protected based on static groups (regular)
2323 $classes[] = 'mw-textarea-protected';
2325 # Is the title cascade-protected?
2326 if ( $this->mTitle
->isCascadeProtected() ) {
2327 $classes[] = 'mw-textarea-cprotected';
2331 $attribs = array( 'tabindex' => 1 );
2333 if ( is_array( $customAttribs ) ) {
2334 $attribs +
= $customAttribs;
2337 if ( count( $classes ) ) {
2338 if ( isset( $attribs['class'] ) ) {
2339 $classes[] = $attribs['class'];
2341 $attribs['class'] = implode( ' ', $classes );
2345 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2348 protected function showTextbox2() {
2349 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2352 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2353 global $wgOut, $wgUser;
2355 $wikitext = $this->safeUnicodeOutput( $text );
2356 if ( strval($wikitext) !== '' ) {
2357 // Ensure there's a newline at the end, otherwise adding lines
2359 // But don't add a newline if the ext is empty, or Firefox in XHTML
2360 // mode will show an extra newline. A bit annoying.
2364 $attribs = $customAttribs +
array(
2367 'cols' => $wgUser->getIntOption( 'cols' ),
2368 'rows' => $wgUser->getIntOption( 'rows' ),
2369 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2372 $pageLang = $this->mTitle
->getPageLanguage();
2373 $attribs['lang'] = $pageLang->getCode();
2374 $attribs['dir'] = $pageLang->getDir();
2376 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2379 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2383 $classes[] = 'ontop';
2385 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2387 if ( $this->formtype
!= 'preview' )
2388 $attribs['style'] = 'display: none;';
2390 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2392 if ( $this->formtype
== 'preview' ) {
2393 $this->showPreview( $previewOutput );
2396 $wgOut->addHTML( '</div>' );
2398 if ( $this->formtype
== 'diff') {
2404 * Append preview output to $wgOut.
2405 * Includes category rendering if this is a category page.
2407 * @param $text String: the HTML to be output for the preview.
2409 protected function showPreview( $text ) {
2411 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2412 $this->mArticle
->openShowCategory();
2414 # This hook seems slightly odd here, but makes things more
2415 # consistent for extensions.
2416 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
2417 $wgOut->addHTML( $text );
2418 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2419 $this->mArticle
->closeShowCategory();
2424 * Get a diff between the current contents of the edit box and the
2425 * version of the page we're editing from.
2427 * If this is a section edit, we'll replace the section as for final
2428 * save and then make a comparison.
2430 function showDiff() {
2431 global $wgUser, $wgContLang, $wgOut;
2433 $oldContent = $this->getOriginalContent();
2435 $textboxContent = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(),
2436 $this->content_model
, $this->content_format
); #FIXME: handle parse errors
2438 $newContent = $this->mArticle
->replaceSectionContent(
2439 $this->section
, $textboxContent,
2440 $this->summary
, $this->edittime
);
2442 # hanlde legacy text-based hook
2443 $newtext_orig = $newContent->serialize( $this->content_format
);
2444 $newtext = $newtext_orig; #clone
2445 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2447 if ( $newtext != $newtext_orig ) {
2448 #if the hook changed the text, create a new Content object accordingly.
2449 $newContent = ContentHandler
::makeContent( $newtext, $this->getTitle(), $newContent->getModelName() ); #FIXME: handle parse errors
2452 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) ); #FIXME: document new hook
2454 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2455 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2457 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2458 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2459 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2461 $de = $oldContent->getContentHandler()->getDifferenceEngine( $this->mArticle
->getContext() );
2462 $de->setContent( $oldContent, $newContent );
2464 $difftext = $de->getDiff( $oldtitle, $newtitle );
2465 $de->showDiffStyle();
2470 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2474 * Give a chance for site and per-namespace customizations of
2475 * terms of service summary link that might exist separately
2476 * from the copyright notice.
2478 * This will display between the save button and the edit tools,
2479 * so should remain short!
2481 protected function showTosSummary() {
2482 $msg = 'editpage-tos-summary';
2483 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2484 if( !wfMessage( $msg )->isDisabled() ) {
2486 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2487 $wgOut->addWikiMsg( $msg );
2488 $wgOut->addHTML( '</div>' );
2492 protected function showEditTools() {
2494 $wgOut->addHTML( '<div class="mw-editTools">' .
2495 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2499 protected function getCopywarn() {
2500 global $wgRightsText;
2501 if ( $wgRightsText ) {
2502 $copywarnMsg = array( 'copyrightwarning',
2503 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2506 $copywarnMsg = array( 'copyrightwarning2',
2507 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2509 // Allow for site and per-namespace customization of contribution/copyright notice.
2510 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2512 return "<div id=\"editpage-copywarn\">\n" .
2513 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
2516 protected function showStandardInputs( &$tabindex = 2 ) {
2518 $wgOut->addHTML( "<div class='editOptions'>\n" );
2520 if ( $this->section
!= 'new' ) {
2521 $this->showSummaryInput( false, $this->summary
);
2522 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2525 $checkboxes = $this->getCheckboxes( $tabindex,
2526 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2527 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2528 $wgOut->addHTML( "<div class='editButtons'>\n" );
2529 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2531 $cancel = $this->getCancelLink();
2532 if ( $cancel !== '' ) {
2533 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2535 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2536 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
2537 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
2538 htmlspecialchars( wfMsg( 'newwindow' ) );
2539 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2540 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2544 * Show an edit conflict. textbox1 is already shown in showEditForm().
2545 * If you want to use another entry point to this function, be careful.
2547 protected function showConflict() {
2550 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2551 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2553 $content1 = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
); #FIXME: handle parse errors
2554 $content2 = ContentHandler
::makeContent( $this->textbox2
, $this->getTitle(), $this->content_model
, $this->content_format
); #FIXME: handle parse errors
2556 $handler = ContentHandler
::getForModelName( $this->content_model
);
2557 $de = $handler->getDifferenceEngine( $this->mArticle
->getContext() );
2558 $de->setContent( $content2, $content1 );
2559 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2561 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2562 $this->showTextbox2();
2569 public function getCancelLink() {
2570 $cancelParams = array();
2571 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2572 $cancelParams['oldid'] = $this->oldid
;
2575 return Linker
::linkKnown(
2576 $this->getContextTitle(),
2577 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2578 array( 'id' => 'mw-editform-cancel' ),
2584 * Returns the URL to use in the form's action attribute.
2585 * This is used by EditPage subclasses when simply customizing the action
2586 * variable in the constructor is not enough. This can be used when the
2587 * EditPage lives inside of a Special page rather than a custom page action.
2589 * @param $title Title object for which is being edited (where we go to for &action= links)
2592 protected function getActionURL( Title
$title ) {
2593 return $title->getLocalURL( array( 'action' => $this->action
) );
2597 * Check if a page was deleted while the user was editing it, before submit.
2598 * Note that we rely on the logging table, which hasn't been always there,
2599 * but that doesn't matter, because this only applies to brand new
2602 protected function wasDeletedSinceLastEdit() {
2603 if ( $this->deletedSinceEdit
!== null ) {
2604 return $this->deletedSinceEdit
;
2607 $this->deletedSinceEdit
= false;
2609 if ( $this->mTitle
->isDeletedQuick() ) {
2610 $this->lastDelete
= $this->getLastDelete();
2611 if ( $this->lastDelete
) {
2612 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2613 if ( $deleteTime > $this->starttime
) {
2614 $this->deletedSinceEdit
= true;
2619 return $this->deletedSinceEdit
;
2622 protected function getLastDelete() {
2623 $dbr = wfGetDB( DB_SLAVE
);
2624 $data = $dbr->selectRow(
2625 array( 'logging', 'user' ),
2636 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2637 'log_title' => $this->mTitle
->getDBkey(),
2638 'log_type' => 'delete',
2639 'log_action' => 'delete',
2640 'user_id=log_user' ),
2642 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2644 // Quick paranoid permission checks...
2645 if( is_object( $data ) ) {
2646 if( $data->log_deleted
& LogPage
::DELETED_USER
)
2647 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2648 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2649 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2655 * Get the rendered text for previewing.
2658 function getPreviewText() {
2659 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2661 wfProfileIn( __METHOD__
);
2663 if ( $wgRawHtml && !$this->mTokenOk
) {
2664 // Could be an offsite preview attempt. This is very unsafe if
2665 // HTML is enabled, as it could be an attack.
2667 if ( $this->textbox1
!== '' ) {
2668 // Do not put big scary notice, if previewing the empty
2669 // string, which happens when you initially edit
2670 // a category page, due to automatic preview-on-open.
2671 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2672 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2674 wfProfileOut( __METHOD__
);
2678 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2679 if ( $this->mTokenOkExceptSuffix
) {
2680 $note = wfMsg( 'token_suffix_mismatch' );
2682 $note = wfMsg( 'session_fail_preview' );
2684 } elseif ( $this->incompleteForm
) {
2685 $note = wfMsg( 'edit_form_incomplete' );
2687 $note = wfMsg( 'previewnote' );
2690 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2691 $parserOptions->setEditSection( false );
2692 $parserOptions->setTidy( true );
2693 $parserOptions->setIsPreview( true );
2694 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2696 # don't parse non-wikitext pages, show message about preview
2697 # 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?
2699 if ( $this->isCssJsSubpage ||
$this->mTitle
->isCssOrJsPage() ) { #TODO: kill all special case handling for CSS/JS content!
2700 if( $this->mTitle
->isCssJsSubpage() ) {
2702 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2708 # Used messages to make sure grep find them:
2709 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2711 #FIXME: move this crud into ContentHandler class!
2712 if (preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2713 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2714 $class = "mw-code mw-css";
2715 } elseif (preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2716 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2717 $class = "mw-code mw-js";
2719 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2721 } #FIXME: else $previewtext is undefined!
2723 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2724 $previewHTML = $parserOutput->mText
;
2725 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n"; #FIXME: use content object!
2727 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2729 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2731 $content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
); #FIXME: handle parse errors
2733 # If we're adding a comment, we need to show the
2734 # summary as the headline
2735 if ( $this->section
== "new" && $this->summary
!= "" ) {
2736 $content = $content->addSectionHeader( $this->summary
);
2739 $toparse_orig = $content->serialize( $this->content_format
);
2740 $toparse = $toparse_orig;
2741 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2743 if ( $toparse !== $toparse_orig ) {
2744 #hook changed the text, create new Content object
2745 $content = ContentHandler
::makeContent( $toparse, $this->getTitle(), $this->content_model
, $this->content_format
);
2748 wfRunHooks( 'EditPageGetPreviewContent', array( $this, &$content ) ); # FIXME: document new hook
2750 $parserOptions->enableLimitReport();
2752 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
2753 $parserOutput = $content->getParserOutput( $this->mTitle
, null, $parserOptions );
2755 $previewHTML = $parserOutput->getText();
2756 $this->mParserOutput
= $parserOutput;
2757 $wgOut->addParserOutputNoText( $parserOutput );
2759 if ( count( $parserOutput->getWarnings() ) ) {
2760 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2765 if( $this->isConflict
) {
2766 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2768 $conflict = '<hr />';
2771 $previewhead = "<div class='previewnote'>\n" .
2772 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2773 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2775 $pageLang = $this->mTitle
->getPageLanguage();
2776 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2777 'class' => 'mw-content-'.$pageLang->getDir() );
2778 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2780 wfProfileOut( __METHOD__
);
2781 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2787 function getTemplates() {
2788 if ( $this->preview ||
$this->section
!= '' ) {
2789 $templates = array();
2790 if ( !isset( $this->mParserOutput
) ) {
2793 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
2794 foreach( array_keys( $template ) as $dbk ) {
2795 $templates[] = Title
::makeTitle($ns, $dbk);
2800 return $this->mTitle
->getTemplateLinksFrom();
2805 * Shows a bulletin board style toolbar for common editing functions.
2806 * It can be disabled in the user preferences.
2807 * The necessary JavaScript code can be found in skins/common/edit.js.
2811 static function getEditToolbar() {
2812 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2813 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2815 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2818 * $toolarray is an array of arrays each of which includes the
2819 * filename of the button image (without path), the opening
2820 * tag, the closing tag, optionally a sample text that is
2821 * inserted between the two when no selection is highlighted
2822 * and. The tip text is shown when the user moves the mouse
2825 * Also here: accesskeys (key), which are not used yet until
2826 * someone can figure out a way to make them work in
2827 * IE. However, we should make sure these keys are not defined
2832 'image' => $wgLang->getImageFile( 'button-bold' ),
2833 'id' => 'mw-editbutton-bold',
2835 'close' => '\'\'\'',
2836 'sample' => wfMsg( 'bold_sample' ),
2837 'tip' => wfMsg( 'bold_tip' ),
2841 'image' => $wgLang->getImageFile( 'button-italic' ),
2842 'id' => 'mw-editbutton-italic',
2845 'sample' => wfMsg( 'italic_sample' ),
2846 'tip' => wfMsg( 'italic_tip' ),
2850 'image' => $wgLang->getImageFile( 'button-link' ),
2851 'id' => 'mw-editbutton-link',
2854 'sample' => wfMsg( 'link_sample' ),
2855 'tip' => wfMsg( 'link_tip' ),
2859 'image' => $wgLang->getImageFile( 'button-extlink' ),
2860 'id' => 'mw-editbutton-extlink',
2863 'sample' => wfMsg( 'extlink_sample' ),
2864 'tip' => wfMsg( 'extlink_tip' ),
2868 'image' => $wgLang->getImageFile( 'button-headline' ),
2869 'id' => 'mw-editbutton-headline',
2872 'sample' => wfMsg( 'headline_sample' ),
2873 'tip' => wfMsg( 'headline_tip' ),
2876 $imagesAvailable ?
array(
2877 'image' => $wgLang->getImageFile( 'button-image' ),
2878 'id' => 'mw-editbutton-image',
2879 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2881 'sample' => wfMsg( 'image_sample' ),
2882 'tip' => wfMsg( 'image_tip' ),
2885 $imagesAvailable ?
array(
2886 'image' => $wgLang->getImageFile( 'button-media' ),
2887 'id' => 'mw-editbutton-media',
2888 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2890 'sample' => wfMsg( 'media_sample' ),
2891 'tip' => wfMsg( 'media_tip' ),
2895 'image' => $wgLang->getImageFile( 'button-math' ),
2896 'id' => 'mw-editbutton-math',
2898 'close' => "</math>",
2899 'sample' => wfMsg( 'math_sample' ),
2900 'tip' => wfMsg( 'math_tip' ),
2904 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2905 'id' => 'mw-editbutton-nowiki',
2906 'open' => "<nowiki>",
2907 'close' => "</nowiki>",
2908 'sample' => wfMsg( 'nowiki_sample' ),
2909 'tip' => wfMsg( 'nowiki_tip' ),
2913 'image' => $wgLang->getImageFile( 'button-sig' ),
2914 'id' => 'mw-editbutton-signature',
2918 'tip' => wfMsg( 'sig_tip' ),
2922 'image' => $wgLang->getImageFile( 'button-hr' ),
2923 'id' => 'mw-editbutton-hr',
2924 'open' => "\n----\n",
2927 'tip' => wfMsg( 'hr_tip' ),
2932 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
2933 foreach ( $toolarray as $tool ) {
2939 $image = $wgStylePath . '/common/images/' . $tool['image'],
2940 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2941 // Older browsers show a "speedtip" type message only for ALT.
2942 // Ideally these should be different, realistically they
2943 // probably don't need to be.
2944 $tip = $tool['tip'],
2945 $open = $tool['open'],
2946 $close = $tool['close'],
2947 $sample = $tool['sample'],
2948 $cssId = $tool['id'],
2951 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2954 // This used to be called on DOMReady from mediawiki.action.edit, which
2955 // ended up causing race conditions with the setup code above.
2957 "// Create button bar\n" .
2958 "$(function() { mw.toolbar.init(); } );\n";
2961 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2963 $toolbar = '<div id="toolbar"></div>';
2965 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2971 * Returns an array of html code of the following checkboxes:
2974 * @param $tabindex Current tabindex
2975 * @param $checked Array of checkbox => bool, where bool indicates the checked
2976 * status of the checkbox
2980 public function getCheckboxes( &$tabindex, $checked ) {
2983 $checkboxes = array();
2985 // don't show the minor edit checkbox if it's a new page or section
2986 if ( !$this->isNew
) {
2987 $checkboxes['minor'] = '';
2988 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2989 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2991 'tabindex' => ++
$tabindex,
2992 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2993 'id' => 'wpMinoredit',
2995 $checkboxes['minor'] =
2996 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2997 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2998 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2999 ">{$minorLabel}</label>";
3003 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
3004 $checkboxes['watch'] = '';
3005 if ( $wgUser->isLoggedIn() ) {
3007 'tabindex' => ++
$tabindex,
3008 'accesskey' => wfMsg( 'accesskey-watch' ),
3009 'id' => 'wpWatchthis',
3011 $checkboxes['watch'] =
3012 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3013 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3014 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3015 ">{$watchLabel}</label>";
3017 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3022 * Returns an array of html code of the following buttons:
3023 * save, diff, preview and live
3025 * @param $tabindex Current tabindex
3029 public function getEditButtons( &$tabindex ) {
3036 'tabindex' => ++
$tabindex,
3037 'value' => wfMsg( 'savearticle' ),
3038 'accesskey' => wfMsg( 'accesskey-save' ),
3039 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
3041 $buttons['save'] = Xml
::element('input', $temp, '');
3043 ++
$tabindex; // use the same for preview and live preview
3045 'id' => 'wpPreview',
3046 'name' => 'wpPreview',
3048 'tabindex' => $tabindex,
3049 'value' => wfMsg( 'showpreview' ),
3050 'accesskey' => wfMsg( 'accesskey-preview' ),
3051 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
3053 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3054 $buttons['live'] = '';
3060 'tabindex' => ++
$tabindex,
3061 'value' => wfMsg( 'showdiff' ),
3062 'accesskey' => wfMsg( 'accesskey-diff' ),
3063 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
3065 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3067 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3072 * Output preview text only. This can be sucked into the edit page
3073 * via JavaScript, and saves the server time rendering the skin as
3074 * well as theoretically being more robust on the client (doesn't
3075 * disturb the edit box's undo history, won't eat your text on
3078 * @todo This doesn't include category or interlanguage links.
3079 * Would need to enhance it a bit, <s>maybe wrap them in XML
3080 * or something...</s> that might also require more skin
3081 * initialization, so check whether that's a problem.
3083 function livePreview() {
3086 header( 'Content-type: text/xml; charset=utf-8' );
3087 header( 'Cache-control: no-cache' );
3089 $previewText = $this->getPreviewText();
3090 #$categories = $skin->getCategoryLinks();
3093 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3094 Xml
::tags( 'livepreview', null,
3095 Xml
::element( 'preview', null, $previewText )
3096 #. Xml::element( 'category', null, $categories )
3102 * Call the stock "user is blocked" page
3104 * @deprecated in 1.19; throw an exception directly instead
3106 function blockedPage() {
3107 wfDeprecated( __METHOD__
, '1.19' );
3110 throw new UserBlockedError( $wgUser->mBlock
);
3114 * Produce the stock "please login to edit pages" page
3116 * @deprecated in 1.19; throw an exception directly instead
3118 function userNotLoggedInPage() {
3119 wfDeprecated( __METHOD__
, '1.19' );
3120 throw new PermissionsError( 'edit' );
3124 * Show an error page saying to the user that he has insufficient permissions
3125 * to create a new page
3127 * @deprecated in 1.19; throw an exception directly instead
3129 function noCreatePermission() {
3130 wfDeprecated( __METHOD__
, '1.19' );
3131 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3132 throw new PermissionsError( $permission );
3136 * Creates a basic error page which informs the user that
3137 * they have attempted to edit a nonexistent section.
3139 function noSuchSectionPage() {
3142 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3144 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
3145 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3146 $wgOut->addHTML( $res );
3148 $wgOut->returnToMain( false, $this->mTitle
);
3152 * Produce the stock "your edit contains spam" page
3154 * @param $match Text which triggered one or more filters
3155 * @deprecated since 1.17 Use method spamPageWithContent() instead
3157 static function spamPage( $match = false ) {
3158 wfDeprecated( __METHOD__
, '1.17' );
3160 global $wgOut, $wgTitle;
3162 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3164 $wgOut->addHTML( '<div id="spamprotected">' );
3165 $wgOut->addWikiMsg( 'spamprotectiontext' );
3167 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3169 $wgOut->addHTML( '</div>' );
3171 $wgOut->returnToMain( false, $wgTitle );
3175 * Show "your edit contains spam" page with your diff and text
3177 * @param $match Text which triggered one or more filters
3179 public function spamPageWithContent( $match = false ) {
3181 $this->textbox2
= $this->textbox1
;
3183 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3185 $wgOut->addHTML( '<div id="spamprotected">' );
3186 $wgOut->addWikiMsg( 'spamprotectiontext' );
3188 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3190 $wgOut->addHTML( '</div>' );
3192 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3194 $handler = ContentHandler
::getForTitle( $this->getTitle() );
3195 $de = $handler->getDifferenceEngine( $this->mArticle
->getContext() );
3197 $content2 = ContentHandler
::makeContent( $this->textbox2
, $this->getTitle(), $this->content_model
, $this->content_format
); #FIXME: handle parse errors
3198 $de->setContent( $this->getCurrentContent(), $content2 );
3200 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
3202 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3203 $this->showTextbox2();
3205 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3209 * Format an anchor fragment as it would appear for a given section name
3210 * @param $text String
3214 function sectionAnchor( $text ) {
3216 return $wgParser->guessSectionNameFromWikiText( $text );
3220 * Check if the browser is on a blacklist of user-agents known to
3221 * mangle UTF-8 data on form submission. Returns true if Unicode
3222 * should make it through, false if it's known to be a problem.
3226 function checkUnicodeCompliantBrowser() {
3227 global $wgBrowserBlackList;
3228 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
3229 // No User-Agent header sent? Trust it by default...
3232 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
3233 foreach ( $wgBrowserBlackList as $browser ) {
3234 if ( preg_match($browser, $currentbrowser) ) {
3242 * Filter an input field through a Unicode de-armoring process if it
3243 * came from an old browser with known broken Unicode editing issues.
3245 * @param $request WebRequest
3246 * @param $field String
3250 function safeUnicodeInput( $request, $field ) {
3251 $text = rtrim( $request->getText( $field ) );
3252 return $request->getBool( 'safemode' )
3253 ?
$this->unmakesafe( $text )
3258 * @param $request WebRequest
3259 * @param $text string
3262 function safeUnicodeText( $request, $text ) {
3263 $text = rtrim( $text );
3264 return $request->getBool( 'safemode' )
3265 ?
$this->unmakesafe( $text )
3270 * Filter an output field through a Unicode armoring process if it is
3271 * going to an old browser with known broken Unicode editing issues.
3273 * @param $text String
3277 function safeUnicodeOutput( $text ) {
3279 $codedText = $wgContLang->recodeForEdit( $text );
3280 return $this->checkUnicodeCompliantBrowser()
3282 : $this->makesafe( $codedText );
3286 * A number of web browsers are known to corrupt non-ASCII characters
3287 * in a UTF-8 text editing environment. To protect against this,
3288 * detected browsers will be served an armored version of the text,
3289 * with non-ASCII chars converted to numeric HTML character references.
3291 * Preexisting such character references will have a 0 added to them
3292 * to ensure that round-trips do not alter the original data.
3294 * @param $invalue String
3298 function makesafe( $invalue ) {
3299 // Armor existing references for reversability.
3300 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3305 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3306 $bytevalue = ord( $invalue[$i] );
3307 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
3308 $result .= chr( $bytevalue );
3310 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
3311 $working = $working << 6;
3312 $working +
= ($bytevalue & 0x3F);
3314 if ( $bytesleft <= 0 ) {
3315 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3317 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
3318 $working = $bytevalue & 0x1F;
3320 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
3321 $working = $bytevalue & 0x0F;
3323 } else { //1111 0xxx
3324 $working = $bytevalue & 0x07;
3332 * Reverse the previously applied transliteration of non-ASCII characters
3333 * back to UTF-8. Used to protect data from corruption by broken web browsers
3334 * as listed in $wgBrowserBlackList.
3336 * @param $invalue String
3340 function unmakesafe( $invalue ) {
3342 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3343 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+
3] != '0' ) ) {
3347 $hexstring .= $invalue[$i];
3349 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3351 // Do some sanity checks. These aren't needed for reversability,
3352 // but should help keep the breakage down if the editor
3353 // breaks one of the entities whilst editing.
3354 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
3355 $codepoint = hexdec($hexstring);
3356 $result .= codepointToUtf8( $codepoint );
3358 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3361 $result .= substr( $invalue, $i, 1 );
3364 // reverse the transform that we made for reversability reasons.
3365 return strtr( $result, array( "�" => "&#x" ) );