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->setRobotPolicy( 'noindex,nofollow' );
484 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
485 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
486 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
487 $wgOut->addHTML( "<hr />\n" );
489 # If the user made changes, preserve them when showing the markup
490 # (This happens when a user is blocked during edit, for instance)
491 if ( !$this->firsttime
) {
492 $text = $this->textbox1
;
493 $wgOut->addWikiMsg( 'viewyourtext' );
495 $text = $this->toEditText( $content );
496 $wgOut->addWikiMsg( 'viewsourcetext' );
499 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
501 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
502 Linker
::formatTemplates( $this->getTemplates() ) ) );
504 if ( $this->mTitle
->exists() ) {
505 $wgOut->returnToMain( null, $this->mTitle
);
510 * Show a read-only error
511 * Parameters are the same as OutputPage:readOnlyPage()
512 * Redirect to the article page if redlink=1
513 * @deprecated in 1.19; use displayPermissionsError() instead
515 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
516 wfDeprecated( __METHOD__
, '1.19' );
518 global $wgRequest, $wgOut;
519 if ( $wgRequest->getBool( 'redlink' ) ) {
520 // The edit page was reached via a red link.
521 // Redirect to the article page and let them click the edit tab if
522 // they really want a permission error.
523 $wgOut->redirect( $this->mTitle
->getFullUrl() );
525 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
530 * Should we show a preview when the edit form is first shown?
534 protected function previewOnOpen() {
535 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
536 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
537 // Explicit override from request
539 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
540 // Explicit override from request
542 } elseif ( $this->section
== 'new' ) {
543 // Nothing *to* preview for new sections
545 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
546 // Standard preference behaviour
548 } elseif ( !$this->mTitle
->exists() &&
549 isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] ) &&
550 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
552 // Categories are special
560 * Checks whether the user entered a skin name in uppercase,
561 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
565 protected function isWrongCaseCssJsPage() {
566 if ( $this->mTitle
->isCssJsSubpage() ) {
567 $name = $this->mTitle
->getSkinFromCssJsSubpage();
568 $skins = array_merge(
569 array_keys( Skin
::getSkinNames() ),
572 return !in_array( $name, $skins )
573 && in_array( strtolower( $name ), $skins );
580 * Returns whether section editing is supported for the current page.
581 * Subclasses may override this to replace the default behavior, which is
582 * to check ContentHandler::supportsSections.
584 * @return bool true if this edit page supports sections, false otherwise.
586 protected function isSectionEditSupported() {
587 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
588 return $contentHandler->supportsSections();
592 * This function collects the form data and uses it to populate various member variables.
593 * @param $request WebRequest
595 function importFormData( &$request ) {
596 global $wgContLang, $wgUser;
598 wfProfileIn( __METHOD__
);
600 # Section edit can come from either the form or a link
601 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
603 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
604 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
607 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
609 if ( $request->wasPosted() ) {
610 # These fields need to be checked for encoding.
611 # Also remove trailing whitespace, but don't remove _initial_
612 # whitespace from the text boxes. This may be significant formatting.
613 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
614 if ( !$request->getCheck( 'wpTextbox2' ) ) {
615 // Skip this if wpTextbox2 has input, it indicates that we came
616 // from a conflict page with raw page text, not a custom form
617 // modified by subclasses
618 wfProfileIn( get_class( $this ) . "::importContentFormData" );
619 $textbox1 = $this->importContentFormData( $request );
620 if ( $textbox1 !== null ) {
621 $this->textbox1
= $textbox1;
624 wfProfileOut( get_class( $this ) . "::importContentFormData" );
627 # Trim spaces on user supplied text
628 $summary = trim( $request->getText( 'wpSummary' ) );
630 # Truncate for whole multibyte characters
631 $this->summary
= $wgContLang->truncate( $summary, 255 );
633 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
634 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
636 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
638 # Treat sectiontitle the same way as summary.
639 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
640 # currently doing double duty as both edit summary and section title. Right now this
641 # is just to allow API edits to work around this limitation, but this should be
642 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
643 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
644 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
646 $this->edittime
= $request->getVal( 'wpEdittime' );
647 $this->starttime
= $request->getVal( 'wpStarttime' );
649 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
651 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
652 // wpTextbox1 field is missing, possibly due to being "too big"
653 // according to some filter rules such as Suhosin's setting for
654 // suhosin.request.max_value_length (d'oh)
655 $this->incompleteForm
= true;
657 // edittime should be one of our last fields; if it's missing,
658 // the submission probably broke somewhere in the middle.
659 $this->incompleteForm
= is_null( $this->edittime
);
661 if ( $this->incompleteForm
) {
662 # If the form is incomplete, force to preview.
663 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
664 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
665 $this->preview
= true;
667 /* Fallback for live preview */
668 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
669 $this->diff
= $request->getCheck( 'wpDiff' );
671 // Remember whether a save was requested, so we can indicate
672 // if we forced preview due to session failure.
673 $this->mTriedSave
= !$this->preview
;
675 if ( $this->tokenOk( $request ) ) {
676 # Some browsers will not report any submit button
677 # if the user hits enter in the comment box.
678 # The unmarked state will be assumed to be a save,
679 # if the form seems otherwise complete.
680 wfDebug( __METHOD__
. ": Passed token check.\n" );
681 } elseif ( $this->diff
) {
682 # Failed token check, but only requested "Show Changes".
683 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
685 # Page might be a hack attempt posted from
686 # an external site. Preview instead of saving.
687 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
688 $this->preview
= true;
691 $this->save
= !$this->preview
&& !$this->diff
;
692 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
693 $this->edittime
= null;
696 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
697 $this->starttime
= null;
700 $this->recreate
= $request->getCheck( 'wpRecreate' );
702 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
703 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
705 # Don't force edit summaries when a user is editing their own user or talk page
706 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
707 $this->mTitle
->getText() == $wgUser->getName() )
709 $this->allowBlankSummary
= true;
711 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary' );
714 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
716 # Not a posted form? Start with nothing.
717 wfDebug( __METHOD__
. ": Not a posted form.\n" );
718 $this->textbox1
= '';
720 $this->sectiontitle
= '';
721 $this->edittime
= '';
722 $this->starttime
= wfTimestampNow();
724 $this->preview
= false;
727 $this->minoredit
= false;
728 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
729 $this->recreate
= false;
731 // When creating a new section, we can preload a section title by passing it as the
732 // preloadtitle parameter in the URL (Bug 13100)
733 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
734 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
735 // Once wpSummary isn't being use for setting section titles, we should delete this.
736 $this->summary
= $request->getVal( 'preloadtitle' );
738 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
739 $this->summary
= $request->getText( 'summary' );
740 if ( $this->summary
!== '' ) {
741 $this->hasPresetSummary
= true;
745 if ( $request->getVal( 'minor' ) ) {
746 $this->minoredit
= true;
750 $this->oldid
= $request->getInt( 'oldid' );
752 $this->bot
= $request->getBool( 'bot', true );
753 $this->nosummary
= $request->getBool( 'nosummary' );
755 $content_handler = ContentHandler
::getForTitle( $this->mTitle
);
756 $this->contentModel
= $request->getText( 'model', $content_handler->getModelID() ); #may be overridden by revision
757 $this->contentFormat
= $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
759 #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
760 #TODO: check if the desired content model supports the given content format!
762 $this->live
= $request->getCheck( 'live' );
763 $this->editintro
= $request->getText( 'editintro',
764 // Custom edit intro for new sections
765 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
767 // Allow extensions to modify form data
768 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
770 wfProfileOut( __METHOD__
);
774 * Subpage overridable method for extracting the page content data from the
775 * posted form to be placed in $this->textbox1, if using customized input
776 * this method should be overrided and return the page text that will be used
777 * for saving, preview parsing and so on...
779 * @param $request WebRequest
781 protected function importContentFormData( &$request ) {
782 return; // Don't do anything, EditPage already extracted wpTextbox1
786 * Initialise form fields in the object
787 * Called on the first invocation, e.g. when a user clicks an edit link
788 * @return bool -- if the requested section is valid
790 function initialiseForm() {
792 $this->edittime
= $this->mArticle
->getTimestamp();
794 $content = $this->getContentObject( false ); #TODO: track content object?!
795 if ( $content === false ) {
798 $this->textbox1
= $this->toEditText( $content );
800 // activate checkboxes if user wants them to be always active
801 # Sort out the "watch" checkbox
802 if ( $wgUser->getOption( 'watchdefault' ) ) {
804 $this->watchthis
= true;
805 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
807 $this->watchthis
= true;
808 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
810 $this->watchthis
= true;
812 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
813 $this->minoredit
= true;
815 if ( $this->textbox1
=== false ) {
823 * Fetch initial editing page content.
825 * @param $def_text string|bool
826 * @return mixed string on success, $def_text for invalid sections
828 * @deprecated since 1.21, get WikiPage::getContent() instead.
830 function getContent( $def_text = false ) {
831 ContentHandler
::deprecated( __METHOD__
, '1.21' );
833 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
834 $def_content = $this->toEditContent( $def_text );
836 $def_content = false;
839 $content = $this->getContentObject( $def_content );
841 // Note: EditPage should only be used with text based content anyway.
842 return $this->toEditText( $content );
846 * @param Content|null $def_content The default value to return
848 * @return mixed Content on success, $def_content for invalid sections
852 protected function getContentObject( $def_content = null ) {
853 global $wgOut, $wgRequest;
855 wfProfileIn( __METHOD__
);
859 // For message page not locally set, use the i18n message.
860 // For other non-existent articles, use preload text if any.
861 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
862 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
863 # If this is a system message, get the default text.
864 $msg = $this->mTitle
->getDefaultMessageText();
866 $content = $this->toEditContent( $msg );
868 if ( $content === false ) {
869 # If requested, preload some text.
870 $preload = $wgRequest->getVal( 'preload',
871 // Custom preload text for new sections
872 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
874 $content = $this->getPreloadedContent( $preload );
876 // For existing pages, get text based on "undo" or section parameters.
878 if ( $this->section
!= '' ) {
879 // Get section edit text (returns $def_text for invalid sections)
880 $orig = $this->getOriginalContent();
881 $content = $orig ?
$orig->getSection( $this->section
) : null;
883 if ( !$content ) $content = $def_content;
885 $undoafter = $wgRequest->getInt( 'undoafter' );
886 $undo = $wgRequest->getInt( 'undo' );
888 if ( $undo > 0 && $undoafter > 0 ) {
889 if ( $undo < $undoafter ) {
890 # If they got undoafter and undo round the wrong way, switch them
891 list( $undo, $undoafter ) = array( $undoafter, $undo );
894 $undorev = Revision
::newFromId( $undo );
895 $oldrev = Revision
::newFromId( $undoafter );
897 # Sanity check, make sure it's the right page,
898 # the revisions exist and they were not deleted.
899 # Otherwise, $content will be left as-is.
900 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
901 $undorev->getPage() == $oldrev->getPage() &&
902 $undorev->getPage() == $this->mTitle
->getArticleID() &&
903 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
904 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
906 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
908 if ( $content === false ) {
909 # Warn the user that something went wrong
910 $undoMsg = 'failure';
912 # Inform the user of our success and set an automatic edit summary
913 $undoMsg = 'success';
915 # If we just undid one rev, use an autosummary
916 $firstrev = $oldrev->getNext();
917 if ( $firstrev && $firstrev->getId() == $undo ) {
918 $undoSummary = wfMessage( 'undo-summary', $undo, $undorev->getUserText() )->inContentLanguage()->text();
919 if ( $this->summary
=== '' ) {
920 $this->summary
= $undoSummary;
922 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
923 ->inContentLanguage()->text() . $this->summary
;
925 $this->undidRev
= $undo;
927 $this->formtype
= 'diff';
930 // Failed basic sanity checks.
931 // Older revisions may have been removed since the link
932 // was created, or we may simply have got bogus input.
936 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
937 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
938 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
941 if ( $content === false ) {
942 $content = $this->getOriginalContent();
947 wfProfileOut( __METHOD__
);
952 * Get the content of the wanted revision, without section extraction.
954 * The result of this function can be used to compare user's input with
955 * section replaced in its context (using WikiPage::replaceSection())
956 * to the original text of the edit.
958 * This difers from Article::getContent() that when a missing revision is
959 * encountered the result will be null and not the
960 * 'missing-revision' message.
963 * @return Content|null
965 private function getOriginalContent() {
966 if ( $this->section
== 'new' ) {
967 return $this->getCurrentContent();
969 $revision = $this->mArticle
->getRevisionFetched();
970 if ( $revision === null ) {
971 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
972 $handler = ContentHandler
::getForModelID( $this->contentModel
);
974 return $handler->makeEmptyContent();
976 $content = $revision->getContent();
981 * Get the current content of the page. This is basically similar to
982 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
983 * content object is returned instead of null.
988 protected function getCurrentContent() {
989 $rev = $this->mArticle
->getRevision();
990 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
992 if ( $content === false ||
$content === null ) {
993 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
994 $handler = ContentHandler
::getForModelID( $this->contentModel
);
996 return $handler->makeEmptyContent();
998 # nasty side-effect, but needed for consistency
999 $this->contentModel
= $rev->getContentModel();
1000 $this->contentFormat
= $rev->getContentFormat();
1008 * Use this method before edit() to preload some text into the edit box
1010 * @param $text string
1011 * @deprecated since 1.21, use setPreloadedContent() instead.
1013 public function setPreloadedText( $text ) {
1014 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1016 $content = $this->toEditContent( $text );
1018 $this->setPreloadedContent( $content );
1022 * Use this method before edit() to preload some content into the edit box
1024 * @param $content Content
1028 public function setPreloadedContent( Content
$content ) {
1029 $this->mPreloadContent
= $content;
1033 * Get the contents to be preloaded into the box, either set by
1034 * an earlier setPreloadText() or by loading the given page.
1036 * @param $preload String: representing the title to preload from.
1040 * @deprecated since 1.21, use getPreloadedContent() instead
1042 protected function getPreloadedText( $preload ) {
1043 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1045 $content = $this->getPreloadedContent( $preload );
1046 $text = $this->toEditText( $content );
1052 * Get the contents to be preloaded into the box, either set by
1053 * an earlier setPreloadText() or by loading the given page.
1055 * @param $preload String: representing the title to preload from.
1061 protected function getPreloadedContent( $preload ) {
1064 if ( !empty( $this->mPreloadContent
) ) {
1065 return $this->mPreloadContent
;
1068 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1070 if ( $preload === '' ) {
1071 return $handler->makeEmptyContent();
1074 $title = Title
::newFromText( $preload );
1075 # Check for existence to avoid getting MediaWiki:Noarticletext
1076 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1077 //TODO: somehow show a warning to the user!
1078 return $handler->makeEmptyContent();
1081 $page = WikiPage
::factory( $title );
1082 if ( $page->isRedirect() ) {
1083 $title = $page->getRedirectTarget();
1085 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1086 //TODO: somehow show a warning to the user!
1087 return $handler->makeEmptyContent();
1089 $page = WikiPage
::factory( $title );
1092 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1093 $content = $page->getContent( Revision
::RAW
);
1096 //TODO: somehow show a warning to the user!
1097 return $handler->makeEmptyContent();
1100 if ( $content->getModel() !== $handler->getModelID() ) {
1101 $converted = $content->convert( $handler->getModelID() );
1103 if ( !$converted ) {
1104 //TODO: somehow show a warning to the user!
1105 wfDebug( "Attempt to preload incompatible content: "
1106 . "can't convert " . $content->getModel()
1107 . " to " . $handler->getModelID() );
1109 return $handler->makeEmptyContent();
1112 $content = $converted;
1115 return $content->preloadTransform( $title, $parserOptions );
1119 * Make sure the form isn't faking a user's credentials.
1121 * @param $request WebRequest
1125 function tokenOk( &$request ) {
1127 $token = $request->getVal( 'wpEditToken' );
1128 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1129 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1130 return $this->mTokenOk
;
1134 * Attempt submission
1135 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1136 * @return bool false if output is done, true if the rest of the form should be displayed
1138 function attemptSave() {
1139 global $wgUser, $wgOut;
1141 $resultDetails = false;
1142 # Allow bots to exempt some edits from bot flagging
1143 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1144 $status = $this->internalAttemptSave( $resultDetails, $bot );
1145 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1146 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1147 $this->didSave
= true;
1150 switch ( $status->value
) {
1151 case self
::AS_HOOK_ERROR_EXPECTED
:
1152 case self
::AS_CONTENT_TOO_BIG
:
1153 case self
::AS_ARTICLE_WAS_DELETED
:
1154 case self
::AS_CONFLICT_DETECTED
:
1155 case self
::AS_SUMMARY_NEEDED
:
1156 case self
::AS_TEXTBOX_EMPTY
:
1157 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1161 case self
::AS_HOOK_ERROR
:
1164 case self
::AS_PARSE_ERROR
:
1165 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>');
1168 case self
::AS_SUCCESS_NEW_ARTICLE
:
1169 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1170 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1171 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1174 case self
::AS_SUCCESS_UPDATE
:
1176 $sectionanchor = $resultDetails['sectionanchor'];
1178 // Give extensions a chance to modify URL query on update
1179 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1181 if ( $resultDetails['redirect'] ) {
1182 if ( $extraQuery == '' ) {
1183 $extraQuery = 'redirect=no';
1185 $extraQuery = 'redirect=no&' . $extraQuery;
1188 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1191 case self
::AS_BLANK_ARTICLE
:
1192 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1195 case self
::AS_SPAM_ERROR
:
1196 $this->spamPageWithContent( $resultDetails['spam'] );
1199 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1200 throw new UserBlockedError( $wgUser->getBlock() );
1202 case self
::AS_IMAGE_REDIRECT_ANON
:
1203 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1204 throw new PermissionsError( 'upload' );
1206 case self
::AS_READ_ONLY_PAGE_ANON
:
1207 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1208 throw new PermissionsError( 'edit' );
1210 case self
::AS_READ_ONLY_PAGE
:
1211 throw new ReadOnlyError
;
1213 case self
::AS_RATE_LIMITED
:
1214 throw new ThrottledError();
1216 case self
::AS_NO_CREATE_PERMISSION
:
1217 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1218 throw new PermissionsError( $permission );
1221 // We don't recognize $status->value. The only way that can happen
1222 // is if an extension hook aborted from inside ArticleSave.
1223 // Render the status object into $this->hookError
1224 // FIXME this sucks, we should just use the Status object throughout
1225 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1232 * Run hooks that can filter edits just before they get saved.
1234 * @param Content $content the Content to filter.
1235 * @param Status $status for reporting the outcome to the caller
1236 * @param User $user the user performing the edit
1240 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1241 // Run old style post-section-merge edit filter
1242 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1243 array( $this, $content, &$this->hookError
, $this->summary
) ) ) {
1245 # Error messages etc. could be handled within the hook...
1246 $status->fatal( 'hookaborted' );
1247 $status->value
= self
::AS_HOOK_ERROR
;
1249 } elseif ( $this->hookError
!= '' ) {
1250 # ...or the hook could be expecting us to produce an error
1251 $status->fatal( 'hookaborted' );
1252 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1256 // Run new style post-section-merge edit filter
1257 if ( !wfRunHooks( 'EditFilterMergedContent',
1258 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1259 $user, $this->minoredit
) ) ) {
1261 # Error messages etc. could be handled within the hook...
1262 // XXX: $status->value may already be something informative...
1263 $this->hookError
= $status->getWikiText();
1264 $status->fatal( 'hookaborted' );
1265 $status->value
= self
::AS_HOOK_ERROR
;
1267 } elseif ( !$status->isOK() ) {
1268 # ...or the hook could be expecting us to produce an error
1269 // FIXME this sucks, we should just use the Status object throughout
1270 $this->hookError
= $status->getWikiText();
1271 $status->fatal( 'hookaborted' );
1272 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1280 * Attempt submission (no UI)
1285 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1287 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1288 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1289 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1291 function internalAttemptSave( &$result, $bot = false ) {
1292 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1294 $status = Status
::newGood();
1296 wfProfileIn( __METHOD__
);
1297 wfProfileIn( __METHOD__
. '-checks' );
1299 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1300 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1301 $status->fatal( 'hookaborted' );
1302 $status->value
= self
::AS_HOOK_ERROR
;
1303 wfProfileOut( __METHOD__
. '-checks' );
1304 wfProfileOut( __METHOD__
);
1309 # Construct Content object
1310 $textbox_content = $this->toEditContent( $this->textbox1
);
1311 } catch ( MWContentSerializationException
$ex ) {
1312 $status->fatal( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
1313 $status->value
= self
::AS_PARSE_ERROR
;
1314 wfProfileOut( __METHOD__
. '-checks' );
1315 wfProfileOut( __METHOD__
);
1319 # Check image redirect
1320 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1321 $textbox_content->isRedirect() &&
1322 !$wgUser->isAllowed( 'upload' ) ) {
1323 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1324 $status->setResult( false, $code );
1326 wfProfileOut( __METHOD__
. '-checks' );
1327 wfProfileOut( __METHOD__
);
1333 $match = self
::matchSummarySpamRegex( $this->summary
);
1334 if ( $match === false ) {
1335 $match = self
::matchSpamRegex( $this->textbox1
);
1337 if ( $match !== false ) {
1338 $result['spam'] = $match;
1339 $ip = $wgRequest->getIP();
1340 $pdbk = $this->mTitle
->getPrefixedDBkey();
1341 $match = str_replace( "\n", '', $match );
1342 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1343 $status->fatal( 'spamprotectionmatch', $match );
1344 $status->value
= self
::AS_SPAM_ERROR
;
1345 wfProfileOut( __METHOD__
. '-checks' );
1346 wfProfileOut( __METHOD__
);
1349 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1350 # Error messages etc. could be handled within the hook...
1351 $status->fatal( 'hookaborted' );
1352 $status->value
= self
::AS_HOOK_ERROR
;
1353 wfProfileOut( __METHOD__
. '-checks' );
1354 wfProfileOut( __METHOD__
);
1356 } elseif ( $this->hookError
!= '' ) {
1357 # ...or the hook could be expecting us to produce an error
1358 $status->fatal( 'hookaborted' );
1359 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1360 wfProfileOut( __METHOD__
. '-checks' );
1361 wfProfileOut( __METHOD__
);
1365 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1366 // Auto-block user's IP if the account was "hard" blocked
1367 $wgUser->spreadAnyEditBlock();
1368 # Check block state against master, thus 'false'.
1369 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1370 wfProfileOut( __METHOD__
. '-checks' );
1371 wfProfileOut( __METHOD__
);
1375 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1376 if ( $this->kblength
> $wgMaxArticleSize ) {
1377 // Error will be displayed by showEditForm()
1378 $this->tooBig
= true;
1379 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1380 wfProfileOut( __METHOD__
. '-checks' );
1381 wfProfileOut( __METHOD__
);
1385 if ( !$wgUser->isAllowed( 'edit' ) ) {
1386 if ( $wgUser->isAnon() ) {
1387 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1388 wfProfileOut( __METHOD__
. '-checks' );
1389 wfProfileOut( __METHOD__
);
1392 $status->fatal( 'readonlytext' );
1393 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1394 wfProfileOut( __METHOD__
. '-checks' );
1395 wfProfileOut( __METHOD__
);
1400 if ( wfReadOnly() ) {
1401 $status->fatal( 'readonlytext' );
1402 $status->value
= self
::AS_READ_ONLY_PAGE
;
1403 wfProfileOut( __METHOD__
. '-checks' );
1404 wfProfileOut( __METHOD__
);
1407 if ( $wgUser->pingLimiter() ) {
1408 $status->fatal( 'actionthrottledtext' );
1409 $status->value
= self
::AS_RATE_LIMITED
;
1410 wfProfileOut( __METHOD__
. '-checks' );
1411 wfProfileOut( __METHOD__
);
1415 # If the article has been deleted while editing, don't save it without
1417 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1418 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1419 wfProfileOut( __METHOD__
. '-checks' );
1420 wfProfileOut( __METHOD__
);
1424 wfProfileOut( __METHOD__
. '-checks' );
1426 # Load the page data from the master. If anything changes in the meantime,
1427 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1428 $this->mArticle
->loadPageData( 'fromdbmaster' );
1429 $new = !$this->mArticle
->exists();
1432 // Late check for create permission, just in case *PARANOIA*
1433 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1434 $status->fatal( 'nocreatetext' );
1435 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1436 wfDebug( __METHOD__
. ": no create permission\n" );
1437 wfProfileOut( __METHOD__
);
1441 # Don't save a new article if it's blank.
1442 if ( $this->textbox1
== '' ) {
1443 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1444 wfProfileOut( __METHOD__
);
1448 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1449 wfProfileOut( __METHOD__
);
1453 $content = $textbox_content;
1455 $result['sectionanchor'] = '';
1456 if ( $this->section
== 'new' ) {
1457 if ( $this->sectiontitle
!== '' ) {
1458 // Insert the section title above the content.
1459 $content = $content->addSectionHeader( $this->sectiontitle
);
1461 // Jump to the new section
1462 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1464 // If no edit summary was specified, create one automatically from the section
1465 // title and have it link to the new section. Otherwise, respect the summary as
1467 if ( $this->summary
=== '' ) {
1468 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1469 $this->summary
= wfMessage( 'newsectionsummary' )
1470 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1472 } elseif ( $this->summary
!== '' ) {
1473 // Insert the section title above the content.
1474 $content = $content->addSectionHeader( $this->summary
);
1476 // Jump to the new section
1477 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1479 // Create a link to the new section from the edit summary.
1480 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1481 $this->summary
= wfMessage( 'newsectionsummary' )
1482 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1486 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1490 # Article exists. Check for edit conflict.
1492 $this->mArticle
->clear(); # Force reload of dates, etc.
1493 $timestamp = $this->mArticle
->getTimestamp();
1495 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1497 if ( $timestamp != $this->edittime
) {
1498 $this->isConflict
= true;
1499 if ( $this->section
== 'new' ) {
1500 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1501 $this->mArticle
->getComment() == $this->summary
) {
1502 // Probably a duplicate submission of a new comment.
1503 // This can happen when squid resends a request after
1504 // a timeout but the first one actually went through.
1505 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1507 // New comment; suppress conflict.
1508 $this->isConflict
= false;
1509 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1511 } elseif ( $this->section
== '' && Revision
::userWasLastToEdit( DB_MASTER
, $this->mTitle
->getArticleID(),
1512 $wgUser->getId(), $this->edittime
) ) {
1513 # Suppress edit conflict with self, except for section edits where merging is required.
1514 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1515 $this->isConflict
= false;
1519 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1520 // backwards compatibility with old forms/bots).
1521 if ( $this->sectiontitle
!== '' ) {
1522 $sectionTitle = $this->sectiontitle
;
1524 $sectionTitle = $this->summary
;
1529 if ( $this->isConflict
) {
1530 wfDebug( __METHOD__
. ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1531 . " (article time '{$timestamp}')\n" );
1533 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1535 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1536 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1539 if ( is_null( $content ) ) {
1540 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1541 $this->isConflict
= true;
1542 $content = $textbox_content; // do not try to merge here!
1543 } elseif ( $this->isConflict
) {
1545 if ( $this->mergeChangesIntoContent( $content ) ) {
1546 // Successful merge! Maybe we should tell the user the good news?
1547 $this->isConflict
= false;
1548 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1550 $this->section
= '';
1551 $this->textbox1
= ContentHandler
::getContentText( $content );
1552 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1556 if ( $this->isConflict
) {
1557 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1558 wfProfileOut( __METHOD__
);
1562 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1563 wfProfileOut( __METHOD__
);
1567 # Handle the user preference to force summaries here, but not for null edits
1568 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1569 && !$content->equals( $this->getOriginalContent() )
1570 && !$content->isRedirect() ) # check if it's not a redirect
1572 if ( md5( $this->summary
) == $this->autoSumm
) {
1573 $this->missingSummary
= true;
1574 $status->fatal( 'missingsummary' );
1575 $status->value
= self
::AS_SUMMARY_NEEDED
;
1576 wfProfileOut( __METHOD__
);
1581 # And a similar thing for new sections
1582 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1583 if ( trim( $this->summary
) == '' ) {
1584 $this->missingSummary
= true;
1585 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1586 $status->value
= self
::AS_SUMMARY_NEEDED
;
1587 wfProfileOut( __METHOD__
);
1593 wfProfileIn( __METHOD__
. '-sectionanchor' );
1594 $sectionanchor = '';
1595 if ( $this->section
== 'new' ) {
1596 if ( $this->textbox1
== '' ) {
1597 $this->missingComment
= true;
1598 $status->fatal( 'missingcommenttext' );
1599 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1600 wfProfileOut( __METHOD__
. '-sectionanchor' );
1601 wfProfileOut( __METHOD__
);
1604 if ( $this->sectiontitle
!== '' ) {
1605 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1606 // If no edit summary was specified, create one automatically from the section
1607 // title and have it link to the new section. Otherwise, respect the summary as
1609 if ( $this->summary
=== '' ) {
1610 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1611 $this->summary
= wfMessage( 'newsectionsummary' )
1612 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1614 } elseif ( $this->summary
!== '' ) {
1615 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1616 # This is a new section, so create a link to the new section
1617 # in the revision summary.
1618 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1619 $this->summary
= wfMessage( 'newsectionsummary' )
1620 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1622 } elseif ( $this->section
!= '' ) {
1623 # Try to get a section anchor from the section source, redirect to edited section if header found
1624 # XXX: might be better to integrate this into Article::replaceSection
1625 # for duplicate heading checking and maybe parsing
1626 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1627 # we can't deal with anchors, includes, html etc in the header for now,
1628 # headline would need to be parsed to improve this
1629 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1630 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1633 $result['sectionanchor'] = $sectionanchor;
1634 wfProfileOut( __METHOD__
. '-sectionanchor' );
1636 // Save errors may fall down to the edit form, but we've now
1637 // merged the section into full text. Clear the section field
1638 // so that later submission of conflict forms won't try to
1639 // replace that into a duplicated mess.
1640 $this->textbox1
= $this->toEditText( $content );
1641 $this->section
= '';
1643 $status->value
= self
::AS_SUCCESS_UPDATE
;
1646 // Check for length errors again now that the section is merged in
1647 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1648 if ( $this->kblength
> $wgMaxArticleSize ) {
1649 $this->tooBig
= true;
1650 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1651 wfProfileOut( __METHOD__
);
1655 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1656 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1657 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1658 ( $bot ? EDIT_FORCE_BOT
: 0 );
1660 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags,
1661 false, null, $this->contentFormat
);
1663 if ( !$doEditStatus->isOK() ) {
1664 // Failure from doEdit()
1665 // Show the edit conflict page for certain recognized errors from doEdit(),
1666 // but don't show it for errors from extension hooks
1667 $errors = $doEditStatus->getErrorsArray();
1668 if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
1669 'edit-already-exists' ) ) )
1671 $this->isConflict
= true;
1672 // Destroys data doEdit() put in $status->value but who cares
1673 $doEditStatus->value
= self
::AS_END
;
1675 wfProfileOut( __METHOD__
);
1676 return $doEditStatus;
1679 $result['redirect'] = $content->isRedirect();
1680 $this->updateWatchlist();
1681 wfProfileOut( __METHOD__
);
1686 * Register the change of watch status
1688 protected function updateWatchlist() {
1691 if ( $wgUser->isLoggedIn() && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
) ) {
1692 $fname = __METHOD__
;
1693 $title = $this->mTitle
;
1694 $watch = $this->watchthis
;
1696 // Do this in its own transaction to reduce contention...
1697 $dbw = wfGetDB( DB_MASTER
);
1698 $dbw->onTransactionIdle( function() use ( $dbw, $title, $watch, $wgUser, $fname ) {
1699 $dbw->begin( $fname );
1701 WatchAction
::doWatch( $title, $wgUser );
1703 WatchAction
::doUnwatch( $title, $wgUser );
1705 $dbw->commit( $fname );
1711 * Attempts to merge text content with base and current revisions
1713 * @param $editText string
1716 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1718 function mergeChangesInto( &$editText ) {
1719 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1721 $editContent = $this->toEditContent( $editText );
1723 $ok = $this->mergeChangesIntoContent( $editContent );
1726 $editText = $this->toEditText( $editContent );
1733 * Attempts to do 3-way merge of edit content with a base revision
1734 * and current content, in case of edit conflict, in whichever way appropriate
1735 * for the content type.
1739 * @param $editContent
1743 private function mergeChangesIntoContent( &$editContent ) {
1744 wfProfileIn( __METHOD__
);
1746 $db = wfGetDB( DB_MASTER
);
1748 // This is the revision the editor started from
1749 $baseRevision = $this->getBaseRevision();
1750 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
1752 if ( is_null( $baseContent ) ) {
1753 wfProfileOut( __METHOD__
);
1757 // The current state, we want to merge updates into it
1758 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1759 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
1761 if ( is_null( $currentContent ) ) {
1762 wfProfileOut( __METHOD__
);
1766 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
1768 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1771 $editContent = $result;
1772 wfProfileOut( __METHOD__
);
1776 wfProfileOut( __METHOD__
);
1783 function getBaseRevision() {
1784 if ( !$this->mBaseRevision
) {
1785 $db = wfGetDB( DB_MASTER
);
1786 $baseRevision = Revision
::loadFromTimestamp(
1787 $db, $this->mTitle
, $this->edittime
);
1788 return $this->mBaseRevision
= $baseRevision;
1790 return $this->mBaseRevision
;
1795 * Check given input text against $wgSpamRegex, and return the text of the first match.
1797 * @param $text string
1799 * @return string|bool matching string or false
1801 public static function matchSpamRegex( $text ) {
1802 global $wgSpamRegex;
1803 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1804 $regexes = (array)$wgSpamRegex;
1805 return self
::matchSpamRegexInternal( $text, $regexes );
1809 * Check given input text against $wgSpamRegex, and return the text of the first match.
1811 * @param $text string
1813 * @return string|bool matching string or false
1815 public static function matchSummarySpamRegex( $text ) {
1816 global $wgSummarySpamRegex;
1817 $regexes = (array)$wgSummarySpamRegex;
1818 return self
::matchSpamRegexInternal( $text, $regexes );
1822 * @param $text string
1823 * @param $regexes array
1824 * @return bool|string
1826 protected static function matchSpamRegexInternal( $text, $regexes ) {
1827 foreach ( $regexes as $regex ) {
1829 if ( preg_match( $regex, $text, $matches ) ) {
1836 function setHeaders() {
1837 global $wgOut, $wgUser;
1839 $wgOut->addModules( 'mediawiki.action.edit' );
1841 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1842 $wgOut->addModules( 'mediawiki.action.edit.preview' );
1844 // Bug #19334: textarea jumps when editing articles in IE8
1845 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1847 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1849 # Enabled article-related sidebar, toplinks, etc.
1850 $wgOut->setArticleRelated( true );
1852 $contextTitle = $this->getContextTitle();
1853 if ( $this->isConflict
) {
1854 $msg = 'editconflict';
1855 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1856 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1858 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1859 'editing' : 'creating';
1861 # Use the title defined by DISPLAYTITLE magic word when present
1862 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1863 if ( $displayTitle === false ) {
1864 $displayTitle = $contextTitle->getPrefixedText();
1866 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1870 * Show all applicable editing introductions
1872 protected function showIntro() {
1873 global $wgOut, $wgUser;
1874 if ( $this->suppressIntro
) {
1878 $namespace = $this->mTitle
->getNamespace();
1880 if ( $namespace == NS_MEDIAWIKI
) {
1881 # Show a warning if editing an interface message
1882 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1883 } else if( $namespace == NS_FILE
) {
1884 # Show a hint to shared repo
1885 $file = wfFindFile( $this->mTitle
);
1886 if( $file && !$file->isLocal() ) {
1887 $descUrl = $file->getDescriptionUrl();
1888 # there must be a description url to show a hint to shared repo
1890 if( !$this->mTitle
->exists() ) {
1891 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1892 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1895 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1896 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1903 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1904 # Show log extract when the user is currently blocked
1905 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1906 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1907 $username = $parts[0];
1908 $user = User
::newFromName( $username, false /* allow IP users*/ );
1909 $ip = User
::isIP( $username );
1910 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1911 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1912 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1913 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1914 LogEventsList
::showLogExtract(
1917 $user->getUserPage(),
1921 'showIfEmpty' => false,
1923 'blocked-notice-logextract',
1924 $user->getName() # Support GENDER in notice
1930 # Try to add a custom edit intro, or use the standard one if this is not possible.
1931 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1932 if ( $wgUser->isLoggedIn() ) {
1933 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1935 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1938 # Give a notice if the user is editing a deleted/moved page...
1939 if ( !$this->mTitle
->exists() ) {
1940 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1944 'conds' => array( "log_action != 'revision'" ),
1945 'showIfEmpty' => false,
1946 'msgKey' => array( 'recreate-moveddeleted-warn' )
1953 * Attempt to show a custom editing introduction, if supplied
1957 protected function showCustomIntro() {
1958 if ( $this->editintro
) {
1959 $title = Title
::newFromText( $this->editintro
);
1960 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1962 // Added using template syntax, to take <noinclude>'s into account.
1963 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1971 * Gets an editable textual representation of $content.
1972 * The textual representation can be turned by into a Content object by the
1973 * toEditContent() method.
1975 * If $content is null or false or a string, $content is returned unchanged.
1977 * If the given Content object is not of a type that can be edited using the text base EditPage,
1978 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
1981 * @param Content|null|bool|string $content
1982 * @return String the editable text form of the content.
1984 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
1986 protected function toEditText( $content ) {
1987 if ( $content === null ||
$content === false ) {
1991 if ( is_string( $content ) ) {
1995 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
1996 throw new MWException( "This content model can not be edited as text: "
1997 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2000 return $content->serialize( $this->contentFormat
);
2004 * Turns the given text into a Content object by unserializing it.
2006 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
2007 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2010 * @param String|null|bool $text Text to unserialize
2011 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
2014 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
2015 * and $this->allowNonTextContent is not true.
2017 protected function toEditContent( $text ) {
2018 if ( $text === false ||
$text === null ) {
2022 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2023 $this->contentModel
, $this->contentFormat
);
2025 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
2026 throw new MWException( "This content model can not be edited as text: "
2027 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2034 * Send the edit form and related headers to $wgOut
2035 * @param $formCallback Callback|null that takes an OutputPage parameter; will be called
2036 * during form output near the top, for captchas and the like.
2038 function showEditForm( $formCallback = null ) {
2039 global $wgOut, $wgUser;
2041 wfProfileIn( __METHOD__
);
2043 # need to parse the preview early so that we know which templates are used,
2044 # otherwise users with "show preview after edit box" will get a blank list
2045 # we parse this near the beginning so that setHeaders can do the title
2046 # setting work instead of leaving it in getPreviewText
2047 $previewOutput = '';
2048 if ( $this->formtype
== 'preview' ) {
2049 $previewOutput = $this->getPreviewText();
2052 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2054 $this->setHeaders();
2056 if ( $this->showHeader() === false ) {
2057 wfProfileOut( __METHOD__
);
2061 $wgOut->addHTML( $this->editFormPageTop
);
2063 if ( $wgUser->getOption( 'previewontop' ) ) {
2064 $this->displayPreviewArea( $previewOutput, true );
2067 $wgOut->addHTML( $this->editFormTextTop
);
2069 $showToolbar = true;
2070 if ( $this->wasDeletedSinceLastEdit() ) {
2071 if ( $this->formtype
== 'save' ) {
2072 // Hide the toolbar and edit area, user can click preview to get it back
2073 // Add an confirmation checkbox and explanation.
2074 $showToolbar = false;
2076 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2077 'deletedwhileediting' );
2081 //@todo: add EditForm plugin interface and use it here!
2082 // search for textarea1 and textares2, and allow EditForm to override all uses.
2083 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => self
::EDITFORM_ID
, 'name' => self
::EDITFORM_ID
,
2084 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
2085 'enctype' => 'multipart/form-data' ) ) );
2087 if ( is_callable( $formCallback ) ) {
2088 call_user_func_array( $formCallback, array( &$wgOut ) );
2091 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2093 // Put these up at the top to ensure they aren't lost on early form submission
2094 $this->showFormBeforeText();
2096 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2097 $username = $this->lastDelete
->user_name
;
2098 $comment = $this->lastDelete
->log_comment
;
2100 // It is better to not parse the comment at all than to have templates expanded in the middle
2101 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2102 $key = $comment === ''
2103 ?
'confirmrecreate-noreason'
2104 : 'confirmrecreate';
2106 '<div class="mw-confirm-recreate">' .
2107 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2108 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2109 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2115 # When the summary is hidden, also hide them on preview/show changes
2116 if( $this->nosummary
) {
2117 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2120 # If a blank edit summary was previously provided, and the appropriate
2121 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2122 # user being bounced back more than once in the event that a summary
2125 # For a bit more sophisticated detection of blank summaries, hash the
2126 # automatic one and pass that in the hidden field wpAutoSummary.
2127 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2128 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2131 if ( $this->undidRev
) {
2132 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2135 if ( $this->hasPresetSummary
) {
2136 // If a summary has been preset using &summary= we dont want to prompt for
2137 // a different summary. Only prompt for a summary if the summary is blanked.
2139 $this->autoSumm
= md5( '' );
2142 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2143 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2145 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2147 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2148 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2150 if ( $this->section
== 'new' ) {
2151 $this->showSummaryInput( true, $this->summary
);
2152 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2155 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2157 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2158 $wgOut->addHTML( EditPage
::getEditToolbar() );
2161 if ( $this->isConflict
) {
2162 // In an edit conflict bypass the overrideable content form method
2163 // and fallback to the raw wpTextbox1 since editconflicts can't be
2164 // resolved between page source edits and custom ui edits using the
2166 $this->textbox2
= $this->textbox1
;
2168 $content = $this->getCurrentContent();
2169 $this->textbox1
= $this->toEditText( $content );
2171 $this->showTextbox1();
2173 $this->showContentForm();
2176 $wgOut->addHTML( $this->editFormTextAfterContent
);
2178 $this->showStandardInputs();
2180 $this->showFormAfterText();
2182 $this->showTosSummary();
2184 $this->showEditTools();
2186 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2188 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2189 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2191 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2192 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2194 if ( $this->isConflict
) {
2196 $this->showConflict();
2197 } catch ( MWContentSerializationException
$ex ) {
2198 // this can't really happen, but be nice if it does.
2199 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2200 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2204 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2206 if ( !$wgUser->getOption( 'previewontop' ) ) {
2207 $this->displayPreviewArea( $previewOutput, false );
2210 wfProfileOut( __METHOD__
);
2214 * Extract the section title from current section text, if any.
2216 * @param string $text
2217 * @return Mixed|string or false
2219 public static function extractSectionTitle( $text ) {
2220 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2221 if ( !empty( $matches[2] ) ) {
2223 return $wgParser->stripSectionName( trim( $matches[2] ) );
2229 protected function showHeader() {
2230 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2232 if ( $this->mTitle
->isTalkPage() ) {
2233 $wgOut->addWikiMsg( 'talkpagetext' );
2237 $wgOut->addHTML( implode( "\n", $this->mTitle
->getEditNotices() ) );
2239 if ( $this->isConflict
) {
2240 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2241 $this->edittime
= $this->mArticle
->getTimestamp();
2243 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2244 // We use $this->section to much before this and getVal('wgSection') directly in other places
2245 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2246 // Someone is welcome to try refactoring though
2247 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2251 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2252 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2253 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2254 if ( $sectionTitle !== false ) {
2255 $this->summary
= "/* $sectionTitle */ ";
2260 if ( $this->missingComment
) {
2261 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2264 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2265 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2268 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2269 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2272 if ( $this->hookError
!== '' ) {
2273 $wgOut->addWikiText( $this->hookError
);
2276 if ( !$this->checkUnicodeCompliantBrowser() ) {
2277 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2280 if ( $this->section
!= 'new' ) {
2281 $revision = $this->mArticle
->getRevisionFetched();
2283 // Let sysop know that this will make private content public if saved
2285 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2286 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2287 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2288 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2291 if ( !$revision->isCurrent() ) {
2292 $this->mArticle
->setOldSubtitle( $revision->getId() );
2293 $wgOut->addWikiMsg( 'editingold' );
2295 } elseif ( $this->mTitle
->exists() ) {
2296 // Something went wrong
2298 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2299 array( 'missing-revision', $this->oldid
) );
2304 if ( wfReadOnly() ) {
2305 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2306 } elseif ( $wgUser->isAnon() ) {
2307 if ( $this->formtype
!= 'preview' ) {
2308 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2310 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2313 if ( $this->isCssJsSubpage
) {
2314 # Check the skin exists
2315 if ( $this->isWrongCaseCssJsPage
) {
2316 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2318 if ( $this->formtype
!== 'preview' ) {
2319 if ( $this->isCssSubpage
) {
2320 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2323 if ( $this->isJsSubpage
) {
2324 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2330 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2331 # Is the title semi-protected?
2332 if ( $this->mTitle
->isSemiProtected() ) {
2333 $noticeMsg = 'semiprotectedpagewarning';
2335 # Then it must be protected based on static groups (regular)
2336 $noticeMsg = 'protectedpagewarning';
2338 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2339 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2341 if ( $this->mTitle
->isCascadeProtected() ) {
2342 # Is this page under cascading protection from some source pages?
2343 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2344 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2345 $cascadeSourcesCount = count( $cascadeSources );
2346 if ( $cascadeSourcesCount > 0 ) {
2347 # Explain, and list the titles responsible
2348 foreach ( $cascadeSources as $page ) {
2349 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2352 $notice .= '</div>';
2353 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2355 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2356 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2358 'showIfEmpty' => false,
2359 'msgKey' => array( 'titleprotectedwarning' ),
2360 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2363 if ( $this->kblength
=== false ) {
2364 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2367 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2368 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2369 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2371 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2372 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2373 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2377 # Add header copyright warning
2378 $this->showHeaderCopyrightWarning();
2383 * Standard summary input and label (wgSummary), abstracted so EditPage
2384 * subclasses may reorganize the form.
2385 * Note that you do not need to worry about the label's for=, it will be
2386 * inferred by the id given to the input. You can remove them both by
2387 * passing array( 'id' => false ) to $userInputAttrs.
2389 * @param $summary string The value of the summary input
2390 * @param $labelText string The html to place inside the label
2391 * @param $inputAttrs array of attrs to use on the input
2392 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2394 * @return array An array in the format array( $label, $input )
2396 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2397 // Note: the maxlength is overriden in JS to 255 and to make it use UTF-8 bytes, not characters.
2398 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2399 'id' => 'wpSummary',
2400 'maxlength' => '200',
2403 'spellcheck' => 'true',
2404 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2406 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2407 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2408 'id' => "wpSummaryLabel"
2413 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2414 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2417 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2419 return array( $label, $input );
2423 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2424 * up top, or false if this is the comment summary
2425 * down below the textarea
2426 * @param $summary String: The text of the summary to display
2429 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2430 global $wgOut, $wgContLang;
2431 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2432 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2433 if ( $isSubjectPreview ) {
2434 if ( $this->nosummary
) {
2438 if ( !$this->mShowSummaryField
) {
2442 $summary = $wgContLang->recodeForEdit( $summary );
2443 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2444 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2445 $wgOut->addHTML( "{$label} {$input}" );
2449 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2450 * up top, or false if this is the comment summary
2451 * down below the textarea
2452 * @param $summary String: the text of the summary to display
2455 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2456 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2462 if ( $isSubjectPreview ) {
2463 $summary = wfMessage( 'newsectionsummary', $wgParser->stripSectionName( $summary ) )
2464 ->inContentLanguage()->text();
2467 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2469 $summary = wfMessage( $message )->parse() . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2470 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2473 protected function showFormBeforeText() {
2475 $section = htmlspecialchars( $this->section
);
2476 $wgOut->addHTML( <<<HTML
2477 <input type='hidden' value="{$section}" name="wpSection" />
2478 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2479 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2480 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2484 if ( !$this->checkUnicodeCompliantBrowser() ) {
2485 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2489 protected function showFormAfterText() {
2490 global $wgOut, $wgUser;
2492 * To make it harder for someone to slip a user a page
2493 * which submits an edit form to the wiki without their
2494 * knowledge, a random token is associated with the login
2495 * session. If it's not passed back with the submission,
2496 * we won't save the page, or render user JavaScript and
2499 * For anon editors, who may not have a session, we just
2500 * include the constant suffix to prevent editing from
2501 * broken text-mangling proxies.
2503 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2507 * Subpage overridable method for printing the form for page content editing
2508 * By default this simply outputs wpTextbox1
2509 * Subclasses can override this to provide a custom UI for editing;
2510 * be it a form, or simply wpTextbox1 with a modified content that will be
2511 * reverse modified when extracted from the post data.
2512 * Note that this is basically the inverse for importContentFormData
2514 protected function showContentForm() {
2515 $this->showTextbox1();
2519 * Method to output wpTextbox1
2520 * The $textoverride method can be used by subclasses overriding showContentForm
2521 * to pass back to this method.
2523 * @param $customAttribs array of html attributes to use in the textarea
2524 * @param $textoverride String: optional text to override $this->textarea1 with
2526 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2527 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2528 $attribs = array( 'style' => 'display:none;' );
2530 $classes = array(); // Textarea CSS
2531 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2532 # Is the title semi-protected?
2533 if ( $this->mTitle
->isSemiProtected() ) {
2534 $classes[] = 'mw-textarea-sprotected';
2536 # Then it must be protected based on static groups (regular)
2537 $classes[] = 'mw-textarea-protected';
2539 # Is the title cascade-protected?
2540 if ( $this->mTitle
->isCascadeProtected() ) {
2541 $classes[] = 'mw-textarea-cprotected';
2545 $attribs = array( 'tabindex' => 1 );
2547 if ( is_array( $customAttribs ) ) {
2548 $attribs +
= $customAttribs;
2551 if ( count( $classes ) ) {
2552 if ( isset( $attribs['class'] ) ) {
2553 $classes[] = $attribs['class'];
2555 $attribs['class'] = implode( ' ', $classes );
2559 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2562 protected function showTextbox2() {
2563 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2566 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2567 global $wgOut, $wgUser;
2569 $wikitext = $this->safeUnicodeOutput( $text );
2570 if ( strval( $wikitext ) !== '' ) {
2571 // Ensure there's a newline at the end, otherwise adding lines
2573 // But don't add a newline if the ext is empty, or Firefox in XHTML
2574 // mode will show an extra newline. A bit annoying.
2578 $attribs = $customAttribs +
array(
2581 'cols' => $wgUser->getIntOption( 'cols' ),
2582 'rows' => $wgUser->getIntOption( 'rows' ),
2583 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2586 $pageLang = $this->mTitle
->getPageLanguage();
2587 $attribs['lang'] = $pageLang->getCode();
2588 $attribs['dir'] = $pageLang->getDir();
2590 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2593 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2597 $classes[] = 'ontop';
2600 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2602 if ( $this->formtype
!= 'preview' ) {
2603 $attribs['style'] = 'display: none;';
2606 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2608 if ( $this->formtype
== 'preview' ) {
2609 $this->showPreview( $previewOutput );
2612 $wgOut->addHTML( '</div>' );
2614 if ( $this->formtype
== 'diff' ) {
2617 } catch ( MWContentSerializationException
$ex ) {
2618 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2619 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2625 * Append preview output to $wgOut.
2626 * Includes category rendering if this is a category page.
2628 * @param $text String: the HTML to be output for the preview.
2630 protected function showPreview( $text ) {
2632 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2633 $this->mArticle
->openShowCategory();
2635 # This hook seems slightly odd here, but makes things more
2636 # consistent for extensions.
2637 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2638 $wgOut->addHTML( $text );
2639 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2640 $this->mArticle
->closeShowCategory();
2645 * Get a diff between the current contents of the edit box and the
2646 * version of the page we're editing from.
2648 * If this is a section edit, we'll replace the section as for final
2649 * save and then make a comparison.
2651 function showDiff() {
2652 global $wgUser, $wgContLang, $wgOut;
2654 $oldtitlemsg = 'currentrev';
2655 # if message does not exist, show diff against the preloaded default
2656 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2657 $oldtext = $this->mTitle
->getDefaultMessageText();
2658 if( $oldtext !== false ) {
2659 $oldtitlemsg = 'defaultmessagetext';
2660 $oldContent = $this->toEditContent( $oldtext );
2665 $oldContent = $this->getCurrentContent();
2668 $textboxContent = $this->toEditContent( $this->textbox1
);
2670 $newContent = $this->mArticle
->replaceSectionContent(
2671 $this->section
, $textboxContent,
2672 $this->summary
, $this->edittime
);
2674 if ( $newContent ) {
2675 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2676 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2678 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2679 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2682 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2683 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2684 $newtitle = wfMessage( 'yourtext' )->parse();
2686 if ( !$oldContent ) {
2687 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
2690 if ( !$newContent ) {
2691 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
2694 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
2695 $de->setContent( $oldContent, $newContent );
2697 $difftext = $de->getDiff( $oldtitle, $newtitle );
2698 $de->showDiffStyle();
2703 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2707 * Show the header copyright warning.
2709 protected function showHeaderCopyrightWarning() {
2710 $msg = 'editpage-head-copy-warn';
2711 if ( !wfMessage( $msg )->isDisabled() ) {
2713 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2714 'editpage-head-copy-warn' );
2719 * Give a chance for site and per-namespace customizations of
2720 * terms of service summary link that might exist separately
2721 * from the copyright notice.
2723 * This will display between the save button and the edit tools,
2724 * so should remain short!
2726 protected function showTosSummary() {
2727 $msg = 'editpage-tos-summary';
2728 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2729 if ( !wfMessage( $msg )->isDisabled() ) {
2731 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2732 $wgOut->addWikiMsg( $msg );
2733 $wgOut->addHTML( '</div>' );
2737 protected function showEditTools() {
2739 $wgOut->addHTML( '<div class="mw-editTools">' .
2740 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2745 * Get the copyright warning
2747 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2749 protected function getCopywarn() {
2750 return self
::getCopyrightWarning( $this->mTitle
);
2753 public static function getCopyrightWarning( $title ) {
2754 global $wgRightsText;
2755 if ( $wgRightsText ) {
2756 $copywarnMsg = array( 'copyrightwarning',
2757 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2760 $copywarnMsg = array( 'copyrightwarning2',
2761 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2763 // Allow for site and per-namespace customization of contribution/copyright notice.
2764 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2766 return "<div id=\"editpage-copywarn\">\n" .
2767 call_user_func_array( 'wfMessage', $copywarnMsg )->plain() . "\n</div>";
2770 protected function showStandardInputs( &$tabindex = 2 ) {
2772 $wgOut->addHTML( "<div class='editOptions'>\n" );
2774 if ( $this->section
!= 'new' ) {
2775 $this->showSummaryInput( false, $this->summary
);
2776 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2779 $checkboxes = $this->getCheckboxes( $tabindex,
2780 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2781 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2783 // Show copyright warning.
2784 $wgOut->addWikiText( $this->getCopywarn() );
2785 $wgOut->addHTML( $this->editFormTextAfterWarn
);
2787 $wgOut->addHTML( "<div class='editButtons'>\n" );
2788 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2790 $cancel = $this->getCancelLink();
2791 if ( $cancel !== '' ) {
2792 $cancel .= wfMessage( 'pipe-separator' )->text();
2794 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
2795 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2796 wfMessage( 'edithelp' )->escaped() . '</a> ' .
2797 wfMessage( 'newwindow' )->parse();
2798 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
2799 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
2800 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
2801 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
2802 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
2806 * Show an edit conflict. textbox1 is already shown in showEditForm().
2807 * If you want to use another entry point to this function, be careful.
2809 protected function showConflict() {
2812 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2813 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2815 $content1 = $this->toEditContent( $this->textbox1
);
2816 $content2 = $this->toEditContent( $this->textbox2
);
2818 $handler = ContentHandler
::getForModelID( $this->contentModel
);
2819 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
2820 $de->setContent( $content2, $content1 );
2822 wfMessage( 'yourtext' )->parse(),
2823 wfMessage( 'storedversion' )->text()
2826 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2827 $this->showTextbox2();
2834 public function getCancelLink() {
2835 $cancelParams = array();
2836 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2837 $cancelParams['oldid'] = $this->oldid
;
2840 return Linker
::linkKnown(
2841 $this->getContextTitle(),
2842 wfMessage( 'cancel' )->parse(),
2843 array( 'id' => 'mw-editform-cancel' ),
2849 * Returns the URL to use in the form's action attribute.
2850 * This is used by EditPage subclasses when simply customizing the action
2851 * variable in the constructor is not enough. This can be used when the
2852 * EditPage lives inside of a Special page rather than a custom page action.
2854 * @param $title Title object for which is being edited (where we go to for &action= links)
2857 protected function getActionURL( Title
$title ) {
2858 return $title->getLocalURL( array( 'action' => $this->action
) );
2862 * Check if a page was deleted while the user was editing it, before submit.
2863 * Note that we rely on the logging table, which hasn't been always there,
2864 * but that doesn't matter, because this only applies to brand new
2867 protected function wasDeletedSinceLastEdit() {
2868 if ( $this->deletedSinceEdit
!== null ) {
2869 return $this->deletedSinceEdit
;
2872 $this->deletedSinceEdit
= false;
2874 if ( $this->mTitle
->isDeletedQuick() ) {
2875 $this->lastDelete
= $this->getLastDelete();
2876 if ( $this->lastDelete
) {
2877 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2878 if ( $deleteTime > $this->starttime
) {
2879 $this->deletedSinceEdit
= true;
2884 return $this->deletedSinceEdit
;
2887 protected function getLastDelete() {
2888 $dbr = wfGetDB( DB_SLAVE
);
2889 $data = $dbr->selectRow(
2890 array( 'logging', 'user' ),
2903 'log_namespace' => $this->mTitle
->getNamespace(),
2904 'log_title' => $this->mTitle
->getDBkey(),
2905 'log_type' => 'delete',
2906 'log_action' => 'delete',
2910 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2912 // Quick paranoid permission checks...
2913 if ( is_object( $data ) ) {
2914 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
2915 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
2918 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
2919 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
2926 * Get the rendered text for previewing.
2927 * @throws MWException
2930 function getPreviewText() {
2931 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
2933 wfProfileIn( __METHOD__
);
2935 if ( $wgRawHtml && !$this->mTokenOk
) {
2936 // Could be an offsite preview attempt. This is very unsafe if
2937 // HTML is enabled, as it could be an attack.
2939 if ( $this->textbox1
!== '' ) {
2940 // Do not put big scary notice, if previewing the empty
2941 // string, which happens when you initially edit
2942 // a category page, due to automatic preview-on-open.
2943 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2944 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
2946 wfProfileOut( __METHOD__
);
2953 $content = $this->toEditContent( $this->textbox1
);
2956 if ( !wfRunHooks( 'AlternateEditPreview', array( $this, &$content, &$previewHTML, &$this->mParserOutput
) ) ) {
2957 wfProfileOut( __METHOD__
);
2958 return $previewHTML;
2961 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2962 if ( $this->mTokenOkExceptSuffix
) {
2963 $note = wfMessage( 'token_suffix_mismatch' )->plain() ;
2966 $note = wfMessage( 'session_fail_preview' )->plain() ;
2968 } elseif ( $this->incompleteForm
) {
2969 $note = wfMessage( 'edit_form_incomplete' )->plain() ;
2971 $note = wfMessage( 'previewnote' )->plain() .
2972 ' [[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' . wfMessage( 'continue-editing' )->text() . ']]';
2975 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
2976 $parserOptions->setEditSection( false );
2977 $parserOptions->setIsPreview( true );
2978 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
2980 # don't parse non-wikitext pages, show message about preview
2981 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
2982 if( $this->mTitle
->isCssJsSubpage() ) {
2984 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2990 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
2992 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
2998 # Used messages to make sure grep find them:
2999 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3000 if( $level && $format ) {
3001 $note = "<div id='mw-{$level}{$format}preview'>" . wfMessage( "{$level}{$format}preview" )->text() . "</div>";
3005 $rt = $content->getRedirectChain();
3007 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
3010 # If we're adding a comment, we need to show the
3011 # summary as the headline
3012 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3013 $content = $content->addSectionHeader( $this->summary
);
3016 $hook_args = array( $this, &$content );
3017 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3018 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3020 $parserOptions->enableLimitReport();
3022 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3023 # But it's now deprecated, so never mind
3025 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3026 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
3028 $previewHTML = $parserOutput->getText();
3029 $this->mParserOutput
= $parserOutput;
3030 $wgOut->addParserOutputNoText( $parserOutput );
3032 if ( count( $parserOutput->getWarnings() ) ) {
3033 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3036 } catch ( MWContentSerializationException
$ex ) {
3037 $m = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
3038 $note .= "\n\n" . $m->parse();
3042 if ( $this->isConflict
) {
3043 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3045 $conflict = '<hr />';
3048 $previewhead = "<div class='previewnote'>\n" .
3049 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3050 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3052 $pageLang = $this->mTitle
->getPageLanguage();
3053 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
3054 'class' => 'mw-content-' . $pageLang->getDir() );
3055 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3057 wfProfileOut( __METHOD__
);
3058 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3064 function getTemplates() {
3065 if ( $this->preview ||
$this->section
!= '' ) {
3066 $templates = array();
3067 if ( !isset( $this->mParserOutput
) ) {
3070 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3071 foreach ( array_keys( $template ) as $dbk ) {
3072 $templates[] = Title
::makeTitle( $ns, $dbk );
3077 return $this->mTitle
->getTemplateLinksFrom();
3082 * Shows a bulletin board style toolbar for common editing functions.
3083 * It can be disabled in the user preferences.
3084 * The necessary JavaScript code can be found in skins/common/edit.js.
3088 static function getEditToolbar() {
3089 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3090 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
3092 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3095 * $toolarray is an array of arrays each of which includes the
3096 * filename of the button image (without path), the opening
3097 * tag, the closing tag, optionally a sample text that is
3098 * inserted between the two when no selection is highlighted
3099 * and. The tip text is shown when the user moves the mouse
3102 * Also here: accesskeys (key), which are not used yet until
3103 * someone can figure out a way to make them work in
3104 * IE. However, we should make sure these keys are not defined
3109 'image' => $wgLang->getImageFile( 'button-bold' ),
3110 'id' => 'mw-editbutton-bold',
3112 'close' => '\'\'\'',
3113 'sample' => wfMessage( 'bold_sample' )->text(),
3114 'tip' => wfMessage( 'bold_tip' )->text(),
3118 'image' => $wgLang->getImageFile( 'button-italic' ),
3119 'id' => 'mw-editbutton-italic',
3122 'sample' => wfMessage( 'italic_sample' )->text(),
3123 'tip' => wfMessage( 'italic_tip' )->text(),
3127 'image' => $wgLang->getImageFile( 'button-link' ),
3128 'id' => 'mw-editbutton-link',
3131 'sample' => wfMessage( 'link_sample' )->text(),
3132 'tip' => wfMessage( 'link_tip' )->text(),
3136 'image' => $wgLang->getImageFile( 'button-extlink' ),
3137 'id' => 'mw-editbutton-extlink',
3140 'sample' => wfMessage( 'extlink_sample' )->text(),
3141 'tip' => wfMessage( 'extlink_tip' )->text(),
3145 'image' => $wgLang->getImageFile( 'button-headline' ),
3146 'id' => 'mw-editbutton-headline',
3149 'sample' => wfMessage( 'headline_sample' )->text(),
3150 'tip' => wfMessage( 'headline_tip' )->text(),
3153 $imagesAvailable ?
array(
3154 'image' => $wgLang->getImageFile( 'button-image' ),
3155 'id' => 'mw-editbutton-image',
3156 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3158 'sample' => wfMessage( 'image_sample' )->text(),
3159 'tip' => wfMessage( 'image_tip' )->text(),
3162 $imagesAvailable ?
array(
3163 'image' => $wgLang->getImageFile( 'button-media' ),
3164 'id' => 'mw-editbutton-media',
3165 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3167 'sample' => wfMessage( 'media_sample' )->text(),
3168 'tip' => wfMessage( 'media_tip' )->text(),
3172 'image' => $wgLang->getImageFile( 'button-math' ),
3173 'id' => 'mw-editbutton-math',
3175 'close' => "</math>",
3176 'sample' => wfMessage( 'math_sample' )->text(),
3177 'tip' => wfMessage( 'math_tip' )->text(),
3181 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3182 'id' => 'mw-editbutton-nowiki',
3183 'open' => "<nowiki>",
3184 'close' => "</nowiki>",
3185 'sample' => wfMessage( 'nowiki_sample' )->text(),
3186 'tip' => wfMessage( 'nowiki_tip' )->text(),
3190 'image' => $wgLang->getImageFile( 'button-sig' ),
3191 'id' => 'mw-editbutton-signature',
3195 'tip' => wfMessage( 'sig_tip' )->text(),
3199 'image' => $wgLang->getImageFile( 'button-hr' ),
3200 'id' => 'mw-editbutton-hr',
3201 'open' => "\n----\n",
3204 'tip' => wfMessage( 'hr_tip' )->text(),
3209 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3210 foreach ( $toolarray as $tool ) {
3216 $image = $wgStylePath . '/common/images/' . $tool['image'],
3217 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3218 // Older browsers show a "speedtip" type message only for ALT.
3219 // Ideally these should be different, realistically they
3220 // probably don't need to be.
3221 $tip = $tool['tip'],
3222 $open = $tool['open'],
3223 $close = $tool['close'],
3224 $sample = $tool['sample'],
3225 $cssId = $tool['id'],
3228 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3231 // This used to be called on DOMReady from mediawiki.action.edit, which
3232 // ended up causing race conditions with the setup code above.
3234 "// Create button bar\n" .
3235 "$(function() { mw.toolbar.init(); } );\n";
3238 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3240 $toolbar = '<div id="toolbar"></div>';
3242 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3248 * Returns an array of html code of the following checkboxes:
3251 * @param $tabindex int Current tabindex
3252 * @param $checked Array of checkbox => bool, where bool indicates the checked
3253 * status of the checkbox
3257 public function getCheckboxes( &$tabindex, $checked ) {
3260 $checkboxes = array();
3262 // don't show the minor edit checkbox if it's a new page or section
3263 if ( !$this->isNew
) {
3264 $checkboxes['minor'] = '';
3265 $minorLabel = wfMessage( 'minoredit' )->parse();
3266 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3268 'tabindex' => ++
$tabindex,
3269 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3270 'id' => 'wpMinoredit',
3272 $checkboxes['minor'] =
3273 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3274 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3275 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3276 ">{$minorLabel}</label>";
3280 $watchLabel = wfMessage( 'watchthis' )->parse();
3281 $checkboxes['watch'] = '';
3282 if ( $wgUser->isLoggedIn() ) {
3284 'tabindex' => ++
$tabindex,
3285 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3286 'id' => 'wpWatchthis',
3288 $checkboxes['watch'] =
3289 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3290 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3291 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3292 ">{$watchLabel}</label>";
3294 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3299 * Returns an array of html code of the following buttons:
3300 * save, diff, preview and live
3302 * @param $tabindex int Current tabindex
3306 public function getEditButtons( &$tabindex ) {
3313 'tabindex' => ++
$tabindex,
3314 'value' => wfMessage( 'savearticle' )->text(),
3315 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3316 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3318 $buttons['save'] = Xml
::element( 'input', $temp, '' );
3320 ++
$tabindex; // use the same for preview and live preview
3322 'id' => 'wpPreview',
3323 'name' => 'wpPreview',
3325 'tabindex' => $tabindex,
3326 'value' => wfMessage( 'showpreview' )->text(),
3327 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3328 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3330 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3331 $buttons['live'] = '';
3337 'tabindex' => ++
$tabindex,
3338 'value' => wfMessage( 'showdiff' )->text(),
3339 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3340 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3342 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3344 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3349 * Output preview text only. This can be sucked into the edit page
3350 * via JavaScript, and saves the server time rendering the skin as
3351 * well as theoretically being more robust on the client (doesn't
3352 * disturb the edit box's undo history, won't eat your text on
3355 * @todo This doesn't include category or interlanguage links.
3356 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3357 * or something...</s>" that might also require more skin
3358 * initialization, so check whether that's a problem.
3360 function livePreview() {
3363 header( 'Content-type: text/xml; charset=utf-8' );
3364 header( 'Cache-control: no-cache' );
3366 $previewText = $this->getPreviewText();
3367 #$categories = $skin->getCategoryLinks();
3370 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3371 Xml
::tags( 'livepreview', null,
3372 Xml
::element( 'preview', null, $previewText )
3373 #. Xml::element( 'category', null, $categories )
3379 * Call the stock "user is blocked" page
3381 * @deprecated in 1.19; throw an exception directly instead
3383 function blockedPage() {
3384 wfDeprecated( __METHOD__
, '1.19' );
3387 throw new UserBlockedError( $wgUser->getBlock() );
3391 * Produce the stock "please login to edit pages" page
3393 * @deprecated in 1.19; throw an exception directly instead
3395 function userNotLoggedInPage() {
3396 wfDeprecated( __METHOD__
, '1.19' );
3397 throw new PermissionsError( 'edit' );
3401 * Show an error page saying to the user that he has insufficient permissions
3402 * to create a new page
3404 * @deprecated in 1.19; throw an exception directly instead
3406 function noCreatePermission() {
3407 wfDeprecated( __METHOD__
, '1.19' );
3408 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3409 throw new PermissionsError( $permission );
3413 * Creates a basic error page which informs the user that
3414 * they have attempted to edit a nonexistent section.
3416 function noSuchSectionPage() {
3419 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3421 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3422 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3423 $wgOut->addHTML( $res );
3425 $wgOut->returnToMain( false, $this->mTitle
);
3429 * Produce the stock "your edit contains spam" page
3431 * @param $match string|bool Text which triggered one or more filters
3432 * @deprecated since 1.17 Use method spamPageWithContent() instead
3434 static function spamPage( $match = false ) {
3435 wfDeprecated( __METHOD__
, '1.17' );
3437 global $wgOut, $wgTitle;
3439 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3441 $wgOut->addHTML( '<div id="spamprotected">' );
3442 $wgOut->addWikiMsg( 'spamprotectiontext' );
3444 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3446 $wgOut->addHTML( '</div>' );
3448 $wgOut->returnToMain( false, $wgTitle );
3452 * Show "your edit contains spam" page with your diff and text
3454 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3456 public function spamPageWithContent( $match = false ) {
3457 global $wgOut, $wgLang;
3458 $this->textbox2
= $this->textbox1
;
3460 if( is_array( $match ) ) {
3461 $match = $wgLang->listToText( $match );
3463 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3465 $wgOut->addHTML( '<div id="spamprotected">' );
3466 $wgOut->addWikiMsg( 'spamprotectiontext' );
3468 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3470 $wgOut->addHTML( '</div>' );
3472 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3475 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3476 $this->showTextbox2();
3478 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3482 * Format an anchor fragment as it would appear for a given section name
3483 * @param $text String
3487 function sectionAnchor( $text ) {
3489 return $wgParser->guessSectionNameFromWikiText( $text );
3493 * Check if the browser is on a blacklist of user-agents known to
3494 * mangle UTF-8 data on form submission. Returns true if Unicode
3495 * should make it through, false if it's known to be a problem.
3499 function checkUnicodeCompliantBrowser() {
3500 global $wgBrowserBlackList, $wgRequest;
3502 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3503 if ( $currentbrowser === false ) {
3504 // No User-Agent header sent? Trust it by default...
3508 foreach ( $wgBrowserBlackList as $browser ) {
3509 if ( preg_match( $browser, $currentbrowser ) ) {
3517 * Filter an input field through a Unicode de-armoring process if it
3518 * came from an old browser with known broken Unicode editing issues.
3520 * @param $request WebRequest
3521 * @param $field String
3525 function safeUnicodeInput( $request, $field ) {
3526 $text = rtrim( $request->getText( $field ) );
3527 return $request->getBool( 'safemode' )
3528 ?
$this->unmakesafe( $text )
3533 * @param $request WebRequest
3534 * @param $text string
3537 function safeUnicodeText( $request, $text ) {
3538 $text = rtrim( $text );
3539 return $request->getBool( 'safemode' )
3540 ?
$this->unmakesafe( $text )
3545 * Filter an output field through a Unicode armoring process if it is
3546 * going to an old browser with known broken Unicode editing issues.
3548 * @param $text String
3552 function safeUnicodeOutput( $text ) {
3554 $codedText = $wgContLang->recodeForEdit( $text );
3555 return $this->checkUnicodeCompliantBrowser()
3557 : $this->makesafe( $codedText );
3561 * A number of web browsers are known to corrupt non-ASCII characters
3562 * in a UTF-8 text editing environment. To protect against this,
3563 * detected browsers will be served an armored version of the text,
3564 * with non-ASCII chars converted to numeric HTML character references.
3566 * Preexisting such character references will have a 0 added to them
3567 * to ensure that round-trips do not alter the original data.
3569 * @param $invalue String
3573 function makesafe( $invalue ) {
3574 // Armor existing references for reversability.
3575 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3580 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3581 $bytevalue = ord( $invalue[$i] );
3582 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3583 $result .= chr( $bytevalue );
3585 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3586 $working = $working << 6;
3587 $working +
= ( $bytevalue & 0x3F );
3589 if ( $bytesleft <= 0 ) {
3590 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3592 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3593 $working = $bytevalue & 0x1F;
3595 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3596 $working = $bytevalue & 0x0F;
3598 } else { // 1111 0xxx
3599 $working = $bytevalue & 0x07;
3607 * Reverse the previously applied transliteration of non-ASCII characters
3608 * back to UTF-8. Used to protect data from corruption by broken web browsers
3609 * as listed in $wgBrowserBlackList.
3611 * @param $invalue String
3615 function unmakesafe( $invalue ) {
3617 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3618 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3622 $hexstring .= $invalue[$i];
3624 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3626 // Do some sanity checks. These aren't needed for reversability,
3627 // but should help keep the breakage down if the editor
3628 // breaks one of the entities whilst editing.
3629 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3630 $codepoint = hexdec( $hexstring );
3631 $result .= codepointToUtf8( $codepoint );
3633 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3636 $result .= substr( $invalue, $i, 1 );
3639 // reverse the transform that we made for reversability reasons.
3640 return strtr( $result, array( "�" => "&#x" ) );