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.
23 const AS_SUCCESS_UPDATE
= 200;
24 const AS_SUCCESS_NEW_ARTICLE
= 201;
25 const AS_HOOK_ERROR
= 210;
26 const AS_FILTERING
= 211;
27 const AS_HOOK_ERROR_EXPECTED
= 212;
28 const AS_BLOCKED_PAGE_FOR_USER
= 215;
29 const AS_CONTENT_TOO_BIG
= 216;
30 const AS_USER_CANNOT_EDIT
= 217;
31 const AS_READ_ONLY_PAGE_ANON
= 218;
32 const AS_READ_ONLY_PAGE_LOGGED
= 219;
33 const AS_READ_ONLY_PAGE
= 220;
34 const AS_RATE_LIMITED
= 221;
35 const AS_ARTICLE_WAS_DELETED
= 222;
36 const AS_NO_CREATE_PERMISSION
= 223;
37 const AS_BLANK_ARTICLE
= 224;
38 const AS_CONFLICT_DETECTED
= 225;
39 const AS_SUMMARY_NEEDED
= 226;
40 const AS_TEXTBOX_EMPTY
= 228;
41 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
44 const AS_SPAM_ERROR
= 232;
45 const AS_IMAGE_REDIRECT_ANON
= 233;
46 const AS_IMAGE_REDIRECT_LOGGED
= 234;
57 private $mContextTitle = null;
58 var $action = 'submit';
59 var $isConflict = false;
60 var $isCssJsSubpage = false;
61 var $isCssSubpage = false;
62 var $isJsSubpage = false;
63 var $isWrongCaseCssJsPage = false;
64 var $isNew = false; // new page or new section
65 var $deletedSinceEdit;
69 var $mTokenOk = false;
70 var $mTokenOkExceptSuffix = false;
71 var $mTriedSave = false;
72 var $incompleteForm = false;
74 var $kblength = false;
75 var $missingComment = false;
76 var $missingSummary = false;
77 var $allowBlankSummary = false;
80 #var $mPreviewTemplates;
87 var $mBaseRevision = false;
88 var $mShowSummaryField = true;
91 var $save = false, $preview = false, $diff = false;
92 var $minoredit = false, $watchthis = false, $recreate = false;
93 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
94 var $edittime = '', $section = '', $starttime = '';
95 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
97 # Placeholders for text injection by hooks (must be HTML)
98 # extensions should take care to _append_ to the present value
99 public $editFormPageTop = ''; // Before even the preview
100 public $editFormTextTop = '';
101 public $editFormTextBeforeContent = '';
102 public $editFormTextAfterWarn = '';
103 public $editFormTextAfterTools = '';
104 public $editFormTextBottom = '';
105 public $editFormTextAfterContent = '';
106 public $previewTextAfterContent = '';
107 public $mPreloadText = '';
109 /* $didSave should be set to true whenever an article was succesfully altered. */
110 public $didSave = false;
111 public $undidRev = 0;
113 public $suppressIntro = false;
117 * @param $article Article
119 public function __construct( $article ) {
120 $this->mArticle
= $article;
121 $this->mTitle
= $article->getTitle();
127 public function getArticle() {
128 return $this->mArticle
;
135 public function getTitle() {
136 return $this->mTitle
;
140 * Set the context Title object
142 * @param $title Title object or null
144 public function setContextTitle( $title ) {
145 $this->mContextTitle
= $title;
149 * Get the context title object.
150 * If not set, $wgTitle will be returned. This behavior might changed in
151 * the future to return $this->mTitle instead.
153 * @return Title object
155 public function getContextTitle() {
156 if ( is_null( $this->mContextTitle
) ) {
160 return $this->mContextTitle
;
169 * This is the function that gets called for "action=edit". It
170 * sets up various member variables, then passes execution to
171 * another function, usually showEditForm()
173 * The edit form is self-submitting, so that when things like
174 * preview and edit conflicts occur, we get the same form back
175 * with the extra stuff added. Only when the final submission
176 * is made and all is well do we actually save and redirect to
177 * the newly-edited page.
180 global $wgOut, $wgRequest, $wgUser;
181 // Allow extensions to modify/prevent this form or submission
182 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
186 wfProfileIn( __METHOD__
);
187 wfDebug( __METHOD__
.": enter\n" );
189 // If they used redlink=1 and the page exists, redirect to the main article
190 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
191 $wgOut->redirect( $this->mTitle
->getFullURL() );
192 wfProfileOut( __METHOD__
);
196 $this->importFormData( $wgRequest );
197 $this->firsttime
= false;
200 $this->livePreview();
201 wfProfileOut( __METHOD__
);
205 if ( wfReadOnly() && $this->save
) {
208 $this->preview
= true;
212 $this->formtype
= 'save';
213 } elseif ( $this->preview
) {
214 $this->formtype
= 'preview';
215 } elseif ( $this->diff
) {
216 $this->formtype
= 'diff';
217 } else { # First time through
218 $this->firsttime
= true;
219 if ( $this->previewOnOpen() ) {
220 $this->formtype
= 'preview';
222 $this->formtype
= 'initial';
226 $permErrors = $this->getEditPermissionErrors();
228 wfDebug( __METHOD__
. ": User can't edit\n" );
229 // Auto-block user's IP if the account was "hard" blocked
230 $wgUser->spreadAnyEditBlock();
232 $this->displayPermissionsError( $permErrors );
234 wfProfileOut( __METHOD__
);
238 $wgOut->addModules( array( 'mediawiki.action.edit' ) );
240 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
241 $wgOut->addModules( 'mediawiki.legacy.preview' );
243 // Bug #19334: textarea jumps when editing articles in IE8
244 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
246 wfProfileIn( __METHOD__
."-business-end" );
248 $this->isConflict
= false;
249 // css / js subpages of user pages get a special treatment
250 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
251 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
252 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
253 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
254 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
256 # Show applicable editing introductions
257 if ( $this->formtype
== 'initial' ||
$this->firsttime
)
260 if ( $this->mTitle
->isTalkPage() ) {
261 $wgOut->addWikiMsg( 'talkpagetext' );
264 # Optional notices on a per-namespace and per-page basis
265 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
266 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
267 if ( $editnotice_ns_message->exists() ) {
268 $wgOut->addWikiText( $editnotice_ns_message->plain() );
270 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
271 $parts = explode( '/', $this->mTitle
->getDBkey() );
272 $editnotice_base = $editnotice_ns;
273 while ( count( $parts ) > 0 ) {
274 $editnotice_base .= '-'.array_shift( $parts );
275 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
276 if ( $editnotice_base_msg->exists() ) {
277 $wgOut->addWikiText( $editnotice_base_msg->plain() );
281 # Even if there are no subpages in namespace, we still don't want / in MW ns.
282 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
283 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
284 if ( $editnoticeMsg->exists() ) {
285 $wgOut->addWikiText( $editnoticeMsg->plain() );
289 # Attempt submission here. This will check for edit conflicts,
290 # and redundantly check for locked database, blocked IPs, etc.
291 # that edit() already checked just in case someone tries to sneak
292 # in the back door with a hand-edited submission URL.
294 if ( 'save' == $this->formtype
) {
295 if ( !$this->attemptSave() ) {
296 wfProfileOut( __METHOD__
."-business-end" );
297 wfProfileOut( __METHOD__
);
302 # First time through: get contents, set time for conflict
304 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
305 if ( $this->initialiseForm() === false ) {
306 $this->noSuchSectionPage();
307 wfProfileOut( __METHOD__
."-business-end" );
308 wfProfileOut( __METHOD__
);
311 if ( !$this->mTitle
->getArticleId() )
312 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
314 wfRunHooks( 'EditFormInitialText', array( $this ) );
317 $this->showEditForm();
318 wfProfileOut( __METHOD__
."-business-end" );
319 wfProfileOut( __METHOD__
);
325 protected function getEditPermissionErrors() {
327 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
328 # Can this title be created?
329 if ( !$this->mTitle
->exists() ) {
330 $permErrors = array_merge( $permErrors,
331 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
333 # Ignore some permissions errors when a user is just previewing/viewing diffs
335 foreach( $permErrors as $error ) {
336 if ( ( $this->preview ||
$this->diff
) &&
337 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
342 $permErrors = wfArrayDiff2( $permErrors, $remove );
347 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
348 * but with the following differences:
349 * - If redlink=1, the user will be redirect to the page
350 * - If there is content to display or the error occurs while either saving,
351 * previewing or showing the difference, it will be a
352 * "View source for ..." page displaying the source code after the error message.
355 * @param $permErrors Array of permissions errors, as returned by
356 * Title::getUserPermissionsErrors().
358 protected function displayPermissionsError( array $permErrors ) {
359 global $wgRequest, $wgOut;
361 if ( $wgRequest->getBool( 'redlink' ) ) {
362 // The edit page was reached via a red link.
363 // Redirect to the article page and let them click the edit tab if
364 // they really want a permission error.
365 $wgOut->redirect( $this->mTitle
->getFullUrl() );
369 $content = $this->getContent();
371 # Use the normal message if there's nothing to display
372 if ( $this->firsttime
&& $content === '' ) {
373 $action = $this->mTitle
->exists() ?
'edit' :
374 ( $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
375 throw new PermissionsError( $action, $permErrors );
378 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
379 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
380 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
381 $wgOut->addHTML( "<hr />\n" );
383 # If the user made changes, preserve them when showing the markup
384 # (This happens when a user is blocked during edit, for instance)
385 if ( !$this->firsttime
) {
386 $content = $this->textbox1
;
387 $wgOut->addWikiMsg( 'viewyourtext' );
389 $wgOut->addWikiMsg( 'viewsourcetext' );
392 $this->showTextbox( $content, 'wpTextbox1', array( 'readonly' ) );
394 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
395 Linker
::formatTemplates( $this->getTemplates() ) ) );
397 if ( $this->mTitle
->exists() ) {
398 $wgOut->returnToMain( null, $this->mTitle
);
403 * Show a read-only error
404 * Parameters are the same as OutputPage:readOnlyPage()
405 * Redirect to the article page if redlink=1
406 * @deprecated in 1.19; use displayPermissionsError() instead
408 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
409 global $wgRequest, $wgOut;
410 if ( $wgRequest->getBool( 'redlink' ) ) {
411 // The edit page was reached via a red link.
412 // Redirect to the article page and let them click the edit tab if
413 // they really want a permission error.
414 $wgOut->redirect( $this->mTitle
->getFullUrl() );
416 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
421 * Should we show a preview when the edit form is first shown?
425 protected function previewOnOpen() {
426 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
427 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
428 // Explicit override from request
430 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
431 // Explicit override from request
433 } elseif ( $this->section
== 'new' ) {
434 // Nothing *to* preview for new sections
436 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
437 // Standard preference behaviour
439 } elseif ( !$this->mTitle
->exists() &&
440 isset($wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]) &&
441 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
443 // Categories are special
451 * Checks whether the user entered a skin name in uppercase,
452 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
456 protected function isWrongCaseCssJsPage() {
457 if( $this->mTitle
->isCssJsSubpage() ) {
458 $name = $this->mTitle
->getSkinFromCssJsSubpage();
459 $skins = array_merge(
460 array_keys( Skin
::getSkinNames() ),
463 return !in_array( $name, $skins )
464 && in_array( strtolower( $name ), $skins );
471 * Does this EditPage class support section editing?
472 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
476 protected function isSectionEditSupported() {
482 * @param $request WebRequest
484 function importFormData( &$request ) {
485 global $wgLang, $wgUser;
487 wfProfileIn( __METHOD__
);
489 # Section edit can come from either the form or a link
490 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
492 if ( $request->wasPosted() ) {
493 # These fields need to be checked for encoding.
494 # Also remove trailing whitespace, but don't remove _initial_
495 # whitespace from the text boxes. This may be significant formatting.
496 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
497 if ( !$request->getCheck('wpTextbox2') ) {
498 // Skip this if wpTextbox2 has input, it indicates that we came
499 // from a conflict page with raw page text, not a custom form
500 // modified by subclasses
501 wfProfileIn( get_class($this)."::importContentFormData" );
502 $textbox1 = $this->importContentFormData( $request );
503 if ( isset($textbox1) )
504 $this->textbox1
= $textbox1;
505 wfProfileOut( get_class($this)."::importContentFormData" );
508 # Truncate for whole multibyte characters. +5 bytes for ellipsis
509 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
511 # Remove extra headings from summaries and new sections.
512 $this->summary
= preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
514 $this->edittime
= $request->getVal( 'wpEdittime' );
515 $this->starttime
= $request->getVal( 'wpStarttime' );
517 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
519 if ($this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null) {
520 // wpTextbox1 field is missing, possibly due to being "too big"
521 // according to some filter rules such as Suhosin's setting for
522 // suhosin.request.max_value_length (d'oh)
523 $this->incompleteForm
= true;
525 // edittime should be one of our last fields; if it's missing,
526 // the submission probably broke somewhere in the middle.
527 $this->incompleteForm
= is_null( $this->edittime
);
529 if ( $this->incompleteForm
) {
530 # If the form is incomplete, force to preview.
531 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
532 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
533 $this->preview
= true;
535 /* Fallback for live preview */
536 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
537 $this->diff
= $request->getCheck( 'wpDiff' );
539 // Remember whether a save was requested, so we can indicate
540 // if we forced preview due to session failure.
541 $this->mTriedSave
= !$this->preview
;
543 if ( $this->tokenOk( $request ) ) {
544 # Some browsers will not report any submit button
545 # if the user hits enter in the comment box.
546 # The unmarked state will be assumed to be a save,
547 # if the form seems otherwise complete.
548 wfDebug( __METHOD__
. ": Passed token check.\n" );
549 } elseif ( $this->diff
) {
550 # Failed token check, but only requested "Show Changes".
551 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
553 # Page might be a hack attempt posted from
554 # an external site. Preview instead of saving.
555 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
556 $this->preview
= true;
559 $this->save
= !$this->preview
&& !$this->diff
;
560 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
561 $this->edittime
= null;
564 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
565 $this->starttime
= null;
568 $this->recreate
= $request->getCheck( 'wpRecreate' );
570 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
571 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
573 # Don't force edit summaries when a user is editing their own user or talk page
574 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
575 $this->mTitle
->getText() == $wgUser->getName() )
577 $this->allowBlankSummary
= true;
579 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
582 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
584 # Not a posted form? Start with nothing.
585 wfDebug( __METHOD__
. ": Not a posted form.\n" );
586 $this->textbox1
= '';
588 $this->edittime
= '';
589 $this->starttime
= wfTimestampNow();
591 $this->preview
= false;
594 $this->minoredit
= false;
595 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
596 $this->recreate
= false;
598 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
599 $this->summary
= $request->getVal( 'preloadtitle' );
601 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
602 $this->summary
= $request->getText( 'summary' );
605 if ( $request->getVal( 'minor' ) ) {
606 $this->minoredit
= true;
610 $this->bot
= $request->getBool( 'bot', true );
611 $this->nosummary
= $request->getBool( 'nosummary' );
613 // @todo FIXME: Unused variable?
614 $this->oldid
= $request->getInt( 'oldid' );
616 $this->live
= $request->getCheck( 'live' );
617 $this->editintro
= $request->getText( 'editintro',
618 // Custom edit intro for new sections
619 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
621 // Allow extensions to modify form data
622 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
624 wfProfileOut( __METHOD__
);
628 * Subpage overridable method for extracting the page content data from the
629 * posted form to be placed in $this->textbox1, if using customized input
630 * this method should be overrided and return the page text that will be used
631 * for saving, preview parsing and so on...
633 * @param $request WebRequest
635 protected function importContentFormData( &$request ) {
636 return; // Don't do anything, EditPage already extracted wpTextbox1
640 * Initialise form fields in the object
641 * Called on the first invocation, e.g. when a user clicks an edit link
642 * @return bool -- if the requested section is valid
644 function initialiseForm() {
646 $this->edittime
= $this->mArticle
->getTimestamp();
647 $this->textbox1
= $this->getContent( false );
648 // activate checkboxes if user wants them to be always active
649 # Sort out the "watch" checkbox
650 if ( $wgUser->getOption( 'watchdefault' ) ) {
652 $this->watchthis
= true;
653 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
655 $this->watchthis
= true;
656 } elseif ( $this->mTitle
->userIsWatching() ) {
658 $this->watchthis
= true;
660 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
661 $this->minoredit
= true;
663 if ( $this->textbox1
=== false ) {
671 * Fetch initial editing page content.
673 * @param $def_text string
674 * @return mixed string on success, $def_text for invalid sections
677 function getContent( $def_text = '' ) {
678 global $wgOut, $wgRequest, $wgParser;
680 wfProfileIn( __METHOD__
);
681 # Get variables from query string :P
682 $section = $wgRequest->getVal( 'section' );
684 $preload = $wgRequest->getVal( 'preload',
685 // Custom preload text for new sections
686 $section === 'new' ?
'MediaWiki:addsection-preload' : '' );
687 $undoafter = $wgRequest->getVal( 'undoafter' );
688 $undo = $wgRequest->getVal( 'undo' );
690 // For message page not locally set, use the i18n message.
691 // For other non-existent articles, use preload text if any.
692 if ( !$this->mTitle
->exists() ) {
693 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
694 # If this is a system message, get the default text.
695 $text = $this->mTitle
->getDefaultMessageText();
696 if( $text === false ) {
697 $text = $this->getPreloadedText( $preload );
700 # If requested, preload some text.
701 $text = $this->getPreloadedText( $preload );
703 // For existing pages, get text based on "undo" or section parameters.
705 $text = $this->mArticle
->getContent();
706 if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
707 # If they got undoafter and undo round the wrong way, switch them
708 list( $undo, $undoafter ) = array( $undoafter, $undo );
710 if ( $undo > 0 && $undo > $undoafter ) {
711 # Undoing a specific edit overrides section editing; section-editing
712 # doesn't work with undoing.
714 $undorev = Revision
::newFromId( $undo );
715 $oldrev = Revision
::newFromId( $undoafter );
717 $undorev = Revision
::newFromId( $undo );
718 $oldrev = $undorev ?
$undorev->getPrevious() : null;
721 # Sanity check, make sure it's the right page,
722 # the revisions exist and they were not deleted.
723 # Otherwise, $text will be left as-is.
724 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
725 $undorev->getPage() == $oldrev->getPage() &&
726 $undorev->getPage() == $this->mArticle
->getID() &&
727 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
728 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
730 $undotext = $this->mArticle
->getUndoText( $undorev, $oldrev );
731 if ( $undotext === false ) {
732 # Warn the user that something went wrong
733 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-failure">' .
734 wfMsgNoTrans( 'undo-failure' ) . '</div>', true, /* interface */true );
737 # Inform the user of our success and set an automatic edit summary
738 $this->editFormPageTop
.= $wgOut->parse( '<div class="mw-undo-success">' .
739 wfMsgNoTrans( 'undo-success' ) . '</div>', true, /* interface */true );
740 $firstrev = $oldrev->getNext();
741 # If we just undid one rev, use an autosummary
742 if ( $firstrev->getId() == $undo ) {
743 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
744 if ( $this->summary
=== '' ) {
745 $this->summary
= $undoSummary;
747 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
749 $this->undidRev
= $undo;
751 $this->formtype
= 'diff';
754 // Failed basic sanity checks.
755 // Older revisions may have been removed since the link
756 // was created, or we may simply have got bogus input.
757 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-norev">' .
758 wfMsgNoTrans( 'undo-norev' ) . '</div>', true, /* interface */true );
760 } elseif ( $section != '' ) {
761 if ( $section == 'new' ) {
762 $text = $this->getPreloadedText( $preload );
764 // Get section edit text (returns $def_text for invalid sections)
765 $text = $wgParser->getSection( $text, $section, $def_text );
770 wfProfileOut( __METHOD__
);
775 * Use this method before edit() to preload some text into the edit box
777 * @param $text string
779 public function setPreloadedText( $text ) {
780 $this->mPreloadText
= $text;
784 * Get the contents to be preloaded into the box, either set by
785 * an earlier setPreloadText() or by loading the given page.
787 * @param $preload String: representing the title to preload from.
790 protected function getPreloadedText( $preload ) {
791 global $wgUser, $wgParser;
793 if ( !empty( $this->mPreloadText
) ) {
794 return $this->mPreloadText
;
797 if ( $preload === '' ) {
801 $title = Title
::newFromText( $preload );
802 # Check for existence to avoid getting MediaWiki:Noarticletext
803 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
807 $page = WikiPage
::factory( $title );
808 if ( $page->isRedirect() ) {
809 $title = $page->getRedirectTarget();
811 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
814 $page = WikiPage
::factory( $title );
817 $parserOptions = ParserOptions
::newFromUser( $wgUser );
818 return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
822 * Make sure the form isn't faking a user's credentials.
824 * @param $request WebRequest
828 function tokenOk( &$request ) {
830 $token = $request->getVal( 'wpEditToken' );
831 $this->mTokenOk
= $wgUser->matchEditToken( $token );
832 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
833 return $this->mTokenOk
;
838 * @return bool false if output is done, true if the rest of the form should be displayed
840 function attemptSave() {
841 global $wgUser, $wgOut;
843 $resultDetails = false;
844 # Allow bots to exempt some edits from bot flagging
845 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
846 $status = $this->internalAttemptSave( $resultDetails, $bot );
847 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
849 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
850 $this->didSave
= true;
853 switch ( $status->value
) {
854 case self
::AS_HOOK_ERROR_EXPECTED
:
855 case self
::AS_CONTENT_TOO_BIG
:
856 case self
::AS_ARTICLE_WAS_DELETED
:
857 case self
::AS_CONFLICT_DETECTED
:
858 case self
::AS_SUMMARY_NEEDED
:
859 case self
::AS_TEXTBOX_EMPTY
:
860 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
864 case self
::AS_HOOK_ERROR
:
865 case self
::AS_FILTERING
:
868 case self
::AS_SUCCESS_NEW_ARTICLE
:
869 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
870 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $resultDetails['sectionanchor'] );
873 case self
::AS_SUCCESS_UPDATE
:
875 $sectionanchor = $resultDetails['sectionanchor'];
877 // Give extensions a chance to modify URL query on update
878 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
880 if ( $resultDetails['redirect'] ) {
881 if ( $extraQuery == '' ) {
882 $extraQuery = 'redirect=no';
884 $extraQuery = 'redirect=no&' . $extraQuery;
887 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
890 case self
::AS_BLANK_ARTICLE
:
891 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
894 case self
::AS_SPAM_ERROR
:
895 $this->spamPageWithContent( $resultDetails['spam'] );
898 case self
::AS_BLOCKED_PAGE_FOR_USER
:
899 throw new UserBlockedError( $wgUser->mBlock
);
901 case self
::AS_IMAGE_REDIRECT_ANON
:
902 case self
::AS_IMAGE_REDIRECT_LOGGED
:
903 throw new PermissionsError( 'upload' );
905 case self
::AS_READ_ONLY_PAGE_ANON
:
906 case self
::AS_READ_ONLY_PAGE_LOGGED
:
907 throw new PermissionsError( 'edit' );
909 case self
::AS_READ_ONLY_PAGE
:
910 throw new ReadOnlyError
;
912 case self
::AS_RATE_LIMITED
:
913 throw new ThrottledError();
915 case self
::AS_NO_CREATE_PERMISSION
:
916 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
917 throw new PermissionsError( $permission );
924 * Attempt submission (no UI)
929 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
931 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
932 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
933 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
935 function internalAttemptSave( &$result, $bot = false ) {
936 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
937 global $wgMaxArticleSize;
939 $status = Status
::newGood();
941 wfProfileIn( __METHOD__
);
942 wfProfileIn( __METHOD__
. '-checks' );
944 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
945 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
946 $status->fatal( 'hookaborted' );
947 $status->value
= self
::AS_HOOK_ERROR
;
948 wfProfileOut( __METHOD__
. '-checks' );
949 wfProfileOut( __METHOD__
);
953 # Check image redirect
954 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
955 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
956 !$wgUser->isAllowed( 'upload' ) ) {
957 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
958 $status->setResult( false, $code );
960 wfProfileOut( __METHOD__
. '-checks' );
961 wfProfileOut( __METHOD__
);
967 $match = self
::matchSummarySpamRegex( $this->summary
);
968 if ( $match === false ) {
969 $match = self
::matchSpamRegex( $this->textbox1
);
971 if ( $match !== false ) {
972 $result['spam'] = $match;
973 $ip = $wgRequest->getIP();
974 $pdbk = $this->mTitle
->getPrefixedDBkey();
975 $match = str_replace( "\n", '', $match );
976 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
977 $status->fatal( 'spamprotectionmatch', $match );
978 $status->value
= self
::AS_SPAM_ERROR
;
979 wfProfileOut( __METHOD__
. '-checks' );
980 wfProfileOut( __METHOD__
);
983 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
984 # Error messages or other handling should be performed by the filter function
985 $status->setResult( false, self
::AS_FILTERING
);
986 wfProfileOut( __METHOD__
. '-checks' );
987 wfProfileOut( __METHOD__
);
990 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
991 # Error messages etc. could be handled within the hook...
992 $status->fatal( 'hookaborted' );
993 $status->value
= self
::AS_HOOK_ERROR
;
994 wfProfileOut( __METHOD__
. '-checks' );
995 wfProfileOut( __METHOD__
);
997 } elseif ( $this->hookError
!= '' ) {
998 # ...or the hook could be expecting us to produce an error
999 $status->fatal( 'hookaborted' );
1000 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1001 wfProfileOut( __METHOD__
. '-checks' );
1002 wfProfileOut( __METHOD__
);
1006 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1007 // Auto-block user's IP if the account was "hard" blocked
1008 $wgUser->spreadAnyEditBlock();
1009 # Check block state against master, thus 'false'.
1010 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1011 wfProfileOut( __METHOD__
. '-checks' );
1012 wfProfileOut( __METHOD__
);
1016 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1017 if ( $this->kblength
> $wgMaxArticleSize ) {
1018 // Error will be displayed by showEditForm()
1019 $this->tooBig
= true;
1020 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1021 wfProfileOut( __METHOD__
. '-checks' );
1022 wfProfileOut( __METHOD__
);
1026 if ( !$wgUser->isAllowed( 'edit' ) ) {
1027 if ( $wgUser->isAnon() ) {
1028 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1029 wfProfileOut( __METHOD__
. '-checks' );
1030 wfProfileOut( __METHOD__
);
1033 $status->fatal( 'readonlytext' );
1034 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1035 wfProfileOut( __METHOD__
. '-checks' );
1036 wfProfileOut( __METHOD__
);
1041 if ( wfReadOnly() ) {
1042 $status->fatal( 'readonlytext' );
1043 $status->value
= self
::AS_READ_ONLY_PAGE
;
1044 wfProfileOut( __METHOD__
. '-checks' );
1045 wfProfileOut( __METHOD__
);
1048 if ( $wgUser->pingLimiter() ) {
1049 $status->fatal( 'actionthrottledtext' );
1050 $status->value
= self
::AS_RATE_LIMITED
;
1051 wfProfileOut( __METHOD__
. '-checks' );
1052 wfProfileOut( __METHOD__
);
1056 # If the article has been deleted while editing, don't save it without
1058 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1059 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1060 wfProfileOut( __METHOD__
. '-checks' );
1061 wfProfileOut( __METHOD__
);
1065 wfProfileOut( __METHOD__
. '-checks' );
1067 # If article is new, insert it.
1068 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1069 $new = ( $aid == 0 );
1072 // Late check for create permission, just in case *PARANOIA*
1073 if ( !$this->mTitle
->userCan( 'create' ) ) {
1074 $status->fatal( 'nocreatetext' );
1075 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1076 wfDebug( __METHOD__
. ": no create permission\n" );
1077 wfProfileOut( __METHOD__
);
1081 # Don't save a new article if it's blank.
1082 if ( $this->textbox1
== '' ) {
1083 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1084 wfProfileOut( __METHOD__
);
1088 // Run post-section-merge edit filter
1089 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1090 # Error messages etc. could be handled within the hook...
1091 $status->fatal( 'hookaborted' );
1092 $status->value
= self
::AS_HOOK_ERROR
;
1093 wfProfileOut( __METHOD__
);
1095 } elseif ( $this->hookError
!= '' ) {
1096 # ...or the hook could be expecting us to produce an error
1097 $status->fatal( 'hookaborted' );
1098 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1099 wfProfileOut( __METHOD__
);
1103 # Handle the user preference to force summaries here. Check if it's not a redirect.
1104 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
1105 if ( md5( $this->summary
) == $this->autoSumm
) {
1106 $this->missingSummary
= true;
1107 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1108 $status->value
= self
::AS_SUMMARY_NEEDED
;
1109 wfProfileOut( __METHOD__
);
1114 $text = $this->textbox1
;
1115 $result['sectionanchor'] == '';
1116 if ( $this->section
== 'new' && $this->summary
!= '' ) {
1117 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $text;
1119 # Jump to the new section
1120 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1122 # This is a new section, so create a link to the new section
1123 # in the revision summary.
1124 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1125 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1128 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1132 # Article exists. Check for edit conflict.
1134 $this->mArticle
->clear(); # Force reload of dates, etc.
1136 wfDebug( "timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n" );
1138 if ( $this->mArticle
->getTimestamp() != $this->edittime
) {
1139 $this->isConflict
= true;
1140 if ( $this->section
== 'new' ) {
1141 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1142 $this->mArticle
->getComment() == $this->summary
) {
1143 // Probably a duplicate submission of a new comment.
1144 // This can happen when squid resends a request after
1145 // a timeout but the first one actually went through.
1146 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1148 // New comment; suppress conflict.
1149 $this->isConflict
= false;
1150 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1152 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1153 # Suppress edit conflict with self, except for section edits where merging is required.
1154 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1155 $this->isConflict
= false;
1159 if ( $this->isConflict
) {
1160 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
1161 $this->mArticle
->getTimestamp() . "')\n" );
1162 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1164 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1165 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
1167 if ( is_null( $text ) ) {
1168 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1169 $this->isConflict
= true;
1170 $text = $this->textbox1
; // do not try to merge here!
1171 } elseif ( $this->isConflict
) {
1173 if ( $this->mergeChangesInto( $text ) ) {
1174 // Successful merge! Maybe we should tell the user the good news?
1175 $this->isConflict
= false;
1176 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1178 $this->section
= '';
1179 $this->textbox1
= $text;
1180 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1184 if ( $this->isConflict
) {
1185 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1186 wfProfileOut( __METHOD__
);
1190 // Run post-section-merge edit filter
1191 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
1192 # Error messages etc. could be handled within the hook...
1193 $status->fatal( 'hookaborted' );
1194 $status->value
= self
::AS_HOOK_ERROR
;
1195 wfProfileOut( __METHOD__
);
1197 } elseif ( $this->hookError
!= '' ) {
1198 # ...or the hook could be expecting us to produce an error
1199 $status->fatal( 'hookaborted' );
1200 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1201 wfProfileOut( __METHOD__
);
1205 # Handle the user preference to force summaries here, but not for null edits
1206 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1207 && 0 != strcmp( $this->mArticle
->getContent(), $text )
1208 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1210 if ( md5( $this->summary
) == $this->autoSumm
) {
1211 $this->missingSummary
= true;
1212 $status->fatal( 'missingsummary' );
1213 $status->value
= self
::AS_SUMMARY_NEEDED
;
1214 wfProfileOut( __METHOD__
);
1219 # And a similar thing for new sections
1220 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1221 if ( trim( $this->summary
) == '' ) {
1222 $this->missingSummary
= true;
1223 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1224 $status->value
= self
::AS_SUMMARY_NEEDED
;
1225 wfProfileOut( __METHOD__
);
1231 wfProfileIn( __METHOD__
. '-sectionanchor' );
1232 $sectionanchor = '';
1233 if ( $this->section
== 'new' ) {
1234 if ( $this->textbox1
== '' ) {
1235 $this->missingComment
= true;
1236 $status->fatal( 'missingcommenttext' );
1237 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1238 wfProfileOut( __METHOD__
. '-sectionanchor' );
1239 wfProfileOut( __METHOD__
);
1242 if ( $this->summary
!= '' ) {
1243 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1244 # This is a new section, so create a link to the new section
1245 # in the revision summary.
1246 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1247 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1249 } elseif ( $this->section
!= '' ) {
1250 # Try to get a section anchor from the section source, redirect to edited section if header found
1251 # XXX: might be better to integrate this into Article::replaceSection
1252 # for duplicate heading checking and maybe parsing
1253 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1254 # we can't deal with anchors, includes, html etc in the header for now,
1255 # headline would need to be parsed to improve this
1256 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1257 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1260 $result['sectionanchor'] = $sectionanchor;
1261 wfProfileOut( __METHOD__
. '-sectionanchor' );
1263 // Save errors may fall down to the edit form, but we've now
1264 // merged the section into full text. Clear the section field
1265 // so that later submission of conflict forms won't try to
1266 // replace that into a duplicated mess.
1267 $this->textbox1
= $text;
1268 $this->section
= '';
1270 $status->value
= self
::AS_SUCCESS_UPDATE
;
1273 // Check for length errors again now that the section is merged in
1274 $this->kblength
= (int)( strlen( $text ) / 1024 );
1275 if ( $this->kblength
> $wgMaxArticleSize ) {
1276 $this->tooBig
= true;
1277 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1278 wfProfileOut( __METHOD__
);
1282 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1283 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1284 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1285 ( $bot ? EDIT_FORCE_BOT
: 0 );
1287 $doEditStatus = $this->mArticle
->doEdit( $text, $this->summary
, $flags );
1289 if ( $doEditStatus->isOK() ) {
1290 $result['redirect'] = Title
::newFromRedirect( $text ) !== null;
1291 $this->commitWatch();
1292 wfProfileOut( __METHOD__
);
1295 $this->isConflict
= true;
1296 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1297 wfProfileOut( __METHOD__
);
1298 return $doEditStatus;
1303 * Commit the change of watch status
1305 protected function commitWatch() {
1307 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1308 $dbw = wfGetDB( DB_MASTER
);
1310 if ( $this->watchthis
) {
1311 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1313 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1320 * Check if no edits were made by other users since
1321 * the time a user started editing the page. Limit to
1322 * 50 revisions for the sake of performance.
1325 * @param $edittime string
1329 protected function userWasLastToEdit( $id, $edittime ) {
1330 if( !$id ) return false;
1331 $dbw = wfGetDB( DB_MASTER
);
1332 $res = $dbw->select( 'revision',
1335 'rev_page' => $this->mArticle
->getId(),
1336 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1339 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1340 foreach ( $res as $row ) {
1341 if( $row->rev_user
!= $id ) {
1352 * @parma $editText string
1356 function mergeChangesInto( &$editText ){
1357 wfProfileIn( __METHOD__
);
1359 $db = wfGetDB( DB_MASTER
);
1361 // This is the revision the editor started from
1362 $baseRevision = $this->getBaseRevision();
1363 if ( is_null( $baseRevision ) ) {
1364 wfProfileOut( __METHOD__
);
1367 $baseText = $baseRevision->getText();
1369 // The current state, we want to merge updates into it
1370 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1371 if ( is_null( $currentRevision ) ) {
1372 wfProfileOut( __METHOD__
);
1375 $currentText = $currentRevision->getText();
1378 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1379 $editText = $result;
1380 wfProfileOut( __METHOD__
);
1383 wfProfileOut( __METHOD__
);
1391 function getBaseRevision() {
1392 if ( !$this->mBaseRevision
) {
1393 $db = wfGetDB( DB_MASTER
);
1394 $baseRevision = Revision
::loadFromTimestamp(
1395 $db, $this->mTitle
, $this->edittime
);
1396 return $this->mBaseRevision
= $baseRevision;
1398 return $this->mBaseRevision
;
1403 * Check given input text against $wgSpamRegex, and return the text of the first match.
1405 * @param $text string
1407 * @return string|false matching string or false
1409 public static function matchSpamRegex( $text ) {
1410 global $wgSpamRegex;
1411 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1412 $regexes = (array)$wgSpamRegex;
1413 return self
::matchSpamRegexInternal( $text, $regexes );
1417 * Check given input text against $wgSpamRegex, and return the text of the first match.
1419 * @parma $text string
1421 * @return string|false matching string or false
1423 public static function matchSummarySpamRegex( $text ) {
1424 global $wgSummarySpamRegex;
1425 $regexes = (array)$wgSummarySpamRegex;
1426 return self
::matchSpamRegexInternal( $text, $regexes );
1430 * @param $text string
1431 * @param $regexes array
1432 * @return bool|string
1434 protected static function matchSpamRegexInternal( $text, $regexes ) {
1435 foreach( $regexes as $regex ) {
1437 if( preg_match( $regex, $text, $matches ) ) {
1444 function setHeaders() {
1446 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1447 if ( $this->isConflict
) {
1448 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1449 } elseif ( $this->section
!= '' ) {
1450 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1451 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1453 # Use the title defined by DISPLAYTITLE magic word when present
1454 if ( isset( $this->mParserOutput
)
1455 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1458 $title = $this->getContextTitle()->getPrefixedText();
1460 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1465 * Show all applicable editing introductions
1467 protected function showIntro() {
1468 global $wgOut, $wgUser;
1469 if ( $this->suppressIntro
) {
1473 $namespace = $this->mTitle
->getNamespace();
1475 if ( $namespace == NS_MEDIAWIKI
) {
1476 # Show a warning if editing an interface message
1477 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1480 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1481 # Show log extract when the user is currently blocked
1482 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1483 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1484 $username = $parts[0];
1485 $user = User
::newFromName( $username, false /* allow IP users*/ );
1486 $ip = User
::isIP( $username );
1487 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1488 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1489 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1490 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1491 LogEventsList
::showLogExtract(
1494 $user->getUserPage(),
1498 'showIfEmpty' => false,
1500 'blocked-notice-logextract',
1501 $user->getName() # Support GENDER in notice
1507 # Try to add a custom edit intro, or use the standard one if this is not possible.
1508 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1509 if ( $wgUser->isLoggedIn() ) {
1510 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1512 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1515 # Give a notice if the user is editing a deleted/moved page...
1516 if ( !$this->mTitle
->exists() ) {
1517 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1518 '', array( 'lim' => 10,
1519 'conds' => array( "log_action != 'revision'" ),
1520 'showIfEmpty' => false,
1521 'msgKey' => array( 'recreate-moveddeleted-warn') )
1527 * Attempt to show a custom editing introduction, if supplied
1531 protected function showCustomIntro() {
1532 if ( $this->editintro
) {
1533 $title = Title
::newFromText( $this->editintro
);
1534 if ( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
1536 // Added using template syntax, to take <noinclude>'s into account.
1537 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1548 * Send the edit form and related headers to $wgOut
1549 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1550 * during form output near the top, for captchas and the like.
1552 function showEditForm( $formCallback = null ) {
1553 global $wgOut, $wgUser;
1555 wfProfileIn( __METHOD__
);
1557 #need to parse the preview early so that we know which templates are used,
1558 #otherwise users with "show preview after edit box" will get a blank list
1559 #we parse this near the beginning so that setHeaders can do the title
1560 #setting work instead of leaving it in getPreviewText
1561 $previewOutput = '';
1562 if ( $this->formtype
== 'preview' ) {
1563 $previewOutput = $this->getPreviewText();
1566 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1568 $this->setHeaders();
1570 # Enabled article-related sidebar, toplinks, etc.
1571 $wgOut->setArticleRelated( true );
1573 if ( $this->showHeader() === false ) {
1574 wfProfileOut( __METHOD__
);
1578 $action = htmlspecialchars( $this->getActionURL( $this->getContextTitle() ) );
1580 if ( $wgUser->getOption( 'showtoolbar' ) and !$this->isCssJsSubpage
) {
1581 # prepare toolbar for edit buttons
1582 $toolbar = EditPage
::getEditToolbar();
1588 $wgOut->addHTML( $this->editFormPageTop
);
1590 if ( $wgUser->getOption( 'previewontop' ) ) {
1591 $this->displayPreviewArea( $previewOutput, true );
1594 $wgOut->addHTML( $this->editFormTextTop
);
1596 $templates = $this->getTemplates();
1597 $formattedtemplates = Linker
::formatTemplates( $templates, $this->preview
, $this->section
!= '');
1599 $hiddencats = $this->mArticle
->getHiddenCategories();
1600 $formattedhiddencats = Linker
::formatHiddenCategories( $hiddencats );
1602 if ( $this->wasDeletedSinceLastEdit() && 'save' != $this->formtype
) {
1603 $wgOut->wrapWikiMsg(
1604 "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1605 'deletedwhileediting' );
1606 } elseif ( $this->wasDeletedSinceLastEdit() ) {
1607 // Hide the toolbar and edit area, user can click preview to get it back
1608 // Add an confirmation checkbox and explanation.
1610 // @todo move this to a cleaner conditional instead of blanking a variable
1612 $wgOut->addHTML( <<<HTML
1613 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1617 if ( is_callable( $formCallback ) ) {
1618 call_user_func_array( $formCallback, array( &$wgOut ) );
1621 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1623 // Put these up at the top to ensure they aren't lost on early form submission
1624 $this->showFormBeforeText();
1626 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1627 $username = $this->lastDelete
->user_name
;
1628 $comment = $this->lastDelete
->log_comment
;
1630 // It is better to not parse the comment at all than to have templates expanded in the middle
1631 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1632 $key = $comment === ''
1633 ?
'confirmrecreate-noreason'
1634 : 'confirmrecreate';
1636 '<div class="mw-confirm-recreate">' .
1637 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1638 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1639 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1645 # If a blank edit summary was previously provided, and the appropriate
1646 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1647 # user being bounced back more than once in the event that a summary
1650 # For a bit more sophisticated detection of blank summaries, hash the
1651 # automatic one and pass that in the hidden field wpAutoSummary.
1652 if ( $this->missingSummary ||
1653 ( $this->section
== 'new' && $this->nosummary
) )
1654 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1655 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1656 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1658 $wgOut->addHTML( Html
::hidden( 'oldid', $this->mArticle
->getOldID() ) );
1660 if ( $this->section
== 'new' ) {
1661 $this->showSummaryInput( true, $this->summary
);
1662 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1665 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1667 $wgOut->addHTML( $toolbar );
1669 if ( $this->isConflict
) {
1670 // In an edit conflict bypass the overrideable content form method
1671 // and fallback to the raw wpTextbox1 since editconflicts can't be
1672 // resolved between page source edits and custom ui edits using the
1674 $this->showTextbox1( null, $this->getContent() );
1676 $this->showContentForm();
1679 $wgOut->addHTML( $this->editFormTextAfterContent
);
1681 $wgOut->addWikiText( $this->getCopywarn() );
1682 if ( isset($this->editFormTextAfterWarn
) && $this->editFormTextAfterWarn
!== '' )
1683 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1685 $this->showStandardInputs();
1687 $this->showFormAfterText();
1689 $this->showTosSummary();
1690 $this->showEditTools();
1692 $wgOut->addHTML( <<<HTML
1693 {$this->editFormTextAfterTools}
1694 <div class='templatesUsed'>
1695 {$formattedtemplates}
1697 <div class='hiddencats'>
1698 {$formattedhiddencats}
1703 if ( $this->isConflict
)
1704 $this->showConflict();
1706 $wgOut->addHTML( $this->editFormTextBottom
);
1707 $wgOut->addHTML( "</form>\n" );
1708 if ( !$wgUser->getOption( 'previewontop' ) ) {
1709 $this->displayPreviewArea( $previewOutput, false );
1712 wfProfileOut( __METHOD__
);
1715 protected function showHeader() {
1716 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1717 if ( $this->isConflict
) {
1718 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1719 $this->edittime
= $this->mArticle
->getTimestamp();
1721 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
1722 // We use $this->section to much before this and getVal('wgSection') directly in other places
1723 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1724 // Someone is welcome to try refactoring though
1725 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1729 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1731 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1732 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1
, $matches );
1733 if ( !empty( $matches[2] ) ) {
1735 $this->summary
= "/* " .
1736 $wgParser->stripSectionName(trim($matches[2])) .
1742 if ( $this->missingComment
) {
1743 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1746 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1747 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1750 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1751 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1754 if ( $this->hookError
!== '' ) {
1755 $wgOut->addWikiText( $this->hookError
);
1758 if ( !$this->checkUnicodeCompliantBrowser() ) {
1759 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1762 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1763 // Let sysop know that this will make private content public if saved
1765 if ( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1766 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1767 } elseif ( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1768 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1771 if ( !$this->mArticle
->mRevision
->isCurrent() ) {
1772 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1773 $wgOut->addWikiMsg( 'editingold' );
1778 if ( wfReadOnly() ) {
1779 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1780 } elseif ( $wgUser->isAnon() ) {
1781 if ( $this->formtype
!= 'preview' ) {
1782 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1784 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
1787 if ( $this->isCssJsSubpage
) {
1788 # Check the skin exists
1789 if ( $this->isWrongCaseCssJsPage
) {
1790 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
1792 if ( $this->formtype
!== 'preview' ) {
1793 if ( $this->isCssSubpage
)
1794 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
1795 if ( $this->isJsSubpage
)
1796 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
1801 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
1802 # Is the title semi-protected?
1803 if ( $this->mTitle
->isSemiProtected() ) {
1804 $noticeMsg = 'semiprotectedpagewarning';
1806 # Then it must be protected based on static groups (regular)
1807 $noticeMsg = 'protectedpagewarning';
1809 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1810 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1812 if ( $this->mTitle
->isCascadeProtected() ) {
1813 # Is this page under cascading protection from some source pages?
1814 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1815 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
1816 $cascadeSourcesCount = count( $cascadeSources );
1817 if ( $cascadeSourcesCount > 0 ) {
1818 # Explain, and list the titles responsible
1819 foreach( $cascadeSources as $page ) {
1820 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1823 $notice .= '</div>';
1824 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1826 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1827 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1829 'showIfEmpty' => false,
1830 'msgKey' => array( 'titleprotectedwarning' ),
1831 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
1834 if ( $this->kblength
=== false ) {
1835 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1838 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1839 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
1840 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
1842 if( !wfMessage('longpage-hint')->isDisabled() ) {
1843 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
1844 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
1851 * Standard summary input and label (wgSummary), abstracted so EditPage
1852 * subclasses may reorganize the form.
1853 * Note that you do not need to worry about the label's for=, it will be
1854 * inferred by the id given to the input. You can remove them both by
1855 * passing array( 'id' => false ) to $userInputAttrs.
1857 * @param $summary string The value of the summary input
1858 * @param $labelText string The html to place inside the label
1859 * @param $inputAttrs array of attrs to use on the input
1860 * @param $spanLabelAttrs array of attrs to use on the span inside the label
1862 * @return array An array in the format array( $label, $input )
1864 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
1865 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
1866 $inputAttrs = ( is_array($inputAttrs) ?
$inputAttrs : array() ) +
array(
1867 'id' => 'wpSummary',
1868 'maxlength' => '200',
1871 'spellcheck' => 'true',
1872 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
1874 $spanLabelAttrs = ( is_array($spanLabelAttrs) ?
$spanLabelAttrs : array() ) +
array(
1875 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
1876 'id' => "wpSummaryLabel"
1881 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1882 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
1885 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
1887 return array( $label, $input );
1891 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1892 * up top, or false if this is the comment summary
1893 * down below the textarea
1894 * @param $summary String: The text of the summary to display
1897 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1898 global $wgOut, $wgContLang;
1899 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1900 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1901 if ( $isSubjectPreview ) {
1902 if ( $this->nosummary
) {
1906 if ( !$this->mShowSummaryField
) {
1910 $summary = $wgContLang->recodeForEdit( $summary );
1911 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
1912 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
1913 $wgOut->addHTML("{$label} {$input}");
1917 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1918 * up top, or false if this is the comment summary
1919 * down below the textarea
1920 * @param $summary String: the text of the summary to display
1923 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
1924 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
1929 if ( $isSubjectPreview )
1930 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
1932 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
1934 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
1935 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
1938 protected function showFormBeforeText() {
1940 $section = htmlspecialchars( $this->section
);
1941 $wgOut->addHTML( <<<HTML
1942 <input type='hidden' value="{$section}" name="wpSection" />
1943 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
1944 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
1945 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
1949 if ( !$this->checkUnicodeCompliantBrowser() )
1950 $wgOut->addHTML(Html
::hidden( 'safemode', '1' ));
1953 protected function showFormAfterText() {
1954 global $wgOut, $wgUser;
1956 * To make it harder for someone to slip a user a page
1957 * which submits an edit form to the wiki without their
1958 * knowledge, a random token is associated with the login
1959 * session. If it's not passed back with the submission,
1960 * we won't save the page, or render user JavaScript and
1963 * For anon editors, who may not have a session, we just
1964 * include the constant suffix to prevent editing from
1965 * broken text-mangling proxies.
1967 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
1971 * Subpage overridable method for printing the form for page content editing
1972 * By default this simply outputs wpTextbox1
1973 * Subclasses can override this to provide a custom UI for editing;
1974 * be it a form, or simply wpTextbox1 with a modified content that will be
1975 * reverse modified when extracted from the post data.
1976 * Note that this is basically the inverse for importContentFormData
1978 protected function showContentForm() {
1979 $this->showTextbox1();
1983 * Method to output wpTextbox1
1984 * The $textoverride method can be used by subclasses overriding showContentForm
1985 * to pass back to this method.
1987 * @param $customAttribs An array of html attributes to use in the textarea
1988 * @param $textoverride String: optional text to override $this->textarea1 with
1990 protected function showTextbox1($customAttribs = null, $textoverride = null) {
1991 $classes = array(); // Textarea CSS
1992 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
1993 # Is the title semi-protected?
1994 if ( $this->mTitle
->isSemiProtected() ) {
1995 $classes[] = 'mw-textarea-sprotected';
1997 # Then it must be protected based on static groups (regular)
1998 $classes[] = 'mw-textarea-protected';
2000 # Is the title cascade-protected?
2001 if ( $this->mTitle
->isCascadeProtected() ) {
2002 $classes[] = 'mw-textarea-cprotected';
2005 $attribs = array( 'tabindex' => 1 );
2006 if ( is_array($customAttribs) )
2007 $attribs +
= $customAttribs;
2009 if ( $this->wasDeletedSinceLastEdit() )
2010 $attribs['type'] = 'hidden';
2011 if ( !empty( $classes ) ) {
2012 if ( isset($attribs['class']) )
2013 $classes[] = $attribs['class'];
2014 $attribs['class'] = implode( ' ', $classes );
2017 $this->showTextbox( isset($textoverride) ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2020 protected function showTextbox2() {
2021 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2024 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2025 global $wgOut, $wgUser;
2027 $wikitext = $this->safeUnicodeOutput( $content );
2028 if ( strval($wikitext) !== '' ) {
2029 // Ensure there's a newline at the end, otherwise adding lines
2031 // But don't add a newline if the ext is empty, or Firefox in XHTML
2032 // mode will show an extra newline. A bit annoying.
2036 $attribs = $customAttribs +
array(
2039 'cols' => $wgUser->getIntOption( 'cols' ),
2040 'rows' => $wgUser->getIntOption( 'rows' ),
2041 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2044 $pageLang = $this->mTitle
->getPageLanguage();
2045 $attribs['lang'] = $pageLang->getCode();
2046 $attribs['dir'] = $pageLang->getDir();
2048 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2051 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2055 $classes[] = 'ontop';
2057 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2059 if ( $this->formtype
!= 'preview' )
2060 $attribs['style'] = 'display: none;';
2062 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2064 if ( $this->formtype
== 'preview' ) {
2065 $this->showPreview( $previewOutput );
2068 $wgOut->addHTML( '</div>' );
2070 if ( $this->formtype
== 'diff') {
2076 * Append preview output to $wgOut.
2077 * Includes category rendering if this is a category page.
2079 * @param $text String: the HTML to be output for the preview.
2081 protected function showPreview( $text ) {
2083 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2084 $this->mArticle
->openShowCategory();
2086 # This hook seems slightly odd here, but makes things more
2087 # consistent for extensions.
2088 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
2089 $wgOut->addHTML( $text );
2090 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2091 $this->mArticle
->closeShowCategory();
2096 * Get a diff between the current contents of the edit box and the
2097 * version of the page we're editing from.
2099 * If this is a section edit, we'll replace the section as for final
2100 * save and then make a comparison.
2102 function showDiff() {
2103 global $wgUser, $wgContLang, $wgParser;
2105 $oldtext = $this->mArticle
->fetchContent();
2106 $newtext = $this->mArticle
->replaceSection(
2107 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2109 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2111 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2112 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle
, $wgUser, $popts );
2113 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2114 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2115 if ( $oldtext !== false ||
$newtext != '' ) {
2116 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2117 $de->setText( $oldtext, $newtext );
2118 $difftext = $de->getDiff( $oldtitle, $newtitle );
2119 $de->showDiffStyle();
2125 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2129 * Give a chance for site and per-namespace customizations of
2130 * terms of service summary link that might exist separately
2131 * from the copyright notice.
2133 * This will display between the save button and the edit tools,
2134 * so should remain short!
2136 protected function showTosSummary() {
2137 $msg = 'editpage-tos-summary';
2138 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2139 if( !wfMessage( $msg )->isDisabled() ) {
2141 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2142 $wgOut->addWikiMsg( $msg );
2143 $wgOut->addHTML( '</div>' );
2147 protected function showEditTools() {
2149 $wgOut->addHTML( '<div class="mw-editTools">' .
2150 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2154 protected function getCopywarn() {
2155 global $wgRightsText;
2156 if ( $wgRightsText ) {
2157 $copywarnMsg = array( 'copyrightwarning',
2158 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2161 $copywarnMsg = array( 'copyrightwarning2',
2162 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2164 // Allow for site and per-namespace customization of contribution/copyright notice.
2165 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2167 return "<div id=\"editpage-copywarn\">\n" .
2168 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
2171 protected function showStandardInputs( &$tabindex = 2 ) {
2173 $wgOut->addHTML( "<div class='editOptions'>\n" );
2175 if ( $this->section
!= 'new' ) {
2176 $this->showSummaryInput( false, $this->summary
);
2177 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2180 $checkboxes = $this->getCheckboxes( $tabindex,
2181 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2182 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2183 $wgOut->addHTML( "<div class='editButtons'>\n" );
2184 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2186 $cancel = $this->getCancelLink();
2187 if ( $cancel !== '' ) {
2188 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2190 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2191 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
2192 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
2193 htmlspecialchars( wfMsg( 'newwindow' ) );
2194 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2195 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2199 * Show an edit conflict. textbox1 is already shown in showEditForm().
2200 * If you want to use another entry point to this function, be careful.
2202 protected function showConflict() {
2204 $this->textbox2
= $this->textbox1
;
2205 $this->textbox1
= $this->getContent();
2206 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2207 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2209 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2210 $de->setText( $this->textbox2
, $this->textbox1
);
2211 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2213 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2214 $this->showTextbox2();
2221 public function getCancelLink() {
2222 $cancelParams = array();
2223 if ( !$this->isConflict
&& $this->mArticle
->getOldID() > 0 ) {
2224 $cancelParams['oldid'] = $this->mArticle
->getOldID();
2227 return Linker
::linkKnown(
2228 $this->getContextTitle(),
2229 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2230 array( 'id' => 'mw-editform-cancel' ),
2236 * Returns the URL to use in the form's action attribute.
2237 * This is used by EditPage subclasses when simply customizing the action
2238 * variable in the constructor is not enough. This can be used when the
2239 * EditPage lives inside of a Special page rather than a custom page action.
2241 * @param $title Title object for which is being edited (where we go to for &action= links)
2244 protected function getActionURL( Title
$title ) {
2245 return $title->getLocalURL( array( 'action' => $this->action
) );
2249 * Check if a page was deleted while the user was editing it, before submit.
2250 * Note that we rely on the logging table, which hasn't been always there,
2251 * but that doesn't matter, because this only applies to brand new
2254 protected function wasDeletedSinceLastEdit() {
2255 if ( $this->deletedSinceEdit
!== null ) {
2256 return $this->deletedSinceEdit
;
2259 $this->deletedSinceEdit
= false;
2261 if ( $this->mTitle
->isDeletedQuick() ) {
2262 $this->lastDelete
= $this->getLastDelete();
2263 if ( $this->lastDelete
) {
2264 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2265 if ( $deleteTime > $this->starttime
) {
2266 $this->deletedSinceEdit
= true;
2271 return $this->deletedSinceEdit
;
2274 protected function getLastDelete() {
2275 $dbr = wfGetDB( DB_SLAVE
);
2276 $data = $dbr->selectRow(
2277 array( 'logging', 'user' ),
2288 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2289 'log_title' => $this->mTitle
->getDBkey(),
2290 'log_type' => 'delete',
2291 'log_action' => 'delete',
2292 'user_id=log_user' ),
2294 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2296 // Quick paranoid permission checks...
2297 if( is_object( $data ) ) {
2298 if( $data->log_deleted
& LogPage
::DELETED_USER
)
2299 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2300 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2301 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2307 * Get the rendered text for previewing.
2310 function getPreviewText() {
2311 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2313 wfProfileIn( __METHOD__
);
2315 if ( $wgRawHtml && !$this->mTokenOk
) {
2316 // Could be an offsite preview attempt. This is very unsafe if
2317 // HTML is enabled, as it could be an attack.
2319 if ( $this->textbox1
!== '' ) {
2320 // Do not put big scary notice, if previewing the empty
2321 // string, which happens when you initially edit
2322 // a category page, due to automatic preview-on-open.
2323 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2324 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2326 wfProfileOut( __METHOD__
);
2330 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2331 if ( $this->mTokenOkExceptSuffix
) {
2332 $note = wfMsg( 'token_suffix_mismatch' );
2334 $note = wfMsg( 'session_fail_preview' );
2336 } elseif ( $this->incompleteForm
) {
2337 $note = wfMsg( 'edit_form_incomplete' );
2339 $note = wfMsg( 'previewnote' );
2342 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2343 $parserOptions->setEditSection( false );
2344 $parserOptions->setTidy( true );
2345 $parserOptions->setIsPreview( true );
2346 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2348 # don't parse non-wikitext pages, show message about preview
2349 # 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?
2351 if ( $this->isCssJsSubpage ||
!$this->mTitle
->isWikitextPage() ) {
2352 if( $this->mTitle
->isCssJsSubpage() ) {
2354 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2360 # Used messages to make sure grep find them:
2361 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2363 if (preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2364 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2365 $class = "mw-code mw-css";
2366 } elseif (preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2367 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2368 $class = "mw-code mw-js";
2370 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2374 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2375 $previewHTML = $parserOutput->mText
;
2376 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2378 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2380 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2382 $toparse = $this->textbox1
;
2384 # If we're adding a comment, we need to show the
2385 # summary as the headline
2386 if ( $this->section
== "new" && $this->summary
!= "" ) {
2387 $toparse = "== {$this->summary} ==\n\n" . $toparse;
2390 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2392 $parserOptions->enableLimitReport();
2394 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle
, $wgUser, $parserOptions );
2395 $parserOutput = $wgParser->parse( $toparse, $this->mTitle
, $parserOptions );
2397 $previewHTML = $parserOutput->getText();
2398 $this->mParserOutput
= $parserOutput;
2399 $wgOut->addParserOutputNoText( $parserOutput );
2401 if ( count( $parserOutput->getWarnings() ) ) {
2402 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2407 if( $this->isConflict
) {
2408 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2410 $conflict = '<hr />';
2413 $previewhead = "<div class='previewnote'>\n" .
2414 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2415 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2417 $pageLang = $this->mTitle
->getPageLanguage();
2418 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2419 'class' => 'mw-content-'.$pageLang->getDir() );
2420 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2422 wfProfileOut( __METHOD__
);
2423 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2429 function getTemplates() {
2430 if ( $this->preview ||
$this->section
!= '' ) {
2431 $templates = array();
2432 if ( !isset( $this->mParserOutput
) ) {
2435 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
2436 foreach( array_keys( $template ) as $dbk ) {
2437 $templates[] = Title
::makeTitle($ns, $dbk);
2442 return $this->mArticle
->getUsedTemplates();
2447 * Shows a bulletin board style toolbar for common editing functions.
2448 * It can be disabled in the user preferences.
2449 * The necessary JavaScript code can be found in skins/common/edit.js.
2453 static function getEditToolbar() {
2454 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2455 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2457 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2460 * $toolarray is an array of arrays each of which includes the
2461 * filename of the button image (without path), the opening
2462 * tag, the closing tag, optionally a sample text that is
2463 * inserted between the two when no selection is highlighted
2464 * and. The tip text is shown when the user moves the mouse
2467 * Also here: accesskeys (key), which are not used yet until
2468 * someone can figure out a way to make them work in
2469 * IE. However, we should make sure these keys are not defined
2474 'image' => $wgLang->getImageFile( 'button-bold' ),
2475 'id' => 'mw-editbutton-bold',
2477 'close' => '\'\'\'',
2478 'sample' => wfMsg( 'bold_sample' ),
2479 'tip' => wfMsg( 'bold_tip' ),
2483 'image' => $wgLang->getImageFile( 'button-italic' ),
2484 'id' => 'mw-editbutton-italic',
2487 'sample' => wfMsg( 'italic_sample' ),
2488 'tip' => wfMsg( 'italic_tip' ),
2492 'image' => $wgLang->getImageFile( 'button-link' ),
2493 'id' => 'mw-editbutton-link',
2496 'sample' => wfMsg( 'link_sample' ),
2497 'tip' => wfMsg( 'link_tip' ),
2501 'image' => $wgLang->getImageFile( 'button-extlink' ),
2502 'id' => 'mw-editbutton-extlink',
2505 'sample' => wfMsg( 'extlink_sample' ),
2506 'tip' => wfMsg( 'extlink_tip' ),
2510 'image' => $wgLang->getImageFile( 'button-headline' ),
2511 'id' => 'mw-editbutton-headline',
2514 'sample' => wfMsg( 'headline_sample' ),
2515 'tip' => wfMsg( 'headline_tip' ),
2518 $imagesAvailable ?
array(
2519 'image' => $wgLang->getImageFile( 'button-image' ),
2520 'id' => 'mw-editbutton-image',
2521 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2523 'sample' => wfMsg( 'image_sample' ),
2524 'tip' => wfMsg( 'image_tip' ),
2527 $imagesAvailable ?
array(
2528 'image' => $wgLang->getImageFile( 'button-media' ),
2529 'id' => 'mw-editbutton-media',
2530 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2532 'sample' => wfMsg( 'media_sample' ),
2533 'tip' => wfMsg( 'media_tip' ),
2537 'image' => $wgLang->getImageFile( 'button-math' ),
2538 'id' => 'mw-editbutton-math',
2540 'close' => "</math>",
2541 'sample' => wfMsg( 'math_sample' ),
2542 'tip' => wfMsg( 'math_tip' ),
2546 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2547 'id' => 'mw-editbutton-nowiki',
2548 'open' => "<nowiki>",
2549 'close' => "</nowiki>",
2550 'sample' => wfMsg( 'nowiki_sample' ),
2551 'tip' => wfMsg( 'nowiki_tip' ),
2555 'image' => $wgLang->getImageFile( 'button-sig' ),
2556 'id' => 'mw-editbutton-signature',
2560 'tip' => wfMsg( 'sig_tip' ),
2564 'image' => $wgLang->getImageFile( 'button-hr' ),
2565 'id' => 'mw-editbutton-hr',
2566 'open' => "\n----\n",
2569 'tip' => wfMsg( 'hr_tip' ),
2575 foreach ( $toolarray as $tool ) {
2581 $image = $wgStylePath . '/common/images/' . $tool['image'],
2582 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2583 // Older browsers show a "speedtip" type message only for ALT.
2584 // Ideally these should be different, realistically they
2585 // probably don't need to be.
2586 $tip = $tool['tip'],
2587 $open = $tool['open'],
2588 $close = $tool['close'],
2589 $sample = $tool['sample'],
2590 $cssId = $tool['id'],
2593 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2595 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2597 $toolbar = '<div id="toolbar"></div>';
2599 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2605 * Returns an array of html code of the following checkboxes:
2608 * @param $tabindex Current tabindex
2609 * @param $checked Array of checkbox => bool, where bool indicates the checked
2610 * status of the checkbox
2614 public function getCheckboxes( &$tabindex, $checked ) {
2617 $checkboxes = array();
2619 // don't show the minor edit checkbox if it's a new page or section
2620 if ( !$this->isNew
) {
2621 $checkboxes['minor'] = '';
2622 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2623 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2625 'tabindex' => ++
$tabindex,
2626 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2627 'id' => 'wpMinoredit',
2629 $checkboxes['minor'] =
2630 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2631 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2632 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2633 ">{$minorLabel}</label>";
2637 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2638 $checkboxes['watch'] = '';
2639 if ( $wgUser->isLoggedIn() ) {
2641 'tabindex' => ++
$tabindex,
2642 'accesskey' => wfMsg( 'accesskey-watch' ),
2643 'id' => 'wpWatchthis',
2645 $checkboxes['watch'] =
2646 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2647 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2648 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2649 ">{$watchLabel}</label>";
2651 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2656 * Returns an array of html code of the following buttons:
2657 * save, diff, preview and live
2659 * @param $tabindex Current tabindex
2663 public function getEditButtons( &$tabindex ) {
2670 'tabindex' => ++
$tabindex,
2671 'value' => wfMsg( 'savearticle' ),
2672 'accesskey' => wfMsg( 'accesskey-save' ),
2673 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2675 $buttons['save'] = Xml
::element('input', $temp, '');
2677 ++
$tabindex; // use the same for preview and live preview
2679 'id' => 'wpPreview',
2680 'name' => 'wpPreview',
2682 'tabindex' => $tabindex,
2683 'value' => wfMsg( 'showpreview' ),
2684 'accesskey' => wfMsg( 'accesskey-preview' ),
2685 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2687 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
2688 $buttons['live'] = '';
2694 'tabindex' => ++
$tabindex,
2695 'value' => wfMsg( 'showdiff' ),
2696 'accesskey' => wfMsg( 'accesskey-diff' ),
2697 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2699 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
2701 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2706 * Output preview text only. This can be sucked into the edit page
2707 * via JavaScript, and saves the server time rendering the skin as
2708 * well as theoretically being more robust on the client (doesn't
2709 * disturb the edit box's undo history, won't eat your text on
2712 * @todo This doesn't include category or interlanguage links.
2713 * Would need to enhance it a bit, <s>maybe wrap them in XML
2714 * or something...</s> that might also require more skin
2715 * initialization, so check whether that's a problem.
2717 function livePreview() {
2720 header( 'Content-type: text/xml; charset=utf-8' );
2721 header( 'Cache-control: no-cache' );
2723 $previewText = $this->getPreviewText();
2724 #$categories = $skin->getCategoryLinks();
2727 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2728 Xml
::tags( 'livepreview', null,
2729 Xml
::element( 'preview', null, $previewText )
2730 #. Xml::element( 'category', null, $categories )
2736 * Call the stock "user is blocked" page
2738 * @deprecated in 1.19; throw an exception directly instead
2740 function blockedPage() {
2743 throw new UserBlockedError( $wgUser->mBlock
);
2747 * Produce the stock "please login to edit pages" page
2749 * @deprecated in 1.19; throw an exception directly instead
2751 function userNotLoggedInPage() {
2752 throw new PermissionsError( 'edit' );
2756 * Show an error page saying to the user that he has insufficient permissions
2757 * to create a new page
2759 * @deprecated in 1.19; throw an exception directly instead
2761 function noCreatePermission() {
2762 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
2763 throw new PermissionsError( $permission );
2767 * Creates a basic error page which informs the user that
2768 * they have attempted to edit a nonexistent section.
2770 function noSuchSectionPage() {
2773 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
2775 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
2776 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2777 $wgOut->addHTML( $res );
2779 $wgOut->returnToMain( false, $this->mTitle
);
2783 * Produce the stock "your edit contains spam" page
2785 * @param $match Text which triggered one or more filters
2786 * @deprecated since 1.17 Use method spamPageWithContent() instead
2788 static function spamPage( $match = false ) {
2789 global $wgOut, $wgTitle;
2791 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2793 $wgOut->addHTML( '<div id="spamprotected">' );
2794 $wgOut->addWikiMsg( 'spamprotectiontext' );
2796 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2798 $wgOut->addHTML( '</div>' );
2800 $wgOut->returnToMain( false, $wgTitle );
2804 * Show "your edit contains spam" page with your diff and text
2806 * @param $match Text which triggered one or more filters
2808 public function spamPageWithContent( $match = false ) {
2810 $this->textbox2
= $this->textbox1
;
2812 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2814 $wgOut->addHTML( '<div id="spamprotected">' );
2815 $wgOut->addWikiMsg( 'spamprotectiontext' );
2817 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2819 $wgOut->addHTML( '</div>' );
2821 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2822 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2823 $de->setText( $this->getContent(), $this->textbox2
);
2824 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
2826 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2827 $this->showTextbox2();
2829 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
2833 * Format an anchor fragment as it would appear for a given section name
2834 * @param $text String
2838 function sectionAnchor( $text ) {
2840 return $wgParser->guessSectionNameFromWikiText( $text );
2844 * Check if the browser is on a blacklist of user-agents known to
2845 * mangle UTF-8 data on form submission. Returns true if Unicode
2846 * should make it through, false if it's known to be a problem.
2850 function checkUnicodeCompliantBrowser() {
2851 global $wgBrowserBlackList;
2852 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2853 // No User-Agent header sent? Trust it by default...
2856 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2857 foreach ( $wgBrowserBlackList as $browser ) {
2858 if ( preg_match($browser, $currentbrowser) ) {
2866 * Filter an input field through a Unicode de-armoring process if it
2867 * came from an old browser with known broken Unicode editing issues.
2869 * @param $request WebRequest
2870 * @param $field String
2874 function safeUnicodeInput( $request, $field ) {
2875 $text = rtrim( $request->getText( $field ) );
2876 return $request->getBool( 'safemode' )
2877 ?
$this->unmakesafe( $text )
2882 * @param $request WebRequest
2883 * @param $text string
2886 function safeUnicodeText( $request, $text ) {
2887 $text = rtrim( $text );
2888 return $request->getBool( 'safemode' )
2889 ?
$this->unmakesafe( $text )
2894 * Filter an output field through a Unicode armoring process if it is
2895 * going to an old browser with known broken Unicode editing issues.
2897 * @param $text String
2901 function safeUnicodeOutput( $text ) {
2903 $codedText = $wgContLang->recodeForEdit( $text );
2904 return $this->checkUnicodeCompliantBrowser()
2906 : $this->makesafe( $codedText );
2910 * A number of web browsers are known to corrupt non-ASCII characters
2911 * in a UTF-8 text editing environment. To protect against this,
2912 * detected browsers will be served an armored version of the text,
2913 * with non-ASCII chars converted to numeric HTML character references.
2915 * Preexisting such character references will have a 0 added to them
2916 * to ensure that round-trips do not alter the original data.
2918 * @param $invalue String
2922 function makesafe( $invalue ) {
2923 // Armor existing references for reversability.
2924 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2929 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2930 $bytevalue = ord( $invalue[$i] );
2931 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2932 $result .= chr( $bytevalue );
2934 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2935 $working = $working << 6;
2936 $working +
= ($bytevalue & 0x3F);
2938 if ( $bytesleft <= 0 ) {
2939 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2941 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2942 $working = $bytevalue & 0x1F;
2944 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2945 $working = $bytevalue & 0x0F;
2947 } else { //1111 0xxx
2948 $working = $bytevalue & 0x07;
2956 * Reverse the previously applied transliteration of non-ASCII characters
2957 * back to UTF-8. Used to protect data from corruption by broken web browsers
2958 * as listed in $wgBrowserBlackList.
2960 * @param $invalue String
2964 function unmakesafe( $invalue ) {
2966 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2967 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+
3] != '0' ) ) {
2971 $hexstring .= $invalue[$i];
2973 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
2975 // Do some sanity checks. These aren't needed for reversability,
2976 // but should help keep the breakage down if the editor
2977 // breaks one of the entities whilst editing.
2978 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2979 $codepoint = hexdec($hexstring);
2980 $result .= codepointToUtf8( $codepoint );
2982 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2985 $result .= substr( $invalue, $i, 1 );
2988 // reverse the transform that we made for reversability reasons.
2989 return strtr( $result, array( "�" => "&#x" ) );