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 allowed to be different.
35 * Surgeon General's Warning: prolonged exposure to this class is known to cause
36 * headaches, which may be fatal.
40 * Status: Article successfully updated
42 const AS_SUCCESS_UPDATE
= 200;
45 * Status: Article successfully created
47 const AS_SUCCESS_NEW_ARTICLE
= 201;
50 * Status: Article update aborted by a hook function
52 const AS_HOOK_ERROR
= 210;
55 * Status: A hook function returned an error
57 const AS_HOOK_ERROR_EXPECTED
= 212;
60 * Status: User is blocked from editting this page
62 const AS_BLOCKED_PAGE_FOR_USER
= 215;
65 * Status: Content too big (> $wgMaxArticleSize)
67 const AS_CONTENT_TOO_BIG
= 216;
70 * Status: User cannot edit? (not used)
72 const AS_USER_CANNOT_EDIT
= 217;
75 * Status: this anonymous user is not allowed to edit this page
77 const AS_READ_ONLY_PAGE_ANON
= 218;
80 * Status: this logged in user is not allowed to edit this page
82 const AS_READ_ONLY_PAGE_LOGGED
= 219;
85 * Status: wiki is in readonly mode (wfReadOnly() == true)
87 const AS_READ_ONLY_PAGE
= 220;
90 * Status: rate limiter for action 'edit' was tripped
92 const AS_RATE_LIMITED
= 221;
95 * Status: article was deleted while editting and param wpRecreate == false or form
98 const AS_ARTICLE_WAS_DELETED
= 222;
101 * Status: user tried to create this page, but is not allowed to do that
102 * ( Title->usercan('create') == false )
104 const AS_NO_CREATE_PERMISSION
= 223;
107 * Status: user tried to create a blank page
109 const AS_BLANK_ARTICLE
= 224;
112 * Status: (non-resolvable) edit conflict
114 const AS_CONFLICT_DETECTED
= 225;
117 * Status: no edit summary given and the user has forceeditsummary set and the user is not
118 * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
120 const AS_SUMMARY_NEEDED
= 226;
123 * Status: user tried to create a new section without content
125 const AS_TEXTBOX_EMPTY
= 228;
128 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
130 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
138 * Status: WikiPage::doEdit() was unsuccessfull
143 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
145 const AS_SPAM_ERROR
= 232;
148 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
150 const AS_IMAGE_REDIRECT_ANON
= 233;
153 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
155 const AS_IMAGE_REDIRECT_LOGGED
= 234;
158 * Status: can't parse content
160 const AS_PARSE_ERROR
= 240;
163 * HTML id and name for the beginning of the edit form.
165 const EDITFORM_ID
= 'editform';
176 private $mContextTitle = null;
177 var $action = 'submit';
178 var $isConflict = false;
179 var $isCssJsSubpage = false;
180 var $isCssSubpage = false;
181 var $isJsSubpage = false;
182 var $isWrongCaseCssJsPage = false;
183 var $isNew = false; // new page or new section
184 var $deletedSinceEdit;
188 var $mTokenOk = false;
189 var $mTokenOkExceptSuffix = false;
190 var $mTriedSave = false;
191 var $incompleteForm = false;
193 var $kblength = false;
194 var $missingComment = false;
195 var $missingSummary = false;
196 var $allowBlankSummary = false;
199 #var $mPreviewTemplates;
207 * Has a summary been preset using GET parameter &summary= ?
210 var $hasPresetSummary = false;
212 var $mBaseRevision = false;
213 var $mShowSummaryField = true;
216 var $save = false, $preview = false, $diff = false;
217 var $minoredit = false, $watchthis = false, $recreate = false;
218 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
219 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
220 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
221 var $contentModel = null, $contentFormat = null;
223 # Placeholders for text injection by hooks (must be HTML)
224 # extensions should take care to _append_ to the present value
225 public $editFormPageTop = ''; // Before even the preview
226 public $editFormTextTop = '';
227 public $editFormTextBeforeContent = '';
228 public $editFormTextAfterWarn = '';
229 public $editFormTextAfterTools = '';
230 public $editFormTextBottom = '';
231 public $editFormTextAfterContent = '';
232 public $previewTextAfterContent = '';
233 public $mPreloadContent = null;
235 /* $didSave should be set to true whenever an article was succesfully altered. */
236 public $didSave = false;
237 public $undidRev = 0;
239 public $suppressIntro = false;
242 * Set to true to allow editing of non-text content types.
246 public $allowNonTextContent = false;
249 * @param $article Article
251 public function __construct( Article
$article ) {
252 $this->mArticle
= $article;
253 $this->mTitle
= $article->getTitle();
255 $this->contentModel
= $this->getTitle()->getContentModel();
257 $handler = ContentHandler
::getForModelID( $this->contentModel
);
258 $this->contentFormat
= $handler->getDefaultFormat();
264 public function getArticle() {
265 return $this->mArticle
;
272 public function getTitle() {
273 return $this->mTitle
;
277 * Set the context Title object
279 * @param $title Title object or null
281 public function setContextTitle( $title ) {
282 $this->mContextTitle
= $title;
286 * Get the context title object.
287 * If not set, $wgTitle will be returned. This behavior might change in
288 * the future to return $this->mTitle instead.
290 * @return Title object
292 public function getContextTitle() {
293 if ( is_null( $this->mContextTitle
) ) {
297 return $this->mContextTitle
;
306 * This is the function that gets called for "action=edit". It
307 * sets up various member variables, then passes execution to
308 * another function, usually showEditForm()
310 * The edit form is self-submitting, so that when things like
311 * preview and edit conflicts occur, we get the same form back
312 * with the extra stuff added. Only when the final submission
313 * is made and all is well do we actually save and redirect to
314 * the newly-edited page.
317 // Allow extensions to modify/prevent this form or submission
318 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
322 wfProfileIn( __METHOD__
);
323 wfDebug( __METHOD__
. ": enter\n" );
325 $context = $this->getArticle()->getContext();
326 $title = $this->getTitle();
328 // If they used redlink=1 and the page exists, redirect to the main article
329 $request = $context->getRequest();
330 if ( $request->getBool( 'redlink' ) && $title->exists() ) {
331 $context->getOutput()->redirect( $title->getFullURL() );
332 wfProfileOut( __METHOD__
);
336 $this->importFormData( $request );
337 $this->firsttime
= false;
340 $this->livePreview();
341 wfProfileOut( __METHOD__
);
345 if ( wfReadOnly() && $this->save
) {
348 $this->preview
= true;
352 $this->formtype
= 'save';
353 } elseif ( $this->preview
) {
354 $this->formtype
= 'preview';
355 } elseif ( $this->diff
) {
356 $this->formtype
= 'diff';
357 } else { # First time through
358 $this->firsttime
= true;
359 if ( $this->previewOnOpen() ) {
360 $this->formtype
= 'preview';
362 $this->formtype
= 'initial';
366 $permErrors = $this->getEditPermissionErrors();
368 wfDebug( __METHOD__
. ": User can't edit\n" );
369 // Auto-block user's IP if the account was "hard" blocked
370 $context->getUser()->spreadAnyEditBlock();
372 $this->displayPermissionsError( $permErrors );
374 wfProfileOut( __METHOD__
);
378 wfProfileIn( __METHOD__
. "-business-end" );
380 $this->isConflict
= false;
381 // css / js subpages of user pages get a special treatment
382 $this->isCssJsSubpage
= $title->isCssJsSubpage();
383 $this->isCssSubpage
= $title->isCssSubpage();
384 $this->isJsSubpage
= $title->isJsSubpage();
385 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
387 # Show applicable editing introductions
388 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
392 # Attempt submission here. This will check for edit conflicts,
393 # and redundantly check for locked database, blocked IPs, etc.
394 # that edit() already checked just in case someone tries to sneak
395 # in the back door with a hand-edited submission URL.
397 if ( 'save' == $this->formtype
) {
398 if ( !$this->attemptSave() ) {
399 wfProfileOut( __METHOD__
. "-business-end" );
400 wfProfileOut( __METHOD__
);
405 # First time through: get contents, set time for conflict
407 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
408 if ( $this->initialiseForm() === false ) {
409 $this->noSuchSectionPage();
410 wfProfileOut( __METHOD__
. "-business-end" );
411 wfProfileOut( __METHOD__
);
415 if ( !$title->getArticleID() ){
416 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
418 wfRunHooks( 'EditFormInitialText', array( $this ) );
422 $this->showEditForm();
423 wfProfileOut( __METHOD__
. "-business-end" );
424 wfProfileOut( __METHOD__
);
430 protected function getEditPermissionErrors() {
431 $user = $this->getArticle()->getContext()->getUser();
433 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'edit', $user );
434 # Can this title be created?
435 if ( !$this->getTitle()->exists() ) {
436 $permErrors = array_merge( $permErrors,
437 wfArrayDiff2( $this->getTitle()->getUserPermissionsErrors( 'create', $user ), $permErrors ) );
439 # Ignore some permissions errors when a user is just previewing/viewing diffs
441 foreach ( $permErrors as $error ) {
442 if ( ( $this->preview ||
$this->diff
) &&
443 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
448 $permErrors = wfArrayDiff2( $permErrors, $remove );
453 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
454 * but with the following differences:
455 * - If redlink=1, the user will be redirected to the page
456 * - If there is content to display or the error occurs while either saving,
457 * previewing or showing the difference, it will be a
458 * "View source for ..." page displaying the source code after the error message.
461 * @param $permErrors Array of permissions errors, as returned by
462 * Title::getUserPermissionsErrors().
463 * @throws PermissionsError
465 protected function displayPermissionsError( array $permErrors ) {
466 $context = $this->getArticle()->getContext();
467 $out = $context->getOutput();
469 if ( $context->getRequest()->getBool( 'redlink' ) ) {
470 // The edit page was reached via a red link.
471 // Redirect to the article page and let them click the edit tab if
472 // they really want a permission error.
473 $out->redirect( $this->getTitle()->getFullUrl() );
477 $content = $this->getContentObject();
479 # Use the normal message if there's nothing to display
480 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
481 $action = $this->getTitle()->exists() ?
'edit' :
482 ( $this->getTitle()->isTalkPage() ?
'createtalk' : 'createpage' );
483 throw new PermissionsError( $action, $permErrors );
486 $out->setPageTitle( $context->msg('viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
487 $out->addBacklinkSubtitle( $this->getContextTitle() );
488 $out->addWikiText( $out->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
489 $out->addHTML( "<hr />\n" );
491 # If the user made changes, preserve them when showing the markup
492 # (This happens when a user is blocked during edit, for instance)
493 if ( !$this->firsttime
) {
494 $text = $this->textbox1
;
495 $out->addWikiMsg( 'viewyourtext' );
497 $text = $this->toEditText( $content );
498 $out->addWikiMsg( 'viewsourcetext' );
501 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
503 $out->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
504 Linker
::formatTemplates( $this->getTemplates() ) ) );
506 if ( $this->getTitle()->exists() ) {
507 $out->returnToMain( null, $this->getTitle() );
512 * Show a read-only error
513 * Parameters are the same as OutputPage:readOnlyPage()
514 * Redirect to the article page if redlink=1
515 * @deprecated in 1.19; use displayPermissionsError() instead
517 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
518 wfDeprecated( __METHOD__
, '1.19' );
520 $context = $this->getArticle()->getContext();
522 if ( $context->getRequest()->getBool( 'redlink' ) ) {
523 // The edit page was reached via a red link.
524 // Redirect to the article page and let them click the edit tab if
525 // they really want a permission error.
526 $context->getOutput()->redirect( $this->getTitle()->getFullUrl() );
528 $context->getOutput()->readOnlyPage( $source, $protected, $reasons, $action );
533 * Should we show a preview when the edit form is first shown?
537 protected function previewOnOpen() {
538 global $wgPreviewOnOpenNamespaces;
540 $context = $this->getArticle()->getContext();
541 $request = $context->getRequest();
543 if ( $request->getVal( 'preview' ) == 'yes' ) {
544 // Explicit override from request
546 } elseif ( $request->getVal( 'preview' ) == 'no' ) {
547 // Explicit override from request
549 } elseif ( $this->section
== 'new' ) {
550 // Nothing *to* preview for new sections
553 ( $request->getVal( 'preload' ) !== null ||
$this->getTitle()->exists() ) &&
554 $context->getUser()->getOption( 'previewonfirst' )
556 // Standard preference behaviour
558 } elseif ( !$this->getTitle()->exists() &&
559 isset( $wgPreviewOnOpenNamespaces[$this->getTitle()->getNamespace()] ) &&
560 $wgPreviewOnOpenNamespaces[$this->getTitle()->getNamespace()] )
562 // Categories are special
570 * Checks whether the user entered a skin name in uppercase,
571 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
575 protected function isWrongCaseCssJsPage() {
576 if ( $this->getTitle()->isCssJsSubpage() ) {
577 $name = $this->getTitle()->getSkinFromCssJsSubpage();
578 $skins = array_merge(
579 array_keys( Skin
::getSkinNames() ),
582 return !in_array( $name, $skins )
583 && in_array( strtolower( $name ), $skins );
590 * Does this EditPage class support section editing?
591 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
595 protected function isSectionEditSupported() {
600 * This function collects the form data and uses it to populate various member variables.
601 * @param $request WebRequest
603 function importFormData( &$request ) {
606 wfProfileIn( __METHOD__
);
608 # Section edit can come from either the form or a link
609 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
610 $this->isNew
= !$this->getTitle()->exists() ||
$this->section
== 'new';
612 if ( $request->wasPosted() ) {
613 # These fields need to be checked for encoding.
614 # Also remove trailing whitespace, but don't remove _initial_
615 # whitespace from the text boxes. This may be significant formatting.
616 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
617 if ( !$request->getCheck( 'wpTextbox2' ) ) {
618 // Skip this if wpTextbox2 has input, it indicates that we came
619 // from a conflict page with raw page text, not a custom form
620 // modified by subclasses
621 wfProfileIn( get_class( $this ) . "::importContentFormData" );
622 $textbox1 = $this->importContentFormData( $request );
623 if ( isset( $textbox1 ) ) {
624 $this->textbox1
= $textbox1;
627 wfProfileOut( get_class( $this ) . "::importContentFormData" );
630 # Truncate for whole multibyte characters
631 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 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 $user = $this->getArticle()->getContext()->getUser();
707 if ( ( $this->getTitle()->mNamespace
== NS_USER ||
$this->getTitle()->mNamespace
== NS_USER_TALK
) &&
708 $this->getTitle()->getText() == $user->getName() )
710 $this->allowBlankSummary
= true;
712 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$user->getOption( 'forceeditsummary' );
715 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
717 # Not a posted form? Start with nothing.
718 wfDebug( __METHOD__
. ": Not a posted form.\n" );
719 $this->textbox1
= '';
721 $this->sectiontitle
= '';
722 $this->edittime
= '';
723 $this->starttime
= wfTimestampNow();
725 $this->preview
= false;
728 $this->minoredit
= false;
729 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
730 $this->recreate
= false;
732 // When creating a new section, we can preload a section title by passing it as the
733 // preloadtitle parameter in the URL (Bug 13100)
734 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
735 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
736 // Once wpSummary isn't being use for setting section titles, we should delete this.
737 $this->summary
= $request->getVal( 'preloadtitle' );
739 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
740 $this->summary
= $request->getText( 'summary' );
741 if ( $this->summary
!== '' ) {
742 $this->hasPresetSummary
= true;
746 if ( $request->getVal( 'minor' ) ) {
747 $this->minoredit
= true;
751 $this->oldid
= $request->getInt( 'oldid' );
753 $this->bot
= $request->getBool( 'bot', true );
754 $this->nosummary
= $request->getBool( 'nosummary' );
756 $content_handler = ContentHandler
::getForTitle( $this->getTitle() );
757 $this->contentModel
= $request->getText( 'model', $content_handler->getModelID() ); #may be overridden by revision
758 $this->contentFormat
= $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
760 # @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
761 # @todo Check if the desired content model supports the given content format!
763 $this->live
= $request->getCheck( 'live' );
764 $this->editintro
= $request->getText( 'editintro',
765 // Custom edit intro for new sections
766 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
768 // Allow extensions to modify form data
769 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
771 wfProfileOut( __METHOD__
);
775 * Subpage overridable method for extracting the page content data from the
776 * posted form to be placed in $this->textbox1, if using customized input
777 * this method should be overrided and return the page text that will be used
778 * for saving, preview parsing and so on...
780 * @param $request WebRequest
782 protected function importContentFormData( &$request ) {
783 return; // Don't do anything, EditPage already extracted wpTextbox1
787 * Initialise form fields in the object
788 * Called on the first invocation, e.g. when a user clicks an edit link
789 * @return bool -- if the requested section is valid
791 function initialiseForm() {
792 $this->edittime
= $this->getArticle()->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 $user = $this->getArticle()->getContext()->getUser();
803 if ( $user->getOption( 'watchdefault' ) ) {
805 $this->watchthis
= true;
806 } elseif ( $user->getOption( 'watchcreations' ) && !$this->getTitle()->exists() ) {
808 $this->watchthis
= true;
809 } elseif ( $user->isWatched( $this->getTitle() ) ) {
811 $this->watchthis
= true;
814 if ( $user->getOption( 'minordefault' ) && !$this->isNew
) {
815 $this->minoredit
= true;
818 if ( $this->textbox1
=== false ) {
827 * Fetch initial editing page content.
829 * @param $def_text string|bool
830 * @return mixed string on success, $def_text for invalid sections
832 * @deprecated since 1.21, get WikiPage::getContent() instead.
834 function getContent( $def_text = false ) {
835 ContentHandler
::deprecated( __METHOD__
, '1.21' );
837 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
838 $def_content = $this->toEditContent( $def_text );
840 $def_content = false;
843 $content = $this->getContentObject( $def_content );
845 // Note: EditPage should only be used with text based content anyway.
846 return $this->toEditText( $content );
850 * @param Content|null $def_content The default value to return
852 * @return mixed Content on success, $def_content for invalid sections
856 protected function getContentObject( $def_content = null ) {
857 wfProfileIn( __METHOD__
);
860 $context = $this->getArticle()->getContext();
861 $request = $context->getRequest();
863 // For message page not locally set, use the i18n message.
864 // For other non-existent articles, use preload text if any.
865 if ( !$this->getTitle()->exists() ||
$this->section
== 'new' ) {
866 if ( $this->getTitle()->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
867 # If this is a system message, get the default text.
868 $msg = $this->getTitle()->getDefaultMessageText();
870 $content = $this->toEditContent( $msg );
872 if ( $content === false ) {
873 # If requested, preload some text.
874 $preload = $request->getVal( 'preload',
875 // Custom preload text for new sections
876 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : ''
879 $content = $this->getPreloadedContent( $preload );
881 // For existing pages, get text based on "undo" or section parameters.
883 if ( $this->section
!= '' ) {
884 // Get section edit text (returns $def_text for invalid sections)
885 $orig = $this->getOriginalContent();
886 $content = $orig ?
$orig->getSection( $this->section
) : null;
889 $content = $def_content;
892 $undoafter = $request->getInt( 'undoafter' );
893 $undo = $request->getInt( 'undo' );
895 if ( $undo > 0 && $undoafter > 0 ) {
896 if ( $undo < $undoafter ) {
897 # If they got undoafter and undo round the wrong way, switch them
898 list( $undo, $undoafter ) = array( $undoafter, $undo );
901 $undorev = Revision
::newFromId( $undo );
902 $oldrev = Revision
::newFromId( $undoafter );
904 # Sanity check, make sure it's the right page,
905 # the revisions exist and they were not deleted.
906 # Otherwise, $content will be left as-is.
907 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
908 $undorev->getPage() == $oldrev->getPage() &&
909 $undorev->getPage() == $this->getTitle()->getArticleID() &&
910 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
911 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
913 $content = $this->getArticle()->getUndoContent( $undorev, $oldrev );
915 if ( $content === false ) {
916 # Warn the user that something went wrong
917 $undoMsg = 'failure';
919 # Inform the user of our success and set an automatic edit summary
920 $undoMsg = 'success';
922 # If we just undid one rev, use an autosummary
923 $firstrev = $oldrev->getNext();
924 if ( $firstrev && $firstrev->getId() == $undo ) {
925 $undoSummary = $context->msg( 'undo-summary', $undo,
926 $undorev->getUserText() )->inContentLanguage()->text();
927 if ( $this->summary
=== '' ) {
928 $this->summary
= $undoSummary;
930 $this->summary
= $undoSummary .
931 $context->msg( 'colon-separator' )->inContentLanguage()->text() .
934 $this->undidRev
= $undo;
936 $this->formtype
= 'diff';
939 // Failed basic sanity checks.
940 // Older revisions may have been removed since the link
941 // was created, or we may simply have got bogus input.
945 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
946 $this->editFormPageTop
.= $context->getOutput()->parse( "<div class=\"{$class}\">" .
947 $context->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
950 if ( $content === false ) {
951 $content = $this->getOriginalContent();
956 wfProfileOut( __METHOD__
);
961 * Get the content of the wanted revision, without section extraction.
963 * The result of this function can be used to compare user's input with
964 * section replaced in its context (using WikiPage::replaceSection())
965 * to the original text of the edit.
967 * This difers from Article::getContent() that when a missing revision is
968 * encountered the result will be null and not the
969 * 'missing-revision' message.
972 * @return Content|null
974 private function getOriginalContent() {
975 if ( $this->section
== 'new' ) {
976 return $this->getCurrentContent();
978 $revision = $this->getArticle()->getRevisionFetched();
979 if ( $revision === null ) {
980 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
981 $handler = ContentHandler
::getForModelID( $this->contentModel
);
983 return $handler->makeEmptyContent();
986 $content = $revision->getContent();
992 * Get the current content of the page. This is basically similar to
993 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
994 * content object is returned instead of null.
999 protected function getCurrentContent() {
1000 $rev = $this->getArticle()->getRevision();
1001 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1003 if ( $content === false ||
$content === null ) {
1004 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
1005 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1007 return $handler->makeEmptyContent();
1009 # nasty side-effect, but needed for consistency
1010 $this->contentModel
= $rev->getContentModel();
1011 $this->contentFormat
= $rev->getContentFormat();
1019 * Use this method before edit() to preload some text into the edit box
1021 * @param $text string
1022 * @deprecated since 1.21, use setPreloadedContent() instead.
1024 public function setPreloadedText( $text ) {
1025 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1027 $content = $this->toEditContent( $text );
1029 $this->setPreloadedContent( $content );
1033 * Use this method before edit() to preload some content into the edit box
1035 * @param $content Content
1039 public function setPreloadedContent( Content
$content ) {
1040 $this->mPreloadContent
= $content;
1044 * Get the contents to be preloaded into the box, either set by
1045 * an earlier setPreloadText() or by loading the given page.
1047 * @param $preload String: representing the title to preload from.
1051 * @deprecated since 1.21, use getPreloadedContent() instead
1053 protected function getPreloadedText( $preload ) {
1054 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1056 $content = $this->getPreloadedContent( $preload );
1057 $text = $this->toEditText( $content );
1063 * Get the contents to be preloaded into the box, either set by
1064 * an earlier setPreloadText() or by loading the given page.
1066 * @param $preload String: representing the title to preload from.
1072 protected function getPreloadedContent( $preload ) {
1073 if ( !empty( $this->mPreloadContent
) ) {
1074 return $this->mPreloadContent
;
1077 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1079 if ( $preload === '' ) {
1080 return $handler->makeEmptyContent();
1083 $title = Title
::newFromText( $preload );
1084 $user = $this->getArticle()->getContext()->getUser();
1085 # Check for existence to avoid getting MediaWiki:Noarticletext
1086 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1087 return $handler->makeEmptyContent();
1090 $page = WikiPage
::factory( $title );
1091 if ( $page->isRedirect() ) {
1092 $title = $page->getRedirectTarget();
1094 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $user ) ) {
1095 return $handler->makeEmptyContent();
1097 $page = WikiPage
::factory( $title );
1100 $parserOptions = ParserOptions
::newFromUser( $user );
1101 $content = $page->getContent( Revision
::RAW
);
1104 return $handler->makeEmptyContent();
1107 return $content->preloadTransform( $title, $parserOptions );
1111 * Make sure the form isn't faking a user's credentials.
1113 * @param $request WebRequest
1117 function tokenOk( &$request ) {
1118 $user = $this->getArticle()->getContext()->getUser();
1119 $token = $request->getVal( 'wpEditToken' );
1120 $this->mTokenOk
= $user->matchEditToken( $token );
1121 $this->mTokenOkExceptSuffix
= $user->matchEditTokenNoSuffix( $token );
1122 return $this->mTokenOk
;
1126 * Attempt submission
1127 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1128 * @return bool false if output is done, true if the rest of the form should be displayed
1130 function attemptSave() {
1131 $context = $this->getArticle()->getContext();
1132 $out = $context->getOutput();
1133 $user = $context->getUser();
1135 $resultDetails = false;
1136 # Allow bots to exempt some edits from bot flagging
1137 $bot = $user->isAllowed( 'bot' ) && $this->bot
;
1138 $status = $this->internalAttemptSave( $resultDetails, $bot );
1139 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1140 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1141 $this->didSave
= true;
1144 switch ( $status->value
) {
1145 case self
::AS_HOOK_ERROR_EXPECTED
:
1146 case self
::AS_CONTENT_TOO_BIG
:
1147 case self
::AS_ARTICLE_WAS_DELETED
:
1148 case self
::AS_CONFLICT_DETECTED
:
1149 case self
::AS_SUMMARY_NEEDED
:
1150 case self
::AS_TEXTBOX_EMPTY
:
1151 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1155 case self
::AS_HOOK_ERROR
:
1158 case self
::AS_PARSE_ERROR
:
1159 $out->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>');
1162 case self
::AS_SUCCESS_NEW_ARTICLE
:
1163 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1164 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1165 $out->redirect( $this->getTitle()->getFullURL( $query ) . $anchor );
1168 case self
::AS_SUCCESS_UPDATE
:
1170 $sectionanchor = $resultDetails['sectionanchor'];
1172 // Give extensions a chance to modify URL query on update
1173 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->getArticle(), &$sectionanchor, &$extraQuery ) );
1175 if ( $resultDetails['redirect'] ) {
1176 if ( $extraQuery == '' ) {
1177 $extraQuery = 'redirect=no';
1179 $extraQuery = 'redirect=no&' . $extraQuery;
1182 $out->redirect( $this->getTitle()->getFullURL( $extraQuery ) . $sectionanchor );
1185 case self
::AS_BLANK_ARTICLE
:
1186 $out->redirect( $this->getContextTitle()->getFullURL() );
1189 case self
::AS_SPAM_ERROR
:
1190 $this->spamPageWithContent( $resultDetails['spam'] );
1193 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1194 throw new UserBlockedError( $user->getBlock() );
1196 case self
::AS_IMAGE_REDIRECT_ANON
:
1197 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1198 throw new PermissionsError( 'upload' );
1200 case self
::AS_READ_ONLY_PAGE_ANON
:
1201 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1202 throw new PermissionsError( 'edit' );
1204 case self
::AS_READ_ONLY_PAGE
:
1205 throw new ReadOnlyError
;
1207 case self
::AS_RATE_LIMITED
:
1208 throw new ThrottledError();
1210 case self
::AS_NO_CREATE_PERMISSION
:
1211 $permission = $this->getTitle()->isTalkPage() ?
'createtalk' : 'createpage';
1212 throw new PermissionsError( $permission );
1215 // We don't recognize $status->value. The only way that can happen
1216 // is if an extension hook aborted from inside ArticleSave.
1217 // Render the status object into $this->hookError
1218 // FIXME this sucks, we should just use the Status object throughout
1219 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1226 * Attempt submission (no UI)
1231 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1233 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1234 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1235 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1237 function internalAttemptSave( &$result, $bot = false ) {
1238 global $wgParser, $wgMaxArticleSize;
1240 $status = Status
::newGood();
1242 wfProfileIn( __METHOD__
);
1243 wfProfileIn( __METHOD__
. '-checks' );
1245 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1246 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1247 $status->fatal( 'hookaborted' );
1248 $status->value
= self
::AS_HOOK_ERROR
;
1249 wfProfileOut( __METHOD__
. '-checks' );
1250 wfProfileOut( __METHOD__
);
1255 # Construct Content object
1256 $textbox_content = $this->toEditContent( $this->textbox1
);
1257 } catch (MWContentSerializationException
$ex) {
1258 $status->fatal( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
1259 $status->value
= self
::AS_PARSE_ERROR
;
1260 wfProfileOut( __METHOD__
);
1264 $context = $this->getArticle()->getContext();
1265 $user = $context->getUser();
1267 # Check image redirect
1268 if ( $this->getTitle()->getNamespace() == NS_FILE
&&
1269 $textbox_content->isRedirect() &&
1270 !$user->isAllowed( 'upload' ) ) {
1271 $code = $user->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1272 $status->setResult( false, $code );
1274 wfProfileOut( __METHOD__
. '-checks' );
1275 wfProfileOut( __METHOD__
);
1281 $match = self
::matchSummarySpamRegex( $this->summary
);
1282 if ( $match === false ) {
1283 $match = self
::matchSpamRegex( $this->textbox1
);
1285 if ( $match !== false ) {
1286 $result['spam'] = $match;
1287 $ip = $context->getRequest()->getIP();
1288 $pdbk = $this->getTitle()->getPrefixedDBkey();
1289 $match = str_replace( "\n", '', $match );
1290 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1291 $status->fatal( 'spamprotectionmatch', $match );
1292 $status->value
= self
::AS_SPAM_ERROR
;
1293 wfProfileOut( __METHOD__
. '-checks' );
1294 wfProfileOut( __METHOD__
);
1297 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1298 # Error messages etc. could be handled within the hook...
1299 $status->fatal( 'hookaborted' );
1300 $status->value
= self
::AS_HOOK_ERROR
;
1301 wfProfileOut( __METHOD__
. '-checks' );
1302 wfProfileOut( __METHOD__
);
1304 } elseif ( $this->hookError
!= '' ) {
1305 # ...or the hook could be expecting us to produce an error
1306 $status->fatal( 'hookaborted' );
1307 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1308 wfProfileOut( __METHOD__
. '-checks' );
1309 wfProfileOut( __METHOD__
);
1313 if ( $user->isBlockedFrom( $this->getTitle(), false ) ) {
1314 // Auto-block user's IP if the account was "hard" blocked
1315 $user->spreadAnyEditBlock();
1316 # Check block state against master, thus 'false'.
1317 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1318 wfProfileOut( __METHOD__
. '-checks' );
1319 wfProfileOut( __METHOD__
);
1323 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1324 if ( $this->kblength
> $wgMaxArticleSize ) {
1325 // Error will be displayed by showEditForm()
1326 $this->tooBig
= true;
1327 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1328 wfProfileOut( __METHOD__
. '-checks' );
1329 wfProfileOut( __METHOD__
);
1333 if ( !$user->isAllowed( 'edit' ) ) {
1334 if ( $user->isAnon() ) {
1335 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1336 wfProfileOut( __METHOD__
. '-checks' );
1337 wfProfileOut( __METHOD__
);
1340 $status->fatal( 'readonlytext' );
1341 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1342 wfProfileOut( __METHOD__
. '-checks' );
1343 wfProfileOut( __METHOD__
);
1348 if ( wfReadOnly() ) {
1349 $status->fatal( 'readonlytext' );
1350 $status->value
= self
::AS_READ_ONLY_PAGE
;
1351 wfProfileOut( __METHOD__
. '-checks' );
1352 wfProfileOut( __METHOD__
);
1355 if ( $user->pingLimiter() ) {
1356 $status->fatal( 'actionthrottledtext' );
1357 $status->value
= self
::AS_RATE_LIMITED
;
1358 wfProfileOut( __METHOD__
. '-checks' );
1359 wfProfileOut( __METHOD__
);
1363 # If the article has been deleted while editing, don't save it without
1365 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1366 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1367 wfProfileOut( __METHOD__
. '-checks' );
1368 wfProfileOut( __METHOD__
);
1372 wfProfileOut( __METHOD__
. '-checks' );
1374 # Load the page data from the master. If anything changes in the meantime,
1375 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1376 $this->getArticle()->loadPageData( 'fromdbmaster' );
1377 $new = !$this->getArticle()->exists();
1380 // Late check for create permission, just in case *PARANOIA*
1381 if ( !$this->getTitle()->userCan( 'create', $user ) ) {
1382 $status->fatal( 'nocreatetext' );
1383 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1384 wfDebug( __METHOD__
. ": no create permission\n" );
1385 wfProfileOut( __METHOD__
);
1389 # Don't save a new article if it's blank.
1390 if ( $this->textbox1
== '' ) {
1391 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1392 wfProfileOut( __METHOD__
);
1396 // Run post-section-merge edit filter
1397 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1398 # Error messages etc. could be handled within the hook...
1399 $status->fatal( 'hookaborted' );
1400 $status->value
= self
::AS_HOOK_ERROR
;
1401 wfProfileOut( __METHOD__
);
1403 } elseif ( $this->hookError
!= '' ) {
1404 # ...or the hook could be expecting us to produce an error
1405 $status->fatal( 'hookaborted' );
1406 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1407 wfProfileOut( __METHOD__
);
1411 $content = $textbox_content;
1413 $result['sectionanchor'] = '';
1414 if ( $this->section
== 'new' ) {
1415 if ( $this->sectiontitle
!== '' ) {
1416 // Insert the section title above the content.
1417 $content = $content->addSectionHeader( $this->sectiontitle
);
1419 // Jump to the new section
1420 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1422 // If no edit summary was specified, create one automatically from the section
1423 // title and have it link to the new section. Otherwise, respect the summary as
1425 if ( $this->summary
=== '' ) {
1426 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1427 $this->summary
= $context->msg( 'newsectionsummary' )
1428 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1430 } elseif ( $this->summary
!== '' ) {
1431 // Insert the section title above the content.
1432 $content = $content->addSectionHeader( $this->summary
);
1434 // Jump to the new section
1435 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1437 // Create a link to the new section from the edit summary.
1438 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1439 $this->summary
= $context->msg( 'newsectionsummary' )
1440 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1444 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1446 # Article exists. Check for edit conflict.
1448 $this->getArticle()->clear(); # Force reload of dates, etc.
1449 $timestamp = $this->getArticle()->getTimestamp();
1451 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1453 if ( $timestamp != $this->edittime
) {
1454 $this->isConflict
= true;
1455 if ( $this->section
== 'new' ) {
1456 if ( $this->getArticle()->getUserText() == $user->getName() &&
1457 $this->getArticle()->getComment() == $this->summary
) {
1458 // Probably a duplicate submission of a new comment.
1459 // This can happen when squid resends a request after
1460 // a timeout but the first one actually went through.
1461 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1463 // New comment; suppress conflict.
1464 $this->isConflict
= false;
1465 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1467 } elseif ( $this->section
== '' ) {
1468 $userWasLastToEdit = Revision
::userWasLastToEdit(
1470 $this->getTitle()->getArticleID(),
1475 if ( $userWasLastToEdit ) {
1476 # Suppress edit conflict with self, except for section edits where merging is required.
1477 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1478 $this->isConflict
= false;
1483 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1484 // backwards compatibility with old forms/bots).
1485 if ( $this->sectiontitle
!== '' ) {
1486 $sectionTitle = $this->sectiontitle
;
1488 $sectionTitle = $this->summary
;
1493 if ( $this->isConflict
) {
1494 wfDebug( __METHOD__
. ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1495 . " (article time '{$timestamp}')\n" );
1497 $content = $this->getArticle()->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1499 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1500 $content = $this->getArticle()->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1503 if ( is_null( $content ) ) {
1504 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1505 $this->isConflict
= true;
1506 $content = $textbox_content; // do not try to merge here!
1507 } elseif ( $this->isConflict
) {
1508 $contentObj = $content;
1510 if ( $this->mergeChangesInto( $content ) ) {
1511 // Successful merge! Maybe we should tell the user the good news?
1512 $this->isConflict
= false;
1513 $content = $this->toEditContent( $content );
1514 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1516 $this->section
= '';
1517 $this->textbox1
= ContentHandler
::getContentText( $contentObj );
1518 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1522 if ( $this->isConflict
) {
1523 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1524 wfProfileOut( __METHOD__
);
1528 // Run post-section-merge edit filter
1529 $hook_args = array( $this, $content, &$this->hookError
, $this->summary
);
1531 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged', $hook_args )
1532 ||
!wfRunHooks( 'EditFilterMergedContent', $hook_args ) ) {
1533 # Error messages etc. could be handled within the hook...
1534 $status->fatal( 'hookaborted' );
1535 $status->value
= self
::AS_HOOK_ERROR
;
1536 wfProfileOut( __METHOD__
);
1538 } elseif ( $this->hookError
!= '' ) {
1539 # ...or the hook could be expecting us to produce an error
1540 $status->fatal( 'hookaborted' );
1541 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1542 wfProfileOut( __METHOD__
);
1546 # Handle the user preference to force summaries here, but not for null edits
1547 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1548 && !$content->equals( $this->getOriginalContent() )
1549 && !$content->isRedirect() ) # check if it's not a redirect
1551 if ( md5( $this->summary
) == $this->autoSumm
) {
1552 $this->missingSummary
= true;
1553 $status->fatal( 'missingsummary' );
1554 $status->value
= self
::AS_SUMMARY_NEEDED
;
1555 wfProfileOut( __METHOD__
);
1560 # And a similar thing for new sections
1561 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1562 if ( trim( $this->summary
) == '' ) {
1563 $this->missingSummary
= true;
1564 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1565 $status->value
= self
::AS_SUMMARY_NEEDED
;
1566 wfProfileOut( __METHOD__
);
1572 wfProfileIn( __METHOD__
. '-sectionanchor' );
1573 $sectionanchor = '';
1574 if ( $this->section
== 'new' ) {
1575 if ( $this->textbox1
== '' ) {
1576 $this->missingComment
= true;
1577 $status->fatal( 'missingcommenttext' );
1578 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1579 wfProfileOut( __METHOD__
. '-sectionanchor' );
1580 wfProfileOut( __METHOD__
);
1583 if ( $this->sectiontitle
!== '' ) {
1584 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1585 // If no edit summary was specified, create one automatically from the section
1586 // title and have it link to the new section. Otherwise, respect the summary as
1588 if ( $this->summary
=== '' ) {
1589 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1590 $this->summary
= $context->msg( 'newsectionsummary' )
1591 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1593 } elseif ( $this->summary
!== '' ) {
1594 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1595 # This is a new section, so create a link to the new section
1596 # in the revision summary.
1597 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1598 $this->summary
= $context->msg( 'newsectionsummary' )
1599 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1601 } elseif ( $this->section
!= '' ) {
1602 # Try to get a section anchor from the section source, redirect to edited section if header found
1603 # XXX: might be better to integrate this into Article::replaceSection
1604 # for duplicate heading checking and maybe parsing
1605 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1606 # we can't deal with anchors, includes, html etc in the header for now,
1607 # headline would need to be parsed to improve this
1608 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1609 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1612 $result['sectionanchor'] = $sectionanchor;
1613 wfProfileOut( __METHOD__
. '-sectionanchor' );
1615 // Save errors may fall down to the edit form, but we've now
1616 // merged the section into full text. Clear the section field
1617 // so that later submission of conflict forms won't try to
1618 // replace that into a duplicated mess.
1619 $this->textbox1
= $this->toEditText( $content );
1620 $this->section
= '';
1622 $status->value
= self
::AS_SUCCESS_UPDATE
;
1625 // Check for length errors again now that the section is merged in
1626 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1627 if ( $this->kblength
> $wgMaxArticleSize ) {
1628 $this->tooBig
= true;
1629 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1630 wfProfileOut( __METHOD__
);
1634 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1635 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1636 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1637 ( $bot ? EDIT_FORCE_BOT
: 0 );
1639 $doEditStatus = $this->getArticle()->doEditContent( $content, $this->summary
, $flags,
1640 false, null, $this->contentFormat
);
1642 if ( $doEditStatus->isOK() ) {
1643 $result['redirect'] = $content->isRedirect();
1644 $this->updateWatchlist();
1645 wfProfileOut( __METHOD__
);
1648 // Failure from doEdit()
1649 // Show the edit conflict page for certain recognized errors from doEdit(),
1650 // but don't show it for errors from extension hooks
1651 $errors = $doEditStatus->getErrorsArray();
1652 if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
1653 'edit-already-exists' ) ) )
1655 $this->isConflict
= true;
1656 // Destroys data doEdit() put in $status->value but who cares
1657 $doEditStatus->value
= self
::AS_END
;
1659 wfProfileOut( __METHOD__
);
1660 return $doEditStatus;
1665 * Register the change of watch status
1667 protected function updateWatchlist() {
1668 $title = $this->getTitle();
1669 $user = $this->getArticle()->getContext()->getUser();
1671 if ( $user->isLoggedIn() && $this->watchthis
!= $user->isWatched( $title ) ) {
1672 $fname = __METHOD__
;
1673 $watch = $this->watchthis
;
1675 // Do this in its own transaction to reduce contention...
1676 $dbw = wfGetDB( DB_MASTER
);
1677 $dbw->onTransactionIdle( function() use ( $dbw, $title, $watch, $user, $fname ) {
1678 $dbw->begin( $fname );
1680 WatchAction
::doWatch( $title, $user );
1682 WatchAction
::doUnwatch( $title, $user );
1684 $dbw->commit( $fname );
1693 * @param $editText string
1696 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1698 function mergeChangesInto( &$editText ){
1699 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1701 wfProfileIn( __METHOD__
);
1703 $db = wfGetDB( DB_MASTER
);
1705 // This is the revision the editor started from
1706 $baseRevision = $this->getBaseRevision();
1707 if ( is_null( $baseRevision ) ) {
1708 wfProfileOut( __METHOD__
);
1711 $baseText = $baseRevision->getText();
1713 // The current state, we want to merge updates into it
1714 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1715 if ( is_null( $currentRevision ) ) {
1716 wfProfileOut( __METHOD__
);
1719 $currentText = $currentRevision->getText();
1722 $editText = $this->toEditText( $editText );
1724 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1725 $editText = $result;
1726 wfProfileOut( __METHOD__
);
1730 wfProfileOut( __METHOD__
);
1738 * @param $editContent
1742 private function mergeChangesIntoContent( &$editContent ){
1743 wfProfileIn( __METHOD__
);
1745 $db = wfGetDB( DB_MASTER
);
1747 // This is the revision the editor started from
1748 $baseRevision = $this->getBaseRevision();
1749 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
1751 if ( is_null( $baseContent ) ) {
1752 wfProfileOut( __METHOD__
);
1756 // The current state, we want to merge updates into it
1757 $currentRevision = Revision
::loadFromTitle( $db, $this->getTitle() );
1758 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
1760 if ( is_null( $currentContent ) ) {
1761 wfProfileOut( __METHOD__
);
1765 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
1767 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1770 $editContent = $result;
1771 wfProfileOut( __METHOD__
);
1775 wfProfileOut( __METHOD__
);
1782 function getBaseRevision() {
1783 if ( !$this->mBaseRevision
) {
1784 $db = wfGetDB( DB_MASTER
);
1785 $baseRevision = Revision
::loadFromTimestamp(
1786 $db, $this->getTitle(), $this->edittime
);
1787 return $this->mBaseRevision
= $baseRevision;
1789 return $this->mBaseRevision
;
1794 * Check given input text against $wgSpamRegex, and return the text of the first match.
1796 * @param $text string
1798 * @return string|bool matching string or false
1800 public static function matchSpamRegex( $text ) {
1801 global $wgSpamRegex;
1802 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1803 $regexes = (array)$wgSpamRegex;
1804 return self
::matchSpamRegexInternal( $text, $regexes );
1808 * Check given input text against $wgSpamRegex, and return the text of the first match.
1810 * @param $text string
1812 * @return string|bool matching string or false
1814 public static function matchSummarySpamRegex( $text ) {
1815 global $wgSummarySpamRegex;
1816 $regexes = (array)$wgSummarySpamRegex;
1817 return self
::matchSpamRegexInternal( $text, $regexes );
1821 * @param $text string
1822 * @param $regexes array
1823 * @return bool|string
1825 protected static function matchSpamRegexInternal( $text, $regexes ) {
1826 foreach ( $regexes as $regex ) {
1828 if ( preg_match( $regex, $text, $matches ) ) {
1836 function setHeaders() {
1837 $context = $this->getArticle()->getContext();
1838 $out = $context->getOutput();
1840 $out->addModules( 'mediawiki.action.edit' );
1842 if ( $context->getUser()->getOption( 'uselivepreview', false ) ) {
1843 $out->addModules( 'mediawiki.action.edit.preview' );
1845 // Bug #19334: textarea jumps when editing articles in IE8
1846 $out->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1848 $out->setRobotPolicy( 'noindex,nofollow' );
1850 # Enabled article-related sidebar, toplinks, etc.
1851 $out->setArticleRelated( true );
1853 $contextTitle = $this->getContextTitle();
1854 if ( $this->isConflict
) {
1855 $msg = 'editconflict';
1856 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1857 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1859 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1860 'editing' : 'creating';
1862 # Use the title defined by DISPLAYTITLE magic word when present
1863 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1864 if ( $displayTitle === false ) {
1865 $displayTitle = $contextTitle->getPrefixedText();
1867 $out->setPageTitle( $context->msg( $msg, $displayTitle ) );
1871 * Show all applicable editing introductions
1873 protected function showIntro() {
1874 if ( $this->suppressIntro
) {
1878 $namespace = $this->getTitle()->getNamespace();
1879 $context = $this->getArticle()->getContext();
1880 $out = $context->getOutput();
1882 if ( $namespace == NS_MEDIAWIKI
) {
1883 # Show a warning if editing an interface message
1884 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1885 } else if( $namespace == NS_FILE
) {
1886 # Show a hint to shared repo
1887 $file = wfFindFile( $this->getTitle() );
1888 if( $file && !$file->isLocal() ) {
1889 $descUrl = $file->getDescriptionUrl();
1890 # there must be a description url to show a hint to shared repo
1892 if( !$this->getTitle()->exists() ) {
1893 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1894 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1897 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1898 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1905 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1906 # Show log extract when the user is currently blocked
1907 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1908 $parts = explode( '/', $this->getTitle()->getText(), 2 );
1909 $username = $parts[0];
1910 $user = User
::newFromName( $username, false /* allow IP users*/ );
1911 $ip = User
::isIP( $username );
1912 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1913 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1914 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1915 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1916 LogEventsList
::showLogExtract(
1919 $user->getUserPage(),
1923 'showIfEmpty' => false,
1925 'blocked-notice-logextract',
1926 $user->getName() # Support GENDER in notice
1933 # Try to add a custom edit intro, or use the standard one if this is not possible.
1934 if ( !$this->showCustomIntro() && !$this->getTitle()->exists() ) {
1935 if ( $context->getUser()->isLoggedIn() ) {
1936 $out->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1938 $out->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1942 # Give a notice if the user is editing a deleted/moved page...
1943 if ( !$this->getTitle()->exists() ) {
1944 LogEventsList
::showLogExtract( $out, array( 'delete', 'move' ), $this->getTitle(),
1948 'conds' => array( "log_action != 'revision'" ),
1949 'showIfEmpty' => false,
1950 'msgKey' => array( 'recreate-moveddeleted-warn' )
1957 * Attempt to show a custom editing introduction, if supplied
1961 protected function showCustomIntro() {
1962 if ( $this->editintro
) {
1963 $title = Title
::newFromText( $this->editintro
);
1965 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1966 // Added using template syntax, to take <noinclude>'s into account.
1967 $this->getArticle()->getContext()->getOutput()
1968 ->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->getTitle() );
1978 * Gets an editable textual representation of $content.
1979 * The textual representation can be turned by into a Content object by the
1980 * toEditContent() method.
1982 * If $content is null or false or a string, $content is returned unchanged.
1984 * If the given Content object is not of a type that can be edited using the text base EditPage,
1985 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
1988 * @param Content|null|bool|string $content
1989 * @return String the editable text form of the content.
1991 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
1993 protected function toEditText( $content ) {
1994 if ( $content === null ||
$content === false ) {
1998 if ( is_string( $content ) ) {
2002 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
2003 throw new MWException( "This content model can not be edited as text: "
2004 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2007 return $content->serialize( $this->contentFormat
);
2011 * Turns the given text into a Content object by unserializing it.
2013 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
2014 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2017 * @param String|null|bool $text Text to unserialize
2018 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
2021 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
2022 * and $this->allowNonTextContent is not true.
2024 protected function toEditContent( $text ) {
2025 if ( $text === false ||
$text === null ) {
2029 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2030 $this->contentModel
, $this->contentFormat
);
2032 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
2033 throw new MWException( "This content model can not be edited as text: "
2034 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2041 * Send the edit form and related headers to $wgOut
2042 * @param $formCallback Callback|null that takes an OutputPage parameter; will be called
2043 * during form output near the top, for captchas and the like.
2045 function showEditForm( $formCallback = null ) {
2046 wfProfileIn( __METHOD__
);
2048 # need to parse the preview early so that we know which templates are used,
2049 # otherwise users with "show preview after edit box" will get a blank list
2050 # we parse this near the beginning so that setHeaders can do the title
2051 # setting work instead of leaving it in getPreviewText
2052 $previewOutput = '';
2053 if ( $this->formtype
== 'preview' ) {
2054 $previewOutput = $this->getPreviewText();
2057 $context = $this->getArticle()->getContext();
2058 $out = $context->getOutput();
2059 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$out ) );
2061 $this->setHeaders();
2063 if ( $this->showHeader() === false ) {
2064 wfProfileOut( __METHOD__
);
2068 $out->addHTML( $this->editFormPageTop
);
2070 if ( $context->getUser()->getOption( 'previewontop' ) ) {
2071 $this->displayPreviewArea( $previewOutput, true );
2074 $out->addHTML( $this->editFormTextTop
);
2076 $showToolbar = true;
2077 if ( $this->wasDeletedSinceLastEdit() ) {
2078 if ( $this->formtype
== 'save' ) {
2079 // Hide the toolbar and edit area, user can click preview to get it back
2080 // Add an confirmation checkbox and explanation.
2081 $showToolbar = false;
2083 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2084 'deletedwhileediting' );
2088 // @todo Add EditForm plugin interface and use it here!
2089 // search for textarea1 and textares2, and allow EditForm to override all uses.
2090 $out->addHTML( Html
::openElement( 'form', array( 'id' => self
::EDITFORM_ID
, 'name' => self
::EDITFORM_ID
,
2091 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
2092 'enctype' => 'multipart/form-data' ) ) );
2094 if ( is_callable( $formCallback ) ) {
2095 call_user_func_array( $formCallback, array( &$out ) );
2098 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$out ) );
2100 // Put these up at the top to ensure they aren't lost on early form submission
2101 $this->showFormBeforeText();
2103 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2104 $username = $this->lastDelete
->user_name
;
2105 $comment = $this->lastDelete
->log_comment
;
2107 // It is better to not parse the comment at all than to have templates expanded in the middle
2108 // @todo Can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2109 $key = $comment === ''
2110 ?
'confirmrecreate-noreason'
2111 : 'confirmrecreate';
2113 '<div class="mw-confirm-recreate">' .
2114 $context->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2115 Xml
::checkLabel( $context->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2116 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2122 # When the summary is hidden, also hide them on preview/show changes
2123 if( $this->nosummary
) {
2124 $out->addHTML( Html
::hidden( 'nosummary', true ) );
2127 # If a blank edit summary was previously provided, and the appropriate
2128 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2129 # user being bounced back more than once in the event that a summary
2132 # For a bit more sophisticated detection of blank summaries, hash the
2133 # automatic one and pass that in the hidden field wpAutoSummary.
2134 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2135 $out->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2138 if ( $this->undidRev
) {
2139 $out->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2142 if ( $this->hasPresetSummary
) {
2143 // If a summary has been preset using &summary= we dont want to prompt for
2144 // a different summary. Only prompt for a summary if the summary is blanked.
2146 $this->autoSumm
= md5( '' );
2149 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2150 $out->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2152 $out->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2154 $out->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2155 $out->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2157 if ( $this->section
== 'new' ) {
2158 $this->showSummaryInput( true, $this->summary
);
2159 $out->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2162 $out->addHTML( $this->editFormTextBeforeContent
);
2164 if ( !$this->isCssJsSubpage
&& $showToolbar && $context->getUser()->getOption( 'showtoolbar' ) ) {
2165 $out->addHTML( EditPage
::getEditToolbar() );
2168 if ( $this->isConflict
) {
2169 // In an edit conflict bypass the overrideable content form method
2170 // and fallback to the raw wpTextbox1 since editconflicts can't be
2171 // resolved between page source edits and custom ui edits using the
2173 $this->textbox2
= $this->textbox1
;
2175 $content = $this->getCurrentContent();
2176 $this->textbox1
= $this->toEditText( $content );
2178 $this->showTextbox1();
2180 $this->showContentForm();
2183 $out->addHTML( $this->editFormTextAfterContent
);
2185 $this->showStandardInputs();
2186 $this->showFormAfterText();
2187 $this->showTosSummary();
2188 $this->showEditTools();
2190 $out->addHTML( $this->editFormTextAfterTools
. "\n" );
2192 $out->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2193 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2195 $out->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2196 Linker
::formatHiddenCategories( $this->getArticle()->getHiddenCategories() ) ) );
2198 if ( $this->isConflict
) {
2200 $this->showConflict();
2201 } catch ( MWContentSerializationException
$ex ) {
2202 // this can't really happen, but be nice if it does.
2203 $msg = $context->msg( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2204 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2208 $out->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2210 if ( !$context->getUser()->getOption( 'previewontop' ) ) {
2211 $this->displayPreviewArea( $previewOutput, false );
2214 wfProfileOut( __METHOD__
);
2218 * Extract the section title from current section text, if any.
2220 * @param string $text
2221 * @return Mixed|string or false
2223 public static function extractSectionTitle( $text ) {
2224 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2225 if ( !empty( $matches[2] ) ) {
2227 return $wgParser->stripSectionName( trim( $matches[2] ) );
2233 protected function showHeader() {
2234 global $wgMaxArticleSize;
2236 $context = $this->getArticle()->getContext();
2237 $out = $context->getOutput();
2238 $title = $this->getTitle();
2240 if ( $title->isTalkPage() ) {
2241 $out->addWikiMsg( 'talkpagetext' );
2244 # Optional notices on a per-namespace and per-page basis
2245 $editnotice_ns = 'editnotice-' . $title->getNamespace();
2246 $editnotice_ns_message = $context->msg( $editnotice_ns );
2247 if ( $editnotice_ns_message->exists() ) {
2248 $out->addWikiText( $editnotice_ns_message->plain() );
2251 if ( MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
2252 $parts = explode( '/', $title->getDBkey() );
2253 $editnotice_base = $editnotice_ns;
2255 while ( count( $parts ) > 0 ) {
2256 $editnotice_base .= '-' . array_shift( $parts );
2257 $editnotice_base_msg = $context->msg( $editnotice_base );
2258 if ( $editnotice_base_msg->exists() ) {
2259 $out->addWikiText( $editnotice_base_msg->plain() );
2263 # Even if there are no subpages in namespace, we still don't want / in MW ns.
2264 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $title->getDBkey() );
2265 $editnoticeMsg = $context->msg( $editnoticeText );
2266 if ( $editnoticeMsg->exists() ) {
2267 $out->addWikiText( $editnoticeMsg->plain() );
2271 if ( $this->isConflict
) {
2272 $out->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2273 $this->edittime
= $this->getArticle()->getTimestamp();
2275 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2276 // We use $this->section to much before this and getVal('wgSection') directly in other places
2277 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2278 // Someone is welcome to try refactoring though
2279 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2283 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2284 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2285 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2286 if ( $sectionTitle !== false ) {
2287 $this->summary
= "/* $sectionTitle */ ";
2292 if ( $this->missingComment
) {
2293 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2296 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2297 $out->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2300 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2301 $out->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2304 if ( $this->hookError
!== '' ) {
2305 $out->addWikiText( $this->hookError
);
2308 if ( !$this->checkUnicodeCompliantBrowser() ) {
2309 $out->addWikiMsg( 'nonunicodebrowser' );
2312 if ( $this->section
!= 'new' ) {
2313 $revision = $this->getArticle()->getRevisionFetched();
2315 // Let sysop know that this will make private content public if saved
2317 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $context->getUser() ) ) {
2318 $out->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2319 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2320 $out->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2323 if ( !$revision->isCurrent() ) {
2324 $this->getArticle()->setOldSubtitle( $revision->getId() );
2325 $out->addWikiMsg( 'editingold' );
2327 } elseif ( $title->exists() ) {
2328 // Something went wrong
2330 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2331 array( 'missing-revision', $this->oldid
) );
2336 if ( wfReadOnly() ) {
2337 $out->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2338 } elseif ( $context->getUser()->isAnon() ) {
2339 if ( $this->formtype
!= 'preview' ) {
2340 $out->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2342 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2345 if ( $this->isCssJsSubpage
) {
2346 # Check the skin exists
2347 if ( $this->isWrongCaseCssJsPage
) {
2349 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2350 array( 'userinvalidcssjstitle', $title->getSkinFromCssJsSubpage() )
2353 if ( $this->formtype
!== 'preview' ) {
2354 if ( $this->isCssSubpage
) {
2355 $out->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2358 if ( $this->isJsSubpage
) {
2359 $out->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2365 if ( $title->getNamespace() != NS_MEDIAWIKI
&& $title->isProtected( 'edit' ) ) {
2366 # Is the title semi-protected?
2367 if ( $title->isSemiProtected() ) {
2368 $noticeMsg = 'semiprotectedpagewarning';
2370 # Then it must be protected based on static groups (regular)
2371 $noticeMsg = 'protectedpagewarning';
2373 LogEventsList
::showLogExtract( $out, 'protect', $title, '',
2374 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2377 if ( $title->isCascadeProtected() ) {
2378 # Is this page under cascading protection from some source pages?
2379 list( $cascadeSources, /* $restrictions */ ) = $title->getCascadeProtectionSources();
2380 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2381 $cascadeSourcesCount = count( $cascadeSources );
2382 if ( $cascadeSourcesCount > 0 ) {
2383 # Explain, and list the titles responsible
2384 foreach ( $cascadeSources as $page ) {
2385 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2388 $notice .= '</div>';
2389 $out->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2392 if ( !$title->exists() && $title->getRestrictions( 'create' ) ) {
2393 LogEventsList
::showLogExtract( $out, 'protect', $title, '',
2395 'showIfEmpty' => false,
2396 'msgKey' => array( 'titleprotectedwarning' ),
2397 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2400 if ( $this->kblength
=== false ) {
2401 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2404 $lang = $context->getLanguage();
2405 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2406 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2407 array( 'longpageerror', $lang->formatNum( $this->kblength
), $lang->formatNum( $wgMaxArticleSize ) ) );
2409 if ( !$context->msg( 'longpage-hint' )->isDisabled() ) {
2410 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2411 array( 'longpage-hint', $lang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2416 # Add header copyright warning
2417 $this->showHeaderCopyrightWarning();
2421 * Standard summary input and label (wgSummary), abstracted so EditPage
2422 * subclasses may reorganize the form.
2423 * Note that you do not need to worry about the label's for=, it will be
2424 * inferred by the id given to the input. You can remove them both by
2425 * passing array( 'id' => false ) to $userInputAttrs.
2427 * @param $summary string The value of the summary input
2428 * @param $labelText string The html to place inside the label
2429 * @param $inputAttrs array of attrs to use on the input
2430 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2432 * @return array An array in the format array( $label, $input )
2434 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2435 // Note: the maxlength is overriden in JS to 255 and to make it use UTF-8 bytes, not characters.
2436 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2437 'id' => 'wpSummary',
2438 'maxlength' => '200',
2441 'spellcheck' => 'true',
2442 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2444 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2445 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2446 'id' => "wpSummaryLabel"
2451 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2452 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2455 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2457 return array( $label, $input );
2461 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2462 * up top, or false if this is the comment summary
2463 * down below the textarea
2464 * @param $summary String: The text of the summary to display
2467 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2469 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2470 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2471 if ( $isSubjectPreview ) {
2472 if ( $this->nosummary
) {
2476 if ( !$this->mShowSummaryField
) {
2481 $context = $this->getArticle()->getContext();
2482 $summary = $wgContLang->recodeForEdit( $summary );
2483 $labelText = $context->msg( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2484 list( $label, $input ) = $this->getSummaryInput(
2487 array( 'class' => $summaryClass ),
2490 $context->getOutput()->addHTML( "{$label} {$input}" );
2494 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2495 * up top, or false if this is the comment summary
2496 * down below the textarea
2497 * @param $summary String: the text of the summary to display
2500 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2501 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2507 $context = $this->getArticle()->getContext();
2508 if ( $isSubjectPreview ) {
2509 $summary = $context->msg( 'newsectionsummary', $wgParser->stripSectionName( $summary ) )
2510 ->inContentLanguage()->text();
2513 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2515 $summary = $context->msg( $message )->parse() .
2516 Linker
::commentBlock( $summary, $this->getTitle(), $isSubjectPreview );
2517 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2520 protected function showFormBeforeText() {
2521 $out = $this->getArticle()->getContext()->getOutput();
2522 $section = htmlspecialchars( $this->section
);
2524 $out->addHTML( <<<HTML
2525 <input type='hidden' value="{$section}" name="wpSection" />
2526 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2527 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2528 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2533 if ( !$this->checkUnicodeCompliantBrowser() ) {
2534 $out->addHTML( Html
::hidden( 'safemode', '1' ) );
2538 protected function showFormAfterText() {
2539 $out = $this->getArticle()->getContext()->getOutput();
2540 $user = $this->getArticle()->getContext()->getUser();
2542 * To make it harder for someone to slip a user a page
2543 * which submits an edit form to the wiki without their
2544 * knowledge, a random token is associated with the login
2545 * session. If it's not passed back with the submission,
2546 * we won't save the page, or render user JavaScript and
2549 * For anon editors, who may not have a session, we just
2550 * include the constant suffix to prevent editing from
2551 * broken text-mangling proxies.
2553 $out->addHTML( "\n" . Html
::hidden( "wpEditToken", $user->getEditToken() ) . "\n" );
2557 * Subpage overridable method for printing the form for page content editing
2558 * By default this simply outputs wpTextbox1
2559 * Subclasses can override this to provide a custom UI for editing;
2560 * be it a form, or simply wpTextbox1 with a modified content that will be
2561 * reverse modified when extracted from the post data.
2562 * Note that this is basically the inverse for importContentFormData
2564 protected function showContentForm() {
2565 $this->showTextbox1();
2569 * Method to output wpTextbox1
2570 * The $textoverride method can be used by subclasses overriding showContentForm
2571 * to pass back to this method.
2573 * @param $customAttribs array of html attributes to use in the textarea
2574 * @param $textoverride String: optional text to override $this->textarea1 with
2576 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2577 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2578 $attribs = array( 'style' => 'display:none;' );
2580 $classes = array(); // Textarea CSS
2581 $title = $this->getTitle();
2583 if ( $title->getNamespace() != NS_MEDIAWIKI
&& $title->isProtected( 'edit' ) ) {
2584 # Is the title semi-protected?
2585 if ( $title->isSemiProtected() ) {
2586 $classes[] = 'mw-textarea-sprotected';
2588 # Then it must be protected based on static groups (regular)
2589 $classes[] = 'mw-textarea-protected';
2591 # Is the title cascade-protected?
2592 if ( $title->isCascadeProtected() ) {
2593 $classes[] = 'mw-textarea-cprotected';
2597 $attribs = array( 'tabindex' => 1 );
2599 if ( is_array( $customAttribs ) ) {
2600 $attribs +
= $customAttribs;
2603 if ( count( $classes ) ) {
2604 if ( isset( $attribs['class'] ) ) {
2605 $classes[] = $attribs['class'];
2607 $attribs['class'] = implode( ' ', $classes );
2611 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2614 protected function showTextbox2() {
2615 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2618 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2619 $wikitext = $this->safeUnicodeOutput( $text );
2620 if ( strval( $wikitext ) !== '' ) {
2621 // Ensure there's a newline at the end, otherwise adding lines
2623 // But don't add a newline if the ext is empty, or Firefox in XHTML
2624 // mode will show an extra newline. A bit annoying.
2628 $context = $this->getArticle()->getContext();
2629 $user = $context->getUser();
2630 $attribs = $customAttribs +
array(
2633 'cols' => $user->getIntOption( 'cols' ),
2634 'rows' => $user->getIntOption( 'rows' ),
2635 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2638 $pageLang = $this->getTitle()->getPageLanguage();
2639 $attribs['lang'] = $pageLang->getCode();
2640 $attribs['dir'] = $pageLang->getDir();
2642 $context->getOutput()->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2645 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2649 $classes[] = 'ontop';
2652 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2654 if ( $this->formtype
!= 'preview' ) {
2655 $attribs['style'] = 'display: none;';
2658 $context = $this->getArticle()->getContext();
2659 $out = $context->getOutput();
2660 $out->addHTML( Xml
::openElement( 'div', $attribs ) );
2662 if ( $this->formtype
== 'preview' ) {
2663 $this->showPreview( $previewOutput );
2666 $out->addHTML( '</div>' );
2668 if ( $this->formtype
== 'diff' ) {
2671 } catch ( MWContentSerializationException
$ex ) {
2672 $msg = $context->msg( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2673 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2679 * Append preview output to $wgOut.
2680 * Includes category rendering if this is a category page.
2682 * @param $text String: the HTML to be output for the preview.
2684 protected function showPreview( $text ) {
2685 if ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
2686 $this->getArticle()->openShowCategory();
2688 # This hook seems slightly odd here, but makes things more
2689 # consistent for extensions.
2690 $out = $this->getArticle()->getContext()->getOutput();
2691 wfRunHooks( 'OutputPageBeforeHTML', array( &$out, &$text ) );
2693 $out->addHTML( $text );
2695 if ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
2696 $this->getArticle()->closeShowCategory();
2701 * Get a diff between the current contents of the edit box and the
2702 * version of the page we're editing from.
2704 * If this is a section edit, we'll replace the section as for final
2705 * save and then make a comparison.
2707 function showDiff() {
2710 $oldtitlemsg = 'currentrev';
2711 # if message does not exist, show diff against the preloaded default
2712 $title = $this->getTitle();
2713 if( $title->getNamespace() == NS_MEDIAWIKI
&& !$title->exists() ) {
2714 $oldtext = $title->getDefaultMessageText();
2715 if( $oldtext !== false ) {
2716 $oldtitlemsg = 'defaultmessagetext';
2717 $oldContent = $this->toEditContent( $oldtext );
2722 $oldContent = $this->getCurrentContent();
2725 $textboxContent = $this->toEditContent( $this->textbox1
);
2727 $newContent = $this->getArticle()->replaceSectionContent(
2728 $this->section
, $textboxContent,
2729 $this->summary
, $this->edittime
2732 $context = $this->getArticle()->getContext();
2733 $user = $context->getUser();
2735 if ( $newContent ) {
2736 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2737 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2739 $popts = ParserOptions
::newFromUserAndLang( $user, $wgContLang );
2740 $newContent = $newContent->preSaveTransform( $this->getTitle(), $user, $popts );
2743 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2744 $oldtitle = $context->msg( $oldtitlemsg )->parse();
2745 $newtitle = $context->msg( 'yourtext' )->parse();
2747 if ( !$oldContent ) {
2748 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
2751 if ( !$newContent ) {
2752 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
2755 $de = $oldContent->getContentHandler()->createDifferenceEngine( $context );
2756 $de->setContent( $oldContent, $newContent );
2758 $difftext = $de->getDiff( $oldtitle, $newtitle );
2759 $de->showDiffStyle();
2764 $context->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2768 * Show the header copyright warning.
2770 protected function showHeaderCopyrightWarning() {
2771 $msg = 'editpage-head-copy-warn';
2772 $context = $this->getArticle()->getContext();
2774 if ( !$context->msg( $msg )->isDisabled() ) {
2775 $context->getOutput()->wrapWikiMsg(
2776 "<div class='editpage-head-copywarn'>\n$1\n</div>",
2777 'editpage-head-copy-warn'
2783 * Give a chance for site and per-namespace customizations of
2784 * terms of service summary link that might exist separately
2785 * from the copyright notice.
2787 * This will display between the save button and the edit tools,
2788 * so should remain short!
2790 protected function showTosSummary() {
2791 $msg = 'editpage-tos-summary';
2792 wfRunHooks( 'EditPageTosSummary', array( $this->getTitle(), &$msg ) );
2794 $context = $this->getArticle()->getContext();
2795 if ( !$context->msg( $msg )->isDisabled() ) {
2796 $out = $context->getOutput();
2798 $out->addHTML( '<div class="mw-tos-summary">' );
2799 $out->addWikiMsg( $msg );
2800 $out->addHTML( '</div>' );
2804 protected function showEditTools() {
2805 $context = $this->getArticle()->getContext();
2806 $context->getOutput()->addHTML( '<div class="mw-editTools">' .
2807 $context->msg( 'edittools' )->inContentLanguage()->parse() .
2812 * Get the copyright warning
2814 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2816 protected function getCopywarn() {
2817 return self
::getCopyrightWarning( $this->getTitle() );
2820 public static function getCopyrightWarning( $title ) {
2821 global $wgRightsText;
2823 if ( $wgRightsText ) {
2824 $copywarnMsg = array( 'copyrightwarning',
2825 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2828 $copywarnMsg = array( 'copyrightwarning2',
2829 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2831 // Allow for site and per-namespace customization of contribution/copyright notice.
2832 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2834 return "<div id=\"editpage-copywarn\">\n" .
2835 call_user_func_array( 'wfMessage', $copywarnMsg )->plain() . "\n</div>";
2838 protected function showStandardInputs( &$tabindex = 2 ) {
2839 $context = $this->getArticle()->getContext();
2840 $out = $context->getOutput();
2842 $out->addHTML( "<div class='editOptions'>\n" );
2844 if ( $this->section
!= 'new' ) {
2845 $this->showSummaryInput( false, $this->summary
);
2846 $out->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2849 $checkboxes = $this->getCheckboxes( $tabindex,
2850 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2851 $out->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2853 // Show copyright warning.
2854 $out->addWikiText( $this->getCopywarn() );
2855 $out->addHTML( $this->editFormTextAfterWarn
);
2857 $out->addHTML( "<div class='editButtons'>\n" );
2858 $out->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2860 $cancel = $this->getCancelLink();
2861 if ( $cancel !== '' ) {
2862 $cancel .= $context->msg( 'pipe-separator' )->text();
2864 $edithelpurl = Skin
::makeInternalOrExternalUrl(
2865 $context->msg( 'edithelppage' )->inContentLanguage()->text()
2867 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2868 $context->msg( 'edithelp' )->escaped() . '</a> ' .
2869 $context->msg( 'newwindow' )->parse();
2870 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
2871 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
2872 $out->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2876 * Show an edit conflict. textbox1 is already shown in showEditForm().
2877 * If you want to use another entry point to this function, be careful.
2879 protected function showConflict() {
2880 $context = $this->getArticle()->getContext();
2881 $out = $context->getOutput();
2883 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$out ) ) ) {
2884 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2886 $content1 = $this->toEditContent( $this->textbox1
);
2887 $content2 = $this->toEditContent( $this->textbox2
);
2889 $handler = ContentHandler
::getForModelID( $this->contentModel
);
2890 $de = $handler->createDifferenceEngine( $context );
2891 $de->setContent( $content2, $content1 );
2893 $context->msg( 'yourtext' )->parse(),
2894 $context->msg( 'storedversion' )->text()
2897 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2898 $this->showTextbox2();
2905 public function getCancelLink() {
2906 $cancelParams = array();
2907 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2908 $cancelParams['oldid'] = $this->oldid
;
2911 return Linker
::linkKnown(
2912 $this->getContextTitle(),
2913 $this->getArticle()->getContext()->msg( 'cancel' )->parse(),
2914 array( 'id' => 'mw-editform-cancel' ),
2920 * Returns the URL to use in the form's action attribute.
2921 * This is used by EditPage subclasses when simply customizing the action
2922 * variable in the constructor is not enough. This can be used when the
2923 * EditPage lives inside of a Special page rather than a custom page action.
2925 * @param $title Title object for which is being edited (where we go to for &action= links)
2928 protected function getActionURL( Title
$title ) {
2929 return $title->getLocalURL( array( 'action' => $this->action
) );
2933 * Check if a page was deleted while the user was editing it, before submit.
2934 * Note that we rely on the logging table, which hasn't been always there,
2935 * but that doesn't matter, because this only applies to brand new
2938 protected function wasDeletedSinceLastEdit() {
2939 if ( $this->deletedSinceEdit
!== null ) {
2940 return $this->deletedSinceEdit
;
2943 $this->deletedSinceEdit
= false;
2945 if ( $this->getTitle()->isDeletedQuick() ) {
2946 $this->lastDelete
= $this->getLastDelete();
2947 if ( $this->lastDelete
) {
2948 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2949 if ( $deleteTime > $this->starttime
) {
2950 $this->deletedSinceEdit
= true;
2955 return $this->deletedSinceEdit
;
2958 protected function getLastDelete() {
2959 $dbr = wfGetDB( DB_SLAVE
);
2960 $title = $this->getTitle();
2962 $data = $dbr->selectRow(
2963 array( 'logging', 'user' ),
2974 array( 'log_namespace' => $title->getNamespace(),
2975 'log_title' => $title->getDBkey(),
2976 'log_type' => 'delete',
2977 'log_action' => 'delete',
2978 'user_id=log_user' ),
2980 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2982 // Quick paranoid permission checks...
2983 if ( is_object( $data ) ) {
2984 $context = $this->getArticle()->getContext();
2985 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
2986 $data->user_name
= $context->msg( 'rev-deleted-user' )->escaped();
2989 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
2990 $data->log_comment
= $context->msg( 'rev-deleted-comment' )->escaped();
2998 * Get the rendered text for previewing.
2999 * @throws MWException
3002 function getPreviewText() {
3005 wfProfileIn( __METHOD__
);
3007 $context = $this->getArticle()->getContext();
3008 $out = $context->getOutput();
3009 $title = $this->getTitle();
3011 if ( $wgRawHtml && !$this->mTokenOk
) {
3012 // Could be an offsite preview attempt. This is very unsafe if
3013 // HTML is enabled, as it could be an attack.
3015 if ( $this->textbox1
!== '' ) {
3016 // Do not put big scary notice, if previewing the empty
3017 // string, which happens when you initially edit
3018 // a category page, due to automatic preview-on-open.
3019 $parsedNote = $out->parse( "<div class='previewnote'>" .
3020 $context->msg( 'session_fail_preview_html' )->text() .
3021 "</div>", true, /* interface */true );
3023 wfProfileOut( __METHOD__
);
3030 $content = $this->toEditContent( $this->textbox1
);
3032 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3033 if ( $this->mTokenOkExceptSuffix
) {
3034 $note = $context->msg( 'token_suffix_mismatch' )->plain() ;
3037 $note = $context->msg( 'session_fail_preview' )->plain() ;
3039 } elseif ( $this->incompleteForm
) {
3040 $note = $context->msg( 'edit_form_incomplete' )->plain() ;
3042 $note = $context->msg( 'previewnote' )->plain() .
3043 ' [[#' . self
::EDITFORM_ID
. '|' . $context->getLanguage()->getArrow() . ' ' .
3044 $context->msg( 'continue-editing' )->text() . ']]';
3047 $parserOptions = $this->getAticle()->makeParserOptions( $context );
3048 $parserOptions->setEditSection( false );
3049 $parserOptions->setIsPreview( true );
3050 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
3052 # don't parse non-wikitext pages, show message about preview
3053 if ( $title->isCssJsSubpage() ||
$title->isCssOrJsPage() ) {
3054 if( $title->isCssJsSubpage() ) {
3056 } elseif( $title->isCssOrJsPage() ) {
3062 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3064 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3070 # Used messages to make sure grep find them:
3071 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3072 if( $level && $format ) {
3073 $note = "<div id='mw-{$level}{$format}preview'>" .
3074 $context->msg( "{$level}{$format}preview" )->text() .
3079 $rt = $content->getRedirectChain();
3081 $previewHTML = $this->getArticle()->viewRedirect( $rt, false );
3083 # If we're adding a comment, we need to show the
3084 # summary as the headline
3085 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3086 $content = $content->addSectionHeader( $this->summary
);
3089 $hook_args = array( $this, &$content );
3090 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3091 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3093 $parserOptions->enableLimitReport();
3095 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3096 # But it's now deprecated, so never mind
3098 $content = $content->preSaveTransform( $title, $context->getUser(), $parserOptions );
3099 $parserOutput = $content->getParserOutput( $title, null, $parserOptions );
3101 $previewHTML = $parserOutput->getText();
3102 $this->mParserOutput
= $parserOutput;
3103 $out->addParserOutputNoText( $parserOutput );
3105 if ( count( $parserOutput->getWarnings() ) ) {
3106 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3109 } catch ( MWContentSerializationException
$ex ) {
3110 $m = $context->msg('content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
3111 $note .= "\n\n" . $m->parse();
3115 if ( $this->isConflict
) {
3116 $conflict = '<h2 id="mw-previewconflict">' . $context->msg( 'previewconflict' )->escaped() . "</h2>\n";
3118 $conflict = '<hr />';
3121 $previewhead = "<div class='previewnote'>\n" .
3122 '<h2 id="mw-previewheader">' . $context->msg( 'preview' )->escaped() . "</h2>" .
3123 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3125 $pageLang = $title->getPageLanguage();
3126 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
3127 'class' => 'mw-content-' . $pageLang->getDir() );
3128 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3130 wfProfileOut( __METHOD__
);
3131 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3137 function getTemplates() {
3138 if ( $this->preview ||
$this->section
!= '' ) {
3139 $templates = array();
3140 if ( !isset( $this->mParserOutput
) ) {
3143 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3144 foreach ( array_keys( $template ) as $dbk ) {
3145 $templates[] = Title
::makeTitle( $ns, $dbk );
3150 return $this->getTitle()->getTemplateLinksFrom();
3155 * Shows a bulletin board style toolbar for common editing functions.
3156 * It can be disabled in the user preferences.
3157 * The necessary JavaScript code can be found in skins/common/edit.js.
3161 static function getEditToolbar() {
3162 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3163 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
3165 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3168 * $toolarray is an array of arrays each of which includes the
3169 * filename of the button image (without path), the opening
3170 * tag, the closing tag, optionally a sample text that is
3171 * inserted between the two when no selection is highlighted
3172 * and. The tip text is shown when the user moves the mouse
3175 * Also here: accesskeys (key), which are not used yet until
3176 * someone can figure out a way to make them work in
3177 * IE. However, we should make sure these keys are not defined
3182 'image' => $wgLang->getImageFile( 'button-bold' ),
3183 'id' => 'mw-editbutton-bold',
3185 'close' => '\'\'\'',
3186 'sample' => wfMessage( 'bold_sample' )->text(),
3187 'tip' => wfMessage( 'bold_tip' )->text(),
3191 'image' => $wgLang->getImageFile( 'button-italic' ),
3192 'id' => 'mw-editbutton-italic',
3195 'sample' => wfMessage( 'italic_sample' )->text(),
3196 'tip' => wfMessage( 'italic_tip' )->text(),
3200 'image' => $wgLang->getImageFile( 'button-link' ),
3201 'id' => 'mw-editbutton-link',
3204 'sample' => wfMessage( 'link_sample' )->text(),
3205 'tip' => wfMessage( 'link_tip' )->text(),
3209 'image' => $wgLang->getImageFile( 'button-extlink' ),
3210 'id' => 'mw-editbutton-extlink',
3213 'sample' => wfMessage( 'extlink_sample' )->text(),
3214 'tip' => wfMessage( 'extlink_tip' )->text(),
3218 'image' => $wgLang->getImageFile( 'button-headline' ),
3219 'id' => 'mw-editbutton-headline',
3222 'sample' => wfMessage( 'headline_sample' )->text(),
3223 'tip' => wfMessage( 'headline_tip' )->text(),
3226 $imagesAvailable ?
array(
3227 'image' => $wgLang->getImageFile( 'button-image' ),
3228 'id' => 'mw-editbutton-image',
3229 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3231 'sample' => wfMessage( 'image_sample' )->text(),
3232 'tip' => wfMessage( 'image_tip' )->text(),
3235 $imagesAvailable ?
array(
3236 'image' => $wgLang->getImageFile( 'button-media' ),
3237 'id' => 'mw-editbutton-media',
3238 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3240 'sample' => wfMessage( 'media_sample' )->text(),
3241 'tip' => wfMessage( 'media_tip' )->text(),
3245 'image' => $wgLang->getImageFile( 'button-math' ),
3246 'id' => 'mw-editbutton-math',
3248 'close' => "</math>",
3249 'sample' => wfMessage( 'math_sample' )->text(),
3250 'tip' => wfMessage( 'math_tip' )->text(),
3254 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3255 'id' => 'mw-editbutton-nowiki',
3256 'open' => "<nowiki>",
3257 'close' => "</nowiki>",
3258 'sample' => wfMessage( 'nowiki_sample' )->text(),
3259 'tip' => wfMessage( 'nowiki_tip' )->text(),
3263 'image' => $wgLang->getImageFile( 'button-sig' ),
3264 'id' => 'mw-editbutton-signature',
3268 'tip' => wfMessage( 'sig_tip' )->text(),
3272 'image' => $wgLang->getImageFile( 'button-hr' ),
3273 'id' => 'mw-editbutton-hr',
3274 'open' => "\n----\n",
3277 'tip' => wfMessage( 'hr_tip' )->text(),
3282 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3283 foreach ( $toolarray as $tool ) {
3289 $image = $wgStylePath . '/common/images/' . $tool['image'],
3290 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3291 // Older browsers show a "speedtip" type message only for ALT.
3292 // Ideally these should be different, realistically they
3293 // probably don't need to be.
3294 $tip = $tool['tip'],
3295 $open = $tool['open'],
3296 $close = $tool['close'],
3297 $sample = $tool['sample'],
3298 $cssId = $tool['id'],
3301 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3304 // This used to be called on DOMReady from mediawiki.action.edit, which
3305 // ended up causing race conditions with the setup code above.
3307 "// Create button bar\n" .
3308 "$(function() { mw.toolbar.init(); } );\n";
3311 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3313 $toolbar = '<div id="toolbar"></div>';
3315 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3321 * Returns an array of html code of the following checkboxes:
3324 * @param $tabindex int Current tabindex
3325 * @param $checked Array of checkbox => bool, where bool indicates the checked
3326 * status of the checkbox
3330 public function getCheckboxes( &$tabindex, $checked ) {
3331 $checkboxes = array();
3332 $context = $this->getArticle()->getContext();
3333 $user = $context->getUser();
3335 // don't show the minor edit checkbox if it's a new page or section
3336 if ( !$this->isNew
) {
3337 $checkboxes['minor'] = '';
3338 $minorLabel = $context->msg( 'minoredit' )->parse();
3339 if ( $user->isAllowed( 'minoredit' ) ) {
3341 'tabindex' => ++
$tabindex,
3342 'accesskey' => $context->msg( 'accesskey-minoredit' )->text(),
3343 'id' => 'wpMinoredit',
3345 $checkboxes['minor'] =
3346 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3347 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3348 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3349 ">{$minorLabel}</label>";
3353 $watchLabel = $context->msg( 'watchthis' )->parse();
3354 $checkboxes['watch'] = '';
3356 if ( $user->isLoggedIn() ) {
3358 'tabindex' => ++
$tabindex,
3359 'accesskey' => $context->msg( 'accesskey-watch' )->text(),
3360 'id' => 'wpWatchthis',
3362 $checkboxes['watch'] =
3363 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3364 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3365 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3366 ">{$watchLabel}</label>";
3369 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3375 * Returns an array of html code of the following buttons:
3376 * save, diff, preview and live
3378 * @param $tabindex int Current tabindex
3382 public function getEditButtons( &$tabindex ) {
3384 $context = $this->getArticle()->getContext();
3390 'tabindex' => ++
$tabindex,
3391 'value' => $context->msg( 'savearticle' )->text(),
3392 'accesskey' => $context->msg( 'accesskey-save' )->text(),
3393 'title' => $context->msg( 'tooltip-save' )->text() . ' [' . $context->msg( 'accesskey-save' )->text() . ']',
3395 $buttons['save'] = Xml
::element( 'input', $temp, '' );
3397 ++
$tabindex; // use the same for preview and live preview
3399 'id' => 'wpPreview',
3400 'name' => 'wpPreview',
3402 'tabindex' => $tabindex,
3403 'value' => $context->msg( 'showpreview' )->text(),
3404 'accesskey' => $context->msg( 'accesskey-preview' )->text(),
3405 'title' => $context->msg( 'tooltip-preview' )->text() . ' [' . $context->msg( 'accesskey-preview' )->text() . ']',
3407 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3408 $buttons['live'] = '';
3414 'tabindex' => ++
$tabindex,
3415 'value' => $context->msg( 'showdiff' )->text(),
3416 'accesskey' => $context->msg( 'accesskey-diff' )->text(),
3417 'title' => $context->msg( 'tooltip-diff' )->text() . ' [' . $context->msg( 'accesskey-diff' )->text() . ']',
3419 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3421 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3426 * Output preview text only. This can be sucked into the edit page
3427 * via JavaScript, and saves the server time rendering the skin as
3428 * well as theoretically being more robust on the client (doesn't
3429 * disturb the edit box's undo history, won't eat your text on
3432 * @todo This doesn't include category or interlanguage links.
3433 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3434 * or something...</s>" that might also require more skin
3435 * initialization, so check whether that's a problem.
3437 function livePreview() {
3438 $this->getArticle()->getContext()->getOutput()->disable();
3439 header( 'Content-type: text/xml; charset=utf-8' );
3440 header( 'Cache-control: no-cache' );
3442 $previewText = $this->getPreviewText();
3443 #$categories = $skin->getCategoryLinks();
3446 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3447 Xml
::tags( 'livepreview', null,
3448 Xml
::element( 'preview', null, $previewText )
3449 #. Xml::element( 'category', null, $categories )
3455 * Call the stock "user is blocked" page
3457 * @deprecated in 1.19; throw an exception directly instead
3459 function blockedPage() {
3460 wfDeprecated( __METHOD__
, '1.19' );
3461 throw new UserBlockedError( $this->getArticle()->getContext()->getUser()->getBlock() );
3465 * Produce the stock "please login to edit pages" page
3467 * @deprecated in 1.19; throw an exception directly instead
3469 function userNotLoggedInPage() {
3470 wfDeprecated( __METHOD__
, '1.19' );
3471 throw new PermissionsError( 'edit' );
3475 * Show an error page saying to the user that he has insufficient permissions
3476 * to create a new page
3478 * @deprecated in 1.19; throw an exception directly instead
3480 function noCreatePermission() {
3481 wfDeprecated( __METHOD__
, '1.19' );
3482 $permission = $this->getTitle()->isTalkPage() ?
'createtalk' : 'createpage';
3483 throw new PermissionsError( $permission );
3487 * Creates a basic error page which informs the user that
3488 * they have attempted to edit a nonexistent section.
3490 function noSuchSectionPage() {
3491 $context = $this->getArticle()->getContext();
3492 $out = $context->getOutput();
3494 $out->prepareErrorPage( $context->msg( 'nosuchsectiontitle' ) );
3496 $res = $context->msg( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3497 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3499 $out->addHTML( $res );
3500 $out->returnToMain( false, $this->getTitle() );
3504 * Produce the stock "your edit contains spam" page
3506 * @param $match string|bool Text which triggered one or more filters
3507 * @deprecated since 1.17 Use method spamPageWithContent() instead
3509 static function spamPage( $match = false ) {
3510 wfDeprecated( __METHOD__
, '1.17' );
3512 global $wgOut, $wgTitle;
3514 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3516 $wgOut->addHTML( '<div id="spamprotected">' );
3517 $wgOut->addWikiMsg( 'spamprotectiontext' );
3519 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3521 $wgOut->addHTML( '</div>' );
3523 $wgOut->returnToMain( false, $wgTitle );
3527 * Show "your edit contains spam" page with your diff and text
3529 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3531 public function spamPageWithContent( $match = false ) {
3532 $this->textbox2
= $this->textbox1
;
3534 $context = $this->getArticle()->getContext();
3535 if( is_array( $match ) ){
3536 $match = $context->getLanguage()->listToText( $match );
3539 $out = $context->getOutput();
3540 $out->prepareErrorPage( $context->msg( 'spamprotectiontitle' ) );
3542 $out->addHTML( '<div id="spamprotected">' );
3543 $out->addWikiMsg( 'spamprotectiontext' );
3545 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3547 $out->addHTML( '</div>' );
3549 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3552 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3553 $this->showTextbox2();
3555 $out->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3559 * Format an anchor fragment as it would appear for a given section name
3560 * @param $text String
3564 function sectionAnchor( $text ) {
3566 return $wgParser->guessSectionNameFromWikiText( $text );
3570 * Check if the browser is on a blacklist of user-agents known to
3571 * mangle UTF-8 data on form submission. Returns true if Unicode
3572 * should make it through, false if it's known to be a problem.
3576 function checkUnicodeCompliantBrowser() {
3577 global $wgBrowserBlackList, $wgRequest;
3579 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3580 if ( $currentbrowser === false ) {
3581 // No User-Agent header sent? Trust it by default...
3585 foreach ( $wgBrowserBlackList as $browser ) {
3586 if ( preg_match( $browser, $currentbrowser ) ) {
3594 * Filter an input field through a Unicode de-armoring process if it
3595 * came from an old browser with known broken Unicode editing issues.
3597 * @param $request WebRequest
3598 * @param $field String
3602 function safeUnicodeInput( $request, $field ) {
3603 $text = rtrim( $request->getText( $field ) );
3604 return $request->getBool( 'safemode' )
3605 ?
$this->unmakesafe( $text )
3610 * @param $request WebRequest
3611 * @param $text string
3614 function safeUnicodeText( $request, $text ) {
3615 $text = rtrim( $text );
3616 return $request->getBool( 'safemode' )
3617 ?
$this->unmakesafe( $text )
3622 * Filter an output field through a Unicode armoring process if it is
3623 * going to an old browser with known broken Unicode editing issues.
3625 * @param $text String
3629 function safeUnicodeOutput( $text ) {
3631 $codedText = $wgContLang->recodeForEdit( $text );
3632 return $this->checkUnicodeCompliantBrowser()
3634 : $this->makesafe( $codedText );
3638 * A number of web browsers are known to corrupt non-ASCII characters
3639 * in a UTF-8 text editing environment. To protect against this,
3640 * detected browsers will be served an armored version of the text,
3641 * with non-ASCII chars converted to numeric HTML character references.
3643 * Preexisting such character references will have a 0 added to them
3644 * to ensure that round-trips do not alter the original data.
3646 * @param $invalue String
3650 function makesafe( $invalue ) {
3651 // Armor existing references for reversability.
3652 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3657 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3658 $bytevalue = ord( $invalue[$i] );
3659 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3660 $result .= chr( $bytevalue );
3662 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3663 $working = $working << 6;
3664 $working +
= ( $bytevalue & 0x3F );
3666 if ( $bytesleft <= 0 ) {
3667 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3669 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3670 $working = $bytevalue & 0x1F;
3672 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3673 $working = $bytevalue & 0x0F;
3675 } else { // 1111 0xxx
3676 $working = $bytevalue & 0x07;
3684 * Reverse the previously applied transliteration of non-ASCII characters
3685 * back to UTF-8. Used to protect data from corruption by broken web browsers
3686 * as listed in $wgBrowserBlackList.
3688 * @param $invalue String
3692 function unmakesafe( $invalue ) {
3694 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3695 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3699 $hexstring .= $invalue[$i];
3701 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3703 // Do some sanity checks. These aren't needed for reversability,
3704 // but should help keep the breakage down if the editor
3705 // breaks one of the entities whilst editing.
3706 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3707 $codepoint = hexdec( $hexstring );
3708 $result .= codepointToUtf8( $codepoint );
3710 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3713 $result .= substr( $invalue, $i, 1 );
3716 // reverse the transform that we made for reversability reasons.
3717 return strtr( $result, array( "�" => "&#x" ) );