3 * Page edition user interface.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * The edit page/HTML interface (split from Article)
25 * The actual database and text munging is still in Article,
26 * but it should get easier to call those from alternate
29 * EditPage cares about two distinct titles:
30 * $this->mContextTitle is the page that forms submit to, links point to,
31 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
32 * page in the database that is actually being edited. These are
33 * usually the same, but they are now allowed to be different.
35 * Surgeon General's Warning: prolonged exposure to this class is known to cause
36 * headaches, which may be fatal.
41 * Status: Article successfully updated
43 const AS_SUCCESS_UPDATE
= 200;
46 * Status: Article successfully created
48 const AS_SUCCESS_NEW_ARTICLE
= 201;
51 * Status: Article update aborted by a hook function
53 const AS_HOOK_ERROR
= 210;
56 * Status: A hook function returned an error
58 const AS_HOOK_ERROR_EXPECTED
= 212;
61 * Status: User is blocked from editting this page
63 const AS_BLOCKED_PAGE_FOR_USER
= 215;
66 * Status: Content too big (> $wgMaxArticleSize)
68 const AS_CONTENT_TOO_BIG
= 216;
71 * Status: User cannot edit? (not used)
73 const AS_USER_CANNOT_EDIT
= 217;
76 * Status: this anonymous user is not allowed to edit this page
78 const AS_READ_ONLY_PAGE_ANON
= 218;
81 * Status: this logged in user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_LOGGED
= 219;
86 * Status: wiki is in readonly mode (wfReadOnly() == true)
88 const AS_READ_ONLY_PAGE
= 220;
91 * Status: rate limiter for action 'edit' was tripped
93 const AS_RATE_LIMITED
= 221;
96 * Status: article was deleted while editting and param wpRecreate == false or form
99 const AS_ARTICLE_WAS_DELETED
= 222;
102 * Status: user tried to create this page, but is not allowed to do that
103 * ( Title->usercan('create') == false )
105 const AS_NO_CREATE_PERMISSION
= 223;
108 * Status: user tried to create a blank page
110 const AS_BLANK_ARTICLE
= 224;
113 * Status: (non-resolvable) edit conflict
115 const AS_CONFLICT_DETECTED
= 225;
118 * Status: no edit summary given and the user has forceeditsummary set and the user is not
119 * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
121 const AS_SUMMARY_NEEDED
= 226;
124 * Status: user tried to create a new section without content
126 const AS_TEXTBOX_EMPTY
= 228;
129 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
131 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
139 * Status: WikiPage::doEdit() was unsuccessfull
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
146 const AS_SPAM_ERROR
= 232;
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
151 const AS_IMAGE_REDIRECT_ANON
= 233;
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
156 const AS_IMAGE_REDIRECT_LOGGED
= 234;
159 * Status: can't parse content
161 const AS_PARSE_ERROR
= 240;
164 * HTML id and name for the beginning of the edit form.
166 const EDITFORM_ID
= 'editform';
177 private $mContextTitle = null;
178 var $action = 'submit';
179 var $isConflict = false;
180 var $isCssJsSubpage = false;
181 var $isCssSubpage = false;
182 var $isJsSubpage = false;
183 var $isWrongCaseCssJsPage = false;
184 var $isNew = false; // new page or new section
185 var $deletedSinceEdit;
189 var $mTokenOk = false;
190 var $mTokenOkExceptSuffix = false;
191 var $mTriedSave = false;
192 var $incompleteForm = false;
194 var $kblength = false;
195 var $missingComment = false;
196 var $missingSummary = false;
197 var $allowBlankSummary = false;
200 #var $mPreviewTemplates;
208 * Has a summary been preset using GET parameter &summary= ?
211 var $hasPresetSummary = false;
213 var $mBaseRevision = false;
214 var $mShowSummaryField = true;
217 var $save = false, $preview = false, $diff = false;
218 var $minoredit = false, $watchthis = false, $recreate = false;
219 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
220 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
221 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
222 var $contentModel = null, $contentFormat = null;
224 # Placeholders for text injection by hooks (must be HTML)
225 # extensions should take care to _append_ to the present value
226 public $editFormPageTop = ''; // Before even the preview
227 public $editFormTextTop = '';
228 public $editFormTextBeforeContent = '';
229 public $editFormTextAfterWarn = '';
230 public $editFormTextAfterTools = '';
231 public $editFormTextBottom = '';
232 public $editFormTextAfterContent = '';
233 public $previewTextAfterContent = '';
234 public $mPreloadContent = null;
236 /* $didSave should be set to true whenever an article was succesfully altered. */
237 public $didSave = false;
238 public $undidRev = 0;
240 public $suppressIntro = false;
243 * Set to true to allow editing of non-text content types.
247 public $allowNonTextContent = false;
250 * @param $article Article
252 public function __construct( Article
$article ) {
253 $this->mArticle
= $article;
254 $this->mTitle
= $article->getTitle();
256 $this->contentModel
= $this->mTitle
->getContentModel();
258 $handler = ContentHandler
::getForModelID( $this->contentModel
);
259 $this->contentFormat
= $handler->getDefaultFormat();
265 public function getArticle() {
266 return $this->mArticle
;
273 public function getTitle() {
274 return $this->mTitle
;
278 * Set the context Title object
280 * @param $title Title object or null
282 public function setContextTitle( $title ) {
283 $this->mContextTitle
= $title;
287 * Get the context title object.
288 * If not set, $wgTitle will be returned. This behavior might change in
289 * the future to return $this->mTitle instead.
291 * @return Title object
293 public function getContextTitle() {
294 if ( is_null( $this->mContextTitle
) ) {
298 return $this->mContextTitle
;
307 * This is the function that gets called for "action=edit". It
308 * sets up various member variables, then passes execution to
309 * another function, usually showEditForm()
311 * The edit form is self-submitting, so that when things like
312 * preview and edit conflicts occur, we get the same form back
313 * with the extra stuff added. Only when the final submission
314 * is made and all is well do we actually save and redirect to
315 * the newly-edited page.
318 global $wgOut, $wgRequest, $wgUser;
319 // Allow extensions to modify/prevent this form or submission
320 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
324 wfProfileIn( __METHOD__
);
325 wfDebug( __METHOD__
. ": enter\n" );
327 // If they used redlink=1 and the page exists, redirect to the main article
328 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
329 $wgOut->redirect( $this->mTitle
->getFullURL() );
330 wfProfileOut( __METHOD__
);
334 $this->importFormData( $wgRequest );
335 $this->firsttime
= false;
338 $this->livePreview();
339 wfProfileOut( __METHOD__
);
343 if ( wfReadOnly() && $this->save
) {
346 $this->preview
= true;
350 $this->formtype
= 'save';
351 } elseif ( $this->preview
) {
352 $this->formtype
= 'preview';
353 } elseif ( $this->diff
) {
354 $this->formtype
= 'diff';
355 } else { # First time through
356 $this->firsttime
= true;
357 if ( $this->previewOnOpen() ) {
358 $this->formtype
= 'preview';
360 $this->formtype
= 'initial';
364 $permErrors = $this->getEditPermissionErrors();
366 wfDebug( __METHOD__
. ": User can't edit\n" );
367 // Auto-block user's IP if the account was "hard" blocked
368 $wgUser->spreadAnyEditBlock();
370 $this->displayPermissionsError( $permErrors );
372 wfProfileOut( __METHOD__
);
376 wfProfileIn( __METHOD__
. "-business-end" );
378 $this->isConflict
= false;
379 // css / js subpages of user pages get a special treatment
380 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
381 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
382 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
383 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
385 # Show applicable editing introductions
386 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
390 # Attempt submission here. This will check for edit conflicts,
391 # and redundantly check for locked database, blocked IPs, etc.
392 # that edit() already checked just in case someone tries to sneak
393 # in the back door with a hand-edited submission URL.
395 if ( 'save' == $this->formtype
) {
396 if ( !$this->attemptSave() ) {
397 wfProfileOut( __METHOD__
. "-business-end" );
398 wfProfileOut( __METHOD__
);
403 # First time through: get contents, set time for conflict
405 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
406 if ( $this->initialiseForm() === false ) {
407 $this->noSuchSectionPage();
408 wfProfileOut( __METHOD__
. "-business-end" );
409 wfProfileOut( __METHOD__
);
413 if ( !$this->mTitle
->getArticleID() ) {
414 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
416 wfRunHooks( 'EditFormInitialText', array( $this ) );
421 $this->showEditForm();
422 wfProfileOut( __METHOD__
. "-business-end" );
423 wfProfileOut( __METHOD__
);
429 protected function getEditPermissionErrors() {
431 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
432 # Can this title be created?
433 if ( !$this->mTitle
->exists() ) {
434 $permErrors = array_merge( $permErrors,
435 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
437 # Ignore some permissions errors when a user is just previewing/viewing diffs
439 foreach ( $permErrors as $error ) {
440 if ( ( $this->preview ||
$this->diff
) &&
441 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
446 $permErrors = wfArrayDiff2( $permErrors, $remove );
451 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
452 * but with the following differences:
453 * - If redlink=1, the user will be redirected to the page
454 * - If there is content to display or the error occurs while either saving,
455 * previewing or showing the difference, it will be a
456 * "View source for ..." page displaying the source code after the error message.
459 * @param $permErrors Array of permissions errors, as returned by
460 * Title::getUserPermissionsErrors().
461 * @throws PermissionsError
463 protected function displayPermissionsError( array $permErrors ) {
464 global $wgRequest, $wgOut;
466 if ( $wgRequest->getBool( 'redlink' ) ) {
467 // The edit page was reached via a red link.
468 // Redirect to the article page and let them click the edit tab if
469 // they really want a permission error.
470 $wgOut->redirect( $this->mTitle
->getFullUrl() );
474 $content = $this->getContentObject();
476 # Use the normal message if there's nothing to display
477 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
478 $action = $this->mTitle
->exists() ?
'edit' :
479 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
480 throw new PermissionsError( $action, $permErrors );
483 $wgOut->setRobotPolicy( 'noindex,nofollow' );
484 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
485 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
486 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
487 $wgOut->addHTML( "<hr />\n" );
489 # If the user made changes, preserve them when showing the markup
490 # (This happens when a user is blocked during edit, for instance)
491 if ( !$this->firsttime
) {
492 $text = $this->textbox1
;
493 $wgOut->addWikiMsg( 'viewyourtext' );
495 $text = $this->toEditText( $content );
496 $wgOut->addWikiMsg( 'viewsourcetext' );
499 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
501 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
502 Linker
::formatTemplates( $this->getTemplates() ) ) );
504 if ( $this->mTitle
->exists() ) {
505 $wgOut->returnToMain( null, $this->mTitle
);
510 * Show a read-only error
511 * Parameters are the same as OutputPage:readOnlyPage()
512 * Redirect to the article page if redlink=1
513 * @deprecated in 1.19; use displayPermissionsError() instead
515 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
516 wfDeprecated( __METHOD__
, '1.19' );
518 global $wgRequest, $wgOut;
519 if ( $wgRequest->getBool( 'redlink' ) ) {
520 // The edit page was reached via a red link.
521 // Redirect to the article page and let them click the edit tab if
522 // they really want a permission error.
523 $wgOut->redirect( $this->mTitle
->getFullUrl() );
525 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
530 * Should we show a preview when the edit form is first shown?
534 protected function previewOnOpen() {
535 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
536 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
537 // Explicit override from request
539 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
540 // Explicit override from request
542 } elseif ( $this->section
== 'new' ) {
543 // Nothing *to* preview for new sections
545 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
546 // Standard preference behaviour
548 } elseif ( !$this->mTitle
->exists() &&
549 isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] ) &&
550 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
552 // Categories are special
560 * Checks whether the user entered a skin name in uppercase,
561 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
565 protected function isWrongCaseCssJsPage() {
566 if ( $this->mTitle
->isCssJsSubpage() ) {
567 $name = $this->mTitle
->getSkinFromCssJsSubpage();
568 $skins = array_merge(
569 array_keys( Skin
::getSkinNames() ),
572 return !in_array( $name, $skins )
573 && in_array( strtolower( $name ), $skins );
580 * Does this EditPage class support section editing?
581 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
585 protected function isSectionEditSupported() {
590 * This function collects the form data and uses it to populate various member variables.
591 * @param $request WebRequest
593 function importFormData( &$request ) {
594 global $wgContLang, $wgUser;
596 wfProfileIn( __METHOD__
);
598 # Section edit can come from either the form or a link
599 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
600 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
602 if ( $request->wasPosted() ) {
603 # These fields need to be checked for encoding.
604 # Also remove trailing whitespace, but don't remove _initial_
605 # whitespace from the text boxes. This may be significant formatting.
606 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
607 if ( !$request->getCheck( 'wpTextbox2' ) ) {
608 // Skip this if wpTextbox2 has input, it indicates that we came
609 // from a conflict page with raw page text, not a custom form
610 // modified by subclasses
611 wfProfileIn( get_class( $this ) . "::importContentFormData" );
612 $textbox1 = $this->importContentFormData( $request );
613 if ( $textbox1 !== null ) {
614 $this->textbox1
= $textbox1;
617 wfProfileOut( get_class( $this ) . "::importContentFormData" );
620 # Truncate for whole multibyte characters
621 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
623 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
624 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
626 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
628 # Treat sectiontitle the same way as summary.
629 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
630 # currently doing double duty as both edit summary and section title. Right now this
631 # is just to allow API edits to work around this limitation, but this should be
632 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
633 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
634 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
636 $this->edittime
= $request->getVal( 'wpEdittime' );
637 $this->starttime
= $request->getVal( 'wpStarttime' );
639 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
641 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
642 // wpTextbox1 field is missing, possibly due to being "too big"
643 // according to some filter rules such as Suhosin's setting for
644 // suhosin.request.max_value_length (d'oh)
645 $this->incompleteForm
= true;
647 // edittime should be one of our last fields; if it's missing,
648 // the submission probably broke somewhere in the middle.
649 $this->incompleteForm
= is_null( $this->edittime
);
651 if ( $this->incompleteForm
) {
652 # If the form is incomplete, force to preview.
653 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
654 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
655 $this->preview
= true;
657 /* Fallback for live preview */
658 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
659 $this->diff
= $request->getCheck( 'wpDiff' );
661 // Remember whether a save was requested, so we can indicate
662 // if we forced preview due to session failure.
663 $this->mTriedSave
= !$this->preview
;
665 if ( $this->tokenOk( $request ) ) {
666 # Some browsers will not report any submit button
667 # if the user hits enter in the comment box.
668 # The unmarked state will be assumed to be a save,
669 # if the form seems otherwise complete.
670 wfDebug( __METHOD__
. ": Passed token check.\n" );
671 } elseif ( $this->diff
) {
672 # Failed token check, but only requested "Show Changes".
673 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
675 # Page might be a hack attempt posted from
676 # an external site. Preview instead of saving.
677 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
678 $this->preview
= true;
681 $this->save
= !$this->preview
&& !$this->diff
;
682 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
683 $this->edittime
= null;
686 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
687 $this->starttime
= null;
690 $this->recreate
= $request->getCheck( 'wpRecreate' );
692 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
693 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
695 # Don't force edit summaries when a user is editing their own user or talk page
696 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
697 $this->mTitle
->getText() == $wgUser->getName() )
699 $this->allowBlankSummary
= true;
701 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary' );
704 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
706 # Not a posted form? Start with nothing.
707 wfDebug( __METHOD__
. ": Not a posted form.\n" );
708 $this->textbox1
= '';
710 $this->sectiontitle
= '';
711 $this->edittime
= '';
712 $this->starttime
= wfTimestampNow();
714 $this->preview
= false;
717 $this->minoredit
= false;
718 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
719 $this->recreate
= false;
721 // When creating a new section, we can preload a section title by passing it as the
722 // preloadtitle parameter in the URL (Bug 13100)
723 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
724 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
725 // Once wpSummary isn't being use for setting section titles, we should delete this.
726 $this->summary
= $request->getVal( 'preloadtitle' );
728 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
729 $this->summary
= $request->getText( 'summary' );
730 if ( $this->summary
!== '' ) {
731 $this->hasPresetSummary
= true;
735 if ( $request->getVal( 'minor' ) ) {
736 $this->minoredit
= true;
740 $this->oldid
= $request->getInt( 'oldid' );
742 $this->bot
= $request->getBool( 'bot', true );
743 $this->nosummary
= $request->getBool( 'nosummary' );
745 $content_handler = ContentHandler
::getForTitle( $this->mTitle
);
746 $this->contentModel
= $request->getText( 'model', $content_handler->getModelID() ); #may be overridden by revision
747 $this->contentFormat
= $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
749 #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
750 #TODO: check if the desired content model supports the given content format!
752 $this->live
= $request->getCheck( 'live' );
753 $this->editintro
= $request->getText( 'editintro',
754 // Custom edit intro for new sections
755 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
757 // Allow extensions to modify form data
758 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
760 wfProfileOut( __METHOD__
);
764 * Subpage overridable method for extracting the page content data from the
765 * posted form to be placed in $this->textbox1, if using customized input
766 * this method should be overrided and return the page text that will be used
767 * for saving, preview parsing and so on...
769 * @param $request WebRequest
771 protected function importContentFormData( &$request ) {
772 return; // Don't do anything, EditPage already extracted wpTextbox1
776 * Initialise form fields in the object
777 * Called on the first invocation, e.g. when a user clicks an edit link
778 * @return bool -- if the requested section is valid
780 function initialiseForm() {
782 $this->edittime
= $this->mArticle
->getTimestamp();
784 $content = $this->getContentObject( false ); #TODO: track content object?!
785 if ( $content === false ) {
788 $this->textbox1
= $this->toEditText( $content );
790 // activate checkboxes if user wants them to be always active
791 # Sort out the "watch" checkbox
792 if ( $wgUser->getOption( 'watchdefault' ) ) {
794 $this->watchthis
= true;
795 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
797 $this->watchthis
= true;
798 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
800 $this->watchthis
= true;
802 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
803 $this->minoredit
= true;
805 if ( $this->textbox1
=== false ) {
813 * Fetch initial editing page content.
815 * @param $def_text string|bool
816 * @return mixed string on success, $def_text for invalid sections
818 * @deprecated since 1.21, get WikiPage::getContent() instead.
820 function getContent( $def_text = false ) {
821 ContentHandler
::deprecated( __METHOD__
, '1.21' );
823 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
824 $def_content = $this->toEditContent( $def_text );
826 $def_content = false;
829 $content = $this->getContentObject( $def_content );
831 // Note: EditPage should only be used with text based content anyway.
832 return $this->toEditText( $content );
836 * @param Content|null $def_content The default value to return
838 * @return mixed Content on success, $def_content for invalid sections
842 protected function getContentObject( $def_content = null ) {
843 global $wgOut, $wgRequest;
845 wfProfileIn( __METHOD__
);
849 // For message page not locally set, use the i18n message.
850 // For other non-existent articles, use preload text if any.
851 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
852 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
853 # If this is a system message, get the default text.
854 $msg = $this->mTitle
->getDefaultMessageText();
856 $content = $this->toEditContent( $msg );
858 if ( $content === false ) {
859 # If requested, preload some text.
860 $preload = $wgRequest->getVal( 'preload',
861 // Custom preload text for new sections
862 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
864 $content = $this->getPreloadedContent( $preload );
866 // For existing pages, get text based on "undo" or section parameters.
868 if ( $this->section
!= '' ) {
869 // Get section edit text (returns $def_text for invalid sections)
870 $orig = $this->getOriginalContent();
871 $content = $orig ?
$orig->getSection( $this->section
) : null;
873 if ( !$content ) $content = $def_content;
875 $undoafter = $wgRequest->getInt( 'undoafter' );
876 $undo = $wgRequest->getInt( 'undo' );
878 if ( $undo > 0 && $undoafter > 0 ) {
879 if ( $undo < $undoafter ) {
880 # If they got undoafter and undo round the wrong way, switch them
881 list( $undo, $undoafter ) = array( $undoafter, $undo );
884 $undorev = Revision
::newFromId( $undo );
885 $oldrev = Revision
::newFromId( $undoafter );
887 # Sanity check, make sure it's the right page,
888 # the revisions exist and they were not deleted.
889 # Otherwise, $content will be left as-is.
890 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
891 $undorev->getPage() == $oldrev->getPage() &&
892 $undorev->getPage() == $this->mTitle
->getArticleID() &&
893 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
894 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
896 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
898 if ( $content === false ) {
899 # Warn the user that something went wrong
900 $undoMsg = 'failure';
902 # Inform the user of our success and set an automatic edit summary
903 $undoMsg = 'success';
905 # If we just undid one rev, use an autosummary
906 $firstrev = $oldrev->getNext();
907 if ( $firstrev && $firstrev->getId() == $undo ) {
908 $undoSummary = wfMessage( 'undo-summary', $undo, $undorev->getUserText() )->inContentLanguage()->text();
909 if ( $this->summary
=== '' ) {
910 $this->summary
= $undoSummary;
912 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
913 ->inContentLanguage()->text() . $this->summary
;
915 $this->undidRev
= $undo;
917 $this->formtype
= 'diff';
920 // Failed basic sanity checks.
921 // Older revisions may have been removed since the link
922 // was created, or we may simply have got bogus input.
926 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
927 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
928 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
931 if ( $content === false ) {
932 $content = $this->getOriginalContent();
937 wfProfileOut( __METHOD__
);
942 * Get the content of the wanted revision, without section extraction.
944 * The result of this function can be used to compare user's input with
945 * section replaced in its context (using WikiPage::replaceSection())
946 * to the original text of the edit.
948 * This difers from Article::getContent() that when a missing revision is
949 * encountered the result will be null and not the
950 * 'missing-revision' message.
953 * @return Content|null
955 private function getOriginalContent() {
956 if ( $this->section
== 'new' ) {
957 return $this->getCurrentContent();
959 $revision = $this->mArticle
->getRevisionFetched();
960 if ( $revision === null ) {
961 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
962 $handler = ContentHandler
::getForModelID( $this->contentModel
);
964 return $handler->makeEmptyContent();
966 $content = $revision->getContent();
971 * Get the current content of the page. This is basically similar to
972 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
973 * content object is returned instead of null.
978 protected function getCurrentContent() {
979 $rev = $this->mArticle
->getRevision();
980 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
982 if ( $content === false ||
$content === null ) {
983 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
984 $handler = ContentHandler
::getForModelID( $this->contentModel
);
986 return $handler->makeEmptyContent();
988 # nasty side-effect, but needed for consistency
989 $this->contentModel
= $rev->getContentModel();
990 $this->contentFormat
= $rev->getContentFormat();
998 * Use this method before edit() to preload some text into the edit box
1000 * @param $text string
1001 * @deprecated since 1.21, use setPreloadedContent() instead.
1003 public function setPreloadedText( $text ) {
1004 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1006 $content = $this->toEditContent( $text );
1008 $this->setPreloadedContent( $content );
1012 * Use this method before edit() to preload some content into the edit box
1014 * @param $content Content
1018 public function setPreloadedContent( Content
$content ) {
1019 $this->mPreloadContent
= $content;
1023 * Get the contents to be preloaded into the box, either set by
1024 * an earlier setPreloadText() or by loading the given page.
1026 * @param $preload String: representing the title to preload from.
1030 * @deprecated since 1.21, use getPreloadedContent() instead
1032 protected function getPreloadedText( $preload ) {
1033 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1035 $content = $this->getPreloadedContent( $preload );
1036 $text = $this->toEditText( $content );
1042 * Get the contents to be preloaded into the box, either set by
1043 * an earlier setPreloadText() or by loading the given page.
1045 * @param $preload String: representing the title to preload from.
1051 protected function getPreloadedContent( $preload ) {
1054 if ( !empty( $this->mPreloadContent
) ) {
1055 return $this->mPreloadContent
;
1058 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1060 if ( $preload === '' ) {
1061 return $handler->makeEmptyContent();
1064 $title = Title
::newFromText( $preload );
1065 # Check for existence to avoid getting MediaWiki:Noarticletext
1066 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1067 //TODO: somehow show a warning to the user!
1068 return $handler->makeEmptyContent();
1071 $page = WikiPage
::factory( $title );
1072 if ( $page->isRedirect() ) {
1073 $title = $page->getRedirectTarget();
1075 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1076 //TODO: somehow show a warning to the user!
1077 return $handler->makeEmptyContent();
1079 $page = WikiPage
::factory( $title );
1082 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1083 $content = $page->getContent( Revision
::RAW
);
1086 //TODO: somehow show a warning to the user!
1087 return $handler->makeEmptyContent();
1090 if ( $content->getModel() !== $handler->getModelID() ) {
1091 $converted = $content->convert( $handler->getModelID() );
1093 if ( !$converted ) {
1094 //TODO: somehow show a warning to the user!
1095 wfDebug( "Attempt to preload incompatible content: "
1096 . "can't convert " . $content->getModel()
1097 . " to " . $handler->getModelID() );
1099 return $handler->makeEmptyContent();
1102 $content = $converted;
1105 return $content->preloadTransform( $title, $parserOptions );
1109 * Make sure the form isn't faking a user's credentials.
1111 * @param $request WebRequest
1115 function tokenOk( &$request ) {
1117 $token = $request->getVal( 'wpEditToken' );
1118 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1119 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1120 return $this->mTokenOk
;
1124 * Attempt submission
1125 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1126 * @return bool false if output is done, true if the rest of the form should be displayed
1128 function attemptSave() {
1129 global $wgUser, $wgOut;
1131 $resultDetails = false;
1132 # Allow bots to exempt some edits from bot flagging
1133 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1134 $status = $this->internalAttemptSave( $resultDetails, $bot );
1135 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1136 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1137 $this->didSave
= true;
1140 switch ( $status->value
) {
1141 case self
::AS_HOOK_ERROR_EXPECTED
:
1142 case self
::AS_CONTENT_TOO_BIG
:
1143 case self
::AS_ARTICLE_WAS_DELETED
:
1144 case self
::AS_CONFLICT_DETECTED
:
1145 case self
::AS_SUMMARY_NEEDED
:
1146 case self
::AS_TEXTBOX_EMPTY
:
1147 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1151 case self
::AS_HOOK_ERROR
:
1154 case self
::AS_PARSE_ERROR
:
1155 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>');
1158 case self
::AS_SUCCESS_NEW_ARTICLE
:
1159 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1160 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1161 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1164 case self
::AS_SUCCESS_UPDATE
:
1166 $sectionanchor = $resultDetails['sectionanchor'];
1168 // Give extensions a chance to modify URL query on update
1169 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1171 if ( $resultDetails['redirect'] ) {
1172 if ( $extraQuery == '' ) {
1173 $extraQuery = 'redirect=no';
1175 $extraQuery = 'redirect=no&' . $extraQuery;
1178 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1181 case self
::AS_BLANK_ARTICLE
:
1182 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1185 case self
::AS_SPAM_ERROR
:
1186 $this->spamPageWithContent( $resultDetails['spam'] );
1189 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1190 throw new UserBlockedError( $wgUser->getBlock() );
1192 case self
::AS_IMAGE_REDIRECT_ANON
:
1193 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1194 throw new PermissionsError( 'upload' );
1196 case self
::AS_READ_ONLY_PAGE_ANON
:
1197 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1198 throw new PermissionsError( 'edit' );
1200 case self
::AS_READ_ONLY_PAGE
:
1201 throw new ReadOnlyError
;
1203 case self
::AS_RATE_LIMITED
:
1204 throw new ThrottledError();
1206 case self
::AS_NO_CREATE_PERMISSION
:
1207 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1208 throw new PermissionsError( $permission );
1211 // We don't recognize $status->value. The only way that can happen
1212 // is if an extension hook aborted from inside ArticleSave.
1213 // Render the status object into $this->hookError
1214 // FIXME this sucks, we should just use the Status object throughout
1215 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1222 * Attempt submission (no UI)
1227 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1229 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1230 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1231 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1233 function internalAttemptSave( &$result, $bot = false ) {
1234 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1236 $status = Status
::newGood();
1238 wfProfileIn( __METHOD__
);
1239 wfProfileIn( __METHOD__
. '-checks' );
1241 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1242 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1243 $status->fatal( 'hookaborted' );
1244 $status->value
= self
::AS_HOOK_ERROR
;
1245 wfProfileOut( __METHOD__
. '-checks' );
1246 wfProfileOut( __METHOD__
);
1251 # Construct Content object
1252 $textbox_content = $this->toEditContent( $this->textbox1
);
1253 } catch ( MWContentSerializationException
$ex ) {
1254 $status->fatal( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
1255 $status->value
= self
::AS_PARSE_ERROR
;
1256 wfProfileOut( __METHOD__
. '-checks' );
1257 wfProfileOut( __METHOD__
);
1261 # Check image redirect
1262 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1263 $textbox_content->isRedirect() &&
1264 !$wgUser->isAllowed( 'upload' ) ) {
1265 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1266 $status->setResult( false, $code );
1268 wfProfileOut( __METHOD__
. '-checks' );
1269 wfProfileOut( __METHOD__
);
1275 $match = self
::matchSummarySpamRegex( $this->summary
);
1276 if ( $match === false ) {
1277 $match = self
::matchSpamRegex( $this->textbox1
);
1279 if ( $match !== false ) {
1280 $result['spam'] = $match;
1281 $ip = $wgRequest->getIP();
1282 $pdbk = $this->mTitle
->getPrefixedDBkey();
1283 $match = str_replace( "\n", '', $match );
1284 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1285 $status->fatal( 'spamprotectionmatch', $match );
1286 $status->value
= self
::AS_SPAM_ERROR
;
1287 wfProfileOut( __METHOD__
. '-checks' );
1288 wfProfileOut( __METHOD__
);
1291 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1292 # Error messages etc. could be handled within the hook...
1293 $status->fatal( 'hookaborted' );
1294 $status->value
= self
::AS_HOOK_ERROR
;
1295 wfProfileOut( __METHOD__
. '-checks' );
1296 wfProfileOut( __METHOD__
);
1298 } elseif ( $this->hookError
!= '' ) {
1299 # ...or the hook could be expecting us to produce an error
1300 $status->fatal( 'hookaborted' );
1301 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1302 wfProfileOut( __METHOD__
. '-checks' );
1303 wfProfileOut( __METHOD__
);
1307 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1308 // Auto-block user's IP if the account was "hard" blocked
1309 $wgUser->spreadAnyEditBlock();
1310 # Check block state against master, thus 'false'.
1311 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1312 wfProfileOut( __METHOD__
. '-checks' );
1313 wfProfileOut( __METHOD__
);
1317 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1318 if ( $this->kblength
> $wgMaxArticleSize ) {
1319 // Error will be displayed by showEditForm()
1320 $this->tooBig
= true;
1321 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1322 wfProfileOut( __METHOD__
. '-checks' );
1323 wfProfileOut( __METHOD__
);
1327 if ( !$wgUser->isAllowed( 'edit' ) ) {
1328 if ( $wgUser->isAnon() ) {
1329 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1330 wfProfileOut( __METHOD__
. '-checks' );
1331 wfProfileOut( __METHOD__
);
1334 $status->fatal( 'readonlytext' );
1335 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1336 wfProfileOut( __METHOD__
. '-checks' );
1337 wfProfileOut( __METHOD__
);
1342 if ( wfReadOnly() ) {
1343 $status->fatal( 'readonlytext' );
1344 $status->value
= self
::AS_READ_ONLY_PAGE
;
1345 wfProfileOut( __METHOD__
. '-checks' );
1346 wfProfileOut( __METHOD__
);
1349 if ( $wgUser->pingLimiter() ) {
1350 $status->fatal( 'actionthrottledtext' );
1351 $status->value
= self
::AS_RATE_LIMITED
;
1352 wfProfileOut( __METHOD__
. '-checks' );
1353 wfProfileOut( __METHOD__
);
1357 # If the article has been deleted while editing, don't save it without
1359 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1360 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1361 wfProfileOut( __METHOD__
. '-checks' );
1362 wfProfileOut( __METHOD__
);
1366 wfProfileOut( __METHOD__
. '-checks' );
1368 # Load the page data from the master. If anything changes in the meantime,
1369 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1370 $this->mArticle
->loadPageData( 'fromdbmaster' );
1371 $new = !$this->mArticle
->exists();
1374 // Late check for create permission, just in case *PARANOIA*
1375 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1376 $status->fatal( 'nocreatetext' );
1377 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1378 wfDebug( __METHOD__
. ": no create permission\n" );
1379 wfProfileOut( __METHOD__
);
1383 # Don't save a new article if it's blank.
1384 if ( $this->textbox1
== '' ) {
1385 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1386 wfProfileOut( __METHOD__
);
1390 // Run post-section-merge edit filter
1391 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1392 # Error messages etc. could be handled within the hook...
1393 $status->fatal( 'hookaborted' );
1394 $status->value
= self
::AS_HOOK_ERROR
;
1395 wfProfileOut( __METHOD__
);
1397 } elseif ( $this->hookError
!= '' ) {
1398 # ...or the hook could be expecting us to produce an error
1399 $status->fatal( 'hookaborted' );
1400 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1401 wfProfileOut( __METHOD__
);
1405 $content = $textbox_content;
1407 $result['sectionanchor'] = '';
1408 if ( $this->section
== 'new' ) {
1409 if ( $this->sectiontitle
!== '' ) {
1410 // Insert the section title above the content.
1411 $content = $content->addSectionHeader( $this->sectiontitle
);
1413 // Jump to the new section
1414 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1416 // If no edit summary was specified, create one automatically from the section
1417 // title and have it link to the new section. Otherwise, respect the summary as
1419 if ( $this->summary
=== '' ) {
1420 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1421 $this->summary
= wfMessage( 'newsectionsummary' )
1422 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1424 } elseif ( $this->summary
!== '' ) {
1425 // Insert the section title above the content.
1426 $content = $content->addSectionHeader( $this->summary
);
1428 // Jump to the new section
1429 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1431 // Create a link to the new section from the edit summary.
1432 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1433 $this->summary
= wfMessage( 'newsectionsummary' )
1434 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1438 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1442 # Article exists. Check for edit conflict.
1444 $this->mArticle
->clear(); # Force reload of dates, etc.
1445 $timestamp = $this->mArticle
->getTimestamp();
1447 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1449 if ( $timestamp != $this->edittime
) {
1450 $this->isConflict
= true;
1451 if ( $this->section
== 'new' ) {
1452 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1453 $this->mArticle
->getComment() == $this->summary
) {
1454 // Probably a duplicate submission of a new comment.
1455 // This can happen when squid resends a request after
1456 // a timeout but the first one actually went through.
1457 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1459 // New comment; suppress conflict.
1460 $this->isConflict
= false;
1461 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1463 } elseif ( $this->section
== '' && Revision
::userWasLastToEdit( DB_MASTER
, $this->mTitle
->getArticleID(),
1464 $wgUser->getId(), $this->edittime
) ) {
1465 # Suppress edit conflict with self, except for section edits where merging is required.
1466 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1467 $this->isConflict
= false;
1471 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1472 // backwards compatibility with old forms/bots).
1473 if ( $this->sectiontitle
!== '' ) {
1474 $sectionTitle = $this->sectiontitle
;
1476 $sectionTitle = $this->summary
;
1481 if ( $this->isConflict
) {
1482 wfDebug( __METHOD__
. ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1483 . " (article time '{$timestamp}')\n" );
1485 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1487 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1488 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1491 if ( is_null( $content ) ) {
1492 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1493 $this->isConflict
= true;
1494 $content = $textbox_content; // do not try to merge here!
1495 } elseif ( $this->isConflict
) {
1497 if ( $this->mergeChangesIntoContent( $content ) ) {
1498 // Successful merge! Maybe we should tell the user the good news?
1499 $this->isConflict
= false;
1500 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1502 $this->section
= '';
1503 $this->textbox1
= ContentHandler
::getContentText( $content );
1504 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1508 if ( $this->isConflict
) {
1509 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1510 wfProfileOut( __METHOD__
);
1514 // Run post-section-merge edit filter
1515 $hook_args = array( $this, $content, &$this->hookError
, $this->summary
);
1517 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged', $hook_args )
1518 ||
!wfRunHooks( 'EditFilterMergedContent', $hook_args ) ) {
1519 # Error messages etc. could be handled within the hook...
1520 $status->fatal( 'hookaborted' );
1521 $status->value
= self
::AS_HOOK_ERROR
;
1522 wfProfileOut( __METHOD__
);
1524 } elseif ( $this->hookError
!= '' ) {
1525 # ...or the hook could be expecting us to produce an error
1526 $status->fatal( 'hookaborted' );
1527 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1528 wfProfileOut( __METHOD__
);
1532 # Handle the user preference to force summaries here, but not for null edits
1533 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1534 && !$content->equals( $this->getOriginalContent() )
1535 && !$content->isRedirect() ) # check if it's not a redirect
1537 if ( md5( $this->summary
) == $this->autoSumm
) {
1538 $this->missingSummary
= true;
1539 $status->fatal( 'missingsummary' );
1540 $status->value
= self
::AS_SUMMARY_NEEDED
;
1541 wfProfileOut( __METHOD__
);
1546 # And a similar thing for new sections
1547 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1548 if ( trim( $this->summary
) == '' ) {
1549 $this->missingSummary
= true;
1550 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1551 $status->value
= self
::AS_SUMMARY_NEEDED
;
1552 wfProfileOut( __METHOD__
);
1558 wfProfileIn( __METHOD__
. '-sectionanchor' );
1559 $sectionanchor = '';
1560 if ( $this->section
== 'new' ) {
1561 if ( $this->textbox1
== '' ) {
1562 $this->missingComment
= true;
1563 $status->fatal( 'missingcommenttext' );
1564 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1565 wfProfileOut( __METHOD__
. '-sectionanchor' );
1566 wfProfileOut( __METHOD__
);
1569 if ( $this->sectiontitle
!== '' ) {
1570 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1571 // If no edit summary was specified, create one automatically from the section
1572 // title and have it link to the new section. Otherwise, respect the summary as
1574 if ( $this->summary
=== '' ) {
1575 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1576 $this->summary
= wfMessage( 'newsectionsummary' )
1577 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1579 } elseif ( $this->summary
!== '' ) {
1580 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1581 # This is a new section, so create a link to the new section
1582 # in the revision summary.
1583 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1584 $this->summary
= wfMessage( 'newsectionsummary' )
1585 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1587 } elseif ( $this->section
!= '' ) {
1588 # Try to get a section anchor from the section source, redirect to edited section if header found
1589 # XXX: might be better to integrate this into Article::replaceSection
1590 # for duplicate heading checking and maybe parsing
1591 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1592 # we can't deal with anchors, includes, html etc in the header for now,
1593 # headline would need to be parsed to improve this
1594 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1595 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1598 $result['sectionanchor'] = $sectionanchor;
1599 wfProfileOut( __METHOD__
. '-sectionanchor' );
1601 // Save errors may fall down to the edit form, but we've now
1602 // merged the section into full text. Clear the section field
1603 // so that later submission of conflict forms won't try to
1604 // replace that into a duplicated mess.
1605 $this->textbox1
= $this->toEditText( $content );
1606 $this->section
= '';
1608 $status->value
= self
::AS_SUCCESS_UPDATE
;
1611 // Check for length errors again now that the section is merged in
1612 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1613 if ( $this->kblength
> $wgMaxArticleSize ) {
1614 $this->tooBig
= true;
1615 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1616 wfProfileOut( __METHOD__
);
1620 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1621 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1622 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1623 ( $bot ? EDIT_FORCE_BOT
: 0 );
1625 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags,
1626 false, null, $this->contentFormat
);
1628 if ( $doEditStatus->isOK() ) {
1629 $result['redirect'] = $content->isRedirect();
1630 $this->updateWatchlist();
1631 wfProfileOut( __METHOD__
);
1634 // Failure from doEdit()
1635 // Show the edit conflict page for certain recognized errors from doEdit(),
1636 // but don't show it for errors from extension hooks
1637 $errors = $doEditStatus->getErrorsArray();
1638 if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
1639 'edit-already-exists' ) ) )
1641 $this->isConflict
= true;
1642 // Destroys data doEdit() put in $status->value but who cares
1643 $doEditStatus->value
= self
::AS_END
;
1645 wfProfileOut( __METHOD__
);
1646 return $doEditStatus;
1651 * Register the change of watch status
1653 protected function updateWatchlist() {
1656 if ( $wgUser->isLoggedIn() && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
) ) {
1657 $fname = __METHOD__
;
1658 $title = $this->mTitle
;
1659 $watch = $this->watchthis
;
1661 // Do this in its own transaction to reduce contention...
1662 $dbw = wfGetDB( DB_MASTER
);
1663 $dbw->onTransactionIdle( function() use ( $dbw, $title, $watch, $wgUser, $fname ) {
1664 $dbw->begin( $fname );
1666 WatchAction
::doWatch( $title, $wgUser );
1668 WatchAction
::doUnwatch( $title, $wgUser );
1670 $dbw->commit( $fname );
1676 * Attempts to merge text content with base and current revisions
1678 * @param $editText string
1681 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1683 function mergeChangesInto( &$editText ){
1684 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1686 $editContent = $this->toEditContent( $editText );
1688 $ok = $this->mergeChangesIntoContent( $editContent );
1691 $editText = $this->toEditText( $editContent );
1698 * Attempts to do 3-way merge of edit content with a base revision
1699 * and current content, in case of edit conflict, in whichever way appropriate
1700 * for the content type.
1704 * @param $editContent
1708 private function mergeChangesIntoContent( &$editContent ){
1709 wfProfileIn( __METHOD__
);
1711 $db = wfGetDB( DB_MASTER
);
1713 // This is the revision the editor started from
1714 $baseRevision = $this->getBaseRevision();
1715 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
1717 if ( is_null( $baseContent ) ) {
1718 wfProfileOut( __METHOD__
);
1722 // The current state, we want to merge updates into it
1723 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1724 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
1726 if ( is_null( $currentContent ) ) {
1727 wfProfileOut( __METHOD__
);
1731 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
1733 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1736 $editContent = $result;
1737 wfProfileOut( __METHOD__
);
1740 wfProfileOut( __METHOD__
);
1748 function getBaseRevision() {
1749 if ( !$this->mBaseRevision
) {
1750 $db = wfGetDB( DB_MASTER
);
1751 $baseRevision = Revision
::loadFromTimestamp(
1752 $db, $this->mTitle
, $this->edittime
);
1753 return $this->mBaseRevision
= $baseRevision;
1755 return $this->mBaseRevision
;
1760 * Check given input text against $wgSpamRegex, and return the text of the first match.
1762 * @param $text string
1764 * @return string|bool matching string or false
1766 public static function matchSpamRegex( $text ) {
1767 global $wgSpamRegex;
1768 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1769 $regexes = (array)$wgSpamRegex;
1770 return self
::matchSpamRegexInternal( $text, $regexes );
1774 * Check given input text against $wgSpamRegex, and return the text of the first match.
1776 * @param $text string
1778 * @return string|bool matching string or false
1780 public static function matchSummarySpamRegex( $text ) {
1781 global $wgSummarySpamRegex;
1782 $regexes = (array)$wgSummarySpamRegex;
1783 return self
::matchSpamRegexInternal( $text, $regexes );
1787 * @param $text string
1788 * @param $regexes array
1789 * @return bool|string
1791 protected static function matchSpamRegexInternal( $text, $regexes ) {
1792 foreach ( $regexes as $regex ) {
1794 if ( preg_match( $regex, $text, $matches ) ) {
1801 function setHeaders() {
1802 global $wgOut, $wgUser;
1804 $wgOut->addModules( 'mediawiki.action.edit' );
1806 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1807 $wgOut->addModules( 'mediawiki.action.edit.preview' );
1809 // Bug #19334: textarea jumps when editing articles in IE8
1810 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1812 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1814 # Enabled article-related sidebar, toplinks, etc.
1815 $wgOut->setArticleRelated( true );
1817 $contextTitle = $this->getContextTitle();
1818 if ( $this->isConflict
) {
1819 $msg = 'editconflict';
1820 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1821 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1823 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1824 'editing' : 'creating';
1826 # Use the title defined by DISPLAYTITLE magic word when present
1827 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1828 if ( $displayTitle === false ) {
1829 $displayTitle = $contextTitle->getPrefixedText();
1831 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1835 * Show all applicable editing introductions
1837 protected function showIntro() {
1838 global $wgOut, $wgUser;
1839 if ( $this->suppressIntro
) {
1843 $namespace = $this->mTitle
->getNamespace();
1845 if ( $namespace == NS_MEDIAWIKI
) {
1846 # Show a warning if editing an interface message
1847 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1848 } else if( $namespace == NS_FILE
) {
1849 # Show a hint to shared repo
1850 $file = wfFindFile( $this->mTitle
);
1851 if( $file && !$file->isLocal() ) {
1852 $descUrl = $file->getDescriptionUrl();
1853 # there must be a description url to show a hint to shared repo
1855 if( !$this->mTitle
->exists() ) {
1856 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1857 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1860 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1861 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1868 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1869 # Show log extract when the user is currently blocked
1870 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1871 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1872 $username = $parts[0];
1873 $user = User
::newFromName( $username, false /* allow IP users*/ );
1874 $ip = User
::isIP( $username );
1875 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1876 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1877 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1878 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1879 LogEventsList
::showLogExtract(
1882 $user->getUserPage(),
1886 'showIfEmpty' => false,
1888 'blocked-notice-logextract',
1889 $user->getName() # Support GENDER in notice
1895 # Try to add a custom edit intro, or use the standard one if this is not possible.
1896 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1897 if ( $wgUser->isLoggedIn() ) {
1898 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1900 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1903 # Give a notice if the user is editing a deleted/moved page...
1904 if ( !$this->mTitle
->exists() ) {
1905 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1909 'conds' => array( "log_action != 'revision'" ),
1910 'showIfEmpty' => false,
1911 'msgKey' => array( 'recreate-moveddeleted-warn' )
1918 * Attempt to show a custom editing introduction, if supplied
1922 protected function showCustomIntro() {
1923 if ( $this->editintro
) {
1924 $title = Title
::newFromText( $this->editintro
);
1925 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1927 // Added using template syntax, to take <noinclude>'s into account.
1928 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1936 * Gets an editable textual representation of $content.
1937 * The textual representation can be turned by into a Content object by the
1938 * toEditContent() method.
1940 * If $content is null or false or a string, $content is returned unchanged.
1942 * If the given Content object is not of a type that can be edited using the text base EditPage,
1943 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
1946 * @param Content|null|bool|string $content
1947 * @return String the editable text form of the content.
1949 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
1951 protected function toEditText( $content ) {
1952 if ( $content === null ||
$content === false ) {
1956 if ( is_string( $content ) ) {
1960 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
1961 throw new MWException( "This content model can not be edited as text: "
1962 . ContentHandler
::getLocalizedName( $content->getModel() ) );
1965 return $content->serialize( $this->contentFormat
);
1969 * Turns the given text into a Content object by unserializing it.
1971 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
1972 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
1975 * @param String|null|bool $text Text to unserialize
1976 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
1979 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
1980 * and $this->allowNonTextContent is not true.
1982 protected function toEditContent( $text ) {
1983 if ( $text === false ||
$text === null ) {
1987 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
1988 $this->contentModel
, $this->contentFormat
);
1990 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
1991 throw new MWException( "This content model can not be edited as text: "
1992 . ContentHandler
::getLocalizedName( $content->getModel() ) );
1999 * Send the edit form and related headers to $wgOut
2000 * @param $formCallback Callback|null that takes an OutputPage parameter; will be called
2001 * during form output near the top, for captchas and the like.
2003 function showEditForm( $formCallback = null ) {
2004 global $wgOut, $wgUser;
2006 wfProfileIn( __METHOD__
);
2008 # need to parse the preview early so that we know which templates are used,
2009 # otherwise users with "show preview after edit box" will get a blank list
2010 # we parse this near the beginning so that setHeaders can do the title
2011 # setting work instead of leaving it in getPreviewText
2012 $previewOutput = '';
2013 if ( $this->formtype
== 'preview' ) {
2014 $previewOutput = $this->getPreviewText();
2017 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2019 $this->setHeaders();
2021 if ( $this->showHeader() === false ) {
2022 wfProfileOut( __METHOD__
);
2026 $wgOut->addHTML( $this->editFormPageTop
);
2028 if ( $wgUser->getOption( 'previewontop' ) ) {
2029 $this->displayPreviewArea( $previewOutput, true );
2032 $wgOut->addHTML( $this->editFormTextTop
);
2034 $showToolbar = true;
2035 if ( $this->wasDeletedSinceLastEdit() ) {
2036 if ( $this->formtype
== 'save' ) {
2037 // Hide the toolbar and edit area, user can click preview to get it back
2038 // Add an confirmation checkbox and explanation.
2039 $showToolbar = false;
2041 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2042 'deletedwhileediting' );
2046 //@todo: add EditForm plugin interface and use it here!
2047 // search for textarea1 and textares2, and allow EditForm to override all uses.
2048 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => self
::EDITFORM_ID
, 'name' => self
::EDITFORM_ID
,
2049 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
2050 'enctype' => 'multipart/form-data' ) ) );
2052 if ( is_callable( $formCallback ) ) {
2053 call_user_func_array( $formCallback, array( &$wgOut ) );
2056 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2058 // Put these up at the top to ensure they aren't lost on early form submission
2059 $this->showFormBeforeText();
2061 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2062 $username = $this->lastDelete
->user_name
;
2063 $comment = $this->lastDelete
->log_comment
;
2065 // It is better to not parse the comment at all than to have templates expanded in the middle
2066 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2067 $key = $comment === ''
2068 ?
'confirmrecreate-noreason'
2069 : 'confirmrecreate';
2071 '<div class="mw-confirm-recreate">' .
2072 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2073 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2074 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2080 # When the summary is hidden, also hide them on preview/show changes
2081 if( $this->nosummary
) {
2082 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2085 # If a blank edit summary was previously provided, and the appropriate
2086 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2087 # user being bounced back more than once in the event that a summary
2090 # For a bit more sophisticated detection of blank summaries, hash the
2091 # automatic one and pass that in the hidden field wpAutoSummary.
2092 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2093 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2096 if ( $this->undidRev
) {
2097 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2100 if ( $this->hasPresetSummary
) {
2101 // If a summary has been preset using &summary= we dont want to prompt for
2102 // a different summary. Only prompt for a summary if the summary is blanked.
2104 $this->autoSumm
= md5( '' );
2107 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2108 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2110 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2112 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2113 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2115 if ( $this->section
== 'new' ) {
2116 $this->showSummaryInput( true, $this->summary
);
2117 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2120 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2122 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2123 $wgOut->addHTML( EditPage
::getEditToolbar() );
2126 if ( $this->isConflict
) {
2127 // In an edit conflict bypass the overrideable content form method
2128 // and fallback to the raw wpTextbox1 since editconflicts can't be
2129 // resolved between page source edits and custom ui edits using the
2131 $this->textbox2
= $this->textbox1
;
2133 $content = $this->getCurrentContent();
2134 $this->textbox1
= $this->toEditText( $content );
2136 $this->showTextbox1();
2138 $this->showContentForm();
2141 $wgOut->addHTML( $this->editFormTextAfterContent
);
2143 $this->showStandardInputs();
2145 $this->showFormAfterText();
2147 $this->showTosSummary();
2149 $this->showEditTools();
2151 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2153 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2154 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2156 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2157 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2159 if ( $this->isConflict
) {
2161 $this->showConflict();
2162 } catch ( MWContentSerializationException
$ex ) {
2163 // this can't really happen, but be nice if it does.
2164 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2165 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2169 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2171 if ( !$wgUser->getOption( 'previewontop' ) ) {
2172 $this->displayPreviewArea( $previewOutput, false );
2175 wfProfileOut( __METHOD__
);
2179 * Extract the section title from current section text, if any.
2181 * @param string $text
2182 * @return Mixed|string or false
2184 public static function extractSectionTitle( $text ) {
2185 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2186 if ( !empty( $matches[2] ) ) {
2188 return $wgParser->stripSectionName( trim( $matches[2] ) );
2194 protected function showHeader() {
2195 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2197 if ( $this->mTitle
->isTalkPage() ) {
2198 $wgOut->addWikiMsg( 'talkpagetext' );
2202 $wgOut->addHTML( implode( "\n", $this->mTitle
->getEditNotices() ) );
2204 if ( $this->isConflict
) {
2205 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2206 $this->edittime
= $this->mArticle
->getTimestamp();
2208 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2209 // We use $this->section to much before this and getVal('wgSection') directly in other places
2210 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2211 // Someone is welcome to try refactoring though
2212 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2216 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2217 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2218 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2219 if ( $sectionTitle !== false ) {
2220 $this->summary
= "/* $sectionTitle */ ";
2225 if ( $this->missingComment
) {
2226 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2229 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2230 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2233 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2234 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2237 if ( $this->hookError
!== '' ) {
2238 $wgOut->addWikiText( $this->hookError
);
2241 if ( !$this->checkUnicodeCompliantBrowser() ) {
2242 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2245 if ( $this->section
!= 'new' ) {
2246 $revision = $this->mArticle
->getRevisionFetched();
2248 // Let sysop know that this will make private content public if saved
2250 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2251 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2252 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2253 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2256 if ( !$revision->isCurrent() ) {
2257 $this->mArticle
->setOldSubtitle( $revision->getId() );
2258 $wgOut->addWikiMsg( 'editingold' );
2260 } elseif ( $this->mTitle
->exists() ) {
2261 // Something went wrong
2263 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2264 array( 'missing-revision', $this->oldid
) );
2269 if ( wfReadOnly() ) {
2270 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2271 } elseif ( $wgUser->isAnon() ) {
2272 if ( $this->formtype
!= 'preview' ) {
2273 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2275 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2278 if ( $this->isCssJsSubpage
) {
2279 # Check the skin exists
2280 if ( $this->isWrongCaseCssJsPage
) {
2281 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2283 if ( $this->formtype
!== 'preview' ) {
2284 if ( $this->isCssSubpage
) {
2285 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2288 if ( $this->isJsSubpage
) {
2289 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2295 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2296 # Is the title semi-protected?
2297 if ( $this->mTitle
->isSemiProtected() ) {
2298 $noticeMsg = 'semiprotectedpagewarning';
2300 # Then it must be protected based on static groups (regular)
2301 $noticeMsg = 'protectedpagewarning';
2303 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2304 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2306 if ( $this->mTitle
->isCascadeProtected() ) {
2307 # Is this page under cascading protection from some source pages?
2308 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2309 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2310 $cascadeSourcesCount = count( $cascadeSources );
2311 if ( $cascadeSourcesCount > 0 ) {
2312 # Explain, and list the titles responsible
2313 foreach ( $cascadeSources as $page ) {
2314 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2317 $notice .= '</div>';
2318 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2320 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2321 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2323 'showIfEmpty' => false,
2324 'msgKey' => array( 'titleprotectedwarning' ),
2325 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2328 if ( $this->kblength
=== false ) {
2329 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2332 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2333 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2334 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2336 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2337 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2338 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2342 # Add header copyright warning
2343 $this->showHeaderCopyrightWarning();
2348 * Standard summary input and label (wgSummary), abstracted so EditPage
2349 * subclasses may reorganize the form.
2350 * Note that you do not need to worry about the label's for=, it will be
2351 * inferred by the id given to the input. You can remove them both by
2352 * passing array( 'id' => false ) to $userInputAttrs.
2354 * @param $summary string The value of the summary input
2355 * @param $labelText string The html to place inside the label
2356 * @param $inputAttrs array of attrs to use on the input
2357 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2359 * @return array An array in the format array( $label, $input )
2361 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2362 // Note: the maxlength is overriden in JS to 255 and to make it use UTF-8 bytes, not characters.
2363 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2364 'id' => 'wpSummary',
2365 'maxlength' => '200',
2368 'spellcheck' => 'true',
2369 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2371 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2372 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2373 'id' => "wpSummaryLabel"
2378 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2379 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2382 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2384 return array( $label, $input );
2388 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2389 * up top, or false if this is the comment summary
2390 * down below the textarea
2391 * @param $summary String: The text of the summary to display
2394 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2395 global $wgOut, $wgContLang;
2396 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2397 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2398 if ( $isSubjectPreview ) {
2399 if ( $this->nosummary
) {
2403 if ( !$this->mShowSummaryField
) {
2407 $summary = $wgContLang->recodeForEdit( $summary );
2408 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2409 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2410 $wgOut->addHTML( "{$label} {$input}" );
2414 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2415 * up top, or false if this is the comment summary
2416 * down below the textarea
2417 * @param $summary String: the text of the summary to display
2420 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2421 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2427 if ( $isSubjectPreview ) {
2428 $summary = wfMessage( 'newsectionsummary', $wgParser->stripSectionName( $summary ) )
2429 ->inContentLanguage()->text();
2432 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2434 $summary = wfMessage( $message )->parse() . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2435 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2438 protected function showFormBeforeText() {
2440 $section = htmlspecialchars( $this->section
);
2441 $wgOut->addHTML( <<<HTML
2442 <input type='hidden' value="{$section}" name="wpSection" />
2443 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2444 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2445 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2449 if ( !$this->checkUnicodeCompliantBrowser() ) {
2450 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2454 protected function showFormAfterText() {
2455 global $wgOut, $wgUser;
2457 * To make it harder for someone to slip a user a page
2458 * which submits an edit form to the wiki without their
2459 * knowledge, a random token is associated with the login
2460 * session. If it's not passed back with the submission,
2461 * we won't save the page, or render user JavaScript and
2464 * For anon editors, who may not have a session, we just
2465 * include the constant suffix to prevent editing from
2466 * broken text-mangling proxies.
2468 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2472 * Subpage overridable method for printing the form for page content editing
2473 * By default this simply outputs wpTextbox1
2474 * Subclasses can override this to provide a custom UI for editing;
2475 * be it a form, or simply wpTextbox1 with a modified content that will be
2476 * reverse modified when extracted from the post data.
2477 * Note that this is basically the inverse for importContentFormData
2479 protected function showContentForm() {
2480 $this->showTextbox1();
2484 * Method to output wpTextbox1
2485 * The $textoverride method can be used by subclasses overriding showContentForm
2486 * to pass back to this method.
2488 * @param $customAttribs array of html attributes to use in the textarea
2489 * @param $textoverride String: optional text to override $this->textarea1 with
2491 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2492 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2493 $attribs = array( 'style' => 'display:none;' );
2495 $classes = array(); // Textarea CSS
2496 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2497 # Is the title semi-protected?
2498 if ( $this->mTitle
->isSemiProtected() ) {
2499 $classes[] = 'mw-textarea-sprotected';
2501 # Then it must be protected based on static groups (regular)
2502 $classes[] = 'mw-textarea-protected';
2504 # Is the title cascade-protected?
2505 if ( $this->mTitle
->isCascadeProtected() ) {
2506 $classes[] = 'mw-textarea-cprotected';
2510 $attribs = array( 'tabindex' => 1 );
2512 if ( is_array( $customAttribs ) ) {
2513 $attribs +
= $customAttribs;
2516 if ( count( $classes ) ) {
2517 if ( isset( $attribs['class'] ) ) {
2518 $classes[] = $attribs['class'];
2520 $attribs['class'] = implode( ' ', $classes );
2524 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2527 protected function showTextbox2() {
2528 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2531 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2532 global $wgOut, $wgUser;
2534 $wikitext = $this->safeUnicodeOutput( $text );
2535 if ( strval( $wikitext ) !== '' ) {
2536 // Ensure there's a newline at the end, otherwise adding lines
2538 // But don't add a newline if the ext is empty, or Firefox in XHTML
2539 // mode will show an extra newline. A bit annoying.
2543 $attribs = $customAttribs +
array(
2546 'cols' => $wgUser->getIntOption( 'cols' ),
2547 'rows' => $wgUser->getIntOption( 'rows' ),
2548 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2551 $pageLang = $this->mTitle
->getPageLanguage();
2552 $attribs['lang'] = $pageLang->getCode();
2553 $attribs['dir'] = $pageLang->getDir();
2555 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2558 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2562 $classes[] = 'ontop';
2565 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2567 if ( $this->formtype
!= 'preview' ) {
2568 $attribs['style'] = 'display: none;';
2571 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2573 if ( $this->formtype
== 'preview' ) {
2574 $this->showPreview( $previewOutput );
2577 $wgOut->addHTML( '</div>' );
2579 if ( $this->formtype
== 'diff' ) {
2582 } catch ( MWContentSerializationException
$ex ) {
2583 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2584 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2590 * Append preview output to $wgOut.
2591 * Includes category rendering if this is a category page.
2593 * @param $text String: the HTML to be output for the preview.
2595 protected function showPreview( $text ) {
2597 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2598 $this->mArticle
->openShowCategory();
2600 # This hook seems slightly odd here, but makes things more
2601 # consistent for extensions.
2602 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2603 $wgOut->addHTML( $text );
2604 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2605 $this->mArticle
->closeShowCategory();
2610 * Get a diff between the current contents of the edit box and the
2611 * version of the page we're editing from.
2613 * If this is a section edit, we'll replace the section as for final
2614 * save and then make a comparison.
2616 function showDiff() {
2617 global $wgUser, $wgContLang, $wgOut;
2619 $oldtitlemsg = 'currentrev';
2620 # if message does not exist, show diff against the preloaded default
2621 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2622 $oldtext = $this->mTitle
->getDefaultMessageText();
2623 if( $oldtext !== false ) {
2624 $oldtitlemsg = 'defaultmessagetext';
2625 $oldContent = $this->toEditContent( $oldtext );
2630 $oldContent = $this->getCurrentContent();
2633 $textboxContent = $this->toEditContent( $this->textbox1
);
2635 $newContent = $this->mArticle
->replaceSectionContent(
2636 $this->section
, $textboxContent,
2637 $this->summary
, $this->edittime
);
2639 if ( $newContent ) {
2640 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2641 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2643 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2644 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2647 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2648 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2649 $newtitle = wfMessage( 'yourtext' )->parse();
2651 if ( !$oldContent ) {
2652 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
2655 if ( !$newContent ) {
2656 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
2659 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
2660 $de->setContent( $oldContent, $newContent );
2662 $difftext = $de->getDiff( $oldtitle, $newtitle );
2663 $de->showDiffStyle();
2668 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2672 * Show the header copyright warning.
2674 protected function showHeaderCopyrightWarning() {
2675 $msg = 'editpage-head-copy-warn';
2676 if ( !wfMessage( $msg )->isDisabled() ) {
2678 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2679 'editpage-head-copy-warn' );
2684 * Give a chance for site and per-namespace customizations of
2685 * terms of service summary link that might exist separately
2686 * from the copyright notice.
2688 * This will display between the save button and the edit tools,
2689 * so should remain short!
2691 protected function showTosSummary() {
2692 $msg = 'editpage-tos-summary';
2693 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2694 if ( !wfMessage( $msg )->isDisabled() ) {
2696 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2697 $wgOut->addWikiMsg( $msg );
2698 $wgOut->addHTML( '</div>' );
2702 protected function showEditTools() {
2704 $wgOut->addHTML( '<div class="mw-editTools">' .
2705 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2710 * Get the copyright warning
2712 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2714 protected function getCopywarn() {
2715 return self
::getCopyrightWarning( $this->mTitle
);
2718 public static function getCopyrightWarning( $title ) {
2719 global $wgRightsText;
2720 if ( $wgRightsText ) {
2721 $copywarnMsg = array( 'copyrightwarning',
2722 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2725 $copywarnMsg = array( 'copyrightwarning2',
2726 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2728 // Allow for site and per-namespace customization of contribution/copyright notice.
2729 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2731 return "<div id=\"editpage-copywarn\">\n" .
2732 call_user_func_array( 'wfMessage', $copywarnMsg )->plain() . "\n</div>";
2735 protected function showStandardInputs( &$tabindex = 2 ) {
2737 $wgOut->addHTML( "<div class='editOptions'>\n" );
2739 if ( $this->section
!= 'new' ) {
2740 $this->showSummaryInput( false, $this->summary
);
2741 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2744 $checkboxes = $this->getCheckboxes( $tabindex,
2745 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2746 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2748 // Show copyright warning.
2749 $wgOut->addWikiText( $this->getCopywarn() );
2750 $wgOut->addHTML( $this->editFormTextAfterWarn
);
2752 $wgOut->addHTML( "<div class='editButtons'>\n" );
2753 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2755 $cancel = $this->getCancelLink();
2756 if ( $cancel !== '' ) {
2757 $cancel .= wfMessage( 'pipe-separator' )->text();
2759 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
2760 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2761 wfMessage( 'edithelp' )->escaped() . '</a> ' .
2762 wfMessage( 'newwindow' )->parse();
2763 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
2764 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
2765 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
2766 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
2767 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
2771 * Show an edit conflict. textbox1 is already shown in showEditForm().
2772 * If you want to use another entry point to this function, be careful.
2774 protected function showConflict() {
2777 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2778 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2780 $content1 = $this->toEditContent( $this->textbox1
);
2781 $content2 = $this->toEditContent( $this->textbox2
);
2783 $handler = ContentHandler
::getForModelID( $this->contentModel
);
2784 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
2785 $de->setContent( $content2, $content1 );
2787 wfMessage( 'yourtext' )->parse(),
2788 wfMessage( 'storedversion' )->text()
2791 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2792 $this->showTextbox2();
2799 public function getCancelLink() {
2800 $cancelParams = array();
2801 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2802 $cancelParams['oldid'] = $this->oldid
;
2805 return Linker
::linkKnown(
2806 $this->getContextTitle(),
2807 wfMessage( 'cancel' )->parse(),
2808 array( 'id' => 'mw-editform-cancel' ),
2814 * Returns the URL to use in the form's action attribute.
2815 * This is used by EditPage subclasses when simply customizing the action
2816 * variable in the constructor is not enough. This can be used when the
2817 * EditPage lives inside of a Special page rather than a custom page action.
2819 * @param $title Title object for which is being edited (where we go to for &action= links)
2822 protected function getActionURL( Title
$title ) {
2823 return $title->getLocalURL( array( 'action' => $this->action
) );
2827 * Check if a page was deleted while the user was editing it, before submit.
2828 * Note that we rely on the logging table, which hasn't been always there,
2829 * but that doesn't matter, because this only applies to brand new
2832 protected function wasDeletedSinceLastEdit() {
2833 if ( $this->deletedSinceEdit
!== null ) {
2834 return $this->deletedSinceEdit
;
2837 $this->deletedSinceEdit
= false;
2839 if ( $this->mTitle
->isDeletedQuick() ) {
2840 $this->lastDelete
= $this->getLastDelete();
2841 if ( $this->lastDelete
) {
2842 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2843 if ( $deleteTime > $this->starttime
) {
2844 $this->deletedSinceEdit
= true;
2849 return $this->deletedSinceEdit
;
2852 protected function getLastDelete() {
2853 $dbr = wfGetDB( DB_SLAVE
);
2854 $data = $dbr->selectRow(
2855 array( 'logging', 'user' ),
2866 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2867 'log_title' => $this->mTitle
->getDBkey(),
2868 'log_type' => 'delete',
2869 'log_action' => 'delete',
2870 'user_id=log_user' ),
2872 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2874 // Quick paranoid permission checks...
2875 if ( is_object( $data ) ) {
2876 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
2877 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
2880 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
2881 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
2888 * Get the rendered text for previewing.
2889 * @throws MWException
2892 function getPreviewText() {
2893 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
2895 wfProfileIn( __METHOD__
);
2897 if ( $wgRawHtml && !$this->mTokenOk
) {
2898 // Could be an offsite preview attempt. This is very unsafe if
2899 // HTML is enabled, as it could be an attack.
2901 if ( $this->textbox1
!== '' ) {
2902 // Do not put big scary notice, if previewing the empty
2903 // string, which happens when you initially edit
2904 // a category page, due to automatic preview-on-open.
2905 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2906 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
2908 wfProfileOut( __METHOD__
);
2915 $content = $this->toEditContent( $this->textbox1
);
2918 if ( !wfRunHooks( 'AlternateEditPreview', array( $this, &$content, &$previewHTML, &$this->mParserOutput
) ) ) {
2919 wfProfileOut( __METHOD__
);
2920 return $previewHTML;
2923 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2924 if ( $this->mTokenOkExceptSuffix
) {
2925 $note = wfMessage( 'token_suffix_mismatch' )->plain() ;
2928 $note = wfMessage( 'session_fail_preview' )->plain() ;
2930 } elseif ( $this->incompleteForm
) {
2931 $note = wfMessage( 'edit_form_incomplete' )->plain() ;
2933 $note = wfMessage( 'previewnote' )->plain() .
2934 ' [[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' . wfMessage( 'continue-editing' )->text() . ']]';
2937 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
2938 $parserOptions->setEditSection( false );
2939 $parserOptions->setIsPreview( true );
2940 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2942 # don't parse non-wikitext pages, show message about preview
2943 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
2944 if( $this->mTitle
->isCssJsSubpage() ) {
2946 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2952 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
2954 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
2960 # Used messages to make sure grep find them:
2961 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2962 if( $level && $format ) {
2963 $note = "<div id='mw-{$level}{$format}preview'>" . wfMessage( "{$level}{$format}preview" )->text() . "</div>";
2967 $rt = $content->getRedirectChain();
2969 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2972 # If we're adding a comment, we need to show the
2973 # summary as the headline
2974 if ( $this->section
=== "new" && $this->summary
!== "" ) {
2975 $content = $content->addSectionHeader( $this->summary
);
2978 $hook_args = array( $this, &$content );
2979 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
2980 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
2982 $parserOptions->enableLimitReport();
2984 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
2985 # But it's now deprecated, so never mind
2987 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
2988 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
2990 $previewHTML = $parserOutput->getText();
2991 $this->mParserOutput
= $parserOutput;
2992 $wgOut->addParserOutputNoText( $parserOutput );
2994 if ( count( $parserOutput->getWarnings() ) ) {
2995 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2998 } catch ( MWContentSerializationException
$ex ) {
2999 $m = wfMessage('content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
3000 $note .= "\n\n" . $m->parse();
3004 if ( $this->isConflict
) {
3005 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3007 $conflict = '<hr />';
3010 $previewhead = "<div class='previewnote'>\n" .
3011 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3012 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3014 $pageLang = $this->mTitle
->getPageLanguage();
3015 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
3016 'class' => 'mw-content-' . $pageLang->getDir() );
3017 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3019 wfProfileOut( __METHOD__
);
3020 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3026 function getTemplates() {
3027 if ( $this->preview ||
$this->section
!= '' ) {
3028 $templates = array();
3029 if ( !isset( $this->mParserOutput
) ) {
3032 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3033 foreach ( array_keys( $template ) as $dbk ) {
3034 $templates[] = Title
::makeTitle( $ns, $dbk );
3039 return $this->mTitle
->getTemplateLinksFrom();
3044 * Shows a bulletin board style toolbar for common editing functions.
3045 * It can be disabled in the user preferences.
3046 * The necessary JavaScript code can be found in skins/common/edit.js.
3050 static function getEditToolbar() {
3051 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3052 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
3054 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3057 * $toolarray is an array of arrays each of which includes the
3058 * filename of the button image (without path), the opening
3059 * tag, the closing tag, optionally a sample text that is
3060 * inserted between the two when no selection is highlighted
3061 * and. The tip text is shown when the user moves the mouse
3064 * Also here: accesskeys (key), which are not used yet until
3065 * someone can figure out a way to make them work in
3066 * IE. However, we should make sure these keys are not defined
3071 'image' => $wgLang->getImageFile( 'button-bold' ),
3072 'id' => 'mw-editbutton-bold',
3074 'close' => '\'\'\'',
3075 'sample' => wfMessage( 'bold_sample' )->text(),
3076 'tip' => wfMessage( 'bold_tip' )->text(),
3080 'image' => $wgLang->getImageFile( 'button-italic' ),
3081 'id' => 'mw-editbutton-italic',
3084 'sample' => wfMessage( 'italic_sample' )->text(),
3085 'tip' => wfMessage( 'italic_tip' )->text(),
3089 'image' => $wgLang->getImageFile( 'button-link' ),
3090 'id' => 'mw-editbutton-link',
3093 'sample' => wfMessage( 'link_sample' )->text(),
3094 'tip' => wfMessage( 'link_tip' )->text(),
3098 'image' => $wgLang->getImageFile( 'button-extlink' ),
3099 'id' => 'mw-editbutton-extlink',
3102 'sample' => wfMessage( 'extlink_sample' )->text(),
3103 'tip' => wfMessage( 'extlink_tip' )->text(),
3107 'image' => $wgLang->getImageFile( 'button-headline' ),
3108 'id' => 'mw-editbutton-headline',
3111 'sample' => wfMessage( 'headline_sample' )->text(),
3112 'tip' => wfMessage( 'headline_tip' )->text(),
3115 $imagesAvailable ?
array(
3116 'image' => $wgLang->getImageFile( 'button-image' ),
3117 'id' => 'mw-editbutton-image',
3118 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3120 'sample' => wfMessage( 'image_sample' )->text(),
3121 'tip' => wfMessage( 'image_tip' )->text(),
3124 $imagesAvailable ?
array(
3125 'image' => $wgLang->getImageFile( 'button-media' ),
3126 'id' => 'mw-editbutton-media',
3127 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3129 'sample' => wfMessage( 'media_sample' )->text(),
3130 'tip' => wfMessage( 'media_tip' )->text(),
3134 'image' => $wgLang->getImageFile( 'button-math' ),
3135 'id' => 'mw-editbutton-math',
3137 'close' => "</math>",
3138 'sample' => wfMessage( 'math_sample' )->text(),
3139 'tip' => wfMessage( 'math_tip' )->text(),
3143 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3144 'id' => 'mw-editbutton-nowiki',
3145 'open' => "<nowiki>",
3146 'close' => "</nowiki>",
3147 'sample' => wfMessage( 'nowiki_sample' )->text(),
3148 'tip' => wfMessage( 'nowiki_tip' )->text(),
3152 'image' => $wgLang->getImageFile( 'button-sig' ),
3153 'id' => 'mw-editbutton-signature',
3157 'tip' => wfMessage( 'sig_tip' )->text(),
3161 'image' => $wgLang->getImageFile( 'button-hr' ),
3162 'id' => 'mw-editbutton-hr',
3163 'open' => "\n----\n",
3166 'tip' => wfMessage( 'hr_tip' )->text(),
3171 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3172 foreach ( $toolarray as $tool ) {
3178 $image = $wgStylePath . '/common/images/' . $tool['image'],
3179 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3180 // Older browsers show a "speedtip" type message only for ALT.
3181 // Ideally these should be different, realistically they
3182 // probably don't need to be.
3183 $tip = $tool['tip'],
3184 $open = $tool['open'],
3185 $close = $tool['close'],
3186 $sample = $tool['sample'],
3187 $cssId = $tool['id'],
3190 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3193 // This used to be called on DOMReady from mediawiki.action.edit, which
3194 // ended up causing race conditions with the setup code above.
3196 "// Create button bar\n" .
3197 "$(function() { mw.toolbar.init(); } );\n";
3200 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3202 $toolbar = '<div id="toolbar"></div>';
3204 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3210 * Returns an array of html code of the following checkboxes:
3213 * @param $tabindex int Current tabindex
3214 * @param $checked Array of checkbox => bool, where bool indicates the checked
3215 * status of the checkbox
3219 public function getCheckboxes( &$tabindex, $checked ) {
3222 $checkboxes = array();
3224 // don't show the minor edit checkbox if it's a new page or section
3225 if ( !$this->isNew
) {
3226 $checkboxes['minor'] = '';
3227 $minorLabel = wfMessage( 'minoredit' )->parse();
3228 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3230 'tabindex' => ++
$tabindex,
3231 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3232 'id' => 'wpMinoredit',
3234 $checkboxes['minor'] =
3235 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3236 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3237 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3238 ">{$minorLabel}</label>";
3242 $watchLabel = wfMessage( 'watchthis' )->parse();
3243 $checkboxes['watch'] = '';
3244 if ( $wgUser->isLoggedIn() ) {
3246 'tabindex' => ++
$tabindex,
3247 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3248 'id' => 'wpWatchthis',
3250 $checkboxes['watch'] =
3251 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3252 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3253 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3254 ">{$watchLabel}</label>";
3256 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3261 * Returns an array of html code of the following buttons:
3262 * save, diff, preview and live
3264 * @param $tabindex int Current tabindex
3268 public function getEditButtons( &$tabindex ) {
3275 'tabindex' => ++
$tabindex,
3276 'value' => wfMessage( 'savearticle' )->text(),
3277 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3278 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3280 $buttons['save'] = Xml
::element( 'input', $temp, '' );
3282 ++
$tabindex; // use the same for preview and live preview
3284 'id' => 'wpPreview',
3285 'name' => 'wpPreview',
3287 'tabindex' => $tabindex,
3288 'value' => wfMessage( 'showpreview' )->text(),
3289 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3290 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3292 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3293 $buttons['live'] = '';
3299 'tabindex' => ++
$tabindex,
3300 'value' => wfMessage( 'showdiff' )->text(),
3301 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3302 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3304 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3306 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3311 * Output preview text only. This can be sucked into the edit page
3312 * via JavaScript, and saves the server time rendering the skin as
3313 * well as theoretically being more robust on the client (doesn't
3314 * disturb the edit box's undo history, won't eat your text on
3317 * @todo This doesn't include category or interlanguage links.
3318 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3319 * or something...</s>" that might also require more skin
3320 * initialization, so check whether that's a problem.
3322 function livePreview() {
3325 header( 'Content-type: text/xml; charset=utf-8' );
3326 header( 'Cache-control: no-cache' );
3328 $previewText = $this->getPreviewText();
3329 #$categories = $skin->getCategoryLinks();
3332 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3333 Xml
::tags( 'livepreview', null,
3334 Xml
::element( 'preview', null, $previewText )
3335 #. Xml::element( 'category', null, $categories )
3341 * Call the stock "user is blocked" page
3343 * @deprecated in 1.19; throw an exception directly instead
3345 function blockedPage() {
3346 wfDeprecated( __METHOD__
, '1.19' );
3349 throw new UserBlockedError( $wgUser->getBlock() );
3353 * Produce the stock "please login to edit pages" page
3355 * @deprecated in 1.19; throw an exception directly instead
3357 function userNotLoggedInPage() {
3358 wfDeprecated( __METHOD__
, '1.19' );
3359 throw new PermissionsError( 'edit' );
3363 * Show an error page saying to the user that he has insufficient permissions
3364 * to create a new page
3366 * @deprecated in 1.19; throw an exception directly instead
3368 function noCreatePermission() {
3369 wfDeprecated( __METHOD__
, '1.19' );
3370 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3371 throw new PermissionsError( $permission );
3375 * Creates a basic error page which informs the user that
3376 * they have attempted to edit a nonexistent section.
3378 function noSuchSectionPage() {
3381 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3383 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3384 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3385 $wgOut->addHTML( $res );
3387 $wgOut->returnToMain( false, $this->mTitle
);
3391 * Produce the stock "your edit contains spam" page
3393 * @param $match string|bool Text which triggered one or more filters
3394 * @deprecated since 1.17 Use method spamPageWithContent() instead
3396 static function spamPage( $match = false ) {
3397 wfDeprecated( __METHOD__
, '1.17' );
3399 global $wgOut, $wgTitle;
3401 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3403 $wgOut->addHTML( '<div id="spamprotected">' );
3404 $wgOut->addWikiMsg( 'spamprotectiontext' );
3406 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3408 $wgOut->addHTML( '</div>' );
3410 $wgOut->returnToMain( false, $wgTitle );
3414 * Show "your edit contains spam" page with your diff and text
3416 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3418 public function spamPageWithContent( $match = false ) {
3419 global $wgOut, $wgLang;
3420 $this->textbox2
= $this->textbox1
;
3422 if( is_array( $match ) ){
3423 $match = $wgLang->listToText( $match );
3425 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3427 $wgOut->addHTML( '<div id="spamprotected">' );
3428 $wgOut->addWikiMsg( 'spamprotectiontext' );
3430 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3432 $wgOut->addHTML( '</div>' );
3434 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3437 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3438 $this->showTextbox2();
3440 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3444 * Format an anchor fragment as it would appear for a given section name
3445 * @param $text String
3449 function sectionAnchor( $text ) {
3451 return $wgParser->guessSectionNameFromWikiText( $text );
3455 * Check if the browser is on a blacklist of user-agents known to
3456 * mangle UTF-8 data on form submission. Returns true if Unicode
3457 * should make it through, false if it's known to be a problem.
3461 function checkUnicodeCompliantBrowser() {
3462 global $wgBrowserBlackList, $wgRequest;
3464 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3465 if ( $currentbrowser === false ) {
3466 // No User-Agent header sent? Trust it by default...
3470 foreach ( $wgBrowserBlackList as $browser ) {
3471 if ( preg_match( $browser, $currentbrowser ) ) {
3479 * Filter an input field through a Unicode de-armoring process if it
3480 * came from an old browser with known broken Unicode editing issues.
3482 * @param $request WebRequest
3483 * @param $field String
3487 function safeUnicodeInput( $request, $field ) {
3488 $text = rtrim( $request->getText( $field ) );
3489 return $request->getBool( 'safemode' )
3490 ?
$this->unmakesafe( $text )
3495 * @param $request WebRequest
3496 * @param $text string
3499 function safeUnicodeText( $request, $text ) {
3500 $text = rtrim( $text );
3501 return $request->getBool( 'safemode' )
3502 ?
$this->unmakesafe( $text )
3507 * Filter an output field through a Unicode armoring process if it is
3508 * going to an old browser with known broken Unicode editing issues.
3510 * @param $text String
3514 function safeUnicodeOutput( $text ) {
3516 $codedText = $wgContLang->recodeForEdit( $text );
3517 return $this->checkUnicodeCompliantBrowser()
3519 : $this->makesafe( $codedText );
3523 * A number of web browsers are known to corrupt non-ASCII characters
3524 * in a UTF-8 text editing environment. To protect against this,
3525 * detected browsers will be served an armored version of the text,
3526 * with non-ASCII chars converted to numeric HTML character references.
3528 * Preexisting such character references will have a 0 added to them
3529 * to ensure that round-trips do not alter the original data.
3531 * @param $invalue String
3535 function makesafe( $invalue ) {
3536 // Armor existing references for reversability.
3537 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3542 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3543 $bytevalue = ord( $invalue[$i] );
3544 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3545 $result .= chr( $bytevalue );
3547 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3548 $working = $working << 6;
3549 $working +
= ( $bytevalue & 0x3F );
3551 if ( $bytesleft <= 0 ) {
3552 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3554 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3555 $working = $bytevalue & 0x1F;
3557 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3558 $working = $bytevalue & 0x0F;
3560 } else { // 1111 0xxx
3561 $working = $bytevalue & 0x07;
3569 * Reverse the previously applied transliteration of non-ASCII characters
3570 * back to UTF-8. Used to protect data from corruption by broken web browsers
3571 * as listed in $wgBrowserBlackList.
3573 * @param $invalue String
3577 function unmakesafe( $invalue ) {
3579 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3580 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3584 $hexstring .= $invalue[$i];
3586 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3588 // Do some sanity checks. These aren't needed for reversability,
3589 // but should help keep the breakage down if the editor
3590 // breaks one of the entities whilst editing.
3591 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3592 $codepoint = hexdec( $hexstring );
3593 $result .= codepointToUtf8( $codepoint );
3595 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3598 $result .= substr( $invalue, $i, 1 );
3601 // reverse the transform that we made for reversability reasons.
3602 return strtr( $result, array( "�" => "&#x" ) );