3 * Page edition user interface.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * The edit page/HTML interface (split from Article)
25 * The actual database and text munging is still in Article,
26 * but it should get easier to call those from alternate
29 * EditPage cares about two distinct titles:
30 * $this->mContextTitle is the page that forms submit to, links point to,
31 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
32 * page in the database that is actually being edited. These are
33 * usually the same, but they are now allowed to be different.
35 * Surgeon General's Warning: prolonged exposure to this class is known to cause
36 * headaches, which may be fatal.
41 * Status: Article successfully updated
43 const AS_SUCCESS_UPDATE
= 200;
46 * Status: Article successfully created
48 const AS_SUCCESS_NEW_ARTICLE
= 201;
51 * Status: Article update aborted by a hook function
53 const AS_HOOK_ERROR
= 210;
56 * Status: A hook function returned an error
58 const AS_HOOK_ERROR_EXPECTED
= 212;
61 * Status: User is blocked from editting this page
63 const AS_BLOCKED_PAGE_FOR_USER
= 215;
66 * Status: Content too big (> $wgMaxArticleSize)
68 const AS_CONTENT_TOO_BIG
= 216;
71 * Status: User cannot edit? (not used)
73 const AS_USER_CANNOT_EDIT
= 217;
76 * Status: this anonymous user is not allowed to edit this page
78 const AS_READ_ONLY_PAGE_ANON
= 218;
81 * Status: this logged in user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_LOGGED
= 219;
86 * Status: wiki is in readonly mode (wfReadOnly() == true)
88 const AS_READ_ONLY_PAGE
= 220;
91 * Status: rate limiter for action 'edit' was tripped
93 const AS_RATE_LIMITED
= 221;
96 * Status: article was deleted while editting and param wpRecreate == false or form
99 const AS_ARTICLE_WAS_DELETED
= 222;
102 * Status: user tried to create this page, but is not allowed to do that
103 * ( Title->usercan('create') == false )
105 const AS_NO_CREATE_PERMISSION
= 223;
108 * Status: user tried to create a blank page
110 const AS_BLANK_ARTICLE
= 224;
113 * Status: (non-resolvable) edit conflict
115 const AS_CONFLICT_DETECTED
= 225;
118 * Status: no edit summary given and the user has forceeditsummary set and the user is not
119 * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
121 const AS_SUMMARY_NEEDED
= 226;
124 * Status: user tried to create a new section without content
126 const AS_TEXTBOX_EMPTY
= 228;
129 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
131 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
139 * Status: WikiPage::doEdit() was unsuccessfull
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
146 const AS_SPAM_ERROR
= 232;
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
151 const AS_IMAGE_REDIRECT_ANON
= 233;
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
156 const AS_IMAGE_REDIRECT_LOGGED
= 234;
159 * Status: can't parse content
161 const AS_PARSE_ERROR
= 240;
164 * HTML id and name for the beginning of the edit form.
166 const EDITFORM_ID
= 'editform';
177 private $mContextTitle = null;
178 var $action = 'submit';
179 var $isConflict = false;
180 var $isCssJsSubpage = false;
181 var $isCssSubpage = false;
182 var $isJsSubpage = false;
183 var $isWrongCaseCssJsPage = false;
184 var $isNew = false; // new page or new section
185 var $deletedSinceEdit;
189 var $mTokenOk = false;
190 var $mTokenOkExceptSuffix = false;
191 var $mTriedSave = false;
192 var $incompleteForm = false;
194 var $kblength = false;
195 var $missingComment = false;
196 var $missingSummary = false;
197 var $allowBlankSummary = false;
200 #var $mPreviewTemplates;
208 * Has a summary been preset using GET parameter &summary= ?
211 var $hasPresetSummary = false;
213 var $mBaseRevision = false;
214 var $mShowSummaryField = true;
217 var $save = false, $preview = false, $diff = false;
218 var $minoredit = false, $watchthis = false, $recreate = false;
219 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
220 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
221 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
222 var $contentModel = null, $contentFormat = null;
224 # Placeholders for text injection by hooks (must be HTML)
225 # extensions should take care to _append_ to the present value
226 public $editFormPageTop = ''; // Before even the preview
227 public $editFormTextTop = '';
228 public $editFormTextBeforeContent = '';
229 public $editFormTextAfterWarn = '';
230 public $editFormTextAfterTools = '';
231 public $editFormTextBottom = '';
232 public $editFormTextAfterContent = '';
233 public $previewTextAfterContent = '';
234 public $mPreloadContent = null;
236 /* $didSave should be set to true whenever an article was succesfully altered. */
237 public $didSave = false;
238 public $undidRev = 0;
240 public $suppressIntro = false;
243 * Set to true to allow editing of non-text content types.
247 public $allowNonTextContent = false;
250 * @param $article Article
252 public function __construct( Article
$article ) {
253 $this->mArticle
= $article;
254 $this->mTitle
= $article->getTitle();
256 $this->contentModel
= $this->mTitle
->getContentModel();
258 $handler = ContentHandler
::getForModelID( $this->contentModel
);
259 $this->contentFormat
= $handler->getDefaultFormat();
265 public function getArticle() {
266 return $this->mArticle
;
273 public function getTitle() {
274 return $this->mTitle
;
278 * Set the context Title object
280 * @param $title Title object or null
282 public function setContextTitle( $title ) {
283 $this->mContextTitle
= $title;
287 * Get the context title object.
288 * If not set, $wgTitle will be returned. This behavior might change in
289 * the future to return $this->mTitle instead.
291 * @return Title object
293 public function getContextTitle() {
294 if ( is_null( $this->mContextTitle
) ) {
298 return $this->mContextTitle
;
307 * This is the function that gets called for "action=edit". It
308 * sets up various member variables, then passes execution to
309 * another function, usually showEditForm()
311 * The edit form is self-submitting, so that when things like
312 * preview and edit conflicts occur, we get the same form back
313 * with the extra stuff added. Only when the final submission
314 * is made and all is well do we actually save and redirect to
315 * the newly-edited page.
318 global $wgOut, $wgRequest, $wgUser;
319 // Allow extensions to modify/prevent this form or submission
320 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
324 wfProfileIn( __METHOD__
);
325 wfDebug( __METHOD__
. ": enter\n" );
327 // If they used redlink=1 and the page exists, redirect to the main article
328 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
329 $wgOut->redirect( $this->mTitle
->getFullURL() );
330 wfProfileOut( __METHOD__
);
334 $this->importFormData( $wgRequest );
335 $this->firsttime
= false;
338 $this->livePreview();
339 wfProfileOut( __METHOD__
);
343 if ( wfReadOnly() && $this->save
) {
346 $this->preview
= true;
350 $this->formtype
= 'save';
351 } elseif ( $this->preview
) {
352 $this->formtype
= 'preview';
353 } elseif ( $this->diff
) {
354 $this->formtype
= 'diff';
355 } else { # First time through
356 $this->firsttime
= true;
357 if ( $this->previewOnOpen() ) {
358 $this->formtype
= 'preview';
360 $this->formtype
= 'initial';
364 $permErrors = $this->getEditPermissionErrors();
366 wfDebug( __METHOD__
. ": User can't edit\n" );
367 // Auto-block user's IP if the account was "hard" blocked
368 $wgUser->spreadAnyEditBlock();
370 $this->displayPermissionsError( $permErrors );
372 wfProfileOut( __METHOD__
);
376 wfProfileIn( __METHOD__
. "-business-end" );
378 $this->isConflict
= false;
379 // css / js subpages of user pages get a special treatment
380 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
381 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
382 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
383 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
385 # Show applicable editing introductions
386 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
390 # Attempt submission here. This will check for edit conflicts,
391 # and redundantly check for locked database, blocked IPs, etc.
392 # that edit() already checked just in case someone tries to sneak
393 # in the back door with a hand-edited submission URL.
395 if ( 'save' == $this->formtype
) {
396 if ( !$this->attemptSave() ) {
397 wfProfileOut( __METHOD__
. "-business-end" );
398 wfProfileOut( __METHOD__
);
403 # First time through: get contents, set time for conflict
405 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
406 if ( $this->initialiseForm() === false ) {
407 $this->noSuchSectionPage();
408 wfProfileOut( __METHOD__
. "-business-end" );
409 wfProfileOut( __METHOD__
);
412 if ( !$this->mTitle
->getArticleID() )
413 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
415 wfRunHooks( 'EditFormInitialText', array( $this ) );
418 $this->showEditForm();
419 wfProfileOut( __METHOD__
. "-business-end" );
420 wfProfileOut( __METHOD__
);
426 protected function getEditPermissionErrors() {
428 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
429 # Can this title be created?
430 if ( !$this->mTitle
->exists() ) {
431 $permErrors = array_merge( $permErrors,
432 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
434 # Ignore some permissions errors when a user is just previewing/viewing diffs
436 foreach ( $permErrors as $error ) {
437 if ( ( $this->preview ||
$this->diff
) &&
438 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
443 $permErrors = wfArrayDiff2( $permErrors, $remove );
448 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
449 * but with the following differences:
450 * - If redlink=1, the user will be redirected to the page
451 * - If there is content to display or the error occurs while either saving,
452 * previewing or showing the difference, it will be a
453 * "View source for ..." page displaying the source code after the error message.
456 * @param $permErrors Array of permissions errors, as returned by
457 * Title::getUserPermissionsErrors().
458 * @throws PermissionsError
460 protected function displayPermissionsError( array $permErrors ) {
461 global $wgRequest, $wgOut;
463 if ( $wgRequest->getBool( 'redlink' ) ) {
464 // The edit page was reached via a red link.
465 // Redirect to the article page and let them click the edit tab if
466 // they really want a permission error.
467 $wgOut->redirect( $this->mTitle
->getFullUrl() );
471 $content = $this->getContentObject();
473 # Use the normal message if there's nothing to display
474 if ( $this->firsttime
&& $content->isEmpty() ) {
475 $action = $this->mTitle
->exists() ?
'edit' :
476 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
477 throw new PermissionsError( $action, $permErrors );
480 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
481 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
482 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
483 $wgOut->addHTML( "<hr />\n" );
485 # If the user made changes, preserve them when showing the markup
486 # (This happens when a user is blocked during edit, for instance)
487 if ( !$this->firsttime
) {
488 $text = $this->textbox1
;
489 $wgOut->addWikiMsg( 'viewyourtext' );
491 $text = $this->toEditText( $content );
492 $wgOut->addWikiMsg( 'viewsourcetext' );
495 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
497 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
498 Linker
::formatTemplates( $this->getTemplates() ) ) );
500 if ( $this->mTitle
->exists() ) {
501 $wgOut->returnToMain( null, $this->mTitle
);
506 * Show a read-only error
507 * Parameters are the same as OutputPage:readOnlyPage()
508 * Redirect to the article page if redlink=1
509 * @deprecated in 1.19; use displayPermissionsError() instead
511 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
512 wfDeprecated( __METHOD__
, '1.19' );
514 global $wgRequest, $wgOut;
515 if ( $wgRequest->getBool( 'redlink' ) ) {
516 // The edit page was reached via a red link.
517 // Redirect to the article page and let them click the edit tab if
518 // they really want a permission error.
519 $wgOut->redirect( $this->mTitle
->getFullUrl() );
521 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
526 * Should we show a preview when the edit form is first shown?
530 protected function previewOnOpen() {
531 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
532 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
533 // Explicit override from request
535 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
536 // Explicit override from request
538 } elseif ( $this->section
== 'new' ) {
539 // Nothing *to* preview for new sections
541 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
542 // Standard preference behaviour
544 } elseif ( !$this->mTitle
->exists() &&
545 isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] ) &&
546 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
548 // Categories are special
556 * Checks whether the user entered a skin name in uppercase,
557 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
561 protected function isWrongCaseCssJsPage() {
562 if ( $this->mTitle
->isCssJsSubpage() ) {
563 $name = $this->mTitle
->getSkinFromCssJsSubpage();
564 $skins = array_merge(
565 array_keys( Skin
::getSkinNames() ),
568 return !in_array( $name, $skins )
569 && in_array( strtolower( $name ), $skins );
576 * Does this EditPage class support section editing?
577 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
581 protected function isSectionEditSupported() {
586 * This function collects the form data and uses it to populate various member variables.
587 * @param $request WebRequest
589 function importFormData( &$request ) {
590 global $wgLang, $wgUser;
592 wfProfileIn( __METHOD__
);
594 # Section edit can come from either the form or a link
595 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
596 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
598 if ( $request->wasPosted() ) {
599 # These fields need to be checked for encoding.
600 # Also remove trailing whitespace, but don't remove _initial_
601 # whitespace from the text boxes. This may be significant formatting.
602 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
603 if ( !$request->getCheck( 'wpTextbox2' ) ) {
604 // Skip this if wpTextbox2 has input, it indicates that we came
605 // from a conflict page with raw page text, not a custom form
606 // modified by subclasses
607 wfProfileIn( get_class( $this ) . "::importContentFormData" );
608 $textbox1 = $this->importContentFormData( $request );
609 if ( isset( $textbox1 ) )
610 $this->textbox1
= $textbox1;
611 wfProfileOut( get_class( $this ) . "::importContentFormData" );
614 # Truncate for whole multibyte characters
615 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 255 );
617 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
618 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
620 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
622 # Treat sectiontitle the same way as summary.
623 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
624 # currently doing double duty as both edit summary and section title. Right now this
625 # is just to allow API edits to work around this limitation, but this should be
626 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
627 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
628 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
630 $this->edittime
= $request->getVal( 'wpEdittime' );
631 $this->starttime
= $request->getVal( 'wpStarttime' );
633 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
635 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
636 // wpTextbox1 field is missing, possibly due to being "too big"
637 // according to some filter rules such as Suhosin's setting for
638 // suhosin.request.max_value_length (d'oh)
639 $this->incompleteForm
= true;
641 // edittime should be one of our last fields; if it's missing,
642 // the submission probably broke somewhere in the middle.
643 $this->incompleteForm
= is_null( $this->edittime
);
645 if ( $this->incompleteForm
) {
646 # If the form is incomplete, force to preview.
647 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
648 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
649 $this->preview
= true;
651 /* Fallback for live preview */
652 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
653 $this->diff
= $request->getCheck( 'wpDiff' );
655 // Remember whether a save was requested, so we can indicate
656 // if we forced preview due to session failure.
657 $this->mTriedSave
= !$this->preview
;
659 if ( $this->tokenOk( $request ) ) {
660 # Some browsers will not report any submit button
661 # if the user hits enter in the comment box.
662 # The unmarked state will be assumed to be a save,
663 # if the form seems otherwise complete.
664 wfDebug( __METHOD__
. ": Passed token check.\n" );
665 } elseif ( $this->diff
) {
666 # Failed token check, but only requested "Show Changes".
667 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
669 # Page might be a hack attempt posted from
670 # an external site. Preview instead of saving.
671 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
672 $this->preview
= true;
675 $this->save
= !$this->preview
&& !$this->diff
;
676 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
677 $this->edittime
= null;
680 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
681 $this->starttime
= null;
684 $this->recreate
= $request->getCheck( 'wpRecreate' );
686 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
687 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
689 # Don't force edit summaries when a user is editing their own user or talk page
690 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
691 $this->mTitle
->getText() == $wgUser->getName() )
693 $this->allowBlankSummary
= true;
695 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary' );
698 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
700 # Not a posted form? Start with nothing.
701 wfDebug( __METHOD__
. ": Not a posted form.\n" );
702 $this->textbox1
= '';
704 $this->sectiontitle
= '';
705 $this->edittime
= '';
706 $this->starttime
= wfTimestampNow();
708 $this->preview
= false;
711 $this->minoredit
= false;
712 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
713 $this->recreate
= false;
715 // When creating a new section, we can preload a section title by passing it as the
716 // preloadtitle parameter in the URL (Bug 13100)
717 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
718 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
719 // Once wpSummary isn't being use for setting section titles, we should delete this.
720 $this->summary
= $request->getVal( 'preloadtitle' );
722 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
723 $this->summary
= $request->getText( 'summary' );
724 if ( $this->summary
!== '' ) {
725 $this->hasPresetSummary
= true;
729 if ( $request->getVal( 'minor' ) ) {
730 $this->minoredit
= true;
734 $this->oldid
= $request->getInt( 'oldid' );
736 $this->bot
= $request->getBool( 'bot', true );
737 $this->nosummary
= $request->getBool( 'nosummary' );
739 $content_handler = ContentHandler
::getForTitle( $this->mTitle
);
740 $this->contentModel
= $request->getText( 'model', $content_handler->getModelID() ); #may be overridden by revision
741 $this->contentFormat
= $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
743 #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
744 #TODO: check if the desired content model supports the given content format!
746 $this->live
= $request->getCheck( 'live' );
747 $this->editintro
= $request->getText( 'editintro',
748 // Custom edit intro for new sections
749 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
751 // Allow extensions to modify form data
752 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
754 wfProfileOut( __METHOD__
);
758 * Subpage overridable method for extracting the page content data from the
759 * posted form to be placed in $this->textbox1, if using customized input
760 * this method should be overrided and return the page text that will be used
761 * for saving, preview parsing and so on...
763 * @param $request WebRequest
765 protected function importContentFormData( &$request ) {
766 return; // Don't do anything, EditPage already extracted wpTextbox1
770 * Initialise form fields in the object
771 * Called on the first invocation, e.g. when a user clicks an edit link
772 * @return bool -- if the requested section is valid
774 function initialiseForm() {
776 $this->edittime
= $this->mArticle
->getTimestamp();
778 $content = $this->getContentObject( false ); #TODO: track content object?!
779 $this->textbox1
= $this->toEditText( $content );
781 // activate checkboxes if user wants them to be always active
782 # Sort out the "watch" checkbox
783 if ( $wgUser->getOption( 'watchdefault' ) ) {
785 $this->watchthis
= true;
786 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
788 $this->watchthis
= true;
789 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
791 $this->watchthis
= true;
793 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
794 $this->minoredit
= true;
796 if ( $this->textbox1
=== false ) {
804 * Fetch initial editing page content.
806 * @param $def_text string
807 * @return mixed string on success, $def_text for invalid sections
809 * @deprecated since 1.21
811 function getContent( $def_text = false ) {
812 wfDeprecated( __METHOD__
, '1.21' );
814 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
815 $def_content = $this->toEditContent( $def_text );
817 $def_content = false;
820 $content = $this->getContentObject( $def_content );
822 // Note: EditPage should only be used with text based content anyway.
823 return $this->toEditText( $content );
827 * @param Content|false $def_content The default value to return
829 * @return mixed Content on success, $def_content for invalid sections
833 protected function getContentObject( $def_content = null ) {
834 global $wgOut, $wgRequest;
836 wfProfileIn( __METHOD__
);
840 // For message page not locally set, use the i18n message.
841 // For other non-existent articles, use preload text if any.
842 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
843 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
844 # If this is a system message, get the default text.
845 $msg = $this->mTitle
->getDefaultMessageText();
847 $content = $this->toEditContent( $msg );
849 if ( $content === false ) {
850 # If requested, preload some text.
851 $preload = $wgRequest->getVal( 'preload',
852 // Custom preload text for new sections
853 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
855 $content = $this->getPreloadedContent( $preload );
857 // For existing pages, get text based on "undo" or section parameters.
859 if ( $this->section
!= '' ) {
860 // Get section edit text (returns $def_text for invalid sections)
861 $orig = $this->getOriginalContent();
862 $content = $orig ?
$orig->getSection( $this->section
) : null;
864 if ( !$content ) $content = $def_content;
866 $undoafter = $wgRequest->getInt( 'undoafter' );
867 $undo = $wgRequest->getInt( 'undo' );
869 if ( $undo > 0 && $undoafter > 0 ) {
870 if ( $undo < $undoafter ) {
871 # If they got undoafter and undo round the wrong way, switch them
872 list( $undo, $undoafter ) = array( $undoafter, $undo );
875 $undorev = Revision
::newFromId( $undo );
876 $oldrev = Revision
::newFromId( $undoafter );
878 # Sanity check, make sure it's the right page,
879 # the revisions exist and they were not deleted.
880 # Otherwise, $content will be left as-is.
881 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
882 $undorev->getPage() == $oldrev->getPage() &&
883 $undorev->getPage() == $this->mTitle
->getArticleID() &&
884 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
885 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
887 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
889 if ( $content === false ) {
890 # Warn the user that something went wrong
891 $undoMsg = 'failure';
893 # Inform the user of our success and set an automatic edit summary
894 $undoMsg = 'success';
896 # If we just undid one rev, use an autosummary
897 $firstrev = $oldrev->getNext();
898 if ( $firstrev && $firstrev->getId() == $undo ) {
899 $undoSummary = wfMessage( 'undo-summary', $undo, $undorev->getUserText() )->inContentLanguage()->text();
900 if ( $this->summary
=== '' ) {
901 $this->summary
= $undoSummary;
903 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
904 ->inContentLanguage()->text() . $this->summary
;
906 $this->undidRev
= $undo;
908 $this->formtype
= 'diff';
911 // Failed basic sanity checks.
912 // Older revisions may have been removed since the link
913 // was created, or we may simply have got bogus input.
917 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
918 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
919 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
922 if ( $content === false ) {
923 $content = $this->getOriginalContent();
928 wfProfileOut( __METHOD__
);
933 * Get the content of the wanted revision, without section extraction.
935 * The result of this function can be used to compare user's input with
936 * section replaced in its context (using WikiPage::replaceSection())
937 * to the original text of the edit.
939 * This difers from Article::getContent() that when a missing revision is
940 * encountered the result will be an empty string and not the
941 * 'missing-revision' message.
946 private function getOriginalContent() {
947 if ( $this->section
== 'new' ) {
948 return $this->getCurrentContent();
950 $revision = $this->mArticle
->getRevisionFetched();
951 if ( $revision === null ) {
952 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
953 $handler = ContentHandler
::getForModelID( $this->contentModel
);
955 return $handler->makeEmptyContent();
957 $content = $revision->getContent();
962 * Get the current content of the page. This is basically similar to
963 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
964 * content object is returned instead of null.
969 protected function getCurrentContent() {
970 $rev = $this->mArticle
->getRevision();
971 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
973 if ( $content === false ||
$content === null ) {
974 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
975 $handler = ContentHandler
::getForModelID( $this->contentModel
);
977 return $handler->makeEmptyContent();
979 # nasty side-effect, but needed for consistency
980 $this->contentModel
= $rev->getContentModel();
981 $this->contentFormat
= $rev->getContentFormat();
989 * Use this method before edit() to preload some text into the edit box
991 * @param $text string
992 * @deprecated since 1.21
994 public function setPreloadedText( $text ) {
995 wfDeprecated( __METHOD__
, "1.21" );
997 $content = $this->toEditContent( $text );
999 $this->setPreloadedContent( $content );
1003 * Use this method before edit() to preload some content into the edit box
1005 * @param $content Content
1009 public function setPreloadedContent( Content
$content ) {
1010 $this->mPreloadContent
= $content;
1014 * Get the contents to be preloaded into the box, either set by
1015 * an earlier setPreloadText() or by loading the given page.
1017 * @param $preload String: representing the title to preload from.
1021 * @deprecated since 1.21, use getPreloadedContent() instead
1023 protected function getPreloadedText( $preload ) {
1024 wfDeprecated( __METHOD__
, "1.21" );
1026 $content = $this->getPreloadedContent( $preload );
1027 $text = $this->toEditText( $content );
1033 * Get the contents to be preloaded into the box, either set by
1034 * an earlier setPreloadText() or by loading the given page.
1036 * @param $preload String: representing the title to preload from.
1042 protected function getPreloadedContent( $preload ) {
1045 if ( !empty( $this->mPreloadContent
) ) {
1046 return $this->mPreloadContent
;
1049 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1051 if ( $preload === '' ) {
1052 return $handler->makeEmptyContent();
1055 $title = Title
::newFromText( $preload );
1056 # Check for existence to avoid getting MediaWiki:Noarticletext
1057 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
1058 return $handler->makeEmptyContent();
1061 $page = WikiPage
::factory( $title );
1062 if ( $page->isRedirect() ) {
1063 $title = $page->getRedirectTarget();
1065 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
1066 return $handler->makeEmptyContent();
1068 $page = WikiPage
::factory( $title );
1071 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1072 $content = $page->getContent( Revision
::RAW
);
1074 return $content->preloadTransform( $title, $parserOptions );
1078 * Make sure the form isn't faking a user's credentials.
1080 * @param $request WebRequest
1084 function tokenOk( &$request ) {
1086 $token = $request->getVal( 'wpEditToken' );
1087 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1088 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1089 return $this->mTokenOk
;
1093 * Attempt submission
1094 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1095 * @return bool false if output is done, true if the rest of the form should be displayed
1097 function attemptSave() {
1098 global $wgUser, $wgOut;
1100 $resultDetails = false;
1101 # Allow bots to exempt some edits from bot flagging
1102 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1103 $status = $this->internalAttemptSave( $resultDetails, $bot );
1104 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1105 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1106 $this->didSave
= true;
1109 switch ( $status->value
) {
1110 case self
::AS_HOOK_ERROR_EXPECTED
:
1111 case self
::AS_CONTENT_TOO_BIG
:
1112 case self
::AS_ARTICLE_WAS_DELETED
:
1113 case self
::AS_CONFLICT_DETECTED
:
1114 case self
::AS_SUMMARY_NEEDED
:
1115 case self
::AS_TEXTBOX_EMPTY
:
1116 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1120 case self
::AS_HOOK_ERROR
:
1123 case self
::AS_PARSE_ERROR
:
1124 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>');
1127 case self
::AS_SUCCESS_NEW_ARTICLE
:
1128 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1129 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1130 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1133 case self
::AS_SUCCESS_UPDATE
:
1135 $sectionanchor = $resultDetails['sectionanchor'];
1137 // Give extensions a chance to modify URL query on update
1138 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1140 if ( $resultDetails['redirect'] ) {
1141 if ( $extraQuery == '' ) {
1142 $extraQuery = 'redirect=no';
1144 $extraQuery = 'redirect=no&' . $extraQuery;
1147 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1150 case self
::AS_BLANK_ARTICLE
:
1151 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1154 case self
::AS_SPAM_ERROR
:
1155 $this->spamPageWithContent( $resultDetails['spam'] );
1158 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1159 throw new UserBlockedError( $wgUser->getBlock() );
1161 case self
::AS_IMAGE_REDIRECT_ANON
:
1162 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1163 throw new PermissionsError( 'upload' );
1165 case self
::AS_READ_ONLY_PAGE_ANON
:
1166 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1167 throw new PermissionsError( 'edit' );
1169 case self
::AS_READ_ONLY_PAGE
:
1170 throw new ReadOnlyError
;
1172 case self
::AS_RATE_LIMITED
:
1173 throw new ThrottledError();
1175 case self
::AS_NO_CREATE_PERMISSION
:
1176 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1177 throw new PermissionsError( $permission );
1180 // We don't recognize $status->value. The only way that can happen
1181 // is if an extension hook aborted from inside ArticleSave.
1182 // Render the status object into $this->hookError
1183 // FIXME this sucks, we should just use the Status object throughout
1184 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1191 * Attempt submission (no UI)
1196 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1198 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1199 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1200 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1202 function internalAttemptSave( &$result, $bot = false ) {
1203 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1205 $status = Status
::newGood();
1207 wfProfileIn( __METHOD__
);
1208 wfProfileIn( __METHOD__
. '-checks' );
1210 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1211 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1212 $status->fatal( 'hookaborted' );
1213 $status->value
= self
::AS_HOOK_ERROR
;
1214 wfProfileOut( __METHOD__
. '-checks' );
1215 wfProfileOut( __METHOD__
);
1220 # Construct Content object
1221 $textbox_content = $this->toEditContent( $this->textbox1
);
1222 } catch (MWContentSerializationException
$ex) {
1223 $status->fatal( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
1224 $status->value
= self
::AS_PARSE_ERROR
;
1225 wfProfileOut( __METHOD__
);
1229 # Check image redirect
1230 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1231 $textbox_content->isRedirect() &&
1232 !$wgUser->isAllowed( 'upload' ) ) {
1233 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1234 $status->setResult( false, $code );
1236 wfProfileOut( __METHOD__
. '-checks' );
1237 wfProfileOut( __METHOD__
);
1243 $match = self
::matchSummarySpamRegex( $this->summary
);
1244 if ( $match === false ) {
1245 $match = self
::matchSpamRegex( $this->textbox1
);
1247 if ( $match !== false ) {
1248 $result['spam'] = $match;
1249 $ip = $wgRequest->getIP();
1250 $pdbk = $this->mTitle
->getPrefixedDBkey();
1251 $match = str_replace( "\n", '', $match );
1252 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1253 $status->fatal( 'spamprotectionmatch', $match );
1254 $status->value
= self
::AS_SPAM_ERROR
;
1255 wfProfileOut( __METHOD__
. '-checks' );
1256 wfProfileOut( __METHOD__
);
1259 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1260 # Error messages etc. could be handled within the hook...
1261 $status->fatal( 'hookaborted' );
1262 $status->value
= self
::AS_HOOK_ERROR
;
1263 wfProfileOut( __METHOD__
. '-checks' );
1264 wfProfileOut( __METHOD__
);
1266 } elseif ( $this->hookError
!= '' ) {
1267 # ...or the hook could be expecting us to produce an error
1268 $status->fatal( 'hookaborted' );
1269 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1270 wfProfileOut( __METHOD__
. '-checks' );
1271 wfProfileOut( __METHOD__
);
1275 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1276 // Auto-block user's IP if the account was "hard" blocked
1277 $wgUser->spreadAnyEditBlock();
1278 # Check block state against master, thus 'false'.
1279 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1280 wfProfileOut( __METHOD__
. '-checks' );
1281 wfProfileOut( __METHOD__
);
1285 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1286 if ( $this->kblength
> $wgMaxArticleSize ) {
1287 // Error will be displayed by showEditForm()
1288 $this->tooBig
= true;
1289 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1290 wfProfileOut( __METHOD__
. '-checks' );
1291 wfProfileOut( __METHOD__
);
1295 if ( !$wgUser->isAllowed( 'edit' ) ) {
1296 if ( $wgUser->isAnon() ) {
1297 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1298 wfProfileOut( __METHOD__
. '-checks' );
1299 wfProfileOut( __METHOD__
);
1302 $status->fatal( 'readonlytext' );
1303 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1304 wfProfileOut( __METHOD__
. '-checks' );
1305 wfProfileOut( __METHOD__
);
1310 if ( wfReadOnly() ) {
1311 $status->fatal( 'readonlytext' );
1312 $status->value
= self
::AS_READ_ONLY_PAGE
;
1313 wfProfileOut( __METHOD__
. '-checks' );
1314 wfProfileOut( __METHOD__
);
1317 if ( $wgUser->pingLimiter() ) {
1318 $status->fatal( 'actionthrottledtext' );
1319 $status->value
= self
::AS_RATE_LIMITED
;
1320 wfProfileOut( __METHOD__
. '-checks' );
1321 wfProfileOut( __METHOD__
);
1325 # If the article has been deleted while editing, don't save it without
1327 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1328 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1329 wfProfileOut( __METHOD__
. '-checks' );
1330 wfProfileOut( __METHOD__
);
1334 wfProfileOut( __METHOD__
. '-checks' );
1336 # Load the page data from the master. If anything changes in the meantime,
1337 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1338 $this->mArticle
->loadPageData( 'fromdbmaster' );
1339 $new = !$this->mArticle
->exists();
1342 // Late check for create permission, just in case *PARANOIA*
1343 if ( !$this->mTitle
->userCan( 'create' ) ) {
1344 $status->fatal( 'nocreatetext' );
1345 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1346 wfDebug( __METHOD__
. ": no create permission\n" );
1347 wfProfileOut( __METHOD__
);
1351 # Don't save a new article if it's blank.
1352 if ( $this->textbox1
== '' ) {
1353 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1354 wfProfileOut( __METHOD__
);
1358 // Run post-section-merge edit filter
1359 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1360 # Error messages etc. could be handled within the hook...
1361 $status->fatal( 'hookaborted' );
1362 $status->value
= self
::AS_HOOK_ERROR
;
1363 wfProfileOut( __METHOD__
);
1365 } elseif ( $this->hookError
!= '' ) {
1366 # ...or the hook could be expecting us to produce an error
1367 $status->fatal( 'hookaborted' );
1368 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1369 wfProfileOut( __METHOD__
);
1373 $content = $textbox_content;
1375 $result['sectionanchor'] = '';
1376 if ( $this->section
== 'new' ) {
1377 if ( $this->sectiontitle
!== '' ) {
1378 // Insert the section title above the content.
1379 $content = $content->addSectionHeader( $this->sectiontitle
);
1381 // Jump to the new section
1382 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1384 // If no edit summary was specified, create one automatically from the section
1385 // title and have it link to the new section. Otherwise, respect the summary as
1387 if ( $this->summary
=== '' ) {
1388 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1389 $this->summary
= wfMessage( 'newsectionsummary', $cleanSectionTitle )
1390 ->inContentLanguage()->text() ;
1392 } elseif ( $this->summary
!== '' ) {
1393 // Insert the section title above the content.
1394 $content = $content->addSectionHeader( $this->summary
);
1396 // Jump to the new section
1397 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1399 // Create a link to the new section from the edit summary.
1400 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1401 $this->summary
= wfMessage( 'newsectionsummary', $cleanSummary )
1402 ->inContentLanguage()->text();
1406 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1410 # Article exists. Check for edit conflict.
1412 $this->mArticle
->clear(); # Force reload of dates, etc.
1413 $timestamp = $this->mArticle
->getTimestamp();
1415 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1417 if ( $timestamp != $this->edittime
) {
1418 $this->isConflict
= true;
1419 if ( $this->section
== 'new' ) {
1420 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1421 $this->mArticle
->getComment() == $this->summary
) {
1422 // Probably a duplicate submission of a new comment.
1423 // This can happen when squid resends a request after
1424 // a timeout but the first one actually went through.
1425 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1427 // New comment; suppress conflict.
1428 $this->isConflict
= false;
1429 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1431 } elseif ( $this->section
== '' && Revision
::userWasLastToEdit( DB_MASTER
, $this->mTitle
->getArticleID(),
1432 $wgUser->getId(), $this->edittime
) ) {
1433 # Suppress edit conflict with self, except for section edits where merging is required.
1434 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1435 $this->isConflict
= false;
1439 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1440 // backwards compatibility with old forms/bots).
1441 if ( $this->sectiontitle
!== '' ) {
1442 $sectionTitle = $this->sectiontitle
;
1444 $sectionTitle = $this->summary
;
1449 if ( $this->isConflict
) {
1450 wfDebug( __METHOD__
. ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1451 . " (article time '{$timestamp}')\n" );
1453 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1455 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1456 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1459 if ( is_null( $content ) ) {
1460 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1461 $this->isConflict
= true;
1462 $content = $textbox_content; // do not try to merge here!
1463 } elseif ( $this->isConflict
) {
1465 if ( $this->mergeChangesIntoContent( $textbox_content ) ) {
1466 // Successful merge! Maybe we should tell the user the good news?
1467 $this->isConflict
= false;
1468 $content = $textbox_content;
1469 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1471 $this->section
= '';
1472 #$this->textbox1 = $text; #redundant, nothing to do here?
1473 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1477 if ( $this->isConflict
) {
1478 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1479 wfProfileOut( __METHOD__
);
1483 // Run post-section-merge edit filter
1484 $hook_args = array( $this, $content, &$this->hookError
, $this->summary
);
1486 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged', $hook_args )
1487 ||
!wfRunHooks( 'EditFilterMergedContent', $hook_args ) ) {
1488 # Error messages etc. could be handled within the hook...
1489 $status->fatal( 'hookaborted' );
1490 $status->value
= self
::AS_HOOK_ERROR
;
1491 wfProfileOut( __METHOD__
);
1493 } elseif ( $this->hookError
!= '' ) {
1494 # ...or the hook could be expecting us to produce an error
1495 $status->fatal( 'hookaborted' );
1496 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1497 wfProfileOut( __METHOD__
);
1501 # Handle the user preference to force summaries here, but not for null edits
1502 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1503 && !$content->equals( $this->getOriginalContent() )
1504 && !$content->isRedirect() ) # check if it's not a redirect
1506 if ( md5( $this->summary
) == $this->autoSumm
) {
1507 $this->missingSummary
= true;
1508 $status->fatal( 'missingsummary' );
1509 $status->value
= self
::AS_SUMMARY_NEEDED
;
1510 wfProfileOut( __METHOD__
);
1515 # And a similar thing for new sections
1516 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1517 if ( trim( $this->summary
) == '' ) {
1518 $this->missingSummary
= true;
1519 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1520 $status->value
= self
::AS_SUMMARY_NEEDED
;
1521 wfProfileOut( __METHOD__
);
1527 wfProfileIn( __METHOD__
. '-sectionanchor' );
1528 $sectionanchor = '';
1529 if ( $this->section
== 'new' ) {
1530 if ( $this->textbox1
== '' ) {
1531 $this->missingComment
= true;
1532 $status->fatal( 'missingcommenttext' );
1533 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1534 wfProfileOut( __METHOD__
. '-sectionanchor' );
1535 wfProfileOut( __METHOD__
);
1538 if ( $this->sectiontitle
!== '' ) {
1539 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1540 // If no edit summary was specified, create one automatically from the section
1541 // title and have it link to the new section. Otherwise, respect the summary as
1543 if ( $this->summary
=== '' ) {
1544 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1545 $this->summary
= wfMessage( 'newsectionsummary', $cleanSectionTitle )
1546 ->inContentLanguage()->text();
1548 } elseif ( $this->summary
!== '' ) {
1549 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1550 # This is a new section, so create a link to the new section
1551 # in the revision summary.
1552 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1553 $this->summary
= wfMessage( 'newsectionsummary', $cleanSummary )
1554 ->inContentLanguage()->text();
1556 } elseif ( $this->section
!= '' ) {
1557 # Try to get a section anchor from the section source, redirect to edited section if header found
1558 # XXX: might be better to integrate this into Article::replaceSection
1559 # for duplicate heading checking and maybe parsing
1560 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1561 # we can't deal with anchors, includes, html etc in the header for now,
1562 # headline would need to be parsed to improve this
1563 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1564 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1567 $result['sectionanchor'] = $sectionanchor;
1568 wfProfileOut( __METHOD__
. '-sectionanchor' );
1570 // Save errors may fall down to the edit form, but we've now
1571 // merged the section into full text. Clear the section field
1572 // so that later submission of conflict forms won't try to
1573 // replace that into a duplicated mess.
1574 $this->textbox1
= $this->toEditText( $content );
1575 $this->section
= '';
1577 $status->value
= self
::AS_SUCCESS_UPDATE
;
1580 // Check for length errors again now that the section is merged in
1581 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1582 if ( $this->kblength
> $wgMaxArticleSize ) {
1583 $this->tooBig
= true;
1584 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1585 wfProfileOut( __METHOD__
);
1589 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1590 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1591 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1592 ( $bot ? EDIT_FORCE_BOT
: 0 );
1594 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags,
1595 false, null, $this->contentFormat
);
1597 if ( $doEditStatus->isOK() ) {
1598 $result['redirect'] = $content->isRedirect();
1599 $this->commitWatch();
1600 wfProfileOut( __METHOD__
);
1603 // Failure from doEdit()
1604 // Show the edit conflict page for certain recognized errors from doEdit(),
1605 // but don't show it for errors from extension hooks
1606 $errors = $doEditStatus->getErrorsArray();
1607 if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
1608 'edit-already-exists' ) ) )
1610 $this->isConflict
= true;
1611 // Destroys data doEdit() put in $status->value but who cares
1612 $doEditStatus->value
= self
::AS_END
;
1614 wfProfileOut( __METHOD__
);
1615 return $doEditStatus;
1620 * Commit the change of watch status
1622 protected function commitWatch() {
1624 if ( $wgUser->isLoggedIn() && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
) ) {
1625 $dbw = wfGetDB( DB_MASTER
);
1626 $dbw->begin( __METHOD__
);
1627 if ( $this->watchthis
) {
1628 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1630 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1632 $dbw->commit( __METHOD__
);
1640 * @param $editText string
1643 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1645 function mergeChangesInto( &$editText ){
1646 wfDebug( __METHOD__
, "1.21" );
1648 $editContent = $this->toEditContent( $editText );
1650 $ok = $this->mergeChangesIntoContent( $editContent );
1653 $editText = $this->toEditText( $editContent );
1664 * @parma $editText string
1669 private function mergeChangesIntoContent( &$editContent ){
1670 wfProfileIn( __METHOD__
);
1672 $db = wfGetDB( DB_MASTER
);
1674 // This is the revision the editor started from
1675 $baseRevision = $this->getBaseRevision();
1676 if ( is_null( $baseRevision ) ) {
1677 wfProfileOut( __METHOD__
);
1680 $baseContent = $baseRevision->getContent();
1682 // The current state, we want to merge updates into it
1683 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1684 if ( is_null( $currentRevision ) ) {
1685 wfProfileOut( __METHOD__
);
1688 $currentContent = $currentRevision->getContent();
1690 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
1692 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1695 $editContent = $result;
1696 wfProfileOut( __METHOD__
);
1699 wfProfileOut( __METHOD__
);
1707 function getBaseRevision() {
1708 if ( !$this->mBaseRevision
) {
1709 $db = wfGetDB( DB_MASTER
);
1710 $baseRevision = Revision
::loadFromTimestamp(
1711 $db, $this->mTitle
, $this->edittime
);
1712 return $this->mBaseRevision
= $baseRevision;
1714 return $this->mBaseRevision
;
1719 * Check given input text against $wgSpamRegex, and return the text of the first match.
1721 * @param $text string
1723 * @return string|bool matching string or false
1725 public static function matchSpamRegex( $text ) {
1726 global $wgSpamRegex;
1727 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1728 $regexes = (array)$wgSpamRegex;
1729 return self
::matchSpamRegexInternal( $text, $regexes );
1733 * Check given input text against $wgSpamRegex, and return the text of the first match.
1735 * @param $text string
1737 * @return string|bool matching string or false
1739 public static function matchSummarySpamRegex( $text ) {
1740 global $wgSummarySpamRegex;
1741 $regexes = (array)$wgSummarySpamRegex;
1742 return self
::matchSpamRegexInternal( $text, $regexes );
1746 * @param $text string
1747 * @param $regexes array
1748 * @return bool|string
1750 protected static function matchSpamRegexInternal( $text, $regexes ) {
1751 foreach ( $regexes as $regex ) {
1753 if ( preg_match( $regex, $text, $matches ) ) {
1760 function setHeaders() {
1761 global $wgOut, $wgUser;
1763 $wgOut->addModules( 'mediawiki.action.edit' );
1765 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1766 $wgOut->addModules( 'mediawiki.legacy.preview' );
1768 // Bug #19334: textarea jumps when editing articles in IE8
1769 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1771 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1773 # Enabled article-related sidebar, toplinks, etc.
1774 $wgOut->setArticleRelated( true );
1776 $contextTitle = $this->getContextTitle();
1777 if ( $this->isConflict
) {
1778 $msg = 'editconflict';
1779 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1780 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1782 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1783 'editing' : 'creating';
1785 # Use the title defined by DISPLAYTITLE magic word when present
1786 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1787 if ( $displayTitle === false ) {
1788 $displayTitle = $contextTitle->getPrefixedText();
1790 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1794 * Show all applicable editing introductions
1796 protected function showIntro() {
1797 global $wgOut, $wgUser;
1798 if ( $this->suppressIntro
) {
1802 $namespace = $this->mTitle
->getNamespace();
1804 if ( $namespace == NS_MEDIAWIKI
) {
1805 # Show a warning if editing an interface message
1806 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1807 } else if( $namespace == NS_FILE
) {
1808 # Show a hint to shared repo
1809 $file = wfFindFile( $this->mTitle
);
1810 if( $file && !$file->isLocal() ) {
1811 $descUrl = $file->getDescriptionUrl();
1812 # there must be a description url to show a hint to shared repo
1814 if( !$this->mTitle
->exists() ) {
1815 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1816 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1819 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1820 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1827 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1828 # Show log extract when the user is currently blocked
1829 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1830 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1831 $username = $parts[0];
1832 $user = User
::newFromName( $username, false /* allow IP users*/ );
1833 $ip = User
::isIP( $username );
1834 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1835 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1836 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1837 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1838 LogEventsList
::showLogExtract(
1841 $user->getUserPage(),
1845 'showIfEmpty' => false,
1847 'blocked-notice-logextract',
1848 $user->getName() # Support GENDER in notice
1854 # Try to add a custom edit intro, or use the standard one if this is not possible.
1855 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1856 if ( $wgUser->isLoggedIn() ) {
1857 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1859 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1862 # Give a notice if the user is editing a deleted/moved page...
1863 if ( !$this->mTitle
->exists() ) {
1864 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1865 '', array( 'lim' => 10,
1866 'conds' => array( "log_action != 'revision'" ),
1867 'showIfEmpty' => false,
1868 'msgKey' => array( 'recreate-moveddeleted-warn' ) )
1874 * Attempt to show a custom editing introduction, if supplied
1878 protected function showCustomIntro() {
1879 if ( $this->editintro
) {
1880 $title = Title
::newFromText( $this->editintro
);
1881 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1883 // Added using template syntax, to take <noinclude>'s into account.
1884 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1895 * Gets an editable textual representation of the given Content object.
1896 * The textual representation can be turned by into a Content object by the
1897 * toEditContent() method.
1899 * If the given Content object is not of a type that can be edited using the text base EditPage,
1900 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
1903 * @param Content $content
1904 * @return String the editable text form of the content.
1906 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
1908 protected function toEditText( Content
$content ) {
1909 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
1910 throw new MWException( "This content model can not be edited as text: "
1911 . ContentHandler
::getLocalizedName( $content->getModel() ) );
1914 return $content->serialize( $this->contentFormat
);
1918 * Turns the given text into a Content object by unserializing it.
1920 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
1921 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
1924 * @param String|null|false $text Text to unserialize
1925 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
1928 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
1929 * and $this->allowNonTextContent is not true.
1931 protected function toEditContent( $text ) {
1932 if ( $text === false ||
$text === null ) {
1936 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
1937 $this->contentModel
, $this->contentFormat
);
1939 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
1940 throw new MWException( "This content model can not be edited as text: "
1941 . ContentHandler
::getLocalizedName( $content->getModel() ) );
1948 * Send the edit form and related headers to $wgOut
1949 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1950 * during form output near the top, for captchas and the like.
1952 function showEditForm( $formCallback = null ) {
1953 global $wgOut, $wgUser;
1955 wfProfileIn( __METHOD__
);
1957 # need to parse the preview early so that we know which templates are used,
1958 # otherwise users with "show preview after edit box" will get a blank list
1959 # we parse this near the beginning so that setHeaders can do the title
1960 # setting work instead of leaving it in getPreviewText
1961 $previewOutput = '';
1962 if ( $this->formtype
== 'preview' ) {
1963 $previewOutput = $this->getPreviewText();
1966 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
1968 $this->setHeaders();
1970 if ( $this->showHeader() === false ) {
1971 wfProfileOut( __METHOD__
);
1975 $wgOut->addHTML( $this->editFormPageTop
);
1977 if ( $wgUser->getOption( 'previewontop' ) ) {
1978 $this->displayPreviewArea( $previewOutput, true );
1981 $wgOut->addHTML( $this->editFormTextTop
);
1983 $showToolbar = true;
1984 if ( $this->wasDeletedSinceLastEdit() ) {
1985 if ( $this->formtype
== 'save' ) {
1986 // Hide the toolbar and edit area, user can click preview to get it back
1987 // Add an confirmation checkbox and explanation.
1988 $showToolbar = false;
1990 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1991 'deletedwhileediting' );
1995 //@todo: add EditForm plugin interface and use it here!
1996 // search for textarea1 and textares2, and allow EditForm to override all uses.
1997 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => self
::EDITFORM_ID
, 'name' => self
::EDITFORM_ID
,
1998 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1999 'enctype' => 'multipart/form-data' ) ) );
2001 if ( is_callable( $formCallback ) ) {
2002 call_user_func_array( $formCallback, array( &$wgOut ) );
2005 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2007 // Put these up at the top to ensure they aren't lost on early form submission
2008 $this->showFormBeforeText();
2010 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2011 $username = $this->lastDelete
->user_name
;
2012 $comment = $this->lastDelete
->log_comment
;
2014 // It is better to not parse the comment at all than to have templates expanded in the middle
2015 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2016 $key = $comment === ''
2017 ?
'confirmrecreate-noreason'
2018 : 'confirmrecreate';
2020 '<div class="mw-confirm-recreate">' .
2021 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2022 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2023 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2029 # When the summary is hidden, also hide them on preview/show changes
2030 if( $this->nosummary
) {
2031 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2034 # If a blank edit summary was previously provided, and the appropriate
2035 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2036 # user being bounced back more than once in the event that a summary
2039 # For a bit more sophisticated detection of blank summaries, hash the
2040 # automatic one and pass that in the hidden field wpAutoSummary.
2041 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2042 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2045 if ( $this->undidRev
) {
2046 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2049 if ( $this->hasPresetSummary
) {
2050 // If a summary has been preset using &summary= we dont want to prompt for
2051 // a different summary. Only prompt for a summary if the summary is blanked.
2053 $this->autoSumm
= md5( '' );
2056 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2057 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2059 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2061 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2062 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2064 if ( $this->section
== 'new' ) {
2065 $this->showSummaryInput( true, $this->summary
);
2066 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2069 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2071 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2072 $wgOut->addHTML( EditPage
::getEditToolbar() );
2075 if ( $this->isConflict
) {
2076 // In an edit conflict bypass the overrideable content form method
2077 // and fallback to the raw wpTextbox1 since editconflicts can't be
2078 // resolved between page source edits and custom ui edits using the
2080 $this->textbox2
= $this->textbox1
;
2082 $content = $this->getCurrentContent();
2083 $this->textbox1
= $this->toEditText( $content );
2085 $this->showTextbox1();
2087 $this->showContentForm();
2090 $wgOut->addHTML( $this->editFormTextAfterContent
);
2092 $this->showStandardInputs();
2094 $this->showFormAfterText();
2096 $this->showTosSummary();
2098 $this->showEditTools();
2100 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2102 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2103 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2105 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2106 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2108 if ( $this->isConflict
) {
2110 $this->showConflict();
2111 } catch ( MWContentSerializationException
$ex ) {
2112 // this can't really happen, but be nice if it does.
2113 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2114 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2118 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2120 if ( !$wgUser->getOption( 'previewontop' ) ) {
2121 $this->displayPreviewArea( $previewOutput, false );
2124 wfProfileOut( __METHOD__
);
2128 * Extract the section title from current section text, if any.
2130 * @param string $text
2131 * @return Mixed|string or false
2133 public static function extractSectionTitle( $text ) {
2134 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2135 if ( !empty( $matches[2] ) ) {
2137 return $wgParser->stripSectionName( trim( $matches[2] ) );
2143 protected function showHeader() {
2144 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2146 if ( $this->mTitle
->isTalkPage() ) {
2147 $wgOut->addWikiMsg( 'talkpagetext' );
2150 # Optional notices on a per-namespace and per-page basis
2151 $editnotice_ns = 'editnotice-' . $this->mTitle
->getNamespace();
2152 $editnotice_ns_message = wfMessage( $editnotice_ns );
2153 if ( $editnotice_ns_message->exists() ) {
2154 $wgOut->addWikiText( $editnotice_ns_message->plain() );
2156 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
2157 $parts = explode( '/', $this->mTitle
->getDBkey() );
2158 $editnotice_base = $editnotice_ns;
2159 while ( count( $parts ) > 0 ) {
2160 $editnotice_base .= '-' . array_shift( $parts );
2161 $editnotice_base_msg = wfMessage( $editnotice_base );
2162 if ( $editnotice_base_msg->exists() ) {
2163 $wgOut->addWikiText( $editnotice_base_msg->plain() );
2167 # Even if there are no subpages in namespace, we still don't want / in MW ns.
2168 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
2169 $editnoticeMsg = wfMessage( $editnoticeText );
2170 if ( $editnoticeMsg->exists() ) {
2171 $wgOut->addWikiText( $editnoticeMsg->plain() );
2175 if ( $this->isConflict
) {
2176 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2177 $this->edittime
= $this->mArticle
->getTimestamp();
2179 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2180 // We use $this->section to much before this and getVal('wgSection') directly in other places
2181 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2182 // Someone is welcome to try refactoring though
2183 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2187 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2188 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2189 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2190 if ( $sectionTitle !== false ) {
2191 $this->summary
= "/* $sectionTitle */ ";
2196 if ( $this->missingComment
) {
2197 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2200 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2201 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2204 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2205 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2208 if ( $this->hookError
!== '' ) {
2209 $wgOut->addWikiText( $this->hookError
);
2212 if ( !$this->checkUnicodeCompliantBrowser() ) {
2213 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2216 if ( $this->section
!= 'new' ) {
2217 $revision = $this->mArticle
->getRevisionFetched();
2219 // Let sysop know that this will make private content public if saved
2221 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
2222 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2223 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2224 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2227 if ( !$revision->isCurrent() ) {
2228 $this->mArticle
->setOldSubtitle( $revision->getId() );
2229 $wgOut->addWikiMsg( 'editingold' );
2231 } elseif ( $this->mTitle
->exists() ) {
2232 // Something went wrong
2234 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2235 array( 'missing-revision', $this->oldid
) );
2240 if ( wfReadOnly() ) {
2241 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2242 } elseif ( $wgUser->isAnon() ) {
2243 if ( $this->formtype
!= 'preview' ) {
2244 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2246 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2249 if ( $this->isCssJsSubpage
) {
2250 # Check the skin exists
2251 if ( $this->isWrongCaseCssJsPage
) {
2252 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2254 if ( $this->formtype
!== 'preview' ) {
2255 if ( $this->isCssSubpage
)
2256 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2257 if ( $this->isJsSubpage
)
2258 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2263 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2264 # Is the title semi-protected?
2265 if ( $this->mTitle
->isSemiProtected() ) {
2266 $noticeMsg = 'semiprotectedpagewarning';
2268 # Then it must be protected based on static groups (regular)
2269 $noticeMsg = 'protectedpagewarning';
2271 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2272 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2274 if ( $this->mTitle
->isCascadeProtected() ) {
2275 # Is this page under cascading protection from some source pages?
2276 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2277 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2278 $cascadeSourcesCount = count( $cascadeSources );
2279 if ( $cascadeSourcesCount > 0 ) {
2280 # Explain, and list the titles responsible
2281 foreach ( $cascadeSources as $page ) {
2282 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2285 $notice .= '</div>';
2286 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2288 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2289 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2291 'showIfEmpty' => false,
2292 'msgKey' => array( 'titleprotectedwarning' ),
2293 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2296 if ( $this->kblength
=== false ) {
2297 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2300 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2301 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2302 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2304 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2305 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2306 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2310 # Add header copyright warning
2311 $this->showHeaderCopyrightWarning();
2316 * Standard summary input and label (wgSummary), abstracted so EditPage
2317 * subclasses may reorganize the form.
2318 * Note that you do not need to worry about the label's for=, it will be
2319 * inferred by the id given to the input. You can remove them both by
2320 * passing array( 'id' => false ) to $userInputAttrs.
2322 * @param $summary string The value of the summary input
2323 * @param $labelText string The html to place inside the label
2324 * @param $inputAttrs array of attrs to use on the input
2325 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2327 * @return array An array in the format array( $label, $input )
2329 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2330 // Note: the maxlength is overriden in JS to 255 and to make it use UTF-8 bytes, not characters.
2331 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2332 'id' => 'wpSummary',
2333 'maxlength' => '200',
2336 'spellcheck' => 'true',
2337 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2339 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2340 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2341 'id' => "wpSummaryLabel"
2346 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2347 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2350 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2352 return array( $label, $input );
2356 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2357 * up top, or false if this is the comment summary
2358 * down below the textarea
2359 * @param $summary String: The text of the summary to display
2362 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2363 global $wgOut, $wgContLang;
2364 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2365 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2366 if ( $isSubjectPreview ) {
2367 if ( $this->nosummary
) {
2371 if ( !$this->mShowSummaryField
) {
2375 $summary = $wgContLang->recodeForEdit( $summary );
2376 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2377 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2378 $wgOut->addHTML( "{$label} {$input}" );
2382 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2383 * up top, or false if this is the comment summary
2384 * down below the textarea
2385 * @param $summary String: the text of the summary to display
2388 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2389 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2394 if ( $isSubjectPreview )
2395 $summary = wfMessage( 'newsectionsummary', $wgParser->stripSectionName( $summary ) )
2396 ->inContentLanguage()->text();
2398 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2400 $summary = wfMessage( $message )->parse() . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2401 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2404 protected function showFormBeforeText() {
2406 $section = htmlspecialchars( $this->section
);
2407 $wgOut->addHTML( <<<HTML
2408 <input type='hidden' value="{$section}" name="wpSection" />
2409 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2410 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2411 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2415 if ( !$this->checkUnicodeCompliantBrowser() )
2416 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2419 protected function showFormAfterText() {
2420 global $wgOut, $wgUser;
2422 * To make it harder for someone to slip a user a page
2423 * which submits an edit form to the wiki without their
2424 * knowledge, a random token is associated with the login
2425 * session. If it's not passed back with the submission,
2426 * we won't save the page, or render user JavaScript and
2429 * For anon editors, who may not have a session, we just
2430 * include the constant suffix to prevent editing from
2431 * broken text-mangling proxies.
2433 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2437 * Subpage overridable method for printing the form for page content editing
2438 * By default this simply outputs wpTextbox1
2439 * Subclasses can override this to provide a custom UI for editing;
2440 * be it a form, or simply wpTextbox1 with a modified content that will be
2441 * reverse modified when extracted from the post data.
2442 * Note that this is basically the inverse for importContentFormData
2444 protected function showContentForm() {
2445 $this->showTextbox1();
2449 * Method to output wpTextbox1
2450 * The $textoverride method can be used by subclasses overriding showContentForm
2451 * to pass back to this method.
2453 * @param $customAttribs array of html attributes to use in the textarea
2454 * @param $textoverride String: optional text to override $this->textarea1 with
2456 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2457 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2458 $attribs = array( 'style' => 'display:none;' );
2460 $classes = array(); // Textarea CSS
2461 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2462 # Is the title semi-protected?
2463 if ( $this->mTitle
->isSemiProtected() ) {
2464 $classes[] = 'mw-textarea-sprotected';
2466 # Then it must be protected based on static groups (regular)
2467 $classes[] = 'mw-textarea-protected';
2469 # Is the title cascade-protected?
2470 if ( $this->mTitle
->isCascadeProtected() ) {
2471 $classes[] = 'mw-textarea-cprotected';
2475 $attribs = array( 'tabindex' => 1 );
2477 if ( is_array( $customAttribs ) ) {
2478 $attribs +
= $customAttribs;
2481 if ( count( $classes ) ) {
2482 if ( isset( $attribs['class'] ) ) {
2483 $classes[] = $attribs['class'];
2485 $attribs['class'] = implode( ' ', $classes );
2489 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2492 protected function showTextbox2() {
2493 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2496 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2497 global $wgOut, $wgUser;
2499 $wikitext = $this->safeUnicodeOutput( $text );
2500 if ( strval( $wikitext ) !== '' ) {
2501 // Ensure there's a newline at the end, otherwise adding lines
2503 // But don't add a newline if the ext is empty, or Firefox in XHTML
2504 // mode will show an extra newline. A bit annoying.
2508 $attribs = $customAttribs +
array(
2511 'cols' => $wgUser->getIntOption( 'cols' ),
2512 'rows' => $wgUser->getIntOption( 'rows' ),
2513 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2516 $pageLang = $this->mTitle
->getPageLanguage();
2517 $attribs['lang'] = $pageLang->getCode();
2518 $attribs['dir'] = $pageLang->getDir();
2520 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2523 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2527 $classes[] = 'ontop';
2529 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2531 if ( $this->formtype
!= 'preview' )
2532 $attribs['style'] = 'display: none;';
2534 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2536 if ( $this->formtype
== 'preview' ) {
2537 $this->showPreview( $previewOutput );
2540 $wgOut->addHTML( '</div>' );
2542 if ( $this->formtype
== 'diff' ) {
2545 } catch ( MWContentSerializationException
$ex ) {
2546 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2547 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2553 * Append preview output to $wgOut.
2554 * Includes category rendering if this is a category page.
2556 * @param $text String: the HTML to be output for the preview.
2558 protected function showPreview( $text ) {
2560 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2561 $this->mArticle
->openShowCategory();
2563 # This hook seems slightly odd here, but makes things more
2564 # consistent for extensions.
2565 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2566 $wgOut->addHTML( $text );
2567 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2568 $this->mArticle
->closeShowCategory();
2573 * Get a diff between the current contents of the edit box and the
2574 * version of the page we're editing from.
2576 * If this is a section edit, we'll replace the section as for final
2577 * save and then make a comparison.
2579 function showDiff() {
2580 global $wgUser, $wgContLang, $wgParser, $wgOut;
2582 $oldtitlemsg = 'currentrev';
2583 # if message does not exist, show diff against the preloaded default
2584 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2585 $oldtext = $this->mTitle
->getDefaultMessageText();
2586 if( $oldtext !== false ) {
2587 $oldtitlemsg = 'defaultmessagetext';
2588 $oldContent = $this->toEditContent( $oldtext );
2593 $oldContent = $this->getOriginalContent();
2596 $textboxContent = $this->toEditContent( $this->textbox1
);
2598 $newContent = $this->mArticle
->replaceSectionContent(
2599 $this->section
, $textboxContent,
2600 $this->summary
, $this->edittime
);
2602 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2603 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2605 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2606 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2608 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2609 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2610 $newtitle = wfMessage( 'yourtext' )->parse();
2612 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
2613 $de->setContent( $oldContent, $newContent );
2615 $difftext = $de->getDiff( $oldtitle, $newtitle );
2616 $de->showDiffStyle();
2621 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2625 * Show the header copyright warning.
2627 protected function showHeaderCopyrightWarning() {
2628 $msg = 'editpage-head-copy-warn';
2629 if ( !wfMessage( $msg )->isDisabled() ) {
2631 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2632 'editpage-head-copy-warn' );
2637 * Give a chance for site and per-namespace customizations of
2638 * terms of service summary link that might exist separately
2639 * from the copyright notice.
2641 * This will display between the save button and the edit tools,
2642 * so should remain short!
2644 protected function showTosSummary() {
2645 $msg = 'editpage-tos-summary';
2646 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2647 if ( !wfMessage( $msg )->isDisabled() ) {
2649 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2650 $wgOut->addWikiMsg( $msg );
2651 $wgOut->addHTML( '</div>' );
2655 protected function showEditTools() {
2657 $wgOut->addHTML( '<div class="mw-editTools">' .
2658 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2663 * Get the copyright warning
2665 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2667 protected function getCopywarn() {
2668 return self
::getCopyrightWarning( $this->mTitle
);
2671 public static function getCopyrightWarning( $title ) {
2672 global $wgRightsText;
2673 if ( $wgRightsText ) {
2674 $copywarnMsg = array( 'copyrightwarning',
2675 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2678 $copywarnMsg = array( 'copyrightwarning2',
2679 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2681 // Allow for site and per-namespace customization of contribution/copyright notice.
2682 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2684 return "<div id=\"editpage-copywarn\">\n" .
2685 call_user_func_array( 'wfMessage', $copywarnMsg )->plain() . "\n</div>";
2688 protected function showStandardInputs( &$tabindex = 2 ) {
2690 $wgOut->addHTML( "<div class='editOptions'>\n" );
2692 if ( $this->section
!= 'new' ) {
2693 $this->showSummaryInput( false, $this->summary
);
2694 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2697 $checkboxes = $this->getCheckboxes( $tabindex,
2698 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2699 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2701 // Show copyright warning.
2702 $wgOut->addWikiText( $this->getCopywarn() );
2703 $wgOut->addHTML( $this->editFormTextAfterWarn
);
2705 $wgOut->addHTML( "<div class='editButtons'>\n" );
2706 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2708 $cancel = $this->getCancelLink();
2709 if ( $cancel !== '' ) {
2710 $cancel .= wfMessage( 'pipe-separator' )->text();
2712 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
2713 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2714 wfMessage( 'edithelp' )->escaped() . '</a> ' .
2715 wfMessage( 'newwindow' )->parse();
2716 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
2717 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
2718 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2722 * Show an edit conflict. textbox1 is already shown in showEditForm().
2723 * If you want to use another entry point to this function, be careful.
2725 protected function showConflict() {
2728 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2729 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2731 $content1 = $this->toEditContent( $this->textbox1
);
2732 $content2 = $this->toEditContent( $this->textbox2
);
2734 $handler = ContentHandler
::getForModelID( $this->contentModel
);
2735 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
2736 $de->setContent( $content2, $content1 );
2738 wfMessage( 'yourtext' )->parse(),
2739 wfMessage( 'storedversion' )->text()
2742 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2743 $this->showTextbox2();
2750 public function getCancelLink() {
2751 $cancelParams = array();
2752 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2753 $cancelParams['oldid'] = $this->oldid
;
2756 return Linker
::linkKnown(
2757 $this->getContextTitle(),
2758 wfMessage( 'cancel' )->parse(),
2759 array( 'id' => 'mw-editform-cancel' ),
2765 * Returns the URL to use in the form's action attribute.
2766 * This is used by EditPage subclasses when simply customizing the action
2767 * variable in the constructor is not enough. This can be used when the
2768 * EditPage lives inside of a Special page rather than a custom page action.
2770 * @param $title Title object for which is being edited (where we go to for &action= links)
2773 protected function getActionURL( Title
$title ) {
2774 return $title->getLocalURL( array( 'action' => $this->action
) );
2778 * Check if a page was deleted while the user was editing it, before submit.
2779 * Note that we rely on the logging table, which hasn't been always there,
2780 * but that doesn't matter, because this only applies to brand new
2783 protected function wasDeletedSinceLastEdit() {
2784 if ( $this->deletedSinceEdit
!== null ) {
2785 return $this->deletedSinceEdit
;
2788 $this->deletedSinceEdit
= false;
2790 if ( $this->mTitle
->isDeletedQuick() ) {
2791 $this->lastDelete
= $this->getLastDelete();
2792 if ( $this->lastDelete
) {
2793 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2794 if ( $deleteTime > $this->starttime
) {
2795 $this->deletedSinceEdit
= true;
2800 return $this->deletedSinceEdit
;
2803 protected function getLastDelete() {
2804 $dbr = wfGetDB( DB_SLAVE
);
2805 $data = $dbr->selectRow(
2806 array( 'logging', 'user' ),
2817 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2818 'log_title' => $this->mTitle
->getDBkey(),
2819 'log_type' => 'delete',
2820 'log_action' => 'delete',
2821 'user_id=log_user' ),
2823 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2825 // Quick paranoid permission checks...
2826 if ( is_object( $data ) ) {
2827 if ( $data->log_deleted
& LogPage
::DELETED_USER
)
2828 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
2829 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2830 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
2836 * Get the rendered text for previewing.
2837 * @throws MWException
2840 function getPreviewText() {
2841 global $wgOut, $wgUser, $wgParser, $wgRawHtml, $wgLang;
2843 wfProfileIn( __METHOD__
);
2845 if ( $wgRawHtml && !$this->mTokenOk
) {
2846 // Could be an offsite preview attempt. This is very unsafe if
2847 // HTML is enabled, as it could be an attack.
2849 if ( $this->textbox1
!== '' ) {
2850 // Do not put big scary notice, if previewing the empty
2851 // string, which happens when you initially edit
2852 // a category page, due to automatic preview-on-open.
2853 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2854 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
2856 wfProfileOut( __METHOD__
);
2863 $content = $this->toEditContent( $this->textbox1
);
2865 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2866 if ( $this->mTokenOkExceptSuffix
) {
2867 $note = wfMessage( 'token_suffix_mismatch' )->plain() ;
2870 $note = wfMessage( 'session_fail_preview' )->plain() ;
2872 } elseif ( $this->incompleteForm
) {
2873 $note = wfMessage( 'edit_form_incomplete' )->plain() ;
2875 $note = wfMessage( 'previewnote' )->plain() .
2876 ' [[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' . wfMessage( 'continue-editing' )->text() . ']]';
2879 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
2880 $parserOptions->setEditSection( false );
2881 $parserOptions->setIsPreview( true );
2882 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2884 # don't parse non-wikitext pages, show message about preview
2885 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
2886 if( $this->mTitle
->isCssJsSubpage() ) {
2888 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2894 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
2896 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
2902 # Used messages to make sure grep find them:
2903 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2904 if( $level && $format ) {
2905 $note = "<div id='mw-{$level}{$format}preview'>" . wfMessage( "{$level}{$format}preview" )->text() . "</div>";
2907 $note = wfMessage( 'previewnote' )->text() ;
2910 $note = wfMessage( 'previewnote' )->text() ;
2913 $rt = $content->getRedirectChain();
2915 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2918 # If we're adding a comment, we need to show the
2919 # summary as the headline
2920 if ( $this->section
=== "new" && $this->summary
!== "" ) {
2921 $content = $content->addSectionHeader( $this->summary
);
2924 $hook_args = array( $this, &$content );
2925 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
2926 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
2928 $parserOptions->enableLimitReport();
2930 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
2931 # But it's now deprecated, so never mind
2933 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
2934 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
2936 $previewHTML = $parserOutput->getText();
2937 $this->mParserOutput
= $parserOutput;
2938 $wgOut->addParserOutputNoText( $parserOutput );
2940 if ( count( $parserOutput->getWarnings() ) ) {
2941 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2944 } catch ( MWContentSerializationException
$ex ) {
2945 $m = wfMessage('content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2946 $note .= "\n\n" . $m->parse();
2950 if ( $this->isConflict
) {
2951 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
2953 $conflict = '<hr />';
2956 $previewhead = "<div class='previewnote'>\n" .
2957 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
2958 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2960 $pageLang = $this->mTitle
->getPageLanguage();
2961 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2962 'class' => 'mw-content-' . $pageLang->getDir() );
2963 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2965 wfProfileOut( __METHOD__
);
2966 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2972 function getTemplates() {
2973 if ( $this->preview ||
$this->section
!= '' ) {
2974 $templates = array();
2975 if ( !isset( $this->mParserOutput
) ) {
2978 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
2979 foreach ( array_keys( $template ) as $dbk ) {
2980 $templates[] = Title
::makeTitle( $ns, $dbk );
2985 return $this->mTitle
->getTemplateLinksFrom();
2990 * Shows a bulletin board style toolbar for common editing functions.
2991 * It can be disabled in the user preferences.
2992 * The necessary JavaScript code can be found in skins/common/edit.js.
2996 static function getEditToolbar() {
2997 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2998 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
3000 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3003 * $toolarray is an array of arrays each of which includes the
3004 * filename of the button image (without path), the opening
3005 * tag, the closing tag, optionally a sample text that is
3006 * inserted between the two when no selection is highlighted
3007 * and. The tip text is shown when the user moves the mouse
3010 * Also here: accesskeys (key), which are not used yet until
3011 * someone can figure out a way to make them work in
3012 * IE. However, we should make sure these keys are not defined
3017 'image' => $wgLang->getImageFile( 'button-bold' ),
3018 'id' => 'mw-editbutton-bold',
3020 'close' => '\'\'\'',
3021 'sample' => wfMessage( 'bold_sample' )->text(),
3022 'tip' => wfMessage( 'bold_tip' )->text(),
3026 'image' => $wgLang->getImageFile( 'button-italic' ),
3027 'id' => 'mw-editbutton-italic',
3030 'sample' => wfMessage( 'italic_sample' )->text(),
3031 'tip' => wfMessage( 'italic_tip' )->text(),
3035 'image' => $wgLang->getImageFile( 'button-link' ),
3036 'id' => 'mw-editbutton-link',
3039 'sample' => wfMessage( 'link_sample' )->text(),
3040 'tip' => wfMessage( 'link_tip' )->text(),
3044 'image' => $wgLang->getImageFile( 'button-extlink' ),
3045 'id' => 'mw-editbutton-extlink',
3048 'sample' => wfMessage( 'extlink_sample' )->text(),
3049 'tip' => wfMessage( 'extlink_tip' )->text(),
3053 'image' => $wgLang->getImageFile( 'button-headline' ),
3054 'id' => 'mw-editbutton-headline',
3057 'sample' => wfMessage( 'headline_sample' )->text(),
3058 'tip' => wfMessage( 'headline_tip' )->text(),
3061 $imagesAvailable ?
array(
3062 'image' => $wgLang->getImageFile( 'button-image' ),
3063 'id' => 'mw-editbutton-image',
3064 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3066 'sample' => wfMessage( 'image_sample' )->text(),
3067 'tip' => wfMessage( 'image_tip' )->text(),
3070 $imagesAvailable ?
array(
3071 'image' => $wgLang->getImageFile( 'button-media' ),
3072 'id' => 'mw-editbutton-media',
3073 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3075 'sample' => wfMessage( 'media_sample' )->text(),
3076 'tip' => wfMessage( 'media_tip' )->text(),
3080 'image' => $wgLang->getImageFile( 'button-math' ),
3081 'id' => 'mw-editbutton-math',
3083 'close' => "</math>",
3084 'sample' => wfMessage( 'math_sample' )->text(),
3085 'tip' => wfMessage( 'math_tip' )->text(),
3089 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3090 'id' => 'mw-editbutton-nowiki',
3091 'open' => "<nowiki>",
3092 'close' => "</nowiki>",
3093 'sample' => wfMessage( 'nowiki_sample' )->text(),
3094 'tip' => wfMessage( 'nowiki_tip' )->text(),
3098 'image' => $wgLang->getImageFile( 'button-sig' ),
3099 'id' => 'mw-editbutton-signature',
3103 'tip' => wfMessage( 'sig_tip' )->text(),
3107 'image' => $wgLang->getImageFile( 'button-hr' ),
3108 'id' => 'mw-editbutton-hr',
3109 'open' => "\n----\n",
3112 'tip' => wfMessage( 'hr_tip' )->text(),
3117 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3118 foreach ( $toolarray as $tool ) {
3124 $image = $wgStylePath . '/common/images/' . $tool['image'],
3125 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3126 // Older browsers show a "speedtip" type message only for ALT.
3127 // Ideally these should be different, realistically they
3128 // probably don't need to be.
3129 $tip = $tool['tip'],
3130 $open = $tool['open'],
3131 $close = $tool['close'],
3132 $sample = $tool['sample'],
3133 $cssId = $tool['id'],
3136 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3139 // This used to be called on DOMReady from mediawiki.action.edit, which
3140 // ended up causing race conditions with the setup code above.
3142 "// Create button bar\n" .
3143 "$(function() { mw.toolbar.init(); } );\n";
3146 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3148 $toolbar = '<div id="toolbar"></div>';
3150 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3156 * Returns an array of html code of the following checkboxes:
3159 * @param $tabindex int Current tabindex
3160 * @param $checked Array of checkbox => bool, where bool indicates the checked
3161 * status of the checkbox
3165 public function getCheckboxes( &$tabindex, $checked ) {
3168 $checkboxes = array();
3170 // don't show the minor edit checkbox if it's a new page or section
3171 if ( !$this->isNew
) {
3172 $checkboxes['minor'] = '';
3173 $minorLabel = wfMessage( 'minoredit' )->parse();
3174 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3176 'tabindex' => ++
$tabindex,
3177 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3178 'id' => 'wpMinoredit',
3180 $checkboxes['minor'] =
3181 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3182 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3183 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3184 ">{$minorLabel}</label>";
3188 $watchLabel = wfMessage( 'watchthis' )->parse();
3189 $checkboxes['watch'] = '';
3190 if ( $wgUser->isLoggedIn() ) {
3192 'tabindex' => ++
$tabindex,
3193 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3194 'id' => 'wpWatchthis',
3196 $checkboxes['watch'] =
3197 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3198 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3199 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3200 ">{$watchLabel}</label>";
3202 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3207 * Returns an array of html code of the following buttons:
3208 * save, diff, preview and live
3210 * @param $tabindex int Current tabindex
3214 public function getEditButtons( &$tabindex ) {
3221 'tabindex' => ++
$tabindex,
3222 'value' => wfMessage( 'savearticle' )->text(),
3223 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3224 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3226 $buttons['save'] = Xml
::element( 'input', $temp, '' );
3228 ++
$tabindex; // use the same for preview and live preview
3230 'id' => 'wpPreview',
3231 'name' => 'wpPreview',
3233 'tabindex' => $tabindex,
3234 'value' => wfMessage( 'showpreview' )->text(),
3235 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3236 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3238 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3239 $buttons['live'] = '';
3245 'tabindex' => ++
$tabindex,
3246 'value' => wfMessage( 'showdiff' )->text(),
3247 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3248 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3250 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3252 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3257 * Output preview text only. This can be sucked into the edit page
3258 * via JavaScript, and saves the server time rendering the skin as
3259 * well as theoretically being more robust on the client (doesn't
3260 * disturb the edit box's undo history, won't eat your text on
3263 * @todo This doesn't include category or interlanguage links.
3264 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3265 * or something...</s>" that might also require more skin
3266 * initialization, so check whether that's a problem.
3268 function livePreview() {
3271 header( 'Content-type: text/xml; charset=utf-8' );
3272 header( 'Cache-control: no-cache' );
3274 $previewText = $this->getPreviewText();
3275 #$categories = $skin->getCategoryLinks();
3278 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3279 Xml
::tags( 'livepreview', null,
3280 Xml
::element( 'preview', null, $previewText )
3281 #. Xml::element( 'category', null, $categories )
3287 * Call the stock "user is blocked" page
3289 * @deprecated in 1.19; throw an exception directly instead
3291 function blockedPage() {
3292 wfDeprecated( __METHOD__
, '1.19' );
3295 throw new UserBlockedError( $wgUser->getBlock() );
3299 * Produce the stock "please login to edit pages" page
3301 * @deprecated in 1.19; throw an exception directly instead
3303 function userNotLoggedInPage() {
3304 wfDeprecated( __METHOD__
, '1.19' );
3305 throw new PermissionsError( 'edit' );
3309 * Show an error page saying to the user that he has insufficient permissions
3310 * to create a new page
3312 * @deprecated in 1.19; throw an exception directly instead
3314 function noCreatePermission() {
3315 wfDeprecated( __METHOD__
, '1.19' );
3316 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3317 throw new PermissionsError( $permission );
3321 * Creates a basic error page which informs the user that
3322 * they have attempted to edit a nonexistent section.
3324 function noSuchSectionPage() {
3327 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3329 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3330 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3331 $wgOut->addHTML( $res );
3333 $wgOut->returnToMain( false, $this->mTitle
);
3337 * Produce the stock "your edit contains spam" page
3339 * @param $match string Text which triggered one or more filters
3340 * @deprecated since 1.17 Use method spamPageWithContent() instead
3342 static function spamPage( $match = false ) {
3343 wfDeprecated( __METHOD__
, '1.17' );
3345 global $wgOut, $wgTitle;
3347 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3349 $wgOut->addHTML( '<div id="spamprotected">' );
3350 $wgOut->addWikiMsg( 'spamprotectiontext' );
3352 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3354 $wgOut->addHTML( '</div>' );
3356 $wgOut->returnToMain( false, $wgTitle );
3360 * Show "your edit contains spam" page with your diff and text
3362 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3364 public function spamPageWithContent( $match = false ) {
3365 global $wgOut, $wgLang;
3366 $this->textbox2
= $this->textbox1
;
3368 if( is_array( $match ) ){
3369 $match = $wgLang->listToText( $match );
3371 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3373 $wgOut->addHTML( '<div id="spamprotected">' );
3374 $wgOut->addWikiMsg( 'spamprotectiontext' );
3376 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3378 $wgOut->addHTML( '</div>' );
3380 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3383 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3384 $this->showTextbox2();
3386 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3390 * Format an anchor fragment as it would appear for a given section name
3391 * @param $text String
3395 function sectionAnchor( $text ) {
3397 return $wgParser->guessSectionNameFromWikiText( $text );
3401 * Check if the browser is on a blacklist of user-agents known to
3402 * mangle UTF-8 data on form submission. Returns true if Unicode
3403 * should make it through, false if it's known to be a problem.
3407 function checkUnicodeCompliantBrowser() {
3408 global $wgBrowserBlackList, $wgRequest;
3410 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3411 if ( $currentbrowser === false ) {
3412 // No User-Agent header sent? Trust it by default...
3416 foreach ( $wgBrowserBlackList as $browser ) {
3417 if ( preg_match( $browser, $currentbrowser ) ) {
3425 * Filter an input field through a Unicode de-armoring process if it
3426 * came from an old browser with known broken Unicode editing issues.
3428 * @param $request WebRequest
3429 * @param $field String
3433 function safeUnicodeInput( $request, $field ) {
3434 $text = rtrim( $request->getText( $field ) );
3435 return $request->getBool( 'safemode' )
3436 ?
$this->unmakesafe( $text )
3441 * @param $request WebRequest
3442 * @param $text string
3445 function safeUnicodeText( $request, $text ) {
3446 $text = rtrim( $text );
3447 return $request->getBool( 'safemode' )
3448 ?
$this->unmakesafe( $text )
3453 * Filter an output field through a Unicode armoring process if it is
3454 * going to an old browser with known broken Unicode editing issues.
3456 * @param $text String
3460 function safeUnicodeOutput( $text ) {
3462 $codedText = $wgContLang->recodeForEdit( $text );
3463 return $this->checkUnicodeCompliantBrowser()
3465 : $this->makesafe( $codedText );
3469 * A number of web browsers are known to corrupt non-ASCII characters
3470 * in a UTF-8 text editing environment. To protect against this,
3471 * detected browsers will be served an armored version of the text,
3472 * with non-ASCII chars converted to numeric HTML character references.
3474 * Preexisting such character references will have a 0 added to them
3475 * to ensure that round-trips do not alter the original data.
3477 * @param $invalue String
3481 function makesafe( $invalue ) {
3482 // Armor existing references for reversability.
3483 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3488 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3489 $bytevalue = ord( $invalue[$i] );
3490 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3491 $result .= chr( $bytevalue );
3493 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3494 $working = $working << 6;
3495 $working +
= ( $bytevalue & 0x3F );
3497 if ( $bytesleft <= 0 ) {
3498 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3500 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3501 $working = $bytevalue & 0x1F;
3503 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3504 $working = $bytevalue & 0x0F;
3506 } else { // 1111 0xxx
3507 $working = $bytevalue & 0x07;
3515 * Reverse the previously applied transliteration of non-ASCII characters
3516 * back to UTF-8. Used to protect data from corruption by broken web browsers
3517 * as listed in $wgBrowserBlackList.
3519 * @param $invalue String
3523 function unmakesafe( $invalue ) {
3525 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3526 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3530 $hexstring .= $invalue[$i];
3532 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3534 // Do some sanity checks. These aren't needed for reversability,
3535 // but should help keep the breakage down if the editor
3536 // breaks one of the entities whilst editing.
3537 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3538 $codepoint = hexdec( $hexstring );
3539 $result .= codepointToUtf8( $codepoint );
3541 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3544 $result .= substr( $invalue, $i, 1 );
3547 // reverse the transform that we made for reversability reasons.
3548 return strtr( $result, array( "�" => "&#x" ) );