3 * Contains the EditPage class
8 * The edit page/HTML interface (split from Article)
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
13 * EditPage cares about two distinct titles:
14 * $this->mContextTitle is the page that forms submit to, links point to,
15 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
16 * page in the database that is actually being edited. These are
17 * usually the same, but they are now allowed to be different.
19 * Surgeon General's Warning: prolonged exposure to this class is known to cause
20 * headaches, which may be fatal.
25 * Status: Article successfully updated
27 const AS_SUCCESS_UPDATE
= 200;
30 * Status: Article successfully created
32 const AS_SUCCESS_NEW_ARTICLE
= 201;
35 * Status: Article update aborted by a hook function
37 const AS_HOOK_ERROR
= 210;
40 * Status: The filter function set in $wgFilterCallback returned true (= block it)
42 const AS_FILTERING
= 211;
45 * Status: A hook function returned an error
47 const AS_HOOK_ERROR_EXPECTED
= 212;
50 * Status: User is blocked from editting this page
52 const AS_BLOCKED_PAGE_FOR_USER
= 215;
55 * Status: Content too big (> $wgMaxArticleSize)
57 const AS_CONTENT_TOO_BIG
= 216;
60 * Status: User cannot edit? (not used)
62 const AS_USER_CANNOT_EDIT
= 217;
65 * Status: this anonymous user is not allowed to edit this page
67 const AS_READ_ONLY_PAGE_ANON
= 218;
70 * Status: this logged in user is not allowed to edit this page
72 const AS_READ_ONLY_PAGE_LOGGED
= 219;
75 * Status: wiki is in readonly mode (wfReadOnly() == true)
77 const AS_READ_ONLY_PAGE
= 220;
80 * Status: rate limiter for action 'edit' was tripped
82 const AS_RATE_LIMITED
= 221;
85 * Status: article was deleted while editting and param wpRecreate == false or form
88 const AS_ARTICLE_WAS_DELETED
= 222;
91 * Status: user tried to create this page, but is not allowed to do that
92 * ( Title->usercan('create') == false )
94 const AS_NO_CREATE_PERMISSION
= 223;
97 * Status: user tried to create a blank page
99 const AS_BLANK_ARTICLE
= 224;
102 * Status: (non-resolvable) edit conflict
104 const AS_CONFLICT_DETECTED
= 225;
107 * Status: no edit summary given and the user has forceeditsummary set and the user is not
108 * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
110 const AS_SUMMARY_NEEDED
= 226;
113 * Status: user tried to create a new section without content
115 const AS_TEXTBOX_EMPTY
= 228;
118 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
120 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
128 * Status: WikiPage::doEdit() was unsuccessfull
133 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
135 const AS_SPAM_ERROR
= 232;
138 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
140 const AS_IMAGE_REDIRECT_ANON
= 233;
143 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
145 const AS_IMAGE_REDIRECT_LOGGED
= 234;
148 * Status: can't parse content
150 const AS_PARSE_ERROR
= 240;
153 * HTML id and name for the beginning of the edit form.
155 const EDITFORM_ID
= 'editform';
166 private $mContextTitle = null;
167 var $action = 'submit';
168 var $isConflict = false;
169 var $isCssJsSubpage = false;
170 var $isCssSubpage = false;
171 var $isJsSubpage = false;
172 var $isWrongCaseCssJsPage = false;
173 var $isNew = false; // new page or new section
174 var $deletedSinceEdit;
178 var $mTokenOk = false;
179 var $mTokenOkExceptSuffix = false;
180 var $mTriedSave = false;
181 var $incompleteForm = false;
183 var $kblength = false;
184 var $missingComment = false;
185 var $missingSummary = false;
186 var $allowBlankSummary = false;
189 #var $mPreviewTemplates;
197 * Has a summary been preset using GET parameter &summary= ?
200 var $hasPresetSummary = false;
202 var $mBaseRevision = false;
203 var $mShowSummaryField = true;
206 var $save = false, $preview = false, $diff = false;
207 var $minoredit = false, $watchthis = false, $recreate = false;
208 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
209 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
210 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
211 var $content_model = null, $content_format = null;
213 # Placeholders for text injection by hooks (must be HTML)
214 # extensions should take care to _append_ to the present value
215 public $editFormPageTop = ''; // Before even the preview
216 public $editFormTextTop = '';
217 public $editFormTextBeforeContent = '';
218 public $editFormTextAfterWarn = '';
219 public $editFormTextAfterTools = '';
220 public $editFormTextBottom = '';
221 public $editFormTextAfterContent = '';
222 public $previewTextAfterContent = '';
223 public $mPreloadContent = null;
225 /* $didSave should be set to true whenever an article was succesfully altered. */
226 public $didSave = false;
227 public $undidRev = 0;
229 public $suppressIntro = false;
232 * @param $article Article
234 public function __construct( Article
$article ) {
235 $this->mArticle
= $article;
236 $this->mTitle
= $article->getTitle();
238 $this->content_model
= $this->mTitle
->getContentModelName();
240 $handler = ContentHandler
::getForModelName( $this->content_model
);
241 $this->content_format
= $handler->getDefaultFormat(); #NOTE: should be overridden by format of actual revision
247 public function getArticle() {
248 return $this->mArticle
;
255 public function getTitle() {
256 return $this->mTitle
;
260 * Set the context Title object
262 * @param $title Title object or null
264 public function setContextTitle( $title ) {
265 $this->mContextTitle
= $title;
269 * Get the context title object.
270 * If not set, $wgTitle will be returned. This behavior might changed in
271 * the future to return $this->mTitle instead.
273 * @return Title object
275 public function getContextTitle() {
276 if ( is_null( $this->mContextTitle
) ) {
280 return $this->mContextTitle
;
289 * This is the function that gets called for "action=edit". It
290 * sets up various member variables, then passes execution to
291 * another function, usually showEditForm()
293 * The edit form is self-submitting, so that when things like
294 * preview and edit conflicts occur, we get the same form back
295 * with the extra stuff added. Only when the final submission
296 * is made and all is well do we actually save and redirect to
297 * the newly-edited page.
300 global $wgOut, $wgRequest, $wgUser;
301 // Allow extensions to modify/prevent this form or submission
302 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
306 wfProfileIn( __METHOD__
);
307 wfDebug( __METHOD__
. ": enter\n" );
309 // If they used redlink=1 and the page exists, redirect to the main article
310 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
311 $wgOut->redirect( $this->mTitle
->getFullURL() );
312 wfProfileOut( __METHOD__
);
316 $this->importFormData( $wgRequest );
317 $this->firsttime
= false;
320 $this->livePreview();
321 wfProfileOut( __METHOD__
);
325 if ( wfReadOnly() && $this->save
) {
328 $this->preview
= true;
332 $this->formtype
= 'save';
333 } elseif ( $this->preview
) {
334 $this->formtype
= 'preview';
335 } elseif ( $this->diff
) {
336 $this->formtype
= 'diff';
337 } else { # First time through
338 $this->firsttime
= true;
339 if ( $this->previewOnOpen() ) {
340 $this->formtype
= 'preview';
342 $this->formtype
= 'initial';
346 $permErrors = $this->getEditPermissionErrors();
348 wfDebug( __METHOD__
. ": User can't edit\n" );
349 // Auto-block user's IP if the account was "hard" blocked
350 $wgUser->spreadAnyEditBlock();
352 $this->displayPermissionsError( $permErrors );
354 wfProfileOut( __METHOD__
);
358 wfProfileIn( __METHOD__
. "-business-end" );
360 $this->isConflict
= false;
361 // css / js subpages of user pages get a special treatment
362 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
363 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
364 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
365 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
366 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
368 # Show applicable editing introductions
369 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
373 # Attempt submission here. This will check for edit conflicts,
374 # and redundantly check for locked database, blocked IPs, etc.
375 # that edit() already checked just in case someone tries to sneak
376 # in the back door with a hand-edited submission URL.
378 if ( 'save' == $this->formtype
) {
379 if ( !$this->attemptSave() ) {
380 wfProfileOut( __METHOD__
. "-business-end" );
381 wfProfileOut( __METHOD__
);
386 # First time through: get contents, set time for conflict
388 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
389 if ( $this->initialiseForm() === false ) {
390 $this->noSuchSectionPage();
391 wfProfileOut( __METHOD__
. "-business-end" );
392 wfProfileOut( __METHOD__
);
395 if ( !$this->mTitle
->getArticleID() )
396 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
398 wfRunHooks( 'EditFormInitialText', array( $this ) );
401 $this->showEditForm();
402 wfProfileOut( __METHOD__
. "-business-end" );
403 wfProfileOut( __METHOD__
);
409 protected function getEditPermissionErrors() {
411 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
412 # Can this title be created?
413 if ( !$this->mTitle
->exists() ) {
414 $permErrors = array_merge( $permErrors,
415 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
417 # Ignore some permissions errors when a user is just previewing/viewing diffs
419 foreach ( $permErrors as $error ) {
420 if ( ( $this->preview ||
$this->diff
) &&
421 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
426 $permErrors = wfArrayDiff2( $permErrors, $remove );
431 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
432 * but with the following differences:
433 * - If redlink=1, the user will be redirected to the page
434 * - If there is content to display or the error occurs while either saving,
435 * previewing or showing the difference, it will be a
436 * "View source for ..." page displaying the source code after the error message.
439 * @param $permErrors Array of permissions errors, as returned by
440 * Title::getUserPermissionsErrors().
442 protected function displayPermissionsError( array $permErrors ) {
443 global $wgRequest, $wgOut;
445 if ( $wgRequest->getBool( 'redlink' ) ) {
446 // The edit page was reached via a red link.
447 // Redirect to the article page and let them click the edit tab if
448 // they really want a permission error.
449 $wgOut->redirect( $this->mTitle
->getFullUrl() );
453 $content = $this->getContentObject();
455 # Use the normal message if there's nothing to display
456 if ( $this->firsttime
&& $content->isEmpty() ) {
457 $action = $this->mTitle
->exists() ?
'edit' :
458 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
459 throw new PermissionsError( $action, $permErrors );
462 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
463 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
464 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
465 $wgOut->addHTML( "<hr />\n" );
467 # If the user made changes, preserve them when showing the markup
468 # (This happens when a user is blocked during edit, for instance)
469 if ( !$this->firsttime
) {
470 $text = $this->textbox1
;
471 $wgOut->addWikiMsg( 'viewyourtext' );
473 $text = $content->serialize( $this->content_format
);
474 $wgOut->addWikiMsg( 'viewsourcetext' );
477 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
479 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
480 Linker
::formatTemplates( $this->getTemplates() ) ) );
482 if ( $this->mTitle
->exists() ) {
483 $wgOut->returnToMain( null, $this->mTitle
);
488 * Show a read-only error
489 * Parameters are the same as OutputPage:readOnlyPage()
490 * Redirect to the article page if redlink=1
491 * @deprecated in 1.19; use displayPermissionsError() instead
493 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
494 wfDeprecated( __METHOD__
, '1.19' );
496 global $wgRequest, $wgOut;
497 if ( $wgRequest->getBool( 'redlink' ) ) {
498 // The edit page was reached via a red link.
499 // Redirect to the article page and let them click the edit tab if
500 // they really want a permission error.
501 $wgOut->redirect( $this->mTitle
->getFullUrl() );
503 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
508 * Should we show a preview when the edit form is first shown?
512 protected function previewOnOpen() {
513 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
514 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
515 // Explicit override from request
517 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
518 // Explicit override from request
520 } elseif ( $this->section
== 'new' ) {
521 // Nothing *to* preview for new sections
523 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
524 // Standard preference behaviour
526 } elseif ( !$this->mTitle
->exists() &&
527 isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] ) &&
528 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
530 // Categories are special
538 * Checks whether the user entered a skin name in uppercase,
539 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
543 protected function isWrongCaseCssJsPage() {
544 if ( $this->mTitle
->isCssJsSubpage() ) {
545 $name = $this->mTitle
->getSkinFromCssJsSubpage();
546 $skins = array_merge(
547 array_keys( Skin
::getSkinNames() ),
550 return !in_array( $name, $skins )
551 && in_array( strtolower( $name ), $skins );
558 * Does this EditPage class support section editing?
559 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
563 protected function isSectionEditSupported() {
568 * This function collects the form data and uses it to populate various member variables.
569 * @param $request WebRequest
571 function importFormData( &$request ) {
572 global $wgLang, $wgUser;
574 wfProfileIn( __METHOD__
);
576 # Section edit can come from either the form or a link
577 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
579 if ( $request->wasPosted() ) {
580 # These fields need to be checked for encoding.
581 # Also remove trailing whitespace, but don't remove _initial_
582 # whitespace from the text boxes. This may be significant formatting.
583 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
584 if ( !$request->getCheck( 'wpTextbox2' ) ) {
585 // Skip this if wpTextbox2 has input, it indicates that we came
586 // from a conflict page with raw page text, not a custom form
587 // modified by subclasses
588 wfProfileIn( get_class( $this ) . "::importContentFormData" );
589 $textbox1 = $this->importContentFormData( $request );
590 if ( isset( $textbox1 ) )
591 $this->textbox1
= $textbox1;
592 wfProfileOut( get_class( $this ) . "::importContentFormData" );
595 # Truncate for whole multibyte characters. +5 bytes for ellipsis
596 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
598 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
599 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
601 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
603 # Treat sectiontitle the same way as summary.
604 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
605 # currently doing double duty as both edit summary and section title. Right now this
606 # is just to allow API edits to work around this limitation, but this should be
607 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
608 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 250 );
609 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
611 $this->edittime
= $request->getVal( 'wpEdittime' );
612 $this->starttime
= $request->getVal( 'wpStarttime' );
614 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
616 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
617 // wpTextbox1 field is missing, possibly due to being "too big"
618 // according to some filter rules such as Suhosin's setting for
619 // suhosin.request.max_value_length (d'oh)
620 $this->incompleteForm
= true;
622 // edittime should be one of our last fields; if it's missing,
623 // the submission probably broke somewhere in the middle.
624 $this->incompleteForm
= is_null( $this->edittime
);
626 if ( $this->incompleteForm
) {
627 # If the form is incomplete, force to preview.
628 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
629 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
630 $this->preview
= true;
632 /* Fallback for live preview */
633 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
634 $this->diff
= $request->getCheck( 'wpDiff' );
636 // Remember whether a save was requested, so we can indicate
637 // if we forced preview due to session failure.
638 $this->mTriedSave
= !$this->preview
;
640 if ( $this->tokenOk( $request ) ) {
641 # Some browsers will not report any submit button
642 # if the user hits enter in the comment box.
643 # The unmarked state will be assumed to be a save,
644 # if the form seems otherwise complete.
645 wfDebug( __METHOD__
. ": Passed token check.\n" );
646 } elseif ( $this->diff
) {
647 # Failed token check, but only requested "Show Changes".
648 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
650 # Page might be a hack attempt posted from
651 # an external site. Preview instead of saving.
652 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
653 $this->preview
= true;
656 $this->save
= !$this->preview
&& !$this->diff
;
657 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
658 $this->edittime
= null;
661 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
662 $this->starttime
= null;
665 $this->recreate
= $request->getCheck( 'wpRecreate' );
667 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
668 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
670 # Don't force edit summaries when a user is editing their own user or talk page
671 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
672 $this->mTitle
->getText() == $wgUser->getName() )
674 $this->allowBlankSummary
= true;
676 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary' );
679 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
681 # Not a posted form? Start with nothing.
682 wfDebug( __METHOD__
. ": Not a posted form.\n" );
683 $this->textbox1
= ''; #FIXME: track content object
685 $this->sectiontitle
= '';
686 $this->edittime
= '';
687 $this->starttime
= wfTimestampNow();
689 $this->preview
= false;
692 $this->minoredit
= false;
693 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
694 $this->recreate
= false;
696 // When creating a new section, we can preload a section title by passing it as the
697 // preloadtitle parameter in the URL (Bug 13100)
698 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
699 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
700 // Once wpSummary isn't being use for setting section titles, we should delete this.
701 $this->summary
= $request->getVal( 'preloadtitle' );
703 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
704 $this->summary
= $request->getText( 'summary' );
705 if ( $this->summary
!== '' ) {
706 $this->hasPresetSummary
= true;
710 if ( $request->getVal( 'minor' ) ) {
711 $this->minoredit
= true;
715 $this->oldid
= $request->getInt( 'oldid' );
717 $this->bot
= $request->getBool( 'bot', true );
718 $this->nosummary
= $request->getBool( 'nosummary' );
720 $content_handler = ContentHandler
::getForTitle( $this->mTitle
);
721 $this->content_model
= $request->getText( 'model', $content_handler->getModelName() ); #may be overridden by revision
722 $this->content_format
= $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
724 #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
725 #TODO: check if the desired content model supports the given content format!
727 $this->live
= $request->getCheck( 'live' );
728 $this->editintro
= $request->getText( 'editintro',
729 // Custom edit intro for new sections
730 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
732 // Allow extensions to modify form data
733 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
735 wfProfileOut( __METHOD__
);
739 * Subpage overridable method for extracting the page content data from the
740 * posted form to be placed in $this->textbox1, if using customized input
741 * this method should be overrided and return the page text that will be used
742 * for saving, preview parsing and so on...
744 * @param $request WebRequest
746 protected function importContentFormData( &$request ) {
747 return; // Don't do anything, EditPage already extracted wpTextbox1
751 * Initialise form fields in the object
752 * Called on the first invocation, e.g. when a user clicks an edit link
753 * @return bool -- if the requested section is valid
755 function initialiseForm() {
757 $this->edittime
= $this->mArticle
->getTimestamp();
759 $content = $this->getContentObject( false ); #TODO: track content object?!
760 $this->textbox1
= $content->serialize( $this->content_format
);
762 // activate checkboxes if user wants them to be always active
763 # Sort out the "watch" checkbox
764 if ( $wgUser->getOption( 'watchdefault' ) ) {
766 $this->watchthis
= true;
767 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
769 $this->watchthis
= true;
770 } elseif ( $this->mTitle
->userIsWatching() ) {
772 $this->watchthis
= true;
774 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
775 $this->minoredit
= true;
777 if ( $this->textbox1
=== false ) {
785 * Fetch initial editing page content.
787 * @param $def_text string
788 * @return mixed string on success, $def_text for invalid sections
790 * @deprecated since 1.WD
792 function getContent( $def_text = false ) { #FIXME: deprecated, replace usage!
793 wfDeprecated( __METHOD__
, '1.WD' );
795 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
796 $def_content = ContentHandler
::makeContent( $def_text, $this->getTitle() );
798 $def_content = false;
801 $content = $this->getContentObject( $def_content );
803 return $content->serialize( $this->content_format
); #XXX: really use serialized form? use ContentHandler::getContentText() instead?
806 private function getContentObject( $def_content = null ) { #FIXME: use this!
807 global $wgOut, $wgRequest;
809 wfProfileIn( __METHOD__
);
813 // For message page not locally set, use the i18n message.
814 // For other non-existent articles, use preload text if any.
815 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
816 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
817 # If this is a system message, get the default text.
818 $msg = $this->mTitle
->getDefaultMessageText();
820 $content = ContentHandler
::makeContent( $msg, $this->mTitle
);
822 if ( $content === false ) {
823 # If requested, preload some text.
824 $preload = $wgRequest->getVal( 'preload',
825 // Custom preload text for new sections
826 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
828 $content = $this->getPreloadedContent( $preload );
830 // For existing pages, get text based on "undo" or section parameters.
832 if ( $this->section
!= '' ) {
833 // Get section edit text (returns $def_text for invalid sections)
834 $orig = $this->getOriginalContent();
835 $content = $orig ?
$orig->getSection( $this->section
) : null;
837 if ( !$content ) $content = $def_content;
839 $undoafter = $wgRequest->getInt( 'undoafter' );
840 $undo = $wgRequest->getInt( 'undo' );
842 if ( $undo > 0 && $undoafter > 0 ) {
843 if ( $undo < $undoafter ) {
844 # If they got undoafter and undo round the wrong way, switch them
845 list( $undo, $undoafter ) = array( $undoafter, $undo );
848 $undorev = Revision
::newFromId( $undo );
849 $oldrev = Revision
::newFromId( $undoafter );
851 # Sanity check, make sure it's the right page,
852 # the revisions exist and they were not deleted.
853 # Otherwise, $content will be left as-is.
854 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
855 $undorev->getPage() == $oldrev->getPage() &&
856 $undorev->getPage() == $this->mTitle
->getArticleID() &&
857 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
858 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
860 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
862 if ( $content === false ) {
863 # Warn the user that something went wrong
864 $undoMsg = 'failure';
866 # Inform the user of our success and set an automatic edit summary
867 $undoMsg = 'success';
869 # If we just undid one rev, use an autosummary
870 $firstrev = $oldrev->getNext();
871 if ( $firstrev->getId() == $undo ) {
872 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
873 if ( $this->summary
=== '' ) {
874 $this->summary
= $undoSummary;
876 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
878 $this->undidRev
= $undo;
880 $this->formtype
= 'diff';
883 // Failed basic sanity checks.
884 // Older revisions may have been removed since the link
885 // was created, or we may simply have got bogus input.
889 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
890 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
891 wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
894 if ( $content === false ) {
895 $content = $this->getOriginalContent();
900 wfProfileOut( __METHOD__
);
905 * Get the content of the wanted revision, without section extraction.
907 * The result of this function can be used to compare user's input with
908 * section replaced in its context (using WikiPage::replaceSection())
909 * to the original text of the edit.
911 * This difers from Article::getContent() that when a missing revision is
912 * encountered the result will be an empty string and not the
913 * 'missing-article' message.
918 private function getOriginalContent() {
919 if ( $this->section
== 'new' ) {
920 return $this->getCurrentContent();
922 $revision = $this->mArticle
->getRevisionFetched();
923 if ( $revision === null ) {
924 if ( !$this->content_model
) $this->content_model
= $this->getTitle()->getContentModelName();
925 $handler = ContentHandler
::getForModelName( $this->content_model
);
927 return $handler->makeEmptyContent();
929 $content = $revision->getContent();
934 * Get the current content of the page. This is basically similar to
935 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
936 * content object is returned instead of null.
941 private function getCurrentContent() {
942 $rev = $this->mArticle
->getRevision();
943 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
945 if ( $content === false ||
$content === null ) {
946 if ( !$this->content_model
) $this->content_model
= $this->getTitle()->getContentModelName();
947 $handler = ContentHandler
::getForModelName( $this->content_model
);
949 return $handler->makeEmptyContent();
951 #FIXME: nasty side-effect!
952 $this->content_model
= $rev->getContentModelName();
953 $this->content_format
= $rev->getContentFormat();
961 * Use this method before edit() to preload some text into the edit box
963 * @param $text string
964 * @deprecated since 1.WD
966 public function setPreloadedText( $text ) {
967 wfDeprecated( __METHOD__
, "1.WD" );
969 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
971 $this->setPreloadedContent( $content );
975 * Use this method before edit() to preload some content into the edit box
977 * @param $content Content
981 public function setPreloadedContent( Content
$content ) {
982 $this->mPreloadedContent
= $content;
986 * Get the contents to be preloaded into the box, either set by
987 * an earlier setPreloadText() or by loading the given page.
989 * @param $preload String: representing the title to preload from.
993 * @deprecated since 1.WD, use getPreloadedContent() instead
995 protected function getPreloadedText( $preload ) { #NOTE: B/C only, replace usage!
996 wfDeprecated( __METHOD__
, "1.WD" );
998 $content = $this->getPreloadedContent( $preload );
999 $text = $content->serialize( $this->content_format
); #XXX: really use serialized form? use ContentHandler::getContentText() instead?!
1005 * Get the contents to be preloaded into the box, either set by
1006 * an earlier setPreloadText() or by loading the given page.
1008 * @param $preload String: representing the title to preload from.
1014 protected function getPreloadedContent( $preload ) { #@todo: use this!
1017 if ( !empty( $this->mPreloadContent
) ) {
1018 return $this->mPreloadContent
;
1021 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1023 if ( $preload === '' ) {
1024 return $handler->makeEmptyContent();
1027 $title = Title
::newFromText( $preload );
1028 # Check for existence to avoid getting MediaWiki:Noarticletext
1029 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
1030 return $handler->makeEmptyContent();
1033 $page = WikiPage
::factory( $title );
1034 if ( $page->isRedirect() ) {
1035 $title = $page->getRedirectTarget();
1037 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
1038 return $handler->makeEmptyContent();
1040 $page = WikiPage
::factory( $title );
1043 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1044 $content = $page->getContent( Revision
::RAW
);
1046 return $content->preloadTransform( $title, $parserOptions );
1050 * Make sure the form isn't faking a user's credentials.
1052 * @param $request WebRequest
1056 function tokenOk( &$request ) {
1058 $token = $request->getVal( 'wpEditToken' );
1059 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1060 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1061 return $this->mTokenOk
;
1065 * Attempt submission
1066 * @return bool false if output is done, true if the rest of the form should be displayed
1068 function attemptSave() {
1069 global $wgUser, $wgOut;
1071 $resultDetails = false;
1072 # Allow bots to exempt some edits from bot flagging
1073 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1074 $status = $this->internalAttemptSave( $resultDetails, $bot );
1075 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1077 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1078 $this->didSave
= true;
1081 switch ( $status->value
) {
1082 case self
::AS_HOOK_ERROR_EXPECTED
:
1083 case self
::AS_CONTENT_TOO_BIG
:
1084 case self
::AS_ARTICLE_WAS_DELETED
:
1085 case self
::AS_CONFLICT_DETECTED
:
1086 case self
::AS_SUMMARY_NEEDED
:
1087 case self
::AS_TEXTBOX_EMPTY
:
1088 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1092 case self
::AS_HOOK_ERROR
:
1093 case self
::AS_FILTERING
:
1096 case self
::AS_PARSE_ERROR
:
1097 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>');
1098 #FIXME: cause editform to be shown again, not just an error!
1101 case self
::AS_SUCCESS_NEW_ARTICLE
:
1102 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1103 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1104 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1107 case self
::AS_SUCCESS_UPDATE
:
1109 $sectionanchor = $resultDetails['sectionanchor'];
1111 // Give extensions a chance to modify URL query on update
1112 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1114 if ( $resultDetails['redirect'] ) {
1115 if ( $extraQuery == '' ) {
1116 $extraQuery = 'redirect=no';
1118 $extraQuery = 'redirect=no&' . $extraQuery;
1121 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1124 case self
::AS_BLANK_ARTICLE
:
1125 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1128 case self
::AS_SPAM_ERROR
:
1129 $this->spamPageWithContent( $resultDetails['spam'] );
1132 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1133 throw new UserBlockedError( $wgUser->getBlock() );
1135 case self
::AS_IMAGE_REDIRECT_ANON
:
1136 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1137 throw new PermissionsError( 'upload' );
1139 case self
::AS_READ_ONLY_PAGE_ANON
:
1140 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1141 throw new PermissionsError( 'edit' );
1143 case self
::AS_READ_ONLY_PAGE
:
1144 throw new ReadOnlyError
;
1146 case self
::AS_RATE_LIMITED
:
1147 throw new ThrottledError();
1149 case self
::AS_NO_CREATE_PERMISSION
:
1150 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1151 throw new PermissionsError( $permission );
1158 * Attempt submission (no UI)
1163 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1165 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1166 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1167 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1169 function internalAttemptSave( &$result, $bot = false ) {
1170 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
1171 global $wgMaxArticleSize;
1173 $status = Status
::newGood();
1175 wfProfileIn( __METHOD__
);
1176 wfProfileIn( __METHOD__
. '-checks' );
1178 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1179 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1180 $status->fatal( 'hookaborted' );
1181 $status->value
= self
::AS_HOOK_ERROR
;
1182 wfProfileOut( __METHOD__
. '-checks' );
1183 wfProfileOut( __METHOD__
);
1187 # Check image redirect
1188 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1189 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&& #FIXME: use content handler to check for redirect
1190 !$wgUser->isAllowed( 'upload' ) ) {
1191 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1192 $status->setResult( false, $code );
1194 wfProfileOut( __METHOD__
. '-checks' );
1195 wfProfileOut( __METHOD__
);
1201 $match = self
::matchSummarySpamRegex( $this->summary
);
1202 if ( $match === false ) {
1203 $match = self
::matchSpamRegex( $this->textbox1
);
1205 if ( $match !== false ) {
1206 $result['spam'] = $match;
1207 $ip = $wgRequest->getIP();
1208 $pdbk = $this->mTitle
->getPrefixedDBkey();
1209 $match = str_replace( "\n", '', $match );
1210 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1211 $status->fatal( 'spamprotectionmatch', $match );
1212 $status->value
= self
::AS_SPAM_ERROR
;
1213 wfProfileOut( __METHOD__
. '-checks' );
1214 wfProfileOut( __METHOD__
);
1217 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
1218 # Error messages or other handling should be performed by the filter function
1219 $status->setResult( false, self
::AS_FILTERING
);
1220 wfProfileOut( __METHOD__
. '-checks' );
1221 wfProfileOut( __METHOD__
);
1224 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1225 # Error messages etc. could be handled within the hook...
1226 $status->fatal( 'hookaborted' );
1227 $status->value
= self
::AS_HOOK_ERROR
;
1228 wfProfileOut( __METHOD__
. '-checks' );
1229 wfProfileOut( __METHOD__
);
1231 } elseif ( $this->hookError
!= '' ) {
1232 # ...or the hook could be expecting us to produce an error
1233 $status->fatal( 'hookaborted' );
1234 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1235 wfProfileOut( __METHOD__
. '-checks' );
1236 wfProfileOut( __METHOD__
);
1240 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1241 // Auto-block user's IP if the account was "hard" blocked
1242 $wgUser->spreadAnyEditBlock();
1243 # Check block state against master, thus 'false'.
1244 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1245 wfProfileOut( __METHOD__
. '-checks' );
1246 wfProfileOut( __METHOD__
);
1250 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1251 if ( $this->kblength
> $wgMaxArticleSize ) {
1252 // Error will be displayed by showEditForm()
1253 $this->tooBig
= true;
1254 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1255 wfProfileOut( __METHOD__
. '-checks' );
1256 wfProfileOut( __METHOD__
);
1260 if ( !$wgUser->isAllowed( 'edit' ) ) {
1261 if ( $wgUser->isAnon() ) {
1262 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1263 wfProfileOut( __METHOD__
. '-checks' );
1264 wfProfileOut( __METHOD__
);
1267 $status->fatal( 'readonlytext' );
1268 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1269 wfProfileOut( __METHOD__
. '-checks' );
1270 wfProfileOut( __METHOD__
);
1275 if ( wfReadOnly() ) {
1276 $status->fatal( 'readonlytext' );
1277 $status->value
= self
::AS_READ_ONLY_PAGE
;
1278 wfProfileOut( __METHOD__
. '-checks' );
1279 wfProfileOut( __METHOD__
);
1282 if ( $wgUser->pingLimiter() ) {
1283 $status->fatal( 'actionthrottledtext' );
1284 $status->value
= self
::AS_RATE_LIMITED
;
1285 wfProfileOut( __METHOD__
. '-checks' );
1286 wfProfileOut( __METHOD__
);
1290 # If the article has been deleted while editing, don't save it without
1292 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1293 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1294 wfProfileOut( __METHOD__
. '-checks' );
1295 wfProfileOut( __METHOD__
);
1299 wfProfileOut( __METHOD__
. '-checks' );
1301 # If article is new, insert it.
1302 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1303 $new = ( $aid == 0 );
1307 // Late check for create permission, just in case *PARANOIA*
1308 if ( !$this->mTitle
->userCan( 'create' ) ) {
1309 $status->fatal( 'nocreatetext' );
1310 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1311 wfDebug( __METHOD__
. ": no create permission\n" );
1312 wfProfileOut( __METHOD__
);
1316 # Don't save a new article if it's blank.
1317 if ( $this->textbox1
== '' ) {
1318 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1319 wfProfileOut( __METHOD__
);
1323 // Run post-section-merge edit filter
1324 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1325 # Error messages etc. could be handled within the hook...
1326 $status->fatal( 'hookaborted' );
1327 $status->value
= self
::AS_HOOK_ERROR
;
1328 wfProfileOut( __METHOD__
);
1330 } elseif ( $this->hookError
!= '' ) {
1331 # ...or the hook could be expecting us to produce an error
1332 $status->fatal( 'hookaborted' );
1333 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1334 wfProfileOut( __METHOD__
);
1338 $content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
);
1340 $result['sectionanchor'] = '';
1341 if ( $this->section
== 'new' ) {
1342 if ( $this->sectiontitle
!== '' ) {
1343 // Insert the section title above the content.
1344 $content = $content->addSectionHeader( $this->sectiontitle
);
1346 // Jump to the new section
1347 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1349 // If no edit summary was specified, create one automatically from the section
1350 // title and have it link to the new section. Otherwise, respect the summary as
1352 if ( $this->summary
=== '' ) {
1353 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1354 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1356 } elseif ( $this->summary
!== '' ) {
1357 // Insert the section title above the content.
1358 $content = $content->addSectionHeader( $this->sectiontitle
);
1360 // Jump to the new section
1361 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1363 // Create a link to the new section from the edit summary.
1364 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1365 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1369 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1373 # Article exists. Check for edit conflict.
1375 $this->mArticle
->clear(); # Force reload of dates, etc.
1376 $timestamp = $this->mArticle
->getTimestamp();
1378 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1380 if ( $timestamp != $this->edittime
) {
1381 $this->isConflict
= true;
1382 if ( $this->section
== 'new' ) {
1383 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1384 $this->mArticle
->getComment() == $this->summary
) {
1385 // Probably a duplicate submission of a new comment.
1386 // This can happen when squid resends a request after
1387 // a timeout but the first one actually went through.
1388 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1390 // New comment; suppress conflict.
1391 $this->isConflict
= false;
1392 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1394 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1395 # Suppress edit conflict with self, except for section edits where merging is required.
1396 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1397 $this->isConflict
= false;
1401 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1402 // backwards compatibility with old forms/bots).
1403 if ( $this->sectiontitle
!== '' ) {
1404 $sectionTitle = $this->sectiontitle
;
1406 $sectionTitle = $this->summary
;
1409 $textbox_content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
);
1412 if ( $this->isConflict
) {
1413 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1414 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1416 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1417 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1420 if ( is_null( $content ) ) {
1421 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1422 $this->isConflict
= true;
1423 $content = $textbox_content; // do not try to merge here!
1424 } elseif ( $this->isConflict
) {
1426 if ( $this->mergeChangesIntoContent( $textbox_content ) ) {
1427 // Successful merge! Maybe we should tell the user the good news?
1428 $this->isConflict
= false;
1429 $content = $textbox_content;
1430 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1432 $this->section
= '';
1433 #$this->textbox1 = $text; #redundant, nothing to do here?
1434 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1438 if ( $this->isConflict
) {
1439 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1440 wfProfileOut( __METHOD__
);
1444 // Run post-section-merge edit filter
1445 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $content->serialize( $this->content_format
), &$this->hookError
, $this->summary
) )
1446 ||
!wfRunHooks( 'EditFilterMergedContent', array( $this, $content, &$this->hookError
, $this->summary
) ) ) {
1447 # Error messages etc. could be handled within the hook...
1448 $status->fatal( 'hookaborted' );
1449 $status->value
= self
::AS_HOOK_ERROR
;
1450 wfProfileOut( __METHOD__
);
1452 } elseif ( $this->hookError
!= '' ) {
1453 # ...or the hook could be expecting us to produce an error
1454 $status->fatal( 'hookaborted' );
1455 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1456 wfProfileOut( __METHOD__
);
1460 $content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
);
1462 # Handle the user preference to force summaries here, but not for null edits
1463 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1464 && !$content->equals( $this->getOriginalContent() )
1465 && !$content->isRedirect() ) # check if it's not a redirect
1467 if ( md5( $this->summary
) == $this->autoSumm
) {
1468 $this->missingSummary
= true;
1469 $status->fatal( 'missingsummary' );
1470 $status->value
= self
::AS_SUMMARY_NEEDED
;
1471 wfProfileOut( __METHOD__
);
1476 # And a similar thing for new sections
1477 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1478 if ( trim( $this->summary
) == '' ) {
1479 $this->missingSummary
= true;
1480 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1481 $status->value
= self
::AS_SUMMARY_NEEDED
;
1482 wfProfileOut( __METHOD__
);
1488 wfProfileIn( __METHOD__
. '-sectionanchor' );
1489 $sectionanchor = '';
1490 if ( $this->section
== 'new' ) {
1491 if ( $this->textbox1
== '' ) {
1492 $this->missingComment
= true;
1493 $status->fatal( 'missingcommenttext' );
1494 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1495 wfProfileOut( __METHOD__
. '-sectionanchor' );
1496 wfProfileOut( __METHOD__
);
1499 if ( $this->sectiontitle
!== '' ) {
1500 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1501 // If no edit summary was specified, create one automatically from the section
1502 // title and have it link to the new section. Otherwise, respect the summary as
1504 if ( $this->summary
=== '' ) {
1505 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1506 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1508 } elseif ( $this->summary
!== '' ) {
1509 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1510 # This is a new section, so create a link to the new section
1511 # in the revision summary.
1512 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1513 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1515 } elseif ( $this->section
!= '' ) {
1516 # Try to get a section anchor from the section source, redirect to edited section if header found
1517 # XXX: might be better to integrate this into Article::replaceSection
1518 # for duplicate heading checking and maybe parsing
1519 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1520 # we can't deal with anchors, includes, html etc in the header for now,
1521 # headline would need to be parsed to improve this
1522 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1523 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1526 $result['sectionanchor'] = $sectionanchor;
1527 wfProfileOut( __METHOD__
. '-sectionanchor' );
1529 // Save errors may fall down to the edit form, but we've now
1530 // merged the section into full text. Clear the section field
1531 // so that later submission of conflict forms won't try to
1532 // replace that into a duplicated mess.
1533 $this->textbox1
= $content->serialize( $this->content_format
);
1534 $this->section
= '';
1536 $status->value
= self
::AS_SUCCESS_UPDATE
;
1539 // Check for length errors again now that the section is merged in
1540 $this->kblength
= (int)( strlen( $content->serialize( $this->content_format
) ) / 1024 );
1541 if ( $this->kblength
> $wgMaxArticleSize ) {
1542 $this->tooBig
= true;
1543 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1544 wfProfileOut( __METHOD__
);
1548 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1549 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1550 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1551 ( $bot ? EDIT_FORCE_BOT
: 0 );
1553 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags, false, null, $this->content_format
);
1555 if ( $doEditStatus->isOK() ) {
1556 $result['redirect'] = $content->isRedirect();
1557 $this->commitWatch();
1558 wfProfileOut( __METHOD__
);
1561 $this->isConflict
= true;
1562 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1563 wfProfileOut( __METHOD__
);
1564 return $doEditStatus;
1566 } catch (MWContentSerializationException
$ex) {
1567 $status->fatal( 'content-failed-to-parse', $this->content_model
, $this->content_format
, $ex->getMessage() );
1568 $status->value
= self
::AS_PARSE_ERROR
;
1569 wfProfileOut( __METHOD__
);
1575 * Commit the change of watch status
1577 protected function commitWatch() {
1579 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1580 $dbw = wfGetDB( DB_MASTER
);
1581 $dbw->begin( __METHOD__
);
1582 if ( $this->watchthis
) {
1583 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1585 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1587 $dbw->commit( __METHOD__
);
1592 * Check if no edits were made by other users since
1593 * the time a user started editing the page. Limit to
1594 * 50 revisions for the sake of performance.
1597 * @param $edittime string
1601 protected function userWasLastToEdit( $id, $edittime ) {
1602 if ( !$id ) return false;
1603 $dbw = wfGetDB( DB_MASTER
);
1604 $res = $dbw->select( 'revision',
1607 'rev_page' => $this->mTitle
->getArticleID(),
1608 'rev_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $edittime ) )
1611 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1612 foreach ( $res as $row ) {
1613 if ( $row->rev_user
!= $id ) {
1624 * @parma $editText string
1627 * @deprecated since 1.WD, use mergeChangesIntoContent() instead
1629 function mergeChangesInto( &$editText ){
1630 wfDebug( __METHOD__
, "1.WD" );
1632 $editContent = ContentHandler
::makeContent( $editText, $this->getTitle(), $this->content_model
, $this->content_format
);
1634 $ok = $this->mergeChangesIntoContent( $editContent );
1637 $editText = $editContent->serialize( $this->content_format
); #XXX: really serialize?!
1648 * @parma $editText string
1653 private function mergeChangesIntoContent( &$editContent ){
1654 wfProfileIn( __METHOD__
);
1656 $db = wfGetDB( DB_MASTER
);
1658 // This is the revision the editor started from
1659 $baseRevision = $this->getBaseRevision();
1660 if ( is_null( $baseRevision ) ) {
1661 wfProfileOut( __METHOD__
);
1664 $baseContent = $baseRevision->getContent();
1666 // The current state, we want to merge updates into it
1667 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1668 if ( is_null( $currentRevision ) ) {
1669 wfProfileOut( __METHOD__
);
1672 $currentContent = $currentRevision->getContent();
1674 $handler = ContentHandler
::getForModelName( $baseContent->getModelName() );
1676 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1679 $editContent = $result;
1680 wfProfileOut( __METHOD__
);
1683 wfProfileOut( __METHOD__
);
1691 function getBaseRevision() {
1692 if ( !$this->mBaseRevision
) {
1693 $db = wfGetDB( DB_MASTER
);
1694 $baseRevision = Revision
::loadFromTimestamp(
1695 $db, $this->mTitle
, $this->edittime
);
1696 return $this->mBaseRevision
= $baseRevision;
1698 return $this->mBaseRevision
;
1703 * Check given input text against $wgSpamRegex, and return the text of the first match.
1705 * @param $text string
1707 * @return string|bool matching string or false
1709 public static function matchSpamRegex( $text ) {
1710 global $wgSpamRegex;
1711 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1712 $regexes = (array)$wgSpamRegex;
1713 return self
::matchSpamRegexInternal( $text, $regexes );
1717 * Check given input text against $wgSpamRegex, and return the text of the first match.
1719 * @parma $text string
1721 * @return string|bool matching string or false
1723 public static function matchSummarySpamRegex( $text ) {
1724 global $wgSummarySpamRegex;
1725 $regexes = (array)$wgSummarySpamRegex;
1726 return self
::matchSpamRegexInternal( $text, $regexes );
1730 * @param $text string
1731 * @param $regexes array
1732 * @return bool|string
1734 protected static function matchSpamRegexInternal( $text, $regexes ) {
1735 foreach ( $regexes as $regex ) {
1737 if ( preg_match( $regex, $text, $matches ) ) {
1744 function setHeaders() {
1745 global $wgOut, $wgUser;
1747 $wgOut->addModules( 'mediawiki.action.edit' );
1749 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1750 $wgOut->addModules( 'mediawiki.legacy.preview' );
1752 // Bug #19334: textarea jumps when editing articles in IE8
1753 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1755 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1757 # Enabled article-related sidebar, toplinks, etc.
1758 $wgOut->setArticleRelated( true );
1760 $contextTitle = $this->getContextTitle();
1761 if ( $this->isConflict
) {
1762 $msg = 'editconflict';
1763 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1764 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1766 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1767 'editing' : 'creating';
1769 # Use the title defined by DISPLAYTITLE magic word when present
1770 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1771 if ( $displayTitle === false ) {
1772 $displayTitle = $contextTitle->getPrefixedText();
1774 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1778 * Show all applicable editing introductions
1780 protected function showIntro() {
1781 global $wgOut, $wgUser;
1782 if ( $this->suppressIntro
) {
1786 $namespace = $this->mTitle
->getNamespace();
1788 if ( $namespace == NS_MEDIAWIKI
) {
1789 # Show a warning if editing an interface message
1790 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1791 } else if( $namespace == NS_FILE
) {
1792 # Show a hint to shared repo
1793 $file = wfFindFile( $this->mTitle
);
1794 if( $file && !$file->isLocal() ) {
1795 $descUrl = $file->getDescriptionUrl();
1796 # there must be a description url to show a hint to shared repo
1798 if( !$this->mTitle
->exists() ) {
1799 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1800 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1803 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1804 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1811 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1812 # Show log extract when the user is currently blocked
1813 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1814 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1815 $username = $parts[0];
1816 $user = User
::newFromName( $username, false /* allow IP users*/ );
1817 $ip = User
::isIP( $username );
1818 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1819 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1820 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1821 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1822 LogEventsList
::showLogExtract(
1825 $user->getUserPage(),
1829 'showIfEmpty' => false,
1831 'blocked-notice-logextract',
1832 $user->getName() # Support GENDER in notice
1838 # Try to add a custom edit intro, or use the standard one if this is not possible.
1839 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1840 if ( $wgUser->isLoggedIn() ) {
1841 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1843 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1846 # Give a notice if the user is editing a deleted/moved page...
1847 if ( !$this->mTitle
->exists() ) {
1848 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1849 '', array( 'lim' => 10,
1850 'conds' => array( "log_action != 'revision'" ),
1851 'showIfEmpty' => false,
1852 'msgKey' => array( 'recreate-moveddeleted-warn' ) )
1858 * Attempt to show a custom editing introduction, if supplied
1862 protected function showCustomIntro() {
1863 if ( $this->editintro
) {
1864 $title = Title
::newFromText( $this->editintro
);
1865 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1867 // Added using template syntax, to take <noinclude>'s into account.
1868 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1879 * Send the edit form and related headers to $wgOut
1880 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1881 * during form output near the top, for captchas and the like.
1883 function showEditForm( $formCallback = null ) {
1884 global $wgOut, $wgUser;
1886 wfProfileIn( __METHOD__
);
1888 # need to parse the preview early so that we know which templates are used,
1889 # otherwise users with "show preview after edit box" will get a blank list
1890 # we parse this near the beginning so that setHeaders can do the title
1891 # setting work instead of leaving it in getPreviewText
1892 $previewOutput = '';
1893 if ( $this->formtype
== 'preview' ) {
1894 $previewOutput = $this->getPreviewText();
1897 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
1899 $this->setHeaders();
1901 if ( $this->showHeader() === false ) {
1902 wfProfileOut( __METHOD__
);
1906 $wgOut->addHTML( $this->editFormPageTop
);
1908 if ( $wgUser->getOption( 'previewontop' ) ) {
1909 $this->displayPreviewArea( $previewOutput, true );
1912 $wgOut->addHTML( $this->editFormTextTop
);
1914 $showToolbar = true;
1915 if ( $this->wasDeletedSinceLastEdit() ) {
1916 if ( $this->formtype
== 'save' ) {
1917 // Hide the toolbar and edit area, user can click preview to get it back
1918 // Add an confirmation checkbox and explanation.
1919 $showToolbar = false;
1921 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1922 'deletedwhileediting' );
1926 #FIXME: add EditForm plugin interface and use it here! #FIXME: search for textarea1 and textares2, and allow EditForm to override all uses.
1927 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => self
::EDITFORM_ID
, 'name' => self
::EDITFORM_ID
,
1928 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1929 'enctype' => 'multipart/form-data' ) ) );
1931 if ( is_callable( $formCallback ) ) {
1932 call_user_func_array( $formCallback, array( &$wgOut ) );
1935 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1937 // Put these up at the top to ensure they aren't lost on early form submission
1938 $this->showFormBeforeText();
1940 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1941 $username = $this->lastDelete
->user_name
;
1942 $comment = $this->lastDelete
->log_comment
;
1944 // It is better to not parse the comment at all than to have templates expanded in the middle
1945 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1946 $key = $comment === ''
1947 ?
'confirmrecreate-noreason'
1948 : 'confirmrecreate';
1950 '<div class="mw-confirm-recreate">' .
1951 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1952 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1953 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1959 # When the summary is hidden, also hide them on preview/show changes
1960 if( $this->nosummary
) {
1961 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
1964 # If a blank edit summary was previously provided, and the appropriate
1965 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1966 # user being bounced back more than once in the event that a summary
1969 # For a bit more sophisticated detection of blank summaries, hash the
1970 # automatic one and pass that in the hidden field wpAutoSummary.
1971 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
1972 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1975 if ( $this->hasPresetSummary
) {
1976 // If a summary has been preset using &summary= we dont want to prompt for
1977 // a different summary. Only prompt for a summary if the summary is blanked.
1979 $this->autoSumm
= md5( '' );
1982 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1983 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1985 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
1987 $wgOut->addHTML( Html
::hidden( 'format', $this->content_format
) );
1988 $wgOut->addHTML( Html
::hidden( 'model', $this->content_model
) );
1990 if ( $this->section
== 'new' ) {
1991 $this->showSummaryInput( true, $this->summary
);
1992 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1995 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1997 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1998 $wgOut->addHTML( EditPage
::getEditToolbar() );
2001 if ( $this->isConflict
) {
2002 // In an edit conflict bypass the overrideable content form method
2003 // and fallback to the raw wpTextbox1 since editconflicts can't be
2004 // resolved between page source edits and custom ui edits using the
2006 $this->textbox2
= $this->textbox1
;
2008 $content = $this->getCurrentContent();
2009 $this->textbox1
= $content->serialize( $this->content_format
);
2011 $this->showTextbox1();
2013 $this->showContentForm();
2016 $wgOut->addHTML( $this->editFormTextAfterContent
);
2018 $wgOut->addWikiText( $this->getCopywarn() );
2020 $wgOut->addHTML( $this->editFormTextAfterWarn
);
2022 $this->showStandardInputs();
2024 $this->showFormAfterText();
2026 $this->showTosSummary();
2028 $this->showEditTools();
2030 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2032 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2033 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2035 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2036 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2038 if ( $this->isConflict
) {
2039 $this->showConflict();
2042 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2044 if ( !$wgUser->getOption( 'previewontop' ) ) {
2045 $this->displayPreviewArea( $previewOutput, false );
2048 wfProfileOut( __METHOD__
);
2052 * Extract the section title from current section text, if any.
2054 * @param string $text
2055 * @return Mixed|string or false
2057 public static function extractSectionTitle( $text ) {
2058 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2059 if ( !empty( $matches[2] ) ) {
2061 return $wgParser->stripSectionName( trim( $matches[2] ) );
2067 protected function showHeader() {
2068 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2070 if ( $this->mTitle
->isTalkPage() ) {
2071 $wgOut->addWikiMsg( 'talkpagetext' );
2074 # Optional notices on a per-namespace and per-page basis
2075 $editnotice_ns = 'editnotice-' . $this->mTitle
->getNamespace();
2076 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
2077 if ( $editnotice_ns_message->exists() ) {
2078 $wgOut->addWikiText( $editnotice_ns_message->plain() );
2080 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
2081 $parts = explode( '/', $this->mTitle
->getDBkey() );
2082 $editnotice_base = $editnotice_ns;
2083 while ( count( $parts ) > 0 ) {
2084 $editnotice_base .= '-' . array_shift( $parts );
2085 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
2086 if ( $editnotice_base_msg->exists() ) {
2087 $wgOut->addWikiText( $editnotice_base_msg->plain() );
2091 # Even if there are no subpages in namespace, we still don't want / in MW ns.
2092 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
2093 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
2094 if ( $editnoticeMsg->exists() ) {
2095 $wgOut->addWikiText( $editnoticeMsg->plain() );
2099 if ( $this->isConflict
) {
2100 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2101 $this->edittime
= $this->mArticle
->getTimestamp();
2103 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2104 // We use $this->section to much before this and getVal('wgSection') directly in other places
2105 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2106 // Someone is welcome to try refactoring though
2107 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2111 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2112 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2113 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
2114 if ( $sectionTitle !== false ) {
2115 $this->summary
= "/* $sectionTitle */ ";
2120 if ( $this->missingComment
) {
2121 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2124 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2125 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2128 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2129 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2132 if ( $this->hookError
!== '' ) {
2133 $wgOut->addWikiText( $this->hookError
);
2136 if ( !$this->checkUnicodeCompliantBrowser() ) {
2137 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2140 if ( $this->section
!= 'new' ) {
2141 $revision = $this->mArticle
->getRevisionFetched();
2143 // Let sysop know that this will make private content public if saved
2145 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
2146 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2147 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2148 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2151 if ( !$revision->isCurrent() ) {
2152 $this->mArticle
->setOldSubtitle( $revision->getId() );
2153 $wgOut->addWikiMsg( 'editingold' );
2155 } elseif ( $this->mTitle
->exists() ) {
2156 // Something went wrong
2158 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2159 array( 'missing-article', $this->mTitle
->getPrefixedText(),
2160 wfMsgNoTrans( 'missingarticle-rev', $this->oldid
) ) );
2165 if ( wfReadOnly() ) {
2166 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2167 } elseif ( $wgUser->isAnon() ) {
2168 if ( $this->formtype
!= 'preview' ) {
2169 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2171 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2174 if ( $this->isCssJsSubpage
) {
2175 # Check the skin exists
2176 if ( $this->isWrongCaseCssJsPage
) {
2177 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2179 if ( $this->formtype
!== 'preview' ) {
2180 if ( $this->isCssSubpage
)
2181 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2182 if ( $this->isJsSubpage
)
2183 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2188 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2189 # Is the title semi-protected?
2190 if ( $this->mTitle
->isSemiProtected() ) {
2191 $noticeMsg = 'semiprotectedpagewarning';
2193 # Then it must be protected based on static groups (regular)
2194 $noticeMsg = 'protectedpagewarning';
2196 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2197 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2199 if ( $this->mTitle
->isCascadeProtected() ) {
2200 # Is this page under cascading protection from some source pages?
2201 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2202 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2203 $cascadeSourcesCount = count( $cascadeSources );
2204 if ( $cascadeSourcesCount > 0 ) {
2205 # Explain, and list the titles responsible
2206 foreach ( $cascadeSources as $page ) {
2207 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2210 $notice .= '</div>';
2211 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2213 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2214 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2216 'showIfEmpty' => false,
2217 'msgKey' => array( 'titleprotectedwarning' ),
2218 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2221 if ( $this->kblength
=== false ) {
2222 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2225 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2226 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2227 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2229 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2230 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2231 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2238 * Standard summary input and label (wgSummary), abstracted so EditPage
2239 * subclasses may reorganize the form.
2240 * Note that you do not need to worry about the label's for=, it will be
2241 * inferred by the id given to the input. You can remove them both by
2242 * passing array( 'id' => false ) to $userInputAttrs.
2244 * @param $summary string The value of the summary input
2245 * @param $labelText string The html to place inside the label
2246 * @param $inputAttrs array of attrs to use on the input
2247 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2249 * @return array An array in the format array( $label, $input )
2251 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2252 // Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
2253 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2254 'id' => 'wpSummary',
2255 'maxlength' => '200',
2258 'spellcheck' => 'true',
2259 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2261 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2262 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2263 'id' => "wpSummaryLabel"
2268 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2269 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2272 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2274 return array( $label, $input );
2278 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2279 * up top, or false if this is the comment summary
2280 * down below the textarea
2281 * @param $summary String: The text of the summary to display
2284 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2285 global $wgOut, $wgContLang;
2286 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2287 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2288 if ( $isSubjectPreview ) {
2289 if ( $this->nosummary
) {
2293 if ( !$this->mShowSummaryField
) {
2297 $summary = $wgContLang->recodeForEdit( $summary );
2298 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
2299 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2300 $wgOut->addHTML( "{$label} {$input}" );
2304 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2305 * up top, or false if this is the comment summary
2306 * down below the textarea
2307 * @param $summary String: the text of the summary to display
2310 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2311 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2316 if ( $isSubjectPreview )
2317 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2319 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2321 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2322 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2325 protected function showFormBeforeText() {
2327 $section = htmlspecialchars( $this->section
);
2328 $wgOut->addHTML( <<<HTML
2329 <input type='hidden' value="{$section}" name="wpSection" />
2330 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2331 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2332 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2336 if ( !$this->checkUnicodeCompliantBrowser() )
2337 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2340 protected function showFormAfterText() {
2341 global $wgOut, $wgUser;
2343 * To make it harder for someone to slip a user a page
2344 * which submits an edit form to the wiki without their
2345 * knowledge, a random token is associated with the login
2346 * session. If it's not passed back with the submission,
2347 * we won't save the page, or render user JavaScript and
2350 * For anon editors, who may not have a session, we just
2351 * include the constant suffix to prevent editing from
2352 * broken text-mangling proxies.
2354 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2358 * Subpage overridable method for printing the form for page content editing
2359 * By default this simply outputs wpTextbox1
2360 * Subclasses can override this to provide a custom UI for editing;
2361 * be it a form, or simply wpTextbox1 with a modified content that will be
2362 * reverse modified when extracted from the post data.
2363 * Note that this is basically the inverse for importContentFormData
2365 protected function showContentForm() {
2366 $this->showTextbox1();
2370 * Method to output wpTextbox1
2371 * The $textoverride method can be used by subclasses overriding showContentForm
2372 * to pass back to this method.
2374 * @param $customAttribs array of html attributes to use in the textarea
2375 * @param $textoverride String: optional text to override $this->textarea1 with
2377 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2378 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2379 $attribs = array( 'style' => 'display:none;' );
2381 $classes = array(); // Textarea CSS
2382 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2383 # Is the title semi-protected?
2384 if ( $this->mTitle
->isSemiProtected() ) {
2385 $classes[] = 'mw-textarea-sprotected';
2387 # Then it must be protected based on static groups (regular)
2388 $classes[] = 'mw-textarea-protected';
2390 # Is the title cascade-protected?
2391 if ( $this->mTitle
->isCascadeProtected() ) {
2392 $classes[] = 'mw-textarea-cprotected';
2396 $attribs = array( 'tabindex' => 1 );
2398 if ( is_array( $customAttribs ) ) {
2399 $attribs +
= $customAttribs;
2402 if ( count( $classes ) ) {
2403 if ( isset( $attribs['class'] ) ) {
2404 $classes[] = $attribs['class'];
2406 $attribs['class'] = implode( ' ', $classes );
2410 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2413 protected function showTextbox2() {
2414 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2417 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2418 global $wgOut, $wgUser;
2420 $wikitext = $this->safeUnicodeOutput( $text );
2421 if ( strval( $wikitext ) !== '' ) {
2422 // Ensure there's a newline at the end, otherwise adding lines
2424 // But don't add a newline if the ext is empty, or Firefox in XHTML
2425 // mode will show an extra newline. A bit annoying.
2429 $attribs = $customAttribs +
array(
2432 'cols' => $wgUser->getIntOption( 'cols' ),
2433 'rows' => $wgUser->getIntOption( 'rows' ),
2434 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2437 $pageLang = $this->mTitle
->getPageLanguage();
2438 $attribs['lang'] = $pageLang->getCode();
2439 $attribs['dir'] = $pageLang->getDir();
2441 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2444 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2448 $classes[] = 'ontop';
2450 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2452 if ( $this->formtype
!= 'preview' )
2453 $attribs['style'] = 'display: none;';
2455 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2457 if ( $this->formtype
== 'preview' ) {
2458 $this->showPreview( $previewOutput );
2461 $wgOut->addHTML( '</div>' );
2463 if ( $this->formtype
== 'diff' ) {
2469 * Append preview output to $wgOut.
2470 * Includes category rendering if this is a category page.
2472 * @param $text String: the HTML to be output for the preview.
2474 protected function showPreview( $text ) {
2476 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2477 $this->mArticle
->openShowCategory();
2479 # This hook seems slightly odd here, but makes things more
2480 # consistent for extensions.
2481 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2482 $wgOut->addHTML( $text );
2483 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2484 $this->mArticle
->closeShowCategory();
2489 * Get a diff between the current contents of the edit box and the
2490 * version of the page we're editing from.
2492 * If this is a section edit, we'll replace the section as for final
2493 * save and then make a comparison.
2495 function showDiff() {
2496 global $wgUser, $wgContLang, $wgParser, $wgOut;
2498 $oldtitlemsg = 'currentrev';
2499 # if message does not exist, show diff against the preloaded default
2500 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2501 $oldtext = $this->mTitle
->getDefaultMessageText();
2502 if( $oldtext !== false ) {
2503 $oldtitlemsg = 'defaultmessagetext';
2504 $oldContent = ContentHandler
::makeContent( $oldtext, $this->mTitle
);
2509 $oldContent = $this->getOriginalContent();
2512 $textboxContent = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(),
2513 $this->content_model
, $this->content_format
); #XXX: handle parse errors ?
2515 $newContent = $this->mArticle
->replaceSectionContent(
2516 $this->section
, $textboxContent,
2517 $this->summary
, $this->edittime
);
2519 # hanlde legacy text-based hook
2520 $newtext_orig = $newContent->serialize( $this->content_format
);
2521 $newtext = $newtext_orig; #clone
2522 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2524 if ( $newtext != $newtext_orig ) {
2525 #if the hook changed the text, create a new Content object accordingly.
2526 $newContent = ContentHandler
::makeContent( $newtext, $this->getTitle(), $newContent->getModelName() ); #XXX: handle parse errors ?
2529 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2531 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2532 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2534 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2535 $oldtitle = wfMsgExt( $oldtitlemsg, array( 'parseinline' ) );
2536 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2538 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
2539 $de->setContent( $oldContent, $newContent );
2541 $difftext = $de->getDiff( $oldtitle, $newtitle );
2542 $de->showDiffStyle();
2547 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2551 * Give a chance for site and per-namespace customizations of
2552 * terms of service summary link that might exist separately
2553 * from the copyright notice.
2555 * This will display between the save button and the edit tools,
2556 * so should remain short!
2558 protected function showTosSummary() {
2559 $msg = 'editpage-tos-summary';
2560 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2561 if ( !wfMessage( $msg )->isDisabled() ) {
2563 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2564 $wgOut->addWikiMsg( $msg );
2565 $wgOut->addHTML( '</div>' );
2569 protected function showEditTools() {
2571 $wgOut->addHTML( '<div class="mw-editTools">' .
2572 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2576 protected function getCopywarn() {
2577 global $wgRightsText;
2578 if ( $wgRightsText ) {
2579 $copywarnMsg = array( 'copyrightwarning',
2580 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2583 $copywarnMsg = array( 'copyrightwarning2',
2584 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2586 // Allow for site and per-namespace customization of contribution/copyright notice.
2587 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2589 return "<div id=\"editpage-copywarn\">\n" .
2590 call_user_func_array( "wfMsgNoTrans", $copywarnMsg ) . "\n</div>";
2593 protected function showStandardInputs( &$tabindex = 2 ) {
2595 $wgOut->addHTML( "<div class='editOptions'>\n" );
2597 if ( $this->section
!= 'new' ) {
2598 $this->showSummaryInput( false, $this->summary
);
2599 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2602 $checkboxes = $this->getCheckboxes( $tabindex,
2603 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2604 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2605 $wgOut->addHTML( "<div class='editButtons'>\n" );
2606 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2608 $cancel = $this->getCancelLink();
2609 if ( $cancel !== '' ) {
2610 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2612 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2613 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2614 htmlspecialchars( wfMsg( 'edithelp' ) ) . '</a> ' .
2615 htmlspecialchars( wfMsg( 'newwindow' ) );
2616 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2617 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2621 * Show an edit conflict. textbox1 is already shown in showEditForm().
2622 * If you want to use another entry point to this function, be careful.
2624 protected function showConflict() {
2627 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2628 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2630 $content1 = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
); #XXX: handle parse errors?
2631 $content2 = ContentHandler
::makeContent( $this->textbox2
, $this->getTitle(), $this->content_model
, $this->content_format
); #XXX: handle parse errors?
2633 $handler = ContentHandler
::getForModelName( $this->content_model
);
2634 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
2635 $de->setContent( $content2, $content1 );
2636 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2638 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2639 $this->showTextbox2();
2646 public function getCancelLink() {
2647 $cancelParams = array();
2648 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2649 $cancelParams['oldid'] = $this->oldid
;
2652 return Linker
::linkKnown(
2653 $this->getContextTitle(),
2654 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2655 array( 'id' => 'mw-editform-cancel' ),
2661 * Returns the URL to use in the form's action attribute.
2662 * This is used by EditPage subclasses when simply customizing the action
2663 * variable in the constructor is not enough. This can be used when the
2664 * EditPage lives inside of a Special page rather than a custom page action.
2666 * @param $title Title object for which is being edited (where we go to for &action= links)
2669 protected function getActionURL( Title
$title ) {
2670 return $title->getLocalURL( array( 'action' => $this->action
) );
2674 * Check if a page was deleted while the user was editing it, before submit.
2675 * Note that we rely on the logging table, which hasn't been always there,
2676 * but that doesn't matter, because this only applies to brand new
2679 protected function wasDeletedSinceLastEdit() {
2680 if ( $this->deletedSinceEdit
!== null ) {
2681 return $this->deletedSinceEdit
;
2684 $this->deletedSinceEdit
= false;
2686 if ( $this->mTitle
->isDeletedQuick() ) {
2687 $this->lastDelete
= $this->getLastDelete();
2688 if ( $this->lastDelete
) {
2689 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2690 if ( $deleteTime > $this->starttime
) {
2691 $this->deletedSinceEdit
= true;
2696 return $this->deletedSinceEdit
;
2699 protected function getLastDelete() {
2700 $dbr = wfGetDB( DB_SLAVE
);
2701 $data = $dbr->selectRow(
2702 array( 'logging', 'user' ),
2713 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2714 'log_title' => $this->mTitle
->getDBkey(),
2715 'log_type' => 'delete',
2716 'log_action' => 'delete',
2717 'user_id=log_user' ),
2719 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2721 // Quick paranoid permission checks...
2722 if ( is_object( $data ) ) {
2723 if ( $data->log_deleted
& LogPage
::DELETED_USER
)
2724 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2725 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2726 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2732 * Get the rendered text for previewing.
2735 function getPreviewText() {
2736 global $wgOut, $wgUser, $wgParser, $wgRawHtml, $wgLang;
2738 wfProfileIn( __METHOD__
);
2740 if ( $wgRawHtml && !$this->mTokenOk
) {
2741 // Could be an offsite preview attempt. This is very unsafe if
2742 // HTML is enabled, as it could be an attack.
2744 if ( $this->textbox1
!== '' ) {
2745 // Do not put big scary notice, if previewing the empty
2746 // string, which happens when you initially edit
2747 // a category page, due to automatic preview-on-open.
2748 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2749 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2751 wfProfileOut( __METHOD__
);
2758 $content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
);
2760 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2761 if ( $this->mTokenOkExceptSuffix
) {
2762 $note = wfMsg( 'token_suffix_mismatch' );
2764 $note = wfMsg( 'session_fail_preview' );
2766 } elseif ( $this->incompleteForm
) {
2767 $note = wfMsg( 'edit_form_incomplete' );
2769 $note = wfMsg( 'previewnote' ) .
2770 ' [[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' . wfMsg( 'continue-editing' ) . ']]';
2773 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2774 $parserOptions->setEditSection( false );
2775 $parserOptions->setTidy( true );
2776 $parserOptions->setIsPreview( true );
2777 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2779 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
2780 # don't parse non-wikitext pages, show message about preview
2781 if( $this->mTitle
->isCssJsSubpage() ) {
2783 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2789 if ( $content->getModelName() == CONTENT_MODEL_CSS
) {
2791 } elseif ( $content->getModelName() == CONTENT_MODEL_JAVASCRIPT
) {
2797 # Used messages to make sure grep find them:
2798 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2799 if( $level && $format ) {
2800 $note = "<div id='mw-{$level}{$format}preview'>" . wfMsg( "{$level}{$format}preview" ) . "</div>";
2802 $note = wfMsg( 'previewnote' );
2805 $note = wfMsg( 'previewnote' );
2808 $rt = $content->getRedirectChain();
2811 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2814 # If we're adding a comment, we need to show the
2815 # summary as the headline
2816 if ( $this->section
== "new" && $this->summary
!= "" ) {
2817 $content = $content->addSectionHeader( $this->summary
);
2820 $toparse_orig = $content->serialize( $this->content_format
);
2821 $toparse = $toparse_orig;
2822 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2824 if ( $toparse !== $toparse_orig ) {
2825 #hook changed the text, create new Content object
2826 $content = ContentHandler
::makeContent( $toparse, $this->getTitle(), $this->content_model
, $this->content_format
);
2829 wfRunHooks( 'EditPageGetPreviewContent', array( $this, &$content ) );
2831 $parserOptions->enableLimitReport();
2833 #XXX: For CSS/JS pages, we should have called the ShowRawCssJs hook here. But it's now deprecated, so never mind
2834 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
2836 // TODO: might be a saner way to get a meaningfull context here?
2837 $parserOutput = $content->getParserOutput( $this->getArticle()->getContext(), null, $parserOptions );
2839 $previewHTML = $parserOutput->getText();
2840 $this->mParserOutput
= $parserOutput;
2841 $wgOut->addParserOutputNoText( $parserOutput );
2843 if ( count( $parserOutput->getWarnings() ) ) {
2844 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2847 } catch (MWContentSerializationException
$ex) {
2848 $note .= "\n\n" . wfMsg('content-failed-to-parse', $this->content_model
, $this->content_format
, $ex->getMessage() );
2852 if ( $this->isConflict
) {
2853 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2855 $conflict = '<hr />';
2858 $previewhead = "<div class='previewnote'>\n" .
2859 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2860 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2862 $pageLang = $this->mTitle
->getPageLanguage();
2863 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2864 'class' => 'mw-content-' . $pageLang->getDir() );
2865 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2867 wfProfileOut( __METHOD__
);
2868 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2874 function getTemplates() {
2875 if ( $this->preview ||
$this->section
!= '' ) {
2876 $templates = array();
2877 if ( !isset( $this->mParserOutput
) ) {
2880 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
2881 foreach ( array_keys( $template ) as $dbk ) {
2882 $templates[] = Title
::makeTitle( $ns, $dbk );
2887 return $this->mTitle
->getTemplateLinksFrom();
2892 * Shows a bulletin board style toolbar for common editing functions.
2893 * It can be disabled in the user preferences.
2894 * The necessary JavaScript code can be found in skins/common/edit.js.
2898 static function getEditToolbar() {
2899 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2900 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2902 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2905 * $toolarray is an array of arrays each of which includes the
2906 * filename of the button image (without path), the opening
2907 * tag, the closing tag, optionally a sample text that is
2908 * inserted between the two when no selection is highlighted
2909 * and. The tip text is shown when the user moves the mouse
2912 * Also here: accesskeys (key), which are not used yet until
2913 * someone can figure out a way to make them work in
2914 * IE. However, we should make sure these keys are not defined
2919 'image' => $wgLang->getImageFile( 'button-bold' ),
2920 'id' => 'mw-editbutton-bold',
2922 'close' => '\'\'\'',
2923 'sample' => wfMsg( 'bold_sample' ),
2924 'tip' => wfMsg( 'bold_tip' ),
2928 'image' => $wgLang->getImageFile( 'button-italic' ),
2929 'id' => 'mw-editbutton-italic',
2932 'sample' => wfMsg( 'italic_sample' ),
2933 'tip' => wfMsg( 'italic_tip' ),
2937 'image' => $wgLang->getImageFile( 'button-link' ),
2938 'id' => 'mw-editbutton-link',
2941 'sample' => wfMsg( 'link_sample' ),
2942 'tip' => wfMsg( 'link_tip' ),
2946 'image' => $wgLang->getImageFile( 'button-extlink' ),
2947 'id' => 'mw-editbutton-extlink',
2950 'sample' => wfMsg( 'extlink_sample' ),
2951 'tip' => wfMsg( 'extlink_tip' ),
2955 'image' => $wgLang->getImageFile( 'button-headline' ),
2956 'id' => 'mw-editbutton-headline',
2959 'sample' => wfMsg( 'headline_sample' ),
2960 'tip' => wfMsg( 'headline_tip' ),
2963 $imagesAvailable ?
array(
2964 'image' => $wgLang->getImageFile( 'button-image' ),
2965 'id' => 'mw-editbutton-image',
2966 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2968 'sample' => wfMsg( 'image_sample' ),
2969 'tip' => wfMsg( 'image_tip' ),
2972 $imagesAvailable ?
array(
2973 'image' => $wgLang->getImageFile( 'button-media' ),
2974 'id' => 'mw-editbutton-media',
2975 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2977 'sample' => wfMsg( 'media_sample' ),
2978 'tip' => wfMsg( 'media_tip' ),
2982 'image' => $wgLang->getImageFile( 'button-math' ),
2983 'id' => 'mw-editbutton-math',
2985 'close' => "</math>",
2986 'sample' => wfMsg( 'math_sample' ),
2987 'tip' => wfMsg( 'math_tip' ),
2991 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2992 'id' => 'mw-editbutton-nowiki',
2993 'open' => "<nowiki>",
2994 'close' => "</nowiki>",
2995 'sample' => wfMsg( 'nowiki_sample' ),
2996 'tip' => wfMsg( 'nowiki_tip' ),
3000 'image' => $wgLang->getImageFile( 'button-sig' ),
3001 'id' => 'mw-editbutton-signature',
3005 'tip' => wfMsg( 'sig_tip' ),
3009 'image' => $wgLang->getImageFile( 'button-hr' ),
3010 'id' => 'mw-editbutton-hr',
3011 'open' => "\n----\n",
3014 'tip' => wfMsg( 'hr_tip' ),
3019 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3020 foreach ( $toolarray as $tool ) {
3026 $image = $wgStylePath . '/common/images/' . $tool['image'],
3027 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3028 // Older browsers show a "speedtip" type message only for ALT.
3029 // Ideally these should be different, realistically they
3030 // probably don't need to be.
3031 $tip = $tool['tip'],
3032 $open = $tool['open'],
3033 $close = $tool['close'],
3034 $sample = $tool['sample'],
3035 $cssId = $tool['id'],
3038 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3041 // This used to be called on DOMReady from mediawiki.action.edit, which
3042 // ended up causing race conditions with the setup code above.
3044 "// Create button bar\n" .
3045 "$(function() { mw.toolbar.init(); } );\n";
3048 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3050 $toolbar = '<div id="toolbar"></div>';
3052 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3058 * Returns an array of html code of the following checkboxes:
3061 * @param $tabindex int Current tabindex
3062 * @param $checked Array of checkbox => bool, where bool indicates the checked
3063 * status of the checkbox
3067 public function getCheckboxes( &$tabindex, $checked ) {
3070 $checkboxes = array();
3072 // don't show the minor edit checkbox if it's a new page or section
3073 if ( !$this->isNew
) {
3074 $checkboxes['minor'] = '';
3075 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
3076 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3078 'tabindex' => ++
$tabindex,
3079 'accesskey' => wfMsg( 'accesskey-minoredit' ),
3080 'id' => 'wpMinoredit',
3082 $checkboxes['minor'] =
3083 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3084 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3085 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3086 ">{$minorLabel}</label>";
3090 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
3091 $checkboxes['watch'] = '';
3092 if ( $wgUser->isLoggedIn() ) {
3094 'tabindex' => ++
$tabindex,
3095 'accesskey' => wfMsg( 'accesskey-watch' ),
3096 'id' => 'wpWatchthis',
3098 $checkboxes['watch'] =
3099 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3100 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3101 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3102 ">{$watchLabel}</label>";
3104 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3109 * Returns an array of html code of the following buttons:
3110 * save, diff, preview and live
3112 * @param $tabindex int Current tabindex
3116 public function getEditButtons( &$tabindex ) {
3123 'tabindex' => ++
$tabindex,
3124 'value' => wfMsg( 'savearticle' ),
3125 'accesskey' => wfMsg( 'accesskey-save' ),
3126 'title' => wfMsg( 'tooltip-save' ) . ' [' . wfMsg( 'accesskey-save' ) . ']',
3128 $buttons['save'] = Xml
::element( 'input', $temp, '' );
3130 ++
$tabindex; // use the same for preview and live preview
3132 'id' => 'wpPreview',
3133 'name' => 'wpPreview',
3135 'tabindex' => $tabindex,
3136 'value' => wfMsg( 'showpreview' ),
3137 'accesskey' => wfMsg( 'accesskey-preview' ),
3138 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
3140 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3141 $buttons['live'] = '';
3147 'tabindex' => ++
$tabindex,
3148 'value' => wfMsg( 'showdiff' ),
3149 'accesskey' => wfMsg( 'accesskey-diff' ),
3150 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
3152 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3154 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3159 * Output preview text only. This can be sucked into the edit page
3160 * via JavaScript, and saves the server time rendering the skin as
3161 * well as theoretically being more robust on the client (doesn't
3162 * disturb the edit box's undo history, won't eat your text on
3165 * @todo This doesn't include category or interlanguage links.
3166 * Would need to enhance it a bit, <s>maybe wrap them in XML
3167 * or something...</s> that might also require more skin
3168 * initialization, so check whether that's a problem.
3170 function livePreview() {
3173 header( 'Content-type: text/xml; charset=utf-8' );
3174 header( 'Cache-control: no-cache' );
3176 $previewText = $this->getPreviewText();
3177 #$categories = $skin->getCategoryLinks();
3180 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3181 Xml
::tags( 'livepreview', null,
3182 Xml
::element( 'preview', null, $previewText )
3183 #. Xml::element( 'category', null, $categories )
3189 * Call the stock "user is blocked" page
3191 * @deprecated in 1.19; throw an exception directly instead
3193 function blockedPage() {
3194 wfDeprecated( __METHOD__
, '1.19' );
3197 throw new UserBlockedError( $wgUser->getBlock() );
3201 * Produce the stock "please login to edit pages" page
3203 * @deprecated in 1.19; throw an exception directly instead
3205 function userNotLoggedInPage() {
3206 wfDeprecated( __METHOD__
, '1.19' );
3207 throw new PermissionsError( 'edit' );
3211 * Show an error page saying to the user that he has insufficient permissions
3212 * to create a new page
3214 * @deprecated in 1.19; throw an exception directly instead
3216 function noCreatePermission() {
3217 wfDeprecated( __METHOD__
, '1.19' );
3218 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3219 throw new PermissionsError( $permission );
3223 * Creates a basic error page which informs the user that
3224 * they have attempted to edit a nonexistent section.
3226 function noSuchSectionPage() {
3229 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3231 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
3232 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3233 $wgOut->addHTML( $res );
3235 $wgOut->returnToMain( false, $this->mTitle
);
3239 * Produce the stock "your edit contains spam" page
3241 * @param $match string Text which triggered one or more filters
3242 * @deprecated since 1.17 Use method spamPageWithContent() instead
3244 static function spamPage( $match = false ) {
3245 wfDeprecated( __METHOD__
, '1.17' );
3247 global $wgOut, $wgTitle;
3249 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3251 $wgOut->addHTML( '<div id="spamprotected">' );
3252 $wgOut->addWikiMsg( 'spamprotectiontext' );
3254 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3256 $wgOut->addHTML( '</div>' );
3258 $wgOut->returnToMain( false, $wgTitle );
3262 * Show "your edit contains spam" page with your diff and text
3264 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3266 public function spamPageWithContent( $match = false ) {
3267 global $wgOut, $wgLang;
3268 $this->textbox2
= $this->textbox1
;
3270 if( is_array( $match ) ){
3271 $match = $wgLang->listToText( $match );
3273 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3275 $wgOut->addHTML( '<div id="spamprotected">' );
3276 $wgOut->addWikiMsg( 'spamprotectiontext' );
3278 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3280 $wgOut->addHTML( '</div>' );
3282 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3285 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3286 $this->showTextbox2();
3288 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3292 * Format an anchor fragment as it would appear for a given section name
3293 * @param $text String
3297 function sectionAnchor( $text ) {
3299 return $wgParser->guessSectionNameFromWikiText( $text );
3303 * Check if the browser is on a blacklist of user-agents known to
3304 * mangle UTF-8 data on form submission. Returns true if Unicode
3305 * should make it through, false if it's known to be a problem.
3309 function checkUnicodeCompliantBrowser() {
3310 global $wgBrowserBlackList;
3311 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
3312 // No User-Agent header sent? Trust it by default...
3315 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
3316 foreach ( $wgBrowserBlackList as $browser ) {
3317 if ( preg_match( $browser, $currentbrowser ) ) {
3325 * Filter an input field through a Unicode de-armoring process if it
3326 * came from an old browser with known broken Unicode editing issues.
3328 * @param $request WebRequest
3329 * @param $field String
3333 function safeUnicodeInput( $request, $field ) {
3334 $text = rtrim( $request->getText( $field ) );
3335 return $request->getBool( 'safemode' )
3336 ?
$this->unmakesafe( $text )
3341 * @param $request WebRequest
3342 * @param $text string
3345 function safeUnicodeText( $request, $text ) {
3346 $text = rtrim( $text );
3347 return $request->getBool( 'safemode' )
3348 ?
$this->unmakesafe( $text )
3353 * Filter an output field through a Unicode armoring process if it is
3354 * going to an old browser with known broken Unicode editing issues.
3356 * @param $text String
3360 function safeUnicodeOutput( $text ) {
3362 $codedText = $wgContLang->recodeForEdit( $text );
3363 return $this->checkUnicodeCompliantBrowser()
3365 : $this->makesafe( $codedText );
3369 * A number of web browsers are known to corrupt non-ASCII characters
3370 * in a UTF-8 text editing environment. To protect against this,
3371 * detected browsers will be served an armored version of the text,
3372 * with non-ASCII chars converted to numeric HTML character references.
3374 * Preexisting such character references will have a 0 added to them
3375 * to ensure that round-trips do not alter the original data.
3377 * @param $invalue String
3381 function makesafe( $invalue ) {
3382 // Armor existing references for reversability.
3383 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3388 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3389 $bytevalue = ord( $invalue[$i] );
3390 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3391 $result .= chr( $bytevalue );
3393 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3394 $working = $working << 6;
3395 $working +
= ( $bytevalue & 0x3F );
3397 if ( $bytesleft <= 0 ) {
3398 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3400 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3401 $working = $bytevalue & 0x1F;
3403 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3404 $working = $bytevalue & 0x0F;
3406 } else { // 1111 0xxx
3407 $working = $bytevalue & 0x07;
3415 * Reverse the previously applied transliteration of non-ASCII characters
3416 * back to UTF-8. Used to protect data from corruption by broken web browsers
3417 * as listed in $wgBrowserBlackList.
3419 * @param $invalue String
3423 function unmakesafe( $invalue ) {
3425 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3426 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3430 $hexstring .= $invalue[$i];
3432 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3434 // Do some sanity checks. These aren't needed for reversability,
3435 // but should help keep the breakage down if the editor
3436 // breaks one of the entities whilst editing.
3437 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3438 $codepoint = hexdec( $hexstring );
3439 $result .= codepointToUtf8( $codepoint );
3441 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3444 $result .= substr( $invalue, $i, 1 );
3447 // reverse the transform that we made for reversability reasons.
3448 return strtr( $result, array( "�" => "&#x" ) );