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 $wgContLang, $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
= $wgContLang->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
= $wgContLang->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 if ( $content === false ) {
782 $this->textbox1
= $this->toEditText( $content );
784 // activate checkboxes if user wants them to be always active
785 # Sort out the "watch" checkbox
786 if ( $wgUser->getOption( 'watchdefault' ) ) {
788 $this->watchthis
= true;
789 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
791 $this->watchthis
= true;
792 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
794 $this->watchthis
= true;
796 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
797 $this->minoredit
= true;
799 if ( $this->textbox1
=== false ) {
807 * Fetch initial editing page content.
809 * @param $def_text string
810 * @return mixed string on success, $def_text for invalid sections
812 * @deprecated since 1.21, get WikiPage::getContent() instead.
814 function getContent( $def_text = false ) {
815 ContentHandler
::deprecated( __METHOD__
, '1.21' );
817 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
818 $def_content = $this->toEditContent( $def_text );
820 $def_content = false;
823 $content = $this->getContentObject( $def_content );
825 // Note: EditPage should only be used with text based content anyway.
826 return $this->toEditText( $content );
830 * @param Content|false $def_content The default value to return
832 * @return mixed Content on success, $def_content for invalid sections
836 protected function getContentObject( $def_content = null ) {
837 global $wgOut, $wgRequest;
839 wfProfileIn( __METHOD__
);
843 // For message page not locally set, use the i18n message.
844 // For other non-existent articles, use preload text if any.
845 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
846 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
847 # If this is a system message, get the default text.
848 $msg = $this->mTitle
->getDefaultMessageText();
850 $content = $this->toEditContent( $msg );
852 if ( $content === false ) {
853 # If requested, preload some text.
854 $preload = $wgRequest->getVal( 'preload',
855 // Custom preload text for new sections
856 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
858 $content = $this->getPreloadedContent( $preload );
860 // For existing pages, get text based on "undo" or section parameters.
862 if ( $this->section
!= '' ) {
863 // Get section edit text (returns $def_text for invalid sections)
864 $orig = $this->getOriginalContent();
865 $content = $orig ?
$orig->getSection( $this->section
) : null;
867 if ( !$content ) $content = $def_content;
869 $undoafter = $wgRequest->getInt( 'undoafter' );
870 $undo = $wgRequest->getInt( 'undo' );
872 if ( $undo > 0 && $undoafter > 0 ) {
873 if ( $undo < $undoafter ) {
874 # If they got undoafter and undo round the wrong way, switch them
875 list( $undo, $undoafter ) = array( $undoafter, $undo );
878 $undorev = Revision
::newFromId( $undo );
879 $oldrev = Revision
::newFromId( $undoafter );
881 # Sanity check, make sure it's the right page,
882 # the revisions exist and they were not deleted.
883 # Otherwise, $content will be left as-is.
884 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
885 $undorev->getPage() == $oldrev->getPage() &&
886 $undorev->getPage() == $this->mTitle
->getArticleID() &&
887 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
888 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
890 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
892 if ( $content === false ) {
893 # Warn the user that something went wrong
894 $undoMsg = 'failure';
896 # Inform the user of our success and set an automatic edit summary
897 $undoMsg = 'success';
899 # If we just undid one rev, use an autosummary
900 $firstrev = $oldrev->getNext();
901 if ( $firstrev && $firstrev->getId() == $undo ) {
902 $undoSummary = wfMessage( 'undo-summary', $undo, $undorev->getUserText() )->inContentLanguage()->text();
903 if ( $this->summary
=== '' ) {
904 $this->summary
= $undoSummary;
906 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
907 ->inContentLanguage()->text() . $this->summary
;
909 $this->undidRev
= $undo;
911 $this->formtype
= 'diff';
914 // Failed basic sanity checks.
915 // Older revisions may have been removed since the link
916 // was created, or we may simply have got bogus input.
920 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
921 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
922 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
925 if ( $content === false ) {
926 $content = $this->getOriginalContent();
931 wfProfileOut( __METHOD__
);
936 * Get the content of the wanted revision, without section extraction.
938 * The result of this function can be used to compare user's input with
939 * section replaced in its context (using WikiPage::replaceSection())
940 * to the original text of the edit.
942 * This difers from Article::getContent() that when a missing revision is
943 * encountered the result will be an empty string and not the
944 * 'missing-revision' message.
949 private function getOriginalContent() {
950 if ( $this->section
== 'new' ) {
951 return $this->getCurrentContent();
953 $revision = $this->mArticle
->getRevisionFetched();
954 if ( $revision === null ) {
955 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
956 $handler = ContentHandler
::getForModelID( $this->contentModel
);
958 return $handler->makeEmptyContent();
960 $content = $revision->getContent();
965 * Get the current content of the page. This is basically similar to
966 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
967 * content object is returned instead of null.
972 protected function getCurrentContent() {
973 $rev = $this->mArticle
->getRevision();
974 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
976 if ( $content === false ||
$content === null ) {
977 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
978 $handler = ContentHandler
::getForModelID( $this->contentModel
);
980 return $handler->makeEmptyContent();
982 # nasty side-effect, but needed for consistency
983 $this->contentModel
= $rev->getContentModel();
984 $this->contentFormat
= $rev->getContentFormat();
992 * Use this method before edit() to preload some text into the edit box
994 * @param $text string
995 * @deprecated since 1.21, use setPreloadedContent() instead.
997 public function setPreloadedText( $text ) {
998 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1000 $content = $this->toEditContent( $text );
1002 $this->setPreloadedContent( $content );
1006 * Use this method before edit() to preload some content into the edit box
1008 * @param $content Content
1012 public function setPreloadedContent( Content
$content ) {
1013 $this->mPreloadContent
= $content;
1017 * Get the contents to be preloaded into the box, either set by
1018 * an earlier setPreloadText() or by loading the given page.
1020 * @param $preload String: representing the title to preload from.
1024 * @deprecated since 1.21, use getPreloadedContent() instead
1026 protected function getPreloadedText( $preload ) {
1027 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1029 $content = $this->getPreloadedContent( $preload );
1030 $text = $this->toEditText( $content );
1036 * Get the contents to be preloaded into the box, either set by
1037 * an earlier setPreloadText() or by loading the given page.
1039 * @param $preload String: representing the title to preload from.
1045 protected function getPreloadedContent( $preload ) {
1048 if ( !empty( $this->mPreloadContent
) ) {
1049 return $this->mPreloadContent
;
1052 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1054 if ( $preload === '' ) {
1055 return $handler->makeEmptyContent();
1058 $title = Title
::newFromText( $preload );
1059 # Check for existence to avoid getting MediaWiki:Noarticletext
1060 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
1061 return $handler->makeEmptyContent();
1064 $page = WikiPage
::factory( $title );
1065 if ( $page->isRedirect() ) {
1066 $title = $page->getRedirectTarget();
1068 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
1069 return $handler->makeEmptyContent();
1071 $page = WikiPage
::factory( $title );
1074 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1075 $content = $page->getContent( Revision
::RAW
);
1077 return $content->preloadTransform( $title, $parserOptions );
1081 * Make sure the form isn't faking a user's credentials.
1083 * @param $request WebRequest
1087 function tokenOk( &$request ) {
1089 $token = $request->getVal( 'wpEditToken' );
1090 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1091 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1092 return $this->mTokenOk
;
1096 * Attempt submission
1097 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1098 * @return bool false if output is done, true if the rest of the form should be displayed
1100 function attemptSave() {
1101 global $wgUser, $wgOut;
1103 $resultDetails = false;
1104 # Allow bots to exempt some edits from bot flagging
1105 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1106 $status = $this->internalAttemptSave( $resultDetails, $bot );
1107 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1108 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1109 $this->didSave
= true;
1112 switch ( $status->value
) {
1113 case self
::AS_HOOK_ERROR_EXPECTED
:
1114 case self
::AS_CONTENT_TOO_BIG
:
1115 case self
::AS_ARTICLE_WAS_DELETED
:
1116 case self
::AS_CONFLICT_DETECTED
:
1117 case self
::AS_SUMMARY_NEEDED
:
1118 case self
::AS_TEXTBOX_EMPTY
:
1119 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1123 case self
::AS_HOOK_ERROR
:
1126 case self
::AS_PARSE_ERROR
:
1127 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>');
1130 case self
::AS_SUCCESS_NEW_ARTICLE
:
1131 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1132 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1133 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1136 case self
::AS_SUCCESS_UPDATE
:
1138 $sectionanchor = $resultDetails['sectionanchor'];
1140 // Give extensions a chance to modify URL query on update
1141 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1143 if ( $resultDetails['redirect'] ) {
1144 if ( $extraQuery == '' ) {
1145 $extraQuery = 'redirect=no';
1147 $extraQuery = 'redirect=no&' . $extraQuery;
1150 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1153 case self
::AS_BLANK_ARTICLE
:
1154 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1157 case self
::AS_SPAM_ERROR
:
1158 $this->spamPageWithContent( $resultDetails['spam'] );
1161 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1162 throw new UserBlockedError( $wgUser->getBlock() );
1164 case self
::AS_IMAGE_REDIRECT_ANON
:
1165 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1166 throw new PermissionsError( 'upload' );
1168 case self
::AS_READ_ONLY_PAGE_ANON
:
1169 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1170 throw new PermissionsError( 'edit' );
1172 case self
::AS_READ_ONLY_PAGE
:
1173 throw new ReadOnlyError
;
1175 case self
::AS_RATE_LIMITED
:
1176 throw new ThrottledError();
1178 case self
::AS_NO_CREATE_PERMISSION
:
1179 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1180 throw new PermissionsError( $permission );
1183 // We don't recognize $status->value. The only way that can happen
1184 // is if an extension hook aborted from inside ArticleSave.
1185 // Render the status object into $this->hookError
1186 // FIXME this sucks, we should just use the Status object throughout
1187 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1194 * Attempt submission (no UI)
1199 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1201 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1202 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1203 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1205 function internalAttemptSave( &$result, $bot = false ) {
1206 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1208 $status = Status
::newGood();
1210 wfProfileIn( __METHOD__
);
1211 wfProfileIn( __METHOD__
. '-checks' );
1213 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1214 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1215 $status->fatal( 'hookaborted' );
1216 $status->value
= self
::AS_HOOK_ERROR
;
1217 wfProfileOut( __METHOD__
. '-checks' );
1218 wfProfileOut( __METHOD__
);
1223 # Construct Content object
1224 $textbox_content = $this->toEditContent( $this->textbox1
);
1225 } catch (MWContentSerializationException
$ex) {
1226 $status->fatal( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
1227 $status->value
= self
::AS_PARSE_ERROR
;
1228 wfProfileOut( __METHOD__
);
1232 # Check image redirect
1233 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1234 $textbox_content->isRedirect() &&
1235 !$wgUser->isAllowed( 'upload' ) ) {
1236 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1237 $status->setResult( false, $code );
1239 wfProfileOut( __METHOD__
. '-checks' );
1240 wfProfileOut( __METHOD__
);
1246 $match = self
::matchSummarySpamRegex( $this->summary
);
1247 if ( $match === false ) {
1248 $match = self
::matchSpamRegex( $this->textbox1
);
1250 if ( $match !== false ) {
1251 $result['spam'] = $match;
1252 $ip = $wgRequest->getIP();
1253 $pdbk = $this->mTitle
->getPrefixedDBkey();
1254 $match = str_replace( "\n", '', $match );
1255 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1256 $status->fatal( 'spamprotectionmatch', $match );
1257 $status->value
= self
::AS_SPAM_ERROR
;
1258 wfProfileOut( __METHOD__
. '-checks' );
1259 wfProfileOut( __METHOD__
);
1262 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1263 # Error messages etc. could be handled within the hook...
1264 $status->fatal( 'hookaborted' );
1265 $status->value
= self
::AS_HOOK_ERROR
;
1266 wfProfileOut( __METHOD__
. '-checks' );
1267 wfProfileOut( __METHOD__
);
1269 } elseif ( $this->hookError
!= '' ) {
1270 # ...or the hook could be expecting us to produce an error
1271 $status->fatal( 'hookaborted' );
1272 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1273 wfProfileOut( __METHOD__
. '-checks' );
1274 wfProfileOut( __METHOD__
);
1278 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1279 // Auto-block user's IP if the account was "hard" blocked
1280 $wgUser->spreadAnyEditBlock();
1281 # Check block state against master, thus 'false'.
1282 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1283 wfProfileOut( __METHOD__
. '-checks' );
1284 wfProfileOut( __METHOD__
);
1288 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1289 if ( $this->kblength
> $wgMaxArticleSize ) {
1290 // Error will be displayed by showEditForm()
1291 $this->tooBig
= true;
1292 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1293 wfProfileOut( __METHOD__
. '-checks' );
1294 wfProfileOut( __METHOD__
);
1298 if ( !$wgUser->isAllowed( 'edit' ) ) {
1299 if ( $wgUser->isAnon() ) {
1300 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1301 wfProfileOut( __METHOD__
. '-checks' );
1302 wfProfileOut( __METHOD__
);
1305 $status->fatal( 'readonlytext' );
1306 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1307 wfProfileOut( __METHOD__
. '-checks' );
1308 wfProfileOut( __METHOD__
);
1313 if ( wfReadOnly() ) {
1314 $status->fatal( 'readonlytext' );
1315 $status->value
= self
::AS_READ_ONLY_PAGE
;
1316 wfProfileOut( __METHOD__
. '-checks' );
1317 wfProfileOut( __METHOD__
);
1320 if ( $wgUser->pingLimiter() ) {
1321 $status->fatal( 'actionthrottledtext' );
1322 $status->value
= self
::AS_RATE_LIMITED
;
1323 wfProfileOut( __METHOD__
. '-checks' );
1324 wfProfileOut( __METHOD__
);
1328 # If the article has been deleted while editing, don't save it without
1330 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1331 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1332 wfProfileOut( __METHOD__
. '-checks' );
1333 wfProfileOut( __METHOD__
);
1337 wfProfileOut( __METHOD__
. '-checks' );
1339 # Load the page data from the master. If anything changes in the meantime,
1340 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1341 $this->mArticle
->loadPageData( 'fromdbmaster' );
1342 $new = !$this->mArticle
->exists();
1345 // Late check for create permission, just in case *PARANOIA*
1346 if ( !$this->mTitle
->userCan( 'create' ) ) {
1347 $status->fatal( 'nocreatetext' );
1348 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1349 wfDebug( __METHOD__
. ": no create permission\n" );
1350 wfProfileOut( __METHOD__
);
1354 # Don't save a new article if it's blank.
1355 if ( $this->textbox1
== '' ) {
1356 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1357 wfProfileOut( __METHOD__
);
1361 // Run post-section-merge edit filter
1362 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1363 # Error messages etc. could be handled within the hook...
1364 $status->fatal( 'hookaborted' );
1365 $status->value
= self
::AS_HOOK_ERROR
;
1366 wfProfileOut( __METHOD__
);
1368 } elseif ( $this->hookError
!= '' ) {
1369 # ...or the hook could be expecting us to produce an error
1370 $status->fatal( 'hookaborted' );
1371 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1372 wfProfileOut( __METHOD__
);
1376 $content = $textbox_content;
1378 $result['sectionanchor'] = '';
1379 if ( $this->section
== 'new' ) {
1380 if ( $this->sectiontitle
!== '' ) {
1381 // Insert the section title above the content.
1382 $content = $content->addSectionHeader( $this->sectiontitle
);
1384 // Jump to the new section
1385 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1387 // If no edit summary was specified, create one automatically from the section
1388 // title and have it link to the new section. Otherwise, respect the summary as
1390 if ( $this->summary
=== '' ) {
1391 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1392 $this->summary
= wfMessage( 'newsectionsummary', $cleanSectionTitle )
1393 ->inContentLanguage()->text() ;
1395 } elseif ( $this->summary
!== '' ) {
1396 // Insert the section title above the content.
1397 $content = $content->addSectionHeader( $this->summary
);
1399 // Jump to the new section
1400 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1402 // Create a link to the new section from the edit summary.
1403 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1404 $this->summary
= wfMessage( 'newsectionsummary', $cleanSummary )
1405 ->inContentLanguage()->text();
1409 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1413 # Article exists. Check for edit conflict.
1415 $this->mArticle
->clear(); # Force reload of dates, etc.
1416 $timestamp = $this->mArticle
->getTimestamp();
1418 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1420 if ( $timestamp != $this->edittime
) {
1421 $this->isConflict
= true;
1422 if ( $this->section
== 'new' ) {
1423 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1424 $this->mArticle
->getComment() == $this->summary
) {
1425 // Probably a duplicate submission of a new comment.
1426 // This can happen when squid resends a request after
1427 // a timeout but the first one actually went through.
1428 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1430 // New comment; suppress conflict.
1431 $this->isConflict
= false;
1432 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1434 } elseif ( $this->section
== '' && Revision
::userWasLastToEdit( DB_MASTER
, $this->mTitle
->getArticleID(),
1435 $wgUser->getId(), $this->edittime
) ) {
1436 # Suppress edit conflict with self, except for section edits where merging is required.
1437 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1438 $this->isConflict
= false;
1442 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1443 // backwards compatibility with old forms/bots).
1444 if ( $this->sectiontitle
!== '' ) {
1445 $sectionTitle = $this->sectiontitle
;
1447 $sectionTitle = $this->summary
;
1452 if ( $this->isConflict
) {
1453 wfDebug( __METHOD__
. ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1454 . " (article time '{$timestamp}')\n" );
1456 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1458 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1459 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1462 if ( is_null( $content ) ) {
1463 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1464 $this->isConflict
= true;
1465 $content = $textbox_content; // do not try to merge here!
1466 } elseif ( $this->isConflict
) {
1468 if ( $this->mergeChangesIntoContent( $textbox_content ) ) {
1469 // Successful merge! Maybe we should tell the user the good news?
1470 $this->isConflict
= false;
1471 $content = $textbox_content;
1472 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1474 $this->section
= '';
1475 #$this->textbox1 = $text; #redundant, nothing to do here?
1476 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1480 if ( $this->isConflict
) {
1481 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1482 wfProfileOut( __METHOD__
);
1486 // Run post-section-merge edit filter
1487 $hook_args = array( $this, $content, &$this->hookError
, $this->summary
);
1489 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged', $hook_args )
1490 ||
!wfRunHooks( 'EditFilterMergedContent', $hook_args ) ) {
1491 # Error messages etc. could be handled within the hook...
1492 $status->fatal( 'hookaborted' );
1493 $status->value
= self
::AS_HOOK_ERROR
;
1494 wfProfileOut( __METHOD__
);
1496 } elseif ( $this->hookError
!= '' ) {
1497 # ...or the hook could be expecting us to produce an error
1498 $status->fatal( 'hookaborted' );
1499 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1500 wfProfileOut( __METHOD__
);
1504 # Handle the user preference to force summaries here, but not for null edits
1505 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1506 && !$content->equals( $this->getOriginalContent() )
1507 && !$content->isRedirect() ) # check if it's not a redirect
1509 if ( md5( $this->summary
) == $this->autoSumm
) {
1510 $this->missingSummary
= true;
1511 $status->fatal( 'missingsummary' );
1512 $status->value
= self
::AS_SUMMARY_NEEDED
;
1513 wfProfileOut( __METHOD__
);
1518 # And a similar thing for new sections
1519 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1520 if ( trim( $this->summary
) == '' ) {
1521 $this->missingSummary
= true;
1522 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1523 $status->value
= self
::AS_SUMMARY_NEEDED
;
1524 wfProfileOut( __METHOD__
);
1530 wfProfileIn( __METHOD__
. '-sectionanchor' );
1531 $sectionanchor = '';
1532 if ( $this->section
== 'new' ) {
1533 if ( $this->textbox1
== '' ) {
1534 $this->missingComment
= true;
1535 $status->fatal( 'missingcommenttext' );
1536 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1537 wfProfileOut( __METHOD__
. '-sectionanchor' );
1538 wfProfileOut( __METHOD__
);
1541 if ( $this->sectiontitle
!== '' ) {
1542 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1543 // If no edit summary was specified, create one automatically from the section
1544 // title and have it link to the new section. Otherwise, respect the summary as
1546 if ( $this->summary
=== '' ) {
1547 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1548 $this->summary
= wfMessage( 'newsectionsummary', $cleanSectionTitle )
1549 ->inContentLanguage()->text();
1551 } elseif ( $this->summary
!== '' ) {
1552 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1553 # This is a new section, so create a link to the new section
1554 # in the revision summary.
1555 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1556 $this->summary
= wfMessage( 'newsectionsummary', $cleanSummary )
1557 ->inContentLanguage()->text();
1559 } elseif ( $this->section
!= '' ) {
1560 # Try to get a section anchor from the section source, redirect to edited section if header found
1561 # XXX: might be better to integrate this into Article::replaceSection
1562 # for duplicate heading checking and maybe parsing
1563 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1564 # we can't deal with anchors, includes, html etc in the header for now,
1565 # headline would need to be parsed to improve this
1566 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1567 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1570 $result['sectionanchor'] = $sectionanchor;
1571 wfProfileOut( __METHOD__
. '-sectionanchor' );
1573 // Save errors may fall down to the edit form, but we've now
1574 // merged the section into full text. Clear the section field
1575 // so that later submission of conflict forms won't try to
1576 // replace that into a duplicated mess.
1577 $this->textbox1
= $this->toEditText( $content );
1578 $this->section
= '';
1580 $status->value
= self
::AS_SUCCESS_UPDATE
;
1583 // Check for length errors again now that the section is merged in
1584 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1585 if ( $this->kblength
> $wgMaxArticleSize ) {
1586 $this->tooBig
= true;
1587 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1588 wfProfileOut( __METHOD__
);
1592 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1593 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1594 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1595 ( $bot ? EDIT_FORCE_BOT
: 0 );
1597 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags,
1598 false, null, $this->contentFormat
);
1600 if ( $doEditStatus->isOK() ) {
1601 $result['redirect'] = $content->isRedirect();
1602 $this->commitWatch();
1603 wfProfileOut( __METHOD__
);
1606 // Failure from doEdit()
1607 // Show the edit conflict page for certain recognized errors from doEdit(),
1608 // but don't show it for errors from extension hooks
1609 $errors = $doEditStatus->getErrorsArray();
1610 if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
1611 'edit-already-exists' ) ) )
1613 $this->isConflict
= true;
1614 // Destroys data doEdit() put in $status->value but who cares
1615 $doEditStatus->value
= self
::AS_END
;
1617 wfProfileOut( __METHOD__
);
1618 return $doEditStatus;
1623 * Commit the change of watch status
1625 protected function commitWatch() {
1627 if ( $wgUser->isLoggedIn() && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
) ) {
1628 $dbw = wfGetDB( DB_MASTER
);
1629 $dbw->begin( __METHOD__
);
1630 if ( $this->watchthis
) {
1631 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1633 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1635 $dbw->commit( __METHOD__
);
1643 * @param $editText string
1646 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1648 function mergeChangesInto( &$editText ){
1649 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1651 $editContent = $this->toEditContent( $editText );
1653 $ok = $this->mergeChangesIntoContent( $editContent );
1656 $editText = $this->toEditText( $editContent );
1667 * @parma $editText string
1672 private function mergeChangesIntoContent( &$editContent ){
1673 wfProfileIn( __METHOD__
);
1675 $db = wfGetDB( DB_MASTER
);
1677 // This is the revision the editor started from
1678 $baseRevision = $this->getBaseRevision();
1679 if ( is_null( $baseRevision ) ) {
1680 wfProfileOut( __METHOD__
);
1683 $baseContent = $baseRevision->getContent();
1685 // The current state, we want to merge updates into it
1686 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1687 if ( is_null( $currentRevision ) ) {
1688 wfProfileOut( __METHOD__
);
1691 $currentContent = $currentRevision->getContent();
1693 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
1695 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1698 $editContent = $result;
1699 wfProfileOut( __METHOD__
);
1702 wfProfileOut( __METHOD__
);
1710 function getBaseRevision() {
1711 if ( !$this->mBaseRevision
) {
1712 $db = wfGetDB( DB_MASTER
);
1713 $baseRevision = Revision
::loadFromTimestamp(
1714 $db, $this->mTitle
, $this->edittime
);
1715 return $this->mBaseRevision
= $baseRevision;
1717 return $this->mBaseRevision
;
1722 * Check given input text against $wgSpamRegex, and return the text of the first match.
1724 * @param $text string
1726 * @return string|bool matching string or false
1728 public static function matchSpamRegex( $text ) {
1729 global $wgSpamRegex;
1730 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1731 $regexes = (array)$wgSpamRegex;
1732 return self
::matchSpamRegexInternal( $text, $regexes );
1736 * Check given input text against $wgSpamRegex, and return the text of the first match.
1738 * @param $text string
1740 * @return string|bool matching string or false
1742 public static function matchSummarySpamRegex( $text ) {
1743 global $wgSummarySpamRegex;
1744 $regexes = (array)$wgSummarySpamRegex;
1745 return self
::matchSpamRegexInternal( $text, $regexes );
1749 * @param $text string
1750 * @param $regexes array
1751 * @return bool|string
1753 protected static function matchSpamRegexInternal( $text, $regexes ) {
1754 foreach ( $regexes as $regex ) {
1756 if ( preg_match( $regex, $text, $matches ) ) {
1763 function setHeaders() {
1764 global $wgOut, $wgUser;
1766 $wgOut->addModules( 'mediawiki.action.edit' );
1768 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1769 $wgOut->addModules( 'mediawiki.legacy.preview' );
1771 // Bug #19334: textarea jumps when editing articles in IE8
1772 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1774 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1776 # Enabled article-related sidebar, toplinks, etc.
1777 $wgOut->setArticleRelated( true );
1779 $contextTitle = $this->getContextTitle();
1780 if ( $this->isConflict
) {
1781 $msg = 'editconflict';
1782 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1783 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1785 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1786 'editing' : 'creating';
1788 # Use the title defined by DISPLAYTITLE magic word when present
1789 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1790 if ( $displayTitle === false ) {
1791 $displayTitle = $contextTitle->getPrefixedText();
1793 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1797 * Show all applicable editing introductions
1799 protected function showIntro() {
1800 global $wgOut, $wgUser;
1801 if ( $this->suppressIntro
) {
1805 $namespace = $this->mTitle
->getNamespace();
1807 if ( $namespace == NS_MEDIAWIKI
) {
1808 # Show a warning if editing an interface message
1809 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1810 } else if( $namespace == NS_FILE
) {
1811 # Show a hint to shared repo
1812 $file = wfFindFile( $this->mTitle
);
1813 if( $file && !$file->isLocal() ) {
1814 $descUrl = $file->getDescriptionUrl();
1815 # there must be a description url to show a hint to shared repo
1817 if( !$this->mTitle
->exists() ) {
1818 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1819 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1822 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1823 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1830 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1831 # Show log extract when the user is currently blocked
1832 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1833 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1834 $username = $parts[0];
1835 $user = User
::newFromName( $username, false /* allow IP users*/ );
1836 $ip = User
::isIP( $username );
1837 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1838 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1839 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1840 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1841 LogEventsList
::showLogExtract(
1844 $user->getUserPage(),
1848 'showIfEmpty' => false,
1850 'blocked-notice-logextract',
1851 $user->getName() # Support GENDER in notice
1857 # Try to add a custom edit intro, or use the standard one if this is not possible.
1858 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1859 if ( $wgUser->isLoggedIn() ) {
1860 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1862 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1865 # Give a notice if the user is editing a deleted/moved page...
1866 if ( !$this->mTitle
->exists() ) {
1867 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1868 '', array( 'lim' => 10,
1869 'conds' => array( "log_action != 'revision'" ),
1870 'showIfEmpty' => false,
1871 'msgKey' => array( 'recreate-moveddeleted-warn' ) )
1877 * Attempt to show a custom editing introduction, if supplied
1881 protected function showCustomIntro() {
1882 if ( $this->editintro
) {
1883 $title = Title
::newFromText( $this->editintro
);
1884 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1886 // Added using template syntax, to take <noinclude>'s into account.
1887 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1898 * Gets an editable textual representation of the given Content object.
1899 * The textual representation can be turned by into a Content object by the
1900 * toEditContent() method.
1902 * If the given Content object is not of a type that can be edited using the text base EditPage,
1903 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
1906 * @param Content $content
1907 * @return String the editable text form of the content.
1909 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
1911 protected function toEditText( Content
$content ) {
1912 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
1913 throw new MWException( "This content model can not be edited as text: "
1914 . ContentHandler
::getLocalizedName( $content->getModel() ) );
1917 return $content->serialize( $this->contentFormat
);
1921 * Turns the given text into a Content object by unserializing it.
1923 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
1924 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
1927 * @param String|null|false $text Text to unserialize
1928 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
1931 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
1932 * and $this->allowNonTextContent is not true.
1934 protected function toEditContent( $text ) {
1935 if ( $text === false ||
$text === null ) {
1939 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
1940 $this->contentModel
, $this->contentFormat
);
1942 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
1943 throw new MWException( "This content model can not be edited as text: "
1944 . ContentHandler
::getLocalizedName( $content->getModel() ) );
1951 * Send the edit form and related headers to $wgOut
1952 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1953 * during form output near the top, for captchas and the like.
1955 function showEditForm( $formCallback = null ) {
1956 global $wgOut, $wgUser;
1958 wfProfileIn( __METHOD__
);
1960 # need to parse the preview early so that we know which templates are used,
1961 # otherwise users with "show preview after edit box" will get a blank list
1962 # we parse this near the beginning so that setHeaders can do the title
1963 # setting work instead of leaving it in getPreviewText
1964 $previewOutput = '';
1965 if ( $this->formtype
== 'preview' ) {
1966 $previewOutput = $this->getPreviewText();
1969 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
1971 $this->setHeaders();
1973 if ( $this->showHeader() === false ) {
1974 wfProfileOut( __METHOD__
);
1978 $wgOut->addHTML( $this->editFormPageTop
);
1980 if ( $wgUser->getOption( 'previewontop' ) ) {
1981 $this->displayPreviewArea( $previewOutput, true );
1984 $wgOut->addHTML( $this->editFormTextTop
);
1986 $showToolbar = true;
1987 if ( $this->wasDeletedSinceLastEdit() ) {
1988 if ( $this->formtype
== 'save' ) {
1989 // Hide the toolbar and edit area, user can click preview to get it back
1990 // Add an confirmation checkbox and explanation.
1991 $showToolbar = false;
1993 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1994 'deletedwhileediting' );
1998 //@todo: add EditForm plugin interface and use it here!
1999 // search for textarea1 and textares2, and allow EditForm to override all uses.
2000 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => self
::EDITFORM_ID
, 'name' => self
::EDITFORM_ID
,
2001 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
2002 'enctype' => 'multipart/form-data' ) ) );
2004 if ( is_callable( $formCallback ) ) {
2005 call_user_func_array( $formCallback, array( &$wgOut ) );
2008 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2010 // Put these up at the top to ensure they aren't lost on early form submission
2011 $this->showFormBeforeText();
2013 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2014 $username = $this->lastDelete
->user_name
;
2015 $comment = $this->lastDelete
->log_comment
;
2017 // It is better to not parse the comment at all than to have templates expanded in the middle
2018 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2019 $key = $comment === ''
2020 ?
'confirmrecreate-noreason'
2021 : 'confirmrecreate';
2023 '<div class="mw-confirm-recreate">' .
2024 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2025 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2026 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2032 # When the summary is hidden, also hide them on preview/show changes
2033 if( $this->nosummary
) {
2034 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2037 # If a blank edit summary was previously provided, and the appropriate
2038 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2039 # user being bounced back more than once in the event that a summary
2042 # For a bit more sophisticated detection of blank summaries, hash the
2043 # automatic one and pass that in the hidden field wpAutoSummary.
2044 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2045 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2048 if ( $this->undidRev
) {
2049 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2052 if ( $this->hasPresetSummary
) {
2053 // If a summary has been preset using &summary= we dont want to prompt for
2054 // a different summary. Only prompt for a summary if the summary is blanked.
2056 $this->autoSumm
= md5( '' );
2059 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2060 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2062 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2064 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2065 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2067 if ( $this->section
== 'new' ) {
2068 $this->showSummaryInput( true, $this->summary
);
2069 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2072 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2074 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2075 $wgOut->addHTML( EditPage
::getEditToolbar() );
2078 if ( $this->isConflict
) {
2079 // In an edit conflict bypass the overrideable content form method
2080 // and fallback to the raw wpTextbox1 since editconflicts can't be
2081 // resolved between page source edits and custom ui edits using the
2083 $this->textbox2
= $this->textbox1
;
2085 $content = $this->getCurrentContent();
2086 $this->textbox1
= $this->toEditText( $content );
2088 $this->showTextbox1();
2090 $this->showContentForm();
2093 $wgOut->addHTML( $this->editFormTextAfterContent
);
2095 $this->showStandardInputs();
2097 $this->showFormAfterText();
2099 $this->showTosSummary();
2101 $this->showEditTools();
2103 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2105 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2106 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2108 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2109 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2111 if ( $this->isConflict
) {
2113 $this->showConflict();
2114 } catch ( MWContentSerializationException
$ex ) {
2115 // this can't really happen, but be nice if it does.
2116 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2117 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2121 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2123 if ( !$wgUser->getOption( 'previewontop' ) ) {
2124 $this->displayPreviewArea( $previewOutput, false );
2127 wfProfileOut( __METHOD__
);
2131 * Extract the section title from current section text, if any.
2133 * @param string $text
2134 * @return Mixed|string or false
2136 public static function extractSectionTitle( $text ) {
2137 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2138 if ( !empty( $matches[2] ) ) {
2140 return $wgParser->stripSectionName( trim( $matches[2] ) );
2146 protected function showHeader() {
2147 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2149 if ( $this->mTitle
->isTalkPage() ) {
2150 $wgOut->addWikiMsg( 'talkpagetext' );
2153 # Optional notices on a per-namespace and per-page basis
2154 $editnotice_ns = 'editnotice-' . $this->mTitle
->getNamespace();
2155 $editnotice_ns_message = wfMessage( $editnotice_ns );
2156 if ( $editnotice_ns_message->exists() ) {
2157 $wgOut->addWikiText( $editnotice_ns_message->plain() );
2159 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
2160 $parts = explode( '/', $this->mTitle
->getDBkey() );
2161 $editnotice_base = $editnotice_ns;
2162 while ( count( $parts ) > 0 ) {
2163 $editnotice_base .= '-' . array_shift( $parts );
2164 $editnotice_base_msg = wfMessage( $editnotice_base );
2165 if ( $editnotice_base_msg->exists() ) {
2166 $wgOut->addWikiText( $editnotice_base_msg->plain() );
2170 # Even if there are no subpages in namespace, we still don't want / in MW ns.
2171 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
2172 $editnoticeMsg = wfMessage( $editnoticeText );
2173 if ( $editnoticeMsg->exists() ) {
2174 $wgOut->addWikiText( $editnoticeMsg->plain() );
2178 if ( $this->isConflict
) {
2179 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2180 $this->edittime
= $this->mArticle
->getTimestamp();
2182 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2183 // We use $this->section to much before this and getVal('wgSection') directly in other places
2184 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2185 // Someone is welcome to try refactoring though
2186 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2190 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2191 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2192 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2193 if ( $sectionTitle !== false ) {
2194 $this->summary
= "/* $sectionTitle */ ";
2199 if ( $this->missingComment
) {
2200 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2203 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2204 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2207 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2208 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2211 if ( $this->hookError
!== '' ) {
2212 $wgOut->addWikiText( $this->hookError
);
2215 if ( !$this->checkUnicodeCompliantBrowser() ) {
2216 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2219 if ( $this->section
!= 'new' ) {
2220 $revision = $this->mArticle
->getRevisionFetched();
2222 // Let sysop know that this will make private content public if saved
2224 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
2225 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2226 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2227 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2230 if ( !$revision->isCurrent() ) {
2231 $this->mArticle
->setOldSubtitle( $revision->getId() );
2232 $wgOut->addWikiMsg( 'editingold' );
2234 } elseif ( $this->mTitle
->exists() ) {
2235 // Something went wrong
2237 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2238 array( 'missing-revision', $this->oldid
) );
2243 if ( wfReadOnly() ) {
2244 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2245 } elseif ( $wgUser->isAnon() ) {
2246 if ( $this->formtype
!= 'preview' ) {
2247 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2249 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2252 if ( $this->isCssJsSubpage
) {
2253 # Check the skin exists
2254 if ( $this->isWrongCaseCssJsPage
) {
2255 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2257 if ( $this->formtype
!== 'preview' ) {
2258 if ( $this->isCssSubpage
)
2259 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2260 if ( $this->isJsSubpage
)
2261 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2266 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2267 # Is the title semi-protected?
2268 if ( $this->mTitle
->isSemiProtected() ) {
2269 $noticeMsg = 'semiprotectedpagewarning';
2271 # Then it must be protected based on static groups (regular)
2272 $noticeMsg = 'protectedpagewarning';
2274 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2275 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2277 if ( $this->mTitle
->isCascadeProtected() ) {
2278 # Is this page under cascading protection from some source pages?
2279 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2280 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2281 $cascadeSourcesCount = count( $cascadeSources );
2282 if ( $cascadeSourcesCount > 0 ) {
2283 # Explain, and list the titles responsible
2284 foreach ( $cascadeSources as $page ) {
2285 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2288 $notice .= '</div>';
2289 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2291 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2292 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2294 'showIfEmpty' => false,
2295 'msgKey' => array( 'titleprotectedwarning' ),
2296 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2299 if ( $this->kblength
=== false ) {
2300 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2303 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2304 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2305 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2307 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2308 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2309 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2313 # Add header copyright warning
2314 $this->showHeaderCopyrightWarning();
2319 * Standard summary input and label (wgSummary), abstracted so EditPage
2320 * subclasses may reorganize the form.
2321 * Note that you do not need to worry about the label's for=, it will be
2322 * inferred by the id given to the input. You can remove them both by
2323 * passing array( 'id' => false ) to $userInputAttrs.
2325 * @param $summary string The value of the summary input
2326 * @param $labelText string The html to place inside the label
2327 * @param $inputAttrs array of attrs to use on the input
2328 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2330 * @return array An array in the format array( $label, $input )
2332 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2333 // Note: the maxlength is overriden in JS to 255 and to make it use UTF-8 bytes, not characters.
2334 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2335 'id' => 'wpSummary',
2336 'maxlength' => '200',
2339 'spellcheck' => 'true',
2340 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2342 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2343 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2344 'id' => "wpSummaryLabel"
2349 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2350 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2353 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2355 return array( $label, $input );
2359 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2360 * up top, or false if this is the comment summary
2361 * down below the textarea
2362 * @param $summary String: The text of the summary to display
2365 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2366 global $wgOut, $wgContLang;
2367 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2368 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2369 if ( $isSubjectPreview ) {
2370 if ( $this->nosummary
) {
2374 if ( !$this->mShowSummaryField
) {
2378 $summary = $wgContLang->recodeForEdit( $summary );
2379 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2380 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2381 $wgOut->addHTML( "{$label} {$input}" );
2385 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2386 * up top, or false if this is the comment summary
2387 * down below the textarea
2388 * @param $summary String: the text of the summary to display
2391 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2392 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2397 if ( $isSubjectPreview )
2398 $summary = wfMessage( 'newsectionsummary', $wgParser->stripSectionName( $summary ) )
2399 ->inContentLanguage()->text();
2401 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2403 $summary = wfMessage( $message )->parse() . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2404 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2407 protected function showFormBeforeText() {
2409 $section = htmlspecialchars( $this->section
);
2410 $wgOut->addHTML( <<<HTML
2411 <input type='hidden' value="{$section}" name="wpSection" />
2412 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2413 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2414 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2418 if ( !$this->checkUnicodeCompliantBrowser() )
2419 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2422 protected function showFormAfterText() {
2423 global $wgOut, $wgUser;
2425 * To make it harder for someone to slip a user a page
2426 * which submits an edit form to the wiki without their
2427 * knowledge, a random token is associated with the login
2428 * session. If it's not passed back with the submission,
2429 * we won't save the page, or render user JavaScript and
2432 * For anon editors, who may not have a session, we just
2433 * include the constant suffix to prevent editing from
2434 * broken text-mangling proxies.
2436 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2440 * Subpage overridable method for printing the form for page content editing
2441 * By default this simply outputs wpTextbox1
2442 * Subclasses can override this to provide a custom UI for editing;
2443 * be it a form, or simply wpTextbox1 with a modified content that will be
2444 * reverse modified when extracted from the post data.
2445 * Note that this is basically the inverse for importContentFormData
2447 protected function showContentForm() {
2448 $this->showTextbox1();
2452 * Method to output wpTextbox1
2453 * The $textoverride method can be used by subclasses overriding showContentForm
2454 * to pass back to this method.
2456 * @param $customAttribs array of html attributes to use in the textarea
2457 * @param $textoverride String: optional text to override $this->textarea1 with
2459 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2460 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2461 $attribs = array( 'style' => 'display:none;' );
2463 $classes = array(); // Textarea CSS
2464 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2465 # Is the title semi-protected?
2466 if ( $this->mTitle
->isSemiProtected() ) {
2467 $classes[] = 'mw-textarea-sprotected';
2469 # Then it must be protected based on static groups (regular)
2470 $classes[] = 'mw-textarea-protected';
2472 # Is the title cascade-protected?
2473 if ( $this->mTitle
->isCascadeProtected() ) {
2474 $classes[] = 'mw-textarea-cprotected';
2478 $attribs = array( 'tabindex' => 1 );
2480 if ( is_array( $customAttribs ) ) {
2481 $attribs +
= $customAttribs;
2484 if ( count( $classes ) ) {
2485 if ( isset( $attribs['class'] ) ) {
2486 $classes[] = $attribs['class'];
2488 $attribs['class'] = implode( ' ', $classes );
2492 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2495 protected function showTextbox2() {
2496 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2499 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2500 global $wgOut, $wgUser;
2502 $wikitext = $this->safeUnicodeOutput( $text );
2503 if ( strval( $wikitext ) !== '' ) {
2504 // Ensure there's a newline at the end, otherwise adding lines
2506 // But don't add a newline if the ext is empty, or Firefox in XHTML
2507 // mode will show an extra newline. A bit annoying.
2511 $attribs = $customAttribs +
array(
2514 'cols' => $wgUser->getIntOption( 'cols' ),
2515 'rows' => $wgUser->getIntOption( 'rows' ),
2516 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2519 $pageLang = $this->mTitle
->getPageLanguage();
2520 $attribs['lang'] = $pageLang->getCode();
2521 $attribs['dir'] = $pageLang->getDir();
2523 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2526 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2530 $classes[] = 'ontop';
2532 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2534 if ( $this->formtype
!= 'preview' )
2535 $attribs['style'] = 'display: none;';
2537 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2539 if ( $this->formtype
== 'preview' ) {
2540 $this->showPreview( $previewOutput );
2543 $wgOut->addHTML( '</div>' );
2545 if ( $this->formtype
== 'diff' ) {
2548 } catch ( MWContentSerializationException
$ex ) {
2549 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2550 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2556 * Append preview output to $wgOut.
2557 * Includes category rendering if this is a category page.
2559 * @param $text String: the HTML to be output for the preview.
2561 protected function showPreview( $text ) {
2563 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2564 $this->mArticle
->openShowCategory();
2566 # This hook seems slightly odd here, but makes things more
2567 # consistent for extensions.
2568 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2569 $wgOut->addHTML( $text );
2570 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2571 $this->mArticle
->closeShowCategory();
2576 * Get a diff between the current contents of the edit box and the
2577 * version of the page we're editing from.
2579 * If this is a section edit, we'll replace the section as for final
2580 * save and then make a comparison.
2582 function showDiff() {
2583 global $wgUser, $wgContLang, $wgParser, $wgOut;
2585 $oldtitlemsg = 'currentrev';
2586 # if message does not exist, show diff against the preloaded default
2587 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2588 $oldtext = $this->mTitle
->getDefaultMessageText();
2589 if( $oldtext !== false ) {
2590 $oldtitlemsg = 'defaultmessagetext';
2591 $oldContent = $this->toEditContent( $oldtext );
2596 $oldContent = $this->getOriginalContent();
2599 $textboxContent = $this->toEditContent( $this->textbox1
);
2601 $newContent = $this->mArticle
->replaceSectionContent(
2602 $this->section
, $textboxContent,
2603 $this->summary
, $this->edittime
);
2605 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2606 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2608 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2609 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2611 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2612 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2613 $newtitle = wfMessage( 'yourtext' )->parse();
2615 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
2616 $de->setContent( $oldContent, $newContent );
2618 $difftext = $de->getDiff( $oldtitle, $newtitle );
2619 $de->showDiffStyle();
2624 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2628 * Show the header copyright warning.
2630 protected function showHeaderCopyrightWarning() {
2631 $msg = 'editpage-head-copy-warn';
2632 if ( !wfMessage( $msg )->isDisabled() ) {
2634 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2635 'editpage-head-copy-warn' );
2640 * Give a chance for site and per-namespace customizations of
2641 * terms of service summary link that might exist separately
2642 * from the copyright notice.
2644 * This will display between the save button and the edit tools,
2645 * so should remain short!
2647 protected function showTosSummary() {
2648 $msg = 'editpage-tos-summary';
2649 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2650 if ( !wfMessage( $msg )->isDisabled() ) {
2652 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2653 $wgOut->addWikiMsg( $msg );
2654 $wgOut->addHTML( '</div>' );
2658 protected function showEditTools() {
2660 $wgOut->addHTML( '<div class="mw-editTools">' .
2661 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2666 * Get the copyright warning
2668 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2670 protected function getCopywarn() {
2671 return self
::getCopyrightWarning( $this->mTitle
);
2674 public static function getCopyrightWarning( $title ) {
2675 global $wgRightsText;
2676 if ( $wgRightsText ) {
2677 $copywarnMsg = array( 'copyrightwarning',
2678 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2681 $copywarnMsg = array( 'copyrightwarning2',
2682 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2684 // Allow for site and per-namespace customization of contribution/copyright notice.
2685 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2687 return "<div id=\"editpage-copywarn\">\n" .
2688 call_user_func_array( 'wfMessage', $copywarnMsg )->plain() . "\n</div>";
2691 protected function showStandardInputs( &$tabindex = 2 ) {
2693 $wgOut->addHTML( "<div class='editOptions'>\n" );
2695 if ( $this->section
!= 'new' ) {
2696 $this->showSummaryInput( false, $this->summary
);
2697 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2700 $checkboxes = $this->getCheckboxes( $tabindex,
2701 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2702 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2704 // Show copyright warning.
2705 $wgOut->addWikiText( $this->getCopywarn() );
2706 $wgOut->addHTML( $this->editFormTextAfterWarn
);
2708 $wgOut->addHTML( "<div class='editButtons'>\n" );
2709 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2711 $cancel = $this->getCancelLink();
2712 if ( $cancel !== '' ) {
2713 $cancel .= wfMessage( 'pipe-separator' )->text();
2715 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
2716 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2717 wfMessage( 'edithelp' )->escaped() . '</a> ' .
2718 wfMessage( 'newwindow' )->parse();
2719 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
2720 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
2721 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2725 * Show an edit conflict. textbox1 is already shown in showEditForm().
2726 * If you want to use another entry point to this function, be careful.
2728 protected function showConflict() {
2731 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2732 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2734 $content1 = $this->toEditContent( $this->textbox1
);
2735 $content2 = $this->toEditContent( $this->textbox2
);
2737 $handler = ContentHandler
::getForModelID( $this->contentModel
);
2738 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
2739 $de->setContent( $content2, $content1 );
2741 wfMessage( 'yourtext' )->parse(),
2742 wfMessage( 'storedversion' )->text()
2745 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2746 $this->showTextbox2();
2753 public function getCancelLink() {
2754 $cancelParams = array();
2755 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2756 $cancelParams['oldid'] = $this->oldid
;
2759 return Linker
::linkKnown(
2760 $this->getContextTitle(),
2761 wfMessage( 'cancel' )->parse(),
2762 array( 'id' => 'mw-editform-cancel' ),
2768 * Returns the URL to use in the form's action attribute.
2769 * This is used by EditPage subclasses when simply customizing the action
2770 * variable in the constructor is not enough. This can be used when the
2771 * EditPage lives inside of a Special page rather than a custom page action.
2773 * @param $title Title object for which is being edited (where we go to for &action= links)
2776 protected function getActionURL( Title
$title ) {
2777 return $title->getLocalURL( array( 'action' => $this->action
) );
2781 * Check if a page was deleted while the user was editing it, before submit.
2782 * Note that we rely on the logging table, which hasn't been always there,
2783 * but that doesn't matter, because this only applies to brand new
2786 protected function wasDeletedSinceLastEdit() {
2787 if ( $this->deletedSinceEdit
!== null ) {
2788 return $this->deletedSinceEdit
;
2791 $this->deletedSinceEdit
= false;
2793 if ( $this->mTitle
->isDeletedQuick() ) {
2794 $this->lastDelete
= $this->getLastDelete();
2795 if ( $this->lastDelete
) {
2796 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2797 if ( $deleteTime > $this->starttime
) {
2798 $this->deletedSinceEdit
= true;
2803 return $this->deletedSinceEdit
;
2806 protected function getLastDelete() {
2807 $dbr = wfGetDB( DB_SLAVE
);
2808 $data = $dbr->selectRow(
2809 array( 'logging', 'user' ),
2820 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2821 'log_title' => $this->mTitle
->getDBkey(),
2822 'log_type' => 'delete',
2823 'log_action' => 'delete',
2824 'user_id=log_user' ),
2826 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2828 // Quick paranoid permission checks...
2829 if ( is_object( $data ) ) {
2830 if ( $data->log_deleted
& LogPage
::DELETED_USER
)
2831 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
2832 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2833 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
2839 * Get the rendered text for previewing.
2840 * @throws MWException
2843 function getPreviewText() {
2844 global $wgOut, $wgUser, $wgParser, $wgRawHtml, $wgLang;
2846 wfProfileIn( __METHOD__
);
2848 if ( $wgRawHtml && !$this->mTokenOk
) {
2849 // Could be an offsite preview attempt. This is very unsafe if
2850 // HTML is enabled, as it could be an attack.
2852 if ( $this->textbox1
!== '' ) {
2853 // Do not put big scary notice, if previewing the empty
2854 // string, which happens when you initially edit
2855 // a category page, due to automatic preview-on-open.
2856 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2857 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
2859 wfProfileOut( __METHOD__
);
2866 $content = $this->toEditContent( $this->textbox1
);
2868 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2869 if ( $this->mTokenOkExceptSuffix
) {
2870 $note = wfMessage( 'token_suffix_mismatch' )->plain() ;
2873 $note = wfMessage( 'session_fail_preview' )->plain() ;
2875 } elseif ( $this->incompleteForm
) {
2876 $note = wfMessage( 'edit_form_incomplete' )->plain() ;
2878 $note = wfMessage( 'previewnote' )->plain() .
2879 ' [[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' . wfMessage( 'continue-editing' )->text() . ']]';
2882 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
2883 $parserOptions->setEditSection( false );
2884 $parserOptions->setIsPreview( true );
2885 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2887 # don't parse non-wikitext pages, show message about preview
2888 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
2889 if( $this->mTitle
->isCssJsSubpage() ) {
2891 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2897 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
2899 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
2905 # Used messages to make sure grep find them:
2906 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2907 if( $level && $format ) {
2908 $note = "<div id='mw-{$level}{$format}preview'>" . wfMessage( "{$level}{$format}preview" )->text() . "</div>";
2910 $note = wfMessage( 'previewnote' )->text() ;
2913 $note = wfMessage( 'previewnote' )->text() ;
2916 $rt = $content->getRedirectChain();
2918 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2921 # If we're adding a comment, we need to show the
2922 # summary as the headline
2923 if ( $this->section
=== "new" && $this->summary
!== "" ) {
2924 $content = $content->addSectionHeader( $this->summary
);
2927 $hook_args = array( $this, &$content );
2928 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
2929 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
2931 $parserOptions->enableLimitReport();
2933 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
2934 # But it's now deprecated, so never mind
2936 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
2937 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
2939 $previewHTML = $parserOutput->getText();
2940 $this->mParserOutput
= $parserOutput;
2941 $wgOut->addParserOutputNoText( $parserOutput );
2943 if ( count( $parserOutput->getWarnings() ) ) {
2944 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2947 } catch ( MWContentSerializationException
$ex ) {
2948 $m = wfMessage('content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2949 $note .= "\n\n" . $m->parse();
2953 if ( $this->isConflict
) {
2954 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
2956 $conflict = '<hr />';
2959 $previewhead = "<div class='previewnote'>\n" .
2960 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
2961 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2963 $pageLang = $this->mTitle
->getPageLanguage();
2964 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2965 'class' => 'mw-content-' . $pageLang->getDir() );
2966 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2968 wfProfileOut( __METHOD__
);
2969 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2975 function getTemplates() {
2976 if ( $this->preview ||
$this->section
!= '' ) {
2977 $templates = array();
2978 if ( !isset( $this->mParserOutput
) ) {
2981 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
2982 foreach ( array_keys( $template ) as $dbk ) {
2983 $templates[] = Title
::makeTitle( $ns, $dbk );
2988 return $this->mTitle
->getTemplateLinksFrom();
2993 * Shows a bulletin board style toolbar for common editing functions.
2994 * It can be disabled in the user preferences.
2995 * The necessary JavaScript code can be found in skins/common/edit.js.
2999 static function getEditToolbar() {
3000 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3001 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
3003 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3006 * $toolarray is an array of arrays each of which includes the
3007 * filename of the button image (without path), the opening
3008 * tag, the closing tag, optionally a sample text that is
3009 * inserted between the two when no selection is highlighted
3010 * and. The tip text is shown when the user moves the mouse
3013 * Also here: accesskeys (key), which are not used yet until
3014 * someone can figure out a way to make them work in
3015 * IE. However, we should make sure these keys are not defined
3020 'image' => $wgLang->getImageFile( 'button-bold' ),
3021 'id' => 'mw-editbutton-bold',
3023 'close' => '\'\'\'',
3024 'sample' => wfMessage( 'bold_sample' )->text(),
3025 'tip' => wfMessage( 'bold_tip' )->text(),
3029 'image' => $wgLang->getImageFile( 'button-italic' ),
3030 'id' => 'mw-editbutton-italic',
3033 'sample' => wfMessage( 'italic_sample' )->text(),
3034 'tip' => wfMessage( 'italic_tip' )->text(),
3038 'image' => $wgLang->getImageFile( 'button-link' ),
3039 'id' => 'mw-editbutton-link',
3042 'sample' => wfMessage( 'link_sample' )->text(),
3043 'tip' => wfMessage( 'link_tip' )->text(),
3047 'image' => $wgLang->getImageFile( 'button-extlink' ),
3048 'id' => 'mw-editbutton-extlink',
3051 'sample' => wfMessage( 'extlink_sample' )->text(),
3052 'tip' => wfMessage( 'extlink_tip' )->text(),
3056 'image' => $wgLang->getImageFile( 'button-headline' ),
3057 'id' => 'mw-editbutton-headline',
3060 'sample' => wfMessage( 'headline_sample' )->text(),
3061 'tip' => wfMessage( 'headline_tip' )->text(),
3064 $imagesAvailable ?
array(
3065 'image' => $wgLang->getImageFile( 'button-image' ),
3066 'id' => 'mw-editbutton-image',
3067 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3069 'sample' => wfMessage( 'image_sample' )->text(),
3070 'tip' => wfMessage( 'image_tip' )->text(),
3073 $imagesAvailable ?
array(
3074 'image' => $wgLang->getImageFile( 'button-media' ),
3075 'id' => 'mw-editbutton-media',
3076 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3078 'sample' => wfMessage( 'media_sample' )->text(),
3079 'tip' => wfMessage( 'media_tip' )->text(),
3083 'image' => $wgLang->getImageFile( 'button-math' ),
3084 'id' => 'mw-editbutton-math',
3086 'close' => "</math>",
3087 'sample' => wfMessage( 'math_sample' )->text(),
3088 'tip' => wfMessage( 'math_tip' )->text(),
3092 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3093 'id' => 'mw-editbutton-nowiki',
3094 'open' => "<nowiki>",
3095 'close' => "</nowiki>",
3096 'sample' => wfMessage( 'nowiki_sample' )->text(),
3097 'tip' => wfMessage( 'nowiki_tip' )->text(),
3101 'image' => $wgLang->getImageFile( 'button-sig' ),
3102 'id' => 'mw-editbutton-signature',
3106 'tip' => wfMessage( 'sig_tip' )->text(),
3110 'image' => $wgLang->getImageFile( 'button-hr' ),
3111 'id' => 'mw-editbutton-hr',
3112 'open' => "\n----\n",
3115 'tip' => wfMessage( 'hr_tip' )->text(),
3120 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3121 foreach ( $toolarray as $tool ) {
3127 $image = $wgStylePath . '/common/images/' . $tool['image'],
3128 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3129 // Older browsers show a "speedtip" type message only for ALT.
3130 // Ideally these should be different, realistically they
3131 // probably don't need to be.
3132 $tip = $tool['tip'],
3133 $open = $tool['open'],
3134 $close = $tool['close'],
3135 $sample = $tool['sample'],
3136 $cssId = $tool['id'],
3139 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3142 // This used to be called on DOMReady from mediawiki.action.edit, which
3143 // ended up causing race conditions with the setup code above.
3145 "// Create button bar\n" .
3146 "$(function() { mw.toolbar.init(); } );\n";
3149 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3151 $toolbar = '<div id="toolbar"></div>';
3153 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3159 * Returns an array of html code of the following checkboxes:
3162 * @param $tabindex int Current tabindex
3163 * @param $checked Array of checkbox => bool, where bool indicates the checked
3164 * status of the checkbox
3168 public function getCheckboxes( &$tabindex, $checked ) {
3171 $checkboxes = array();
3173 // don't show the minor edit checkbox if it's a new page or section
3174 if ( !$this->isNew
) {
3175 $checkboxes['minor'] = '';
3176 $minorLabel = wfMessage( 'minoredit' )->parse();
3177 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3179 'tabindex' => ++
$tabindex,
3180 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3181 'id' => 'wpMinoredit',
3183 $checkboxes['minor'] =
3184 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3185 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3186 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3187 ">{$minorLabel}</label>";
3191 $watchLabel = wfMessage( 'watchthis' )->parse();
3192 $checkboxes['watch'] = '';
3193 if ( $wgUser->isLoggedIn() ) {
3195 'tabindex' => ++
$tabindex,
3196 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3197 'id' => 'wpWatchthis',
3199 $checkboxes['watch'] =
3200 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3201 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3202 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3203 ">{$watchLabel}</label>";
3205 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3210 * Returns an array of html code of the following buttons:
3211 * save, diff, preview and live
3213 * @param $tabindex int Current tabindex
3217 public function getEditButtons( &$tabindex ) {
3224 'tabindex' => ++
$tabindex,
3225 'value' => wfMessage( 'savearticle' )->text(),
3226 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3227 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3229 $buttons['save'] = Xml
::element( 'input', $temp, '' );
3231 ++
$tabindex; // use the same for preview and live preview
3233 'id' => 'wpPreview',
3234 'name' => 'wpPreview',
3236 'tabindex' => $tabindex,
3237 'value' => wfMessage( 'showpreview' )->text(),
3238 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3239 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3241 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3242 $buttons['live'] = '';
3248 'tabindex' => ++
$tabindex,
3249 'value' => wfMessage( 'showdiff' )->text(),
3250 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3251 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3253 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3255 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3260 * Output preview text only. This can be sucked into the edit page
3261 * via JavaScript, and saves the server time rendering the skin as
3262 * well as theoretically being more robust on the client (doesn't
3263 * disturb the edit box's undo history, won't eat your text on
3266 * @todo This doesn't include category or interlanguage links.
3267 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3268 * or something...</s>" that might also require more skin
3269 * initialization, so check whether that's a problem.
3271 function livePreview() {
3274 header( 'Content-type: text/xml; charset=utf-8' );
3275 header( 'Cache-control: no-cache' );
3277 $previewText = $this->getPreviewText();
3278 #$categories = $skin->getCategoryLinks();
3281 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3282 Xml
::tags( 'livepreview', null,
3283 Xml
::element( 'preview', null, $previewText )
3284 #. Xml::element( 'category', null, $categories )
3290 * Call the stock "user is blocked" page
3292 * @deprecated in 1.19; throw an exception directly instead
3294 function blockedPage() {
3295 wfDeprecated( __METHOD__
, '1.19' );
3298 throw new UserBlockedError( $wgUser->getBlock() );
3302 * Produce the stock "please login to edit pages" page
3304 * @deprecated in 1.19; throw an exception directly instead
3306 function userNotLoggedInPage() {
3307 wfDeprecated( __METHOD__
, '1.19' );
3308 throw new PermissionsError( 'edit' );
3312 * Show an error page saying to the user that he has insufficient permissions
3313 * to create a new page
3315 * @deprecated in 1.19; throw an exception directly instead
3317 function noCreatePermission() {
3318 wfDeprecated( __METHOD__
, '1.19' );
3319 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3320 throw new PermissionsError( $permission );
3324 * Creates a basic error page which informs the user that
3325 * they have attempted to edit a nonexistent section.
3327 function noSuchSectionPage() {
3330 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3332 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3333 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3334 $wgOut->addHTML( $res );
3336 $wgOut->returnToMain( false, $this->mTitle
);
3340 * Produce the stock "your edit contains spam" page
3342 * @param $match string Text which triggered one or more filters
3343 * @deprecated since 1.17 Use method spamPageWithContent() instead
3345 static function spamPage( $match = false ) {
3346 wfDeprecated( __METHOD__
, '1.17' );
3348 global $wgOut, $wgTitle;
3350 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3352 $wgOut->addHTML( '<div id="spamprotected">' );
3353 $wgOut->addWikiMsg( 'spamprotectiontext' );
3355 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3357 $wgOut->addHTML( '</div>' );
3359 $wgOut->returnToMain( false, $wgTitle );
3363 * Show "your edit contains spam" page with your diff and text
3365 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3367 public function spamPageWithContent( $match = false ) {
3368 global $wgOut, $wgLang;
3369 $this->textbox2
= $this->textbox1
;
3371 if( is_array( $match ) ){
3372 $match = $wgLang->listToText( $match );
3374 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3376 $wgOut->addHTML( '<div id="spamprotected">' );
3377 $wgOut->addWikiMsg( 'spamprotectiontext' );
3379 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3381 $wgOut->addHTML( '</div>' );
3383 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3386 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3387 $this->showTextbox2();
3389 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3393 * Format an anchor fragment as it would appear for a given section name
3394 * @param $text String
3398 function sectionAnchor( $text ) {
3400 return $wgParser->guessSectionNameFromWikiText( $text );
3404 * Check if the browser is on a blacklist of user-agents known to
3405 * mangle UTF-8 data on form submission. Returns true if Unicode
3406 * should make it through, false if it's known to be a problem.
3410 function checkUnicodeCompliantBrowser() {
3411 global $wgBrowserBlackList, $wgRequest;
3413 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3414 if ( $currentbrowser === false ) {
3415 // No User-Agent header sent? Trust it by default...
3419 foreach ( $wgBrowserBlackList as $browser ) {
3420 if ( preg_match( $browser, $currentbrowser ) ) {
3428 * Filter an input field through a Unicode de-armoring process if it
3429 * came from an old browser with known broken Unicode editing issues.
3431 * @param $request WebRequest
3432 * @param $field String
3436 function safeUnicodeInput( $request, $field ) {
3437 $text = rtrim( $request->getText( $field ) );
3438 return $request->getBool( 'safemode' )
3439 ?
$this->unmakesafe( $text )
3444 * @param $request WebRequest
3445 * @param $text string
3448 function safeUnicodeText( $request, $text ) {
3449 $text = rtrim( $text );
3450 return $request->getBool( 'safemode' )
3451 ?
$this->unmakesafe( $text )
3456 * Filter an output field through a Unicode armoring process if it is
3457 * going to an old browser with known broken Unicode editing issues.
3459 * @param $text String
3463 function safeUnicodeOutput( $text ) {
3465 $codedText = $wgContLang->recodeForEdit( $text );
3466 return $this->checkUnicodeCompliantBrowser()
3468 : $this->makesafe( $codedText );
3472 * A number of web browsers are known to corrupt non-ASCII characters
3473 * in a UTF-8 text editing environment. To protect against this,
3474 * detected browsers will be served an armored version of the text,
3475 * with non-ASCII chars converted to numeric HTML character references.
3477 * Preexisting such character references will have a 0 added to them
3478 * to ensure that round-trips do not alter the original data.
3480 * @param $invalue String
3484 function makesafe( $invalue ) {
3485 // Armor existing references for reversability.
3486 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3491 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3492 $bytevalue = ord( $invalue[$i] );
3493 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3494 $result .= chr( $bytevalue );
3496 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3497 $working = $working << 6;
3498 $working +
= ( $bytevalue & 0x3F );
3500 if ( $bytesleft <= 0 ) {
3501 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3503 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3504 $working = $bytevalue & 0x1F;
3506 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3507 $working = $bytevalue & 0x0F;
3509 } else { // 1111 0xxx
3510 $working = $bytevalue & 0x07;
3518 * Reverse the previously applied transliteration of non-ASCII characters
3519 * back to UTF-8. Used to protect data from corruption by broken web browsers
3520 * as listed in $wgBrowserBlackList.
3522 * @param $invalue String
3526 function unmakesafe( $invalue ) {
3528 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3529 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3533 $hexstring .= $invalue[$i];
3535 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3537 // Do some sanity checks. These aren't needed for reversability,
3538 // but should help keep the breakage down if the editor
3539 // breaks one of the entities whilst editing.
3540 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3541 $codepoint = hexdec( $hexstring );
3542 $result .= codepointToUtf8( $codepoint );
3544 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3547 $result .= substr( $invalue, $i, 1 );
3550 // reverse the transform that we made for reversability reasons.
3551 return strtr( $result, array( "�" => "&#x" ) );