3 * Contains the EditPage class
8 * The edit page/HTML interface (split from Article)
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
13 * EditPage cares about two distinct titles:
14 * $this->mContextTitle is the page that forms submit to, links point to,
15 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
16 * page in the database that is actually being edited. These are
17 * usually the same, but they are now allowed to be different.
19 * Surgeon General's Warning: prolonged exposure to this class is known to cause
20 * headaches, which may be fatal.
25 * Status: Article successfully updated
27 const AS_SUCCESS_UPDATE
= 200;
30 * Status: Article successfully created
32 const AS_SUCCESS_NEW_ARTICLE
= 201;
35 * Status: Article update aborted by a hook function
37 const AS_HOOK_ERROR
= 210;
40 * Status: The filter function set in $wgFilterCallback returned true (= block it)
42 const AS_FILTERING
= 211;
45 * Status: A hook function returned an error
47 const AS_HOOK_ERROR_EXPECTED
= 212;
50 * Status: User is blocked from editting this page
52 const AS_BLOCKED_PAGE_FOR_USER
= 215;
55 * Status: Content too big (> $wgMaxArticleSize)
57 const AS_CONTENT_TOO_BIG
= 216;
60 * Status: User cannot edit? (not used)
62 const AS_USER_CANNOT_EDIT
= 217;
65 * Status: this anonymous user is not allowed to edit this page
67 const AS_READ_ONLY_PAGE_ANON
= 218;
70 * Status: this logged in user is not allowed to edit this page
72 const AS_READ_ONLY_PAGE_LOGGED
= 219;
75 * Status: wiki is in readonly mode (wfReadOnly() == true)
77 const AS_READ_ONLY_PAGE
= 220;
80 * Status: rate limiter for action 'edit' was tripped
82 const AS_RATE_LIMITED
= 221;
85 * Status: article was deleted while editting and param wpRecreate == false or form
88 const AS_ARTICLE_WAS_DELETED
= 222;
91 * Status: user tried to create this page, but is not allowed to do that
92 * ( Title->usercan('create') == false )
94 const AS_NO_CREATE_PERMISSION
= 223;
97 * Status: user tried to create a blank page
99 const AS_BLANK_ARTICLE
= 224;
102 * Status: (non-resolvable) edit conflict
104 const AS_CONFLICT_DETECTED
= 225;
107 * Status: no edit summary given and the user has forceeditsummary set and the user is not
108 * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
110 const AS_SUMMARY_NEEDED
= 226;
113 * Status: user tried to create a new section without content
115 const AS_TEXTBOX_EMPTY
= 228;
118 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
120 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
128 * Status: WikiPage::doEdit() was unsuccessfull
133 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
135 const AS_SPAM_ERROR
= 232;
138 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
140 const AS_IMAGE_REDIRECT_ANON
= 233;
143 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
145 const AS_IMAGE_REDIRECT_LOGGED
= 234;
148 * Status: can't parse content
150 const AS_PARSE_ERROR
= 240;
161 private $mContextTitle = null;
162 var $action = 'submit';
163 var $isConflict = false;
164 var $isCssJsSubpage = false;
165 var $isCssSubpage = false;
166 var $isJsSubpage = false;
167 var $isWrongCaseCssJsPage = false;
168 var $isNew = false; // new page or new section
169 var $deletedSinceEdit;
173 var $mTokenOk = false;
174 var $mTokenOkExceptSuffix = false;
175 var $mTriedSave = false;
176 var $incompleteForm = false;
178 var $kblength = false;
179 var $missingComment = false;
180 var $missingSummary = false;
181 var $allowBlankSummary = false;
184 #var $mPreviewTemplates;
192 * Has a summary been preset using GET parameter &summary= ?
195 var $hasPresetSummary = false;
197 var $mBaseRevision = false;
198 var $mShowSummaryField = true;
201 var $save = false, $preview = false, $diff = false;
202 var $minoredit = false, $watchthis = false, $recreate = false;
203 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
204 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
205 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
206 var $content_model = null, $content_format = null;
208 # Placeholders for text injection by hooks (must be HTML)
209 # extensions should take care to _append_ to the present value
210 public $editFormPageTop = ''; // Before even the preview
211 public $editFormTextTop = '';
212 public $editFormTextBeforeContent = '';
213 public $editFormTextAfterWarn = '';
214 public $editFormTextAfterTools = '';
215 public $editFormTextBottom = '';
216 public $editFormTextAfterContent = '';
217 public $previewTextAfterContent = '';
218 public $mPreloadContent = null;
220 /* $didSave should be set to true whenever an article was succesfully altered. */
221 public $didSave = false;
222 public $undidRev = 0;
224 public $suppressIntro = false;
227 * @param $article Article
229 public function __construct( Article
$article ) {
230 $this->mArticle
= $article;
231 $this->mTitle
= $article->getTitle();
233 $this->content_model
= $this->mTitle
->getContentModelName();
235 $handler = ContentHandler
::getForModelName( $this->content_model
);
236 $this->content_format
= $handler->getDefaultFormat(); #NOTE: should be overridden by format of actual revision
242 public function getArticle() {
243 return $this->mArticle
;
250 public function getTitle() {
251 return $this->mTitle
;
255 * Set the context Title object
257 * @param $title Title object or null
259 public function setContextTitle( $title ) {
260 $this->mContextTitle
= $title;
264 * Get the context title object.
265 * If not set, $wgTitle will be returned. This behavior might changed in
266 * the future to return $this->mTitle instead.
268 * @return Title object
270 public function getContextTitle() {
271 if ( is_null( $this->mContextTitle
) ) {
275 return $this->mContextTitle
;
284 * This is the function that gets called for "action=edit". It
285 * sets up various member variables, then passes execution to
286 * another function, usually showEditForm()
288 * The edit form is self-submitting, so that when things like
289 * preview and edit conflicts occur, we get the same form back
290 * with the extra stuff added. Only when the final submission
291 * is made and all is well do we actually save and redirect to
292 * the newly-edited page.
295 global $wgOut, $wgRequest, $wgUser;
296 // Allow extensions to modify/prevent this form or submission
297 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
301 wfProfileIn( __METHOD__
);
302 wfDebug( __METHOD__
. ": enter\n" );
304 // If they used redlink=1 and the page exists, redirect to the main article
305 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
306 $wgOut->redirect( $this->mTitle
->getFullURL() );
307 wfProfileOut( __METHOD__
);
311 $this->importFormData( $wgRequest );
312 $this->firsttime
= false;
315 $this->livePreview();
316 wfProfileOut( __METHOD__
);
320 if ( wfReadOnly() && $this->save
) {
323 $this->preview
= true;
327 $this->formtype
= 'save';
328 } elseif ( $this->preview
) {
329 $this->formtype
= 'preview';
330 } elseif ( $this->diff
) {
331 $this->formtype
= 'diff';
332 } else { # First time through
333 $this->firsttime
= true;
334 if ( $this->previewOnOpen() ) {
335 $this->formtype
= 'preview';
337 $this->formtype
= 'initial';
341 $permErrors = $this->getEditPermissionErrors();
343 wfDebug( __METHOD__
. ": User can't edit\n" );
344 // Auto-block user's IP if the account was "hard" blocked
345 $wgUser->spreadAnyEditBlock();
347 $this->displayPermissionsError( $permErrors );
349 wfProfileOut( __METHOD__
);
353 wfProfileIn( __METHOD__
. "-business-end" );
355 $this->isConflict
= false;
356 // css / js subpages of user pages get a special treatment
357 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
358 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
359 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
360 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
361 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
363 # Show applicable editing introductions
364 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
368 # Attempt submission here. This will check for edit conflicts,
369 # and redundantly check for locked database, blocked IPs, etc.
370 # that edit() already checked just in case someone tries to sneak
371 # in the back door with a hand-edited submission URL.
373 if ( 'save' == $this->formtype
) {
374 if ( !$this->attemptSave() ) {
375 wfProfileOut( __METHOD__
. "-business-end" );
376 wfProfileOut( __METHOD__
);
381 # First time through: get contents, set time for conflict
383 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
384 if ( $this->initialiseForm() === false ) {
385 $this->noSuchSectionPage();
386 wfProfileOut( __METHOD__
. "-business-end" );
387 wfProfileOut( __METHOD__
);
390 if ( !$this->mTitle
->getArticleID() )
391 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
393 wfRunHooks( 'EditFormInitialText', array( $this ) );
396 $this->showEditForm();
397 wfProfileOut( __METHOD__
. "-business-end" );
398 wfProfileOut( __METHOD__
);
404 protected function getEditPermissionErrors() {
406 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
407 # Can this title be created?
408 if ( !$this->mTitle
->exists() ) {
409 $permErrors = array_merge( $permErrors,
410 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
412 # Ignore some permissions errors when a user is just previewing/viewing diffs
414 foreach ( $permErrors as $error ) {
415 if ( ( $this->preview ||
$this->diff
) &&
416 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
421 $permErrors = wfArrayDiff2( $permErrors, $remove );
426 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
427 * but with the following differences:
428 * - If redlink=1, the user will be redirected to the page
429 * - If there is content to display or the error occurs while either saving,
430 * previewing or showing the difference, it will be a
431 * "View source for ..." page displaying the source code after the error message.
434 * @param $permErrors Array of permissions errors, as returned by
435 * Title::getUserPermissionsErrors().
437 protected function displayPermissionsError( array $permErrors ) {
438 global $wgRequest, $wgOut;
440 if ( $wgRequest->getBool( 'redlink' ) ) {
441 // The edit page was reached via a red link.
442 // Redirect to the article page and let them click the edit tab if
443 // they really want a permission error.
444 $wgOut->redirect( $this->mTitle
->getFullUrl() );
448 $content = $this->getContentObject();
450 # Use the normal message if there's nothing to display
451 if ( $this->firsttime
&& $content->isEmpty() ) {
452 $action = $this->mTitle
->exists() ?
'edit' :
453 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
454 throw new PermissionsError( $action, $permErrors );
457 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
458 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
459 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
460 $wgOut->addHTML( "<hr />\n" );
462 # If the user made changes, preserve them when showing the markup
463 # (This happens when a user is blocked during edit, for instance)
464 if ( !$this->firsttime
) {
465 $text = $this->textbox1
;
466 $wgOut->addWikiMsg( 'viewyourtext' );
468 $text = $content->serialize( $this->content_format
);
469 $wgOut->addWikiMsg( 'viewsourcetext' );
472 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
474 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
475 Linker
::formatTemplates( $this->getTemplates() ) ) );
477 if ( $this->mTitle
->exists() ) {
478 $wgOut->returnToMain( null, $this->mTitle
);
483 * Show a read-only error
484 * Parameters are the same as OutputPage:readOnlyPage()
485 * Redirect to the article page if redlink=1
486 * @deprecated in 1.19; use displayPermissionsError() instead
488 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
489 wfDeprecated( __METHOD__
, '1.19' );
491 global $wgRequest, $wgOut;
492 if ( $wgRequest->getBool( 'redlink' ) ) {
493 // The edit page was reached via a red link.
494 // Redirect to the article page and let them click the edit tab if
495 // they really want a permission error.
496 $wgOut->redirect( $this->mTitle
->getFullUrl() );
498 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
503 * Should we show a preview when the edit form is first shown?
507 protected function previewOnOpen() {
508 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
509 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
510 // Explicit override from request
512 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
513 // Explicit override from request
515 } elseif ( $this->section
== 'new' ) {
516 // Nothing *to* preview for new sections
518 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
519 // Standard preference behaviour
521 } elseif ( !$this->mTitle
->exists() &&
522 isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] ) &&
523 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
525 // Categories are special
533 * Checks whether the user entered a skin name in uppercase,
534 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
538 protected function isWrongCaseCssJsPage() {
539 if ( $this->mTitle
->isCssJsSubpage() ) {
540 $name = $this->mTitle
->getSkinFromCssJsSubpage();
541 $skins = array_merge(
542 array_keys( Skin
::getSkinNames() ),
545 return !in_array( $name, $skins )
546 && in_array( strtolower( $name ), $skins );
553 * Does this EditPage class support section editing?
554 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
558 protected function isSectionEditSupported() {
563 * This function collects the form data and uses it to populate various member variables.
564 * @param $request WebRequest
566 function importFormData( &$request ) {
567 global $wgLang, $wgUser;
569 wfProfileIn( __METHOD__
);
571 # Section edit can come from either the form or a link
572 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
574 if ( $request->wasPosted() ) {
575 # These fields need to be checked for encoding.
576 # Also remove trailing whitespace, but don't remove _initial_
577 # whitespace from the text boxes. This may be significant formatting.
578 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
579 if ( !$request->getCheck( 'wpTextbox2' ) ) {
580 // Skip this if wpTextbox2 has input, it indicates that we came
581 // from a conflict page with raw page text, not a custom form
582 // modified by subclasses
583 wfProfileIn( get_class($this)."::importContentFormData" );
584 $textbox1 = $this->importContentFormData( $request ); #FIXME: what should this return??
585 if ( isset($textbox1) )
586 $this->textbox1
= $textbox1;
587 wfProfileOut( get_class( $this ) . "::importContentFormData" );
590 # Truncate for whole multibyte characters. +5 bytes for ellipsis
591 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
593 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
594 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
596 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
598 # Treat sectiontitle the same way as summary.
599 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
600 # currently doing double duty as both edit summary and section title. Right now this
601 # is just to allow API edits to work around this limitation, but this should be
602 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
603 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 250 );
604 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
606 $this->edittime
= $request->getVal( 'wpEdittime' );
607 $this->starttime
= $request->getVal( 'wpStarttime' );
609 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
611 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
612 // wpTextbox1 field is missing, possibly due to being "too big"
613 // according to some filter rules such as Suhosin's setting for
614 // suhosin.request.max_value_length (d'oh)
615 $this->incompleteForm
= true;
617 // edittime should be one of our last fields; if it's missing,
618 // the submission probably broke somewhere in the middle.
619 $this->incompleteForm
= is_null( $this->edittime
);
621 if ( $this->incompleteForm
) {
622 # If the form is incomplete, force to preview.
623 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
624 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
625 $this->preview
= true;
627 /* Fallback for live preview */
628 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
629 $this->diff
= $request->getCheck( 'wpDiff' );
631 // Remember whether a save was requested, so we can indicate
632 // if we forced preview due to session failure.
633 $this->mTriedSave
= !$this->preview
;
635 if ( $this->tokenOk( $request ) ) {
636 # Some browsers will not report any submit button
637 # if the user hits enter in the comment box.
638 # The unmarked state will be assumed to be a save,
639 # if the form seems otherwise complete.
640 wfDebug( __METHOD__
. ": Passed token check.\n" );
641 } elseif ( $this->diff
) {
642 # Failed token check, but only requested "Show Changes".
643 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
645 # Page might be a hack attempt posted from
646 # an external site. Preview instead of saving.
647 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
648 $this->preview
= true;
651 $this->save
= !$this->preview
&& !$this->diff
;
652 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
653 $this->edittime
= null;
656 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
657 $this->starttime
= null;
660 $this->recreate
= $request->getCheck( 'wpRecreate' );
662 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
663 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
665 # Don't force edit summaries when a user is editing their own user or talk page
666 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
667 $this->mTitle
->getText() == $wgUser->getName() )
669 $this->allowBlankSummary
= true;
671 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary' );
674 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
676 # Not a posted form? Start with nothing.
677 wfDebug( __METHOD__
. ": Not a posted form.\n" );
678 $this->textbox1
= ''; #FIXME: track content object
680 $this->sectiontitle
= '';
681 $this->edittime
= '';
682 $this->starttime
= wfTimestampNow();
684 $this->preview
= false;
687 $this->minoredit
= false;
688 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
689 $this->recreate
= false;
691 // When creating a new section, we can preload a section title by passing it as the
692 // preloadtitle parameter in the URL (Bug 13100)
693 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
694 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
695 // Once wpSummary isn't being use for setting section titles, we should delete this.
696 $this->summary
= $request->getVal( 'preloadtitle' );
698 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
699 $this->summary
= $request->getText( 'summary' );
700 if ( $this->summary
!== '' ) {
701 $this->hasPresetSummary
= true;
705 if ( $request->getVal( 'minor' ) ) {
706 $this->minoredit
= true;
710 $this->oldid
= $request->getInt( 'oldid' );
712 $this->bot
= $request->getBool( 'bot', true );
713 $this->nosummary
= $request->getBool( 'nosummary' );
715 $content_handler = ContentHandler
::getForTitle( $this->mTitle
);
716 $this->content_model
= $request->getText( 'model', $content_handler->getModelName() ); #may be overridden by revision
717 $this->content_format
= $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
719 #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
720 #TODO: check if the desired content model supports the given content format!
722 $this->live
= $request->getCheck( 'live' );
723 $this->editintro
= $request->getText( 'editintro',
724 // Custom edit intro for new sections
725 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
727 // Allow extensions to modify form data
728 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
730 wfProfileOut( __METHOD__
);
734 * Subpage overridable method for extracting the page content data from the
735 * posted form to be placed in $this->textbox1, if using customized input
736 * this method should be overrided and return the page text that will be used
737 * for saving, preview parsing and so on...
739 * @param $request WebRequest
741 protected function importContentFormData( &$request ) {
742 return; // Don't do anything, EditPage already extracted wpTextbox1
746 * Initialise form fields in the object
747 * Called on the first invocation, e.g. when a user clicks an edit link
748 * @return bool -- if the requested section is valid
750 function initialiseForm() {
752 $this->edittime
= $this->mArticle
->getTimestamp();
754 $content = $this->getContentObject( false ); #TODO: track content object?!
755 $this->textbox1
= $content->serialize( $this->content_format
);
757 // activate checkboxes if user wants them to be always active
758 # Sort out the "watch" checkbox
759 if ( $wgUser->getOption( 'watchdefault' ) ) {
761 $this->watchthis
= true;
762 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
764 $this->watchthis
= true;
765 } elseif ( $this->mTitle
->userIsWatching() ) {
767 $this->watchthis
= true;
769 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
770 $this->minoredit
= true;
772 if ( $this->textbox1
=== false ) {
780 * Fetch initial editing page content.
782 * @param $def_text string
783 * @return mixed string on success, $def_text for invalid sections
785 * @deprecated since 1.20
787 function getContent( $def_text = false ) { #FIXME: deprecated, replace usage!
788 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
789 $def_content = ContentHandler
::makeContent( $def_text, $this->getTitle() );
791 $def_content = false;
794 $content = $this->getContentObject( $def_content );
796 return $content->serialize( $this->content_format
); #XXX: really use serialized form? use ContentHandler::getContentText() instead?
799 private function getContentObject( $def_content = null ) { #FIXME: use this!
800 global $wgOut, $wgRequest;
802 wfProfileIn( __METHOD__
);
806 // For message page not locally set, use the i18n message.
807 // For other non-existent articles, use preload text if any.
808 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
809 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
810 # If this is a system message, get the default text.
811 $msg = $this->mTitle
->getDefaultMessageText();
813 $content = new WikitextContent($msg); //XXX: really hardcode wikitext here?
815 if ( $content === false ) {
816 # If requested, preload some text.
817 $preload = $wgRequest->getVal( 'preload',
818 // Custom preload text for new sections
819 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
821 $content = $this->getPreloadedContent( $preload );
823 // For existing pages, get text based on "undo" or section parameters.
825 if ( $this->section
!= '' ) {
826 // Get section edit text (returns $def_text for invalid sections)
827 $orig = $this->getOriginalContent();
828 $content = $orig ?
$orig->getSection( $this->section
) : null;
830 if ( !$content ) $content = $def_content;
832 $undoafter = $wgRequest->getInt( 'undoafter' );
833 $undo = $wgRequest->getInt( 'undo' );
835 if ( $undo > 0 && $undoafter > 0 ) {
836 if ( $undo < $undoafter ) {
837 # If they got undoafter and undo round the wrong way, switch them
838 list( $undo, $undoafter ) = array( $undoafter, $undo );
841 $undorev = Revision
::newFromId( $undo );
842 $oldrev = Revision
::newFromId( $undoafter );
844 # Sanity check, make sure it's the right page,
845 # the revisions exist and they were not deleted.
846 # Otherwise, $content will be left as-is.
847 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
848 $undorev->getPage() == $oldrev->getPage() &&
849 $undorev->getPage() == $this->mTitle
->getArticleID() &&
850 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
851 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
853 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
855 if ( $content === false ) {
856 # Warn the user that something went wrong
857 $undoMsg = 'failure';
859 # Inform the user of our success and set an automatic edit summary
860 $undoMsg = 'success';
862 # If we just undid one rev, use an autosummary
863 $firstrev = $oldrev->getNext();
864 if ( $firstrev->getId() == $undo ) {
865 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
866 if ( $this->summary
=== '' ) {
867 $this->summary
= $undoSummary;
869 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
871 $this->undidRev
= $undo;
873 $this->formtype
= 'diff';
876 // Failed basic sanity checks.
877 // Older revisions may have been removed since the link
878 // was created, or we may simply have got bogus input.
882 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
883 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
884 wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
887 if ( $content === false ) {
888 $content = $this->getOriginalContent();
893 wfProfileOut( __METHOD__
);
898 * Get the content of the wanted revision, without section extraction.
900 * The result of this function can be used to compare user's input with
901 * section replaced in its context (using WikiPage::replaceSection())
902 * to the original text of the edit.
904 * When a missing revision is
905 * encountered, the result will be an empty Content object.
910 private function getOriginalContent() { #FIXME: use Content! set content_model and content_format!
911 if ( $this->section
== 'new' ) {
912 return $this->getCurrentContent();
914 $revision = $this->mArticle
->getRevisionFetched();
915 if ( $revision === null ) {
916 if ( !$this->content_model
) $this->content_model
= $this->getTitle()->getContentModelName();
917 $handler = ContentHandler
::getForModelName( $this->content_model
);
919 return $handler->emptyContent();
922 $content = $revision->getContent();
927 * Get the current content of the page. This is basically similar to
928 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
929 * content object is returned instead of null.
934 private function getCurrentContent() {
935 $rev = $this->mArticle
->getRevision();
936 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
938 if ( $content === false ||
$content === null ) {
939 if ( !$this->content_model
) $this->content_model
= $this->getTitle()->getContentModelName();
940 $handler = ContentHandler
::getForModelName( $this->content_model
);
942 return $handler->emptyContent();
944 #FIXME: nasty side-effect!
945 $this->content_model
= $rev->getContentModelName();
946 $this->content_format
= $rev->getContentFormat();
953 * Use this method before edit() to preload some text into the edit box
955 * @param $text string
956 * @deprecated since 1.20
958 public function setPreloadedText( $text ) { #FIXME: deprecated, use setPreloadedContent()
959 wfDeprecated( __METHOD__
, "1.20" );
961 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
963 $this->setPreloadedContent( $content );
967 * Use this method before edit() to preload some content into the edit box
969 * @param $content Content
971 public function setPreloadedContent( Content
$content ) { #FIXME: use this!
972 $this->mPreloadedContent
= $content;
976 * Get the contents to be preloaded into the box, either set by
977 * an earlier setPreloadText() or by loading the given page.
979 * @param $preload String: representing the title to preload from.
981 * @deprecated since 1.20
983 protected function getPreloadedText( $preload ) { #FIXME: B/C only, replace usage!
984 wfDeprecated( __METHOD__
, "1.20" );
986 $content = $this->getPreloadedContent( $preload );
987 $text = $content->serialize( $this->content_format
); #XXX: really use serialized form? use ContentHandler::getContentText() instead?!
992 protected function getPreloadedContent( $preload ) { #FIXME: use this!
995 if ( !empty( $this->mPreloadContent
) ) {
996 return $this->mPreloadContent
;
999 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1001 if ( $preload === '' ) {
1002 return $handler->emptyContent();
1005 $title = Title
::newFromText( $preload );
1006 # Check for existence to avoid getting MediaWiki:Noarticletext
1007 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
1008 return $handler->emptyContent();
1011 $page = WikiPage
::factory( $title );
1012 if ( $page->isRedirect() ) {
1013 $title = $page->getRedirectTarget();
1015 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
1016 return $handler->emptyContent();
1018 $page = WikiPage
::factory( $title );
1021 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1022 $content = $page->getContent( Revision
::RAW
);
1024 return $content->preloadTransform( $title, $parserOptions );
1028 * Make sure the form isn't faking a user's credentials.
1030 * @param $request WebRequest
1034 function tokenOk( &$request ) {
1036 $token = $request->getVal( 'wpEditToken' );
1037 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1038 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1039 return $this->mTokenOk
;
1043 * Attempt submission
1044 * @return bool false if output is done, true if the rest of the form should be displayed
1046 function attemptSave() {
1047 global $wgUser, $wgOut;
1049 $resultDetails = false;
1050 # Allow bots to exempt some edits from bot flagging
1051 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1052 $status = $this->internalAttemptSave( $resultDetails, $bot );
1053 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1055 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1056 $this->didSave
= true;
1059 switch ( $status->value
) {
1060 case self
::AS_HOOK_ERROR_EXPECTED
:
1061 case self
::AS_CONTENT_TOO_BIG
:
1062 case self
::AS_ARTICLE_WAS_DELETED
:
1063 case self
::AS_CONFLICT_DETECTED
:
1064 case self
::AS_SUMMARY_NEEDED
:
1065 case self
::AS_TEXTBOX_EMPTY
:
1066 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1070 case self
::AS_HOOK_ERROR
:
1071 case self
::AS_FILTERING
:
1074 case self
::AS_PARSE_ERROR
:
1075 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>');
1076 #FIXME: cause editform to be shown again, not just an error!
1079 case self
::AS_SUCCESS_NEW_ARTICLE
:
1080 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1081 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1082 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1085 case self
::AS_SUCCESS_UPDATE
:
1087 $sectionanchor = $resultDetails['sectionanchor'];
1089 // Give extensions a chance to modify URL query on update
1090 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1092 if ( $resultDetails['redirect'] ) {
1093 if ( $extraQuery == '' ) {
1094 $extraQuery = 'redirect=no';
1096 $extraQuery = 'redirect=no&' . $extraQuery;
1099 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1102 case self
::AS_BLANK_ARTICLE
:
1103 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1106 case self
::AS_SPAM_ERROR
:
1107 $this->spamPageWithContent( $resultDetails['spam'] );
1110 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1111 throw new UserBlockedError( $wgUser->getBlock() );
1113 case self
::AS_IMAGE_REDIRECT_ANON
:
1114 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1115 throw new PermissionsError( 'upload' );
1117 case self
::AS_READ_ONLY_PAGE_ANON
:
1118 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1119 throw new PermissionsError( 'edit' );
1121 case self
::AS_READ_ONLY_PAGE
:
1122 throw new ReadOnlyError
;
1124 case self
::AS_RATE_LIMITED
:
1125 throw new ThrottledError();
1127 case self
::AS_NO_CREATE_PERMISSION
:
1128 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1129 throw new PermissionsError( $permission );
1136 * Attempt submission (no UI)
1141 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1143 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1144 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1145 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1147 function internalAttemptSave( &$result, $bot = false ) {
1148 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
1149 global $wgMaxArticleSize;
1151 $status = Status
::newGood();
1153 wfProfileIn( __METHOD__
);
1154 wfProfileIn( __METHOD__
. '-checks' );
1156 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1157 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1158 $status->fatal( 'hookaborted' );
1159 $status->value
= self
::AS_HOOK_ERROR
;
1160 wfProfileOut( __METHOD__
. '-checks' );
1161 wfProfileOut( __METHOD__
);
1165 # Check image redirect
1166 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1167 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&& #FIXME: use content handler to check for redirect
1168 !$wgUser->isAllowed( 'upload' ) ) {
1169 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1170 $status->setResult( false, $code );
1172 wfProfileOut( __METHOD__
. '-checks' );
1173 wfProfileOut( __METHOD__
);
1179 $match = self
::matchSummarySpamRegex( $this->summary
);
1180 if ( $match === false ) {
1181 $match = self
::matchSpamRegex( $this->textbox1
);
1183 if ( $match !== false ) {
1184 $result['spam'] = $match;
1185 $ip = $wgRequest->getIP();
1186 $pdbk = $this->mTitle
->getPrefixedDBkey();
1187 $match = str_replace( "\n", '', $match );
1188 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1189 $status->fatal( 'spamprotectionmatch', $match );
1190 $status->value
= self
::AS_SPAM_ERROR
;
1191 wfProfileOut( __METHOD__
. '-checks' );
1192 wfProfileOut( __METHOD__
);
1195 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
1196 # Error messages or other handling should be performed by the filter function
1197 $status->setResult( false, self
::AS_FILTERING
);
1198 wfProfileOut( __METHOD__
. '-checks' );
1199 wfProfileOut( __METHOD__
);
1202 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1203 # Error messages etc. could be handled within the hook...
1204 $status->fatal( 'hookaborted' );
1205 $status->value
= self
::AS_HOOK_ERROR
;
1206 wfProfileOut( __METHOD__
. '-checks' );
1207 wfProfileOut( __METHOD__
);
1209 } elseif ( $this->hookError
!= '' ) {
1210 # ...or the hook could be expecting us to produce an error
1211 $status->fatal( 'hookaborted' );
1212 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1213 wfProfileOut( __METHOD__
. '-checks' );
1214 wfProfileOut( __METHOD__
);
1218 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1219 // Auto-block user's IP if the account was "hard" blocked
1220 $wgUser->spreadAnyEditBlock();
1221 # Check block state against master, thus 'false'.
1222 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1223 wfProfileOut( __METHOD__
. '-checks' );
1224 wfProfileOut( __METHOD__
);
1228 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1229 if ( $this->kblength
> $wgMaxArticleSize ) {
1230 // Error will be displayed by showEditForm()
1231 $this->tooBig
= true;
1232 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1233 wfProfileOut( __METHOD__
. '-checks' );
1234 wfProfileOut( __METHOD__
);
1238 if ( !$wgUser->isAllowed( 'edit' ) ) {
1239 if ( $wgUser->isAnon() ) {
1240 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1241 wfProfileOut( __METHOD__
. '-checks' );
1242 wfProfileOut( __METHOD__
);
1245 $status->fatal( 'readonlytext' );
1246 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1247 wfProfileOut( __METHOD__
. '-checks' );
1248 wfProfileOut( __METHOD__
);
1253 if ( wfReadOnly() ) {
1254 $status->fatal( 'readonlytext' );
1255 $status->value
= self
::AS_READ_ONLY_PAGE
;
1256 wfProfileOut( __METHOD__
. '-checks' );
1257 wfProfileOut( __METHOD__
);
1260 if ( $wgUser->pingLimiter() ) {
1261 $status->fatal( 'actionthrottledtext' );
1262 $status->value
= self
::AS_RATE_LIMITED
;
1263 wfProfileOut( __METHOD__
. '-checks' );
1264 wfProfileOut( __METHOD__
);
1268 # If the article has been deleted while editing, don't save it without
1270 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1271 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1272 wfProfileOut( __METHOD__
. '-checks' );
1273 wfProfileOut( __METHOD__
);
1277 wfProfileOut( __METHOD__
. '-checks' );
1279 # If article is new, insert it.
1280 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1281 $new = ( $aid == 0 );
1285 // Late check for create permission, just in case *PARANOIA*
1286 if ( !$this->mTitle
->userCan( 'create' ) ) {
1287 $status->fatal( 'nocreatetext' );
1288 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1289 wfDebug( __METHOD__
. ": no create permission\n" );
1290 wfProfileOut( __METHOD__
);
1294 # Don't save a new article if it's blank.
1295 if ( $this->textbox1
== '' ) {
1296 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1297 wfProfileOut( __METHOD__
);
1301 // Run post-section-merge edit filter
1302 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1303 # Error messages etc. could be handled within the hook...
1304 $status->fatal( 'hookaborted' );
1305 $status->value
= self
::AS_HOOK_ERROR
;
1306 wfProfileOut( __METHOD__
);
1308 } elseif ( $this->hookError
!= '' ) {
1309 # ...or the hook could be expecting us to produce an error
1310 $status->fatal( 'hookaborted' );
1311 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1312 wfProfileOut( __METHOD__
);
1316 $content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
);
1318 # Handle the user preference to force summaries here. Check if it's not a redirect.
1319 if ( !$this->allowBlankSummary
&& !$content->isRedirect() ) {
1320 if ( md5( $this->summary
) == $this->autoSumm
) {
1321 $this->missingSummary
= true;
1322 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1323 $status->value
= self
::AS_SUMMARY_NEEDED
;
1324 wfProfileOut( __METHOD__
);
1329 $result['sectionanchor'] = '';
1330 if ( $this->section
== 'new' ) {
1331 if ( $this->sectiontitle
!== '' ) {
1332 // Insert the section title above the content.
1333 $content = $content->addSectionHeader( $this->sectiontitle
);
1335 // Jump to the new section
1336 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1338 // If no edit summary was specified, create one automatically from the section
1339 // title and have it link to the new section. Otherwise, respect the summary as
1341 if ( $this->summary
=== '' ) {
1342 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1343 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1345 } elseif ( $this->summary
!== '' ) {
1346 // Insert the section title above the content.
1347 $content = $content->addSectionHeader( $this->sectiontitle
);
1349 // Jump to the new section
1350 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1352 // Create a link to the new section from the edit summary.
1353 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1354 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1358 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1362 # Article exists. Check for edit conflict.
1364 $this->mArticle
->clear(); # Force reload of dates, etc.
1365 $timestamp = $this->mArticle
->getTimestamp();
1367 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1369 if ( $timestamp != $this->edittime
) {
1370 $this->isConflict
= true;
1371 if ( $this->section
== 'new' ) {
1372 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1373 $this->mArticle
->getComment() == $this->summary
) {
1374 // Probably a duplicate submission of a new comment.
1375 // This can happen when squid resends a request after
1376 // a timeout but the first one actually went through.
1377 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1379 // New comment; suppress conflict.
1380 $this->isConflict
= false;
1381 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1383 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1384 # Suppress edit conflict with self, except for section edits where merging is required.
1385 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1386 $this->isConflict
= false;
1388 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1393 $textbox_content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
);
1396 if ( $this->isConflict
) {
1397 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1399 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1401 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1403 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1406 if ( is_null( $content ) ) {
1407 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1408 $this->isConflict
= true;
1409 $content = $textbox_content; // do not try to merge here!
1410 } elseif ( $this->isConflict
) {
1412 if ( $this->mergeChangesIntoContent( $textbox_content ) ) {
1413 // Successful merge! Maybe we should tell the user the good news?
1414 $content = $textbox_content;
1415 $this->isConflict
= false;
1416 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1418 $this->section
= '';
1419 #$this->textbox1 = $text; #redundant, nothing to do here?
1420 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1424 if ( $this->isConflict
) {
1425 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1426 wfProfileOut( __METHOD__
);
1430 // Run post-section-merge edit filter
1431 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $content->serialize( $this->content_format
), &$this->hookError
, $this->summary
) )
1432 ||
!wfRunHooks( 'EditFilterMergedContent', array( $this, $content, &$this->hookError
, $this->summary
) ) ) { #FIXME: document new hook
1433 # Error messages etc. could be handled within the hook...
1434 $status->fatal( 'hookaborted' );
1435 $status->value
= self
::AS_HOOK_ERROR
;
1436 wfProfileOut( __METHOD__
);
1438 } elseif ( $this->hookError
!= '' ) {
1439 # ...or the hook could be expecting us to produce an error
1440 $status->fatal( 'hookaborted' );
1441 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1442 wfProfileOut( __METHOD__
);
1446 # Handle the user preference to force summaries here, but not for null edits
1447 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1448 && !$content->equals( $this->getOriginalContent() )
1449 && !$content->isRedirect() ) # check if it's not a redirect
1451 if ( md5( $this->summary
) == $this->autoSumm
) {
1452 $this->missingSummary
= true;
1453 $status->fatal( 'missingsummary' );
1454 $status->value
= self
::AS_SUMMARY_NEEDED
;
1455 wfProfileOut( __METHOD__
);
1460 # And a similar thing for new sections
1461 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1462 if ( trim( $this->summary
) == '' ) {
1463 $this->missingSummary
= true;
1464 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1465 $status->value
= self
::AS_SUMMARY_NEEDED
;
1466 wfProfileOut( __METHOD__
);
1472 wfProfileIn( __METHOD__
. '-sectionanchor' );
1473 $sectionanchor = '';
1474 if ( $this->section
== 'new' ) {
1475 if ( $this->textbox1
== '' ) {
1476 $this->missingComment
= true;
1477 $status->fatal( 'missingcommenttext' );
1478 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1479 wfProfileOut( __METHOD__
. '-sectionanchor' );
1480 wfProfileOut( __METHOD__
);
1483 if ( $this->sectiontitle
!== '' ) {
1484 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1485 // If no edit summary was specified, create one automatically from the section
1486 // title and have it link to the new section. Otherwise, respect the summary as
1488 if ( $this->summary
=== '' ) {
1489 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1490 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1492 } elseif ( $this->summary
!== '' ) {
1493 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1494 # This is a new section, so create a link to the new section
1495 # in the revision summary.
1496 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1497 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1499 } elseif ( $this->section
!= '' ) {
1500 # Try to get a section anchor from the section source, redirect to edited section if header found
1501 # XXX: might be better to integrate this into Article::replaceSection
1502 # for duplicate heading checking and maybe parsing
1503 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1504 # we can't deal with anchors, includes, html etc in the header for now,
1505 # headline would need to be parsed to improve this
1506 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1507 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1510 $result['sectionanchor'] = $sectionanchor;
1511 wfProfileOut( __METHOD__
. '-sectionanchor' );
1513 // Save errors may fall down to the edit form, but we've now
1514 // merged the section into full text. Clear the section field
1515 // so that later submission of conflict forms won't try to
1516 // replace that into a duplicated mess.
1517 $this->textbox1
= $content->serialize( $this->content_format
);
1518 $this->section
= '';
1520 $status->value
= self
::AS_SUCCESS_UPDATE
;
1523 // Check for length errors again now that the section is merged in
1524 $this->kblength
= (int)( strlen( $content->serialize( $this->content_format
) ) / 1024 );
1525 if ( $this->kblength
> $wgMaxArticleSize ) {
1526 $this->tooBig
= true;
1527 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1528 wfProfileOut( __METHOD__
);
1532 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1533 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1534 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1535 ( $bot ? EDIT_FORCE_BOT
: 0 );
1537 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags, false, null, $this->content_format
);
1539 if ( $doEditStatus->isOK() ) {
1540 $result['redirect'] = $content->isRedirect();
1541 $this->commitWatch();
1542 wfProfileOut( __METHOD__
);
1545 $this->isConflict
= true;
1546 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1547 wfProfileOut( __METHOD__
);
1548 return $doEditStatus;
1550 } catch (MWContentSerializationException
$ex) {
1551 $status->fatal( 'content-failed-to-parse', $this->content_model
, $this->content_format
, $ex->getMessage() );
1552 $status->value
= self
::AS_PARSE_ERROR
;
1553 wfProfileOut( __METHOD__
);
1559 * Commit the change of watch status
1561 protected function commitWatch() {
1563 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1564 $dbw = wfGetDB( DB_MASTER
);
1565 $dbw->begin( __METHOD__
);
1566 if ( $this->watchthis
) {
1567 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1569 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1571 $dbw->commit( __METHOD__
);
1576 * Check if no edits were made by other users since
1577 * the time a user started editing the page. Limit to
1578 * 50 revisions for the sake of performance.
1581 * @param $edittime string
1585 protected function userWasLastToEdit( $id, $edittime ) {
1586 if ( !$id ) return false;
1587 $dbw = wfGetDB( DB_MASTER
);
1588 $res = $dbw->select( 'revision',
1591 'rev_page' => $this->mTitle
->getArticleID(),
1592 'rev_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $edittime ) )
1595 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1596 foreach ( $res as $row ) {
1597 if ( $row->rev_user
!= $id ) {
1608 * @parma $editText string
1611 * @deprecated since 1.20
1613 function mergeChangesInto( &$editText ){
1614 wfDebug( __METHOD__
, "1.20" );
1616 $editContent = ContentHandler
::makeContent( $editText, $this->getTitle(), $this->content_model
, $this->content_format
);
1618 $ok = $this->mergeChangesIntoContent( $editContent );
1621 $editText = $editContent->serialize( $this->content_format
); #XXX: really serialize?!
1632 * @parma $editText string
1637 private function mergeChangesIntoContent( &$editContent ){
1638 wfProfileIn( __METHOD__
);
1640 $db = wfGetDB( DB_MASTER
);
1642 // This is the revision the editor started from
1643 $baseRevision = $this->getBaseRevision();
1644 if ( is_null( $baseRevision ) ) {
1645 wfProfileOut( __METHOD__
);
1648 $baseContent = $baseRevision->getContent();
1650 // The current state, we want to merge updates into it
1651 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1652 if ( is_null( $currentRevision ) ) {
1653 wfProfileOut( __METHOD__
);
1656 $currentContent = $currentRevision->getContent();
1658 $handler = ContentHandler
::getForModelName( $baseContent->getModelName() );
1660 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1663 $editContent = $result;
1664 wfProfileOut( __METHOD__
);
1667 wfProfileOut( __METHOD__
);
1675 function getBaseRevision() {
1676 if ( !$this->mBaseRevision
) {
1677 $db = wfGetDB( DB_MASTER
);
1678 $baseRevision = Revision
::loadFromTimestamp(
1679 $db, $this->mTitle
, $this->edittime
);
1680 return $this->mBaseRevision
= $baseRevision;
1682 return $this->mBaseRevision
;
1687 * Check given input text against $wgSpamRegex, and return the text of the first match.
1689 * @param $text string
1691 * @return string|bool matching string or false
1693 public static function matchSpamRegex( $text ) {
1694 global $wgSpamRegex;
1695 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1696 $regexes = (array)$wgSpamRegex;
1697 return self
::matchSpamRegexInternal( $text, $regexes );
1701 * Check given input text against $wgSpamRegex, and return the text of the first match.
1703 * @parma $text string
1705 * @return string|bool matching string or false
1707 public static function matchSummarySpamRegex( $text ) {
1708 global $wgSummarySpamRegex;
1709 $regexes = (array)$wgSummarySpamRegex;
1710 return self
::matchSpamRegexInternal( $text, $regexes );
1714 * @param $text string
1715 * @param $regexes array
1716 * @return bool|string
1718 protected static function matchSpamRegexInternal( $text, $regexes ) {
1719 foreach ( $regexes as $regex ) {
1721 if ( preg_match( $regex, $text, $matches ) ) {
1728 function setHeaders() {
1729 global $wgOut, $wgUser;
1731 $wgOut->addModules( 'mediawiki.action.edit' );
1733 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1734 $wgOut->addModules( 'mediawiki.legacy.preview' );
1736 // Bug #19334: textarea jumps when editing articles in IE8
1737 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1739 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1741 # Enabled article-related sidebar, toplinks, etc.
1742 $wgOut->setArticleRelated( true );
1744 $contextTitle = $this->getContextTitle();
1745 if ( $this->isConflict
) {
1746 $msg = 'editconflict';
1747 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1748 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1750 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1751 'editing' : 'creating';
1753 # Use the title defined by DISPLAYTITLE magic word when present
1754 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1755 if ( $displayTitle === false ) {
1756 $displayTitle = $contextTitle->getPrefixedText();
1758 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1762 * Show all applicable editing introductions
1764 protected function showIntro() {
1765 global $wgOut, $wgUser;
1766 if ( $this->suppressIntro
) {
1770 $namespace = $this->mTitle
->getNamespace();
1772 if ( $namespace == NS_MEDIAWIKI
) {
1773 # Show a warning if editing an interface message
1774 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1775 } else if( $namespace == NS_FILE
) {
1776 # Show a hint to shared repo
1777 $file = wfFindFile( $this->mTitle
);
1778 if( $file && !$file->isLocal() ) {
1779 $descUrl = $file->getDescriptionUrl();
1780 # there must be a description url to show a hint to shared repo
1782 if( !$this->mTitle
->exists() ) {
1783 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1784 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1787 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1788 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1795 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1796 # Show log extract when the user is currently blocked
1797 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1798 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1799 $username = $parts[0];
1800 $user = User
::newFromName( $username, false /* allow IP users*/ );
1801 $ip = User
::isIP( $username );
1802 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1803 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1804 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1805 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1806 LogEventsList
::showLogExtract(
1809 $user->getUserPage(),
1813 'showIfEmpty' => false,
1815 'blocked-notice-logextract',
1816 $user->getName() # Support GENDER in notice
1822 # Try to add a custom edit intro, or use the standard one if this is not possible.
1823 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1824 if ( $wgUser->isLoggedIn() ) {
1825 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1827 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1830 # Give a notice if the user is editing a deleted/moved page...
1831 if ( !$this->mTitle
->exists() ) {
1832 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1833 '', array( 'lim' => 10,
1834 'conds' => array( "log_action != 'revision'" ),
1835 'showIfEmpty' => false,
1836 'msgKey' => array( 'recreate-moveddeleted-warn' ) )
1842 * Attempt to show a custom editing introduction, if supplied
1846 protected function showCustomIntro() {
1847 if ( $this->editintro
) {
1848 $title = Title
::newFromText( $this->editintro
);
1849 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1851 // Added using template syntax, to take <noinclude>'s into account.
1852 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1863 * Send the edit form and related headers to $wgOut
1864 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1865 * during form output near the top, for captchas and the like.
1867 function showEditForm( $formCallback = null ) {
1868 global $wgOut, $wgUser;
1870 wfProfileIn( __METHOD__
);
1872 # need to parse the preview early so that we know which templates are used,
1873 # otherwise users with "show preview after edit box" will get a blank list
1874 # we parse this near the beginning so that setHeaders can do the title
1875 # setting work instead of leaving it in getPreviewText
1876 $previewOutput = '';
1877 if ( $this->formtype
== 'preview' ) {
1878 $previewOutput = $this->getPreviewText();
1881 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
1883 $this->setHeaders();
1885 if ( $this->showHeader() === false ) {
1886 wfProfileOut( __METHOD__
);
1890 $wgOut->addHTML( $this->editFormPageTop
);
1892 if ( $wgUser->getOption( 'previewontop' ) ) {
1893 $this->displayPreviewArea( $previewOutput, true );
1896 $wgOut->addHTML( $this->editFormTextTop
);
1898 $showToolbar = true;
1899 if ( $this->wasDeletedSinceLastEdit() ) {
1900 if ( $this->formtype
== 'save' ) {
1901 // Hide the toolbar and edit area, user can click preview to get it back
1902 // Add an confirmation checkbox and explanation.
1903 $showToolbar = false;
1905 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1906 'deletedwhileediting' );
1910 #FIXME: add EditForm plugin interface and use it here! #FIXME: search for textarea1 and textares2, and allow EditForm to override all uses.
1911 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
1912 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1913 'enctype' => 'multipart/form-data' ) ) );
1915 if ( is_callable( $formCallback ) ) {
1916 call_user_func_array( $formCallback, array( &$wgOut ) );
1919 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1921 // Put these up at the top to ensure they aren't lost on early form submission
1922 $this->showFormBeforeText();
1924 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1925 $username = $this->lastDelete
->user_name
;
1926 $comment = $this->lastDelete
->log_comment
;
1928 // It is better to not parse the comment at all than to have templates expanded in the middle
1929 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1930 $key = $comment === ''
1931 ?
'confirmrecreate-noreason'
1932 : 'confirmrecreate';
1934 '<div class="mw-confirm-recreate">' .
1935 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1936 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1937 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1943 # When the summary is hidden, also hide them on preview/show changes
1944 if( $this->nosummary
) {
1945 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
1948 # If a blank edit summary was previously provided, and the appropriate
1949 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1950 # user being bounced back more than once in the event that a summary
1953 # For a bit more sophisticated detection of blank summaries, hash the
1954 # automatic one and pass that in the hidden field wpAutoSummary.
1955 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
1956 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1959 if ( $this->hasPresetSummary
) {
1960 // If a summary has been preset using &summary= we dont want to prompt for
1961 // a different summary. Only prompt for a summary if the summary is blanked.
1963 $this->autoSumm
= md5( '' );
1966 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1967 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1969 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
1971 $wgOut->addHTML( Html
::hidden( 'format', $this->content_format
) );
1972 $wgOut->addHTML( Html
::hidden( 'model', $this->content_model
) );
1974 if ( $this->section
== 'new' ) {
1975 $this->showSummaryInput( true, $this->summary
);
1976 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1979 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1981 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1982 $wgOut->addHTML( EditPage
::getEditToolbar() );
1985 if ( $this->isConflict
) {
1986 // In an edit conflict bypass the overrideable content form method
1987 // and fallback to the raw wpTextbox1 since editconflicts can't be
1988 // resolved between page source edits and custom ui edits using the
1990 $this->textbox2
= $this->textbox1
;
1992 $content = $this->getCurrentContent();
1993 $this->textbox1
= $content->serialize( $this->content_format
);
1995 $this->showTextbox1();
1997 $this->showContentForm();
2000 $wgOut->addHTML( $this->editFormTextAfterContent
);
2002 $wgOut->addWikiText( $this->getCopywarn() );
2004 $wgOut->addHTML( $this->editFormTextAfterWarn
);
2006 $this->showStandardInputs();
2008 $this->showFormAfterText();
2010 $this->showTosSummary();
2012 $this->showEditTools();
2014 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2016 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2017 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2019 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2020 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2022 if ( $this->isConflict
) {
2023 $this->showConflict();
2026 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2028 if ( !$wgUser->getOption( 'previewontop' ) ) {
2029 $this->displayPreviewArea( $previewOutput, false );
2032 wfProfileOut( __METHOD__
);
2036 * Extract the section title from current section text, if any.
2038 * @param string $text
2039 * @return Mixed|string or false
2041 public static function extractSectionTitle( $text ) {
2042 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2043 if ( !empty( $matches[2] ) ) {
2045 return $wgParser->stripSectionName( trim( $matches[2] ) );
2051 protected function showHeader() {
2052 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2054 if ( $this->mTitle
->isTalkPage() ) {
2055 $wgOut->addWikiMsg( 'talkpagetext' );
2058 # Optional notices on a per-namespace and per-page basis
2059 $editnotice_ns = 'editnotice-' . $this->mTitle
->getNamespace();
2060 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
2061 if ( $editnotice_ns_message->exists() ) {
2062 $wgOut->addWikiText( $editnotice_ns_message->plain() );
2064 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
2065 $parts = explode( '/', $this->mTitle
->getDBkey() );
2066 $editnotice_base = $editnotice_ns;
2067 while ( count( $parts ) > 0 ) {
2068 $editnotice_base .= '-' . array_shift( $parts );
2069 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
2070 if ( $editnotice_base_msg->exists() ) {
2071 $wgOut->addWikiText( $editnotice_base_msg->plain() );
2075 # Even if there are no subpages in namespace, we still don't want / in MW ns.
2076 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
2077 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
2078 if ( $editnoticeMsg->exists() ) {
2079 $wgOut->addWikiText( $editnoticeMsg->plain() );
2083 if ( $this->isConflict
) {
2084 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2085 $this->edittime
= $this->mArticle
->getTimestamp();
2087 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2088 // We use $this->section to much before this and getVal('wgSection') directly in other places
2089 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2090 // Someone is welcome to try refactoring though
2091 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2095 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2096 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2097 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
2098 if ( $sectionTitle !== false ) {
2099 $this->summary
= "/* $sectionTitle */ ";
2104 if ( $this->missingComment
) {
2105 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2108 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2109 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2112 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2113 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2116 if ( $this->hookError
!== '' ) {
2117 $wgOut->addWikiText( $this->hookError
);
2120 if ( !$this->checkUnicodeCompliantBrowser() ) {
2121 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2124 if ( $this->section
!= 'new' ) {
2125 $revision = $this->mArticle
->getRevisionFetched();
2127 // Let sysop know that this will make private content public if saved
2129 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
2130 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2131 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2132 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2135 if ( !$revision->isCurrent() ) {
2136 $this->mArticle
->setOldSubtitle( $revision->getId() );
2137 $wgOut->addWikiMsg( 'editingold' );
2139 } elseif ( $this->mTitle
->exists() ) {
2140 // Something went wrong
2142 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2143 array( 'missing-article', $this->mTitle
->getPrefixedText(),
2144 wfMsgNoTrans( 'missingarticle-rev', $this->oldid
) ) );
2149 if ( wfReadOnly() ) {
2150 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2151 } elseif ( $wgUser->isAnon() ) {
2152 if ( $this->formtype
!= 'preview' ) {
2153 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2155 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2158 if ( $this->isCssJsSubpage
) {
2159 # Check the skin exists
2160 if ( $this->isWrongCaseCssJsPage
) {
2161 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2163 if ( $this->formtype
!== 'preview' ) {
2164 if ( $this->isCssSubpage
)
2165 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2166 if ( $this->isJsSubpage
)
2167 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2172 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2173 # Is the title semi-protected?
2174 if ( $this->mTitle
->isSemiProtected() ) {
2175 $noticeMsg = 'semiprotectedpagewarning';
2177 # Then it must be protected based on static groups (regular)
2178 $noticeMsg = 'protectedpagewarning';
2180 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2181 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2183 if ( $this->mTitle
->isCascadeProtected() ) {
2184 # Is this page under cascading protection from some source pages?
2185 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2186 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2187 $cascadeSourcesCount = count( $cascadeSources );
2188 if ( $cascadeSourcesCount > 0 ) {
2189 # Explain, and list the titles responsible
2190 foreach ( $cascadeSources as $page ) {
2191 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2194 $notice .= '</div>';
2195 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2197 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2198 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2200 'showIfEmpty' => false,
2201 'msgKey' => array( 'titleprotectedwarning' ),
2202 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2205 if ( $this->kblength
=== false ) {
2206 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2209 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2210 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2211 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2213 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2214 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2215 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2222 * Standard summary input and label (wgSummary), abstracted so EditPage
2223 * subclasses may reorganize the form.
2224 * Note that you do not need to worry about the label's for=, it will be
2225 * inferred by the id given to the input. You can remove them both by
2226 * passing array( 'id' => false ) to $userInputAttrs.
2228 * @param $summary string The value of the summary input
2229 * @param $labelText string The html to place inside the label
2230 * @param $inputAttrs array of attrs to use on the input
2231 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2233 * @return array An array in the format array( $label, $input )
2235 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2236 // Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
2237 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2238 'id' => 'wpSummary',
2239 'maxlength' => '200',
2242 'spellcheck' => 'true',
2243 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2245 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2246 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2247 'id' => "wpSummaryLabel"
2252 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2253 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2256 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2258 return array( $label, $input );
2262 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2263 * up top, or false if this is the comment summary
2264 * down below the textarea
2265 * @param $summary String: The text of the summary to display
2268 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2269 global $wgOut, $wgContLang;
2270 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2271 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2272 if ( $isSubjectPreview ) {
2273 if ( $this->nosummary
) {
2277 if ( !$this->mShowSummaryField
) {
2281 $summary = $wgContLang->recodeForEdit( $summary );
2282 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
2283 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2284 $wgOut->addHTML( "{$label} {$input}" );
2288 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2289 * up top, or false if this is the comment summary
2290 * down below the textarea
2291 * @param $summary String: the text of the summary to display
2294 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2295 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2300 if ( $isSubjectPreview )
2301 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2303 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2305 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2306 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2309 protected function showFormBeforeText() {
2311 $section = htmlspecialchars( $this->section
);
2312 $wgOut->addHTML( <<<HTML
2313 <input type='hidden' value="{$section}" name="wpSection" />
2314 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2315 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2316 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2320 if ( !$this->checkUnicodeCompliantBrowser() )
2321 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2324 protected function showFormAfterText() {
2325 global $wgOut, $wgUser;
2327 * To make it harder for someone to slip a user a page
2328 * which submits an edit form to the wiki without their
2329 * knowledge, a random token is associated with the login
2330 * session. If it's not passed back with the submission,
2331 * we won't save the page, or render user JavaScript and
2334 * For anon editors, who may not have a session, we just
2335 * include the constant suffix to prevent editing from
2336 * broken text-mangling proxies.
2338 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2342 * Subpage overridable method for printing the form for page content editing
2343 * By default this simply outputs wpTextbox1
2344 * Subclasses can override this to provide a custom UI for editing;
2345 * be it a form, or simply wpTextbox1 with a modified content that will be
2346 * reverse modified when extracted from the post data.
2347 * Note that this is basically the inverse for importContentFormData
2349 protected function showContentForm() {
2350 $this->showTextbox1();
2354 * Method to output wpTextbox1
2355 * The $textoverride method can be used by subclasses overriding showContentForm
2356 * to pass back to this method.
2358 * @param $customAttribs array of html attributes to use in the textarea
2359 * @param $textoverride String: optional text to override $this->textarea1 with
2361 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2362 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2363 $attribs = array( 'style' => 'display:none;' );
2365 $classes = array(); // Textarea CSS
2366 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2367 # Is the title semi-protected?
2368 if ( $this->mTitle
->isSemiProtected() ) {
2369 $classes[] = 'mw-textarea-sprotected';
2371 # Then it must be protected based on static groups (regular)
2372 $classes[] = 'mw-textarea-protected';
2374 # Is the title cascade-protected?
2375 if ( $this->mTitle
->isCascadeProtected() ) {
2376 $classes[] = 'mw-textarea-cprotected';
2380 $attribs = array( 'tabindex' => 1 );
2382 if ( is_array( $customAttribs ) ) {
2383 $attribs +
= $customAttribs;
2386 if ( count( $classes ) ) {
2387 if ( isset( $attribs['class'] ) ) {
2388 $classes[] = $attribs['class'];
2390 $attribs['class'] = implode( ' ', $classes );
2394 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2397 protected function showTextbox2() {
2398 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2401 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2402 global $wgOut, $wgUser;
2404 $wikitext = $this->safeUnicodeOutput( $text );
2405 if ( strval( $wikitext ) !== '' ) {
2406 // Ensure there's a newline at the end, otherwise adding lines
2408 // But don't add a newline if the ext is empty, or Firefox in XHTML
2409 // mode will show an extra newline. A bit annoying.
2413 $attribs = $customAttribs +
array(
2416 'cols' => $wgUser->getIntOption( 'cols' ),
2417 'rows' => $wgUser->getIntOption( 'rows' ),
2418 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2421 $pageLang = $this->mTitle
->getPageLanguage();
2422 $attribs['lang'] = $pageLang->getCode();
2423 $attribs['dir'] = $pageLang->getDir();
2425 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2428 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2432 $classes[] = 'ontop';
2434 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2436 if ( $this->formtype
!= 'preview' )
2437 $attribs['style'] = 'display: none;';
2439 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2441 if ( $this->formtype
== 'preview' ) {
2442 $this->showPreview( $previewOutput );
2445 $wgOut->addHTML( '</div>' );
2447 if ( $this->formtype
== 'diff' ) {
2453 * Append preview output to $wgOut.
2454 * Includes category rendering if this is a category page.
2456 * @param $text String: the HTML to be output for the preview.
2458 protected function showPreview( $text ) {
2460 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2461 $this->mArticle
->openShowCategory();
2463 # This hook seems slightly odd here, but makes things more
2464 # consistent for extensions.
2465 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2466 $wgOut->addHTML( $text );
2467 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2468 $this->mArticle
->closeShowCategory();
2473 * Get a diff between the current contents of the edit box and the
2474 * version of the page we're editing from.
2476 * If this is a section edit, we'll replace the section as for final
2477 * save and then make a comparison.
2479 function showDiff() {
2480 global $wgUser, $wgContLang, $wgOut;
2482 $oldContent = $this->getOriginalContent();
2484 $textboxContent = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(),
2485 $this->content_model
, $this->content_format
); #XXX: handle parse errors ?
2487 $newContent = $this->mArticle
->replaceSectionContent(
2488 $this->section
, $textboxContent,
2489 $this->summary
, $this->edittime
);
2490 $oldtitlemsg = 'currentrev';
2491 # if message does not exist, show diff against the preloaded default
2492 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2493 $oldtext = $this->mTitle
->getDefaultMessageText();
2494 if( $oldtext !== false ) {
2495 $oldtitlemsg = 'defaultmessagetext';
2498 $oldtext = $this->mArticle
->getRawText();
2500 $newtext = $this->mArticle
->replaceSection(
2501 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2503 # hanlde legacy text-based hook
2504 $newtext_orig = $newContent->serialize( $this->content_format
);
2505 $newtext = $newtext_orig; #clone
2506 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2508 if ( $newtext != $newtext_orig ) {
2509 #if the hook changed the text, create a new Content object accordingly.
2510 $newContent = ContentHandler
::makeContent( $newtext, $this->getTitle(), $newContent->getModelName() ); #XXX: handle parse errors ?
2513 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) ); #FIXME: document new hook
2515 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2516 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2518 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2519 $oldtitle = wfMsgExt( $oldtitlemsg, array( 'parseinline' ) );
2520 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2522 $de = $oldContent->getContentHandler()->getDifferenceEngine( $this->mArticle
->getContext() );
2523 $de->setContent( $oldContent, $newContent );
2525 $difftext = $de->getDiff( $oldtitle, $newtitle );
2526 $de->showDiffStyle();
2531 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2535 * Give a chance for site and per-namespace customizations of
2536 * terms of service summary link that might exist separately
2537 * from the copyright notice.
2539 * This will display between the save button and the edit tools,
2540 * so should remain short!
2542 protected function showTosSummary() {
2543 $msg = 'editpage-tos-summary';
2544 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2545 if ( !wfMessage( $msg )->isDisabled() ) {
2547 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2548 $wgOut->addWikiMsg( $msg );
2549 $wgOut->addHTML( '</div>' );
2553 protected function showEditTools() {
2555 $wgOut->addHTML( '<div class="mw-editTools">' .
2556 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2560 protected function getCopywarn() {
2561 global $wgRightsText;
2562 if ( $wgRightsText ) {
2563 $copywarnMsg = array( 'copyrightwarning',
2564 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2567 $copywarnMsg = array( 'copyrightwarning2',
2568 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2570 // Allow for site and per-namespace customization of contribution/copyright notice.
2571 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2573 return "<div id=\"editpage-copywarn\">\n" .
2574 call_user_func_array( "wfMsgNoTrans", $copywarnMsg ) . "\n</div>";
2577 protected function showStandardInputs( &$tabindex = 2 ) {
2579 $wgOut->addHTML( "<div class='editOptions'>\n" );
2581 if ( $this->section
!= 'new' ) {
2582 $this->showSummaryInput( false, $this->summary
);
2583 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2586 $checkboxes = $this->getCheckboxes( $tabindex,
2587 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2588 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2589 $wgOut->addHTML( "<div class='editButtons'>\n" );
2590 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2592 $cancel = $this->getCancelLink();
2593 if ( $cancel !== '' ) {
2594 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2596 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2597 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2598 htmlspecialchars( wfMsg( 'edithelp' ) ) . '</a> ' .
2599 htmlspecialchars( wfMsg( 'newwindow' ) );
2600 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2601 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2605 * Show an edit conflict. textbox1 is already shown in showEditForm().
2606 * If you want to use another entry point to this function, be careful.
2608 protected function showConflict() {
2611 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2612 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2614 $content1 = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
); #XXX: handle parse errors?
2615 $content2 = ContentHandler
::makeContent( $this->textbox2
, $this->getTitle(), $this->content_model
, $this->content_format
); #XXX: handle parse errors?
2617 $handler = ContentHandler
::getForModelName( $this->content_model
);
2618 $de = $handler->getDifferenceEngine( $this->mArticle
->getContext() );
2619 $de->setContent( $content2, $content1 );
2620 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2622 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2623 $this->showTextbox2();
2630 public function getCancelLink() {
2631 $cancelParams = array();
2632 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2633 $cancelParams['oldid'] = $this->oldid
;
2636 return Linker
::linkKnown(
2637 $this->getContextTitle(),
2638 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2639 array( 'id' => 'mw-editform-cancel' ),
2645 * Returns the URL to use in the form's action attribute.
2646 * This is used by EditPage subclasses when simply customizing the action
2647 * variable in the constructor is not enough. This can be used when the
2648 * EditPage lives inside of a Special page rather than a custom page action.
2650 * @param $title Title object for which is being edited (where we go to for &action= links)
2653 protected function getActionURL( Title
$title ) {
2654 return $title->getLocalURL( array( 'action' => $this->action
) );
2658 * Check if a page was deleted while the user was editing it, before submit.
2659 * Note that we rely on the logging table, which hasn't been always there,
2660 * but that doesn't matter, because this only applies to brand new
2663 protected function wasDeletedSinceLastEdit() {
2664 if ( $this->deletedSinceEdit
!== null ) {
2665 return $this->deletedSinceEdit
;
2668 $this->deletedSinceEdit
= false;
2670 if ( $this->mTitle
->isDeletedQuick() ) {
2671 $this->lastDelete
= $this->getLastDelete();
2672 if ( $this->lastDelete
) {
2673 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2674 if ( $deleteTime > $this->starttime
) {
2675 $this->deletedSinceEdit
= true;
2680 return $this->deletedSinceEdit
;
2683 protected function getLastDelete() {
2684 $dbr = wfGetDB( DB_SLAVE
);
2685 $data = $dbr->selectRow(
2686 array( 'logging', 'user' ),
2697 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2698 'log_title' => $this->mTitle
->getDBkey(),
2699 'log_type' => 'delete',
2700 'log_action' => 'delete',
2701 'user_id=log_user' ),
2703 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2705 // Quick paranoid permission checks...
2706 if ( is_object( $data ) ) {
2707 if ( $data->log_deleted
& LogPage
::DELETED_USER
)
2708 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2709 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2710 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2716 * Get the rendered text for previewing.
2719 function getPreviewText() {
2720 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2722 wfProfileIn( __METHOD__
);
2724 if ( $wgRawHtml && !$this->mTokenOk
) {
2725 // Could be an offsite preview attempt. This is very unsafe if
2726 // HTML is enabled, as it could be an attack.
2728 if ( $this->textbox1
!== '' ) {
2729 // Do not put big scary notice, if previewing the empty
2730 // string, which happens when you initially edit
2731 // a category page, due to automatic preview-on-open.
2732 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2733 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2735 wfProfileOut( __METHOD__
);
2740 $content = ContentHandler
::makeContent( $this->textbox1
, $this->getTitle(), $this->content_model
, $this->content_format
);
2742 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2743 if ( $this->mTokenOkExceptSuffix
) {
2744 $note = wfMsg( 'token_suffix_mismatch' );
2746 $note = wfMsg( 'session_fail_preview' );
2748 } elseif ( $this->incompleteForm
) {
2749 $note = wfMsg( 'edit_form_incomplete' );
2750 } elseif ( $this->isCssJsSubpage ||
$this->mTitle
->isCssOrJsPage() ) {
2751 # if this is a CSS or JS page used in the UI, show a special notice
2752 # XXX: stupid php bug won't let us use $this->getContextTitle()->isCssJsSubpage() here -- This note has been there since r3530. Sure the bug was fixed time ago?
2754 if( $this->mTitle
->isCssJsSubpage() ) {
2756 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2762 if ( $content->getModelName() == CONTENT_MODEL_CSS
) {
2764 } elseif ( $content->getModelName() == CONTENT_MODEL_JAVASCRIPT
) {
2770 # Used messages to make sure grep find them:
2771 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2772 if( $level && $format ) {
2773 $note = "<div id='mw-{$level}{$format}preview'>" . wfMsg( "{$level}{$format}preview" ) . "</div>";
2775 $note = wfMsg( 'previewnote' );
2778 $note = wfMsg( 'previewnote' );
2781 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2782 $parserOptions->setEditSection( false );
2783 $parserOptions->setTidy( true );
2784 $parserOptions->setIsPreview( true );
2785 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2787 $rt = $content->getRedirectChain();
2790 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2793 # If we're adding a comment, we need to show the
2794 # summary as the headline
2795 if ( $this->section
== "new" && $this->summary
!= "" ) {
2796 $content = $content->addSectionHeader( $this->summary
);
2799 $toparse_orig = $content->serialize( $this->content_format
);
2800 $toparse = $toparse_orig;
2801 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2803 if ( $toparse !== $toparse_orig ) {
2804 #hook changed the text, create new Content object
2805 $content = ContentHandler
::makeContent( $toparse, $this->getTitle(), $this->content_model
, $this->content_format
);
2808 wfRunHooks( 'EditPageGetPreviewContent', array( $this, &$content ) ); # FIXME: document new hook
2810 $parserOptions->enableLimitReport();
2812 #XXX: For CSS/JS pages, we should have called the ShowRawCssJs hook here. But it's now deprecated, so never mind
2813 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
2814 $parserOutput = $content->getParserOutput( $this->mTitle
, null, $parserOptions );
2816 $previewHTML = $parserOutput->getText();
2817 $this->mParserOutput
= $parserOutput;
2818 $wgOut->addParserOutputNoText( $parserOutput );
2820 if ( count( $parserOutput->getWarnings() ) ) {
2821 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2824 } catch (MWContentSerializationException
$ex) {
2825 $note .= "\n\n" . wfMsg('content-failed-to-parse', $this->content_model
, $this->content_format
, $ex->getMessage() );
2828 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2829 if ( $this->mTokenOkExceptSuffix
) {
2830 $note = wfMsg( 'token_suffix_mismatch' );
2832 $note = wfMsg( 'session_fail_preview' );
2834 } elseif ( $this->incompleteForm
) {
2835 $note = wfMsg( 'edit_form_incomplete' );
2837 $note = wfMsg( 'previewnote' );
2840 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2841 $parserOptions->setEditSection( false );
2842 $parserOptions->setTidy( true );
2843 $parserOptions->setIsPreview( true );
2844 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
2846 # don't parse non-wikitext pages, show message about preview
2847 # XXX: stupid php bug won't let us use $this->getContextTitle()->isCssJsSubpage() here -- This note has been there since r3530. Sure the bug was fixed time ago?
2849 if ( $this->isCssJsSubpage ||
!$this->mTitle
->isWikitextPage() ) {
2850 if ( $this->mTitle
->isCssJsSubpage() ) {
2852 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
2858 # Used messages to make sure grep find them:
2859 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2861 if ( preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2862 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2863 $class = "mw-code mw-css";
2864 } elseif ( preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2865 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2866 $class = "mw-code mw-js";
2868 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2872 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2873 $previewHTML = $parserOutput->mText
;
2874 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2876 $toparse = $this->textbox1
;
2878 # If we're adding a comment, we need to show the
2879 # summary as the headline
2880 if ( $this->section
== "new" && $this->summary
!= "" ) {
2881 $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $toparse;
2884 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2886 $parserOptions->enableLimitReport();
2888 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle
, $wgUser, $parserOptions );
2889 $parserOutput = $wgParser->parse( $toparse, $this->mTitle
, $parserOptions );
2891 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2893 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2895 $previewHTML = $parserOutput->getText();
2898 $this->mParserOutput
= $parserOutput;
2899 $wgOut->addParserOutputNoText( $parserOutput );
2901 if ( count( $parserOutput->getWarnings() ) ) {
2902 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2906 if ( $this->isConflict
) {
2907 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2909 $conflict = '<hr />';
2912 $previewhead = "<div class='previewnote'>\n" .
2913 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2914 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2916 $pageLang = $this->mTitle
->getPageLanguage();
2917 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2918 'class' => 'mw-content-' . $pageLang->getDir() );
2919 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2921 wfProfileOut( __METHOD__
);
2922 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2928 function getTemplates() {
2929 if ( $this->preview ||
$this->section
!= '' ) {
2930 $templates = array();
2931 if ( !isset( $this->mParserOutput
) ) {
2934 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
2935 foreach ( array_keys( $template ) as $dbk ) {
2936 $templates[] = Title
::makeTitle( $ns, $dbk );
2941 return $this->mTitle
->getTemplateLinksFrom();
2946 * Shows a bulletin board style toolbar for common editing functions.
2947 * It can be disabled in the user preferences.
2948 * The necessary JavaScript code can be found in skins/common/edit.js.
2952 static function getEditToolbar() {
2953 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2954 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2956 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2959 * $toolarray is an array of arrays each of which includes the
2960 * filename of the button image (without path), the opening
2961 * tag, the closing tag, optionally a sample text that is
2962 * inserted between the two when no selection is highlighted
2963 * and. The tip text is shown when the user moves the mouse
2966 * Also here: accesskeys (key), which are not used yet until
2967 * someone can figure out a way to make them work in
2968 * IE. However, we should make sure these keys are not defined
2973 'image' => $wgLang->getImageFile( 'button-bold' ),
2974 'id' => 'mw-editbutton-bold',
2976 'close' => '\'\'\'',
2977 'sample' => wfMsg( 'bold_sample' ),
2978 'tip' => wfMsg( 'bold_tip' ),
2982 'image' => $wgLang->getImageFile( 'button-italic' ),
2983 'id' => 'mw-editbutton-italic',
2986 'sample' => wfMsg( 'italic_sample' ),
2987 'tip' => wfMsg( 'italic_tip' ),
2991 'image' => $wgLang->getImageFile( 'button-link' ),
2992 'id' => 'mw-editbutton-link',
2995 'sample' => wfMsg( 'link_sample' ),
2996 'tip' => wfMsg( 'link_tip' ),
3000 'image' => $wgLang->getImageFile( 'button-extlink' ),
3001 'id' => 'mw-editbutton-extlink',
3004 'sample' => wfMsg( 'extlink_sample' ),
3005 'tip' => wfMsg( 'extlink_tip' ),
3009 'image' => $wgLang->getImageFile( 'button-headline' ),
3010 'id' => 'mw-editbutton-headline',
3013 'sample' => wfMsg( 'headline_sample' ),
3014 'tip' => wfMsg( 'headline_tip' ),
3017 $imagesAvailable ?
array(
3018 'image' => $wgLang->getImageFile( 'button-image' ),
3019 'id' => 'mw-editbutton-image',
3020 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3022 'sample' => wfMsg( 'image_sample' ),
3023 'tip' => wfMsg( 'image_tip' ),
3026 $imagesAvailable ?
array(
3027 'image' => $wgLang->getImageFile( 'button-media' ),
3028 'id' => 'mw-editbutton-media',
3029 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3031 'sample' => wfMsg( 'media_sample' ),
3032 'tip' => wfMsg( 'media_tip' ),
3036 'image' => $wgLang->getImageFile( 'button-math' ),
3037 'id' => 'mw-editbutton-math',
3039 'close' => "</math>",
3040 'sample' => wfMsg( 'math_sample' ),
3041 'tip' => wfMsg( 'math_tip' ),
3045 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3046 'id' => 'mw-editbutton-nowiki',
3047 'open' => "<nowiki>",
3048 'close' => "</nowiki>",
3049 'sample' => wfMsg( 'nowiki_sample' ),
3050 'tip' => wfMsg( 'nowiki_tip' ),
3054 'image' => $wgLang->getImageFile( 'button-sig' ),
3055 'id' => 'mw-editbutton-signature',
3059 'tip' => wfMsg( 'sig_tip' ),
3063 'image' => $wgLang->getImageFile( 'button-hr' ),
3064 'id' => 'mw-editbutton-hr',
3065 'open' => "\n----\n",
3068 'tip' => wfMsg( 'hr_tip' ),
3073 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3074 foreach ( $toolarray as $tool ) {
3080 $image = $wgStylePath . '/common/images/' . $tool['image'],
3081 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3082 // Older browsers show a "speedtip" type message only for ALT.
3083 // Ideally these should be different, realistically they
3084 // probably don't need to be.
3085 $tip = $tool['tip'],
3086 $open = $tool['open'],
3087 $close = $tool['close'],
3088 $sample = $tool['sample'],
3089 $cssId = $tool['id'],
3092 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3095 // This used to be called on DOMReady from mediawiki.action.edit, which
3096 // ended up causing race conditions with the setup code above.
3098 "// Create button bar\n" .
3099 "$(function() { mw.toolbar.init(); } );\n";
3102 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3104 $toolbar = '<div id="toolbar"></div>';
3106 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3112 * Returns an array of html code of the following checkboxes:
3115 * @param $tabindex int Current tabindex
3116 * @param $checked Array of checkbox => bool, where bool indicates the checked
3117 * status of the checkbox
3121 public function getCheckboxes( &$tabindex, $checked ) {
3124 $checkboxes = array();
3126 // don't show the minor edit checkbox if it's a new page or section
3127 if ( !$this->isNew
) {
3128 $checkboxes['minor'] = '';
3129 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
3130 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3132 'tabindex' => ++
$tabindex,
3133 'accesskey' => wfMsg( 'accesskey-minoredit' ),
3134 'id' => 'wpMinoredit',
3136 $checkboxes['minor'] =
3137 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3138 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3139 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3140 ">{$minorLabel}</label>";
3144 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
3145 $checkboxes['watch'] = '';
3146 if ( $wgUser->isLoggedIn() ) {
3148 'tabindex' => ++
$tabindex,
3149 'accesskey' => wfMsg( 'accesskey-watch' ),
3150 'id' => 'wpWatchthis',
3152 $checkboxes['watch'] =
3153 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3154 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3155 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3156 ">{$watchLabel}</label>";
3158 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3163 * Returns an array of html code of the following buttons:
3164 * save, diff, preview and live
3166 * @param $tabindex int Current tabindex
3170 public function getEditButtons( &$tabindex ) {
3177 'tabindex' => ++
$tabindex,
3178 'value' => wfMsg( 'savearticle' ),
3179 'accesskey' => wfMsg( 'accesskey-save' ),
3180 'title' => wfMsg( 'tooltip-save' ) . ' [' . wfMsg( 'accesskey-save' ) . ']',
3182 $buttons['save'] = Xml
::element( 'input', $temp, '' );
3184 ++
$tabindex; // use the same for preview and live preview
3186 'id' => 'wpPreview',
3187 'name' => 'wpPreview',
3189 'tabindex' => $tabindex,
3190 'value' => wfMsg( 'showpreview' ),
3191 'accesskey' => wfMsg( 'accesskey-preview' ),
3192 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
3194 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3195 $buttons['live'] = '';
3201 'tabindex' => ++
$tabindex,
3202 'value' => wfMsg( 'showdiff' ),
3203 'accesskey' => wfMsg( 'accesskey-diff' ),
3204 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
3206 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3208 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3213 * Output preview text only. This can be sucked into the edit page
3214 * via JavaScript, and saves the server time rendering the skin as
3215 * well as theoretically being more robust on the client (doesn't
3216 * disturb the edit box's undo history, won't eat your text on
3219 * @todo This doesn't include category or interlanguage links.
3220 * Would need to enhance it a bit, <s>maybe wrap them in XML
3221 * or something...</s> that might also require more skin
3222 * initialization, so check whether that's a problem.
3224 function livePreview() {
3227 header( 'Content-type: text/xml; charset=utf-8' );
3228 header( 'Cache-control: no-cache' );
3230 $previewText = $this->getPreviewText();
3231 #$categories = $skin->getCategoryLinks();
3234 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3235 Xml
::tags( 'livepreview', null,
3236 Xml
::element( 'preview', null, $previewText )
3237 #. Xml::element( 'category', null, $categories )
3243 * Call the stock "user is blocked" page
3245 * @deprecated in 1.19; throw an exception directly instead
3247 function blockedPage() {
3248 wfDeprecated( __METHOD__
, '1.19' );
3251 throw new UserBlockedError( $wgUser->getBlock() );
3255 * Produce the stock "please login to edit pages" page
3257 * @deprecated in 1.19; throw an exception directly instead
3259 function userNotLoggedInPage() {
3260 wfDeprecated( __METHOD__
, '1.19' );
3261 throw new PermissionsError( 'edit' );
3265 * Show an error page saying to the user that he has insufficient permissions
3266 * to create a new page
3268 * @deprecated in 1.19; throw an exception directly instead
3270 function noCreatePermission() {
3271 wfDeprecated( __METHOD__
, '1.19' );
3272 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3273 throw new PermissionsError( $permission );
3277 * Creates a basic error page which informs the user that
3278 * they have attempted to edit a nonexistent section.
3280 function noSuchSectionPage() {
3283 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3285 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
3286 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3287 $wgOut->addHTML( $res );
3289 $wgOut->returnToMain( false, $this->mTitle
);
3293 * Produce the stock "your edit contains spam" page
3295 * @param $match string Text which triggered one or more filters
3296 * @deprecated since 1.17 Use method spamPageWithContent() instead
3298 static function spamPage( $match = false ) {
3299 wfDeprecated( __METHOD__
, '1.17' );
3301 global $wgOut, $wgTitle;
3303 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3305 $wgOut->addHTML( '<div id="spamprotected">' );
3306 $wgOut->addWikiMsg( 'spamprotectiontext' );
3308 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3310 $wgOut->addHTML( '</div>' );
3312 $wgOut->returnToMain( false, $wgTitle );
3316 * Show "your edit contains spam" page with your diff and text
3318 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3320 public function spamPageWithContent( $match = false ) {
3321 global $wgOut, $wgLang;
3322 $this->textbox2
= $this->textbox1
;
3324 if( is_array( $match ) ){
3325 $match = $wgLang->listToText( $match );
3327 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3329 $wgOut->addHTML( '<div id="spamprotected">' );
3330 $wgOut->addWikiMsg( 'spamprotectiontext' );
3332 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3334 $wgOut->addHTML( '</div>' );
3336 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3338 $handler = ContentHandler
::getForTitle( $this->getTitle() );
3339 $de = $handler->getDifferenceEngine( $this->mArticle
->getContext() );
3341 $content2 = ContentHandler
::makeContent( $this->textbox2
, $this->getTitle(), $this->content_model
, $this->content_format
); #XXX: handle parse errors?
3342 $de->setContent( $this->getCurrentContent(), $content2 );
3344 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
3346 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3347 $this->showTextbox2();
3349 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3353 * Format an anchor fragment as it would appear for a given section name
3354 * @param $text String
3358 function sectionAnchor( $text ) {
3360 return $wgParser->guessSectionNameFromWikiText( $text );
3364 * Check if the browser is on a blacklist of user-agents known to
3365 * mangle UTF-8 data on form submission. Returns true if Unicode
3366 * should make it through, false if it's known to be a problem.
3370 function checkUnicodeCompliantBrowser() {
3371 global $wgBrowserBlackList;
3372 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
3373 // No User-Agent header sent? Trust it by default...
3376 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
3377 foreach ( $wgBrowserBlackList as $browser ) {
3378 if ( preg_match( $browser, $currentbrowser ) ) {
3386 * Filter an input field through a Unicode de-armoring process if it
3387 * came from an old browser with known broken Unicode editing issues.
3389 * @param $request WebRequest
3390 * @param $field String
3394 function safeUnicodeInput( $request, $field ) {
3395 $text = rtrim( $request->getText( $field ) );
3396 return $request->getBool( 'safemode' )
3397 ?
$this->unmakesafe( $text )
3402 * @param $request WebRequest
3403 * @param $text string
3406 function safeUnicodeText( $request, $text ) {
3407 $text = rtrim( $text );
3408 return $request->getBool( 'safemode' )
3409 ?
$this->unmakesafe( $text )
3414 * Filter an output field through a Unicode armoring process if it is
3415 * going to an old browser with known broken Unicode editing issues.
3417 * @param $text String
3421 function safeUnicodeOutput( $text ) {
3423 $codedText = $wgContLang->recodeForEdit( $text );
3424 return $this->checkUnicodeCompliantBrowser()
3426 : $this->makesafe( $codedText );
3430 * A number of web browsers are known to corrupt non-ASCII characters
3431 * in a UTF-8 text editing environment. To protect against this,
3432 * detected browsers will be served an armored version of the text,
3433 * with non-ASCII chars converted to numeric HTML character references.
3435 * Preexisting such character references will have a 0 added to them
3436 * to ensure that round-trips do not alter the original data.
3438 * @param $invalue String
3442 function makesafe( $invalue ) {
3443 // Armor existing references for reversability.
3444 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3449 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3450 $bytevalue = ord( $invalue[$i] );
3451 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3452 $result .= chr( $bytevalue );
3454 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3455 $working = $working << 6;
3456 $working +
= ( $bytevalue & 0x3F );
3458 if ( $bytesleft <= 0 ) {
3459 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3461 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3462 $working = $bytevalue & 0x1F;
3464 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3465 $working = $bytevalue & 0x0F;
3467 } else { // 1111 0xxx
3468 $working = $bytevalue & 0x07;
3476 * Reverse the previously applied transliteration of non-ASCII characters
3477 * back to UTF-8. Used to protect data from corruption by broken web browsers
3478 * as listed in $wgBrowserBlackList.
3480 * @param $invalue String
3484 function unmakesafe( $invalue ) {
3486 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3487 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3491 $hexstring .= $invalue[$i];
3493 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3495 // Do some sanity checks. These aren't needed for reversability,
3496 // but should help keep the breakage down if the editor
3497 // breaks one of the entities whilst editing.
3498 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3499 $codepoint = hexdec($hexstring);
3500 $result .= codepointToUtf8( $codepoint );
3502 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3505 $result .= substr( $invalue, $i, 1 );
3508 // reverse the transform that we made for reversability reasons.
3509 return strtr( $result, array( "�" => "&#x" ) );