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__
);
413 if ( !$this->mTitle
->getArticleID() ) {
414 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
416 wfRunHooks( 'EditFormInitialText', array( $this ) );
421 $this->showEditForm();
422 wfProfileOut( __METHOD__
. "-business-end" );
423 wfProfileOut( __METHOD__
);
429 protected function getEditPermissionErrors() {
431 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
432 # Can this title be created?
433 if ( !$this->mTitle
->exists() ) {
434 $permErrors = array_merge( $permErrors,
435 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
437 # Ignore some permissions errors when a user is just previewing/viewing diffs
439 foreach ( $permErrors as $error ) {
440 if ( ( $this->preview ||
$this->diff
) &&
441 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
446 $permErrors = wfArrayDiff2( $permErrors, $remove );
451 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
452 * but with the following differences:
453 * - If redlink=1, the user will be redirected to the page
454 * - If there is content to display or the error occurs while either saving,
455 * previewing or showing the difference, it will be a
456 * "View source for ..." page displaying the source code after the error message.
459 * @param $permErrors Array of permissions errors, as returned by
460 * Title::getUserPermissionsErrors().
461 * @throws PermissionsError
463 protected function displayPermissionsError( array $permErrors ) {
464 global $wgRequest, $wgOut;
466 if ( $wgRequest->getBool( 'redlink' ) ) {
467 // The edit page was reached via a red link.
468 // Redirect to the article page and let them click the edit tab if
469 // they really want a permission error.
470 $wgOut->redirect( $this->mTitle
->getFullUrl() );
474 $content = $this->getContentObject();
476 # Use the normal message if there's nothing to display
477 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
478 $action = $this->mTitle
->exists() ?
'edit' :
479 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
480 throw new PermissionsError( $action, $permErrors );
483 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
484 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
485 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
486 $wgOut->addHTML( "<hr />\n" );
488 # If the user made changes, preserve them when showing the markup
489 # (This happens when a user is blocked during edit, for instance)
490 if ( !$this->firsttime
) {
491 $text = $this->textbox1
;
492 $wgOut->addWikiMsg( 'viewyourtext' );
494 $text = $this->toEditText( $content );
495 $wgOut->addWikiMsg( 'viewsourcetext' );
498 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
500 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
501 Linker
::formatTemplates( $this->getTemplates() ) ) );
503 if ( $this->mTitle
->exists() ) {
504 $wgOut->returnToMain( null, $this->mTitle
);
509 * Show a read-only error
510 * Parameters are the same as OutputPage:readOnlyPage()
511 * Redirect to the article page if redlink=1
512 * @deprecated in 1.19; use displayPermissionsError() instead
514 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
515 wfDeprecated( __METHOD__
, '1.19' );
517 global $wgRequest, $wgOut;
518 if ( $wgRequest->getBool( 'redlink' ) ) {
519 // The edit page was reached via a red link.
520 // Redirect to the article page and let them click the edit tab if
521 // they really want a permission error.
522 $wgOut->redirect( $this->mTitle
->getFullUrl() );
524 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
529 * Should we show a preview when the edit form is first shown?
533 protected function previewOnOpen() {
534 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
535 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
536 // Explicit override from request
538 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
539 // Explicit override from request
541 } elseif ( $this->section
== 'new' ) {
542 // Nothing *to* preview for new sections
544 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
545 // Standard preference behaviour
547 } elseif ( !$this->mTitle
->exists() &&
548 isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] ) &&
549 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
551 // Categories are special
559 * Checks whether the user entered a skin name in uppercase,
560 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
564 protected function isWrongCaseCssJsPage() {
565 if ( $this->mTitle
->isCssJsSubpage() ) {
566 $name = $this->mTitle
->getSkinFromCssJsSubpage();
567 $skins = array_merge(
568 array_keys( Skin
::getSkinNames() ),
571 return !in_array( $name, $skins )
572 && in_array( strtolower( $name ), $skins );
579 * Does this EditPage class support section editing?
580 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
584 protected function isSectionEditSupported() {
589 * This function collects the form data and uses it to populate various member variables.
590 * @param $request WebRequest
592 function importFormData( &$request ) {
593 global $wgContLang, $wgUser;
595 wfProfileIn( __METHOD__
);
597 # Section edit can come from either the form or a link
598 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
599 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
601 if ( $request->wasPosted() ) {
602 # These fields need to be checked for encoding.
603 # Also remove trailing whitespace, but don't remove _initial_
604 # whitespace from the text boxes. This may be significant formatting.
605 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
606 if ( !$request->getCheck( 'wpTextbox2' ) ) {
607 // Skip this if wpTextbox2 has input, it indicates that we came
608 // from a conflict page with raw page text, not a custom form
609 // modified by subclasses
610 wfProfileIn( get_class( $this ) . "::importContentFormData" );
611 $textbox1 = $this->importContentFormData( $request );
612 if ( isset( $textbox1 ) ) {
613 $this->textbox1
= $textbox1;
616 wfProfileOut( get_class( $this ) . "::importContentFormData" );
619 # Truncate for whole multibyte characters
620 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
622 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
623 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
625 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
627 # Treat sectiontitle the same way as summary.
628 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
629 # currently doing double duty as both edit summary and section title. Right now this
630 # is just to allow API edits to work around this limitation, but this should be
631 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
632 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
633 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
635 $this->edittime
= $request->getVal( 'wpEdittime' );
636 $this->starttime
= $request->getVal( 'wpStarttime' );
638 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
640 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
641 // wpTextbox1 field is missing, possibly due to being "too big"
642 // according to some filter rules such as Suhosin's setting for
643 // suhosin.request.max_value_length (d'oh)
644 $this->incompleteForm
= true;
646 // edittime should be one of our last fields; if it's missing,
647 // the submission probably broke somewhere in the middle.
648 $this->incompleteForm
= is_null( $this->edittime
);
650 if ( $this->incompleteForm
) {
651 # If the form is incomplete, force to preview.
652 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
653 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
654 $this->preview
= true;
656 /* Fallback for live preview */
657 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
658 $this->diff
= $request->getCheck( 'wpDiff' );
660 // Remember whether a save was requested, so we can indicate
661 // if we forced preview due to session failure.
662 $this->mTriedSave
= !$this->preview
;
664 if ( $this->tokenOk( $request ) ) {
665 # Some browsers will not report any submit button
666 # if the user hits enter in the comment box.
667 # The unmarked state will be assumed to be a save,
668 # if the form seems otherwise complete.
669 wfDebug( __METHOD__
. ": Passed token check.\n" );
670 } elseif ( $this->diff
) {
671 # Failed token check, but only requested "Show Changes".
672 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
674 # Page might be a hack attempt posted from
675 # an external site. Preview instead of saving.
676 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
677 $this->preview
= true;
680 $this->save
= !$this->preview
&& !$this->diff
;
681 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
682 $this->edittime
= null;
685 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
686 $this->starttime
= null;
689 $this->recreate
= $request->getCheck( 'wpRecreate' );
691 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
692 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
694 # Don't force edit summaries when a user is editing their own user or talk page
695 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
696 $this->mTitle
->getText() == $wgUser->getName() )
698 $this->allowBlankSummary
= true;
700 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary' );
703 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
705 # Not a posted form? Start with nothing.
706 wfDebug( __METHOD__
. ": Not a posted form.\n" );
707 $this->textbox1
= '';
709 $this->sectiontitle
= '';
710 $this->edittime
= '';
711 $this->starttime
= wfTimestampNow();
713 $this->preview
= false;
716 $this->minoredit
= false;
717 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
718 $this->recreate
= false;
720 // When creating a new section, we can preload a section title by passing it as the
721 // preloadtitle parameter in the URL (Bug 13100)
722 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
723 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
724 // Once wpSummary isn't being use for setting section titles, we should delete this.
725 $this->summary
= $request->getVal( 'preloadtitle' );
727 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
728 $this->summary
= $request->getText( 'summary' );
729 if ( $this->summary
!== '' ) {
730 $this->hasPresetSummary
= true;
734 if ( $request->getVal( 'minor' ) ) {
735 $this->minoredit
= true;
739 $this->oldid
= $request->getInt( 'oldid' );
741 $this->bot
= $request->getBool( 'bot', true );
742 $this->nosummary
= $request->getBool( 'nosummary' );
744 $content_handler = ContentHandler
::getForTitle( $this->mTitle
);
745 $this->contentModel
= $request->getText( 'model', $content_handler->getModelID() ); #may be overridden by revision
746 $this->contentFormat
= $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
748 #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
749 #TODO: check if the desired content model supports the given content format!
751 $this->live
= $request->getCheck( 'live' );
752 $this->editintro
= $request->getText( 'editintro',
753 // Custom edit intro for new sections
754 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
756 // Allow extensions to modify form data
757 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
759 wfProfileOut( __METHOD__
);
763 * Subpage overridable method for extracting the page content data from the
764 * posted form to be placed in $this->textbox1, if using customized input
765 * this method should be overrided and return the page text that will be used
766 * for saving, preview parsing and so on...
768 * @param $request WebRequest
770 protected function importContentFormData( &$request ) {
771 return; // Don't do anything, EditPage already extracted wpTextbox1
775 * Initialise form fields in the object
776 * Called on the first invocation, e.g. when a user clicks an edit link
777 * @return bool -- if the requested section is valid
779 function initialiseForm() {
781 $this->edittime
= $this->mArticle
->getTimestamp();
783 $content = $this->getContentObject( false ); #TODO: track content object?!
784 if ( $content === false ) {
787 $this->textbox1
= $this->toEditText( $content );
789 // activate checkboxes if user wants them to be always active
790 # Sort out the "watch" checkbox
791 if ( $wgUser->getOption( 'watchdefault' ) ) {
793 $this->watchthis
= true;
794 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
796 $this->watchthis
= true;
797 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
799 $this->watchthis
= true;
801 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
802 $this->minoredit
= true;
804 if ( $this->textbox1
=== false ) {
812 * Fetch initial editing page content.
814 * @param $def_text string|bool
815 * @return mixed string on success, $def_text for invalid sections
817 * @deprecated since 1.21, get WikiPage::getContent() instead.
819 function getContent( $def_text = false ) {
820 ContentHandler
::deprecated( __METHOD__
, '1.21' );
822 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
823 $def_content = $this->toEditContent( $def_text );
825 $def_content = false;
828 $content = $this->getContentObject( $def_content );
830 // Note: EditPage should only be used with text based content anyway.
831 return $this->toEditText( $content );
835 * @param Content|null $def_content The default value to return
837 * @return mixed Content on success, $def_content for invalid sections
841 protected function getContentObject( $def_content = null ) {
842 global $wgOut, $wgRequest;
844 wfProfileIn( __METHOD__
);
848 // For message page not locally set, use the i18n message.
849 // For other non-existent articles, use preload text if any.
850 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
851 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
852 # If this is a system message, get the default text.
853 $msg = $this->mTitle
->getDefaultMessageText();
855 $content = $this->toEditContent( $msg );
857 if ( $content === false ) {
858 # If requested, preload some text.
859 $preload = $wgRequest->getVal( 'preload',
860 // Custom preload text for new sections
861 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
863 $content = $this->getPreloadedContent( $preload );
865 // For existing pages, get text based on "undo" or section parameters.
867 if ( $this->section
!= '' ) {
868 // Get section edit text (returns $def_text for invalid sections)
869 $orig = $this->getOriginalContent();
870 $content = $orig ?
$orig->getSection( $this->section
) : null;
872 if ( !$content ) $content = $def_content;
874 $undoafter = $wgRequest->getInt( 'undoafter' );
875 $undo = $wgRequest->getInt( 'undo' );
877 if ( $undo > 0 && $undoafter > 0 ) {
878 if ( $undo < $undoafter ) {
879 # If they got undoafter and undo round the wrong way, switch them
880 list( $undo, $undoafter ) = array( $undoafter, $undo );
883 $undorev = Revision
::newFromId( $undo );
884 $oldrev = Revision
::newFromId( $undoafter );
886 # Sanity check, make sure it's the right page,
887 # the revisions exist and they were not deleted.
888 # Otherwise, $content will be left as-is.
889 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
890 $undorev->getPage() == $oldrev->getPage() &&
891 $undorev->getPage() == $this->mTitle
->getArticleID() &&
892 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
893 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
895 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
897 if ( $content === false ) {
898 # Warn the user that something went wrong
899 $undoMsg = 'failure';
901 # Inform the user of our success and set an automatic edit summary
902 $undoMsg = 'success';
904 # If we just undid one rev, use an autosummary
905 $firstrev = $oldrev->getNext();
906 if ( $firstrev && $firstrev->getId() == $undo ) {
907 $undoSummary = wfMessage( 'undo-summary', $undo, $undorev->getUserText() )->inContentLanguage()->text();
908 if ( $this->summary
=== '' ) {
909 $this->summary
= $undoSummary;
911 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
912 ->inContentLanguage()->text() . $this->summary
;
914 $this->undidRev
= $undo;
916 $this->formtype
= 'diff';
919 // Failed basic sanity checks.
920 // Older revisions may have been removed since the link
921 // was created, or we may simply have got bogus input.
925 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
926 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
927 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
930 if ( $content === false ) {
931 $content = $this->getOriginalContent();
936 wfProfileOut( __METHOD__
);
941 * Get the content of the wanted revision, without section extraction.
943 * The result of this function can be used to compare user's input with
944 * section replaced in its context (using WikiPage::replaceSection())
945 * to the original text of the edit.
947 * This difers from Article::getContent() that when a missing revision is
948 * encountered the result will be null and not the
949 * 'missing-revision' message.
952 * @return Content|null
954 private function getOriginalContent() {
955 if ( $this->section
== 'new' ) {
956 return $this->getCurrentContent();
958 $revision = $this->mArticle
->getRevisionFetched();
959 if ( $revision === null ) {
960 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
961 $handler = ContentHandler
::getForModelID( $this->contentModel
);
963 return $handler->makeEmptyContent();
965 $content = $revision->getContent();
970 * Get the current content of the page. This is basically similar to
971 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
972 * content object is returned instead of null.
977 protected function getCurrentContent() {
978 $rev = $this->mArticle
->getRevision();
979 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
981 if ( $content === false ||
$content === null ) {
982 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
983 $handler = ContentHandler
::getForModelID( $this->contentModel
);
985 return $handler->makeEmptyContent();
987 # nasty side-effect, but needed for consistency
988 $this->contentModel
= $rev->getContentModel();
989 $this->contentFormat
= $rev->getContentFormat();
997 * Use this method before edit() to preload some text into the edit box
999 * @param $text string
1000 * @deprecated since 1.21, use setPreloadedContent() instead.
1002 public function setPreloadedText( $text ) {
1003 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1005 $content = $this->toEditContent( $text );
1007 $this->setPreloadedContent( $content );
1011 * Use this method before edit() to preload some content into the edit box
1013 * @param $content Content
1017 public function setPreloadedContent( Content
$content ) {
1018 $this->mPreloadContent
= $content;
1022 * Get the contents to be preloaded into the box, either set by
1023 * an earlier setPreloadText() or by loading the given page.
1025 * @param $preload String: representing the title to preload from.
1029 * @deprecated since 1.21, use getPreloadedContent() instead
1031 protected function getPreloadedText( $preload ) {
1032 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1034 $content = $this->getPreloadedContent( $preload );
1035 $text = $this->toEditText( $content );
1041 * Get the contents to be preloaded into the box, either set by
1042 * an earlier setPreloadText() or by loading the given page.
1044 * @param $preload String: representing the title to preload from.
1050 protected function getPreloadedContent( $preload ) {
1053 if ( !empty( $this->mPreloadContent
) ) {
1054 return $this->mPreloadContent
;
1057 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1059 if ( $preload === '' ) {
1060 return $handler->makeEmptyContent();
1063 $title = Title
::newFromText( $preload );
1064 # Check for existence to avoid getting MediaWiki:Noarticletext
1065 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1066 return $handler->makeEmptyContent();
1069 $page = WikiPage
::factory( $title );
1070 if ( $page->isRedirect() ) {
1071 $title = $page->getRedirectTarget();
1073 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1074 return $handler->makeEmptyContent();
1076 $page = WikiPage
::factory( $title );
1079 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1080 $content = $page->getContent( Revision
::RAW
);
1083 return $handler->makeEmptyContent();
1086 return $content->preloadTransform( $title, $parserOptions );
1090 * Make sure the form isn't faking a user's credentials.
1092 * @param $request WebRequest
1096 function tokenOk( &$request ) {
1098 $token = $request->getVal( 'wpEditToken' );
1099 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1100 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1101 return $this->mTokenOk
;
1105 * Attempt submission
1106 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1107 * @return bool false if output is done, true if the rest of the form should be displayed
1109 function attemptSave() {
1110 global $wgUser, $wgOut;
1112 $resultDetails = false;
1113 # Allow bots to exempt some edits from bot flagging
1114 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1115 $status = $this->internalAttemptSave( $resultDetails, $bot );
1116 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1117 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1118 $this->didSave
= true;
1121 switch ( $status->value
) {
1122 case self
::AS_HOOK_ERROR_EXPECTED
:
1123 case self
::AS_CONTENT_TOO_BIG
:
1124 case self
::AS_ARTICLE_WAS_DELETED
:
1125 case self
::AS_CONFLICT_DETECTED
:
1126 case self
::AS_SUMMARY_NEEDED
:
1127 case self
::AS_TEXTBOX_EMPTY
:
1128 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1132 case self
::AS_HOOK_ERROR
:
1135 case self
::AS_PARSE_ERROR
:
1136 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>');
1139 case self
::AS_SUCCESS_NEW_ARTICLE
:
1140 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1141 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1142 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1145 case self
::AS_SUCCESS_UPDATE
:
1147 $sectionanchor = $resultDetails['sectionanchor'];
1149 // Give extensions a chance to modify URL query on update
1150 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1152 if ( $resultDetails['redirect'] ) {
1153 if ( $extraQuery == '' ) {
1154 $extraQuery = 'redirect=no';
1156 $extraQuery = 'redirect=no&' . $extraQuery;
1159 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1162 case self
::AS_BLANK_ARTICLE
:
1163 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1166 case self
::AS_SPAM_ERROR
:
1167 $this->spamPageWithContent( $resultDetails['spam'] );
1170 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1171 throw new UserBlockedError( $wgUser->getBlock() );
1173 case self
::AS_IMAGE_REDIRECT_ANON
:
1174 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1175 throw new PermissionsError( 'upload' );
1177 case self
::AS_READ_ONLY_PAGE_ANON
:
1178 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1179 throw new PermissionsError( 'edit' );
1181 case self
::AS_READ_ONLY_PAGE
:
1182 throw new ReadOnlyError
;
1184 case self
::AS_RATE_LIMITED
:
1185 throw new ThrottledError();
1187 case self
::AS_NO_CREATE_PERMISSION
:
1188 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1189 throw new PermissionsError( $permission );
1192 // We don't recognize $status->value. The only way that can happen
1193 // is if an extension hook aborted from inside ArticleSave.
1194 // Render the status object into $this->hookError
1195 // FIXME this sucks, we should just use the Status object throughout
1196 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1203 * Attempt submission (no UI)
1208 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1210 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1211 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1212 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1214 function internalAttemptSave( &$result, $bot = false ) {
1215 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1217 $status = Status
::newGood();
1219 wfProfileIn( __METHOD__
);
1220 wfProfileIn( __METHOD__
. '-checks' );
1222 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1223 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1224 $status->fatal( 'hookaborted' );
1225 $status->value
= self
::AS_HOOK_ERROR
;
1226 wfProfileOut( __METHOD__
. '-checks' );
1227 wfProfileOut( __METHOD__
);
1232 # Construct Content object
1233 $textbox_content = $this->toEditContent( $this->textbox1
);
1234 } catch (MWContentSerializationException
$ex) {
1235 $status->fatal( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
1236 $status->value
= self
::AS_PARSE_ERROR
;
1237 wfProfileOut( __METHOD__
);
1241 # Check image redirect
1242 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1243 $textbox_content->isRedirect() &&
1244 !$wgUser->isAllowed( 'upload' ) ) {
1245 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1246 $status->setResult( false, $code );
1248 wfProfileOut( __METHOD__
. '-checks' );
1249 wfProfileOut( __METHOD__
);
1255 $match = self
::matchSummarySpamRegex( $this->summary
);
1256 if ( $match === false ) {
1257 $match = self
::matchSpamRegex( $this->textbox1
);
1259 if ( $match !== false ) {
1260 $result['spam'] = $match;
1261 $ip = $wgRequest->getIP();
1262 $pdbk = $this->mTitle
->getPrefixedDBkey();
1263 $match = str_replace( "\n", '', $match );
1264 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1265 $status->fatal( 'spamprotectionmatch', $match );
1266 $status->value
= self
::AS_SPAM_ERROR
;
1267 wfProfileOut( __METHOD__
. '-checks' );
1268 wfProfileOut( __METHOD__
);
1271 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1272 # Error messages etc. could be handled within the hook...
1273 $status->fatal( 'hookaborted' );
1274 $status->value
= self
::AS_HOOK_ERROR
;
1275 wfProfileOut( __METHOD__
. '-checks' );
1276 wfProfileOut( __METHOD__
);
1278 } elseif ( $this->hookError
!= '' ) {
1279 # ...or the hook could be expecting us to produce an error
1280 $status->fatal( 'hookaborted' );
1281 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1282 wfProfileOut( __METHOD__
. '-checks' );
1283 wfProfileOut( __METHOD__
);
1287 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1288 // Auto-block user's IP if the account was "hard" blocked
1289 $wgUser->spreadAnyEditBlock();
1290 # Check block state against master, thus 'false'.
1291 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1292 wfProfileOut( __METHOD__
. '-checks' );
1293 wfProfileOut( __METHOD__
);
1297 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1298 if ( $this->kblength
> $wgMaxArticleSize ) {
1299 // Error will be displayed by showEditForm()
1300 $this->tooBig
= true;
1301 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1302 wfProfileOut( __METHOD__
. '-checks' );
1303 wfProfileOut( __METHOD__
);
1307 if ( !$wgUser->isAllowed( 'edit' ) ) {
1308 if ( $wgUser->isAnon() ) {
1309 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1310 wfProfileOut( __METHOD__
. '-checks' );
1311 wfProfileOut( __METHOD__
);
1314 $status->fatal( 'readonlytext' );
1315 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1316 wfProfileOut( __METHOD__
. '-checks' );
1317 wfProfileOut( __METHOD__
);
1322 if ( wfReadOnly() ) {
1323 $status->fatal( 'readonlytext' );
1324 $status->value
= self
::AS_READ_ONLY_PAGE
;
1325 wfProfileOut( __METHOD__
. '-checks' );
1326 wfProfileOut( __METHOD__
);
1329 if ( $wgUser->pingLimiter() ) {
1330 $status->fatal( 'actionthrottledtext' );
1331 $status->value
= self
::AS_RATE_LIMITED
;
1332 wfProfileOut( __METHOD__
. '-checks' );
1333 wfProfileOut( __METHOD__
);
1337 # If the article has been deleted while editing, don't save it without
1339 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1340 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1341 wfProfileOut( __METHOD__
. '-checks' );
1342 wfProfileOut( __METHOD__
);
1346 wfProfileOut( __METHOD__
. '-checks' );
1348 # Load the page data from the master. If anything changes in the meantime,
1349 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1350 $this->mArticle
->loadPageData( 'fromdbmaster' );
1351 $new = !$this->mArticle
->exists();
1354 // Late check for create permission, just in case *PARANOIA*
1355 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1356 $status->fatal( 'nocreatetext' );
1357 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1358 wfDebug( __METHOD__
. ": no create permission\n" );
1359 wfProfileOut( __METHOD__
);
1363 # Don't save a new article if it's blank.
1364 if ( $this->textbox1
== '' ) {
1365 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1366 wfProfileOut( __METHOD__
);
1370 // Run post-section-merge edit filter
1371 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1372 # Error messages etc. could be handled within the hook...
1373 $status->fatal( 'hookaborted' );
1374 $status->value
= self
::AS_HOOK_ERROR
;
1375 wfProfileOut( __METHOD__
);
1377 } elseif ( $this->hookError
!= '' ) {
1378 # ...or the hook could be expecting us to produce an error
1379 $status->fatal( 'hookaborted' );
1380 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1381 wfProfileOut( __METHOD__
);
1385 $content = $textbox_content;
1387 $result['sectionanchor'] = '';
1388 if ( $this->section
== 'new' ) {
1389 if ( $this->sectiontitle
!== '' ) {
1390 // Insert the section title above the content.
1391 $content = $content->addSectionHeader( $this->sectiontitle
);
1393 // Jump to the new section
1394 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1396 // If no edit summary was specified, create one automatically from the section
1397 // title and have it link to the new section. Otherwise, respect the summary as
1399 if ( $this->summary
=== '' ) {
1400 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1401 $this->summary
= wfMessage( 'newsectionsummary' )
1402 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1404 } elseif ( $this->summary
!== '' ) {
1405 // Insert the section title above the content.
1406 $content = $content->addSectionHeader( $this->summary
);
1408 // Jump to the new section
1409 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1411 // Create a link to the new section from the edit summary.
1412 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1413 $this->summary
= wfMessage( 'newsectionsummary' )
1414 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1418 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1422 # Article exists. Check for edit conflict.
1424 $this->mArticle
->clear(); # Force reload of dates, etc.
1425 $timestamp = $this->mArticle
->getTimestamp();
1427 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1429 if ( $timestamp != $this->edittime
) {
1430 $this->isConflict
= true;
1431 if ( $this->section
== 'new' ) {
1432 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1433 $this->mArticle
->getComment() == $this->summary
) {
1434 // Probably a duplicate submission of a new comment.
1435 // This can happen when squid resends a request after
1436 // a timeout but the first one actually went through.
1437 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1439 // New comment; suppress conflict.
1440 $this->isConflict
= false;
1441 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1443 } elseif ( $this->section
== '' && Revision
::userWasLastToEdit( DB_MASTER
, $this->mTitle
->getArticleID(),
1444 $wgUser->getId(), $this->edittime
) ) {
1445 # Suppress edit conflict with self, except for section edits where merging is required.
1446 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1447 $this->isConflict
= false;
1451 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1452 // backwards compatibility with old forms/bots).
1453 if ( $this->sectiontitle
!== '' ) {
1454 $sectionTitle = $this->sectiontitle
;
1456 $sectionTitle = $this->summary
;
1461 if ( $this->isConflict
) {
1462 wfDebug( __METHOD__
. ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1463 . " (article time '{$timestamp}')\n" );
1465 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1467 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1468 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1471 if ( is_null( $content ) ) {
1472 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1473 $this->isConflict
= true;
1474 $content = $textbox_content; // do not try to merge here!
1475 } elseif ( $this->isConflict
) {
1477 if ( $this->mergeChangesIntoContent( $content ) ) {
1478 // Successful merge! Maybe we should tell the user the good news?
1479 $this->isConflict
= false;
1480 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1482 $this->section
= '';
1483 $this->textbox1
= ContentHandler
::getContentText( $content );
1484 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1488 if ( $this->isConflict
) {
1489 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1490 wfProfileOut( __METHOD__
);
1494 // Run post-section-merge edit filter
1495 $hook_args = array( $this, $content, &$this->hookError
, $this->summary
);
1497 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged', $hook_args )
1498 ||
!wfRunHooks( 'EditFilterMergedContent', $hook_args ) ) {
1499 # Error messages etc. could be handled within the hook...
1500 $status->fatal( 'hookaborted' );
1501 $status->value
= self
::AS_HOOK_ERROR
;
1502 wfProfileOut( __METHOD__
);
1504 } elseif ( $this->hookError
!= '' ) {
1505 # ...or the hook could be expecting us to produce an error
1506 $status->fatal( 'hookaborted' );
1507 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1508 wfProfileOut( __METHOD__
);
1512 # Handle the user preference to force summaries here, but not for null edits
1513 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1514 && !$content->equals( $this->getOriginalContent() )
1515 && !$content->isRedirect() ) # check if it's not a redirect
1517 if ( md5( $this->summary
) == $this->autoSumm
) {
1518 $this->missingSummary
= true;
1519 $status->fatal( 'missingsummary' );
1520 $status->value
= self
::AS_SUMMARY_NEEDED
;
1521 wfProfileOut( __METHOD__
);
1526 # And a similar thing for new sections
1527 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1528 if ( trim( $this->summary
) == '' ) {
1529 $this->missingSummary
= true;
1530 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1531 $status->value
= self
::AS_SUMMARY_NEEDED
;
1532 wfProfileOut( __METHOD__
);
1538 wfProfileIn( __METHOD__
. '-sectionanchor' );
1539 $sectionanchor = '';
1540 if ( $this->section
== 'new' ) {
1541 if ( $this->textbox1
== '' ) {
1542 $this->missingComment
= true;
1543 $status->fatal( 'missingcommenttext' );
1544 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1545 wfProfileOut( __METHOD__
. '-sectionanchor' );
1546 wfProfileOut( __METHOD__
);
1549 if ( $this->sectiontitle
!== '' ) {
1550 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1551 // If no edit summary was specified, create one automatically from the section
1552 // title and have it link to the new section. Otherwise, respect the summary as
1554 if ( $this->summary
=== '' ) {
1555 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1556 $this->summary
= wfMessage( 'newsectionsummary' )
1557 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1559 } elseif ( $this->summary
!== '' ) {
1560 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1561 # This is a new section, so create a link to the new section
1562 # in the revision summary.
1563 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1564 $this->summary
= wfMessage( 'newsectionsummary' )
1565 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1567 } elseif ( $this->section
!= '' ) {
1568 # Try to get a section anchor from the section source, redirect to edited section if header found
1569 # XXX: might be better to integrate this into Article::replaceSection
1570 # for duplicate heading checking and maybe parsing
1571 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1572 # we can't deal with anchors, includes, html etc in the header for now,
1573 # headline would need to be parsed to improve this
1574 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1575 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1578 $result['sectionanchor'] = $sectionanchor;
1579 wfProfileOut( __METHOD__
. '-sectionanchor' );
1581 // Save errors may fall down to the edit form, but we've now
1582 // merged the section into full text. Clear the section field
1583 // so that later submission of conflict forms won't try to
1584 // replace that into a duplicated mess.
1585 $this->textbox1
= $this->toEditText( $content );
1586 $this->section
= '';
1588 $status->value
= self
::AS_SUCCESS_UPDATE
;
1591 // Check for length errors again now that the section is merged in
1592 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1593 if ( $this->kblength
> $wgMaxArticleSize ) {
1594 $this->tooBig
= true;
1595 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1596 wfProfileOut( __METHOD__
);
1600 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1601 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1602 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1603 ( $bot ? EDIT_FORCE_BOT
: 0 );
1605 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags,
1606 false, null, $this->contentFormat
);
1608 if ( $doEditStatus->isOK() ) {
1609 $result['redirect'] = $content->isRedirect();
1610 $this->updateWatchlist();
1611 wfProfileOut( __METHOD__
);
1614 // Failure from doEdit()
1615 // Show the edit conflict page for certain recognized errors from doEdit(),
1616 // but don't show it for errors from extension hooks
1617 $errors = $doEditStatus->getErrorsArray();
1618 if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
1619 'edit-already-exists' ) ) )
1621 $this->isConflict
= true;
1622 // Destroys data doEdit() put in $status->value but who cares
1623 $doEditStatus->value
= self
::AS_END
;
1625 wfProfileOut( __METHOD__
);
1626 return $doEditStatus;
1631 * Register the change of watch status
1633 protected function updateWatchlist() {
1636 if ( $wgUser->isLoggedIn() && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
) ) {
1637 $fname = __METHOD__
;
1638 $title = $this->mTitle
;
1639 $watch = $this->watchthis
;
1641 // Do this in its own transaction to reduce contention...
1642 $dbw = wfGetDB( DB_MASTER
);
1643 $dbw->onTransactionIdle( function() use ( $dbw, $title, $watch, $wgUser, $fname ) {
1644 $dbw->begin( $fname );
1646 WatchAction
::doWatch( $title, $wgUser );
1648 WatchAction
::doUnwatch( $title, $wgUser );
1650 $dbw->commit( $fname );
1659 * @param $editText string
1662 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1664 function mergeChangesInto( &$editText ){
1665 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1667 $editContent = $this->toEditContent( $editText );
1669 $ok = $this->mergeChangesIntoContent( $editContent );
1672 $editText = $this->toEditText( $editContent );
1682 * @param $editContent
1686 private function mergeChangesIntoContent( &$editContent ){
1687 wfProfileIn( __METHOD__
);
1689 $db = wfGetDB( DB_MASTER
);
1691 // This is the revision the editor started from
1692 $baseRevision = $this->getBaseRevision();
1693 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
1695 if ( is_null( $baseContent ) ) {
1696 wfProfileOut( __METHOD__
);
1700 // The current state, we want to merge updates into it
1701 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1702 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
1704 if ( is_null( $currentContent ) ) {
1705 wfProfileOut( __METHOD__
);
1709 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
1711 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1714 $editContent = $result;
1715 wfProfileOut( __METHOD__
);
1718 wfProfileOut( __METHOD__
);
1726 function getBaseRevision() {
1727 if ( !$this->mBaseRevision
) {
1728 $db = wfGetDB( DB_MASTER
);
1729 $baseRevision = Revision
::loadFromTimestamp(
1730 $db, $this->mTitle
, $this->edittime
);
1731 return $this->mBaseRevision
= $baseRevision;
1733 return $this->mBaseRevision
;
1738 * Check given input text against $wgSpamRegex, and return the text of the first match.
1740 * @param $text string
1742 * @return string|bool matching string or false
1744 public static function matchSpamRegex( $text ) {
1745 global $wgSpamRegex;
1746 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1747 $regexes = (array)$wgSpamRegex;
1748 return self
::matchSpamRegexInternal( $text, $regexes );
1752 * Check given input text against $wgSpamRegex, and return the text of the first match.
1754 * @param $text string
1756 * @return string|bool matching string or false
1758 public static function matchSummarySpamRegex( $text ) {
1759 global $wgSummarySpamRegex;
1760 $regexes = (array)$wgSummarySpamRegex;
1761 return self
::matchSpamRegexInternal( $text, $regexes );
1765 * @param $text string
1766 * @param $regexes array
1767 * @return bool|string
1769 protected static function matchSpamRegexInternal( $text, $regexes ) {
1770 foreach ( $regexes as $regex ) {
1772 if ( preg_match( $regex, $text, $matches ) ) {
1779 function setHeaders() {
1780 global $wgOut, $wgUser;
1782 $wgOut->addModules( 'mediawiki.action.edit' );
1784 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1785 $wgOut->addModules( 'mediawiki.action.edit.preview' );
1787 // Bug #19334: textarea jumps when editing articles in IE8
1788 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1790 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1792 # Enabled article-related sidebar, toplinks, etc.
1793 $wgOut->setArticleRelated( true );
1795 $contextTitle = $this->getContextTitle();
1796 if ( $this->isConflict
) {
1797 $msg = 'editconflict';
1798 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1799 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1801 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1802 'editing' : 'creating';
1804 # Use the title defined by DISPLAYTITLE magic word when present
1805 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1806 if ( $displayTitle === false ) {
1807 $displayTitle = $contextTitle->getPrefixedText();
1809 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1813 * Show all applicable editing introductions
1815 protected function showIntro() {
1816 global $wgOut, $wgUser;
1817 if ( $this->suppressIntro
) {
1821 $namespace = $this->mTitle
->getNamespace();
1823 if ( $namespace == NS_MEDIAWIKI
) {
1824 # Show a warning if editing an interface message
1825 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1826 } else if( $namespace == NS_FILE
) {
1827 # Show a hint to shared repo
1828 $file = wfFindFile( $this->mTitle
);
1829 if( $file && !$file->isLocal() ) {
1830 $descUrl = $file->getDescriptionUrl();
1831 # there must be a description url to show a hint to shared repo
1833 if( !$this->mTitle
->exists() ) {
1834 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1835 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1838 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1839 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1846 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1847 # Show log extract when the user is currently blocked
1848 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1849 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1850 $username = $parts[0];
1851 $user = User
::newFromName( $username, false /* allow IP users*/ );
1852 $ip = User
::isIP( $username );
1853 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1854 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1855 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1856 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1857 LogEventsList
::showLogExtract(
1860 $user->getUserPage(),
1864 'showIfEmpty' => false,
1866 'blocked-notice-logextract',
1867 $user->getName() # Support GENDER in notice
1873 # Try to add a custom edit intro, or use the standard one if this is not possible.
1874 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1875 if ( $wgUser->isLoggedIn() ) {
1876 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1878 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1881 # Give a notice if the user is editing a deleted/moved page...
1882 if ( !$this->mTitle
->exists() ) {
1883 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1887 'conds' => array( "log_action != 'revision'" ),
1888 'showIfEmpty' => false,
1889 'msgKey' => array( 'recreate-moveddeleted-warn' )
1896 * Attempt to show a custom editing introduction, if supplied
1900 protected function showCustomIntro() {
1901 if ( $this->editintro
) {
1902 $title = Title
::newFromText( $this->editintro
);
1903 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1905 // Added using template syntax, to take <noinclude>'s into account.
1906 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1914 * Gets an editable textual representation of $content.
1915 * The textual representation can be turned by into a Content object by the
1916 * toEditContent() method.
1918 * If $content is null or false or a string, $content is returned unchanged.
1920 * If the given Content object is not of a type that can be edited using the text base EditPage,
1921 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
1924 * @param Content|null|bool|string $content
1925 * @return String the editable text form of the content.
1927 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
1929 protected function toEditText( $content ) {
1930 if ( $content === null ||
$content === false ) {
1934 if ( is_string( $content ) ) {
1938 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
1939 throw new MWException( "This content model can not be edited as text: "
1940 . ContentHandler
::getLocalizedName( $content->getModel() ) );
1943 return $content->serialize( $this->contentFormat
);
1947 * Turns the given text into a Content object by unserializing it.
1949 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
1950 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
1953 * @param String|null|bool $text Text to unserialize
1954 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
1957 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
1958 * and $this->allowNonTextContent is not true.
1960 protected function toEditContent( $text ) {
1961 if ( $text === false ||
$text === null ) {
1965 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
1966 $this->contentModel
, $this->contentFormat
);
1968 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
1969 throw new MWException( "This content model can not be edited as text: "
1970 . ContentHandler
::getLocalizedName( $content->getModel() ) );
1977 * Send the edit form and related headers to $wgOut
1978 * @param $formCallback Callback|null that takes an OutputPage parameter; will be called
1979 * during form output near the top, for captchas and the like.
1981 function showEditForm( $formCallback = null ) {
1982 global $wgOut, $wgUser;
1984 wfProfileIn( __METHOD__
);
1986 # need to parse the preview early so that we know which templates are used,
1987 # otherwise users with "show preview after edit box" will get a blank list
1988 # we parse this near the beginning so that setHeaders can do the title
1989 # setting work instead of leaving it in getPreviewText
1990 $previewOutput = '';
1991 if ( $this->formtype
== 'preview' ) {
1992 $previewOutput = $this->getPreviewText();
1995 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
1997 $this->setHeaders();
1999 if ( $this->showHeader() === false ) {
2000 wfProfileOut( __METHOD__
);
2004 $wgOut->addHTML( $this->editFormPageTop
);
2006 if ( $wgUser->getOption( 'previewontop' ) ) {
2007 $this->displayPreviewArea( $previewOutput, true );
2010 $wgOut->addHTML( $this->editFormTextTop
);
2012 $showToolbar = true;
2013 if ( $this->wasDeletedSinceLastEdit() ) {
2014 if ( $this->formtype
== 'save' ) {
2015 // Hide the toolbar and edit area, user can click preview to get it back
2016 // Add an confirmation checkbox and explanation.
2017 $showToolbar = false;
2019 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2020 'deletedwhileediting' );
2024 //@todo: add EditForm plugin interface and use it here!
2025 // search for textarea1 and textares2, and allow EditForm to override all uses.
2026 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => self
::EDITFORM_ID
, 'name' => self
::EDITFORM_ID
,
2027 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
2028 'enctype' => 'multipart/form-data' ) ) );
2030 if ( is_callable( $formCallback ) ) {
2031 call_user_func_array( $formCallback, array( &$wgOut ) );
2034 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2036 // Put these up at the top to ensure they aren't lost on early form submission
2037 $this->showFormBeforeText();
2039 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2040 $username = $this->lastDelete
->user_name
;
2041 $comment = $this->lastDelete
->log_comment
;
2043 // It is better to not parse the comment at all than to have templates expanded in the middle
2044 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2045 $key = $comment === ''
2046 ?
'confirmrecreate-noreason'
2047 : 'confirmrecreate';
2049 '<div class="mw-confirm-recreate">' .
2050 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2051 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2052 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2058 # When the summary is hidden, also hide them on preview/show changes
2059 if( $this->nosummary
) {
2060 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2063 # If a blank edit summary was previously provided, and the appropriate
2064 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2065 # user being bounced back more than once in the event that a summary
2068 # For a bit more sophisticated detection of blank summaries, hash the
2069 # automatic one and pass that in the hidden field wpAutoSummary.
2070 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2071 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2074 if ( $this->undidRev
) {
2075 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2078 if ( $this->hasPresetSummary
) {
2079 // If a summary has been preset using &summary= we dont want to prompt for
2080 // a different summary. Only prompt for a summary if the summary is blanked.
2082 $this->autoSumm
= md5( '' );
2085 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2086 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2088 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2090 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2091 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2093 if ( $this->section
== 'new' ) {
2094 $this->showSummaryInput( true, $this->summary
);
2095 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2098 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2100 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2101 $wgOut->addHTML( EditPage
::getEditToolbar() );
2104 if ( $this->isConflict
) {
2105 // In an edit conflict bypass the overrideable content form method
2106 // and fallback to the raw wpTextbox1 since editconflicts can't be
2107 // resolved between page source edits and custom ui edits using the
2109 $this->textbox2
= $this->textbox1
;
2111 $content = $this->getCurrentContent();
2112 $this->textbox1
= $this->toEditText( $content );
2114 $this->showTextbox1();
2116 $this->showContentForm();
2119 $wgOut->addHTML( $this->editFormTextAfterContent
);
2121 $this->showStandardInputs();
2123 $this->showFormAfterText();
2125 $this->showTosSummary();
2127 $this->showEditTools();
2129 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2131 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2132 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2134 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2135 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2137 if ( $this->isConflict
) {
2139 $this->showConflict();
2140 } catch ( MWContentSerializationException
$ex ) {
2141 // this can't really happen, but be nice if it does.
2142 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2143 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2147 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2149 if ( !$wgUser->getOption( 'previewontop' ) ) {
2150 $this->displayPreviewArea( $previewOutput, false );
2153 wfProfileOut( __METHOD__
);
2157 * Extract the section title from current section text, if any.
2159 * @param string $text
2160 * @return Mixed|string or false
2162 public static function extractSectionTitle( $text ) {
2163 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2164 if ( !empty( $matches[2] ) ) {
2166 return $wgParser->stripSectionName( trim( $matches[2] ) );
2172 protected function showHeader() {
2173 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2175 if ( $this->mTitle
->isTalkPage() ) {
2176 $wgOut->addWikiMsg( 'talkpagetext' );
2179 # Optional notices on a per-namespace and per-page basis
2180 $editnotice_ns = 'editnotice-' . $this->mTitle
->getNamespace();
2181 $editnotice_ns_message = wfMessage( $editnotice_ns );
2182 if ( $editnotice_ns_message->exists() ) {
2183 $wgOut->addWikiText( $editnotice_ns_message->plain() );
2185 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
2186 $parts = explode( '/', $this->mTitle
->getDBkey() );
2187 $editnotice_base = $editnotice_ns;
2188 while ( count( $parts ) > 0 ) {
2189 $editnotice_base .= '-' . array_shift( $parts );
2190 $editnotice_base_msg = wfMessage( $editnotice_base );
2191 if ( $editnotice_base_msg->exists() ) {
2192 $wgOut->addWikiText( $editnotice_base_msg->plain() );
2196 # Even if there are no subpages in namespace, we still don't want / in MW ns.
2197 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
2198 $editnoticeMsg = wfMessage( $editnoticeText );
2199 if ( $editnoticeMsg->exists() ) {
2200 $wgOut->addWikiText( $editnoticeMsg->plain() );
2204 if ( $this->isConflict
) {
2205 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2206 $this->edittime
= $this->mArticle
->getTimestamp();
2208 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2209 // We use $this->section to much before this and getVal('wgSection') directly in other places
2210 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2211 // Someone is welcome to try refactoring though
2212 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2216 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2217 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2218 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2219 if ( $sectionTitle !== false ) {
2220 $this->summary
= "/* $sectionTitle */ ";
2225 if ( $this->missingComment
) {
2226 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2229 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2230 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2233 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2234 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2237 if ( $this->hookError
!== '' ) {
2238 $wgOut->addWikiText( $this->hookError
);
2241 if ( !$this->checkUnicodeCompliantBrowser() ) {
2242 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2245 if ( $this->section
!= 'new' ) {
2246 $revision = $this->mArticle
->getRevisionFetched();
2248 // Let sysop know that this will make private content public if saved
2250 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2251 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2252 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2253 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2256 if ( !$revision->isCurrent() ) {
2257 $this->mArticle
->setOldSubtitle( $revision->getId() );
2258 $wgOut->addWikiMsg( 'editingold' );
2260 } elseif ( $this->mTitle
->exists() ) {
2261 // Something went wrong
2263 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2264 array( 'missing-revision', $this->oldid
) );
2269 if ( wfReadOnly() ) {
2270 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2271 } elseif ( $wgUser->isAnon() ) {
2272 if ( $this->formtype
!= 'preview' ) {
2273 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2275 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2278 if ( $this->isCssJsSubpage
) {
2279 # Check the skin exists
2280 if ( $this->isWrongCaseCssJsPage
) {
2281 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2283 if ( $this->formtype
!== 'preview' ) {
2284 if ( $this->isCssSubpage
) {
2285 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2288 if ( $this->isJsSubpage
) {
2289 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2295 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2296 # Is the title semi-protected?
2297 if ( $this->mTitle
->isSemiProtected() ) {
2298 $noticeMsg = 'semiprotectedpagewarning';
2300 # Then it must be protected based on static groups (regular)
2301 $noticeMsg = 'protectedpagewarning';
2303 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2304 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2306 if ( $this->mTitle
->isCascadeProtected() ) {
2307 # Is this page under cascading protection from some source pages?
2308 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2309 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2310 $cascadeSourcesCount = count( $cascadeSources );
2311 if ( $cascadeSourcesCount > 0 ) {
2312 # Explain, and list the titles responsible
2313 foreach ( $cascadeSources as $page ) {
2314 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2317 $notice .= '</div>';
2318 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2320 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2321 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2323 'showIfEmpty' => false,
2324 'msgKey' => array( 'titleprotectedwarning' ),
2325 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2328 if ( $this->kblength
=== false ) {
2329 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2332 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2333 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2334 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2336 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2337 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2338 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2342 # Add header copyright warning
2343 $this->showHeaderCopyrightWarning();
2348 * Standard summary input and label (wgSummary), abstracted so EditPage
2349 * subclasses may reorganize the form.
2350 * Note that you do not need to worry about the label's for=, it will be
2351 * inferred by the id given to the input. You can remove them both by
2352 * passing array( 'id' => false ) to $userInputAttrs.
2354 * @param $summary string The value of the summary input
2355 * @param $labelText string The html to place inside the label
2356 * @param $inputAttrs array of attrs to use on the input
2357 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2359 * @return array An array in the format array( $label, $input )
2361 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2362 // Note: the maxlength is overriden in JS to 255 and to make it use UTF-8 bytes, not characters.
2363 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2364 'id' => 'wpSummary',
2365 'maxlength' => '200',
2368 'spellcheck' => 'true',
2369 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2371 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2372 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2373 'id' => "wpSummaryLabel"
2378 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2379 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2382 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2384 return array( $label, $input );
2388 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2389 * up top, or false if this is the comment summary
2390 * down below the textarea
2391 * @param $summary String: The text of the summary to display
2394 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2395 global $wgOut, $wgContLang;
2396 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2397 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2398 if ( $isSubjectPreview ) {
2399 if ( $this->nosummary
) {
2403 if ( !$this->mShowSummaryField
) {
2407 $summary = $wgContLang->recodeForEdit( $summary );
2408 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2409 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2410 $wgOut->addHTML( "{$label} {$input}" );
2414 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2415 * up top, or false if this is the comment summary
2416 * down below the textarea
2417 * @param $summary String: the text of the summary to display
2420 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2421 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2427 if ( $isSubjectPreview ) {
2428 $summary = wfMessage( 'newsectionsummary', $wgParser->stripSectionName( $summary ) )
2429 ->inContentLanguage()->text();
2432 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2434 $summary = wfMessage( $message )->parse() . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2435 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2438 protected function showFormBeforeText() {
2440 $section = htmlspecialchars( $this->section
);
2441 $wgOut->addHTML( <<<HTML
2442 <input type='hidden' value="{$section}" name="wpSection" />
2443 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2444 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2445 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2449 if ( !$this->checkUnicodeCompliantBrowser() ) {
2450 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2454 protected function showFormAfterText() {
2455 global $wgOut, $wgUser;
2457 * To make it harder for someone to slip a user a page
2458 * which submits an edit form to the wiki without their
2459 * knowledge, a random token is associated with the login
2460 * session. If it's not passed back with the submission,
2461 * we won't save the page, or render user JavaScript and
2464 * For anon editors, who may not have a session, we just
2465 * include the constant suffix to prevent editing from
2466 * broken text-mangling proxies.
2468 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2472 * Subpage overridable method for printing the form for page content editing
2473 * By default this simply outputs wpTextbox1
2474 * Subclasses can override this to provide a custom UI for editing;
2475 * be it a form, or simply wpTextbox1 with a modified content that will be
2476 * reverse modified when extracted from the post data.
2477 * Note that this is basically the inverse for importContentFormData
2479 protected function showContentForm() {
2480 $this->showTextbox1();
2484 * Method to output wpTextbox1
2485 * The $textoverride method can be used by subclasses overriding showContentForm
2486 * to pass back to this method.
2488 * @param $customAttribs array of html attributes to use in the textarea
2489 * @param $textoverride String: optional text to override $this->textarea1 with
2491 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2492 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2493 $attribs = array( 'style' => 'display:none;' );
2495 $classes = array(); // Textarea CSS
2496 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2497 # Is the title semi-protected?
2498 if ( $this->mTitle
->isSemiProtected() ) {
2499 $classes[] = 'mw-textarea-sprotected';
2501 # Then it must be protected based on static groups (regular)
2502 $classes[] = 'mw-textarea-protected';
2504 # Is the title cascade-protected?
2505 if ( $this->mTitle
->isCascadeProtected() ) {
2506 $classes[] = 'mw-textarea-cprotected';
2510 $attribs = array( 'tabindex' => 1 );
2512 if ( is_array( $customAttribs ) ) {
2513 $attribs +
= $customAttribs;
2516 if ( count( $classes ) ) {
2517 if ( isset( $attribs['class'] ) ) {
2518 $classes[] = $attribs['class'];
2520 $attribs['class'] = implode( ' ', $classes );
2524 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2527 protected function showTextbox2() {
2528 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2531 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2532 global $wgOut, $wgUser;
2534 $wikitext = $this->safeUnicodeOutput( $text );
2535 if ( strval( $wikitext ) !== '' ) {
2536 // Ensure there's a newline at the end, otherwise adding lines
2538 // But don't add a newline if the ext is empty, or Firefox in XHTML
2539 // mode will show an extra newline. A bit annoying.
2543 $attribs = $customAttribs +
array(
2546 'cols' => $wgUser->getIntOption( 'cols' ),
2547 'rows' => $wgUser->getIntOption( 'rows' ),
2548 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2551 $pageLang = $this->mTitle
->getPageLanguage();
2552 $attribs['lang'] = $pageLang->getCode();
2553 $attribs['dir'] = $pageLang->getDir();
2555 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2558 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2562 $classes[] = 'ontop';
2565 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2567 if ( $this->formtype
!= 'preview' ) {
2568 $attribs['style'] = 'display: none;';
2571 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2573 if ( $this->formtype
== 'preview' ) {
2574 $this->showPreview( $previewOutput );
2577 $wgOut->addHTML( '</div>' );
2579 if ( $this->formtype
== 'diff' ) {
2582 } catch ( MWContentSerializationException
$ex ) {
2583 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2584 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2590 * Append preview output to $wgOut.
2591 * Includes category rendering if this is a category page.
2593 * @param $text String: the HTML to be output for the preview.
2595 protected function showPreview( $text ) {
2597 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2598 $this->mArticle
->openShowCategory();
2600 # This hook seems slightly odd here, but makes things more
2601 # consistent for extensions.
2602 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2603 $wgOut->addHTML( $text );
2604 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2605 $this->mArticle
->closeShowCategory();
2610 * Get a diff between the current contents of the edit box and the
2611 * version of the page we're editing from.
2613 * If this is a section edit, we'll replace the section as for final
2614 * save and then make a comparison.
2616 function showDiff() {
2617 global $wgUser, $wgContLang, $wgOut;
2619 $oldtitlemsg = 'currentrev';
2620 # if message does not exist, show diff against the preloaded default
2621 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2622 $oldtext = $this->mTitle
->getDefaultMessageText();
2623 if( $oldtext !== false ) {
2624 $oldtitlemsg = 'defaultmessagetext';
2625 $oldContent = $this->toEditContent( $oldtext );
2630 $oldContent = $this->getCurrentContent();
2633 $textboxContent = $this->toEditContent( $this->textbox1
);
2635 $newContent = $this->mArticle
->replaceSectionContent(
2636 $this->section
, $textboxContent,
2637 $this->summary
, $this->edittime
);
2639 if ( $newContent ) {
2640 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2641 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2643 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2644 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2647 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2648 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2649 $newtitle = wfMessage( 'yourtext' )->parse();
2651 if ( !$oldContent ) {
2652 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
2655 if ( !$newContent ) {
2656 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
2659 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
2660 $de->setContent( $oldContent, $newContent );
2662 $difftext = $de->getDiff( $oldtitle, $newtitle );
2663 $de->showDiffStyle();
2668 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2672 * Show the header copyright warning.
2674 protected function showHeaderCopyrightWarning() {
2675 $msg = 'editpage-head-copy-warn';
2676 if ( !wfMessage( $msg )->isDisabled() ) {
2678 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2679 'editpage-head-copy-warn' );
2684 * Give a chance for site and per-namespace customizations of
2685 * terms of service summary link that might exist separately
2686 * from the copyright notice.
2688 * This will display between the save button and the edit tools,
2689 * so should remain short!
2691 protected function showTosSummary() {
2692 $msg = 'editpage-tos-summary';
2693 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2694 if ( !wfMessage( $msg )->isDisabled() ) {
2696 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2697 $wgOut->addWikiMsg( $msg );
2698 $wgOut->addHTML( '</div>' );
2702 protected function showEditTools() {
2704 $wgOut->addHTML( '<div class="mw-editTools">' .
2705 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2710 * Get the copyright warning
2712 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2714 protected function getCopywarn() {
2715 return self
::getCopyrightWarning( $this->mTitle
);
2718 public static function getCopyrightWarning( $title ) {
2719 global $wgRightsText;
2720 if ( $wgRightsText ) {
2721 $copywarnMsg = array( 'copyrightwarning',
2722 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2725 $copywarnMsg = array( 'copyrightwarning2',
2726 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2728 // Allow for site and per-namespace customization of contribution/copyright notice.
2729 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2731 return "<div id=\"editpage-copywarn\">\n" .
2732 call_user_func_array( 'wfMessage', $copywarnMsg )->plain() . "\n</div>";
2735 protected function showStandardInputs( &$tabindex = 2 ) {
2737 $wgOut->addHTML( "<div class='editOptions'>\n" );
2739 if ( $this->section
!= 'new' ) {
2740 $this->showSummaryInput( false, $this->summary
);
2741 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2744 $checkboxes = $this->getCheckboxes( $tabindex,
2745 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2746 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2748 // Show copyright warning.
2749 $wgOut->addWikiText( $this->getCopywarn() );
2750 $wgOut->addHTML( $this->editFormTextAfterWarn
);
2752 $wgOut->addHTML( "<div class='editButtons'>\n" );
2753 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2755 $cancel = $this->getCancelLink();
2756 if ( $cancel !== '' ) {
2757 $cancel .= wfMessage( 'pipe-separator' )->text();
2759 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
2760 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2761 wfMessage( 'edithelp' )->escaped() . '</a> ' .
2762 wfMessage( 'newwindow' )->parse();
2763 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
2764 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
2765 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2769 * Show an edit conflict. textbox1 is already shown in showEditForm().
2770 * If you want to use another entry point to this function, be careful.
2772 protected function showConflict() {
2775 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2776 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2778 $content1 = $this->toEditContent( $this->textbox1
);
2779 $content2 = $this->toEditContent( $this->textbox2
);
2781 $handler = ContentHandler
::getForModelID( $this->contentModel
);
2782 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
2783 $de->setContent( $content2, $content1 );
2785 wfMessage( 'yourtext' )->parse(),
2786 wfMessage( 'storedversion' )->text()
2789 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2790 $this->showTextbox2();
2797 public function getCancelLink() {
2798 $cancelParams = array();
2799 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2800 $cancelParams['oldid'] = $this->oldid
;
2803 return Linker
::linkKnown(
2804 $this->getContextTitle(),
2805 wfMessage( 'cancel' )->parse(),
2806 array( 'id' => 'mw-editform-cancel' ),
2812 * Returns the URL to use in the form's action attribute.
2813 * This is used by EditPage subclasses when simply customizing the action
2814 * variable in the constructor is not enough. This can be used when the
2815 * EditPage lives inside of a Special page rather than a custom page action.
2817 * @param $title Title object for which is being edited (where we go to for &action= links)
2820 protected function getActionURL( Title
$title ) {
2821 return $title->getLocalURL( array( 'action' => $this->action
) );
2825 * Check if a page was deleted while the user was editing it, before submit.
2826 * Note that we rely on the logging table, which hasn't been always there,
2827 * but that doesn't matter, because this only applies to brand new
2830 protected function wasDeletedSinceLastEdit() {
2831 if ( $this->deletedSinceEdit
!== null ) {
2832 return $this->deletedSinceEdit
;
2835 $this->deletedSinceEdit
= false;
2837 if ( $this->mTitle
->isDeletedQuick() ) {
2838 $this->lastDelete
= $this->getLastDelete();
2839 if ( $this->lastDelete
) {
2840 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2841 if ( $deleteTime > $this->starttime
) {
2842 $this->deletedSinceEdit
= true;
2847 return $this->deletedSinceEdit
;
2850 protected function getLastDelete() {
2851 $dbr = wfGetDB( DB_SLAVE
);
2852 $data = $dbr->selectRow(
2853 array( 'logging', 'user' ),
2864 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2865 'log_title' => $this->mTitle
->getDBkey(),
2866 'log_type' => 'delete',
2867 'log_action' => 'delete',
2868 'user_id=log_user' ),
2870 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2872 // Quick paranoid permission checks...
2873 if ( is_object( $data ) ) {
2874 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
2875 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
2878 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
2879 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
2886 * Get the rendered text for previewing.
2887 * @throws MWException
2890 function getPreviewText() {
2891 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
2893 wfProfileIn( __METHOD__
);
2895 if ( $wgRawHtml && !$this->mTokenOk
) {
2896 // Could be an offsite preview attempt. This is very unsafe if
2897 // HTML is enabled, as it could be an attack.
2899 if ( $this->textbox1
!== '' ) {
2900 // Do not put big scary notice, if previewing the empty
2901 // string, which happens when you initially edit
2902 // a category page, due to automatic preview-on-open.
2903 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2904 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
2906 wfProfileOut( __METHOD__
);
2913 $content = $this->toEditContent( $this->textbox1
);
2915 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2916 if ( $this->mTokenOkExceptSuffix
) {
2917 $note = wfMessage( 'token_suffix_mismatch' )->plain() ;
2920 $note = wfMessage( 'session_fail_preview' )->plain() ;
2922 } elseif ( $this->incompleteForm
) {
2923 $note = wfMessage( 'edit_form_incomplete' )->plain() ;
2925 $note = wfMessage( 'previewnote' )->plain() .
2926 ' [[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' . wfMessage( 'continue-editing' )->text() . ']]';
2929 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
2930 $parserOptions->setEditSection( false );
2931 $parserOptions->setIsPreview( true );
2932 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2934 # don't parse non-wikitext pages, show message about preview
2935 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
2936 if( $this->mTitle
->isCssJsSubpage() ) {
2938 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2944 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
2946 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
2952 # Used messages to make sure grep find them:
2953 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2954 if( $level && $format ) {
2955 $note = "<div id='mw-{$level}{$format}preview'>" . wfMessage( "{$level}{$format}preview" )->text() . "</div>";
2959 $rt = $content->getRedirectChain();
2961 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2964 # If we're adding a comment, we need to show the
2965 # summary as the headline
2966 if ( $this->section
=== "new" && $this->summary
!== "" ) {
2967 $content = $content->addSectionHeader( $this->summary
);
2970 $hook_args = array( $this, &$content );
2971 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
2972 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
2974 $parserOptions->enableLimitReport();
2976 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
2977 # But it's now deprecated, so never mind
2979 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
2980 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
2982 $previewHTML = $parserOutput->getText();
2983 $this->mParserOutput
= $parserOutput;
2984 $wgOut->addParserOutputNoText( $parserOutput );
2986 if ( count( $parserOutput->getWarnings() ) ) {
2987 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2990 } catch ( MWContentSerializationException
$ex ) {
2991 $m = wfMessage('content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2992 $note .= "\n\n" . $m->parse();
2996 if ( $this->isConflict
) {
2997 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
2999 $conflict = '<hr />';
3002 $previewhead = "<div class='previewnote'>\n" .
3003 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3004 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3006 $pageLang = $this->mTitle
->getPageLanguage();
3007 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
3008 'class' => 'mw-content-' . $pageLang->getDir() );
3009 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3011 wfProfileOut( __METHOD__
);
3012 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3018 function getTemplates() {
3019 if ( $this->preview ||
$this->section
!= '' ) {
3020 $templates = array();
3021 if ( !isset( $this->mParserOutput
) ) {
3024 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3025 foreach ( array_keys( $template ) as $dbk ) {
3026 $templates[] = Title
::makeTitle( $ns, $dbk );
3031 return $this->mTitle
->getTemplateLinksFrom();
3036 * Shows a bulletin board style toolbar for common editing functions.
3037 * It can be disabled in the user preferences.
3038 * The necessary JavaScript code can be found in skins/common/edit.js.
3042 static function getEditToolbar() {
3043 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3044 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
3046 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3049 * $toolarray is an array of arrays each of which includes the
3050 * filename of the button image (without path), the opening
3051 * tag, the closing tag, optionally a sample text that is
3052 * inserted between the two when no selection is highlighted
3053 * and. The tip text is shown when the user moves the mouse
3056 * Also here: accesskeys (key), which are not used yet until
3057 * someone can figure out a way to make them work in
3058 * IE. However, we should make sure these keys are not defined
3063 'image' => $wgLang->getImageFile( 'button-bold' ),
3064 'id' => 'mw-editbutton-bold',
3066 'close' => '\'\'\'',
3067 'sample' => wfMessage( 'bold_sample' )->text(),
3068 'tip' => wfMessage( 'bold_tip' )->text(),
3072 'image' => $wgLang->getImageFile( 'button-italic' ),
3073 'id' => 'mw-editbutton-italic',
3076 'sample' => wfMessage( 'italic_sample' )->text(),
3077 'tip' => wfMessage( 'italic_tip' )->text(),
3081 'image' => $wgLang->getImageFile( 'button-link' ),
3082 'id' => 'mw-editbutton-link',
3085 'sample' => wfMessage( 'link_sample' )->text(),
3086 'tip' => wfMessage( 'link_tip' )->text(),
3090 'image' => $wgLang->getImageFile( 'button-extlink' ),
3091 'id' => 'mw-editbutton-extlink',
3094 'sample' => wfMessage( 'extlink_sample' )->text(),
3095 'tip' => wfMessage( 'extlink_tip' )->text(),
3099 'image' => $wgLang->getImageFile( 'button-headline' ),
3100 'id' => 'mw-editbutton-headline',
3103 'sample' => wfMessage( 'headline_sample' )->text(),
3104 'tip' => wfMessage( 'headline_tip' )->text(),
3107 $imagesAvailable ?
array(
3108 'image' => $wgLang->getImageFile( 'button-image' ),
3109 'id' => 'mw-editbutton-image',
3110 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3112 'sample' => wfMessage( 'image_sample' )->text(),
3113 'tip' => wfMessage( 'image_tip' )->text(),
3116 $imagesAvailable ?
array(
3117 'image' => $wgLang->getImageFile( 'button-media' ),
3118 'id' => 'mw-editbutton-media',
3119 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3121 'sample' => wfMessage( 'media_sample' )->text(),
3122 'tip' => wfMessage( 'media_tip' )->text(),
3126 'image' => $wgLang->getImageFile( 'button-math' ),
3127 'id' => 'mw-editbutton-math',
3129 'close' => "</math>",
3130 'sample' => wfMessage( 'math_sample' )->text(),
3131 'tip' => wfMessage( 'math_tip' )->text(),
3135 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3136 'id' => 'mw-editbutton-nowiki',
3137 'open' => "<nowiki>",
3138 'close' => "</nowiki>",
3139 'sample' => wfMessage( 'nowiki_sample' )->text(),
3140 'tip' => wfMessage( 'nowiki_tip' )->text(),
3144 'image' => $wgLang->getImageFile( 'button-sig' ),
3145 'id' => 'mw-editbutton-signature',
3149 'tip' => wfMessage( 'sig_tip' )->text(),
3153 'image' => $wgLang->getImageFile( 'button-hr' ),
3154 'id' => 'mw-editbutton-hr',
3155 'open' => "\n----\n",
3158 'tip' => wfMessage( 'hr_tip' )->text(),
3163 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3164 foreach ( $toolarray as $tool ) {
3170 $image = $wgStylePath . '/common/images/' . $tool['image'],
3171 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3172 // Older browsers show a "speedtip" type message only for ALT.
3173 // Ideally these should be different, realistically they
3174 // probably don't need to be.
3175 $tip = $tool['tip'],
3176 $open = $tool['open'],
3177 $close = $tool['close'],
3178 $sample = $tool['sample'],
3179 $cssId = $tool['id'],
3182 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3185 // This used to be called on DOMReady from mediawiki.action.edit, which
3186 // ended up causing race conditions with the setup code above.
3188 "// Create button bar\n" .
3189 "$(function() { mw.toolbar.init(); } );\n";
3192 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3194 $toolbar = '<div id="toolbar"></div>';
3196 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3202 * Returns an array of html code of the following checkboxes:
3205 * @param $tabindex int Current tabindex
3206 * @param $checked Array of checkbox => bool, where bool indicates the checked
3207 * status of the checkbox
3211 public function getCheckboxes( &$tabindex, $checked ) {
3214 $checkboxes = array();
3216 // don't show the minor edit checkbox if it's a new page or section
3217 if ( !$this->isNew
) {
3218 $checkboxes['minor'] = '';
3219 $minorLabel = wfMessage( 'minoredit' )->parse();
3220 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3222 'tabindex' => ++
$tabindex,
3223 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3224 'id' => 'wpMinoredit',
3226 $checkboxes['minor'] =
3227 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3228 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3229 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3230 ">{$minorLabel}</label>";
3234 $watchLabel = wfMessage( 'watchthis' )->parse();
3235 $checkboxes['watch'] = '';
3236 if ( $wgUser->isLoggedIn() ) {
3238 'tabindex' => ++
$tabindex,
3239 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3240 'id' => 'wpWatchthis',
3242 $checkboxes['watch'] =
3243 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3244 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3245 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3246 ">{$watchLabel}</label>";
3248 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3253 * Returns an array of html code of the following buttons:
3254 * save, diff, preview and live
3256 * @param $tabindex int Current tabindex
3260 public function getEditButtons( &$tabindex ) {
3267 'tabindex' => ++
$tabindex,
3268 'value' => wfMessage( 'savearticle' )->text(),
3269 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3270 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3272 $buttons['save'] = Xml
::element( 'input', $temp, '' );
3274 ++
$tabindex; // use the same for preview and live preview
3276 'id' => 'wpPreview',
3277 'name' => 'wpPreview',
3279 'tabindex' => $tabindex,
3280 'value' => wfMessage( 'showpreview' )->text(),
3281 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3282 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3284 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3285 $buttons['live'] = '';
3291 'tabindex' => ++
$tabindex,
3292 'value' => wfMessage( 'showdiff' )->text(),
3293 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3294 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3296 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3298 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3303 * Output preview text only. This can be sucked into the edit page
3304 * via JavaScript, and saves the server time rendering the skin as
3305 * well as theoretically being more robust on the client (doesn't
3306 * disturb the edit box's undo history, won't eat your text on
3309 * @todo This doesn't include category or interlanguage links.
3310 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3311 * or something...</s>" that might also require more skin
3312 * initialization, so check whether that's a problem.
3314 function livePreview() {
3317 header( 'Content-type: text/xml; charset=utf-8' );
3318 header( 'Cache-control: no-cache' );
3320 $previewText = $this->getPreviewText();
3321 #$categories = $skin->getCategoryLinks();
3324 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3325 Xml
::tags( 'livepreview', null,
3326 Xml
::element( 'preview', null, $previewText )
3327 #. Xml::element( 'category', null, $categories )
3333 * Call the stock "user is blocked" page
3335 * @deprecated in 1.19; throw an exception directly instead
3337 function blockedPage() {
3338 wfDeprecated( __METHOD__
, '1.19' );
3341 throw new UserBlockedError( $wgUser->getBlock() );
3345 * Produce the stock "please login to edit pages" page
3347 * @deprecated in 1.19; throw an exception directly instead
3349 function userNotLoggedInPage() {
3350 wfDeprecated( __METHOD__
, '1.19' );
3351 throw new PermissionsError( 'edit' );
3355 * Show an error page saying to the user that he has insufficient permissions
3356 * to create a new page
3358 * @deprecated in 1.19; throw an exception directly instead
3360 function noCreatePermission() {
3361 wfDeprecated( __METHOD__
, '1.19' );
3362 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3363 throw new PermissionsError( $permission );
3367 * Creates a basic error page which informs the user that
3368 * they have attempted to edit a nonexistent section.
3370 function noSuchSectionPage() {
3373 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3375 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3376 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3377 $wgOut->addHTML( $res );
3379 $wgOut->returnToMain( false, $this->mTitle
);
3383 * Produce the stock "your edit contains spam" page
3385 * @param $match string|bool Text which triggered one or more filters
3386 * @deprecated since 1.17 Use method spamPageWithContent() instead
3388 static function spamPage( $match = false ) {
3389 wfDeprecated( __METHOD__
, '1.17' );
3391 global $wgOut, $wgTitle;
3393 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3395 $wgOut->addHTML( '<div id="spamprotected">' );
3396 $wgOut->addWikiMsg( 'spamprotectiontext' );
3398 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3400 $wgOut->addHTML( '</div>' );
3402 $wgOut->returnToMain( false, $wgTitle );
3406 * Show "your edit contains spam" page with your diff and text
3408 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3410 public function spamPageWithContent( $match = false ) {
3411 global $wgOut, $wgLang;
3412 $this->textbox2
= $this->textbox1
;
3414 if( is_array( $match ) ){
3415 $match = $wgLang->listToText( $match );
3417 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3419 $wgOut->addHTML( '<div id="spamprotected">' );
3420 $wgOut->addWikiMsg( 'spamprotectiontext' );
3422 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3424 $wgOut->addHTML( '</div>' );
3426 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3429 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3430 $this->showTextbox2();
3432 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3436 * Format an anchor fragment as it would appear for a given section name
3437 * @param $text String
3441 function sectionAnchor( $text ) {
3443 return $wgParser->guessSectionNameFromWikiText( $text );
3447 * Check if the browser is on a blacklist of user-agents known to
3448 * mangle UTF-8 data on form submission. Returns true if Unicode
3449 * should make it through, false if it's known to be a problem.
3453 function checkUnicodeCompliantBrowser() {
3454 global $wgBrowserBlackList, $wgRequest;
3456 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3457 if ( $currentbrowser === false ) {
3458 // No User-Agent header sent? Trust it by default...
3462 foreach ( $wgBrowserBlackList as $browser ) {
3463 if ( preg_match( $browser, $currentbrowser ) ) {
3471 * Filter an input field through a Unicode de-armoring process if it
3472 * came from an old browser with known broken Unicode editing issues.
3474 * @param $request WebRequest
3475 * @param $field String
3479 function safeUnicodeInput( $request, $field ) {
3480 $text = rtrim( $request->getText( $field ) );
3481 return $request->getBool( 'safemode' )
3482 ?
$this->unmakesafe( $text )
3487 * @param $request WebRequest
3488 * @param $text string
3491 function safeUnicodeText( $request, $text ) {
3492 $text = rtrim( $text );
3493 return $request->getBool( 'safemode' )
3494 ?
$this->unmakesafe( $text )
3499 * Filter an output field through a Unicode armoring process if it is
3500 * going to an old browser with known broken Unicode editing issues.
3502 * @param $text String
3506 function safeUnicodeOutput( $text ) {
3508 $codedText = $wgContLang->recodeForEdit( $text );
3509 return $this->checkUnicodeCompliantBrowser()
3511 : $this->makesafe( $codedText );
3515 * A number of web browsers are known to corrupt non-ASCII characters
3516 * in a UTF-8 text editing environment. To protect against this,
3517 * detected browsers will be served an armored version of the text,
3518 * with non-ASCII chars converted to numeric HTML character references.
3520 * Preexisting such character references will have a 0 added to them
3521 * to ensure that round-trips do not alter the original data.
3523 * @param $invalue String
3527 function makesafe( $invalue ) {
3528 // Armor existing references for reversability.
3529 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3534 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3535 $bytevalue = ord( $invalue[$i] );
3536 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3537 $result .= chr( $bytevalue );
3539 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3540 $working = $working << 6;
3541 $working +
= ( $bytevalue & 0x3F );
3543 if ( $bytesleft <= 0 ) {
3544 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3546 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3547 $working = $bytevalue & 0x1F;
3549 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3550 $working = $bytevalue & 0x0F;
3552 } else { // 1111 0xxx
3553 $working = $bytevalue & 0x07;
3561 * Reverse the previously applied transliteration of non-ASCII characters
3562 * back to UTF-8. Used to protect data from corruption by broken web browsers
3563 * as listed in $wgBrowserBlackList.
3565 * @param $invalue String
3569 function unmakesafe( $invalue ) {
3571 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3572 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3576 $hexstring .= $invalue[$i];
3578 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3580 // Do some sanity checks. These aren't needed for reversability,
3581 // but should help keep the breakage down if the editor
3582 // breaks one of the entities whilst editing.
3583 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3584 $codepoint = hexdec( $hexstring );
3585 $result .= codepointToUtf8( $codepoint );
3587 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3590 $result .= substr( $invalue, $i, 1 );
3593 // reverse the transform that we made for reversability reasons.
3594 return strtr( $result, array( "�" => "&#x" ) );