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 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"error mw-undo-{$undoMsg}\">" .
841 wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
844 if ( $text === false ) {
845 $text = $this->getOriginalContent();
850 wfProfileOut( __METHOD__
);
855 * Get the content of the wanted revision, without section extraction.
857 * The result of this function can be used to compare user's input with
858 * section replaced in its context (using WikiPage::replaceSection())
859 * to the original text of the edit.
861 * This difers from Article::getContent() that when a missing revision is
862 * encountered the result will be an empty string and not the
863 * 'missing-article' message.
868 private function getOriginalContent() {
869 if ( $this->section
== 'new' ) {
870 return $this->getCurrentText();
872 $revision = $this->mArticle
->getRevisionFetched();
873 if ( $revision === null ) {
876 return $this->mArticle
->getContent();
880 * Get the actual text of the page. This is basically similar to
881 * WikiPage::getRawText() except that when the page doesn't exist an empty
882 * string is returned instead of false.
887 private function getCurrentText() {
888 $text = $this->mArticle
->getRawText();
889 if ( $text === false ) {
897 * Use this method before edit() to preload some text into the edit box
899 * @param $text string
901 public function setPreloadedText( $text ) {
902 $this->mPreloadText
= $text;
906 * Get the contents to be preloaded into the box, either set by
907 * an earlier setPreloadText() or by loading the given page.
909 * @param $preload String: representing the title to preload from.
912 protected function getPreloadedText( $preload ) {
913 global $wgUser, $wgParser;
915 if ( !empty( $this->mPreloadText
) ) {
916 return $this->mPreloadText
;
919 if ( $preload === '' ) {
923 $title = Title
::newFromText( $preload );
924 # Check for existence to avoid getting MediaWiki:Noarticletext
925 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
929 $page = WikiPage
::factory( $title );
930 if ( $page->isRedirect() ) {
931 $title = $page->getRedirectTarget();
933 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
936 $page = WikiPage
::factory( $title );
939 $parserOptions = ParserOptions
::newFromUser( $wgUser );
940 return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
944 * Make sure the form isn't faking a user's credentials.
946 * @param $request WebRequest
950 function tokenOk( &$request ) {
952 $token = $request->getVal( 'wpEditToken' );
953 $this->mTokenOk
= $wgUser->matchEditToken( $token );
954 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
955 return $this->mTokenOk
;
960 * @return bool false if output is done, true if the rest of the form should be displayed
962 function attemptSave() {
963 global $wgUser, $wgOut;
965 $resultDetails = false;
966 # Allow bots to exempt some edits from bot flagging
967 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
968 $status = $this->internalAttemptSave( $resultDetails, $bot );
969 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
971 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
972 $this->didSave
= true;
975 switch ( $status->value
) {
976 case self
::AS_HOOK_ERROR_EXPECTED
:
977 case self
::AS_CONTENT_TOO_BIG
:
978 case self
::AS_ARTICLE_WAS_DELETED
:
979 case self
::AS_CONFLICT_DETECTED
:
980 case self
::AS_SUMMARY_NEEDED
:
981 case self
::AS_TEXTBOX_EMPTY
:
982 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
986 case self
::AS_HOOK_ERROR
:
987 case self
::AS_FILTERING
:
990 case self
::AS_SUCCESS_NEW_ARTICLE
:
991 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
992 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
993 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
996 case self
::AS_SUCCESS_UPDATE
:
998 $sectionanchor = $resultDetails['sectionanchor'];
1000 // Give extensions a chance to modify URL query on update
1001 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1003 if ( $resultDetails['redirect'] ) {
1004 if ( $extraQuery == '' ) {
1005 $extraQuery = 'redirect=no';
1007 $extraQuery = 'redirect=no&' . $extraQuery;
1010 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1013 case self
::AS_BLANK_ARTICLE
:
1014 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1017 case self
::AS_SPAM_ERROR
:
1018 $this->spamPageWithContent( $resultDetails['spam'] );
1021 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1022 throw new UserBlockedError( $wgUser->mBlock
);
1024 case self
::AS_IMAGE_REDIRECT_ANON
:
1025 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1026 throw new PermissionsError( 'upload' );
1028 case self
::AS_READ_ONLY_PAGE_ANON
:
1029 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1030 throw new PermissionsError( 'edit' );
1032 case self
::AS_READ_ONLY_PAGE
:
1033 throw new ReadOnlyError
;
1035 case self
::AS_RATE_LIMITED
:
1036 throw new ThrottledError();
1038 case self
::AS_NO_CREATE_PERMISSION
:
1039 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1040 throw new PermissionsError( $permission );
1047 * Attempt submission (no UI)
1052 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1054 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1055 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1056 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1058 function internalAttemptSave( &$result, $bot = false ) {
1059 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
1060 global $wgMaxArticleSize;
1062 $status = Status
::newGood();
1064 wfProfileIn( __METHOD__
);
1065 wfProfileIn( __METHOD__
. '-checks' );
1067 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1068 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1069 $status->fatal( 'hookaborted' );
1070 $status->value
= self
::AS_HOOK_ERROR
;
1071 wfProfileOut( __METHOD__
. '-checks' );
1072 wfProfileOut( __METHOD__
);
1076 # Check image redirect
1077 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1078 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
1079 !$wgUser->isAllowed( 'upload' ) ) {
1080 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1081 $status->setResult( false, $code );
1083 wfProfileOut( __METHOD__
. '-checks' );
1084 wfProfileOut( __METHOD__
);
1090 $match = self
::matchSummarySpamRegex( $this->summary
);
1091 if ( $match === false ) {
1092 $match = self
::matchSpamRegex( $this->textbox1
);
1094 if ( $match !== false ) {
1095 $result['spam'] = $match;
1096 $ip = $wgRequest->getIP();
1097 $pdbk = $this->mTitle
->getPrefixedDBkey();
1098 $match = str_replace( "\n", '', $match );
1099 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1100 $status->fatal( 'spamprotectionmatch', $match );
1101 $status->value
= self
::AS_SPAM_ERROR
;
1102 wfProfileOut( __METHOD__
. '-checks' );
1103 wfProfileOut( __METHOD__
);
1106 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
1107 # Error messages or other handling should be performed by the filter function
1108 $status->setResult( false, self
::AS_FILTERING
);
1109 wfProfileOut( __METHOD__
. '-checks' );
1110 wfProfileOut( __METHOD__
);
1113 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1114 # Error messages etc. could be handled within the hook...
1115 $status->fatal( 'hookaborted' );
1116 $status->value
= self
::AS_HOOK_ERROR
;
1117 wfProfileOut( __METHOD__
. '-checks' );
1118 wfProfileOut( __METHOD__
);
1120 } elseif ( $this->hookError
!= '' ) {
1121 # ...or the hook could be expecting us to produce an error
1122 $status->fatal( 'hookaborted' );
1123 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1124 wfProfileOut( __METHOD__
. '-checks' );
1125 wfProfileOut( __METHOD__
);
1129 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1130 // Auto-block user's IP if the account was "hard" blocked
1131 $wgUser->spreadAnyEditBlock();
1132 # Check block state against master, thus 'false'.
1133 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1134 wfProfileOut( __METHOD__
. '-checks' );
1135 wfProfileOut( __METHOD__
);
1139 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1140 if ( $this->kblength
> $wgMaxArticleSize ) {
1141 // Error will be displayed by showEditForm()
1142 $this->tooBig
= true;
1143 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1144 wfProfileOut( __METHOD__
. '-checks' );
1145 wfProfileOut( __METHOD__
);
1149 if ( !$wgUser->isAllowed( 'edit' ) ) {
1150 if ( $wgUser->isAnon() ) {
1151 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1152 wfProfileOut( __METHOD__
. '-checks' );
1153 wfProfileOut( __METHOD__
);
1156 $status->fatal( 'readonlytext' );
1157 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1158 wfProfileOut( __METHOD__
. '-checks' );
1159 wfProfileOut( __METHOD__
);
1164 if ( wfReadOnly() ) {
1165 $status->fatal( 'readonlytext' );
1166 $status->value
= self
::AS_READ_ONLY_PAGE
;
1167 wfProfileOut( __METHOD__
. '-checks' );
1168 wfProfileOut( __METHOD__
);
1171 if ( $wgUser->pingLimiter() ) {
1172 $status->fatal( 'actionthrottledtext' );
1173 $status->value
= self
::AS_RATE_LIMITED
;
1174 wfProfileOut( __METHOD__
. '-checks' );
1175 wfProfileOut( __METHOD__
);
1179 # If the article has been deleted while editing, don't save it without
1181 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1182 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1183 wfProfileOut( __METHOD__
. '-checks' );
1184 wfProfileOut( __METHOD__
);
1188 wfProfileOut( __METHOD__
. '-checks' );
1190 # If article is new, insert it.
1191 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1192 $new = ( $aid == 0 );
1195 // Late check for create permission, just in case *PARANOIA*
1196 if ( !$this->mTitle
->userCan( 'create' ) ) {
1197 $status->fatal( 'nocreatetext' );
1198 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1199 wfDebug( __METHOD__
. ": no create permission\n" );
1200 wfProfileOut( __METHOD__
);
1204 # Don't save a new article if it's blank.
1205 if ( $this->textbox1
== '' ) {
1206 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1207 wfProfileOut( __METHOD__
);
1211 // Run post-section-merge edit filter
1212 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1213 # Error messages etc. could be handled within the hook...
1214 $status->fatal( 'hookaborted' );
1215 $status->value
= self
::AS_HOOK_ERROR
;
1216 wfProfileOut( __METHOD__
);
1218 } elseif ( $this->hookError
!= '' ) {
1219 # ...or the hook could be expecting us to produce an error
1220 $status->fatal( 'hookaborted' );
1221 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1222 wfProfileOut( __METHOD__
);
1226 # Handle the user preference to force summaries here. Check if it's not a redirect.
1227 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
1228 if ( md5( $this->summary
) == $this->autoSumm
) {
1229 $this->missingSummary
= true;
1230 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1231 $status->value
= self
::AS_SUMMARY_NEEDED
;
1232 wfProfileOut( __METHOD__
);
1237 $text = $this->textbox1
;
1238 $result['sectionanchor'] = '';
1239 if ( $this->section
== 'new' ) {
1240 if ( $this->sectiontitle
!== '' ) {
1241 // Insert the section title above the content.
1242 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle
) . "\n\n" . $text;
1244 // Jump to the new section
1245 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1247 // If no edit summary was specified, create one automatically from the section
1248 // title and have it link to the new section. Otherwise, respect the summary as
1250 if ( $this->summary
=== '' ) {
1251 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1252 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1254 } elseif ( $this->summary
!== '' ) {
1255 // Insert the section title above the content.
1256 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $text;
1258 // Jump to the new section
1259 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1261 // Create a link to the new section from the edit summary.
1262 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1263 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1267 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1271 # Article exists. Check for edit conflict.
1273 $this->mArticle
->clear(); # Force reload of dates, etc.
1274 $timestamp = $this->mArticle
->getTimestamp();
1276 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1278 if ( $timestamp != $this->edittime
) {
1279 $this->isConflict
= true;
1280 if ( $this->section
== 'new' ) {
1281 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1282 $this->mArticle
->getComment() == $this->summary
) {
1283 // Probably a duplicate submission of a new comment.
1284 // This can happen when squid resends a request after
1285 // a timeout but the first one actually went through.
1286 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1288 // New comment; suppress conflict.
1289 $this->isConflict
= false;
1290 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1292 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1293 # Suppress edit conflict with self, except for section edits where merging is required.
1294 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1295 $this->isConflict
= false;
1299 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1300 // backwards compatibility with old forms/bots).
1301 if ( $this->sectiontitle
!== '' ) {
1302 $sectionTitle = $this->sectiontitle
;
1304 $sectionTitle = $this->summary
;
1307 if ( $this->isConflict
) {
1308 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1309 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle, $this->edittime
);
1311 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1312 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle );
1314 if ( is_null( $text ) ) {
1315 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1316 $this->isConflict
= true;
1317 $text = $this->textbox1
; // do not try to merge here!
1318 } elseif ( $this->isConflict
) {
1320 if ( $this->mergeChangesInto( $text ) ) {
1321 // Successful merge! Maybe we should tell the user the good news?
1322 $this->isConflict
= false;
1323 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1325 $this->section
= '';
1326 $this->textbox1
= $text;
1327 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1331 if ( $this->isConflict
) {
1332 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1333 wfProfileOut( __METHOD__
);
1337 // Run post-section-merge edit filter
1338 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
1339 # Error messages etc. could be handled within the hook...
1340 $status->fatal( 'hookaborted' );
1341 $status->value
= self
::AS_HOOK_ERROR
;
1342 wfProfileOut( __METHOD__
);
1344 } elseif ( $this->hookError
!= '' ) {
1345 # ...or the hook could be expecting us to produce an error
1346 $status->fatal( 'hookaborted' );
1347 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1348 wfProfileOut( __METHOD__
);
1352 # Handle the user preference to force summaries here, but not for null edits
1353 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1354 && $this->getOriginalContent() != $text
1355 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1357 if ( md5( $this->summary
) == $this->autoSumm
) {
1358 $this->missingSummary
= true;
1359 $status->fatal( 'missingsummary' );
1360 $status->value
= self
::AS_SUMMARY_NEEDED
;
1361 wfProfileOut( __METHOD__
);
1366 # And a similar thing for new sections
1367 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1368 if ( trim( $this->summary
) == '' ) {
1369 $this->missingSummary
= true;
1370 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1371 $status->value
= self
::AS_SUMMARY_NEEDED
;
1372 wfProfileOut( __METHOD__
);
1378 wfProfileIn( __METHOD__
. '-sectionanchor' );
1379 $sectionanchor = '';
1380 if ( $this->section
== 'new' ) {
1381 if ( $this->textbox1
== '' ) {
1382 $this->missingComment
= true;
1383 $status->fatal( 'missingcommenttext' );
1384 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1385 wfProfileOut( __METHOD__
. '-sectionanchor' );
1386 wfProfileOut( __METHOD__
);
1389 if ( $this->sectiontitle
!== '' ) {
1390 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1391 // If no edit summary was specified, create one automatically from the section
1392 // title and have it link to the new section. Otherwise, respect the summary as
1394 if ( $this->summary
=== '' ) {
1395 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1396 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1398 } elseif ( $this->summary
!== '' ) {
1399 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1400 # This is a new section, so create a link to the new section
1401 # in the revision summary.
1402 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1403 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1405 } elseif ( $this->section
!= '' ) {
1406 # Try to get a section anchor from the section source, redirect to edited section if header found
1407 # XXX: might be better to integrate this into Article::replaceSection
1408 # for duplicate heading checking and maybe parsing
1409 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1410 # we can't deal with anchors, includes, html etc in the header for now,
1411 # headline would need to be parsed to improve this
1412 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1413 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1416 $result['sectionanchor'] = $sectionanchor;
1417 wfProfileOut( __METHOD__
. '-sectionanchor' );
1419 // Save errors may fall down to the edit form, but we've now
1420 // merged the section into full text. Clear the section field
1421 // so that later submission of conflict forms won't try to
1422 // replace that into a duplicated mess.
1423 $this->textbox1
= $text;
1424 $this->section
= '';
1426 $status->value
= self
::AS_SUCCESS_UPDATE
;
1429 // Check for length errors again now that the section is merged in
1430 $this->kblength
= (int)( strlen( $text ) / 1024 );
1431 if ( $this->kblength
> $wgMaxArticleSize ) {
1432 $this->tooBig
= true;
1433 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1434 wfProfileOut( __METHOD__
);
1438 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1439 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1440 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1441 ( $bot ? EDIT_FORCE_BOT
: 0 );
1443 $doEditStatus = $this->mArticle
->doEdit( $text, $this->summary
, $flags );
1445 if ( $doEditStatus->isOK() ) {
1446 $result['redirect'] = Title
::newFromRedirect( $text ) !== null;
1447 $this->commitWatch();
1448 wfProfileOut( __METHOD__
);
1451 $this->isConflict
= true;
1452 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1453 wfProfileOut( __METHOD__
);
1454 return $doEditStatus;
1459 * Commit the change of watch status
1461 protected function commitWatch() {
1463 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1464 $dbw = wfGetDB( DB_MASTER
);
1466 if ( $this->watchthis
) {
1467 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1469 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1476 * Check if no edits were made by other users since
1477 * the time a user started editing the page. Limit to
1478 * 50 revisions for the sake of performance.
1481 * @param $edittime string
1485 protected function userWasLastToEdit( $id, $edittime ) {
1486 if( !$id ) return false;
1487 $dbw = wfGetDB( DB_MASTER
);
1488 $res = $dbw->select( 'revision',
1491 'rev_page' => $this->mTitle
->getArticleId(),
1492 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1495 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1496 foreach ( $res as $row ) {
1497 if( $row->rev_user
!= $id ) {
1508 * @parma $editText string
1512 function mergeChangesInto( &$editText ){
1513 wfProfileIn( __METHOD__
);
1515 $db = wfGetDB( DB_MASTER
);
1517 // This is the revision the editor started from
1518 $baseRevision = $this->getBaseRevision();
1519 if ( is_null( $baseRevision ) ) {
1520 wfProfileOut( __METHOD__
);
1523 $baseText = $baseRevision->getText();
1525 // The current state, we want to merge updates into it
1526 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1527 if ( is_null( $currentRevision ) ) {
1528 wfProfileOut( __METHOD__
);
1531 $currentText = $currentRevision->getText();
1534 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1535 $editText = $result;
1536 wfProfileOut( __METHOD__
);
1539 wfProfileOut( __METHOD__
);
1547 function getBaseRevision() {
1548 if ( !$this->mBaseRevision
) {
1549 $db = wfGetDB( DB_MASTER
);
1550 $baseRevision = Revision
::loadFromTimestamp(
1551 $db, $this->mTitle
, $this->edittime
);
1552 return $this->mBaseRevision
= $baseRevision;
1554 return $this->mBaseRevision
;
1559 * Check given input text against $wgSpamRegex, and return the text of the first match.
1561 * @param $text string
1563 * @return string|bool matching string or false
1565 public static function matchSpamRegex( $text ) {
1566 global $wgSpamRegex;
1567 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1568 $regexes = (array)$wgSpamRegex;
1569 return self
::matchSpamRegexInternal( $text, $regexes );
1573 * Check given input text against $wgSpamRegex, and return the text of the first match.
1575 * @parma $text string
1577 * @return string|bool matching string or false
1579 public static function matchSummarySpamRegex( $text ) {
1580 global $wgSummarySpamRegex;
1581 $regexes = (array)$wgSummarySpamRegex;
1582 return self
::matchSpamRegexInternal( $text, $regexes );
1586 * @param $text string
1587 * @param $regexes array
1588 * @return bool|string
1590 protected static function matchSpamRegexInternal( $text, $regexes ) {
1591 foreach( $regexes as $regex ) {
1593 if( preg_match( $regex, $text, $matches ) ) {
1600 function setHeaders() {
1601 global $wgOut, $wgUser;
1603 $wgOut->addModules( 'mediawiki.action.edit' );
1605 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1606 $wgOut->addModules( 'mediawiki.legacy.preview' );
1608 // Bug #19334: textarea jumps when editing articles in IE8
1609 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1611 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1613 # Enabled article-related sidebar, toplinks, etc.
1614 $wgOut->setArticleRelated( true );
1616 if ( $this->isConflict
) {
1617 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1618 } elseif ( $this->section
!= '' ) {
1619 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1620 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1622 # Use the title defined by DISPLAYTITLE magic word when present
1623 if ( isset( $this->mParserOutput
)
1624 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1627 $title = $this->getContextTitle()->getPrefixedText();
1629 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1634 * Show all applicable editing introductions
1636 protected function showIntro() {
1637 global $wgOut, $wgUser;
1638 if ( $this->suppressIntro
) {
1642 $namespace = $this->mTitle
->getNamespace();
1644 if ( $namespace == NS_MEDIAWIKI
) {
1645 # Show a warning if editing an interface message
1646 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1649 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1650 # Show log extract when the user is currently blocked
1651 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1652 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1653 $username = $parts[0];
1654 $user = User
::newFromName( $username, false /* allow IP users*/ );
1655 $ip = User
::isIP( $username );
1656 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1657 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1658 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1659 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1660 LogEventsList
::showLogExtract(
1663 $user->getUserPage(),
1667 'showIfEmpty' => false,
1669 'blocked-notice-logextract',
1670 $user->getName() # Support GENDER in notice
1676 # Try to add a custom edit intro, or use the standard one if this is not possible.
1677 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1678 if ( $wgUser->isLoggedIn() ) {
1679 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1681 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1684 # Give a notice if the user is editing a deleted/moved page...
1685 if ( !$this->mTitle
->exists() ) {
1686 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1687 '', array( 'lim' => 10,
1688 'conds' => array( "log_action != 'revision'" ),
1689 'showIfEmpty' => false,
1690 'msgKey' => array( 'recreate-moveddeleted-warn') )
1696 * Attempt to show a custom editing introduction, if supplied
1700 protected function showCustomIntro() {
1701 if ( $this->editintro
) {
1702 $title = Title
::newFromText( $this->editintro
);
1703 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1705 // Added using template syntax, to take <noinclude>'s into account.
1706 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1717 * Send the edit form and related headers to $wgOut
1718 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1719 * during form output near the top, for captchas and the like.
1721 function showEditForm( $formCallback = null ) {
1722 global $wgOut, $wgUser;
1724 wfProfileIn( __METHOD__
);
1726 #need to parse the preview early so that we know which templates are used,
1727 #otherwise users with "show preview after edit box" will get a blank list
1728 #we parse this near the beginning so that setHeaders can do the title
1729 #setting work instead of leaving it in getPreviewText
1730 $previewOutput = '';
1731 if ( $this->formtype
== 'preview' ) {
1732 $previewOutput = $this->getPreviewText();
1735 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1737 $this->setHeaders();
1739 if ( $this->showHeader() === false ) {
1740 wfProfileOut( __METHOD__
);
1744 $wgOut->addHTML( $this->editFormPageTop
);
1746 if ( $wgUser->getOption( 'previewontop' ) ) {
1747 $this->displayPreviewArea( $previewOutput, true );
1750 $wgOut->addHTML( $this->editFormTextTop
);
1752 $showToolbar = true;
1753 if ( $this->wasDeletedSinceLastEdit() ) {
1754 if ( $this->formtype
== 'save' ) {
1755 // Hide the toolbar and edit area, user can click preview to get it back
1756 // Add an confirmation checkbox and explanation.
1757 $showToolbar = false;
1759 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1760 'deletedwhileediting' );
1764 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
1765 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1766 'enctype' => 'multipart/form-data' ) ) );
1768 if ( is_callable( $formCallback ) ) {
1769 call_user_func_array( $formCallback, array( &$wgOut ) );
1772 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1774 // Put these up at the top to ensure they aren't lost on early form submission
1775 $this->showFormBeforeText();
1777 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1778 $username = $this->lastDelete
->user_name
;
1779 $comment = $this->lastDelete
->log_comment
;
1781 // It is better to not parse the comment at all than to have templates expanded in the middle
1782 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1783 $key = $comment === ''
1784 ?
'confirmrecreate-noreason'
1785 : 'confirmrecreate';
1787 '<div class="mw-confirm-recreate">' .
1788 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1789 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1790 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1796 # If a blank edit summary was previously provided, and the appropriate
1797 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1798 # user being bounced back more than once in the event that a summary
1801 # For a bit more sophisticated detection of blank summaries, hash the
1802 # automatic one and pass that in the hidden field wpAutoSummary.
1803 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
1804 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1807 if ( $this->hasPresetSummary
) {
1808 // If a summary has been preset using &summary= we dont want to prompt for
1809 // a different summary. Only prompt for a summary if the summary is blanked.
1811 $this->autoSumm
= 'd41d8cd98f00b204e9800998ecf8427e'; # == md5('')
1814 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1815 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1817 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
1819 if ( $this->section
== 'new' ) {
1820 $this->showSummaryInput( true, $this->summary
);
1821 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1824 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1826 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1827 $wgOut->addHTML( EditPage
::getEditToolbar() );
1830 if ( $this->isConflict
) {
1831 // In an edit conflict bypass the overrideable content form method
1832 // and fallback to the raw wpTextbox1 since editconflicts can't be
1833 // resolved between page source edits and custom ui edits using the
1835 $this->textbox2
= $this->textbox1
;
1836 $this->textbox1
= $this->getCurrentText();
1838 $this->showTextbox1();
1840 $this->showContentForm();
1843 $wgOut->addHTML( $this->editFormTextAfterContent
);
1845 $wgOut->addWikiText( $this->getCopywarn() );
1847 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1849 $this->showStandardInputs();
1851 $this->showFormAfterText();
1853 $this->showTosSummary();
1855 $this->showEditTools();
1857 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
1859 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
1860 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
1862 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
1863 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
1865 if ( $this->isConflict
) {
1866 $this->showConflict();
1869 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
1871 if ( !$wgUser->getOption( 'previewontop' ) ) {
1872 $this->displayPreviewArea( $previewOutput, false );
1875 wfProfileOut( __METHOD__
);
1879 * Extract the section title from current section text, if any.
1881 * @param string $text
1882 * @return Mixed|string or false
1884 public static function extractSectionTitle( $text ) {
1885 preg_match( "/^(=+)(.+)\\1(\n|$)/i", $text, $matches );
1886 if ( !empty( $matches[2] ) ) {
1888 return $wgParser->stripSectionName(trim($matches[2]));
1894 protected function showHeader() {
1895 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1897 if ( $this->mTitle
->isTalkPage() ) {
1898 $wgOut->addWikiMsg( 'talkpagetext' );
1901 # Optional notices on a per-namespace and per-page basis
1902 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
1903 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
1904 if ( $editnotice_ns_message->exists() ) {
1905 $wgOut->addWikiText( $editnotice_ns_message->plain() );
1907 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
1908 $parts = explode( '/', $this->mTitle
->getDBkey() );
1909 $editnotice_base = $editnotice_ns;
1910 while ( count( $parts ) > 0 ) {
1911 $editnotice_base .= '-'.array_shift( $parts );
1912 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
1913 if ( $editnotice_base_msg->exists() ) {
1914 $wgOut->addWikiText( $editnotice_base_msg->plain() );
1918 # Even if there are no subpages in namespace, we still don't want / in MW ns.
1919 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
1920 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
1921 if ( $editnoticeMsg->exists() ) {
1922 $wgOut->addWikiText( $editnoticeMsg->plain() );
1926 if ( $this->isConflict
) {
1927 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1928 $this->edittime
= $this->mArticle
->getTimestamp();
1930 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
1931 // We use $this->section to much before this and getVal('wgSection') directly in other places
1932 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1933 // Someone is welcome to try refactoring though
1934 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1938 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1939 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1940 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
1941 if ( $sectionTitle !== false ) {
1942 $this->summary
= "/* $sectionTitle */ ";
1947 if ( $this->missingComment
) {
1948 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1951 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1952 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1955 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1956 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1959 if ( $this->hookError
!== '' ) {
1960 $wgOut->addWikiText( $this->hookError
);
1963 if ( !$this->checkUnicodeCompliantBrowser() ) {
1964 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1967 if ( $this->section
!= 'new' ) {
1968 $revision = $this->mArticle
->getRevisionFetched();
1970 // Let sysop know that this will make private content public if saved
1972 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
1973 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1974 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
1975 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1978 if ( !$revision->isCurrent() ) {
1979 $this->mArticle
->setOldSubtitle( $revision->getId() );
1980 $wgOut->addWikiMsg( 'editingold' );
1982 } elseif ( $this->mTitle
->exists() ) {
1983 // Something went wrong
1985 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
1986 array( 'missing-article', $this->mTitle
->getPrefixedText(),
1987 wfMsgNoTrans( 'missingarticle-rev', $this->oldid
) ) );
1992 if ( wfReadOnly() ) {
1993 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1994 } elseif ( $wgUser->isAnon() ) {
1995 if ( $this->formtype
!= 'preview' ) {
1996 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1998 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2001 if ( $this->isCssJsSubpage
) {
2002 # Check the skin exists
2003 if ( $this->isWrongCaseCssJsPage
) {
2004 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2006 if ( $this->formtype
!== 'preview' ) {
2007 if ( $this->isCssSubpage
)
2008 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2009 if ( $this->isJsSubpage
)
2010 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2015 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2016 # Is the title semi-protected?
2017 if ( $this->mTitle
->isSemiProtected() ) {
2018 $noticeMsg = 'semiprotectedpagewarning';
2020 # Then it must be protected based on static groups (regular)
2021 $noticeMsg = 'protectedpagewarning';
2023 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2024 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2026 if ( $this->mTitle
->isCascadeProtected() ) {
2027 # Is this page under cascading protection from some source pages?
2028 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
2029 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2030 $cascadeSourcesCount = count( $cascadeSources );
2031 if ( $cascadeSourcesCount > 0 ) {
2032 # Explain, and list the titles responsible
2033 foreach( $cascadeSources as $page ) {
2034 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2037 $notice .= '</div>';
2038 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2040 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2041 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2043 'showIfEmpty' => false,
2044 'msgKey' => array( 'titleprotectedwarning' ),
2045 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2048 if ( $this->kblength
=== false ) {
2049 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2052 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2053 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2054 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2056 if( !wfMessage('longpage-hint')->isDisabled() ) {
2057 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2058 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2065 * Standard summary input and label (wgSummary), abstracted so EditPage
2066 * subclasses may reorganize the form.
2067 * Note that you do not need to worry about the label's for=, it will be
2068 * inferred by the id given to the input. You can remove them both by
2069 * passing array( 'id' => false ) to $userInputAttrs.
2071 * @param $summary string The value of the summary input
2072 * @param $labelText string The html to place inside the label
2073 * @param $inputAttrs array of attrs to use on the input
2074 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2076 * @return array An array in the format array( $label, $input )
2078 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
2079 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
2080 $inputAttrs = ( is_array($inputAttrs) ?
$inputAttrs : array() ) +
array(
2081 'id' => 'wpSummary',
2082 'maxlength' => '200',
2085 'spellcheck' => 'true',
2086 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2088 $spanLabelAttrs = ( is_array($spanLabelAttrs) ?
$spanLabelAttrs : array() ) +
array(
2089 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2090 'id' => "wpSummaryLabel"
2095 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2096 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2099 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2101 return array( $label, $input );
2105 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2106 * up top, or false if this is the comment summary
2107 * down below the textarea
2108 * @param $summary String: The text of the summary to display
2111 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2112 global $wgOut, $wgContLang;
2113 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2114 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2115 if ( $isSubjectPreview ) {
2116 if ( $this->nosummary
) {
2120 if ( !$this->mShowSummaryField
) {
2124 $summary = $wgContLang->recodeForEdit( $summary );
2125 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
2126 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
2127 $wgOut->addHTML("{$label} {$input}");
2131 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2132 * up top, or false if this is the comment summary
2133 * down below the textarea
2134 * @param $summary String: the text of the summary to display
2137 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2138 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2143 if ( $isSubjectPreview )
2144 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2146 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2148 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2149 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2152 protected function showFormBeforeText() {
2154 $section = htmlspecialchars( $this->section
);
2155 $wgOut->addHTML( <<<HTML
2156 <input type='hidden' value="{$section}" name="wpSection" />
2157 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2158 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2159 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2163 if ( !$this->checkUnicodeCompliantBrowser() )
2164 $wgOut->addHTML(Html
::hidden( 'safemode', '1' ));
2167 protected function showFormAfterText() {
2168 global $wgOut, $wgUser;
2170 * To make it harder for someone to slip a user a page
2171 * which submits an edit form to the wiki without their
2172 * knowledge, a random token is associated with the login
2173 * session. If it's not passed back with the submission,
2174 * we won't save the page, or render user JavaScript and
2177 * For anon editors, who may not have a session, we just
2178 * include the constant suffix to prevent editing from
2179 * broken text-mangling proxies.
2181 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2185 * Subpage overridable method for printing the form for page content editing
2186 * By default this simply outputs wpTextbox1
2187 * Subclasses can override this to provide a custom UI for editing;
2188 * be it a form, or simply wpTextbox1 with a modified content that will be
2189 * reverse modified when extracted from the post data.
2190 * Note that this is basically the inverse for importContentFormData
2192 protected function showContentForm() {
2193 $this->showTextbox1();
2197 * Method to output wpTextbox1
2198 * The $textoverride method can be used by subclasses overriding showContentForm
2199 * to pass back to this method.
2201 * @param $customAttribs array of html attributes to use in the textarea
2202 * @param $textoverride String: optional text to override $this->textarea1 with
2204 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2205 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2206 $attribs = array( 'style' => 'display:none;' );
2208 $classes = array(); // Textarea CSS
2209 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2210 # Is the title semi-protected?
2211 if ( $this->mTitle
->isSemiProtected() ) {
2212 $classes[] = 'mw-textarea-sprotected';
2214 # Then it must be protected based on static groups (regular)
2215 $classes[] = 'mw-textarea-protected';
2217 # Is the title cascade-protected?
2218 if ( $this->mTitle
->isCascadeProtected() ) {
2219 $classes[] = 'mw-textarea-cprotected';
2223 $attribs = array( 'tabindex' => 1 );
2225 if ( is_array( $customAttribs ) ) {
2226 $attribs +
= $customAttribs;
2229 if ( count( $classes ) ) {
2230 if ( isset( $attribs['class'] ) ) {
2231 $classes[] = $attribs['class'];
2233 $attribs['class'] = implode( ' ', $classes );
2237 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2240 protected function showTextbox2() {
2241 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2244 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2245 global $wgOut, $wgUser;
2247 $wikitext = $this->safeUnicodeOutput( $content );
2248 if ( strval($wikitext) !== '' ) {
2249 // Ensure there's a newline at the end, otherwise adding lines
2251 // But don't add a newline if the ext is empty, or Firefox in XHTML
2252 // mode will show an extra newline. A bit annoying.
2256 $attribs = $customAttribs +
array(
2259 'cols' => $wgUser->getIntOption( 'cols' ),
2260 'rows' => $wgUser->getIntOption( 'rows' ),
2261 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2264 $pageLang = $this->mTitle
->getPageLanguage();
2265 $attribs['lang'] = $pageLang->getCode();
2266 $attribs['dir'] = $pageLang->getDir();
2268 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2271 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2275 $classes[] = 'ontop';
2277 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2279 if ( $this->formtype
!= 'preview' )
2280 $attribs['style'] = 'display: none;';
2282 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2284 if ( $this->formtype
== 'preview' ) {
2285 $this->showPreview( $previewOutput );
2288 $wgOut->addHTML( '</div>' );
2290 if ( $this->formtype
== 'diff') {
2296 * Append preview output to $wgOut.
2297 * Includes category rendering if this is a category page.
2299 * @param $text String: the HTML to be output for the preview.
2301 protected function showPreview( $text ) {
2303 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2304 $this->mArticle
->openShowCategory();
2306 # This hook seems slightly odd here, but makes things more
2307 # consistent for extensions.
2308 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
2309 $wgOut->addHTML( $text );
2310 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2311 $this->mArticle
->closeShowCategory();
2316 * Get a diff between the current contents of the edit box and the
2317 * version of the page we're editing from.
2319 * If this is a section edit, we'll replace the section as for final
2320 * save and then make a comparison.
2322 function showDiff() {
2323 global $wgUser, $wgContLang, $wgParser, $wgOut;
2325 $oldtext = $this->getOriginalContent();
2326 $newtext = $this->mArticle
->replaceSection(
2327 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2329 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2331 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2332 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle
, $wgUser, $popts );
2334 if ( $oldtext !== false ||
$newtext != '' ) {
2335 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2336 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2338 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2339 $de->setText( $oldtext, $newtext );
2340 $difftext = $de->getDiff( $oldtitle, $newtitle );
2341 $de->showDiffStyle();
2346 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2350 * Give a chance for site and per-namespace customizations of
2351 * terms of service summary link that might exist separately
2352 * from the copyright notice.
2354 * This will display between the save button and the edit tools,
2355 * so should remain short!
2357 protected function showTosSummary() {
2358 $msg = 'editpage-tos-summary';
2359 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2360 if( !wfMessage( $msg )->isDisabled() ) {
2362 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2363 $wgOut->addWikiMsg( $msg );
2364 $wgOut->addHTML( '</div>' );
2368 protected function showEditTools() {
2370 $wgOut->addHTML( '<div class="mw-editTools">' .
2371 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2375 protected function getCopywarn() {
2376 global $wgRightsText;
2377 if ( $wgRightsText ) {
2378 $copywarnMsg = array( 'copyrightwarning',
2379 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2382 $copywarnMsg = array( 'copyrightwarning2',
2383 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2385 // Allow for site and per-namespace customization of contribution/copyright notice.
2386 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2388 return "<div id=\"editpage-copywarn\">\n" .
2389 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
2392 protected function showStandardInputs( &$tabindex = 2 ) {
2394 $wgOut->addHTML( "<div class='editOptions'>\n" );
2396 if ( $this->section
!= 'new' ) {
2397 $this->showSummaryInput( false, $this->summary
);
2398 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2401 $checkboxes = $this->getCheckboxes( $tabindex,
2402 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2403 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2404 $wgOut->addHTML( "<div class='editButtons'>\n" );
2405 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2407 $cancel = $this->getCancelLink();
2408 if ( $cancel !== '' ) {
2409 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2411 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2412 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
2413 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
2414 htmlspecialchars( wfMsg( 'newwindow' ) );
2415 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2416 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2420 * Show an edit conflict. textbox1 is already shown in showEditForm().
2421 * If you want to use another entry point to this function, be careful.
2423 protected function showConflict() {
2426 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2427 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2429 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2430 $de->setText( $this->textbox2
, $this->textbox1
);
2431 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2433 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2434 $this->showTextbox2();
2441 public function getCancelLink() {
2442 $cancelParams = array();
2443 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2444 $cancelParams['oldid'] = $this->oldid
;
2447 return Linker
::linkKnown(
2448 $this->getContextTitle(),
2449 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2450 array( 'id' => 'mw-editform-cancel' ),
2456 * Returns the URL to use in the form's action attribute.
2457 * This is used by EditPage subclasses when simply customizing the action
2458 * variable in the constructor is not enough. This can be used when the
2459 * EditPage lives inside of a Special page rather than a custom page action.
2461 * @param $title Title object for which is being edited (where we go to for &action= links)
2464 protected function getActionURL( Title
$title ) {
2465 return $title->getLocalURL( array( 'action' => $this->action
) );
2469 * Check if a page was deleted while the user was editing it, before submit.
2470 * Note that we rely on the logging table, which hasn't been always there,
2471 * but that doesn't matter, because this only applies to brand new
2474 protected function wasDeletedSinceLastEdit() {
2475 if ( $this->deletedSinceEdit
!== null ) {
2476 return $this->deletedSinceEdit
;
2479 $this->deletedSinceEdit
= false;
2481 if ( $this->mTitle
->isDeletedQuick() ) {
2482 $this->lastDelete
= $this->getLastDelete();
2483 if ( $this->lastDelete
) {
2484 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2485 if ( $deleteTime > $this->starttime
) {
2486 $this->deletedSinceEdit
= true;
2491 return $this->deletedSinceEdit
;
2494 protected function getLastDelete() {
2495 $dbr = wfGetDB( DB_SLAVE
);
2496 $data = $dbr->selectRow(
2497 array( 'logging', 'user' ),
2508 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2509 'log_title' => $this->mTitle
->getDBkey(),
2510 'log_type' => 'delete',
2511 'log_action' => 'delete',
2512 'user_id=log_user' ),
2514 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2516 // Quick paranoid permission checks...
2517 if( is_object( $data ) ) {
2518 if( $data->log_deleted
& LogPage
::DELETED_USER
)
2519 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2520 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2521 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2527 * Get the rendered text for previewing.
2530 function getPreviewText() {
2531 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2533 wfProfileIn( __METHOD__
);
2535 if ( $wgRawHtml && !$this->mTokenOk
) {
2536 // Could be an offsite preview attempt. This is very unsafe if
2537 // HTML is enabled, as it could be an attack.
2539 if ( $this->textbox1
!== '' ) {
2540 // Do not put big scary notice, if previewing the empty
2541 // string, which happens when you initially edit
2542 // a category page, due to automatic preview-on-open.
2543 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2544 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2546 wfProfileOut( __METHOD__
);
2550 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2551 if ( $this->mTokenOkExceptSuffix
) {
2552 $note = wfMsg( 'token_suffix_mismatch' );
2554 $note = wfMsg( 'session_fail_preview' );
2556 } elseif ( $this->incompleteForm
) {
2557 $note = wfMsg( 'edit_form_incomplete' );
2559 $note = wfMsg( 'previewnote' );
2562 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2563 $parserOptions->setEditSection( false );
2564 $parserOptions->setTidy( true );
2565 $parserOptions->setIsPreview( true );
2566 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2568 # don't parse non-wikitext pages, show message about preview
2569 # 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?
2571 if ( $this->isCssJsSubpage ||
!$this->mTitle
->isWikitextPage() ) {
2572 if( $this->mTitle
->isCssJsSubpage() ) {
2574 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2580 # Used messages to make sure grep find them:
2581 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2583 if (preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2584 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2585 $class = "mw-code mw-css";
2586 } elseif (preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2587 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2588 $class = "mw-code mw-js";
2590 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2594 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2595 $previewHTML = $parserOutput->mText
;
2596 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2598 $toparse = $this->textbox1
;
2600 # If we're adding a comment, we need to show the
2601 # summary as the headline
2602 if ( $this->section
== "new" && $this->summary
!= "" ) {
2603 $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $toparse;
2606 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2608 $parserOptions->enableLimitReport();
2610 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle
, $wgUser, $parserOptions );
2611 $parserOutput = $wgParser->parse( $toparse, $this->mTitle
, $parserOptions );
2613 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2615 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2617 $previewHTML = $parserOutput->getText();
2620 $this->mParserOutput
= $parserOutput;
2621 $wgOut->addParserOutputNoText( $parserOutput );
2623 if ( count( $parserOutput->getWarnings() ) ) {
2624 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2628 if( $this->isConflict
) {
2629 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2631 $conflict = '<hr />';
2634 $previewhead = "<div class='previewnote'>\n" .
2635 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2636 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2638 $pageLang = $this->mTitle
->getPageLanguage();
2639 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2640 'class' => 'mw-content-'.$pageLang->getDir() );
2641 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2643 wfProfileOut( __METHOD__
);
2644 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2650 function getTemplates() {
2651 if ( $this->preview ||
$this->section
!= '' ) {
2652 $templates = array();
2653 if ( !isset( $this->mParserOutput
) ) {
2656 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
2657 foreach( array_keys( $template ) as $dbk ) {
2658 $templates[] = Title
::makeTitle($ns, $dbk);
2663 return $this->mTitle
->getTemplateLinksFrom();
2668 * Shows a bulletin board style toolbar for common editing functions.
2669 * It can be disabled in the user preferences.
2670 * The necessary JavaScript code can be found in skins/common/edit.js.
2674 static function getEditToolbar() {
2675 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2676 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2678 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2681 * $toolarray is an array of arrays each of which includes the
2682 * filename of the button image (without path), the opening
2683 * tag, the closing tag, optionally a sample text that is
2684 * inserted between the two when no selection is highlighted
2685 * and. The tip text is shown when the user moves the mouse
2688 * Also here: accesskeys (key), which are not used yet until
2689 * someone can figure out a way to make them work in
2690 * IE. However, we should make sure these keys are not defined
2695 'image' => $wgLang->getImageFile( 'button-bold' ),
2696 'id' => 'mw-editbutton-bold',
2698 'close' => '\'\'\'',
2699 'sample' => wfMsg( 'bold_sample' ),
2700 'tip' => wfMsg( 'bold_tip' ),
2704 'image' => $wgLang->getImageFile( 'button-italic' ),
2705 'id' => 'mw-editbutton-italic',
2708 'sample' => wfMsg( 'italic_sample' ),
2709 'tip' => wfMsg( 'italic_tip' ),
2713 'image' => $wgLang->getImageFile( 'button-link' ),
2714 'id' => 'mw-editbutton-link',
2717 'sample' => wfMsg( 'link_sample' ),
2718 'tip' => wfMsg( 'link_tip' ),
2722 'image' => $wgLang->getImageFile( 'button-extlink' ),
2723 'id' => 'mw-editbutton-extlink',
2726 'sample' => wfMsg( 'extlink_sample' ),
2727 'tip' => wfMsg( 'extlink_tip' ),
2731 'image' => $wgLang->getImageFile( 'button-headline' ),
2732 'id' => 'mw-editbutton-headline',
2735 'sample' => wfMsg( 'headline_sample' ),
2736 'tip' => wfMsg( 'headline_tip' ),
2739 $imagesAvailable ?
array(
2740 'image' => $wgLang->getImageFile( 'button-image' ),
2741 'id' => 'mw-editbutton-image',
2742 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2744 'sample' => wfMsg( 'image_sample' ),
2745 'tip' => wfMsg( 'image_tip' ),
2748 $imagesAvailable ?
array(
2749 'image' => $wgLang->getImageFile( 'button-media' ),
2750 'id' => 'mw-editbutton-media',
2751 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2753 'sample' => wfMsg( 'media_sample' ),
2754 'tip' => wfMsg( 'media_tip' ),
2758 'image' => $wgLang->getImageFile( 'button-math' ),
2759 'id' => 'mw-editbutton-math',
2761 'close' => "</math>",
2762 'sample' => wfMsg( 'math_sample' ),
2763 'tip' => wfMsg( 'math_tip' ),
2767 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2768 'id' => 'mw-editbutton-nowiki',
2769 'open' => "<nowiki>",
2770 'close' => "</nowiki>",
2771 'sample' => wfMsg( 'nowiki_sample' ),
2772 'tip' => wfMsg( 'nowiki_tip' ),
2776 'image' => $wgLang->getImageFile( 'button-sig' ),
2777 'id' => 'mw-editbutton-signature',
2781 'tip' => wfMsg( 'sig_tip' ),
2785 'image' => $wgLang->getImageFile( 'button-hr' ),
2786 'id' => 'mw-editbutton-hr',
2787 'open' => "\n----\n",
2790 'tip' => wfMsg( 'hr_tip' ),
2795 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
2796 foreach ( $toolarray as $tool ) {
2802 $image = $wgStylePath . '/common/images/' . $tool['image'],
2803 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2804 // Older browsers show a "speedtip" type message only for ALT.
2805 // Ideally these should be different, realistically they
2806 // probably don't need to be.
2807 $tip = $tool['tip'],
2808 $open = $tool['open'],
2809 $close = $tool['close'],
2810 $sample = $tool['sample'],
2811 $cssId = $tool['id'],
2814 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2817 // This used to be called on DOMReady from mediawiki.action.edit, which
2818 // ended up causing race conditions with the setup code above.
2820 "// Create button bar\n" .
2821 "$(function() { mw.toolbar.init(); } );\n";
2824 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2826 $toolbar = '<div id="toolbar"></div>';
2828 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2834 * Returns an array of html code of the following checkboxes:
2837 * @param $tabindex int Current tabindex
2838 * @param $checked Array of checkbox => bool, where bool indicates the checked
2839 * status of the checkbox
2843 public function getCheckboxes( &$tabindex, $checked ) {
2846 $checkboxes = array();
2848 // don't show the minor edit checkbox if it's a new page or section
2849 if ( !$this->isNew
) {
2850 $checkboxes['minor'] = '';
2851 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2852 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2854 'tabindex' => ++
$tabindex,
2855 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2856 'id' => 'wpMinoredit',
2858 $checkboxes['minor'] =
2859 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2860 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2861 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2862 ">{$minorLabel}</label>";
2866 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2867 $checkboxes['watch'] = '';
2868 if ( $wgUser->isLoggedIn() ) {
2870 'tabindex' => ++
$tabindex,
2871 'accesskey' => wfMsg( 'accesskey-watch' ),
2872 'id' => 'wpWatchthis',
2874 $checkboxes['watch'] =
2875 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2876 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2877 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2878 ">{$watchLabel}</label>";
2880 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2885 * Returns an array of html code of the following buttons:
2886 * save, diff, preview and live
2888 * @param $tabindex int Current tabindex
2892 public function getEditButtons( &$tabindex ) {
2899 'tabindex' => ++
$tabindex,
2900 'value' => wfMsg( 'savearticle' ),
2901 'accesskey' => wfMsg( 'accesskey-save' ),
2902 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2904 $buttons['save'] = Xml
::element('input', $temp, '');
2906 ++
$tabindex; // use the same for preview and live preview
2908 'id' => 'wpPreview',
2909 'name' => 'wpPreview',
2911 'tabindex' => $tabindex,
2912 'value' => wfMsg( 'showpreview' ),
2913 'accesskey' => wfMsg( 'accesskey-preview' ),
2914 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2916 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
2917 $buttons['live'] = '';
2923 'tabindex' => ++
$tabindex,
2924 'value' => wfMsg( 'showdiff' ),
2925 'accesskey' => wfMsg( 'accesskey-diff' ),
2926 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2928 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
2930 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2935 * Output preview text only. This can be sucked into the edit page
2936 * via JavaScript, and saves the server time rendering the skin as
2937 * well as theoretically being more robust on the client (doesn't
2938 * disturb the edit box's undo history, won't eat your text on
2941 * @todo This doesn't include category or interlanguage links.
2942 * Would need to enhance it a bit, <s>maybe wrap them in XML
2943 * or something...</s> that might also require more skin
2944 * initialization, so check whether that's a problem.
2946 function livePreview() {
2949 header( 'Content-type: text/xml; charset=utf-8' );
2950 header( 'Cache-control: no-cache' );
2952 $previewText = $this->getPreviewText();
2953 #$categories = $skin->getCategoryLinks();
2956 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2957 Xml
::tags( 'livepreview', null,
2958 Xml
::element( 'preview', null, $previewText )
2959 #. Xml::element( 'category', null, $categories )
2965 * Call the stock "user is blocked" page
2967 * @deprecated in 1.19; throw an exception directly instead
2969 function blockedPage() {
2970 wfDeprecated( __METHOD__
, '1.19' );
2973 throw new UserBlockedError( $wgUser->mBlock
);
2977 * Produce the stock "please login to edit pages" page
2979 * @deprecated in 1.19; throw an exception directly instead
2981 function userNotLoggedInPage() {
2982 wfDeprecated( __METHOD__
, '1.19' );
2983 throw new PermissionsError( 'edit' );
2987 * Show an error page saying to the user that he has insufficient permissions
2988 * to create a new page
2990 * @deprecated in 1.19; throw an exception directly instead
2992 function noCreatePermission() {
2993 wfDeprecated( __METHOD__
, '1.19' );
2994 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
2995 throw new PermissionsError( $permission );
2999 * Creates a basic error page which informs the user that
3000 * they have attempted to edit a nonexistent section.
3002 function noSuchSectionPage() {
3005 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3007 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
3008 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3009 $wgOut->addHTML( $res );
3011 $wgOut->returnToMain( false, $this->mTitle
);
3015 * Produce the stock "your edit contains spam" page
3017 * @param $match string Text which triggered one or more filters
3018 * @deprecated since 1.17 Use method spamPageWithContent() instead
3020 static function spamPage( $match = false ) {
3021 wfDeprecated( __METHOD__
, '1.17' );
3023 global $wgOut, $wgTitle;
3025 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3027 $wgOut->addHTML( '<div id="spamprotected">' );
3028 $wgOut->addWikiMsg( 'spamprotectiontext' );
3030 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3032 $wgOut->addHTML( '</div>' );
3034 $wgOut->returnToMain( false, $wgTitle );
3038 * Show "your edit contains spam" page with your diff and text
3040 * @param $match string|bool Text which triggered one or more filters
3042 public function spamPageWithContent( $match = false ) {
3044 $this->textbox2
= $this->textbox1
;
3046 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3048 $wgOut->addHTML( '<div id="spamprotected">' );
3049 $wgOut->addWikiMsg( 'spamprotectiontext' );
3051 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3053 $wgOut->addHTML( '</div>' );
3055 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3056 $de = new DifferenceEngine( $this->mArticle
->getContext() );
3057 $de->setText( $this->getCurrentText(), $this->textbox2
);
3058 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
3060 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3061 $this->showTextbox2();
3063 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3067 * Format an anchor fragment as it would appear for a given section name
3068 * @param $text String
3072 function sectionAnchor( $text ) {
3074 return $wgParser->guessSectionNameFromWikiText( $text );
3078 * Check if the browser is on a blacklist of user-agents known to
3079 * mangle UTF-8 data on form submission. Returns true if Unicode
3080 * should make it through, false if it's known to be a problem.
3084 function checkUnicodeCompliantBrowser() {
3085 global $wgBrowserBlackList;
3086 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
3087 // No User-Agent header sent? Trust it by default...
3090 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
3091 foreach ( $wgBrowserBlackList as $browser ) {
3092 if ( preg_match($browser, $currentbrowser) ) {
3100 * Filter an input field through a Unicode de-armoring process if it
3101 * came from an old browser with known broken Unicode editing issues.
3103 * @param $request WebRequest
3104 * @param $field String
3108 function safeUnicodeInput( $request, $field ) {
3109 $text = rtrim( $request->getText( $field ) );
3110 return $request->getBool( 'safemode' )
3111 ?
$this->unmakesafe( $text )
3116 * @param $request WebRequest
3117 * @param $text string
3120 function safeUnicodeText( $request, $text ) {
3121 $text = rtrim( $text );
3122 return $request->getBool( 'safemode' )
3123 ?
$this->unmakesafe( $text )
3128 * Filter an output field through a Unicode armoring process if it is
3129 * going to an old browser with known broken Unicode editing issues.
3131 * @param $text String
3135 function safeUnicodeOutput( $text ) {
3137 $codedText = $wgContLang->recodeForEdit( $text );
3138 return $this->checkUnicodeCompliantBrowser()
3140 : $this->makesafe( $codedText );
3144 * A number of web browsers are known to corrupt non-ASCII characters
3145 * in a UTF-8 text editing environment. To protect against this,
3146 * detected browsers will be served an armored version of the text,
3147 * with non-ASCII chars converted to numeric HTML character references.
3149 * Preexisting such character references will have a 0 added to them
3150 * to ensure that round-trips do not alter the original data.
3152 * @param $invalue String
3156 function makesafe( $invalue ) {
3157 // Armor existing references for reversability.
3158 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3163 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3164 $bytevalue = ord( $invalue[$i] );
3165 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
3166 $result .= chr( $bytevalue );
3168 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
3169 $working = $working << 6;
3170 $working +
= ($bytevalue & 0x3F);
3172 if ( $bytesleft <= 0 ) {
3173 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3175 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
3176 $working = $bytevalue & 0x1F;
3178 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
3179 $working = $bytevalue & 0x0F;
3181 } else { //1111 0xxx
3182 $working = $bytevalue & 0x07;
3190 * Reverse the previously applied transliteration of non-ASCII characters
3191 * back to UTF-8. Used to protect data from corruption by broken web browsers
3192 * as listed in $wgBrowserBlackList.
3194 * @param $invalue String
3198 function unmakesafe( $invalue ) {
3200 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3201 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+
3] != '0' ) ) {
3205 $hexstring .= $invalue[$i];
3207 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3209 // Do some sanity checks. These aren't needed for reversability,
3210 // but should help keep the breakage down if the editor
3211 // breaks one of the entities whilst editing.
3212 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
3213 $codepoint = hexdec($hexstring);
3214 $result .= codepointToUtf8( $codepoint );
3216 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3219 $result .= substr( $invalue, $i, 1 );
3222 // reverse the transform that we made for reversability reasons.
3223 return strtr( $result, array( "�" => "&#x" ) );