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 wfDeprecated( __METHOD__
, '1.19' );
411 global $wgRequest, $wgOut;
412 if ( $wgRequest->getBool( 'redlink' ) ) {
413 // The edit page was reached via a red link.
414 // Redirect to the article page and let them click the edit tab if
415 // they really want a permission error.
416 $wgOut->redirect( $this->mTitle
->getFullUrl() );
418 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
423 * Should we show a preview when the edit form is first shown?
427 protected function previewOnOpen() {
428 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
429 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
430 // Explicit override from request
432 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
433 // Explicit override from request
435 } elseif ( $this->section
== 'new' ) {
436 // Nothing *to* preview for new sections
438 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
439 // Standard preference behaviour
441 } elseif ( !$this->mTitle
->exists() &&
442 isset($wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]) &&
443 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
445 // Categories are special
453 * Checks whether the user entered a skin name in uppercase,
454 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
458 protected function isWrongCaseCssJsPage() {
459 if( $this->mTitle
->isCssJsSubpage() ) {
460 $name = $this->mTitle
->getSkinFromCssJsSubpage();
461 $skins = array_merge(
462 array_keys( Skin
::getSkinNames() ),
465 return !in_array( $name, $skins )
466 && in_array( strtolower( $name ), $skins );
473 * Does this EditPage class support section editing?
474 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
478 protected function isSectionEditSupported() {
484 * @param $request WebRequest
486 function importFormData( &$request ) {
487 global $wgLang, $wgUser;
489 wfProfileIn( __METHOD__
);
491 # Section edit can come from either the form or a link
492 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
494 if ( $request->wasPosted() ) {
495 # These fields need to be checked for encoding.
496 # Also remove trailing whitespace, but don't remove _initial_
497 # whitespace from the text boxes. This may be significant formatting.
498 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
499 if ( !$request->getCheck('wpTextbox2') ) {
500 // Skip this if wpTextbox2 has input, it indicates that we came
501 // from a conflict page with raw page text, not a custom form
502 // modified by subclasses
503 wfProfileIn( get_class($this)."::importContentFormData" );
504 $textbox1 = $this->importContentFormData( $request );
505 if ( isset($textbox1) )
506 $this->textbox1
= $textbox1;
507 wfProfileOut( get_class($this)."::importContentFormData" );
510 # Truncate for whole multibyte characters. +5 bytes for ellipsis
511 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
513 # Remove extra headings from summaries and new sections.
514 $this->summary
= preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
516 $this->edittime
= $request->getVal( 'wpEdittime' );
517 $this->starttime
= $request->getVal( 'wpStarttime' );
519 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
521 if ($this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null) {
522 // wpTextbox1 field is missing, possibly due to being "too big"
523 // according to some filter rules such as Suhosin's setting for
524 // suhosin.request.max_value_length (d'oh)
525 $this->incompleteForm
= true;
527 // edittime should be one of our last fields; if it's missing,
528 // the submission probably broke somewhere in the middle.
529 $this->incompleteForm
= is_null( $this->edittime
);
531 if ( $this->incompleteForm
) {
532 # If the form is incomplete, force to preview.
533 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
534 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
535 $this->preview
= true;
537 /* Fallback for live preview */
538 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
539 $this->diff
= $request->getCheck( 'wpDiff' );
541 // Remember whether a save was requested, so we can indicate
542 // if we forced preview due to session failure.
543 $this->mTriedSave
= !$this->preview
;
545 if ( $this->tokenOk( $request ) ) {
546 # Some browsers will not report any submit button
547 # if the user hits enter in the comment box.
548 # The unmarked state will be assumed to be a save,
549 # if the form seems otherwise complete.
550 wfDebug( __METHOD__
. ": Passed token check.\n" );
551 } elseif ( $this->diff
) {
552 # Failed token check, but only requested "Show Changes".
553 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
555 # Page might be a hack attempt posted from
556 # an external site. Preview instead of saving.
557 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
558 $this->preview
= true;
561 $this->save
= !$this->preview
&& !$this->diff
;
562 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
563 $this->edittime
= null;
566 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
567 $this->starttime
= null;
570 $this->recreate
= $request->getCheck( 'wpRecreate' );
572 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
573 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
575 # Don't force edit summaries when a user is editing their own user or talk page
576 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
577 $this->mTitle
->getText() == $wgUser->getName() )
579 $this->allowBlankSummary
= true;
581 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
584 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
586 # Not a posted form? Start with nothing.
587 wfDebug( __METHOD__
. ": Not a posted form.\n" );
588 $this->textbox1
= '';
590 $this->edittime
= '';
591 $this->starttime
= wfTimestampNow();
593 $this->preview
= false;
596 $this->minoredit
= false;
597 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
598 $this->recreate
= false;
600 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
601 $this->summary
= $request->getVal( 'preloadtitle' );
603 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
604 $this->summary
= $request->getText( 'summary' );
607 if ( $request->getVal( 'minor' ) ) {
608 $this->minoredit
= true;
612 $this->bot
= $request->getBool( 'bot', true );
613 $this->nosummary
= $request->getBool( 'nosummary' );
615 // @todo FIXME: Unused variable?
616 $this->oldid
= $request->getInt( 'oldid' );
618 $this->live
= $request->getCheck( 'live' );
619 $this->editintro
= $request->getText( 'editintro',
620 // Custom edit intro for new sections
621 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
623 // Allow extensions to modify form data
624 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
626 wfProfileOut( __METHOD__
);
630 * Subpage overridable method for extracting the page content data from the
631 * posted form to be placed in $this->textbox1, if using customized input
632 * this method should be overrided and return the page text that will be used
633 * for saving, preview parsing and so on...
635 * @param $request WebRequest
637 protected function importContentFormData( &$request ) {
638 return; // Don't do anything, EditPage already extracted wpTextbox1
642 * Initialise form fields in the object
643 * Called on the first invocation, e.g. when a user clicks an edit link
644 * @return bool -- if the requested section is valid
646 function initialiseForm() {
648 $this->edittime
= $this->mArticle
->getTimestamp();
649 $this->textbox1
= $this->getContent( false );
650 // activate checkboxes if user wants them to be always active
651 # Sort out the "watch" checkbox
652 if ( $wgUser->getOption( 'watchdefault' ) ) {
654 $this->watchthis
= true;
655 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
657 $this->watchthis
= true;
658 } elseif ( $this->mTitle
->userIsWatching() ) {
660 $this->watchthis
= true;
662 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
663 $this->minoredit
= true;
665 if ( $this->textbox1
=== false ) {
673 * Fetch initial editing page content.
675 * @param $def_text string
676 * @return mixed string on success, $def_text for invalid sections
679 function getContent( $def_text = '' ) {
680 global $wgOut, $wgRequest, $wgParser;
682 wfProfileIn( __METHOD__
);
683 # Get variables from query string :P
684 $section = $wgRequest->getVal( 'section' );
686 $preload = $wgRequest->getVal( 'preload',
687 // Custom preload text for new sections
688 $section === 'new' ?
'MediaWiki:addsection-preload' : '' );
689 $undoafter = $wgRequest->getVal( 'undoafter' );
690 $undo = $wgRequest->getVal( 'undo' );
692 // For message page not locally set, use the i18n message.
693 // For other non-existent articles, use preload text if any.
694 if ( !$this->mTitle
->exists() ) {
695 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
696 # If this is a system message, get the default text.
697 $text = $this->mTitle
->getDefaultMessageText();
698 if( $text === false ) {
699 $text = $this->getPreloadedText( $preload );
702 # If requested, preload some text.
703 $text = $this->getPreloadedText( $preload );
705 // For existing pages, get text based on "undo" or section parameters.
707 $text = $this->mArticle
->getContent();
708 if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
709 # If they got undoafter and undo round the wrong way, switch them
710 list( $undo, $undoafter ) = array( $undoafter, $undo );
712 if ( $undo > 0 && $undo > $undoafter ) {
713 # Undoing a specific edit overrides section editing; section-editing
714 # doesn't work with undoing.
716 $undorev = Revision
::newFromId( $undo );
717 $oldrev = Revision
::newFromId( $undoafter );
719 $undorev = Revision
::newFromId( $undo );
720 $oldrev = $undorev ?
$undorev->getPrevious() : null;
723 # Sanity check, make sure it's the right page,
724 # the revisions exist and they were not deleted.
725 # Otherwise, $text will be left as-is.
726 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
727 $undorev->getPage() == $oldrev->getPage() &&
728 $undorev->getPage() == $this->mArticle
->getID() &&
729 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
730 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
732 $undotext = $this->mArticle
->getUndoText( $undorev, $oldrev );
733 if ( $undotext === false ) {
734 # Warn the user that something went wrong
735 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-failure">' .
736 wfMsgNoTrans( 'undo-failure' ) . '</div>', true, /* interface */true );
739 # Inform the user of our success and set an automatic edit summary
740 $this->editFormPageTop
.= $wgOut->parse( '<div class="mw-undo-success">' .
741 wfMsgNoTrans( 'undo-success' ) . '</div>', true, /* interface */true );
742 $firstrev = $oldrev->getNext();
743 # If we just undid one rev, use an autosummary
744 if ( $firstrev->getId() == $undo ) {
745 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
746 if ( $this->summary
=== '' ) {
747 $this->summary
= $undoSummary;
749 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
751 $this->undidRev
= $undo;
753 $this->formtype
= 'diff';
756 // Failed basic sanity checks.
757 // Older revisions may have been removed since the link
758 // was created, or we may simply have got bogus input.
759 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-norev">' .
760 wfMsgNoTrans( 'undo-norev' ) . '</div>', true, /* interface */true );
762 } elseif ( $section != '' ) {
763 if ( $section == 'new' ) {
764 $text = $this->getPreloadedText( $preload );
766 // Get section edit text (returns $def_text for invalid sections)
767 $text = $wgParser->getSection( $text, $section, $def_text );
772 wfProfileOut( __METHOD__
);
777 * Use this method before edit() to preload some text into the edit box
779 * @param $text string
781 public function setPreloadedText( $text ) {
782 $this->mPreloadText
= $text;
786 * Get the contents to be preloaded into the box, either set by
787 * an earlier setPreloadText() or by loading the given page.
789 * @param $preload String: representing the title to preload from.
792 protected function getPreloadedText( $preload ) {
793 global $wgUser, $wgParser;
795 if ( !empty( $this->mPreloadText
) ) {
796 return $this->mPreloadText
;
799 if ( $preload === '' ) {
803 $title = Title
::newFromText( $preload );
804 # Check for existence to avoid getting MediaWiki:Noarticletext
805 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
809 $page = WikiPage
::factory( $title );
810 if ( $page->isRedirect() ) {
811 $title = $page->getRedirectTarget();
813 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
816 $page = WikiPage
::factory( $title );
819 $parserOptions = ParserOptions
::newFromUser( $wgUser );
820 return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
824 * Make sure the form isn't faking a user's credentials.
826 * @param $request WebRequest
830 function tokenOk( &$request ) {
832 $token = $request->getVal( 'wpEditToken' );
833 $this->mTokenOk
= $wgUser->matchEditToken( $token );
834 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
835 return $this->mTokenOk
;
840 * @return bool false if output is done, true if the rest of the form should be displayed
842 function attemptSave() {
843 global $wgUser, $wgOut;
845 $resultDetails = false;
846 # Allow bots to exempt some edits from bot flagging
847 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
848 $status = $this->internalAttemptSave( $resultDetails, $bot );
849 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
851 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
852 $this->didSave
= true;
855 switch ( $status->value
) {
856 case self
::AS_HOOK_ERROR_EXPECTED
:
857 case self
::AS_CONTENT_TOO_BIG
:
858 case self
::AS_ARTICLE_WAS_DELETED
:
859 case self
::AS_CONFLICT_DETECTED
:
860 case self
::AS_SUMMARY_NEEDED
:
861 case self
::AS_TEXTBOX_EMPTY
:
862 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
866 case self
::AS_HOOK_ERROR
:
867 case self
::AS_FILTERING
:
870 case self
::AS_SUCCESS_NEW_ARTICLE
:
871 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
872 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
873 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
876 case self
::AS_SUCCESS_UPDATE
:
878 $sectionanchor = $resultDetails['sectionanchor'];
880 // Give extensions a chance to modify URL query on update
881 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
883 if ( $resultDetails['redirect'] ) {
884 if ( $extraQuery == '' ) {
885 $extraQuery = 'redirect=no';
887 $extraQuery = 'redirect=no&' . $extraQuery;
890 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
893 case self
::AS_BLANK_ARTICLE
:
894 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
897 case self
::AS_SPAM_ERROR
:
898 $this->spamPageWithContent( $resultDetails['spam'] );
901 case self
::AS_BLOCKED_PAGE_FOR_USER
:
902 throw new UserBlockedError( $wgUser->mBlock
);
904 case self
::AS_IMAGE_REDIRECT_ANON
:
905 case self
::AS_IMAGE_REDIRECT_LOGGED
:
906 throw new PermissionsError( 'upload' );
908 case self
::AS_READ_ONLY_PAGE_ANON
:
909 case self
::AS_READ_ONLY_PAGE_LOGGED
:
910 throw new PermissionsError( 'edit' );
912 case self
::AS_READ_ONLY_PAGE
:
913 throw new ReadOnlyError
;
915 case self
::AS_RATE_LIMITED
:
916 throw new ThrottledError();
918 case self
::AS_NO_CREATE_PERMISSION
:
919 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
920 throw new PermissionsError( $permission );
927 * Attempt submission (no UI)
932 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
934 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
935 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
936 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
938 function internalAttemptSave( &$result, $bot = false ) {
939 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
940 global $wgMaxArticleSize;
942 $status = Status
::newGood();
944 wfProfileIn( __METHOD__
);
945 wfProfileIn( __METHOD__
. '-checks' );
947 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
948 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
949 $status->fatal( 'hookaborted' );
950 $status->value
= self
::AS_HOOK_ERROR
;
951 wfProfileOut( __METHOD__
. '-checks' );
952 wfProfileOut( __METHOD__
);
956 # Check image redirect
957 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
958 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
959 !$wgUser->isAllowed( 'upload' ) ) {
960 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
961 $status->setResult( false, $code );
963 wfProfileOut( __METHOD__
. '-checks' );
964 wfProfileOut( __METHOD__
);
970 $match = self
::matchSummarySpamRegex( $this->summary
);
971 if ( $match === false ) {
972 $match = self
::matchSpamRegex( $this->textbox1
);
974 if ( $match !== false ) {
975 $result['spam'] = $match;
976 $ip = $wgRequest->getIP();
977 $pdbk = $this->mTitle
->getPrefixedDBkey();
978 $match = str_replace( "\n", '', $match );
979 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
980 $status->fatal( 'spamprotectionmatch', $match );
981 $status->value
= self
::AS_SPAM_ERROR
;
982 wfProfileOut( __METHOD__
. '-checks' );
983 wfProfileOut( __METHOD__
);
986 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
987 # Error messages or other handling should be performed by the filter function
988 $status->setResult( false, self
::AS_FILTERING
);
989 wfProfileOut( __METHOD__
. '-checks' );
990 wfProfileOut( __METHOD__
);
993 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
994 # Error messages etc. could be handled within the hook...
995 $status->fatal( 'hookaborted' );
996 $status->value
= self
::AS_HOOK_ERROR
;
997 wfProfileOut( __METHOD__
. '-checks' );
998 wfProfileOut( __METHOD__
);
1000 } elseif ( $this->hookError
!= '' ) {
1001 # ...or the hook could be expecting us to produce an error
1002 $status->fatal( 'hookaborted' );
1003 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1004 wfProfileOut( __METHOD__
. '-checks' );
1005 wfProfileOut( __METHOD__
);
1009 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1010 // Auto-block user's IP if the account was "hard" blocked
1011 $wgUser->spreadAnyEditBlock();
1012 # Check block state against master, thus 'false'.
1013 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1014 wfProfileOut( __METHOD__
. '-checks' );
1015 wfProfileOut( __METHOD__
);
1019 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1020 if ( $this->kblength
> $wgMaxArticleSize ) {
1021 // Error will be displayed by showEditForm()
1022 $this->tooBig
= true;
1023 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1024 wfProfileOut( __METHOD__
. '-checks' );
1025 wfProfileOut( __METHOD__
);
1029 if ( !$wgUser->isAllowed( 'edit' ) ) {
1030 if ( $wgUser->isAnon() ) {
1031 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1032 wfProfileOut( __METHOD__
. '-checks' );
1033 wfProfileOut( __METHOD__
);
1036 $status->fatal( 'readonlytext' );
1037 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1038 wfProfileOut( __METHOD__
. '-checks' );
1039 wfProfileOut( __METHOD__
);
1044 if ( wfReadOnly() ) {
1045 $status->fatal( 'readonlytext' );
1046 $status->value
= self
::AS_READ_ONLY_PAGE
;
1047 wfProfileOut( __METHOD__
. '-checks' );
1048 wfProfileOut( __METHOD__
);
1051 if ( $wgUser->pingLimiter() ) {
1052 $status->fatal( 'actionthrottledtext' );
1053 $status->value
= self
::AS_RATE_LIMITED
;
1054 wfProfileOut( __METHOD__
. '-checks' );
1055 wfProfileOut( __METHOD__
);
1059 # If the article has been deleted while editing, don't save it without
1061 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1062 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1063 wfProfileOut( __METHOD__
. '-checks' );
1064 wfProfileOut( __METHOD__
);
1068 wfProfileOut( __METHOD__
. '-checks' );
1070 # If article is new, insert it.
1071 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1072 $new = ( $aid == 0 );
1075 // Late check for create permission, just in case *PARANOIA*
1076 if ( !$this->mTitle
->userCan( 'create' ) ) {
1077 $status->fatal( 'nocreatetext' );
1078 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1079 wfDebug( __METHOD__
. ": no create permission\n" );
1080 wfProfileOut( __METHOD__
);
1084 # Don't save a new article if it's blank.
1085 if ( $this->textbox1
== '' ) {
1086 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1087 wfProfileOut( __METHOD__
);
1091 // Run post-section-merge edit filter
1092 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1093 # Error messages etc. could be handled within the hook...
1094 $status->fatal( 'hookaborted' );
1095 $status->value
= self
::AS_HOOK_ERROR
;
1096 wfProfileOut( __METHOD__
);
1098 } elseif ( $this->hookError
!= '' ) {
1099 # ...or the hook could be expecting us to produce an error
1100 $status->fatal( 'hookaborted' );
1101 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1102 wfProfileOut( __METHOD__
);
1106 # Handle the user preference to force summaries here. Check if it's not a redirect.
1107 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
1108 if ( md5( $this->summary
) == $this->autoSumm
) {
1109 $this->missingSummary
= true;
1110 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1111 $status->value
= self
::AS_SUMMARY_NEEDED
;
1112 wfProfileOut( __METHOD__
);
1117 $text = $this->textbox1
;
1118 $result['sectionanchor'] == '';
1119 if ( $this->section
== 'new' && $this->summary
!= '' ) {
1120 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $text;
1122 # Jump to the new section
1123 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1125 # This is a new section, so create a link to the new section
1126 # in the revision summary.
1127 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1128 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1131 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1135 # Article exists. Check for edit conflict.
1137 $this->mArticle
->clear(); # Force reload of dates, etc.
1139 wfDebug( "timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n" );
1141 if ( $this->mArticle
->getTimestamp() != $this->edittime
) {
1142 $this->isConflict
= true;
1143 if ( $this->section
== 'new' ) {
1144 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1145 $this->mArticle
->getComment() == $this->summary
) {
1146 // Probably a duplicate submission of a new comment.
1147 // This can happen when squid resends a request after
1148 // a timeout but the first one actually went through.
1149 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1151 // New comment; suppress conflict.
1152 $this->isConflict
= false;
1153 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1155 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1156 # Suppress edit conflict with self, except for section edits where merging is required.
1157 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1158 $this->isConflict
= false;
1162 if ( $this->isConflict
) {
1163 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
1164 $this->mArticle
->getTimestamp() . "')\n" );
1165 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1167 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1168 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
1170 if ( is_null( $text ) ) {
1171 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1172 $this->isConflict
= true;
1173 $text = $this->textbox1
; // do not try to merge here!
1174 } elseif ( $this->isConflict
) {
1176 if ( $this->mergeChangesInto( $text ) ) {
1177 // Successful merge! Maybe we should tell the user the good news?
1178 $this->isConflict
= false;
1179 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1181 $this->section
= '';
1182 $this->textbox1
= $text;
1183 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1187 if ( $this->isConflict
) {
1188 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1189 wfProfileOut( __METHOD__
);
1193 // Run post-section-merge edit filter
1194 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
1195 # Error messages etc. could be handled within the hook...
1196 $status->fatal( 'hookaborted' );
1197 $status->value
= self
::AS_HOOK_ERROR
;
1198 wfProfileOut( __METHOD__
);
1200 } elseif ( $this->hookError
!= '' ) {
1201 # ...or the hook could be expecting us to produce an error
1202 $status->fatal( 'hookaborted' );
1203 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1204 wfProfileOut( __METHOD__
);
1208 # Handle the user preference to force summaries here, but not for null edits
1209 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1210 && 0 != strcmp( $this->mArticle
->getContent(), $text )
1211 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1213 if ( md5( $this->summary
) == $this->autoSumm
) {
1214 $this->missingSummary
= true;
1215 $status->fatal( 'missingsummary' );
1216 $status->value
= self
::AS_SUMMARY_NEEDED
;
1217 wfProfileOut( __METHOD__
);
1222 # And a similar thing for new sections
1223 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1224 if ( trim( $this->summary
) == '' ) {
1225 $this->missingSummary
= true;
1226 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1227 $status->value
= self
::AS_SUMMARY_NEEDED
;
1228 wfProfileOut( __METHOD__
);
1234 wfProfileIn( __METHOD__
. '-sectionanchor' );
1235 $sectionanchor = '';
1236 if ( $this->section
== 'new' ) {
1237 if ( $this->textbox1
== '' ) {
1238 $this->missingComment
= true;
1239 $status->fatal( 'missingcommenttext' );
1240 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1241 wfProfileOut( __METHOD__
. '-sectionanchor' );
1242 wfProfileOut( __METHOD__
);
1245 if ( $this->summary
!= '' ) {
1246 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1247 # This is a new section, so create a link to the new section
1248 # in the revision summary.
1249 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1250 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1252 } elseif ( $this->section
!= '' ) {
1253 # Try to get a section anchor from the section source, redirect to edited section if header found
1254 # XXX: might be better to integrate this into Article::replaceSection
1255 # for duplicate heading checking and maybe parsing
1256 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1257 # we can't deal with anchors, includes, html etc in the header for now,
1258 # headline would need to be parsed to improve this
1259 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1260 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1263 $result['sectionanchor'] = $sectionanchor;
1264 wfProfileOut( __METHOD__
. '-sectionanchor' );
1266 // Save errors may fall down to the edit form, but we've now
1267 // merged the section into full text. Clear the section field
1268 // so that later submission of conflict forms won't try to
1269 // replace that into a duplicated mess.
1270 $this->textbox1
= $text;
1271 $this->section
= '';
1273 $status->value
= self
::AS_SUCCESS_UPDATE
;
1276 // Check for length errors again now that the section is merged in
1277 $this->kblength
= (int)( strlen( $text ) / 1024 );
1278 if ( $this->kblength
> $wgMaxArticleSize ) {
1279 $this->tooBig
= true;
1280 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1281 wfProfileOut( __METHOD__
);
1285 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1286 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1287 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1288 ( $bot ? EDIT_FORCE_BOT
: 0 );
1290 $doEditStatus = $this->mArticle
->doEdit( $text, $this->summary
, $flags );
1292 if ( $doEditStatus->isOK() ) {
1293 $result['redirect'] = Title
::newFromRedirect( $text ) !== null;
1294 $this->commitWatch();
1295 wfProfileOut( __METHOD__
);
1298 $this->isConflict
= true;
1299 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1300 wfProfileOut( __METHOD__
);
1301 return $doEditStatus;
1306 * Commit the change of watch status
1308 protected function commitWatch() {
1310 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1311 $dbw = wfGetDB( DB_MASTER
);
1313 if ( $this->watchthis
) {
1314 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1316 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1323 * Check if no edits were made by other users since
1324 * the time a user started editing the page. Limit to
1325 * 50 revisions for the sake of performance.
1328 * @param $edittime string
1332 protected function userWasLastToEdit( $id, $edittime ) {
1333 if( !$id ) return false;
1334 $dbw = wfGetDB( DB_MASTER
);
1335 $res = $dbw->select( 'revision',
1338 'rev_page' => $this->mArticle
->getId(),
1339 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1342 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1343 foreach ( $res as $row ) {
1344 if( $row->rev_user
!= $id ) {
1355 * @parma $editText string
1359 function mergeChangesInto( &$editText ){
1360 wfProfileIn( __METHOD__
);
1362 $db = wfGetDB( DB_MASTER
);
1364 // This is the revision the editor started from
1365 $baseRevision = $this->getBaseRevision();
1366 if ( is_null( $baseRevision ) ) {
1367 wfProfileOut( __METHOD__
);
1370 $baseText = $baseRevision->getText();
1372 // The current state, we want to merge updates into it
1373 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1374 if ( is_null( $currentRevision ) ) {
1375 wfProfileOut( __METHOD__
);
1378 $currentText = $currentRevision->getText();
1381 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1382 $editText = $result;
1383 wfProfileOut( __METHOD__
);
1386 wfProfileOut( __METHOD__
);
1394 function getBaseRevision() {
1395 if ( !$this->mBaseRevision
) {
1396 $db = wfGetDB( DB_MASTER
);
1397 $baseRevision = Revision
::loadFromTimestamp(
1398 $db, $this->mTitle
, $this->edittime
);
1399 return $this->mBaseRevision
= $baseRevision;
1401 return $this->mBaseRevision
;
1406 * Check given input text against $wgSpamRegex, and return the text of the first match.
1408 * @param $text string
1410 * @return string|false matching string or false
1412 public static function matchSpamRegex( $text ) {
1413 global $wgSpamRegex;
1414 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1415 $regexes = (array)$wgSpamRegex;
1416 return self
::matchSpamRegexInternal( $text, $regexes );
1420 * Check given input text against $wgSpamRegex, and return the text of the first match.
1422 * @parma $text string
1424 * @return string|false matching string or false
1426 public static function matchSummarySpamRegex( $text ) {
1427 global $wgSummarySpamRegex;
1428 $regexes = (array)$wgSummarySpamRegex;
1429 return self
::matchSpamRegexInternal( $text, $regexes );
1433 * @param $text string
1434 * @param $regexes array
1435 * @return bool|string
1437 protected static function matchSpamRegexInternal( $text, $regexes ) {
1438 foreach( $regexes as $regex ) {
1440 if( preg_match( $regex, $text, $matches ) ) {
1447 function setHeaders() {
1449 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1450 if ( $this->isConflict
) {
1451 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1452 } elseif ( $this->section
!= '' ) {
1453 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1454 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1456 # Use the title defined by DISPLAYTITLE magic word when present
1457 if ( isset( $this->mParserOutput
)
1458 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1461 $title = $this->getContextTitle()->getPrefixedText();
1463 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1468 * Show all applicable editing introductions
1470 protected function showIntro() {
1471 global $wgOut, $wgUser;
1472 if ( $this->suppressIntro
) {
1476 $namespace = $this->mTitle
->getNamespace();
1478 if ( $namespace == NS_MEDIAWIKI
) {
1479 # Show a warning if editing an interface message
1480 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1483 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1484 # Show log extract when the user is currently blocked
1485 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1486 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1487 $username = $parts[0];
1488 $user = User
::newFromName( $username, false /* allow IP users*/ );
1489 $ip = User
::isIP( $username );
1490 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1491 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1492 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1493 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1494 LogEventsList
::showLogExtract(
1497 $user->getUserPage(),
1501 'showIfEmpty' => false,
1503 'blocked-notice-logextract',
1504 $user->getName() # Support GENDER in notice
1510 # Try to add a custom edit intro, or use the standard one if this is not possible.
1511 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1512 if ( $wgUser->isLoggedIn() ) {
1513 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1515 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1518 # Give a notice if the user is editing a deleted/moved page...
1519 if ( !$this->mTitle
->exists() ) {
1520 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1521 '', array( 'lim' => 10,
1522 'conds' => array( "log_action != 'revision'" ),
1523 'showIfEmpty' => false,
1524 'msgKey' => array( 'recreate-moveddeleted-warn') )
1530 * Attempt to show a custom editing introduction, if supplied
1534 protected function showCustomIntro() {
1535 if ( $this->editintro
) {
1536 $title = Title
::newFromText( $this->editintro
);
1537 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1539 // Added using template syntax, to take <noinclude>'s into account.
1540 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1551 * Send the edit form and related headers to $wgOut
1552 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1553 * during form output near the top, for captchas and the like.
1555 function showEditForm( $formCallback = null ) {
1556 global $wgOut, $wgUser;
1558 wfProfileIn( __METHOD__
);
1560 #need to parse the preview early so that we know which templates are used,
1561 #otherwise users with "show preview after edit box" will get a blank list
1562 #we parse this near the beginning so that setHeaders can do the title
1563 #setting work instead of leaving it in getPreviewText
1564 $previewOutput = '';
1565 if ( $this->formtype
== 'preview' ) {
1566 $previewOutput = $this->getPreviewText();
1569 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1571 $this->setHeaders();
1573 # Enabled article-related sidebar, toplinks, etc.
1574 $wgOut->setArticleRelated( true );
1576 if ( $this->showHeader() === false ) {
1577 wfProfileOut( __METHOD__
);
1581 $action = htmlspecialchars( $this->getActionURL( $this->getContextTitle() ) );
1583 if ( $wgUser->getOption( 'showtoolbar' ) and !$this->isCssJsSubpage
) {
1584 # prepare toolbar for edit buttons
1585 $toolbar = EditPage
::getEditToolbar();
1591 $wgOut->addHTML( $this->editFormPageTop
);
1593 if ( $wgUser->getOption( 'previewontop' ) ) {
1594 $this->displayPreviewArea( $previewOutput, true );
1597 $wgOut->addHTML( $this->editFormTextTop
);
1599 $templates = $this->getTemplates();
1600 $formattedtemplates = Linker
::formatTemplates( $templates, $this->preview
, $this->section
!= '');
1602 $hiddencats = $this->mArticle
->getHiddenCategories();
1603 $formattedhiddencats = Linker
::formatHiddenCategories( $hiddencats );
1605 if ( $this->wasDeletedSinceLastEdit() && 'save' != $this->formtype
) {
1606 $wgOut->wrapWikiMsg(
1607 "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1608 'deletedwhileediting' );
1609 } elseif ( $this->wasDeletedSinceLastEdit() ) {
1610 // Hide the toolbar and edit area, user can click preview to get it back
1611 // Add an confirmation checkbox and explanation.
1613 // @todo move this to a cleaner conditional instead of blanking a variable
1615 $wgOut->addHTML( <<<HTML
1616 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1620 if ( is_callable( $formCallback ) ) {
1621 call_user_func_array( $formCallback, array( &$wgOut ) );
1624 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1626 // Put these up at the top to ensure they aren't lost on early form submission
1627 $this->showFormBeforeText();
1629 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1630 $username = $this->lastDelete
->user_name
;
1631 $comment = $this->lastDelete
->log_comment
;
1633 // It is better to not parse the comment at all than to have templates expanded in the middle
1634 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1635 $key = $comment === ''
1636 ?
'confirmrecreate-noreason'
1637 : 'confirmrecreate';
1639 '<div class="mw-confirm-recreate">' .
1640 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1641 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1642 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1648 # If a blank edit summary was previously provided, and the appropriate
1649 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1650 # user being bounced back more than once in the event that a summary
1653 # For a bit more sophisticated detection of blank summaries, hash the
1654 # automatic one and pass that in the hidden field wpAutoSummary.
1655 if ( $this->missingSummary ||
1656 ( $this->section
== 'new' && $this->nosummary
) )
1657 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1658 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1659 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1661 $wgOut->addHTML( Html
::hidden( 'oldid', $this->mArticle
->getOldID() ) );
1663 if ( $this->section
== 'new' ) {
1664 $this->showSummaryInput( true, $this->summary
);
1665 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1668 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1670 $wgOut->addHTML( $toolbar );
1672 if ( $this->isConflict
) {
1673 // In an edit conflict bypass the overrideable content form method
1674 // and fallback to the raw wpTextbox1 since editconflicts can't be
1675 // resolved between page source edits and custom ui edits using the
1677 $this->showTextbox1( null, $this->getContent() );
1679 $this->showContentForm();
1682 $wgOut->addHTML( $this->editFormTextAfterContent
);
1684 $wgOut->addWikiText( $this->getCopywarn() );
1685 if ( isset($this->editFormTextAfterWarn
) && $this->editFormTextAfterWarn
!== '' )
1686 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1688 $this->showStandardInputs();
1690 $this->showFormAfterText();
1692 $this->showTosSummary();
1693 $this->showEditTools();
1695 $wgOut->addHTML( <<<HTML
1696 {$this->editFormTextAfterTools}
1697 <div class='templatesUsed'>
1698 {$formattedtemplates}
1700 <div class='hiddencats'>
1701 {$formattedhiddencats}
1706 if ( $this->isConflict
)
1707 $this->showConflict();
1709 $wgOut->addHTML( $this->editFormTextBottom
);
1710 $wgOut->addHTML( "</form>\n" );
1711 if ( !$wgUser->getOption( 'previewontop' ) ) {
1712 $this->displayPreviewArea( $previewOutput, false );
1715 wfProfileOut( __METHOD__
);
1719 * Extract the section title from current section text, if any.
1721 * @param string $text
1722 * @return Mixed|string or false
1724 public static function extractSectionTitle( $text ) {
1725 preg_match( "/^(=+)(.+)\\1(\n|$)/i", $text, $matches );
1726 if ( !empty( $matches[2] ) ) {
1728 return $wgParser->stripSectionName(trim($matches[2]));
1734 protected function showHeader() {
1735 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1736 if ( $this->isConflict
) {
1737 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1738 $this->edittime
= $this->mArticle
->getTimestamp();
1740 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
1741 // We use $this->section to much before this and getVal('wgSection') directly in other places
1742 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1743 // Someone is welcome to try refactoring though
1744 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1748 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1750 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1751 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
1752 if ( $sectionTitle !== false ) {
1753 $this->summary
= "/* $sectionTitle */ ";
1758 if ( $this->missingComment
) {
1759 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1762 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1763 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1766 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1767 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1770 if ( $this->hookError
!== '' ) {
1771 $wgOut->addWikiText( $this->hookError
);
1774 if ( !$this->checkUnicodeCompliantBrowser() ) {
1775 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1778 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1779 // Let sysop know that this will make private content public if saved
1781 if ( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1782 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1783 } elseif ( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1784 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1787 if ( !$this->mArticle
->mRevision
->isCurrent() ) {
1788 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1789 $wgOut->addWikiMsg( 'editingold' );
1794 if ( wfReadOnly() ) {
1795 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1796 } elseif ( $wgUser->isAnon() ) {
1797 if ( $this->formtype
!= 'preview' ) {
1798 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1800 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
1803 if ( $this->isCssJsSubpage
) {
1804 # Check the skin exists
1805 if ( $this->isWrongCaseCssJsPage
) {
1806 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
1808 if ( $this->formtype
!== 'preview' ) {
1809 if ( $this->isCssSubpage
)
1810 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
1811 if ( $this->isJsSubpage
)
1812 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
1817 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
1818 # Is the title semi-protected?
1819 if ( $this->mTitle
->isSemiProtected() ) {
1820 $noticeMsg = 'semiprotectedpagewarning';
1822 # Then it must be protected based on static groups (regular)
1823 $noticeMsg = 'protectedpagewarning';
1825 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1826 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1828 if ( $this->mTitle
->isCascadeProtected() ) {
1829 # Is this page under cascading protection from some source pages?
1830 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1831 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
1832 $cascadeSourcesCount = count( $cascadeSources );
1833 if ( $cascadeSourcesCount > 0 ) {
1834 # Explain, and list the titles responsible
1835 foreach( $cascadeSources as $page ) {
1836 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1839 $notice .= '</div>';
1840 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1842 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1843 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1845 'showIfEmpty' => false,
1846 'msgKey' => array( 'titleprotectedwarning' ),
1847 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
1850 if ( $this->kblength
=== false ) {
1851 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1854 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1855 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
1856 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
1858 if( !wfMessage('longpage-hint')->isDisabled() ) {
1859 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
1860 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
1867 * Standard summary input and label (wgSummary), abstracted so EditPage
1868 * subclasses may reorganize the form.
1869 * Note that you do not need to worry about the label's for=, it will be
1870 * inferred by the id given to the input. You can remove them both by
1871 * passing array( 'id' => false ) to $userInputAttrs.
1873 * @param $summary string The value of the summary input
1874 * @param $labelText string The html to place inside the label
1875 * @param $inputAttrs array of attrs to use on the input
1876 * @param $spanLabelAttrs array of attrs to use on the span inside the label
1878 * @return array An array in the format array( $label, $input )
1880 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
1881 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
1882 $inputAttrs = ( is_array($inputAttrs) ?
$inputAttrs : array() ) +
array(
1883 'id' => 'wpSummary',
1884 'maxlength' => '200',
1887 'spellcheck' => 'true',
1888 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
1890 $spanLabelAttrs = ( is_array($spanLabelAttrs) ?
$spanLabelAttrs : array() ) +
array(
1891 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
1892 'id' => "wpSummaryLabel"
1897 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1898 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
1901 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
1903 return array( $label, $input );
1907 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1908 * up top, or false if this is the comment summary
1909 * down below the textarea
1910 * @param $summary String: The text of the summary to display
1913 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1914 global $wgOut, $wgContLang;
1915 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1916 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1917 if ( $isSubjectPreview ) {
1918 if ( $this->nosummary
) {
1922 if ( !$this->mShowSummaryField
) {
1926 $summary = $wgContLang->recodeForEdit( $summary );
1927 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
1928 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
1929 $wgOut->addHTML("{$label} {$input}");
1933 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1934 * up top, or false if this is the comment summary
1935 * down below the textarea
1936 * @param $summary String: the text of the summary to display
1939 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
1940 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
1945 if ( $isSubjectPreview )
1946 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
1948 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
1950 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
1951 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
1954 protected function showFormBeforeText() {
1956 $section = htmlspecialchars( $this->section
);
1957 $wgOut->addHTML( <<<HTML
1958 <input type='hidden' value="{$section}" name="wpSection" />
1959 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
1960 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
1961 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
1965 if ( !$this->checkUnicodeCompliantBrowser() )
1966 $wgOut->addHTML(Html
::hidden( 'safemode', '1' ));
1969 protected function showFormAfterText() {
1970 global $wgOut, $wgUser;
1972 * To make it harder for someone to slip a user a page
1973 * which submits an edit form to the wiki without their
1974 * knowledge, a random token is associated with the login
1975 * session. If it's not passed back with the submission,
1976 * we won't save the page, or render user JavaScript and
1979 * For anon editors, who may not have a session, we just
1980 * include the constant suffix to prevent editing from
1981 * broken text-mangling proxies.
1983 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
1987 * Subpage overridable method for printing the form for page content editing
1988 * By default this simply outputs wpTextbox1
1989 * Subclasses can override this to provide a custom UI for editing;
1990 * be it a form, or simply wpTextbox1 with a modified content that will be
1991 * reverse modified when extracted from the post data.
1992 * Note that this is basically the inverse for importContentFormData
1994 protected function showContentForm() {
1995 $this->showTextbox1();
1999 * Method to output wpTextbox1
2000 * The $textoverride method can be used by subclasses overriding showContentForm
2001 * to pass back to this method.
2003 * @param $customAttribs An array of html attributes to use in the textarea
2004 * @param $textoverride String: optional text to override $this->textarea1 with
2006 protected function showTextbox1($customAttribs = null, $textoverride = null) {
2007 $classes = array(); // Textarea CSS
2008 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2009 # Is the title semi-protected?
2010 if ( $this->mTitle
->isSemiProtected() ) {
2011 $classes[] = 'mw-textarea-sprotected';
2013 # Then it must be protected based on static groups (regular)
2014 $classes[] = 'mw-textarea-protected';
2016 # Is the title cascade-protected?
2017 if ( $this->mTitle
->isCascadeProtected() ) {
2018 $classes[] = 'mw-textarea-cprotected';
2021 $attribs = array( 'tabindex' => 1 );
2022 if ( is_array($customAttribs) )
2023 $attribs +
= $customAttribs;
2025 if ( $this->wasDeletedSinceLastEdit() )
2026 $attribs['type'] = 'hidden';
2027 if ( !empty( $classes ) ) {
2028 if ( isset($attribs['class']) )
2029 $classes[] = $attribs['class'];
2030 $attribs['class'] = implode( ' ', $classes );
2033 $this->showTextbox( isset($textoverride) ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2036 protected function showTextbox2() {
2037 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2040 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2041 global $wgOut, $wgUser;
2043 $wikitext = $this->safeUnicodeOutput( $content );
2044 if ( strval($wikitext) !== '' ) {
2045 // Ensure there's a newline at the end, otherwise adding lines
2047 // But don't add a newline if the ext is empty, or Firefox in XHTML
2048 // mode will show an extra newline. A bit annoying.
2052 $attribs = $customAttribs +
array(
2055 'cols' => $wgUser->getIntOption( 'cols' ),
2056 'rows' => $wgUser->getIntOption( 'rows' ),
2057 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2060 $pageLang = $this->mTitle
->getPageLanguage();
2061 $attribs['lang'] = $pageLang->getCode();
2062 $attribs['dir'] = $pageLang->getDir();
2064 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2067 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2071 $classes[] = 'ontop';
2073 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2075 if ( $this->formtype
!= 'preview' )
2076 $attribs['style'] = 'display: none;';
2078 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2080 if ( $this->formtype
== 'preview' ) {
2081 $this->showPreview( $previewOutput );
2084 $wgOut->addHTML( '</div>' );
2086 if ( $this->formtype
== 'diff') {
2092 * Append preview output to $wgOut.
2093 * Includes category rendering if this is a category page.
2095 * @param $text String: the HTML to be output for the preview.
2097 protected function showPreview( $text ) {
2099 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2100 $this->mArticle
->openShowCategory();
2102 # This hook seems slightly odd here, but makes things more
2103 # consistent for extensions.
2104 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
2105 $wgOut->addHTML( $text );
2106 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2107 $this->mArticle
->closeShowCategory();
2112 * Get a diff between the current contents of the edit box and the
2113 * version of the page we're editing from.
2115 * If this is a section edit, we'll replace the section as for final
2116 * save and then make a comparison.
2118 function showDiff() {
2119 global $wgUser, $wgContLang, $wgParser;
2121 $oldtext = $this->mArticle
->fetchContent();
2122 $newtext = $this->mArticle
->replaceSection(
2123 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2125 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2127 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2128 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle
, $wgUser, $popts );
2129 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2130 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2131 if ( $oldtext !== false ||
$newtext != '' ) {
2132 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2133 $de->setText( $oldtext, $newtext );
2134 $difftext = $de->getDiff( $oldtitle, $newtitle );
2135 $de->showDiffStyle();
2141 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2145 * Give a chance for site and per-namespace customizations of
2146 * terms of service summary link that might exist separately
2147 * from the copyright notice.
2149 * This will display between the save button and the edit tools,
2150 * so should remain short!
2152 protected function showTosSummary() {
2153 $msg = 'editpage-tos-summary';
2154 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2155 if( !wfMessage( $msg )->isDisabled() ) {
2157 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2158 $wgOut->addWikiMsg( $msg );
2159 $wgOut->addHTML( '</div>' );
2163 protected function showEditTools() {
2165 $wgOut->addHTML( '<div class="mw-editTools">' .
2166 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2170 protected function getCopywarn() {
2171 global $wgRightsText;
2172 if ( $wgRightsText ) {
2173 $copywarnMsg = array( 'copyrightwarning',
2174 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2177 $copywarnMsg = array( 'copyrightwarning2',
2178 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2180 // Allow for site and per-namespace customization of contribution/copyright notice.
2181 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2183 return "<div id=\"editpage-copywarn\">\n" .
2184 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
2187 protected function showStandardInputs( &$tabindex = 2 ) {
2189 $wgOut->addHTML( "<div class='editOptions'>\n" );
2191 if ( $this->section
!= 'new' ) {
2192 $this->showSummaryInput( false, $this->summary
);
2193 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2196 $checkboxes = $this->getCheckboxes( $tabindex,
2197 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2198 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2199 $wgOut->addHTML( "<div class='editButtons'>\n" );
2200 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2202 $cancel = $this->getCancelLink();
2203 if ( $cancel !== '' ) {
2204 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2206 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2207 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
2208 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
2209 htmlspecialchars( wfMsg( 'newwindow' ) );
2210 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2211 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2215 * Show an edit conflict. textbox1 is already shown in showEditForm().
2216 * If you want to use another entry point to this function, be careful.
2218 protected function showConflict() {
2220 $this->textbox2
= $this->textbox1
;
2221 $this->textbox1
= $this->getContent();
2222 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2223 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2225 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2226 $de->setText( $this->textbox2
, $this->textbox1
);
2227 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2229 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2230 $this->showTextbox2();
2237 public function getCancelLink() {
2238 $cancelParams = array();
2239 if ( !$this->isConflict
&& $this->mArticle
->getOldID() > 0 ) {
2240 $cancelParams['oldid'] = $this->mArticle
->getOldID();
2243 return Linker
::linkKnown(
2244 $this->getContextTitle(),
2245 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2246 array( 'id' => 'mw-editform-cancel' ),
2252 * Returns the URL to use in the form's action attribute.
2253 * This is used by EditPage subclasses when simply customizing the action
2254 * variable in the constructor is not enough. This can be used when the
2255 * EditPage lives inside of a Special page rather than a custom page action.
2257 * @param $title Title object for which is being edited (where we go to for &action= links)
2260 protected function getActionURL( Title
$title ) {
2261 return $title->getLocalURL( array( 'action' => $this->action
) );
2265 * Check if a page was deleted while the user was editing it, before submit.
2266 * Note that we rely on the logging table, which hasn't been always there,
2267 * but that doesn't matter, because this only applies to brand new
2270 protected function wasDeletedSinceLastEdit() {
2271 if ( $this->deletedSinceEdit
!== null ) {
2272 return $this->deletedSinceEdit
;
2275 $this->deletedSinceEdit
= false;
2277 if ( $this->mTitle
->isDeletedQuick() ) {
2278 $this->lastDelete
= $this->getLastDelete();
2279 if ( $this->lastDelete
) {
2280 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2281 if ( $deleteTime > $this->starttime
) {
2282 $this->deletedSinceEdit
= true;
2287 return $this->deletedSinceEdit
;
2290 protected function getLastDelete() {
2291 $dbr = wfGetDB( DB_SLAVE
);
2292 $data = $dbr->selectRow(
2293 array( 'logging', 'user' ),
2304 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2305 'log_title' => $this->mTitle
->getDBkey(),
2306 'log_type' => 'delete',
2307 'log_action' => 'delete',
2308 'user_id=log_user' ),
2310 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2312 // Quick paranoid permission checks...
2313 if( is_object( $data ) ) {
2314 if( $data->log_deleted
& LogPage
::DELETED_USER
)
2315 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2316 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2317 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2323 * Get the rendered text for previewing.
2326 function getPreviewText() {
2327 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2329 wfProfileIn( __METHOD__
);
2331 if ( $wgRawHtml && !$this->mTokenOk
) {
2332 // Could be an offsite preview attempt. This is very unsafe if
2333 // HTML is enabled, as it could be an attack.
2335 if ( $this->textbox1
!== '' ) {
2336 // Do not put big scary notice, if previewing the empty
2337 // string, which happens when you initially edit
2338 // a category page, due to automatic preview-on-open.
2339 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2340 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2342 wfProfileOut( __METHOD__
);
2346 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2347 if ( $this->mTokenOkExceptSuffix
) {
2348 $note = wfMsg( 'token_suffix_mismatch' );
2350 $note = wfMsg( 'session_fail_preview' );
2352 } elseif ( $this->incompleteForm
) {
2353 $note = wfMsg( 'edit_form_incomplete' );
2355 $note = wfMsg( 'previewnote' );
2358 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2359 $parserOptions->setEditSection( false );
2360 $parserOptions->setTidy( true );
2361 $parserOptions->setIsPreview( true );
2362 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2364 # don't parse non-wikitext pages, show message about preview
2365 # 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?
2367 if ( $this->isCssJsSubpage ||
!$this->mTitle
->isWikitextPage() ) {
2368 if( $this->mTitle
->isCssJsSubpage() ) {
2370 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2376 # Used messages to make sure grep find them:
2377 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2379 if (preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2380 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2381 $class = "mw-code mw-css";
2382 } elseif (preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2383 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2384 $class = "mw-code mw-js";
2386 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2390 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2391 $previewHTML = $parserOutput->mText
;
2392 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2394 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2396 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2398 $toparse = $this->textbox1
;
2400 # If we're adding a comment, we need to show the
2401 # summary as the headline
2402 if ( $this->section
== "new" && $this->summary
!= "" ) {
2403 $toparse = "== {$this->summary} ==\n\n" . $toparse;
2406 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2408 $parserOptions->enableLimitReport();
2410 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle
, $wgUser, $parserOptions );
2411 $parserOutput = $wgParser->parse( $toparse, $this->mTitle
, $parserOptions );
2413 $previewHTML = $parserOutput->getText();
2414 $this->mParserOutput
= $parserOutput;
2415 $wgOut->addParserOutputNoText( $parserOutput );
2417 if ( count( $parserOutput->getWarnings() ) ) {
2418 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2423 if( $this->isConflict
) {
2424 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2426 $conflict = '<hr />';
2429 $previewhead = "<div class='previewnote'>\n" .
2430 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2431 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2433 $pageLang = $this->mTitle
->getPageLanguage();
2434 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2435 'class' => 'mw-content-'.$pageLang->getDir() );
2436 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2438 wfProfileOut( __METHOD__
);
2439 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2445 function getTemplates() {
2446 if ( $this->preview ||
$this->section
!= '' ) {
2447 $templates = array();
2448 if ( !isset( $this->mParserOutput
) ) {
2451 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
2452 foreach( array_keys( $template ) as $dbk ) {
2453 $templates[] = Title
::makeTitle($ns, $dbk);
2458 return $this->mArticle
->getUsedTemplates();
2463 * Shows a bulletin board style toolbar for common editing functions.
2464 * It can be disabled in the user preferences.
2465 * The necessary JavaScript code can be found in skins/common/edit.js.
2469 static function getEditToolbar() {
2470 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2471 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2473 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2476 * $toolarray is an array of arrays each of which includes the
2477 * filename of the button image (without path), the opening
2478 * tag, the closing tag, optionally a sample text that is
2479 * inserted between the two when no selection is highlighted
2480 * and. The tip text is shown when the user moves the mouse
2483 * Also here: accesskeys (key), which are not used yet until
2484 * someone can figure out a way to make them work in
2485 * IE. However, we should make sure these keys are not defined
2490 'image' => $wgLang->getImageFile( 'button-bold' ),
2491 'id' => 'mw-editbutton-bold',
2493 'close' => '\'\'\'',
2494 'sample' => wfMsg( 'bold_sample' ),
2495 'tip' => wfMsg( 'bold_tip' ),
2499 'image' => $wgLang->getImageFile( 'button-italic' ),
2500 'id' => 'mw-editbutton-italic',
2503 'sample' => wfMsg( 'italic_sample' ),
2504 'tip' => wfMsg( 'italic_tip' ),
2508 'image' => $wgLang->getImageFile( 'button-link' ),
2509 'id' => 'mw-editbutton-link',
2512 'sample' => wfMsg( 'link_sample' ),
2513 'tip' => wfMsg( 'link_tip' ),
2517 'image' => $wgLang->getImageFile( 'button-extlink' ),
2518 'id' => 'mw-editbutton-extlink',
2521 'sample' => wfMsg( 'extlink_sample' ),
2522 'tip' => wfMsg( 'extlink_tip' ),
2526 'image' => $wgLang->getImageFile( 'button-headline' ),
2527 'id' => 'mw-editbutton-headline',
2530 'sample' => wfMsg( 'headline_sample' ),
2531 'tip' => wfMsg( 'headline_tip' ),
2534 $imagesAvailable ?
array(
2535 'image' => $wgLang->getImageFile( 'button-image' ),
2536 'id' => 'mw-editbutton-image',
2537 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2539 'sample' => wfMsg( 'image_sample' ),
2540 'tip' => wfMsg( 'image_tip' ),
2543 $imagesAvailable ?
array(
2544 'image' => $wgLang->getImageFile( 'button-media' ),
2545 'id' => 'mw-editbutton-media',
2546 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2548 'sample' => wfMsg( 'media_sample' ),
2549 'tip' => wfMsg( 'media_tip' ),
2553 'image' => $wgLang->getImageFile( 'button-math' ),
2554 'id' => 'mw-editbutton-math',
2556 'close' => "</math>",
2557 'sample' => wfMsg( 'math_sample' ),
2558 'tip' => wfMsg( 'math_tip' ),
2562 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2563 'id' => 'mw-editbutton-nowiki',
2564 'open' => "<nowiki>",
2565 'close' => "</nowiki>",
2566 'sample' => wfMsg( 'nowiki_sample' ),
2567 'tip' => wfMsg( 'nowiki_tip' ),
2571 'image' => $wgLang->getImageFile( 'button-sig' ),
2572 'id' => 'mw-editbutton-signature',
2576 'tip' => wfMsg( 'sig_tip' ),
2580 'image' => $wgLang->getImageFile( 'button-hr' ),
2581 'id' => 'mw-editbutton-hr',
2582 'open' => "\n----\n",
2585 'tip' => wfMsg( 'hr_tip' ),
2591 foreach ( $toolarray as $tool ) {
2597 $image = $wgStylePath . '/common/images/' . $tool['image'],
2598 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2599 // Older browsers show a "speedtip" type message only for ALT.
2600 // Ideally these should be different, realistically they
2601 // probably don't need to be.
2602 $tip = $tool['tip'],
2603 $open = $tool['open'],
2604 $close = $tool['close'],
2605 $sample = $tool['sample'],
2606 $cssId = $tool['id'],
2609 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2611 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2613 $toolbar = '<div id="toolbar"></div>';
2615 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2621 * Returns an array of html code of the following checkboxes:
2624 * @param $tabindex Current tabindex
2625 * @param $checked Array of checkbox => bool, where bool indicates the checked
2626 * status of the checkbox
2630 public function getCheckboxes( &$tabindex, $checked ) {
2633 $checkboxes = array();
2635 // don't show the minor edit checkbox if it's a new page or section
2636 if ( !$this->isNew
) {
2637 $checkboxes['minor'] = '';
2638 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2639 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2641 'tabindex' => ++
$tabindex,
2642 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2643 'id' => 'wpMinoredit',
2645 $checkboxes['minor'] =
2646 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2647 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2648 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2649 ">{$minorLabel}</label>";
2653 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2654 $checkboxes['watch'] = '';
2655 if ( $wgUser->isLoggedIn() ) {
2657 'tabindex' => ++
$tabindex,
2658 'accesskey' => wfMsg( 'accesskey-watch' ),
2659 'id' => 'wpWatchthis',
2661 $checkboxes['watch'] =
2662 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2663 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2664 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2665 ">{$watchLabel}</label>";
2667 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2672 * Returns an array of html code of the following buttons:
2673 * save, diff, preview and live
2675 * @param $tabindex Current tabindex
2679 public function getEditButtons( &$tabindex ) {
2686 'tabindex' => ++
$tabindex,
2687 'value' => wfMsg( 'savearticle' ),
2688 'accesskey' => wfMsg( 'accesskey-save' ),
2689 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2691 $buttons['save'] = Xml
::element('input', $temp, '');
2693 ++
$tabindex; // use the same for preview and live preview
2695 'id' => 'wpPreview',
2696 'name' => 'wpPreview',
2698 'tabindex' => $tabindex,
2699 'value' => wfMsg( 'showpreview' ),
2700 'accesskey' => wfMsg( 'accesskey-preview' ),
2701 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2703 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
2704 $buttons['live'] = '';
2710 'tabindex' => ++
$tabindex,
2711 'value' => wfMsg( 'showdiff' ),
2712 'accesskey' => wfMsg( 'accesskey-diff' ),
2713 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2715 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
2717 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2722 * Output preview text only. This can be sucked into the edit page
2723 * via JavaScript, and saves the server time rendering the skin as
2724 * well as theoretically being more robust on the client (doesn't
2725 * disturb the edit box's undo history, won't eat your text on
2728 * @todo This doesn't include category or interlanguage links.
2729 * Would need to enhance it a bit, <s>maybe wrap them in XML
2730 * or something...</s> that might also require more skin
2731 * initialization, so check whether that's a problem.
2733 function livePreview() {
2736 header( 'Content-type: text/xml; charset=utf-8' );
2737 header( 'Cache-control: no-cache' );
2739 $previewText = $this->getPreviewText();
2740 #$categories = $skin->getCategoryLinks();
2743 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2744 Xml
::tags( 'livepreview', null,
2745 Xml
::element( 'preview', null, $previewText )
2746 #. Xml::element( 'category', null, $categories )
2752 * Call the stock "user is blocked" page
2754 * @deprecated in 1.19; throw an exception directly instead
2756 function blockedPage() {
2757 wfDeprecated( __METHOD__
, '1.19' );
2760 throw new UserBlockedError( $wgUser->mBlock
);
2764 * Produce the stock "please login to edit pages" page
2766 * @deprecated in 1.19; throw an exception directly instead
2768 function userNotLoggedInPage() {
2769 wfDeprecated( __METHOD__
, '1.19' );
2770 throw new PermissionsError( 'edit' );
2774 * Show an error page saying to the user that he has insufficient permissions
2775 * to create a new page
2777 * @deprecated in 1.19; throw an exception directly instead
2779 function noCreatePermission() {
2780 wfDeprecated( __METHOD__
, '1.19' );
2781 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
2782 throw new PermissionsError( $permission );
2786 * Creates a basic error page which informs the user that
2787 * they have attempted to edit a nonexistent section.
2789 function noSuchSectionPage() {
2792 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
2794 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
2795 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2796 $wgOut->addHTML( $res );
2798 $wgOut->returnToMain( false, $this->mTitle
);
2802 * Produce the stock "your edit contains spam" page
2804 * @param $match Text which triggered one or more filters
2805 * @deprecated since 1.17 Use method spamPageWithContent() instead
2807 static function spamPage( $match = false ) {
2808 wfDeprecated( __METHOD__
, '1.17' );
2810 global $wgOut, $wgTitle;
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->returnToMain( false, $wgTitle );
2825 * Show "your edit contains spam" page with your diff and text
2827 * @param $match Text which triggered one or more filters
2829 public function spamPageWithContent( $match = false ) {
2831 $this->textbox2
= $this->textbox1
;
2833 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2835 $wgOut->addHTML( '<div id="spamprotected">' );
2836 $wgOut->addWikiMsg( 'spamprotectiontext' );
2838 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2840 $wgOut->addHTML( '</div>' );
2842 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2843 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2844 $de->setText( $this->getContent(), $this->textbox2
);
2845 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
2847 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2848 $this->showTextbox2();
2850 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
2854 * Format an anchor fragment as it would appear for a given section name
2855 * @param $text String
2859 function sectionAnchor( $text ) {
2861 return $wgParser->guessSectionNameFromWikiText( $text );
2865 * Check if the browser is on a blacklist of user-agents known to
2866 * mangle UTF-8 data on form submission. Returns true if Unicode
2867 * should make it through, false if it's known to be a problem.
2871 function checkUnicodeCompliantBrowser() {
2872 global $wgBrowserBlackList;
2873 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2874 // No User-Agent header sent? Trust it by default...
2877 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2878 foreach ( $wgBrowserBlackList as $browser ) {
2879 if ( preg_match($browser, $currentbrowser) ) {
2887 * Filter an input field through a Unicode de-armoring process if it
2888 * came from an old browser with known broken Unicode editing issues.
2890 * @param $request WebRequest
2891 * @param $field String
2895 function safeUnicodeInput( $request, $field ) {
2896 $text = rtrim( $request->getText( $field ) );
2897 return $request->getBool( 'safemode' )
2898 ?
$this->unmakesafe( $text )
2903 * @param $request WebRequest
2904 * @param $text string
2907 function safeUnicodeText( $request, $text ) {
2908 $text = rtrim( $text );
2909 return $request->getBool( 'safemode' )
2910 ?
$this->unmakesafe( $text )
2915 * Filter an output field through a Unicode armoring process if it is
2916 * going to an old browser with known broken Unicode editing issues.
2918 * @param $text String
2922 function safeUnicodeOutput( $text ) {
2924 $codedText = $wgContLang->recodeForEdit( $text );
2925 return $this->checkUnicodeCompliantBrowser()
2927 : $this->makesafe( $codedText );
2931 * A number of web browsers are known to corrupt non-ASCII characters
2932 * in a UTF-8 text editing environment. To protect against this,
2933 * detected browsers will be served an armored version of the text,
2934 * with non-ASCII chars converted to numeric HTML character references.
2936 * Preexisting such character references will have a 0 added to them
2937 * to ensure that round-trips do not alter the original data.
2939 * @param $invalue String
2943 function makesafe( $invalue ) {
2944 // Armor existing references for reversability.
2945 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2950 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2951 $bytevalue = ord( $invalue[$i] );
2952 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2953 $result .= chr( $bytevalue );
2955 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2956 $working = $working << 6;
2957 $working +
= ($bytevalue & 0x3F);
2959 if ( $bytesleft <= 0 ) {
2960 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2962 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2963 $working = $bytevalue & 0x1F;
2965 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2966 $working = $bytevalue & 0x0F;
2968 } else { //1111 0xxx
2969 $working = $bytevalue & 0x07;
2977 * Reverse the previously applied transliteration of non-ASCII characters
2978 * back to UTF-8. Used to protect data from corruption by broken web browsers
2979 * as listed in $wgBrowserBlackList.
2981 * @param $invalue String
2985 function unmakesafe( $invalue ) {
2987 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2988 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+
3] != '0' ) ) {
2992 $hexstring .= $invalue[$i];
2994 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
2996 // Do some sanity checks. These aren't needed for reversability,
2997 // but should help keep the breakage down if the editor
2998 // breaks one of the entities whilst editing.
2999 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
3000 $codepoint = hexdec($hexstring);
3001 $result .= codepointToUtf8( $codepoint );
3003 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3006 $result .= substr( $invalue, $i, 1 );
3009 // reverse the transform that we made for reversability reasons.
3010 return strtr( $result, array( "�" => "&#x" ) );