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;
186 var $mBaseRevision = false;
187 var $mShowSummaryField = true;
190 var $save = false, $preview = false, $diff = false;
191 var $minoredit = false, $watchthis = false, $recreate = false;
192 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
193 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
194 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
196 # Placeholders for text injection by hooks (must be HTML)
197 # extensions should take care to _append_ to the present value
198 public $editFormPageTop = ''; // Before even the preview
199 public $editFormTextTop = '';
200 public $editFormTextBeforeContent = '';
201 public $editFormTextAfterWarn = '';
202 public $editFormTextAfterTools = '';
203 public $editFormTextBottom = '';
204 public $editFormTextAfterContent = '';
205 public $previewTextAfterContent = '';
206 public $mPreloadText = '';
208 /* $didSave should be set to true whenever an article was succesfully altered. */
209 public $didSave = false;
210 public $undidRev = 0;
212 public $suppressIntro = false;
215 * @param $article Article
217 public function __construct( Article
$article ) {
218 $this->mArticle
= $article;
219 $this->mTitle
= $article->getTitle();
225 public function getArticle() {
226 return $this->mArticle
;
233 public function getTitle() {
234 return $this->mTitle
;
238 * Set the context Title object
240 * @param $title Title object or null
242 public function setContextTitle( $title ) {
243 $this->mContextTitle
= $title;
247 * Get the context title object.
248 * If not set, $wgTitle will be returned. This behavior might changed in
249 * the future to return $this->mTitle instead.
251 * @return Title object
253 public function getContextTitle() {
254 if ( is_null( $this->mContextTitle
) ) {
258 return $this->mContextTitle
;
267 * This is the function that gets called for "action=edit". It
268 * sets up various member variables, then passes execution to
269 * another function, usually showEditForm()
271 * The edit form is self-submitting, so that when things like
272 * preview and edit conflicts occur, we get the same form back
273 * with the extra stuff added. Only when the final submission
274 * is made and all is well do we actually save and redirect to
275 * the newly-edited page.
278 global $wgOut, $wgRequest, $wgUser;
279 // Allow extensions to modify/prevent this form or submission
280 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
284 wfProfileIn( __METHOD__
);
285 wfDebug( __METHOD__
.": enter\n" );
287 // If they used redlink=1 and the page exists, redirect to the main article
288 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
289 $wgOut->redirect( $this->mTitle
->getFullURL() );
290 wfProfileOut( __METHOD__
);
294 $this->importFormData( $wgRequest );
295 $this->firsttime
= false;
298 $this->livePreview();
299 wfProfileOut( __METHOD__
);
303 if ( wfReadOnly() && $this->save
) {
306 $this->preview
= true;
310 $this->formtype
= 'save';
311 } elseif ( $this->preview
) {
312 $this->formtype
= 'preview';
313 } elseif ( $this->diff
) {
314 $this->formtype
= 'diff';
315 } else { # First time through
316 $this->firsttime
= true;
317 if ( $this->previewOnOpen() ) {
318 $this->formtype
= 'preview';
320 $this->formtype
= 'initial';
324 $permErrors = $this->getEditPermissionErrors();
326 wfDebug( __METHOD__
. ": User can't edit\n" );
327 // Auto-block user's IP if the account was "hard" blocked
328 $wgUser->spreadAnyEditBlock();
330 $this->displayPermissionsError( $permErrors );
332 wfProfileOut( __METHOD__
);
336 wfProfileIn( __METHOD__
."-business-end" );
338 $this->isConflict
= false;
339 // css / js subpages of user pages get a special treatment
340 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
341 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
342 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
343 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
344 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
346 # Show applicable editing introductions
347 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
351 # Attempt submission here. This will check for edit conflicts,
352 # and redundantly check for locked database, blocked IPs, etc.
353 # that edit() already checked just in case someone tries to sneak
354 # in the back door with a hand-edited submission URL.
356 if ( 'save' == $this->formtype
) {
357 if ( !$this->attemptSave() ) {
358 wfProfileOut( __METHOD__
."-business-end" );
359 wfProfileOut( __METHOD__
);
364 # First time through: get contents, set time for conflict
366 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
367 if ( $this->initialiseForm() === false ) {
368 $this->noSuchSectionPage();
369 wfProfileOut( __METHOD__
."-business-end" );
370 wfProfileOut( __METHOD__
);
373 if ( !$this->mTitle
->getArticleId() )
374 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
376 wfRunHooks( 'EditFormInitialText', array( $this ) );
379 $this->showEditForm();
380 wfProfileOut( __METHOD__
."-business-end" );
381 wfProfileOut( __METHOD__
);
387 protected function getEditPermissionErrors() {
389 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
390 # Can this title be created?
391 if ( !$this->mTitle
->exists() ) {
392 $permErrors = array_merge( $permErrors,
393 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
395 # Ignore some permissions errors when a user is just previewing/viewing diffs
397 foreach( $permErrors as $error ) {
398 if ( ( $this->preview ||
$this->diff
) &&
399 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
404 $permErrors = wfArrayDiff2( $permErrors, $remove );
409 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
410 * but with the following differences:
411 * - If redlink=1, the user will be redirected to the page
412 * - If there is content to display or the error occurs while either saving,
413 * previewing or showing the difference, it will be a
414 * "View source for ..." page displaying the source code after the error message.
417 * @param $permErrors Array of permissions errors, as returned by
418 * Title::getUserPermissionsErrors().
420 protected function displayPermissionsError( array $permErrors ) {
421 global $wgRequest, $wgOut;
423 if ( $wgRequest->getBool( 'redlink' ) ) {
424 // The edit page was reached via a red link.
425 // Redirect to the article page and let them click the edit tab if
426 // they really want a permission error.
427 $wgOut->redirect( $this->mTitle
->getFullUrl() );
431 $content = $this->getContent();
433 # Use the normal message if there's nothing to display
434 if ( $this->firsttime
&& $content === '' ) {
435 $action = $this->mTitle
->exists() ?
'edit' :
436 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
437 throw new PermissionsError( $action, $permErrors );
440 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
441 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
442 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
443 $wgOut->addHTML( "<hr />\n" );
445 # If the user made changes, preserve them when showing the markup
446 # (This happens when a user is blocked during edit, for instance)
447 if ( !$this->firsttime
) {
448 $content = $this->textbox1
;
449 $wgOut->addWikiMsg( 'viewyourtext' );
451 $wgOut->addWikiMsg( 'viewsourcetext' );
454 $this->showTextbox( $content, 'wpTextbox1', array( 'readonly' ) );
456 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
457 Linker
::formatTemplates( $this->getTemplates() ) ) );
459 if ( $this->mTitle
->exists() ) {
460 $wgOut->returnToMain( null, $this->mTitle
);
465 * Show a read-only error
466 * Parameters are the same as OutputPage:readOnlyPage()
467 * Redirect to the article page if redlink=1
468 * @deprecated in 1.19; use displayPermissionsError() instead
470 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
471 wfDeprecated( __METHOD__
, '1.19' );
473 global $wgRequest, $wgOut;
474 if ( $wgRequest->getBool( 'redlink' ) ) {
475 // The edit page was reached via a red link.
476 // Redirect to the article page and let them click the edit tab if
477 // they really want a permission error.
478 $wgOut->redirect( $this->mTitle
->getFullUrl() );
480 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
485 * Should we show a preview when the edit form is first shown?
489 protected function previewOnOpen() {
490 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
491 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
492 // Explicit override from request
494 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
495 // Explicit override from request
497 } elseif ( $this->section
== 'new' ) {
498 // Nothing *to* preview for new sections
500 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
501 // Standard preference behaviour
503 } elseif ( !$this->mTitle
->exists() &&
504 isset($wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]) &&
505 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
507 // Categories are special
515 * Checks whether the user entered a skin name in uppercase,
516 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
520 protected function isWrongCaseCssJsPage() {
521 if( $this->mTitle
->isCssJsSubpage() ) {
522 $name = $this->mTitle
->getSkinFromCssJsSubpage();
523 $skins = array_merge(
524 array_keys( Skin
::getSkinNames() ),
527 return !in_array( $name, $skins )
528 && in_array( strtolower( $name ), $skins );
535 * Does this EditPage class support section editing?
536 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
540 protected function isSectionEditSupported() {
545 * This function collects the form data and uses it to populate various member variables.
546 * @param $request WebRequest
548 function importFormData( &$request ) {
549 global $wgLang, $wgUser;
551 wfProfileIn( __METHOD__
);
553 # Section edit can come from either the form or a link
554 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
556 if ( $request->wasPosted() ) {
557 # These fields need to be checked for encoding.
558 # Also remove trailing whitespace, but don't remove _initial_
559 # whitespace from the text boxes. This may be significant formatting.
560 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
561 if ( !$request->getCheck('wpTextbox2') ) {
562 // Skip this if wpTextbox2 has input, it indicates that we came
563 // from a conflict page with raw page text, not a custom form
564 // modified by subclasses
565 wfProfileIn( get_class($this)."::importContentFormData" );
566 $textbox1 = $this->importContentFormData( $request );
567 if ( isset($textbox1) )
568 $this->textbox1
= $textbox1;
569 wfProfileOut( get_class($this)."::importContentFormData" );
572 # Truncate for whole multibyte characters. +5 bytes for ellipsis
573 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
575 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
576 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
578 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
580 # Treat sectiontitle the same way as summary.
581 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
582 # currently doing double duty as both edit summary and section title. Right now this
583 # is just to allow API edits to work around this limitation, but this should be
584 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
585 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 250 );
586 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
588 $this->edittime
= $request->getVal( 'wpEdittime' );
589 $this->starttime
= $request->getVal( 'wpStarttime' );
591 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
593 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
594 // wpTextbox1 field is missing, possibly due to being "too big"
595 // according to some filter rules such as Suhosin's setting for
596 // suhosin.request.max_value_length (d'oh)
597 $this->incompleteForm
= true;
599 // edittime should be one of our last fields; if it's missing,
600 // the submission probably broke somewhere in the middle.
601 $this->incompleteForm
= is_null( $this->edittime
);
603 if ( $this->incompleteForm
) {
604 # If the form is incomplete, force to preview.
605 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
606 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
607 $this->preview
= true;
609 /* Fallback for live preview */
610 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
611 $this->diff
= $request->getCheck( 'wpDiff' );
613 // Remember whether a save was requested, so we can indicate
614 // if we forced preview due to session failure.
615 $this->mTriedSave
= !$this->preview
;
617 if ( $this->tokenOk( $request ) ) {
618 # Some browsers will not report any submit button
619 # if the user hits enter in the comment box.
620 # The unmarked state will be assumed to be a save,
621 # if the form seems otherwise complete.
622 wfDebug( __METHOD__
. ": Passed token check.\n" );
623 } elseif ( $this->diff
) {
624 # Failed token check, but only requested "Show Changes".
625 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
627 # Page might be a hack attempt posted from
628 # an external site. Preview instead of saving.
629 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
630 $this->preview
= true;
633 $this->save
= !$this->preview
&& !$this->diff
;
634 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
635 $this->edittime
= null;
638 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
639 $this->starttime
= null;
642 $this->recreate
= $request->getCheck( 'wpRecreate' );
644 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
645 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
647 # Don't force edit summaries when a user is editing their own user or talk page
648 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
649 $this->mTitle
->getText() == $wgUser->getName() )
651 $this->allowBlankSummary
= true;
653 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
656 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
658 # Not a posted form? Start with nothing.
659 wfDebug( __METHOD__
. ": Not a posted form.\n" );
660 $this->textbox1
= '';
662 $this->sectiontitle
= '';
663 $this->edittime
= '';
664 $this->starttime
= wfTimestampNow();
666 $this->preview
= false;
669 $this->minoredit
= false;
670 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
671 $this->recreate
= false;
673 // When creating a new section, we can preload a section title by passing it as the
674 // preloadtitle parameter in the URL (Bug 13100)
675 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
676 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
677 // Once wpSummary isn't being use for setting section titles, we should delete this.
678 $this->summary
= $request->getVal( 'preloadtitle' );
680 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
681 $this->summary
= $request->getText( 'summary' );
684 if ( $request->getVal( 'minor' ) ) {
685 $this->minoredit
= true;
689 $this->bot
= $request->getBool( 'bot', true );
690 $this->nosummary
= $request->getBool( 'nosummary' );
692 $this->oldid
= $request->getInt( 'oldid' );
694 $this->live
= $request->getCheck( 'live' );
695 $this->editintro
= $request->getText( 'editintro',
696 // Custom edit intro for new sections
697 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
699 // Allow extensions to modify form data
700 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
702 wfProfileOut( __METHOD__
);
706 * Subpage overridable method for extracting the page content data from the
707 * posted form to be placed in $this->textbox1, if using customized input
708 * this method should be overrided and return the page text that will be used
709 * for saving, preview parsing and so on...
711 * @param $request WebRequest
713 protected function importContentFormData( &$request ) {
714 return; // Don't do anything, EditPage already extracted wpTextbox1
718 * Initialise form fields in the object
719 * Called on the first invocation, e.g. when a user clicks an edit link
720 * @return bool -- if the requested section is valid
722 function initialiseForm() {
724 $this->edittime
= $this->mArticle
->getTimestamp();
725 $this->textbox1
= $this->getContent( false );
726 // activate checkboxes if user wants them to be always active
727 # Sort out the "watch" checkbox
728 if ( $wgUser->getOption( 'watchdefault' ) ) {
730 $this->watchthis
= true;
731 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
733 $this->watchthis
= true;
734 } elseif ( $this->mTitle
->userIsWatching() ) {
736 $this->watchthis
= true;
738 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
739 $this->minoredit
= true;
741 if ( $this->textbox1
=== false ) {
749 * Fetch initial editing page content.
751 * @param $def_text string
752 * @return mixed string on success, $def_text for invalid sections
755 function getContent( $def_text = '' ) {
756 global $wgOut, $wgRequest, $wgParser;
758 wfProfileIn( __METHOD__
);
762 // For message page not locally set, use the i18n message.
763 // For other non-existent articles, use preload text if any.
764 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
765 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
766 # If this is a system message, get the default text.
767 $text = $this->mTitle
->getDefaultMessageText();
769 if ( $text === false ) {
770 # If requested, preload some text.
771 $preload = $wgRequest->getVal( 'preload',
772 // Custom preload text for new sections
773 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
774 $text = $this->getPreloadedText( $preload );
776 // For existing pages, get text based on "undo" or section parameters.
778 if ( $this->section
!= '' ) {
779 // Get section edit text (returns $def_text for invalid sections)
780 $text = $wgParser->getSection( $this->getOriginalContent(), $this->section
, $def_text );
782 $undoafter = $wgRequest->getInt( 'undoafter' );
783 $undo = $wgRequest->getInt( 'undo' );
785 if ( $undo > 0 && $undoafter > 0 ) {
786 if ( $undo < $undoafter ) {
787 # If they got undoafter and undo round the wrong way, switch them
788 list( $undo, $undoafter ) = array( $undoafter, $undo );
791 $undorev = Revision
::newFromId( $undo );
792 $oldrev = Revision
::newFromId( $undoafter );
794 # Sanity check, make sure it's the right page,
795 # the revisions exist and they were not deleted.
796 # Otherwise, $text will be left as-is.
797 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
798 $undorev->getPage() == $oldrev->getPage() &&
799 $undorev->getPage() == $this->mTitle
->getArticleId() &&
800 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
801 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
803 $text = $this->mArticle
->getUndoText( $undorev, $oldrev );
804 if ( $text === false ) {
805 # Warn the user that something went wrong
806 $undoMsg = 'failure';
808 # Inform the user of our success and set an automatic edit summary
809 $undoMsg = 'success';
811 # If we just undid one rev, use an autosummary
812 $firstrev = $oldrev->getNext();
813 if ( $firstrev->getId() == $undo ) {
814 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
815 if ( $this->summary
=== '' ) {
816 $this->summary
= $undoSummary;
818 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
820 $this->undidRev
= $undo;
822 $this->formtype
= 'diff';
825 // Failed basic sanity checks.
826 // Older revisions may have been removed since the link
827 // was created, or we may simply have got bogus input.
831 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"error mw-undo-{$undoMsg}\">" .
832 wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
835 if ( $text === false ) {
836 $text = $this->getOriginalContent();
841 wfProfileOut( __METHOD__
);
846 * Get the content of the wanted revision, without section extraction.
848 * The result of this function can be used to compare user's input with
849 * section replaced in its context (using WikiPage::replaceSection())
850 * to the original text of the edit.
852 * This difers from Article::getContent() that when a missing revision is
853 * encountered the result will be an empty string and not the
854 * 'missing-article' message.
859 private function getOriginalContent() {
860 if ( $this->section
== 'new' ) {
861 return $this->getCurrentText();
863 $revision = $this->mArticle
->getRevisionFetched();
864 if ( $revision === null ) {
867 return $this->mArticle
->getContent();
871 * Get the actual text of the page. This is basically similar to
872 * WikiPage::getRawText() except that when the page doesn't exist an empty
873 * string is returned instead of false.
878 private function getCurrentText() {
879 $text = $this->mArticle
->getRawText();
880 if ( $text === false ) {
888 * Use this method before edit() to preload some text into the edit box
890 * @param $text string
892 public function setPreloadedText( $text ) {
893 $this->mPreloadText
= $text;
897 * Get the contents to be preloaded into the box, either set by
898 * an earlier setPreloadText() or by loading the given page.
900 * @param $preload String: representing the title to preload from.
903 protected function getPreloadedText( $preload ) {
904 global $wgUser, $wgParser;
906 if ( !empty( $this->mPreloadText
) ) {
907 return $this->mPreloadText
;
910 if ( $preload === '' ) {
914 $title = Title
::newFromText( $preload );
915 # Check for existence to avoid getting MediaWiki:Noarticletext
916 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
920 $page = WikiPage
::factory( $title );
921 if ( $page->isRedirect() ) {
922 $title = $page->getRedirectTarget();
924 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
927 $page = WikiPage
::factory( $title );
930 $parserOptions = ParserOptions
::newFromUser( $wgUser );
931 return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
935 * Make sure the form isn't faking a user's credentials.
937 * @param $request WebRequest
941 function tokenOk( &$request ) {
943 $token = $request->getVal( 'wpEditToken' );
944 $this->mTokenOk
= $wgUser->matchEditToken( $token );
945 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
946 return $this->mTokenOk
;
951 * @return bool false if output is done, true if the rest of the form should be displayed
953 function attemptSave() {
954 global $wgUser, $wgOut;
956 $resultDetails = false;
957 # Allow bots to exempt some edits from bot flagging
958 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
959 $status = $this->internalAttemptSave( $resultDetails, $bot );
960 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
962 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
963 $this->didSave
= true;
966 switch ( $status->value
) {
967 case self
::AS_HOOK_ERROR_EXPECTED
:
968 case self
::AS_CONTENT_TOO_BIG
:
969 case self
::AS_ARTICLE_WAS_DELETED
:
970 case self
::AS_CONFLICT_DETECTED
:
971 case self
::AS_SUMMARY_NEEDED
:
972 case self
::AS_TEXTBOX_EMPTY
:
973 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
977 case self
::AS_HOOK_ERROR
:
978 case self
::AS_FILTERING
:
981 case self
::AS_SUCCESS_NEW_ARTICLE
:
982 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
983 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
984 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
987 case self
::AS_SUCCESS_UPDATE
:
989 $sectionanchor = $resultDetails['sectionanchor'];
991 // Give extensions a chance to modify URL query on update
992 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
994 if ( $resultDetails['redirect'] ) {
995 if ( $extraQuery == '' ) {
996 $extraQuery = 'redirect=no';
998 $extraQuery = 'redirect=no&' . $extraQuery;
1001 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1004 case self
::AS_BLANK_ARTICLE
:
1005 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1008 case self
::AS_SPAM_ERROR
:
1009 $this->spamPageWithContent( $resultDetails['spam'] );
1012 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1013 throw new UserBlockedError( $wgUser->mBlock
);
1015 case self
::AS_IMAGE_REDIRECT_ANON
:
1016 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1017 throw new PermissionsError( 'upload' );
1019 case self
::AS_READ_ONLY_PAGE_ANON
:
1020 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1021 throw new PermissionsError( 'edit' );
1023 case self
::AS_READ_ONLY_PAGE
:
1024 throw new ReadOnlyError
;
1026 case self
::AS_RATE_LIMITED
:
1027 throw new ThrottledError();
1029 case self
::AS_NO_CREATE_PERMISSION
:
1030 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1031 throw new PermissionsError( $permission );
1038 * Attempt submission (no UI)
1043 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1045 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1046 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1047 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1049 function internalAttemptSave( &$result, $bot = false ) {
1050 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
1051 global $wgMaxArticleSize;
1053 $status = Status
::newGood();
1055 wfProfileIn( __METHOD__
);
1056 wfProfileIn( __METHOD__
. '-checks' );
1058 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1059 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1060 $status->fatal( 'hookaborted' );
1061 $status->value
= self
::AS_HOOK_ERROR
;
1062 wfProfileOut( __METHOD__
. '-checks' );
1063 wfProfileOut( __METHOD__
);
1067 # Check image redirect
1068 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1069 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
1070 !$wgUser->isAllowed( 'upload' ) ) {
1071 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1072 $status->setResult( false, $code );
1074 wfProfileOut( __METHOD__
. '-checks' );
1075 wfProfileOut( __METHOD__
);
1081 $match = self
::matchSummarySpamRegex( $this->summary
);
1082 if ( $match === false ) {
1083 $match = self
::matchSpamRegex( $this->textbox1
);
1085 if ( $match !== false ) {
1086 $result['spam'] = $match;
1087 $ip = $wgRequest->getIP();
1088 $pdbk = $this->mTitle
->getPrefixedDBkey();
1089 $match = str_replace( "\n", '', $match );
1090 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1091 $status->fatal( 'spamprotectionmatch', $match );
1092 $status->value
= self
::AS_SPAM_ERROR
;
1093 wfProfileOut( __METHOD__
. '-checks' );
1094 wfProfileOut( __METHOD__
);
1097 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
1098 # Error messages or other handling should be performed by the filter function
1099 $status->setResult( false, self
::AS_FILTERING
);
1100 wfProfileOut( __METHOD__
. '-checks' );
1101 wfProfileOut( __METHOD__
);
1104 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1105 # Error messages etc. could be handled within the hook...
1106 $status->fatal( 'hookaborted' );
1107 $status->value
= self
::AS_HOOK_ERROR
;
1108 wfProfileOut( __METHOD__
. '-checks' );
1109 wfProfileOut( __METHOD__
);
1111 } elseif ( $this->hookError
!= '' ) {
1112 # ...or the hook could be expecting us to produce an error
1113 $status->fatal( 'hookaborted' );
1114 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1115 wfProfileOut( __METHOD__
. '-checks' );
1116 wfProfileOut( __METHOD__
);
1120 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1121 // Auto-block user's IP if the account was "hard" blocked
1122 $wgUser->spreadAnyEditBlock();
1123 # Check block state against master, thus 'false'.
1124 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1125 wfProfileOut( __METHOD__
. '-checks' );
1126 wfProfileOut( __METHOD__
);
1130 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1131 if ( $this->kblength
> $wgMaxArticleSize ) {
1132 // Error will be displayed by showEditForm()
1133 $this->tooBig
= true;
1134 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1135 wfProfileOut( __METHOD__
. '-checks' );
1136 wfProfileOut( __METHOD__
);
1140 if ( !$wgUser->isAllowed( 'edit' ) ) {
1141 if ( $wgUser->isAnon() ) {
1142 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1143 wfProfileOut( __METHOD__
. '-checks' );
1144 wfProfileOut( __METHOD__
);
1147 $status->fatal( 'readonlytext' );
1148 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1149 wfProfileOut( __METHOD__
. '-checks' );
1150 wfProfileOut( __METHOD__
);
1155 if ( wfReadOnly() ) {
1156 $status->fatal( 'readonlytext' );
1157 $status->value
= self
::AS_READ_ONLY_PAGE
;
1158 wfProfileOut( __METHOD__
. '-checks' );
1159 wfProfileOut( __METHOD__
);
1162 if ( $wgUser->pingLimiter() ) {
1163 $status->fatal( 'actionthrottledtext' );
1164 $status->value
= self
::AS_RATE_LIMITED
;
1165 wfProfileOut( __METHOD__
. '-checks' );
1166 wfProfileOut( __METHOD__
);
1170 # If the article has been deleted while editing, don't save it without
1172 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1173 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1174 wfProfileOut( __METHOD__
. '-checks' );
1175 wfProfileOut( __METHOD__
);
1179 wfProfileOut( __METHOD__
. '-checks' );
1181 # If article is new, insert it.
1182 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1183 $new = ( $aid == 0 );
1186 // Late check for create permission, just in case *PARANOIA*
1187 if ( !$this->mTitle
->userCan( 'create' ) ) {
1188 $status->fatal( 'nocreatetext' );
1189 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1190 wfDebug( __METHOD__
. ": no create permission\n" );
1191 wfProfileOut( __METHOD__
);
1195 # Don't save a new article if it's blank.
1196 if ( $this->textbox1
== '' ) {
1197 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1198 wfProfileOut( __METHOD__
);
1202 // Run post-section-merge edit filter
1203 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1204 # Error messages etc. could be handled within the hook...
1205 $status->fatal( 'hookaborted' );
1206 $status->value
= self
::AS_HOOK_ERROR
;
1207 wfProfileOut( __METHOD__
);
1209 } elseif ( $this->hookError
!= '' ) {
1210 # ...or the hook could be expecting us to produce an error
1211 $status->fatal( 'hookaborted' );
1212 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1213 wfProfileOut( __METHOD__
);
1217 # Handle the user preference to force summaries here. Check if it's not a redirect.
1218 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
1219 if ( md5( $this->summary
) == $this->autoSumm
) {
1220 $this->missingSummary
= true;
1221 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1222 $status->value
= self
::AS_SUMMARY_NEEDED
;
1223 wfProfileOut( __METHOD__
);
1228 $text = $this->textbox1
;
1229 $result['sectionanchor'] = '';
1230 if ( $this->section
== 'new' ) {
1231 if ( $this->sectiontitle
!== '' ) {
1232 // Insert the section title above the content.
1233 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle
) . "\n\n" . $text;
1235 // Jump to the new section
1236 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1238 // If no edit summary was specified, create one automatically from the section
1239 // title and have it link to the new section. Otherwise, respect the summary as
1241 if ( $this->summary
=== '' ) {
1242 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1243 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1245 } elseif ( $this->summary
!== '' ) {
1246 // Insert the section title above the content.
1247 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $text;
1249 // Jump to the new section
1250 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1252 // Create a link to the new section from the edit summary.
1253 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1254 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1258 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1262 # Article exists. Check for edit conflict.
1264 $this->mArticle
->clear(); # Force reload of dates, etc.
1265 $timestamp = $this->mArticle
->getTimestamp();
1267 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1269 if ( $timestamp != $this->edittime
) {
1270 $this->isConflict
= true;
1271 if ( $this->section
== 'new' ) {
1272 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1273 $this->mArticle
->getComment() == $this->summary
) {
1274 // Probably a duplicate submission of a new comment.
1275 // This can happen when squid resends a request after
1276 // a timeout but the first one actually went through.
1277 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1279 // New comment; suppress conflict.
1280 $this->isConflict
= false;
1281 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1283 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1284 # Suppress edit conflict with self, except for section edits where merging is required.
1285 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1286 $this->isConflict
= false;
1290 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1291 // backwards compatibility with old forms/bots).
1292 if ( $this->sectiontitle
!== '' ) {
1293 $sectionTitle = $this->sectiontitle
;
1295 $sectionTitle = $this->summary
;
1298 if ( $this->isConflict
) {
1299 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1300 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle, $this->edittime
);
1302 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1303 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle );
1305 if ( is_null( $text ) ) {
1306 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1307 $this->isConflict
= true;
1308 $text = $this->textbox1
; // do not try to merge here!
1309 } elseif ( $this->isConflict
) {
1311 if ( $this->mergeChangesInto( $text ) ) {
1312 // Successful merge! Maybe we should tell the user the good news?
1313 $this->isConflict
= false;
1314 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1316 $this->section
= '';
1317 $this->textbox1
= $text;
1318 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1322 if ( $this->isConflict
) {
1323 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1324 wfProfileOut( __METHOD__
);
1328 // Run post-section-merge edit filter
1329 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
1330 # Error messages etc. could be handled within the hook...
1331 $status->fatal( 'hookaborted' );
1332 $status->value
= self
::AS_HOOK_ERROR
;
1333 wfProfileOut( __METHOD__
);
1335 } elseif ( $this->hookError
!= '' ) {
1336 # ...or the hook could be expecting us to produce an error
1337 $status->fatal( 'hookaborted' );
1338 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1339 wfProfileOut( __METHOD__
);
1343 # Handle the user preference to force summaries here, but not for null edits
1344 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1345 && $this->getOriginalContent() != $text
1346 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1348 if ( md5( $this->summary
) == $this->autoSumm
) {
1349 $this->missingSummary
= true;
1350 $status->fatal( 'missingsummary' );
1351 $status->value
= self
::AS_SUMMARY_NEEDED
;
1352 wfProfileOut( __METHOD__
);
1357 # And a similar thing for new sections
1358 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1359 if ( trim( $this->summary
) == '' ) {
1360 $this->missingSummary
= true;
1361 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1362 $status->value
= self
::AS_SUMMARY_NEEDED
;
1363 wfProfileOut( __METHOD__
);
1369 wfProfileIn( __METHOD__
. '-sectionanchor' );
1370 $sectionanchor = '';
1371 if ( $this->section
== 'new' ) {
1372 if ( $this->textbox1
== '' ) {
1373 $this->missingComment
= true;
1374 $status->fatal( 'missingcommenttext' );
1375 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1376 wfProfileOut( __METHOD__
. '-sectionanchor' );
1377 wfProfileOut( __METHOD__
);
1380 if ( $this->sectiontitle
!== '' ) {
1381 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1382 // If no edit summary was specified, create one automatically from the section
1383 // title and have it link to the new section. Otherwise, respect the summary as
1385 if ( $this->summary
=== '' ) {
1386 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1387 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1389 } elseif ( $this->summary
!== '' ) {
1390 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1391 # This is a new section, so create a link to the new section
1392 # in the revision summary.
1393 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1394 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1396 } elseif ( $this->section
!= '' ) {
1397 # Try to get a section anchor from the section source, redirect to edited section if header found
1398 # XXX: might be better to integrate this into Article::replaceSection
1399 # for duplicate heading checking and maybe parsing
1400 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1401 # we can't deal with anchors, includes, html etc in the header for now,
1402 # headline would need to be parsed to improve this
1403 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1404 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1407 $result['sectionanchor'] = $sectionanchor;
1408 wfProfileOut( __METHOD__
. '-sectionanchor' );
1410 // Save errors may fall down to the edit form, but we've now
1411 // merged the section into full text. Clear the section field
1412 // so that later submission of conflict forms won't try to
1413 // replace that into a duplicated mess.
1414 $this->textbox1
= $text;
1415 $this->section
= '';
1417 $status->value
= self
::AS_SUCCESS_UPDATE
;
1420 // Check for length errors again now that the section is merged in
1421 $this->kblength
= (int)( strlen( $text ) / 1024 );
1422 if ( $this->kblength
> $wgMaxArticleSize ) {
1423 $this->tooBig
= true;
1424 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1425 wfProfileOut( __METHOD__
);
1429 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1430 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1431 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1432 ( $bot ? EDIT_FORCE_BOT
: 0 );
1434 $doEditStatus = $this->mArticle
->doEdit( $text, $this->summary
, $flags );
1436 if ( $doEditStatus->isOK() ) {
1437 $result['redirect'] = Title
::newFromRedirect( $text ) !== null;
1438 $this->commitWatch();
1439 wfProfileOut( __METHOD__
);
1442 $this->isConflict
= true;
1443 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1444 wfProfileOut( __METHOD__
);
1445 return $doEditStatus;
1450 * Commit the change of watch status
1452 protected function commitWatch() {
1454 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1455 $dbw = wfGetDB( DB_MASTER
);
1457 if ( $this->watchthis
) {
1458 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1460 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1467 * Check if no edits were made by other users since
1468 * the time a user started editing the page. Limit to
1469 * 50 revisions for the sake of performance.
1472 * @param $edittime string
1476 protected function userWasLastToEdit( $id, $edittime ) {
1477 if( !$id ) return false;
1478 $dbw = wfGetDB( DB_MASTER
);
1479 $res = $dbw->select( 'revision',
1482 'rev_page' => $this->mTitle
->getArticleId(),
1483 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1486 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1487 foreach ( $res as $row ) {
1488 if( $row->rev_user
!= $id ) {
1499 * @parma $editText string
1503 function mergeChangesInto( &$editText ){
1504 wfProfileIn( __METHOD__
);
1506 $db = wfGetDB( DB_MASTER
);
1508 // This is the revision the editor started from
1509 $baseRevision = $this->getBaseRevision();
1510 if ( is_null( $baseRevision ) ) {
1511 wfProfileOut( __METHOD__
);
1514 $baseText = $baseRevision->getText();
1516 // The current state, we want to merge updates into it
1517 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1518 if ( is_null( $currentRevision ) ) {
1519 wfProfileOut( __METHOD__
);
1522 $currentText = $currentRevision->getText();
1525 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1526 $editText = $result;
1527 wfProfileOut( __METHOD__
);
1530 wfProfileOut( __METHOD__
);
1538 function getBaseRevision() {
1539 if ( !$this->mBaseRevision
) {
1540 $db = wfGetDB( DB_MASTER
);
1541 $baseRevision = Revision
::loadFromTimestamp(
1542 $db, $this->mTitle
, $this->edittime
);
1543 return $this->mBaseRevision
= $baseRevision;
1545 return $this->mBaseRevision
;
1550 * Check given input text against $wgSpamRegex, and return the text of the first match.
1552 * @param $text string
1554 * @return string|false matching string or false
1556 public static function matchSpamRegex( $text ) {
1557 global $wgSpamRegex;
1558 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1559 $regexes = (array)$wgSpamRegex;
1560 return self
::matchSpamRegexInternal( $text, $regexes );
1564 * Check given input text against $wgSpamRegex, and return the text of the first match.
1566 * @parma $text string
1568 * @return string|false matching string or false
1570 public static function matchSummarySpamRegex( $text ) {
1571 global $wgSummarySpamRegex;
1572 $regexes = (array)$wgSummarySpamRegex;
1573 return self
::matchSpamRegexInternal( $text, $regexes );
1577 * @param $text string
1578 * @param $regexes array
1579 * @return bool|string
1581 protected static function matchSpamRegexInternal( $text, $regexes ) {
1582 foreach( $regexes as $regex ) {
1584 if( preg_match( $regex, $text, $matches ) ) {
1591 function setHeaders() {
1592 global $wgOut, $wgUser;
1594 $wgOut->addModules( 'mediawiki.action.edit' );
1596 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1597 $wgOut->addModules( 'mediawiki.legacy.preview' );
1599 // Bug #19334: textarea jumps when editing articles in IE8
1600 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1602 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1604 # Enabled article-related sidebar, toplinks, etc.
1605 $wgOut->setArticleRelated( true );
1607 if ( $this->isConflict
) {
1608 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1609 } elseif ( $this->section
!= '' ) {
1610 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1611 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1613 # Use the title defined by DISPLAYTITLE magic word when present
1614 if ( isset( $this->mParserOutput
)
1615 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1618 $title = $this->getContextTitle()->getPrefixedText();
1620 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1625 * Show all applicable editing introductions
1627 protected function showIntro() {
1628 global $wgOut, $wgUser;
1629 if ( $this->suppressIntro
) {
1633 $namespace = $this->mTitle
->getNamespace();
1635 if ( $namespace == NS_MEDIAWIKI
) {
1636 # Show a warning if editing an interface message
1637 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1640 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1641 # Show log extract when the user is currently blocked
1642 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1643 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1644 $username = $parts[0];
1645 $user = User
::newFromName( $username, false /* allow IP users*/ );
1646 $ip = User
::isIP( $username );
1647 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1648 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1649 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1650 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1651 LogEventsList
::showLogExtract(
1654 $user->getUserPage(),
1658 'showIfEmpty' => false,
1660 'blocked-notice-logextract',
1661 $user->getName() # Support GENDER in notice
1667 # Try to add a custom edit intro, or use the standard one if this is not possible.
1668 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1669 if ( $wgUser->isLoggedIn() ) {
1670 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1672 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1675 # Give a notice if the user is editing a deleted/moved page...
1676 if ( !$this->mTitle
->exists() ) {
1677 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1678 '', array( 'lim' => 10,
1679 'conds' => array( "log_action != 'revision'" ),
1680 'showIfEmpty' => false,
1681 'msgKey' => array( 'recreate-moveddeleted-warn') )
1687 * Attempt to show a custom editing introduction, if supplied
1691 protected function showCustomIntro() {
1692 if ( $this->editintro
) {
1693 $title = Title
::newFromText( $this->editintro
);
1694 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1696 // Added using template syntax, to take <noinclude>'s into account.
1697 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1708 * Send the edit form and related headers to $wgOut
1709 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1710 * during form output near the top, for captchas and the like.
1712 function showEditForm( $formCallback = null ) {
1713 global $wgOut, $wgUser;
1715 wfProfileIn( __METHOD__
);
1717 #need to parse the preview early so that we know which templates are used,
1718 #otherwise users with "show preview after edit box" will get a blank list
1719 #we parse this near the beginning so that setHeaders can do the title
1720 #setting work instead of leaving it in getPreviewText
1721 $previewOutput = '';
1722 if ( $this->formtype
== 'preview' ) {
1723 $previewOutput = $this->getPreviewText();
1726 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1728 $this->setHeaders();
1730 if ( $this->showHeader() === false ) {
1731 wfProfileOut( __METHOD__
);
1735 $wgOut->addHTML( $this->editFormPageTop
);
1737 if ( $wgUser->getOption( 'previewontop' ) ) {
1738 $this->displayPreviewArea( $previewOutput, true );
1741 $wgOut->addHTML( $this->editFormTextTop
);
1743 $showToolbar = true;
1744 if ( $this->wasDeletedSinceLastEdit() ) {
1745 if ( $this->formtype
== 'save' ) {
1746 // Hide the toolbar and edit area, user can click preview to get it back
1747 // Add an confirmation checkbox and explanation.
1748 $showToolbar = false;
1750 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1751 'deletedwhileediting' );
1755 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
1756 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1757 'enctype' => 'multipart/form-data' ) ) );
1759 if ( is_callable( $formCallback ) ) {
1760 call_user_func_array( $formCallback, array( &$wgOut ) );
1763 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1765 // Put these up at the top to ensure they aren't lost on early form submission
1766 $this->showFormBeforeText();
1768 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1769 $username = $this->lastDelete
->user_name
;
1770 $comment = $this->lastDelete
->log_comment
;
1772 // It is better to not parse the comment at all than to have templates expanded in the middle
1773 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1774 $key = $comment === ''
1775 ?
'confirmrecreate-noreason'
1776 : 'confirmrecreate';
1778 '<div class="mw-confirm-recreate">' .
1779 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1780 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1781 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1787 # If a blank edit summary was previously provided, and the appropriate
1788 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1789 # user being bounced back more than once in the event that a summary
1792 # For a bit more sophisticated detection of blank summaries, hash the
1793 # automatic one and pass that in the hidden field wpAutoSummary.
1794 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
1795 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1798 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1799 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1801 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
1803 if ( $this->section
== 'new' ) {
1804 $this->showSummaryInput( true, $this->summary
);
1805 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1808 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1810 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1811 $wgOut->addHTML( EditPage
::getEditToolbar() );
1814 if ( $this->isConflict
) {
1815 // In an edit conflict bypass the overrideable content form method
1816 // and fallback to the raw wpTextbox1 since editconflicts can't be
1817 // resolved between page source edits and custom ui edits using the
1819 $this->textbox2
= $this->textbox1
;
1820 $this->textbox1
= $this->getCurrentText();
1822 $this->showTextbox1();
1824 $this->showContentForm();
1827 $wgOut->addHTML( $this->editFormTextAfterContent
);
1829 $wgOut->addWikiText( $this->getCopywarn() );
1831 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1833 $this->showStandardInputs();
1835 $this->showFormAfterText();
1837 $this->showTosSummary();
1839 $this->showEditTools();
1841 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
1843 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
1844 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
1846 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
1847 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
1849 if ( $this->isConflict
) {
1850 $this->showConflict();
1853 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
1855 if ( !$wgUser->getOption( 'previewontop' ) ) {
1856 $this->displayPreviewArea( $previewOutput, false );
1859 wfProfileOut( __METHOD__
);
1863 * Extract the section title from current section text, if any.
1865 * @param string $text
1866 * @return Mixed|string or false
1868 public static function extractSectionTitle( $text ) {
1869 preg_match( "/^(=+)(.+)\\1(\n|$)/i", $text, $matches );
1870 if ( !empty( $matches[2] ) ) {
1872 return $wgParser->stripSectionName(trim($matches[2]));
1878 protected function showHeader() {
1879 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1881 if ( $this->mTitle
->isTalkPage() ) {
1882 $wgOut->addWikiMsg( 'talkpagetext' );
1885 # Optional notices on a per-namespace and per-page basis
1886 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
1887 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
1888 if ( $editnotice_ns_message->exists() ) {
1889 $wgOut->addWikiText( $editnotice_ns_message->plain() );
1891 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
1892 $parts = explode( '/', $this->mTitle
->getDBkey() );
1893 $editnotice_base = $editnotice_ns;
1894 while ( count( $parts ) > 0 ) {
1895 $editnotice_base .= '-'.array_shift( $parts );
1896 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
1897 if ( $editnotice_base_msg->exists() ) {
1898 $wgOut->addWikiText( $editnotice_base_msg->plain() );
1902 # Even if there are no subpages in namespace, we still don't want / in MW ns.
1903 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
1904 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
1905 if ( $editnoticeMsg->exists() ) {
1906 $wgOut->addWikiText( $editnoticeMsg->plain() );
1910 if ( $this->isConflict
) {
1911 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1912 $this->edittime
= $this->mArticle
->getTimestamp();
1914 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
1915 // We use $this->section to much before this and getVal('wgSection') directly in other places
1916 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1917 // Someone is welcome to try refactoring though
1918 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1922 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1923 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1924 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
1925 if ( $sectionTitle !== false ) {
1926 $this->summary
= "/* $sectionTitle */ ";
1931 if ( $this->missingComment
) {
1932 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1935 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1936 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1939 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1940 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1943 if ( $this->hookError
!== '' ) {
1944 $wgOut->addWikiText( $this->hookError
);
1947 if ( !$this->checkUnicodeCompliantBrowser() ) {
1948 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1951 if ( $this->section
!= 'new' ) {
1952 $revision = $this->mArticle
->getRevisionFetched();
1954 // Let sysop know that this will make private content public if saved
1956 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
1957 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1958 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
1959 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1962 if ( !$revision->isCurrent() ) {
1963 $this->mArticle
->setOldSubtitle( $revision->getId() );
1964 $wgOut->addWikiMsg( 'editingold' );
1966 } elseif ( $this->mTitle
->exists() ) {
1967 // Something went wrong
1969 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
1970 array( 'missing-article', $this->mTitle
->getPrefixedText(),
1971 wfMsgNoTrans( 'missingarticle-rev', $this->oldid
) ) );
1976 if ( wfReadOnly() ) {
1977 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1978 } elseif ( $wgUser->isAnon() ) {
1979 if ( $this->formtype
!= 'preview' ) {
1980 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1982 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
1985 if ( $this->isCssJsSubpage
) {
1986 # Check the skin exists
1987 if ( $this->isWrongCaseCssJsPage
) {
1988 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
1990 if ( $this->formtype
!== 'preview' ) {
1991 if ( $this->isCssSubpage
)
1992 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
1993 if ( $this->isJsSubpage
)
1994 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
1999 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2000 # Is the title semi-protected?
2001 if ( $this->mTitle
->isSemiProtected() ) {
2002 $noticeMsg = 'semiprotectedpagewarning';
2004 # Then it must be protected based on static groups (regular)
2005 $noticeMsg = 'protectedpagewarning';
2007 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2008 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2010 if ( $this->mTitle
->isCascadeProtected() ) {
2011 # Is this page under cascading protection from some source pages?
2012 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
2013 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2014 $cascadeSourcesCount = count( $cascadeSources );
2015 if ( $cascadeSourcesCount > 0 ) {
2016 # Explain, and list the titles responsible
2017 foreach( $cascadeSources as $page ) {
2018 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2021 $notice .= '</div>';
2022 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2024 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2025 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2027 'showIfEmpty' => false,
2028 'msgKey' => array( 'titleprotectedwarning' ),
2029 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2032 if ( $this->kblength
=== false ) {
2033 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2036 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2037 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2038 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2040 if( !wfMessage('longpage-hint')->isDisabled() ) {
2041 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2042 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2049 * Standard summary input and label (wgSummary), abstracted so EditPage
2050 * subclasses may reorganize the form.
2051 * Note that you do not need to worry about the label's for=, it will be
2052 * inferred by the id given to the input. You can remove them both by
2053 * passing array( 'id' => false ) to $userInputAttrs.
2055 * @param $summary string The value of the summary input
2056 * @param $labelText string The html to place inside the label
2057 * @param $inputAttrs array of attrs to use on the input
2058 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2060 * @return array An array in the format array( $label, $input )
2062 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
2063 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
2064 $inputAttrs = ( is_array($inputAttrs) ?
$inputAttrs : array() ) +
array(
2065 'id' => 'wpSummary',
2066 'maxlength' => '200',
2069 'spellcheck' => 'true',
2070 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2072 $spanLabelAttrs = ( is_array($spanLabelAttrs) ?
$spanLabelAttrs : array() ) +
array(
2073 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2074 'id' => "wpSummaryLabel"
2079 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2080 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2083 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2085 return array( $label, $input );
2089 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2090 * up top, or false if this is the comment summary
2091 * down below the textarea
2092 * @param $summary String: The text of the summary to display
2095 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2096 global $wgOut, $wgContLang;
2097 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2098 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2099 if ( $isSubjectPreview ) {
2100 if ( $this->nosummary
) {
2104 if ( !$this->mShowSummaryField
) {
2108 $summary = $wgContLang->recodeForEdit( $summary );
2109 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
2110 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
2111 $wgOut->addHTML("{$label} {$input}");
2115 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2116 * up top, or false if this is the comment summary
2117 * down below the textarea
2118 * @param $summary String: the text of the summary to display
2121 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2122 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2127 if ( $isSubjectPreview )
2128 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2130 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2132 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2133 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2136 protected function showFormBeforeText() {
2138 $section = htmlspecialchars( $this->section
);
2139 $wgOut->addHTML( <<<HTML
2140 <input type='hidden' value="{$section}" name="wpSection" />
2141 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2142 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2143 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2147 if ( !$this->checkUnicodeCompliantBrowser() )
2148 $wgOut->addHTML(Html
::hidden( 'safemode', '1' ));
2151 protected function showFormAfterText() {
2152 global $wgOut, $wgUser;
2154 * To make it harder for someone to slip a user a page
2155 * which submits an edit form to the wiki without their
2156 * knowledge, a random token is associated with the login
2157 * session. If it's not passed back with the submission,
2158 * we won't save the page, or render user JavaScript and
2161 * For anon editors, who may not have a session, we just
2162 * include the constant suffix to prevent editing from
2163 * broken text-mangling proxies.
2165 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2169 * Subpage overridable method for printing the form for page content editing
2170 * By default this simply outputs wpTextbox1
2171 * Subclasses can override this to provide a custom UI for editing;
2172 * be it a form, or simply wpTextbox1 with a modified content that will be
2173 * reverse modified when extracted from the post data.
2174 * Note that this is basically the inverse for importContentFormData
2176 protected function showContentForm() {
2177 $this->showTextbox1();
2181 * Method to output wpTextbox1
2182 * The $textoverride method can be used by subclasses overriding showContentForm
2183 * to pass back to this method.
2185 * @param $customAttribs An array of html attributes to use in the textarea
2186 * @param $textoverride String: optional text to override $this->textarea1 with
2188 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2189 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2190 $attribs = array( 'style' => 'display:none;' );
2192 $classes = array(); // Textarea CSS
2193 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2194 # Is the title semi-protected?
2195 if ( $this->mTitle
->isSemiProtected() ) {
2196 $classes[] = 'mw-textarea-sprotected';
2198 # Then it must be protected based on static groups (regular)
2199 $classes[] = 'mw-textarea-protected';
2201 # Is the title cascade-protected?
2202 if ( $this->mTitle
->isCascadeProtected() ) {
2203 $classes[] = 'mw-textarea-cprotected';
2207 $attribs = array( 'tabindex' => 1 );
2209 if ( is_array( $customAttribs ) ) {
2210 $attribs +
= $customAttribs;
2213 if ( count( $classes ) ) {
2214 if ( isset( $attribs['class'] ) ) {
2215 $classes[] = $attribs['class'];
2217 $attribs['class'] = implode( ' ', $classes );
2221 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2224 protected function showTextbox2() {
2225 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2228 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2229 global $wgOut, $wgUser;
2231 $wikitext = $this->safeUnicodeOutput( $content );
2232 if ( strval($wikitext) !== '' ) {
2233 // Ensure there's a newline at the end, otherwise adding lines
2235 // But don't add a newline if the ext is empty, or Firefox in XHTML
2236 // mode will show an extra newline. A bit annoying.
2240 $attribs = $customAttribs +
array(
2243 'cols' => $wgUser->getIntOption( 'cols' ),
2244 'rows' => $wgUser->getIntOption( 'rows' ),
2245 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2248 $pageLang = $this->mTitle
->getPageLanguage();
2249 $attribs['lang'] = $pageLang->getCode();
2250 $attribs['dir'] = $pageLang->getDir();
2252 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2255 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2259 $classes[] = 'ontop';
2261 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2263 if ( $this->formtype
!= 'preview' )
2264 $attribs['style'] = 'display: none;';
2266 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2268 if ( $this->formtype
== 'preview' ) {
2269 $this->showPreview( $previewOutput );
2272 $wgOut->addHTML( '</div>' );
2274 if ( $this->formtype
== 'diff') {
2280 * Append preview output to $wgOut.
2281 * Includes category rendering if this is a category page.
2283 * @param $text String: the HTML to be output for the preview.
2285 protected function showPreview( $text ) {
2287 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2288 $this->mArticle
->openShowCategory();
2290 # This hook seems slightly odd here, but makes things more
2291 # consistent for extensions.
2292 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
2293 $wgOut->addHTML( $text );
2294 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2295 $this->mArticle
->closeShowCategory();
2300 * Get a diff between the current contents of the edit box and the
2301 * version of the page we're editing from.
2303 * If this is a section edit, we'll replace the section as for final
2304 * save and then make a comparison.
2306 function showDiff() {
2307 global $wgUser, $wgContLang, $wgParser, $wgOut;
2309 $oldtext = $this->getOriginalContent();
2310 $newtext = $this->mArticle
->replaceSection(
2311 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2313 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2315 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2316 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle
, $wgUser, $popts );
2318 if ( $oldtext !== false ||
$newtext != '' ) {
2319 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2320 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2322 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2323 $de->setText( $oldtext, $newtext );
2324 $difftext = $de->getDiff( $oldtitle, $newtitle );
2325 $de->showDiffStyle();
2330 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2334 * Give a chance for site and per-namespace customizations of
2335 * terms of service summary link that might exist separately
2336 * from the copyright notice.
2338 * This will display between the save button and the edit tools,
2339 * so should remain short!
2341 protected function showTosSummary() {
2342 $msg = 'editpage-tos-summary';
2343 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2344 if( !wfMessage( $msg )->isDisabled() ) {
2346 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2347 $wgOut->addWikiMsg( $msg );
2348 $wgOut->addHTML( '</div>' );
2352 protected function showEditTools() {
2354 $wgOut->addHTML( '<div class="mw-editTools">' .
2355 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2359 protected function getCopywarn() {
2360 global $wgRightsText;
2361 if ( $wgRightsText ) {
2362 $copywarnMsg = array( 'copyrightwarning',
2363 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2366 $copywarnMsg = array( 'copyrightwarning2',
2367 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2369 // Allow for site and per-namespace customization of contribution/copyright notice.
2370 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2372 return "<div id=\"editpage-copywarn\">\n" .
2373 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
2376 protected function showStandardInputs( &$tabindex = 2 ) {
2378 $wgOut->addHTML( "<div class='editOptions'>\n" );
2380 if ( $this->section
!= 'new' ) {
2381 $this->showSummaryInput( false, $this->summary
);
2382 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2385 $checkboxes = $this->getCheckboxes( $tabindex,
2386 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2387 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2388 $wgOut->addHTML( "<div class='editButtons'>\n" );
2389 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2391 $cancel = $this->getCancelLink();
2392 if ( $cancel !== '' ) {
2393 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2395 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2396 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
2397 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
2398 htmlspecialchars( wfMsg( 'newwindow' ) );
2399 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2400 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2404 * Show an edit conflict. textbox1 is already shown in showEditForm().
2405 * If you want to use another entry point to this function, be careful.
2407 protected function showConflict() {
2410 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2411 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2413 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2414 $de->setText( $this->textbox2
, $this->textbox1
);
2415 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2417 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2418 $this->showTextbox2();
2425 public function getCancelLink() {
2426 $cancelParams = array();
2427 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2428 $cancelParams['oldid'] = $this->oldid
;
2431 return Linker
::linkKnown(
2432 $this->getContextTitle(),
2433 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2434 array( 'id' => 'mw-editform-cancel' ),
2440 * Returns the URL to use in the form's action attribute.
2441 * This is used by EditPage subclasses when simply customizing the action
2442 * variable in the constructor is not enough. This can be used when the
2443 * EditPage lives inside of a Special page rather than a custom page action.
2445 * @param $title Title object for which is being edited (where we go to for &action= links)
2448 protected function getActionURL( Title
$title ) {
2449 return $title->getLocalURL( array( 'action' => $this->action
) );
2453 * Check if a page was deleted while the user was editing it, before submit.
2454 * Note that we rely on the logging table, which hasn't been always there,
2455 * but that doesn't matter, because this only applies to brand new
2458 protected function wasDeletedSinceLastEdit() {
2459 if ( $this->deletedSinceEdit
!== null ) {
2460 return $this->deletedSinceEdit
;
2463 $this->deletedSinceEdit
= false;
2465 if ( $this->mTitle
->isDeletedQuick() ) {
2466 $this->lastDelete
= $this->getLastDelete();
2467 if ( $this->lastDelete
) {
2468 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2469 if ( $deleteTime > $this->starttime
) {
2470 $this->deletedSinceEdit
= true;
2475 return $this->deletedSinceEdit
;
2478 protected function getLastDelete() {
2479 $dbr = wfGetDB( DB_SLAVE
);
2480 $data = $dbr->selectRow(
2481 array( 'logging', 'user' ),
2492 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2493 'log_title' => $this->mTitle
->getDBkey(),
2494 'log_type' => 'delete',
2495 'log_action' => 'delete',
2496 'user_id=log_user' ),
2498 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2500 // Quick paranoid permission checks...
2501 if( is_object( $data ) ) {
2502 if( $data->log_deleted
& LogPage
::DELETED_USER
)
2503 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2504 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2505 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2511 * Get the rendered text for previewing.
2514 function getPreviewText() {
2515 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2517 wfProfileIn( __METHOD__
);
2519 if ( $wgRawHtml && !$this->mTokenOk
) {
2520 // Could be an offsite preview attempt. This is very unsafe if
2521 // HTML is enabled, as it could be an attack.
2523 if ( $this->textbox1
!== '' ) {
2524 // Do not put big scary notice, if previewing the empty
2525 // string, which happens when you initially edit
2526 // a category page, due to automatic preview-on-open.
2527 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2528 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2530 wfProfileOut( __METHOD__
);
2534 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2535 if ( $this->mTokenOkExceptSuffix
) {
2536 $note = wfMsg( 'token_suffix_mismatch' );
2538 $note = wfMsg( 'session_fail_preview' );
2540 } elseif ( $this->incompleteForm
) {
2541 $note = wfMsg( 'edit_form_incomplete' );
2543 $note = wfMsg( 'previewnote' );
2546 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2547 $parserOptions->setEditSection( false );
2548 $parserOptions->setTidy( true );
2549 $parserOptions->setIsPreview( true );
2550 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2552 # don't parse non-wikitext pages, show message about preview
2553 # 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?
2555 if ( $this->isCssJsSubpage ||
!$this->mTitle
->isWikitextPage() ) {
2556 if( $this->mTitle
->isCssJsSubpage() ) {
2558 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2564 # Used messages to make sure grep find them:
2565 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2567 if (preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2568 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2569 $class = "mw-code mw-css";
2570 } elseif (preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2571 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2572 $class = "mw-code mw-js";
2574 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2578 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2579 $previewHTML = $parserOutput->mText
;
2580 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2582 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2584 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2586 $toparse = $this->textbox1
;
2588 # If we're adding a comment, we need to show the
2589 # summary as the headline
2590 if ( $this->section
== "new" && $this->summary
!= "" ) {
2591 $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $toparse;
2594 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2596 $parserOptions->enableLimitReport();
2598 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle
, $wgUser, $parserOptions );
2599 $parserOutput = $wgParser->parse( $toparse, $this->mTitle
, $parserOptions );
2601 $previewHTML = $parserOutput->getText();
2602 $this->mParserOutput
= $parserOutput;
2603 $wgOut->addParserOutputNoText( $parserOutput );
2605 if ( count( $parserOutput->getWarnings() ) ) {
2606 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2611 if( $this->isConflict
) {
2612 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2614 $conflict = '<hr />';
2617 $previewhead = "<div class='previewnote'>\n" .
2618 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2619 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2621 $pageLang = $this->mTitle
->getPageLanguage();
2622 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2623 'class' => 'mw-content-'.$pageLang->getDir() );
2624 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2626 wfProfileOut( __METHOD__
);
2627 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2633 function getTemplates() {
2634 if ( $this->preview ||
$this->section
!= '' ) {
2635 $templates = array();
2636 if ( !isset( $this->mParserOutput
) ) {
2639 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
2640 foreach( array_keys( $template ) as $dbk ) {
2641 $templates[] = Title
::makeTitle($ns, $dbk);
2646 return $this->mTitle
->getTemplateLinksFrom();
2651 * Shows a bulletin board style toolbar for common editing functions.
2652 * It can be disabled in the user preferences.
2653 * The necessary JavaScript code can be found in skins/common/edit.js.
2657 static function getEditToolbar() {
2658 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2659 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2661 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2664 * $toolarray is an array of arrays each of which includes the
2665 * filename of the button image (without path), the opening
2666 * tag, the closing tag, optionally a sample text that is
2667 * inserted between the two when no selection is highlighted
2668 * and. The tip text is shown when the user moves the mouse
2671 * Also here: accesskeys (key), which are not used yet until
2672 * someone can figure out a way to make them work in
2673 * IE. However, we should make sure these keys are not defined
2678 'image' => $wgLang->getImageFile( 'button-bold' ),
2679 'id' => 'mw-editbutton-bold',
2681 'close' => '\'\'\'',
2682 'sample' => wfMsg( 'bold_sample' ),
2683 'tip' => wfMsg( 'bold_tip' ),
2687 'image' => $wgLang->getImageFile( 'button-italic' ),
2688 'id' => 'mw-editbutton-italic',
2691 'sample' => wfMsg( 'italic_sample' ),
2692 'tip' => wfMsg( 'italic_tip' ),
2696 'image' => $wgLang->getImageFile( 'button-link' ),
2697 'id' => 'mw-editbutton-link',
2700 'sample' => wfMsg( 'link_sample' ),
2701 'tip' => wfMsg( 'link_tip' ),
2705 'image' => $wgLang->getImageFile( 'button-extlink' ),
2706 'id' => 'mw-editbutton-extlink',
2709 'sample' => wfMsg( 'extlink_sample' ),
2710 'tip' => wfMsg( 'extlink_tip' ),
2714 'image' => $wgLang->getImageFile( 'button-headline' ),
2715 'id' => 'mw-editbutton-headline',
2718 'sample' => wfMsg( 'headline_sample' ),
2719 'tip' => wfMsg( 'headline_tip' ),
2722 $imagesAvailable ?
array(
2723 'image' => $wgLang->getImageFile( 'button-image' ),
2724 'id' => 'mw-editbutton-image',
2725 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2727 'sample' => wfMsg( 'image_sample' ),
2728 'tip' => wfMsg( 'image_tip' ),
2731 $imagesAvailable ?
array(
2732 'image' => $wgLang->getImageFile( 'button-media' ),
2733 'id' => 'mw-editbutton-media',
2734 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2736 'sample' => wfMsg( 'media_sample' ),
2737 'tip' => wfMsg( 'media_tip' ),
2741 'image' => $wgLang->getImageFile( 'button-math' ),
2742 'id' => 'mw-editbutton-math',
2744 'close' => "</math>",
2745 'sample' => wfMsg( 'math_sample' ),
2746 'tip' => wfMsg( 'math_tip' ),
2750 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2751 'id' => 'mw-editbutton-nowiki',
2752 'open' => "<nowiki>",
2753 'close' => "</nowiki>",
2754 'sample' => wfMsg( 'nowiki_sample' ),
2755 'tip' => wfMsg( 'nowiki_tip' ),
2759 'image' => $wgLang->getImageFile( 'button-sig' ),
2760 'id' => 'mw-editbutton-signature',
2764 'tip' => wfMsg( 'sig_tip' ),
2768 'image' => $wgLang->getImageFile( 'button-hr' ),
2769 'id' => 'mw-editbutton-hr',
2770 'open' => "\n----\n",
2773 'tip' => wfMsg( 'hr_tip' ),
2778 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
2779 foreach ( $toolarray as $tool ) {
2785 $image = $wgStylePath . '/common/images/' . $tool['image'],
2786 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2787 // Older browsers show a "speedtip" type message only for ALT.
2788 // Ideally these should be different, realistically they
2789 // probably don't need to be.
2790 $tip = $tool['tip'],
2791 $open = $tool['open'],
2792 $close = $tool['close'],
2793 $sample = $tool['sample'],
2794 $cssId = $tool['id'],
2797 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2800 // This used to be called on DOMReady from mediawiki.action.edit, which
2801 // ended up causing race conditions with the setup code above.
2803 "// Create button bar\n" .
2804 "$(function() { mw.toolbar.init(); } );\n";
2807 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2809 $toolbar = '<div id="toolbar"></div>';
2811 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2817 * Returns an array of html code of the following checkboxes:
2820 * @param $tabindex Current tabindex
2821 * @param $checked Array of checkbox => bool, where bool indicates the checked
2822 * status of the checkbox
2826 public function getCheckboxes( &$tabindex, $checked ) {
2829 $checkboxes = array();
2831 // don't show the minor edit checkbox if it's a new page or section
2832 if ( !$this->isNew
) {
2833 $checkboxes['minor'] = '';
2834 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2835 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2837 'tabindex' => ++
$tabindex,
2838 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2839 'id' => 'wpMinoredit',
2841 $checkboxes['minor'] =
2842 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2843 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2844 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2845 ">{$minorLabel}</label>";
2849 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2850 $checkboxes['watch'] = '';
2851 if ( $wgUser->isLoggedIn() ) {
2853 'tabindex' => ++
$tabindex,
2854 'accesskey' => wfMsg( 'accesskey-watch' ),
2855 'id' => 'wpWatchthis',
2857 $checkboxes['watch'] =
2858 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2859 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2860 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2861 ">{$watchLabel}</label>";
2863 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2868 * Returns an array of html code of the following buttons:
2869 * save, diff, preview and live
2871 * @param $tabindex Current tabindex
2875 public function getEditButtons( &$tabindex ) {
2882 'tabindex' => ++
$tabindex,
2883 'value' => wfMsg( 'savearticle' ),
2884 'accesskey' => wfMsg( 'accesskey-save' ),
2885 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2887 $buttons['save'] = Xml
::element('input', $temp, '');
2889 ++
$tabindex; // use the same for preview and live preview
2891 'id' => 'wpPreview',
2892 'name' => 'wpPreview',
2894 'tabindex' => $tabindex,
2895 'value' => wfMsg( 'showpreview' ),
2896 'accesskey' => wfMsg( 'accesskey-preview' ),
2897 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2899 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
2900 $buttons['live'] = '';
2906 'tabindex' => ++
$tabindex,
2907 'value' => wfMsg( 'showdiff' ),
2908 'accesskey' => wfMsg( 'accesskey-diff' ),
2909 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2911 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
2913 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2918 * Output preview text only. This can be sucked into the edit page
2919 * via JavaScript, and saves the server time rendering the skin as
2920 * well as theoretically being more robust on the client (doesn't
2921 * disturb the edit box's undo history, won't eat your text on
2924 * @todo This doesn't include category or interlanguage links.
2925 * Would need to enhance it a bit, <s>maybe wrap them in XML
2926 * or something...</s> that might also require more skin
2927 * initialization, so check whether that's a problem.
2929 function livePreview() {
2932 header( 'Content-type: text/xml; charset=utf-8' );
2933 header( 'Cache-control: no-cache' );
2935 $previewText = $this->getPreviewText();
2936 #$categories = $skin->getCategoryLinks();
2939 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2940 Xml
::tags( 'livepreview', null,
2941 Xml
::element( 'preview', null, $previewText )
2942 #. Xml::element( 'category', null, $categories )
2948 * Call the stock "user is blocked" page
2950 * @deprecated in 1.19; throw an exception directly instead
2952 function blockedPage() {
2953 wfDeprecated( __METHOD__
, '1.19' );
2956 throw new UserBlockedError( $wgUser->mBlock
);
2960 * Produce the stock "please login to edit pages" page
2962 * @deprecated in 1.19; throw an exception directly instead
2964 function userNotLoggedInPage() {
2965 wfDeprecated( __METHOD__
, '1.19' );
2966 throw new PermissionsError( 'edit' );
2970 * Show an error page saying to the user that he has insufficient permissions
2971 * to create a new page
2973 * @deprecated in 1.19; throw an exception directly instead
2975 function noCreatePermission() {
2976 wfDeprecated( __METHOD__
, '1.19' );
2977 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
2978 throw new PermissionsError( $permission );
2982 * Creates a basic error page which informs the user that
2983 * they have attempted to edit a nonexistent section.
2985 function noSuchSectionPage() {
2988 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
2990 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
2991 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2992 $wgOut->addHTML( $res );
2994 $wgOut->returnToMain( false, $this->mTitle
);
2998 * Produce the stock "your edit contains spam" page
3000 * @param $match Text which triggered one or more filters
3001 * @deprecated since 1.17 Use method spamPageWithContent() instead
3003 static function spamPage( $match = false ) {
3004 wfDeprecated( __METHOD__
, '1.17' );
3006 global $wgOut, $wgTitle;
3008 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3010 $wgOut->addHTML( '<div id="spamprotected">' );
3011 $wgOut->addWikiMsg( 'spamprotectiontext' );
3013 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3015 $wgOut->addHTML( '</div>' );
3017 $wgOut->returnToMain( false, $wgTitle );
3021 * Show "your edit contains spam" page with your diff and text
3023 * @param $match Text which triggered one or more filters
3025 public function spamPageWithContent( $match = false ) {
3027 $this->textbox2
= $this->textbox1
;
3029 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3031 $wgOut->addHTML( '<div id="spamprotected">' );
3032 $wgOut->addWikiMsg( 'spamprotectiontext' );
3034 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3036 $wgOut->addHTML( '</div>' );
3038 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3039 $de = new DifferenceEngine( $this->mArticle
->getContext() );
3040 $de->setText( $this->getCurrentText(), $this->textbox2
);
3041 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
3043 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3044 $this->showTextbox2();
3046 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3050 * Format an anchor fragment as it would appear for a given section name
3051 * @param $text String
3055 function sectionAnchor( $text ) {
3057 return $wgParser->guessSectionNameFromWikiText( $text );
3061 * Check if the browser is on a blacklist of user-agents known to
3062 * mangle UTF-8 data on form submission. Returns true if Unicode
3063 * should make it through, false if it's known to be a problem.
3067 function checkUnicodeCompliantBrowser() {
3068 global $wgBrowserBlackList;
3069 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
3070 // No User-Agent header sent? Trust it by default...
3073 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
3074 foreach ( $wgBrowserBlackList as $browser ) {
3075 if ( preg_match($browser, $currentbrowser) ) {
3083 * Filter an input field through a Unicode de-armoring process if it
3084 * came from an old browser with known broken Unicode editing issues.
3086 * @param $request WebRequest
3087 * @param $field String
3091 function safeUnicodeInput( $request, $field ) {
3092 $text = rtrim( $request->getText( $field ) );
3093 return $request->getBool( 'safemode' )
3094 ?
$this->unmakesafe( $text )
3099 * @param $request WebRequest
3100 * @param $text string
3103 function safeUnicodeText( $request, $text ) {
3104 $text = rtrim( $text );
3105 return $request->getBool( 'safemode' )
3106 ?
$this->unmakesafe( $text )
3111 * Filter an output field through a Unicode armoring process if it is
3112 * going to an old browser with known broken Unicode editing issues.
3114 * @param $text String
3118 function safeUnicodeOutput( $text ) {
3120 $codedText = $wgContLang->recodeForEdit( $text );
3121 return $this->checkUnicodeCompliantBrowser()
3123 : $this->makesafe( $codedText );
3127 * A number of web browsers are known to corrupt non-ASCII characters
3128 * in a UTF-8 text editing environment. To protect against this,
3129 * detected browsers will be served an armored version of the text,
3130 * with non-ASCII chars converted to numeric HTML character references.
3132 * Preexisting such character references will have a 0 added to them
3133 * to ensure that round-trips do not alter the original data.
3135 * @param $invalue String
3139 function makesafe( $invalue ) {
3140 // Armor existing references for reversability.
3141 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3146 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3147 $bytevalue = ord( $invalue[$i] );
3148 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
3149 $result .= chr( $bytevalue );
3151 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
3152 $working = $working << 6;
3153 $working +
= ($bytevalue & 0x3F);
3155 if ( $bytesleft <= 0 ) {
3156 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3158 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
3159 $working = $bytevalue & 0x1F;
3161 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
3162 $working = $bytevalue & 0x0F;
3164 } else { //1111 0xxx
3165 $working = $bytevalue & 0x07;
3173 * Reverse the previously applied transliteration of non-ASCII characters
3174 * back to UTF-8. Used to protect data from corruption by broken web browsers
3175 * as listed in $wgBrowserBlackList.
3177 * @param $invalue String
3181 function unmakesafe( $invalue ) {
3183 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3184 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+
3] != '0' ) ) {
3188 $hexstring .= $invalue[$i];
3190 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3192 // Do some sanity checks. These aren't needed for reversability,
3193 // but should help keep the breakage down if the editor
3194 // breaks one of the entities whilst editing.
3195 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
3196 $codepoint = hexdec($hexstring);
3197 $result .= codepointToUtf8( $codepoint );
3199 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3202 $result .= substr( $invalue, $i, 1 );
3205 // reverse the transform that we made for reversability reasons.
3206 return strtr( $result, array( "�" => "&#x" ) );