3 * Contains the EditPage class
8 * The edit page/HTML interface (split from Article)
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
13 * EditPage cares about two distinct titles:
14 * $this->mContextTitle is the page that forms submit to, links point to,
15 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
16 * page in the database that is actually being edited. These are
17 * usually the same, but they are now allowed to be different.
19 * Surgeon General's Warning: prolonged exposure to this class is known to cause
20 * headaches, which may be fatal.
25 * Status: Article successfully updated
27 const AS_SUCCESS_UPDATE
= 200;
30 * Status: Article successfully created
32 const AS_SUCCESS_NEW_ARTICLE
= 201;
35 * Status: Article update aborted by a hook function
37 const AS_HOOK_ERROR
= 210;
40 * Status: The filter function set in $wgFilterCallback returned true (= block it)
42 const AS_FILTERING
= 211;
45 * Status: A hook function returned an error
47 const AS_HOOK_ERROR_EXPECTED
= 212;
50 * Status: User is blocked from editting this page
52 const AS_BLOCKED_PAGE_FOR_USER
= 215;
55 * Status: Content too big (> $wgMaxArticleSize)
57 const AS_CONTENT_TOO_BIG
= 216;
60 * Status: User cannot edit? (not used)
62 const AS_USER_CANNOT_EDIT
= 217;
65 * Status: this anonymous user is not allowed to edit this page
67 const AS_READ_ONLY_PAGE_ANON
= 218;
70 * Status: this logged in user is not allowed to edit this page
72 const AS_READ_ONLY_PAGE_LOGGED
= 219;
75 * Status: wiki is in readonly mode (wfReadOnly() == true)
77 const AS_READ_ONLY_PAGE
= 220;
80 * Status: rate limiter for action 'edit' was tripped
82 const AS_RATE_LIMITED
= 221;
85 * Status: article was deleted while editting and param wpRecreate == false or form
88 const AS_ARTICLE_WAS_DELETED
= 222;
91 * Status: user tried to create this page, but is not allowed to do that
92 * ( Title->usercan('create') == false )
94 const AS_NO_CREATE_PERMISSION
= 223;
97 * Status: user tried to create a blank page
99 const AS_BLANK_ARTICLE
= 224;
102 * Status: (non-resolvable) edit conflict
104 const AS_CONFLICT_DETECTED
= 225;
107 * Status: no edit summary given and the user has forceeditsummary set and the user is not
108 * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
110 const AS_SUMMARY_NEEDED
= 226;
113 * Status: user tried to create a new section without content
115 const AS_TEXTBOX_EMPTY
= 228;
118 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
120 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
128 * Status: WikiPage::doEdit() was unsuccessfull
133 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
135 const AS_SPAM_ERROR
= 232;
138 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
140 const AS_IMAGE_REDIRECT_ANON
= 233;
143 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
145 const AS_IMAGE_REDIRECT_LOGGED
= 234;
156 private $mContextTitle = null;
157 var $action = 'submit';
158 var $isConflict = false;
159 var $isCssJsSubpage = false;
160 var $isCssSubpage = false;
161 var $isJsSubpage = false;
162 var $isWrongCaseCssJsPage = false;
163 var $isNew = false; // new page or new section
164 var $deletedSinceEdit;
168 var $mTokenOk = false;
169 var $mTokenOkExceptSuffix = false;
170 var $mTriedSave = false;
171 var $incompleteForm = false;
173 var $kblength = false;
174 var $missingComment = false;
175 var $missingSummary = false;
176 var $allowBlankSummary = false;
179 #var $mPreviewTemplates;
187 * Has a summary been preset using GET parameter &summary= ?
190 var $hasPresetSummary = false;
192 var $mBaseRevision = false;
193 var $mShowSummaryField = true;
196 var $save = false, $preview = false, $diff = false;
197 var $minoredit = false, $watchthis = false, $recreate = false;
198 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
199 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
200 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
202 # Placeholders for text injection by hooks (must be HTML)
203 # extensions should take care to _append_ to the present value
204 public $editFormPageTop = ''; // Before even the preview
205 public $editFormTextTop = '';
206 public $editFormTextBeforeContent = '';
207 public $editFormTextAfterWarn = '';
208 public $editFormTextAfterTools = '';
209 public $editFormTextBottom = '';
210 public $editFormTextAfterContent = '';
211 public $previewTextAfterContent = '';
212 public $mPreloadText = '';
214 /* $didSave should be set to true whenever an article was succesfully altered. */
215 public $didSave = false;
216 public $undidRev = 0;
218 public $suppressIntro = false;
221 * @param $article Article
223 public function __construct( Article
$article ) {
224 $this->mArticle
= $article;
225 $this->mTitle
= $article->getTitle();
231 public function getArticle() {
232 return $this->mArticle
;
239 public function getTitle() {
240 return $this->mTitle
;
244 * Set the context Title object
246 * @param $title Title object or null
248 public function setContextTitle( $title ) {
249 $this->mContextTitle
= $title;
253 * Get the context title object.
254 * If not set, $wgTitle will be returned. This behavior might changed in
255 * the future to return $this->mTitle instead.
257 * @return Title object
259 public function getContextTitle() {
260 if ( is_null( $this->mContextTitle
) ) {
264 return $this->mContextTitle
;
273 * This is the function that gets called for "action=edit". It
274 * sets up various member variables, then passes execution to
275 * another function, usually showEditForm()
277 * The edit form is self-submitting, so that when things like
278 * preview and edit conflicts occur, we get the same form back
279 * with the extra stuff added. Only when the final submission
280 * is made and all is well do we actually save and redirect to
281 * the newly-edited page.
284 global $wgOut, $wgRequest, $wgUser;
285 // Allow extensions to modify/prevent this form or submission
286 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
290 wfProfileIn( __METHOD__
);
291 wfDebug( __METHOD__
. ": enter\n" );
293 // If they used redlink=1 and the page exists, redirect to the main article
294 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
295 $wgOut->redirect( $this->mTitle
->getFullURL() );
296 wfProfileOut( __METHOD__
);
300 $this->importFormData( $wgRequest );
301 $this->firsttime
= false;
304 $this->livePreview();
305 wfProfileOut( __METHOD__
);
309 if ( wfReadOnly() && $this->save
) {
312 $this->preview
= true;
316 $this->formtype
= 'save';
317 } elseif ( $this->preview
) {
318 $this->formtype
= 'preview';
319 } elseif ( $this->diff
) {
320 $this->formtype
= 'diff';
321 } else { # First time through
322 $this->firsttime
= true;
323 if ( $this->previewOnOpen() ) {
324 $this->formtype
= 'preview';
326 $this->formtype
= 'initial';
330 $permErrors = $this->getEditPermissionErrors();
332 wfDebug( __METHOD__
. ": User can't edit\n" );
333 // Auto-block user's IP if the account was "hard" blocked
334 $wgUser->spreadAnyEditBlock();
336 $this->displayPermissionsError( $permErrors );
338 wfProfileOut( __METHOD__
);
342 wfProfileIn( __METHOD__
. "-business-end" );
344 $this->isConflict
= false;
345 // css / js subpages of user pages get a special treatment
346 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
347 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
348 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
349 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
350 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
352 # Show applicable editing introductions
353 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
357 # Attempt submission here. This will check for edit conflicts,
358 # and redundantly check for locked database, blocked IPs, etc.
359 # that edit() already checked just in case someone tries to sneak
360 # in the back door with a hand-edited submission URL.
362 if ( 'save' == $this->formtype
) {
363 if ( !$this->attemptSave() ) {
364 wfProfileOut( __METHOD__
. "-business-end" );
365 wfProfileOut( __METHOD__
);
370 # First time through: get contents, set time for conflict
372 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
373 if ( $this->initialiseForm() === false ) {
374 $this->noSuchSectionPage();
375 wfProfileOut( __METHOD__
. "-business-end" );
376 wfProfileOut( __METHOD__
);
379 if ( !$this->mTitle
->getArticleID() )
380 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
382 wfRunHooks( 'EditFormInitialText', array( $this ) );
385 $this->showEditForm();
386 wfProfileOut( __METHOD__
. "-business-end" );
387 wfProfileOut( __METHOD__
);
393 protected function getEditPermissionErrors() {
395 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
396 # Can this title be created?
397 if ( !$this->mTitle
->exists() ) {
398 $permErrors = array_merge( $permErrors,
399 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
401 # Ignore some permissions errors when a user is just previewing/viewing diffs
403 foreach ( $permErrors as $error ) {
404 if ( ( $this->preview ||
$this->diff
) &&
405 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
410 $permErrors = wfArrayDiff2( $permErrors, $remove );
415 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
416 * but with the following differences:
417 * - If redlink=1, the user will be redirected to the page
418 * - If there is content to display or the error occurs while either saving,
419 * previewing or showing the difference, it will be a
420 * "View source for ..." page displaying the source code after the error message.
423 * @param $permErrors Array of permissions errors, as returned by
424 * Title::getUserPermissionsErrors().
426 protected function displayPermissionsError( array $permErrors ) {
427 global $wgRequest, $wgOut;
429 if ( $wgRequest->getBool( 'redlink' ) ) {
430 // The edit page was reached via a red link.
431 // Redirect to the article page and let them click the edit tab if
432 // they really want a permission error.
433 $wgOut->redirect( $this->mTitle
->getFullUrl() );
437 $content = $this->getContent();
439 # Use the normal message if there's nothing to display
440 if ( $this->firsttime
&& $content === '' ) {
441 $action = $this->mTitle
->exists() ?
'edit' :
442 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
443 throw new PermissionsError( $action, $permErrors );
446 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
447 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
448 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
449 $wgOut->addHTML( "<hr />\n" );
451 # If the user made changes, preserve them when showing the markup
452 # (This happens when a user is blocked during edit, for instance)
453 if ( !$this->firsttime
) {
454 $content = $this->textbox1
;
455 $wgOut->addWikiMsg( 'viewyourtext' );
457 $wgOut->addWikiMsg( 'viewsourcetext' );
460 $this->showTextbox( $content, 'wpTextbox1', array( 'readonly' ) );
462 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
463 Linker
::formatTemplates( $this->getTemplates() ) ) );
465 if ( $this->mTitle
->exists() ) {
466 $wgOut->returnToMain( null, $this->mTitle
);
471 * Show a read-only error
472 * Parameters are the same as OutputPage:readOnlyPage()
473 * Redirect to the article page if redlink=1
474 * @deprecated in 1.19; use displayPermissionsError() instead
476 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
477 wfDeprecated( __METHOD__
, '1.19' );
479 global $wgRequest, $wgOut;
480 if ( $wgRequest->getBool( 'redlink' ) ) {
481 // The edit page was reached via a red link.
482 // Redirect to the article page and let them click the edit tab if
483 // they really want a permission error.
484 $wgOut->redirect( $this->mTitle
->getFullUrl() );
486 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
491 * Should we show a preview when the edit form is first shown?
495 protected function previewOnOpen() {
496 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
497 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
498 // Explicit override from request
500 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
501 // Explicit override from request
503 } elseif ( $this->section
== 'new' ) {
504 // Nothing *to* preview for new sections
506 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
507 // Standard preference behaviour
509 } elseif ( !$this->mTitle
->exists() &&
510 isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] ) &&
511 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
513 // Categories are special
521 * Checks whether the user entered a skin name in uppercase,
522 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
526 protected function isWrongCaseCssJsPage() {
527 if ( $this->mTitle
->isCssJsSubpage() ) {
528 $name = $this->mTitle
->getSkinFromCssJsSubpage();
529 $skins = array_merge(
530 array_keys( Skin
::getSkinNames() ),
533 return !in_array( $name, $skins )
534 && in_array( strtolower( $name ), $skins );
541 * Does this EditPage class support section editing?
542 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
546 protected function isSectionEditSupported() {
551 * This function collects the form data and uses it to populate various member variables.
552 * @param $request WebRequest
554 function importFormData( &$request ) {
555 global $wgLang, $wgUser;
557 wfProfileIn( __METHOD__
);
559 # Section edit can come from either the form or a link
560 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
562 if ( $request->wasPosted() ) {
563 # These fields need to be checked for encoding.
564 # Also remove trailing whitespace, but don't remove _initial_
565 # whitespace from the text boxes. This may be significant formatting.
566 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
567 if ( !$request->getCheck( 'wpTextbox2' ) ) {
568 // Skip this if wpTextbox2 has input, it indicates that we came
569 // from a conflict page with raw page text, not a custom form
570 // modified by subclasses
571 wfProfileIn( get_class( $this ) . "::importContentFormData" );
572 $textbox1 = $this->importContentFormData( $request );
573 if ( isset( $textbox1 ) )
574 $this->textbox1
= $textbox1;
575 wfProfileOut( get_class( $this ) . "::importContentFormData" );
578 # Truncate for whole multibyte characters. +5 bytes for ellipsis
579 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
581 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
582 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
584 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
586 # Treat sectiontitle the same way as summary.
587 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
588 # currently doing double duty as both edit summary and section title. Right now this
589 # is just to allow API edits to work around this limitation, but this should be
590 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
591 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 250 );
592 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
594 $this->edittime
= $request->getVal( 'wpEdittime' );
595 $this->starttime
= $request->getVal( 'wpStarttime' );
597 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
599 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
600 // wpTextbox1 field is missing, possibly due to being "too big"
601 // according to some filter rules such as Suhosin's setting for
602 // suhosin.request.max_value_length (d'oh)
603 $this->incompleteForm
= true;
605 // edittime should be one of our last fields; if it's missing,
606 // the submission probably broke somewhere in the middle.
607 $this->incompleteForm
= is_null( $this->edittime
);
609 if ( $this->incompleteForm
) {
610 # If the form is incomplete, force to preview.
611 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
612 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
613 $this->preview
= true;
615 /* Fallback for live preview */
616 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
617 $this->diff
= $request->getCheck( 'wpDiff' );
619 // Remember whether a save was requested, so we can indicate
620 // if we forced preview due to session failure.
621 $this->mTriedSave
= !$this->preview
;
623 if ( $this->tokenOk( $request ) ) {
624 # Some browsers will not report any submit button
625 # if the user hits enter in the comment box.
626 # The unmarked state will be assumed to be a save,
627 # if the form seems otherwise complete.
628 wfDebug( __METHOD__
. ": Passed token check.\n" );
629 } elseif ( $this->diff
) {
630 # Failed token check, but only requested "Show Changes".
631 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
633 # Page might be a hack attempt posted from
634 # an external site. Preview instead of saving.
635 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
636 $this->preview
= true;
639 $this->save
= !$this->preview
&& !$this->diff
;
640 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
641 $this->edittime
= null;
644 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
645 $this->starttime
= null;
648 $this->recreate
= $request->getCheck( 'wpRecreate' );
650 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
651 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
653 # Don't force edit summaries when a user is editing their own user or talk page
654 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
655 $this->mTitle
->getText() == $wgUser->getName() )
657 $this->allowBlankSummary
= true;
659 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary' );
662 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
664 # Not a posted form? Start with nothing.
665 wfDebug( __METHOD__
. ": Not a posted form.\n" );
666 $this->textbox1
= '';
668 $this->sectiontitle
= '';
669 $this->edittime
= '';
670 $this->starttime
= wfTimestampNow();
672 $this->preview
= false;
675 $this->minoredit
= false;
676 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
677 $this->recreate
= false;
679 // When creating a new section, we can preload a section title by passing it as the
680 // preloadtitle parameter in the URL (Bug 13100)
681 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
682 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
683 // Once wpSummary isn't being use for setting section titles, we should delete this.
684 $this->summary
= $request->getVal( 'preloadtitle' );
686 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
687 $this->summary
= $request->getText( 'summary' );
688 if ( $this->summary
!== '' ) {
689 $this->hasPresetSummary
= true;
693 if ( $request->getVal( 'minor' ) ) {
694 $this->minoredit
= true;
698 $this->bot
= $request->getBool( 'bot', true );
699 $this->nosummary
= $request->getBool( 'nosummary' );
701 $this->oldid
= $request->getInt( 'oldid' );
703 $this->live
= $request->getCheck( 'live' );
704 $this->editintro
= $request->getText( 'editintro',
705 // Custom edit intro for new sections
706 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
708 // Allow extensions to modify form data
709 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
711 wfProfileOut( __METHOD__
);
715 * Subpage overridable method for extracting the page content data from the
716 * posted form to be placed in $this->textbox1, if using customized input
717 * this method should be overrided and return the page text that will be used
718 * for saving, preview parsing and so on...
720 * @param $request WebRequest
722 protected function importContentFormData( &$request ) {
723 return; // Don't do anything, EditPage already extracted wpTextbox1
727 * Initialise form fields in the object
728 * Called on the first invocation, e.g. when a user clicks an edit link
729 * @return bool -- if the requested section is valid
731 function initialiseForm() {
733 $this->edittime
= $this->mArticle
->getTimestamp();
734 $this->textbox1
= $this->getContent( false );
735 // activate checkboxes if user wants them to be always active
736 # Sort out the "watch" checkbox
737 if ( $wgUser->getOption( 'watchdefault' ) ) {
739 $this->watchthis
= true;
740 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
742 $this->watchthis
= true;
743 } elseif ( $this->mTitle
->userIsWatching() ) {
745 $this->watchthis
= true;
747 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
748 $this->minoredit
= true;
750 if ( $this->textbox1
=== false ) {
758 * Fetch initial editing page content.
760 * @param $def_text string
761 * @return mixed string on success, $def_text for invalid sections
764 function getContent( $def_text = '' ) {
765 global $wgOut, $wgRequest, $wgParser;
767 wfProfileIn( __METHOD__
);
771 // For message page not locally set, use the i18n message.
772 // For other non-existent articles, use preload text if any.
773 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
774 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
775 # If this is a system message, get the default text.
776 $text = $this->mTitle
->getDefaultMessageText();
778 if ( $text === false ) {
779 # If requested, preload some text.
780 $preload = $wgRequest->getVal( 'preload',
781 // Custom preload text for new sections
782 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
783 $text = $this->getPreloadedText( $preload );
785 // For existing pages, get text based on "undo" or section parameters.
787 if ( $this->section
!= '' ) {
788 // Get section edit text (returns $def_text for invalid sections)
789 $text = $wgParser->getSection( $this->getOriginalContent(), $this->section
, $def_text );
791 $undoafter = $wgRequest->getInt( 'undoafter' );
792 $undo = $wgRequest->getInt( 'undo' );
794 if ( $undo > 0 && $undoafter > 0 ) {
795 if ( $undo < $undoafter ) {
796 # If they got undoafter and undo round the wrong way, switch them
797 list( $undo, $undoafter ) = array( $undoafter, $undo );
800 $undorev = Revision
::newFromId( $undo );
801 $oldrev = Revision
::newFromId( $undoafter );
803 # Sanity check, make sure it's the right page,
804 # the revisions exist and they were not deleted.
805 # Otherwise, $text will be left as-is.
806 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
807 $undorev->getPage() == $oldrev->getPage() &&
808 $undorev->getPage() == $this->mTitle
->getArticleID() &&
809 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
810 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
812 $text = $this->mArticle
->getUndoText( $undorev, $oldrev );
813 if ( $text === false ) {
814 # Warn the user that something went wrong
815 $undoMsg = 'failure';
817 # Inform the user of our success and set an automatic edit summary
818 $undoMsg = 'success';
820 # If we just undid one rev, use an autosummary
821 $firstrev = $oldrev->getNext();
822 if ( $firstrev->getId() == $undo ) {
823 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
824 if ( $this->summary
=== '' ) {
825 $this->summary
= $undoSummary;
827 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
829 $this->undidRev
= $undo;
831 $this->formtype
= 'diff';
834 // Failed basic sanity checks.
835 // Older revisions may have been removed since the link
836 // was created, or we may simply have got bogus input.
840 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
841 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
842 wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
845 if ( $text === false ) {
846 $text = $this->getOriginalContent();
851 wfProfileOut( __METHOD__
);
856 * Get the content of the wanted revision, without section extraction.
858 * The result of this function can be used to compare user's input with
859 * section replaced in its context (using WikiPage::replaceSection())
860 * to the original text of the edit.
862 * This difers from Article::getContent() that when a missing revision is
863 * encountered the result will be an empty string and not the
864 * 'missing-article' message.
869 private function getOriginalContent() {
870 if ( $this->section
== 'new' ) {
871 return $this->getCurrentText();
873 $revision = $this->mArticle
->getRevisionFetched();
874 if ( $revision === null ) {
877 return $this->mArticle
->getContent();
881 * Get the actual text of the page. This is basically similar to
882 * WikiPage::getRawText() except that when the page doesn't exist an empty
883 * string is returned instead of false.
888 private function getCurrentText() {
889 $text = $this->mArticle
->getRawText();
890 if ( $text === false ) {
898 * Use this method before edit() to preload some text into the edit box
900 * @param $text string
902 public function setPreloadedText( $text ) {
903 $this->mPreloadText
= $text;
907 * Get the contents to be preloaded into the box, either set by
908 * an earlier setPreloadText() or by loading the given page.
910 * @param $preload String: representing the title to preload from.
913 protected function getPreloadedText( $preload ) {
914 global $wgUser, $wgParser;
916 if ( !empty( $this->mPreloadText
) ) {
917 return $this->mPreloadText
;
920 if ( $preload === '' ) {
924 $title = Title
::newFromText( $preload );
925 # Check for existence to avoid getting MediaWiki:Noarticletext
926 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
930 $page = WikiPage
::factory( $title );
931 if ( $page->isRedirect() ) {
932 $title = $page->getRedirectTarget();
934 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
937 $page = WikiPage
::factory( $title );
940 $parserOptions = ParserOptions
::newFromUser( $wgUser );
941 return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
945 * Make sure the form isn't faking a user's credentials.
947 * @param $request WebRequest
951 function tokenOk( &$request ) {
953 $token = $request->getVal( 'wpEditToken' );
954 $this->mTokenOk
= $wgUser->matchEditToken( $token );
955 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
956 return $this->mTokenOk
;
961 * @return bool false if output is done, true if the rest of the form should be displayed
963 function attemptSave() {
964 global $wgUser, $wgOut;
966 $resultDetails = false;
967 # Allow bots to exempt some edits from bot flagging
968 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
969 $status = $this->internalAttemptSave( $resultDetails, $bot );
970 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
972 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
973 $this->didSave
= true;
976 switch ( $status->value
) {
977 case self
::AS_HOOK_ERROR_EXPECTED
:
978 case self
::AS_CONTENT_TOO_BIG
:
979 case self
::AS_ARTICLE_WAS_DELETED
:
980 case self
::AS_CONFLICT_DETECTED
:
981 case self
::AS_SUMMARY_NEEDED
:
982 case self
::AS_TEXTBOX_EMPTY
:
983 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
987 case self
::AS_HOOK_ERROR
:
988 case self
::AS_FILTERING
:
991 case self
::AS_SUCCESS_NEW_ARTICLE
:
992 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
993 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
994 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
997 case self
::AS_SUCCESS_UPDATE
:
999 $sectionanchor = $resultDetails['sectionanchor'];
1001 // Give extensions a chance to modify URL query on update
1002 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1004 if ( $resultDetails['redirect'] ) {
1005 if ( $extraQuery == '' ) {
1006 $extraQuery = 'redirect=no';
1008 $extraQuery = 'redirect=no&' . $extraQuery;
1011 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1014 case self
::AS_BLANK_ARTICLE
:
1015 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1018 case self
::AS_SPAM_ERROR
:
1019 $this->spamPageWithContent( $resultDetails['spam'] );
1022 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1023 throw new UserBlockedError( $wgUser->getBlock() );
1025 case self
::AS_IMAGE_REDIRECT_ANON
:
1026 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1027 throw new PermissionsError( 'upload' );
1029 case self
::AS_READ_ONLY_PAGE_ANON
:
1030 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1031 throw new PermissionsError( 'edit' );
1033 case self
::AS_READ_ONLY_PAGE
:
1034 throw new ReadOnlyError
;
1036 case self
::AS_RATE_LIMITED
:
1037 throw new ThrottledError();
1039 case self
::AS_NO_CREATE_PERMISSION
:
1040 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1041 throw new PermissionsError( $permission );
1048 * Attempt submission (no UI)
1053 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1055 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1056 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1057 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1059 function internalAttemptSave( &$result, $bot = false ) {
1060 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
1061 global $wgMaxArticleSize;
1063 $status = Status
::newGood();
1065 wfProfileIn( __METHOD__
);
1066 wfProfileIn( __METHOD__
. '-checks' );
1068 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1069 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1070 $status->fatal( 'hookaborted' );
1071 $status->value
= self
::AS_HOOK_ERROR
;
1072 wfProfileOut( __METHOD__
. '-checks' );
1073 wfProfileOut( __METHOD__
);
1077 # Check image redirect
1078 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1079 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
1080 !$wgUser->isAllowed( 'upload' ) ) {
1081 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1082 $status->setResult( false, $code );
1084 wfProfileOut( __METHOD__
. '-checks' );
1085 wfProfileOut( __METHOD__
);
1091 $match = self
::matchSummarySpamRegex( $this->summary
);
1092 if ( $match === false ) {
1093 $match = self
::matchSpamRegex( $this->textbox1
);
1095 if ( $match !== false ) {
1096 $result['spam'] = $match;
1097 $ip = $wgRequest->getIP();
1098 $pdbk = $this->mTitle
->getPrefixedDBkey();
1099 $match = str_replace( "\n", '', $match );
1100 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1101 $status->fatal( 'spamprotectionmatch', $match );
1102 $status->value
= self
::AS_SPAM_ERROR
;
1103 wfProfileOut( __METHOD__
. '-checks' );
1104 wfProfileOut( __METHOD__
);
1107 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
1108 # Error messages or other handling should be performed by the filter function
1109 $status->setResult( false, self
::AS_FILTERING
);
1110 wfProfileOut( __METHOD__
. '-checks' );
1111 wfProfileOut( __METHOD__
);
1114 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1115 # Error messages etc. could be handled within the hook...
1116 $status->fatal( 'hookaborted' );
1117 $status->value
= self
::AS_HOOK_ERROR
;
1118 wfProfileOut( __METHOD__
. '-checks' );
1119 wfProfileOut( __METHOD__
);
1121 } elseif ( $this->hookError
!= '' ) {
1122 # ...or the hook could be expecting us to produce an error
1123 $status->fatal( 'hookaborted' );
1124 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1125 wfProfileOut( __METHOD__
. '-checks' );
1126 wfProfileOut( __METHOD__
);
1130 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1131 // Auto-block user's IP if the account was "hard" blocked
1132 $wgUser->spreadAnyEditBlock();
1133 # Check block state against master, thus 'false'.
1134 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1135 wfProfileOut( __METHOD__
. '-checks' );
1136 wfProfileOut( __METHOD__
);
1140 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1141 if ( $this->kblength
> $wgMaxArticleSize ) {
1142 // Error will be displayed by showEditForm()
1143 $this->tooBig
= true;
1144 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1145 wfProfileOut( __METHOD__
. '-checks' );
1146 wfProfileOut( __METHOD__
);
1150 if ( !$wgUser->isAllowed( 'edit' ) ) {
1151 if ( $wgUser->isAnon() ) {
1152 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1153 wfProfileOut( __METHOD__
. '-checks' );
1154 wfProfileOut( __METHOD__
);
1157 $status->fatal( 'readonlytext' );
1158 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1159 wfProfileOut( __METHOD__
. '-checks' );
1160 wfProfileOut( __METHOD__
);
1165 if ( wfReadOnly() ) {
1166 $status->fatal( 'readonlytext' );
1167 $status->value
= self
::AS_READ_ONLY_PAGE
;
1168 wfProfileOut( __METHOD__
. '-checks' );
1169 wfProfileOut( __METHOD__
);
1172 if ( $wgUser->pingLimiter() ) {
1173 $status->fatal( 'actionthrottledtext' );
1174 $status->value
= self
::AS_RATE_LIMITED
;
1175 wfProfileOut( __METHOD__
. '-checks' );
1176 wfProfileOut( __METHOD__
);
1180 # If the article has been deleted while editing, don't save it without
1182 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1183 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1184 wfProfileOut( __METHOD__
. '-checks' );
1185 wfProfileOut( __METHOD__
);
1189 wfProfileOut( __METHOD__
. '-checks' );
1191 # If article is new, insert it.
1192 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1193 $new = ( $aid == 0 );
1196 // Late check for create permission, just in case *PARANOIA*
1197 if ( !$this->mTitle
->userCan( 'create' ) ) {
1198 $status->fatal( 'nocreatetext' );
1199 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1200 wfDebug( __METHOD__
. ": no create permission\n" );
1201 wfProfileOut( __METHOD__
);
1205 # Don't save a new article if it's blank.
1206 if ( $this->textbox1
== '' ) {
1207 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1208 wfProfileOut( __METHOD__
);
1212 // Run post-section-merge edit filter
1213 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1214 # Error messages etc. could be handled within the hook...
1215 $status->fatal( 'hookaborted' );
1216 $status->value
= self
::AS_HOOK_ERROR
;
1217 wfProfileOut( __METHOD__
);
1219 } elseif ( $this->hookError
!= '' ) {
1220 # ...or the hook could be expecting us to produce an error
1221 $status->fatal( 'hookaborted' );
1222 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1223 wfProfileOut( __METHOD__
);
1227 $text = $this->textbox1
;
1228 $result['sectionanchor'] = '';
1229 if ( $this->section
== 'new' ) {
1230 if ( $this->sectiontitle
!== '' ) {
1231 // Insert the section title above the content.
1232 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle
) . "\n\n" . $text;
1234 // Jump to the new section
1235 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1237 // If no edit summary was specified, create one automatically from the section
1238 // title and have it link to the new section. Otherwise, respect the summary as
1240 if ( $this->summary
=== '' ) {
1241 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1242 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1244 } elseif ( $this->summary
!== '' ) {
1245 // Insert the section title above the content.
1246 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $text;
1248 // Jump to the new section
1249 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1251 // Create a link to the new section from the edit summary.
1252 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1253 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1257 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1261 # Article exists. Check for edit conflict.
1263 $this->mArticle
->clear(); # Force reload of dates, etc.
1264 $timestamp = $this->mArticle
->getTimestamp();
1266 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1268 if ( $timestamp != $this->edittime
) {
1269 $this->isConflict
= true;
1270 if ( $this->section
== 'new' ) {
1271 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1272 $this->mArticle
->getComment() == $this->summary
) {
1273 // Probably a duplicate submission of a new comment.
1274 // This can happen when squid resends a request after
1275 // a timeout but the first one actually went through.
1276 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1278 // New comment; suppress conflict.
1279 $this->isConflict
= false;
1280 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1282 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1283 # Suppress edit conflict with self, except for section edits where merging is required.
1284 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1285 $this->isConflict
= false;
1289 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1290 // backwards compatibility with old forms/bots).
1291 if ( $this->sectiontitle
!== '' ) {
1292 $sectionTitle = $this->sectiontitle
;
1294 $sectionTitle = $this->summary
;
1297 if ( $this->isConflict
) {
1298 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1299 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle, $this->edittime
);
1301 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1302 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle );
1304 if ( is_null( $text ) ) {
1305 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1306 $this->isConflict
= true;
1307 $text = $this->textbox1
; // do not try to merge here!
1308 } elseif ( $this->isConflict
) {
1310 if ( $this->mergeChangesInto( $text ) ) {
1311 // Successful merge! Maybe we should tell the user the good news?
1312 $this->isConflict
= false;
1313 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1315 $this->section
= '';
1316 $this->textbox1
= $text;
1317 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1321 if ( $this->isConflict
) {
1322 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1323 wfProfileOut( __METHOD__
);
1327 // Run post-section-merge edit filter
1328 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
1329 # Error messages etc. could be handled within the hook...
1330 $status->fatal( 'hookaborted' );
1331 $status->value
= self
::AS_HOOK_ERROR
;
1332 wfProfileOut( __METHOD__
);
1334 } elseif ( $this->hookError
!= '' ) {
1335 # ...or the hook could be expecting us to produce an error
1336 $status->fatal( 'hookaborted' );
1337 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1338 wfProfileOut( __METHOD__
);
1342 # Handle the user preference to force summaries here, but not for null edits
1343 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1344 && $this->getOriginalContent() != $text
1345 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1347 if ( md5( $this->summary
) == $this->autoSumm
) {
1348 $this->missingSummary
= true;
1349 $status->fatal( 'missingsummary' );
1350 $status->value
= self
::AS_SUMMARY_NEEDED
;
1351 wfProfileOut( __METHOD__
);
1356 # And a similar thing for new sections
1357 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1358 if ( trim( $this->summary
) == '' ) {
1359 $this->missingSummary
= true;
1360 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1361 $status->value
= self
::AS_SUMMARY_NEEDED
;
1362 wfProfileOut( __METHOD__
);
1368 wfProfileIn( __METHOD__
. '-sectionanchor' );
1369 $sectionanchor = '';
1370 if ( $this->section
== 'new' ) {
1371 if ( $this->textbox1
== '' ) {
1372 $this->missingComment
= true;
1373 $status->fatal( 'missingcommenttext' );
1374 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1375 wfProfileOut( __METHOD__
. '-sectionanchor' );
1376 wfProfileOut( __METHOD__
);
1379 if ( $this->sectiontitle
!== '' ) {
1380 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1381 // If no edit summary was specified, create one automatically from the section
1382 // title and have it link to the new section. Otherwise, respect the summary as
1384 if ( $this->summary
=== '' ) {
1385 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1386 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1388 } elseif ( $this->summary
!== '' ) {
1389 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1390 # This is a new section, so create a link to the new section
1391 # in the revision summary.
1392 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1393 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1395 } elseif ( $this->section
!= '' ) {
1396 # Try to get a section anchor from the section source, redirect to edited section if header found
1397 # XXX: might be better to integrate this into Article::replaceSection
1398 # for duplicate heading checking and maybe parsing
1399 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1400 # we can't deal with anchors, includes, html etc in the header for now,
1401 # headline would need to be parsed to improve this
1402 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1403 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1406 $result['sectionanchor'] = $sectionanchor;
1407 wfProfileOut( __METHOD__
. '-sectionanchor' );
1409 // Save errors may fall down to the edit form, but we've now
1410 // merged the section into full text. Clear the section field
1411 // so that later submission of conflict forms won't try to
1412 // replace that into a duplicated mess.
1413 $this->textbox1
= $text;
1414 $this->section
= '';
1416 $status->value
= self
::AS_SUCCESS_UPDATE
;
1419 // Check for length errors again now that the section is merged in
1420 $this->kblength
= (int)( strlen( $text ) / 1024 );
1421 if ( $this->kblength
> $wgMaxArticleSize ) {
1422 $this->tooBig
= true;
1423 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1424 wfProfileOut( __METHOD__
);
1428 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1429 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1430 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1431 ( $bot ? EDIT_FORCE_BOT
: 0 );
1433 $doEditStatus = $this->mArticle
->doEdit( $text, $this->summary
, $flags );
1435 if ( $doEditStatus->isOK() ) {
1436 $result['redirect'] = Title
::newFromRedirect( $text ) !== null;
1437 $this->commitWatch();
1438 wfProfileOut( __METHOD__
);
1441 $this->isConflict
= true;
1442 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1443 wfProfileOut( __METHOD__
);
1444 return $doEditStatus;
1449 * Commit the change of watch status
1451 protected function commitWatch() {
1453 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1454 $dbw = wfGetDB( DB_MASTER
);
1455 $dbw->begin( __METHOD__
);
1456 if ( $this->watchthis
) {
1457 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1459 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1461 $dbw->commit( __METHOD__
);
1466 * Check if no edits were made by other users since
1467 * the time a user started editing the page. Limit to
1468 * 50 revisions for the sake of performance.
1471 * @param $edittime string
1475 protected function userWasLastToEdit( $id, $edittime ) {
1476 if ( !$id ) return false;
1477 $dbw = wfGetDB( DB_MASTER
);
1478 $res = $dbw->select( 'revision',
1481 'rev_page' => $this->mTitle
->getArticleID(),
1482 'rev_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $edittime ) )
1485 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1486 foreach ( $res as $row ) {
1487 if ( $row->rev_user
!= $id ) {
1498 * @parma $editText string
1502 function mergeChangesInto( &$editText ) {
1503 wfProfileIn( __METHOD__
);
1505 $db = wfGetDB( DB_MASTER
);
1507 // This is the revision the editor started from
1508 $baseRevision = $this->getBaseRevision();
1509 if ( is_null( $baseRevision ) ) {
1510 wfProfileOut( __METHOD__
);
1513 $baseText = $baseRevision->getText();
1515 // The current state, we want to merge updates into it
1516 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1517 if ( is_null( $currentRevision ) ) {
1518 wfProfileOut( __METHOD__
);
1521 $currentText = $currentRevision->getText();
1524 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1525 $editText = $result;
1526 wfProfileOut( __METHOD__
);
1529 wfProfileOut( __METHOD__
);
1537 function getBaseRevision() {
1538 if ( !$this->mBaseRevision
) {
1539 $db = wfGetDB( DB_MASTER
);
1540 $baseRevision = Revision
::loadFromTimestamp(
1541 $db, $this->mTitle
, $this->edittime
);
1542 return $this->mBaseRevision
= $baseRevision;
1544 return $this->mBaseRevision
;
1549 * Check given input text against $wgSpamRegex, and return the text of the first match.
1551 * @param $text string
1553 * @return string|bool matching string or false
1555 public static function matchSpamRegex( $text ) {
1556 global $wgSpamRegex;
1557 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1558 $regexes = (array)$wgSpamRegex;
1559 return self
::matchSpamRegexInternal( $text, $regexes );
1563 * Check given input text against $wgSpamRegex, and return the text of the first match.
1565 * @parma $text string
1567 * @return string|bool matching string or false
1569 public static function matchSummarySpamRegex( $text ) {
1570 global $wgSummarySpamRegex;
1571 $regexes = (array)$wgSummarySpamRegex;
1572 return self
::matchSpamRegexInternal( $text, $regexes );
1576 * @param $text string
1577 * @param $regexes array
1578 * @return bool|string
1580 protected static function matchSpamRegexInternal( $text, $regexes ) {
1581 foreach ( $regexes as $regex ) {
1583 if ( preg_match( $regex, $text, $matches ) ) {
1590 function setHeaders() {
1591 global $wgOut, $wgUser;
1593 $wgOut->addModules( 'mediawiki.action.edit' );
1595 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1596 $wgOut->addModules( 'mediawiki.legacy.preview' );
1598 // Bug #19334: textarea jumps when editing articles in IE8
1599 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1601 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1603 # Enabled article-related sidebar, toplinks, etc.
1604 $wgOut->setArticleRelated( true );
1606 $contextTitle = $this->getContextTitle();
1607 if ( $this->isConflict
) {
1608 $msg = 'editconflict';
1609 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1610 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1612 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1613 'editing' : 'creating';
1615 # Use the title defined by DISPLAYTITLE magic word when present
1616 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1617 if ( $displayTitle === false ) {
1618 $displayTitle = $contextTitle->getPrefixedText();
1620 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1624 * Show all applicable editing introductions
1626 protected function showIntro() {
1627 global $wgOut, $wgUser;
1628 if ( $this->suppressIntro
) {
1632 $namespace = $this->mTitle
->getNamespace();
1634 if ( $namespace == NS_MEDIAWIKI
) {
1635 # Show a warning if editing an interface message
1636 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1637 } else if( $namespace == NS_FILE
) {
1638 # Show a hint to shared repo
1639 $file = wfFindFile( $this->mTitle
);
1640 if( $file && !$file->isLocal() ) {
1641 $descUrl = $file->getDescriptionUrl();
1642 # there must be a description url to show a hint to shared repo
1644 if( !$this->mTitle
->exists() ) {
1645 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1646 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1649 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1650 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1657 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1658 # Show log extract when the user is currently blocked
1659 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1660 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1661 $username = $parts[0];
1662 $user = User
::newFromName( $username, false /* allow IP users*/ );
1663 $ip = User
::isIP( $username );
1664 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1665 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1666 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1667 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1668 LogEventsList
::showLogExtract(
1671 $user->getUserPage(),
1675 'showIfEmpty' => false,
1677 'blocked-notice-logextract',
1678 $user->getName() # Support GENDER in notice
1684 # Try to add a custom edit intro, or use the standard one if this is not possible.
1685 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1686 if ( $wgUser->isLoggedIn() ) {
1687 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1689 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1692 # Give a notice if the user is editing a deleted/moved page...
1693 if ( !$this->mTitle
->exists() ) {
1694 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1695 '', array( 'lim' => 10,
1696 'conds' => array( "log_action != 'revision'" ),
1697 'showIfEmpty' => false,
1698 'msgKey' => array( 'recreate-moveddeleted-warn' ) )
1704 * Attempt to show a custom editing introduction, if supplied
1708 protected function showCustomIntro() {
1709 if ( $this->editintro
) {
1710 $title = Title
::newFromText( $this->editintro
);
1711 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1713 // Added using template syntax, to take <noinclude>'s into account.
1714 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1725 * Send the edit form and related headers to $wgOut
1726 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1727 * during form output near the top, for captchas and the like.
1729 function showEditForm( $formCallback = null ) {
1730 global $wgOut, $wgUser;
1732 wfProfileIn( __METHOD__
);
1734 # need to parse the preview early so that we know which templates are used,
1735 # otherwise users with "show preview after edit box" will get a blank list
1736 # we parse this near the beginning so that setHeaders can do the title
1737 # setting work instead of leaving it in getPreviewText
1738 $previewOutput = '';
1739 if ( $this->formtype
== 'preview' ) {
1740 $previewOutput = $this->getPreviewText();
1743 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
1745 $this->setHeaders();
1747 if ( $this->showHeader() === false ) {
1748 wfProfileOut( __METHOD__
);
1752 $wgOut->addHTML( $this->editFormPageTop
);
1754 if ( $wgUser->getOption( 'previewontop' ) ) {
1755 $this->displayPreviewArea( $previewOutput, true );
1758 $wgOut->addHTML( $this->editFormTextTop
);
1760 $showToolbar = true;
1761 if ( $this->wasDeletedSinceLastEdit() ) {
1762 if ( $this->formtype
== 'save' ) {
1763 // Hide the toolbar and edit area, user can click preview to get it back
1764 // Add an confirmation checkbox and explanation.
1765 $showToolbar = false;
1767 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1768 'deletedwhileediting' );
1772 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
1773 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1774 'enctype' => 'multipart/form-data' ) ) );
1776 if ( is_callable( $formCallback ) ) {
1777 call_user_func_array( $formCallback, array( &$wgOut ) );
1780 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1782 // Put these up at the top to ensure they aren't lost on early form submission
1783 $this->showFormBeforeText();
1785 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1786 $username = $this->lastDelete
->user_name
;
1787 $comment = $this->lastDelete
->log_comment
;
1789 // It is better to not parse the comment at all than to have templates expanded in the middle
1790 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1791 $key = $comment === ''
1792 ?
'confirmrecreate-noreason'
1793 : 'confirmrecreate';
1795 '<div class="mw-confirm-recreate">' .
1796 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1797 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1798 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1804 # When the summary is hidden, also hide them on preview/show changes
1805 if( $this->nosummary
) {
1806 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
1809 # If a blank edit summary was previously provided, and the appropriate
1810 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1811 # user being bounced back more than once in the event that a summary
1814 # For a bit more sophisticated detection of blank summaries, hash the
1815 # automatic one and pass that in the hidden field wpAutoSummary.
1816 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
1817 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1820 if ( $this->hasPresetSummary
) {
1821 // If a summary has been preset using &summary= we dont want to prompt for
1822 // a different summary. Only prompt for a summary if the summary is blanked.
1824 $this->autoSumm
= md5( '' );
1827 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1828 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1830 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
1832 if ( $this->section
== 'new' ) {
1833 $this->showSummaryInput( true, $this->summary
);
1834 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1837 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1839 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1840 $wgOut->addHTML( EditPage
::getEditToolbar() );
1843 if ( $this->isConflict
) {
1844 // In an edit conflict bypass the overrideable content form method
1845 // and fallback to the raw wpTextbox1 since editconflicts can't be
1846 // resolved between page source edits and custom ui edits using the
1848 $this->textbox2
= $this->textbox1
;
1849 $this->textbox1
= $this->getCurrentText();
1851 $this->showTextbox1();
1853 $this->showContentForm();
1856 $wgOut->addHTML( $this->editFormTextAfterContent
);
1858 $wgOut->addWikiText( $this->getCopywarn() );
1860 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1862 $this->showStandardInputs();
1864 $this->showFormAfterText();
1866 $this->showTosSummary();
1868 $this->showEditTools();
1870 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
1872 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
1873 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
1875 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
1876 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
1878 if ( $this->isConflict
) {
1879 $this->showConflict();
1882 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
1884 if ( !$wgUser->getOption( 'previewontop' ) ) {
1885 $this->displayPreviewArea( $previewOutput, false );
1888 wfProfileOut( __METHOD__
);
1892 * Extract the section title from current section text, if any.
1894 * @param string $text
1895 * @return Mixed|string or false
1897 public static function extractSectionTitle( $text ) {
1898 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
1899 if ( !empty( $matches[2] ) ) {
1901 return $wgParser->stripSectionName( trim( $matches[2] ) );
1907 protected function showHeader() {
1908 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1910 if ( $this->mTitle
->isTalkPage() ) {
1911 $wgOut->addWikiMsg( 'talkpagetext' );
1914 # Optional notices on a per-namespace and per-page basis
1915 $editnotice_ns = 'editnotice-' . $this->mTitle
->getNamespace();
1916 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
1917 if ( $editnotice_ns_message->exists() ) {
1918 $wgOut->addWikiText( $editnotice_ns_message->plain() );
1920 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
1921 $parts = explode( '/', $this->mTitle
->getDBkey() );
1922 $editnotice_base = $editnotice_ns;
1923 while ( count( $parts ) > 0 ) {
1924 $editnotice_base .= '-' . array_shift( $parts );
1925 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
1926 if ( $editnotice_base_msg->exists() ) {
1927 $wgOut->addWikiText( $editnotice_base_msg->plain() );
1931 # Even if there are no subpages in namespace, we still don't want / in MW ns.
1932 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
1933 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
1934 if ( $editnoticeMsg->exists() ) {
1935 $wgOut->addWikiText( $editnoticeMsg->plain() );
1939 if ( $this->isConflict
) {
1940 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1941 $this->edittime
= $this->mArticle
->getTimestamp();
1943 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
1944 // We use $this->section to much before this and getVal('wgSection') directly in other places
1945 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1946 // Someone is welcome to try refactoring though
1947 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1951 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1952 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1953 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
1954 if ( $sectionTitle !== false ) {
1955 $this->summary
= "/* $sectionTitle */ ";
1960 if ( $this->missingComment
) {
1961 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1964 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1965 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1968 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1969 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1972 if ( $this->hookError
!== '' ) {
1973 $wgOut->addWikiText( $this->hookError
);
1976 if ( !$this->checkUnicodeCompliantBrowser() ) {
1977 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1980 if ( $this->section
!= 'new' ) {
1981 $revision = $this->mArticle
->getRevisionFetched();
1983 // Let sysop know that this will make private content public if saved
1985 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
1986 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1987 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
1988 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1991 if ( !$revision->isCurrent() ) {
1992 $this->mArticle
->setOldSubtitle( $revision->getId() );
1993 $wgOut->addWikiMsg( 'editingold' );
1995 } elseif ( $this->mTitle
->exists() ) {
1996 // Something went wrong
1998 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
1999 array( 'missing-article', $this->mTitle
->getPrefixedText(),
2000 wfMsgNoTrans( 'missingarticle-rev', $this->oldid
) ) );
2005 if ( wfReadOnly() ) {
2006 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2007 } elseif ( $wgUser->isAnon() ) {
2008 if ( $this->formtype
!= 'preview' ) {
2009 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2011 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2014 if ( $this->isCssJsSubpage
) {
2015 # Check the skin exists
2016 if ( $this->isWrongCaseCssJsPage
) {
2017 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2019 if ( $this->formtype
!== 'preview' ) {
2020 if ( $this->isCssSubpage
)
2021 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2022 if ( $this->isJsSubpage
)
2023 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2028 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2029 # Is the title semi-protected?
2030 if ( $this->mTitle
->isSemiProtected() ) {
2031 $noticeMsg = 'semiprotectedpagewarning';
2033 # Then it must be protected based on static groups (regular)
2034 $noticeMsg = 'protectedpagewarning';
2036 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2037 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2039 if ( $this->mTitle
->isCascadeProtected() ) {
2040 # Is this page under cascading protection from some source pages?
2041 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2042 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2043 $cascadeSourcesCount = count( $cascadeSources );
2044 if ( $cascadeSourcesCount > 0 ) {
2045 # Explain, and list the titles responsible
2046 foreach ( $cascadeSources as $page ) {
2047 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2050 $notice .= '</div>';
2051 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2053 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2054 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2056 'showIfEmpty' => false,
2057 'msgKey' => array( 'titleprotectedwarning' ),
2058 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2061 if ( $this->kblength
=== false ) {
2062 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2065 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2066 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2067 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2069 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2070 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2071 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2078 * Standard summary input and label (wgSummary), abstracted so EditPage
2079 * subclasses may reorganize the form.
2080 * Note that you do not need to worry about the label's for=, it will be
2081 * inferred by the id given to the input. You can remove them both by
2082 * passing array( 'id' => false ) to $userInputAttrs.
2084 * @param $summary string The value of the summary input
2085 * @param $labelText string The html to place inside the label
2086 * @param $inputAttrs array of attrs to use on the input
2087 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2089 * @return array An array in the format array( $label, $input )
2091 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2092 // Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
2093 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2094 'id' => 'wpSummary',
2095 'maxlength' => '200',
2098 'spellcheck' => 'true',
2099 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2101 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2102 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2103 'id' => "wpSummaryLabel"
2108 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2109 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2112 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2114 return array( $label, $input );
2118 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2119 * up top, or false if this is the comment summary
2120 * down below the textarea
2121 * @param $summary String: The text of the summary to display
2124 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2125 global $wgOut, $wgContLang;
2126 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2127 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2128 if ( $isSubjectPreview ) {
2129 if ( $this->nosummary
) {
2133 if ( !$this->mShowSummaryField
) {
2137 $summary = $wgContLang->recodeForEdit( $summary );
2138 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
2139 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2140 $wgOut->addHTML( "{$label} {$input}" );
2144 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2145 * up top, or false if this is the comment summary
2146 * down below the textarea
2147 * @param $summary String: the text of the summary to display
2150 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2151 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2156 if ( $isSubjectPreview )
2157 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2159 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2161 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2162 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2165 protected function showFormBeforeText() {
2167 $section = htmlspecialchars( $this->section
);
2168 $wgOut->addHTML( <<<HTML
2169 <input type='hidden' value="{$section}" name="wpSection" />
2170 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2171 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2172 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2176 if ( !$this->checkUnicodeCompliantBrowser() )
2177 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2180 protected function showFormAfterText() {
2181 global $wgOut, $wgUser;
2183 * To make it harder for someone to slip a user a page
2184 * which submits an edit form to the wiki without their
2185 * knowledge, a random token is associated with the login
2186 * session. If it's not passed back with the submission,
2187 * we won't save the page, or render user JavaScript and
2190 * For anon editors, who may not have a session, we just
2191 * include the constant suffix to prevent editing from
2192 * broken text-mangling proxies.
2194 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2198 * Subpage overridable method for printing the form for page content editing
2199 * By default this simply outputs wpTextbox1
2200 * Subclasses can override this to provide a custom UI for editing;
2201 * be it a form, or simply wpTextbox1 with a modified content that will be
2202 * reverse modified when extracted from the post data.
2203 * Note that this is basically the inverse for importContentFormData
2205 protected function showContentForm() {
2206 $this->showTextbox1();
2210 * Method to output wpTextbox1
2211 * The $textoverride method can be used by subclasses overriding showContentForm
2212 * to pass back to this method.
2214 * @param $customAttribs array of html attributes to use in the textarea
2215 * @param $textoverride String: optional text to override $this->textarea1 with
2217 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2218 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2219 $attribs = array( 'style' => 'display:none;' );
2221 $classes = array(); // Textarea CSS
2222 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2223 # Is the title semi-protected?
2224 if ( $this->mTitle
->isSemiProtected() ) {
2225 $classes[] = 'mw-textarea-sprotected';
2227 # Then it must be protected based on static groups (regular)
2228 $classes[] = 'mw-textarea-protected';
2230 # Is the title cascade-protected?
2231 if ( $this->mTitle
->isCascadeProtected() ) {
2232 $classes[] = 'mw-textarea-cprotected';
2236 $attribs = array( 'tabindex' => 1 );
2238 if ( is_array( $customAttribs ) ) {
2239 $attribs +
= $customAttribs;
2242 if ( count( $classes ) ) {
2243 if ( isset( $attribs['class'] ) ) {
2244 $classes[] = $attribs['class'];
2246 $attribs['class'] = implode( ' ', $classes );
2250 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2253 protected function showTextbox2() {
2254 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2257 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2258 global $wgOut, $wgUser;
2260 $wikitext = $this->safeUnicodeOutput( $content );
2261 if ( strval( $wikitext ) !== '' ) {
2262 // Ensure there's a newline at the end, otherwise adding lines
2264 // But don't add a newline if the ext is empty, or Firefox in XHTML
2265 // mode will show an extra newline. A bit annoying.
2269 $attribs = $customAttribs +
array(
2272 'cols' => $wgUser->getIntOption( 'cols' ),
2273 'rows' => $wgUser->getIntOption( 'rows' ),
2274 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2277 $pageLang = $this->mTitle
->getPageLanguage();
2278 $attribs['lang'] = $pageLang->getCode();
2279 $attribs['dir'] = $pageLang->getDir();
2281 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2284 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2288 $classes[] = 'ontop';
2290 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2292 if ( $this->formtype
!= 'preview' )
2293 $attribs['style'] = 'display: none;';
2295 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2297 if ( $this->formtype
== 'preview' ) {
2298 $this->showPreview( $previewOutput );
2301 $wgOut->addHTML( '</div>' );
2303 if ( $this->formtype
== 'diff' ) {
2309 * Append preview output to $wgOut.
2310 * Includes category rendering if this is a category page.
2312 * @param $text String: the HTML to be output for the preview.
2314 protected function showPreview( $text ) {
2316 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2317 $this->mArticle
->openShowCategory();
2319 # This hook seems slightly odd here, but makes things more
2320 # consistent for extensions.
2321 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2322 $wgOut->addHTML( $text );
2323 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2324 $this->mArticle
->closeShowCategory();
2329 * Get a diff between the current contents of the edit box and the
2330 * version of the page we're editing from.
2332 * If this is a section edit, we'll replace the section as for final
2333 * save and then make a comparison.
2335 function showDiff() {
2336 global $wgUser, $wgContLang, $wgParser, $wgOut;
2338 $oldtitlemsg = 'currentrev';
2339 # if message does not exist, show diff against the preloaded default
2340 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2341 $oldtext = $this->mTitle
->getDefaultMessageText();
2342 if( $oldtext !== false ) {
2343 $oldtitlemsg = 'defaultmessagetext';
2346 $oldtext = $this->mArticle
->getRawText();
2348 $newtext = $this->mArticle
->replaceSection(
2349 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2351 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2353 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2354 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle
, $wgUser, $popts );
2356 if ( $oldtext !== false ||
$newtext != '' ) {
2357 $oldtitle = wfMsgExt( $oldtitlemsg, array( 'parseinline' ) );
2358 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2360 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2361 $de->setText( $oldtext, $newtext );
2362 $difftext = $de->getDiff( $oldtitle, $newtitle );
2363 $de->showDiffStyle();
2368 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2372 * Give a chance for site and per-namespace customizations of
2373 * terms of service summary link that might exist separately
2374 * from the copyright notice.
2376 * This will display between the save button and the edit tools,
2377 * so should remain short!
2379 protected function showTosSummary() {
2380 $msg = 'editpage-tos-summary';
2381 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2382 if ( !wfMessage( $msg )->isDisabled() ) {
2384 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2385 $wgOut->addWikiMsg( $msg );
2386 $wgOut->addHTML( '</div>' );
2390 protected function showEditTools() {
2392 $wgOut->addHTML( '<div class="mw-editTools">' .
2393 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2397 protected function getCopywarn() {
2398 global $wgRightsText;
2399 if ( $wgRightsText ) {
2400 $copywarnMsg = array( 'copyrightwarning',
2401 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2404 $copywarnMsg = array( 'copyrightwarning2',
2405 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2407 // Allow for site and per-namespace customization of contribution/copyright notice.
2408 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2410 return "<div id=\"editpage-copywarn\">\n" .
2411 call_user_func_array( "wfMsgNoTrans", $copywarnMsg ) . "\n</div>";
2414 protected function showStandardInputs( &$tabindex = 2 ) {
2416 $wgOut->addHTML( "<div class='editOptions'>\n" );
2418 if ( $this->section
!= 'new' ) {
2419 $this->showSummaryInput( false, $this->summary
);
2420 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2423 $checkboxes = $this->getCheckboxes( $tabindex,
2424 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2425 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2426 $wgOut->addHTML( "<div class='editButtons'>\n" );
2427 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2429 $cancel = $this->getCancelLink();
2430 if ( $cancel !== '' ) {
2431 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2433 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2434 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2435 htmlspecialchars( wfMsg( 'edithelp' ) ) . '</a> ' .
2436 htmlspecialchars( wfMsg( 'newwindow' ) );
2437 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2438 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2442 * Show an edit conflict. textbox1 is already shown in showEditForm().
2443 * If you want to use another entry point to this function, be careful.
2445 protected function showConflict() {
2448 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2449 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2451 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2452 $de->setText( $this->textbox2
, $this->textbox1
);
2453 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2455 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2456 $this->showTextbox2();
2463 public function getCancelLink() {
2464 $cancelParams = array();
2465 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2466 $cancelParams['oldid'] = $this->oldid
;
2469 return Linker
::linkKnown(
2470 $this->getContextTitle(),
2471 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2472 array( 'id' => 'mw-editform-cancel' ),
2478 * Returns the URL to use in the form's action attribute.
2479 * This is used by EditPage subclasses when simply customizing the action
2480 * variable in the constructor is not enough. This can be used when the
2481 * EditPage lives inside of a Special page rather than a custom page action.
2483 * @param $title Title object for which is being edited (where we go to for &action= links)
2486 protected function getActionURL( Title
$title ) {
2487 return $title->getLocalURL( array( 'action' => $this->action
) );
2491 * Check if a page was deleted while the user was editing it, before submit.
2492 * Note that we rely on the logging table, which hasn't been always there,
2493 * but that doesn't matter, because this only applies to brand new
2496 protected function wasDeletedSinceLastEdit() {
2497 if ( $this->deletedSinceEdit
!== null ) {
2498 return $this->deletedSinceEdit
;
2501 $this->deletedSinceEdit
= false;
2503 if ( $this->mTitle
->isDeletedQuick() ) {
2504 $this->lastDelete
= $this->getLastDelete();
2505 if ( $this->lastDelete
) {
2506 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2507 if ( $deleteTime > $this->starttime
) {
2508 $this->deletedSinceEdit
= true;
2513 return $this->deletedSinceEdit
;
2516 protected function getLastDelete() {
2517 $dbr = wfGetDB( DB_SLAVE
);
2518 $data = $dbr->selectRow(
2519 array( 'logging', 'user' ),
2530 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2531 'log_title' => $this->mTitle
->getDBkey(),
2532 'log_type' => 'delete',
2533 'log_action' => 'delete',
2534 'user_id=log_user' ),
2536 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2538 // Quick paranoid permission checks...
2539 if ( is_object( $data ) ) {
2540 if ( $data->log_deleted
& LogPage
::DELETED_USER
)
2541 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2542 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2543 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2549 * Get the rendered text for previewing.
2552 function getPreviewText() {
2553 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2555 wfProfileIn( __METHOD__
);
2557 if ( $wgRawHtml && !$this->mTokenOk
) {
2558 // Could be an offsite preview attempt. This is very unsafe if
2559 // HTML is enabled, as it could be an attack.
2561 if ( $this->textbox1
!== '' ) {
2562 // Do not put big scary notice, if previewing the empty
2563 // string, which happens when you initially edit
2564 // a category page, due to automatic preview-on-open.
2565 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2566 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2568 wfProfileOut( __METHOD__
);
2572 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2573 if ( $this->mTokenOkExceptSuffix
) {
2574 $note = wfMsg( 'token_suffix_mismatch' );
2576 $note = wfMsg( 'session_fail_preview' );
2578 } elseif ( $this->incompleteForm
) {
2579 $note = wfMsg( 'edit_form_incomplete' );
2581 $note = wfMsg( 'previewnote' );
2584 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2585 $parserOptions->setEditSection( false );
2586 $parserOptions->setTidy( true );
2587 $parserOptions->setIsPreview( true );
2588 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
2590 # don't parse non-wikitext pages, show message about preview
2591 # XXX: stupid php bug won't let us use $this->getContextTitle()->isCssJsSubpage() here -- This note has been there since r3530. Sure the bug was fixed time ago?
2593 if ( $this->isCssJsSubpage ||
!$this->mTitle
->isWikitextPage() ) {
2594 if ( $this->mTitle
->isCssJsSubpage() ) {
2596 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
2602 # Used messages to make sure grep find them:
2603 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2605 if ( preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2606 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2607 $class = "mw-code mw-css";
2608 } elseif ( preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2609 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2610 $class = "mw-code mw-js";
2612 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2616 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2617 $previewHTML = $parserOutput->mText
;
2618 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2620 $toparse = $this->textbox1
;
2622 # If we're adding a comment, we need to show the
2623 # summary as the headline
2624 if ( $this->section
== "new" && $this->summary
!= "" ) {
2625 $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $toparse;
2628 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2630 $parserOptions->enableLimitReport();
2632 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle
, $wgUser, $parserOptions );
2633 $parserOutput = $wgParser->parse( $toparse, $this->mTitle
, $parserOptions );
2635 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2637 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2639 $previewHTML = $parserOutput->getText();
2642 $this->mParserOutput
= $parserOutput;
2643 $wgOut->addParserOutputNoText( $parserOutput );
2645 if ( count( $parserOutput->getWarnings() ) ) {
2646 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2650 if ( $this->isConflict
) {
2651 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2653 $conflict = '<hr />';
2656 $previewhead = "<div class='previewnote'>\n" .
2657 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2658 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2660 $pageLang = $this->mTitle
->getPageLanguage();
2661 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2662 'class' => 'mw-content-' . $pageLang->getDir() );
2663 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2665 wfProfileOut( __METHOD__
);
2666 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2672 function getTemplates() {
2673 if ( $this->preview ||
$this->section
!= '' ) {
2674 $templates = array();
2675 if ( !isset( $this->mParserOutput
) ) {
2678 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
2679 foreach ( array_keys( $template ) as $dbk ) {
2680 $templates[] = Title
::makeTitle( $ns, $dbk );
2685 return $this->mTitle
->getTemplateLinksFrom();
2690 * Shows a bulletin board style toolbar for common editing functions.
2691 * It can be disabled in the user preferences.
2692 * The necessary JavaScript code can be found in skins/common/edit.js.
2696 static function getEditToolbar() {
2697 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2698 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2700 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2703 * $toolarray is an array of arrays each of which includes the
2704 * filename of the button image (without path), the opening
2705 * tag, the closing tag, optionally a sample text that is
2706 * inserted between the two when no selection is highlighted
2707 * and. The tip text is shown when the user moves the mouse
2710 * Also here: accesskeys (key), which are not used yet until
2711 * someone can figure out a way to make them work in
2712 * IE. However, we should make sure these keys are not defined
2717 'image' => $wgLang->getImageFile( 'button-bold' ),
2718 'id' => 'mw-editbutton-bold',
2720 'close' => '\'\'\'',
2721 'sample' => wfMsg( 'bold_sample' ),
2722 'tip' => wfMsg( 'bold_tip' ),
2726 'image' => $wgLang->getImageFile( 'button-italic' ),
2727 'id' => 'mw-editbutton-italic',
2730 'sample' => wfMsg( 'italic_sample' ),
2731 'tip' => wfMsg( 'italic_tip' ),
2735 'image' => $wgLang->getImageFile( 'button-link' ),
2736 'id' => 'mw-editbutton-link',
2739 'sample' => wfMsg( 'link_sample' ),
2740 'tip' => wfMsg( 'link_tip' ),
2744 'image' => $wgLang->getImageFile( 'button-extlink' ),
2745 'id' => 'mw-editbutton-extlink',
2748 'sample' => wfMsg( 'extlink_sample' ),
2749 'tip' => wfMsg( 'extlink_tip' ),
2753 'image' => $wgLang->getImageFile( 'button-headline' ),
2754 'id' => 'mw-editbutton-headline',
2757 'sample' => wfMsg( 'headline_sample' ),
2758 'tip' => wfMsg( 'headline_tip' ),
2761 $imagesAvailable ?
array(
2762 'image' => $wgLang->getImageFile( 'button-image' ),
2763 'id' => 'mw-editbutton-image',
2764 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2766 'sample' => wfMsg( 'image_sample' ),
2767 'tip' => wfMsg( 'image_tip' ),
2770 $imagesAvailable ?
array(
2771 'image' => $wgLang->getImageFile( 'button-media' ),
2772 'id' => 'mw-editbutton-media',
2773 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2775 'sample' => wfMsg( 'media_sample' ),
2776 'tip' => wfMsg( 'media_tip' ),
2780 'image' => $wgLang->getImageFile( 'button-math' ),
2781 'id' => 'mw-editbutton-math',
2783 'close' => "</math>",
2784 'sample' => wfMsg( 'math_sample' ),
2785 'tip' => wfMsg( 'math_tip' ),
2789 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2790 'id' => 'mw-editbutton-nowiki',
2791 'open' => "<nowiki>",
2792 'close' => "</nowiki>",
2793 'sample' => wfMsg( 'nowiki_sample' ),
2794 'tip' => wfMsg( 'nowiki_tip' ),
2798 'image' => $wgLang->getImageFile( 'button-sig' ),
2799 'id' => 'mw-editbutton-signature',
2803 'tip' => wfMsg( 'sig_tip' ),
2807 'image' => $wgLang->getImageFile( 'button-hr' ),
2808 'id' => 'mw-editbutton-hr',
2809 'open' => "\n----\n",
2812 'tip' => wfMsg( 'hr_tip' ),
2817 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
2818 foreach ( $toolarray as $tool ) {
2824 $image = $wgStylePath . '/common/images/' . $tool['image'],
2825 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2826 // Older browsers show a "speedtip" type message only for ALT.
2827 // Ideally these should be different, realistically they
2828 // probably don't need to be.
2829 $tip = $tool['tip'],
2830 $open = $tool['open'],
2831 $close = $tool['close'],
2832 $sample = $tool['sample'],
2833 $cssId = $tool['id'],
2836 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2839 // This used to be called on DOMReady from mediawiki.action.edit, which
2840 // ended up causing race conditions with the setup code above.
2842 "// Create button bar\n" .
2843 "$(function() { mw.toolbar.init(); } );\n";
2846 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2848 $toolbar = '<div id="toolbar"></div>';
2850 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2856 * Returns an array of html code of the following checkboxes:
2859 * @param $tabindex int Current tabindex
2860 * @param $checked Array of checkbox => bool, where bool indicates the checked
2861 * status of the checkbox
2865 public function getCheckboxes( &$tabindex, $checked ) {
2868 $checkboxes = array();
2870 // don't show the minor edit checkbox if it's a new page or section
2871 if ( !$this->isNew
) {
2872 $checkboxes['minor'] = '';
2873 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2874 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2876 'tabindex' => ++
$tabindex,
2877 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2878 'id' => 'wpMinoredit',
2880 $checkboxes['minor'] =
2881 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2882 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2883 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2884 ">{$minorLabel}</label>";
2888 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2889 $checkboxes['watch'] = '';
2890 if ( $wgUser->isLoggedIn() ) {
2892 'tabindex' => ++
$tabindex,
2893 'accesskey' => wfMsg( 'accesskey-watch' ),
2894 'id' => 'wpWatchthis',
2896 $checkboxes['watch'] =
2897 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2898 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2899 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2900 ">{$watchLabel}</label>";
2902 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2907 * Returns an array of html code of the following buttons:
2908 * save, diff, preview and live
2910 * @param $tabindex int Current tabindex
2914 public function getEditButtons( &$tabindex ) {
2921 'tabindex' => ++
$tabindex,
2922 'value' => wfMsg( 'savearticle' ),
2923 'accesskey' => wfMsg( 'accesskey-save' ),
2924 'title' => wfMsg( 'tooltip-save' ) . ' [' . wfMsg( 'accesskey-save' ) . ']',
2926 $buttons['save'] = Xml
::element( 'input', $temp, '' );
2928 ++
$tabindex; // use the same for preview and live preview
2930 'id' => 'wpPreview',
2931 'name' => 'wpPreview',
2933 'tabindex' => $tabindex,
2934 'value' => wfMsg( 'showpreview' ),
2935 'accesskey' => wfMsg( 'accesskey-preview' ),
2936 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2938 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
2939 $buttons['live'] = '';
2945 'tabindex' => ++
$tabindex,
2946 'value' => wfMsg( 'showdiff' ),
2947 'accesskey' => wfMsg( 'accesskey-diff' ),
2948 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2950 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
2952 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2957 * Output preview text only. This can be sucked into the edit page
2958 * via JavaScript, and saves the server time rendering the skin as
2959 * well as theoretically being more robust on the client (doesn't
2960 * disturb the edit box's undo history, won't eat your text on
2963 * @todo This doesn't include category or interlanguage links.
2964 * Would need to enhance it a bit, <s>maybe wrap them in XML
2965 * or something...</s> that might also require more skin
2966 * initialization, so check whether that's a problem.
2968 function livePreview() {
2971 header( 'Content-type: text/xml; charset=utf-8' );
2972 header( 'Cache-control: no-cache' );
2974 $previewText = $this->getPreviewText();
2975 #$categories = $skin->getCategoryLinks();
2978 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2979 Xml
::tags( 'livepreview', null,
2980 Xml
::element( 'preview', null, $previewText )
2981 #. Xml::element( 'category', null, $categories )
2987 * Call the stock "user is blocked" page
2989 * @deprecated in 1.19; throw an exception directly instead
2991 function blockedPage() {
2992 wfDeprecated( __METHOD__
, '1.19' );
2995 throw new UserBlockedError( $wgUser->getBlock() );
2999 * Produce the stock "please login to edit pages" page
3001 * @deprecated in 1.19; throw an exception directly instead
3003 function userNotLoggedInPage() {
3004 wfDeprecated( __METHOD__
, '1.19' );
3005 throw new PermissionsError( 'edit' );
3009 * Show an error page saying to the user that he has insufficient permissions
3010 * to create a new page
3012 * @deprecated in 1.19; throw an exception directly instead
3014 function noCreatePermission() {
3015 wfDeprecated( __METHOD__
, '1.19' );
3016 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3017 throw new PermissionsError( $permission );
3021 * Creates a basic error page which informs the user that
3022 * they have attempted to edit a nonexistent section.
3024 function noSuchSectionPage() {
3027 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3029 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
3030 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3031 $wgOut->addHTML( $res );
3033 $wgOut->returnToMain( false, $this->mTitle
);
3037 * Produce the stock "your edit contains spam" page
3039 * @param $match string Text which triggered one or more filters
3040 * @deprecated since 1.17 Use method spamPageWithContent() instead
3042 static function spamPage( $match = false ) {
3043 wfDeprecated( __METHOD__
, '1.17' );
3045 global $wgOut, $wgTitle;
3047 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3049 $wgOut->addHTML( '<div id="spamprotected">' );
3050 $wgOut->addWikiMsg( 'spamprotectiontext' );
3052 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3054 $wgOut->addHTML( '</div>' );
3056 $wgOut->returnToMain( false, $wgTitle );
3060 * Show "your edit contains spam" page with your diff and text
3062 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3064 public function spamPageWithContent( $match = false ) {
3065 global $wgOut, $wgLang;
3066 $this->textbox2
= $this->textbox1
;
3068 if( is_array( $match ) ){
3069 $match = $wgLang->listToText( $match );
3071 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3073 $wgOut->addHTML( '<div id="spamprotected">' );
3074 $wgOut->addWikiMsg( 'spamprotectiontext' );
3076 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3078 $wgOut->addHTML( '</div>' );
3080 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3083 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3084 $this->showTextbox2();
3086 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3090 * Format an anchor fragment as it would appear for a given section name
3091 * @param $text String
3095 function sectionAnchor( $text ) {
3097 return $wgParser->guessSectionNameFromWikiText( $text );
3101 * Check if the browser is on a blacklist of user-agents known to
3102 * mangle UTF-8 data on form submission. Returns true if Unicode
3103 * should make it through, false if it's known to be a problem.
3107 function checkUnicodeCompliantBrowser() {
3108 global $wgBrowserBlackList;
3109 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
3110 // No User-Agent header sent? Trust it by default...
3113 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
3114 foreach ( $wgBrowserBlackList as $browser ) {
3115 if ( preg_match( $browser, $currentbrowser ) ) {
3123 * Filter an input field through a Unicode de-armoring process if it
3124 * came from an old browser with known broken Unicode editing issues.
3126 * @param $request WebRequest
3127 * @param $field String
3131 function safeUnicodeInput( $request, $field ) {
3132 $text = rtrim( $request->getText( $field ) );
3133 return $request->getBool( 'safemode' )
3134 ?
$this->unmakesafe( $text )
3139 * @param $request WebRequest
3140 * @param $text string
3143 function safeUnicodeText( $request, $text ) {
3144 $text = rtrim( $text );
3145 return $request->getBool( 'safemode' )
3146 ?
$this->unmakesafe( $text )
3151 * Filter an output field through a Unicode armoring process if it is
3152 * going to an old browser with known broken Unicode editing issues.
3154 * @param $text String
3158 function safeUnicodeOutput( $text ) {
3160 $codedText = $wgContLang->recodeForEdit( $text );
3161 return $this->checkUnicodeCompliantBrowser()
3163 : $this->makesafe( $codedText );
3167 * A number of web browsers are known to corrupt non-ASCII characters
3168 * in a UTF-8 text editing environment. To protect against this,
3169 * detected browsers will be served an armored version of the text,
3170 * with non-ASCII chars converted to numeric HTML character references.
3172 * Preexisting such character references will have a 0 added to them
3173 * to ensure that round-trips do not alter the original data.
3175 * @param $invalue String
3179 function makesafe( $invalue ) {
3180 // Armor existing references for reversability.
3181 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3186 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3187 $bytevalue = ord( $invalue[$i] );
3188 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3189 $result .= chr( $bytevalue );
3191 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3192 $working = $working << 6;
3193 $working +
= ( $bytevalue & 0x3F );
3195 if ( $bytesleft <= 0 ) {
3196 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3198 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3199 $working = $bytevalue & 0x1F;
3201 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3202 $working = $bytevalue & 0x0F;
3204 } else { // 1111 0xxx
3205 $working = $bytevalue & 0x07;
3213 * Reverse the previously applied transliteration of non-ASCII characters
3214 * back to UTF-8. Used to protect data from corruption by broken web browsers
3215 * as listed in $wgBrowserBlackList.
3217 * @param $invalue String
3221 function unmakesafe( $invalue ) {
3223 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3224 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3228 $hexstring .= $invalue[$i];
3230 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3232 // Do some sanity checks. These aren't needed for reversability,
3233 // but should help keep the breakage down if the editor
3234 // breaks one of the entities whilst editing.
3235 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3236 $codepoint = hexdec( $hexstring );
3237 $result .= codepointToUtf8( $codepoint );
3239 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3242 $result .= substr( $invalue, $i, 1 );
3245 // reverse the transform that we made for reversability reasons.
3246 return strtr( $result, array( "�" => "&#x" ) );