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 = '', $sectiontitle = '', $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() {
483 * This function collects the form data and uses it to populate various member variables.
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 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
514 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
516 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
518 # Treat sectiontitle the same way as summary.
519 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
520 # currently doing double duty as both edit summary and section title. Right now this
521 # is just to allow API edits to work around this limitation, but this should be
522 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
523 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 250 );
524 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
526 $this->edittime
= $request->getVal( 'wpEdittime' );
527 $this->starttime
= $request->getVal( 'wpStarttime' );
529 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
531 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
532 // wpTextbox1 field is missing, possibly due to being "too big"
533 // according to some filter rules such as Suhosin's setting for
534 // suhosin.request.max_value_length (d'oh)
535 $this->incompleteForm
= true;
537 // edittime should be one of our last fields; if it's missing,
538 // the submission probably broke somewhere in the middle.
539 $this->incompleteForm
= is_null( $this->edittime
);
541 if ( $this->incompleteForm
) {
542 # If the form is incomplete, force to preview.
543 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
544 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
545 $this->preview
= true;
547 /* Fallback for live preview */
548 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
549 $this->diff
= $request->getCheck( 'wpDiff' );
551 // Remember whether a save was requested, so we can indicate
552 // if we forced preview due to session failure.
553 $this->mTriedSave
= !$this->preview
;
555 if ( $this->tokenOk( $request ) ) {
556 # Some browsers will not report any submit button
557 # if the user hits enter in the comment box.
558 # The unmarked state will be assumed to be a save,
559 # if the form seems otherwise complete.
560 wfDebug( __METHOD__
. ": Passed token check.\n" );
561 } elseif ( $this->diff
) {
562 # Failed token check, but only requested "Show Changes".
563 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
565 # Page might be a hack attempt posted from
566 # an external site. Preview instead of saving.
567 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
568 $this->preview
= true;
571 $this->save
= !$this->preview
&& !$this->diff
;
572 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
573 $this->edittime
= null;
576 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
577 $this->starttime
= null;
580 $this->recreate
= $request->getCheck( 'wpRecreate' );
582 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
583 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
585 # Don't force edit summaries when a user is editing their own user or talk page
586 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
587 $this->mTitle
->getText() == $wgUser->getName() )
589 $this->allowBlankSummary
= true;
591 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
594 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
596 # Not a posted form? Start with nothing.
597 wfDebug( __METHOD__
. ": Not a posted form.\n" );
598 $this->textbox1
= '';
600 $this->sectiontitle
= '';
601 $this->edittime
= '';
602 $this->starttime
= wfTimestampNow();
604 $this->preview
= false;
607 $this->minoredit
= false;
608 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
609 $this->recreate
= false;
611 // When creating a new section, we can preload a section title by passing it as the
612 // preloadtitle parameter in the URL (Bug 13100)
613 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
614 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
615 // Once wpSummary isn't being use for setting section titles, we should delete this.
616 $this->summary
= $request->getVal( 'preloadtitle' );
618 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
619 $this->summary
= $request->getText( 'summary' );
622 if ( $request->getVal( 'minor' ) ) {
623 $this->minoredit
= true;
627 $this->bot
= $request->getBool( 'bot', true );
628 $this->nosummary
= $request->getBool( 'nosummary' );
630 // @todo FIXME: Unused variable?
631 $this->oldid
= $request->getInt( 'oldid' );
633 $this->live
= $request->getCheck( 'live' );
634 $this->editintro
= $request->getText( 'editintro',
635 // Custom edit intro for new sections
636 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
638 // Allow extensions to modify form data
639 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
641 wfProfileOut( __METHOD__
);
645 * Subpage overridable method for extracting the page content data from the
646 * posted form to be placed in $this->textbox1, if using customized input
647 * this method should be overrided and return the page text that will be used
648 * for saving, preview parsing and so on...
650 * @param $request WebRequest
652 protected function importContentFormData( &$request ) {
653 return; // Don't do anything, EditPage already extracted wpTextbox1
657 * Initialise form fields in the object
658 * Called on the first invocation, e.g. when a user clicks an edit link
659 * @return bool -- if the requested section is valid
661 function initialiseForm() {
663 $this->edittime
= $this->mArticle
->getTimestamp();
664 $this->textbox1
= $this->getContent( false );
665 // activate checkboxes if user wants them to be always active
666 # Sort out the "watch" checkbox
667 if ( $wgUser->getOption( 'watchdefault' ) ) {
669 $this->watchthis
= true;
670 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
672 $this->watchthis
= true;
673 } elseif ( $this->mTitle
->userIsWatching() ) {
675 $this->watchthis
= true;
677 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
678 $this->minoredit
= true;
680 if ( $this->textbox1
=== false ) {
688 * Fetch initial editing page content.
690 * @param $def_text string
691 * @return mixed string on success, $def_text for invalid sections
694 function getContent( $def_text = '' ) {
695 global $wgOut, $wgRequest, $wgParser;
697 wfProfileIn( __METHOD__
);
698 # Get variables from query string :P
699 $section = $wgRequest->getVal( 'section' );
701 $preload = $wgRequest->getVal( 'preload',
702 // Custom preload text for new sections
703 $section === 'new' ?
'MediaWiki:addsection-preload' : '' );
704 $undoafter = $wgRequest->getVal( 'undoafter' );
705 $undo = $wgRequest->getVal( 'undo' );
707 // For message page not locally set, use the i18n message.
708 // For other non-existent articles, use preload text if any.
709 if ( !$this->mTitle
->exists() ) {
710 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
711 # If this is a system message, get the default text.
712 $text = $this->mTitle
->getDefaultMessageText();
713 if( $text === false ) {
714 $text = $this->getPreloadedText( $preload );
717 # If requested, preload some text.
718 $text = $this->getPreloadedText( $preload );
720 // For existing pages, get text based on "undo" or section parameters.
722 $text = $this->mArticle
->getContent();
723 if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
724 # If they got undoafter and undo round the wrong way, switch them
725 list( $undo, $undoafter ) = array( $undoafter, $undo );
727 if ( $undo > 0 && $undo > $undoafter ) {
728 # Undoing a specific edit overrides section editing; section-editing
729 # doesn't work with undoing.
731 $undorev = Revision
::newFromId( $undo );
732 $oldrev = Revision
::newFromId( $undoafter );
734 $undorev = Revision
::newFromId( $undo );
735 $oldrev = $undorev ?
$undorev->getPrevious() : null;
738 # Sanity check, make sure it's the right page,
739 # the revisions exist and they were not deleted.
740 # Otherwise, $text will be left as-is.
741 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
742 $undorev->getPage() == $oldrev->getPage() &&
743 $undorev->getPage() == $this->mArticle
->getID() &&
744 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
745 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
747 $undotext = $this->mArticle
->getUndoText( $undorev, $oldrev );
748 if ( $undotext === false ) {
749 # Warn the user that something went wrong
750 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-failure">' .
751 wfMsgNoTrans( 'undo-failure' ) . '</div>', true, /* interface */true );
754 # Inform the user of our success and set an automatic edit summary
755 $this->editFormPageTop
.= $wgOut->parse( '<div class="mw-undo-success">' .
756 wfMsgNoTrans( 'undo-success' ) . '</div>', true, /* interface */true );
757 $firstrev = $oldrev->getNext();
758 # If we just undid one rev, use an autosummary
759 if ( $firstrev->getId() == $undo ) {
760 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
761 if ( $this->summary
=== '' ) {
762 $this->summary
= $undoSummary;
764 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
766 $this->undidRev
= $undo;
768 $this->formtype
= 'diff';
771 // Failed basic sanity checks.
772 // Older revisions may have been removed since the link
773 // was created, or we may simply have got bogus input.
774 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-norev">' .
775 wfMsgNoTrans( 'undo-norev' ) . '</div>', true, /* interface */true );
777 } elseif ( $section != '' ) {
778 if ( $section == 'new' ) {
779 $text = $this->getPreloadedText( $preload );
781 // Get section edit text (returns $def_text for invalid sections)
782 $text = $wgParser->getSection( $text, $section, $def_text );
787 wfProfileOut( __METHOD__
);
792 * Use this method before edit() to preload some text into the edit box
794 * @param $text string
796 public function setPreloadedText( $text ) {
797 $this->mPreloadText
= $text;
801 * Get the contents to be preloaded into the box, either set by
802 * an earlier setPreloadText() or by loading the given page.
804 * @param $preload String: representing the title to preload from.
807 protected function getPreloadedText( $preload ) {
808 global $wgUser, $wgParser;
810 if ( !empty( $this->mPreloadText
) ) {
811 return $this->mPreloadText
;
814 if ( $preload === '' ) {
818 $title = Title
::newFromText( $preload );
819 # Check for existence to avoid getting MediaWiki:Noarticletext
820 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
824 $page = WikiPage
::factory( $title );
825 if ( $page->isRedirect() ) {
826 $title = $page->getRedirectTarget();
828 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
831 $page = WikiPage
::factory( $title );
834 $parserOptions = ParserOptions
::newFromUser( $wgUser );
835 return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
839 * Make sure the form isn't faking a user's credentials.
841 * @param $request WebRequest
845 function tokenOk( &$request ) {
847 $token = $request->getVal( 'wpEditToken' );
848 $this->mTokenOk
= $wgUser->matchEditToken( $token );
849 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
850 return $this->mTokenOk
;
855 * @return bool false if output is done, true if the rest of the form should be displayed
857 function attemptSave() {
858 global $wgUser, $wgOut;
860 $resultDetails = false;
861 # Allow bots to exempt some edits from bot flagging
862 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
863 $status = $this->internalAttemptSave( $resultDetails, $bot );
864 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
866 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
867 $this->didSave
= true;
870 switch ( $status->value
) {
871 case self
::AS_HOOK_ERROR_EXPECTED
:
872 case self
::AS_CONTENT_TOO_BIG
:
873 case self
::AS_ARTICLE_WAS_DELETED
:
874 case self
::AS_CONFLICT_DETECTED
:
875 case self
::AS_SUMMARY_NEEDED
:
876 case self
::AS_TEXTBOX_EMPTY
:
877 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
881 case self
::AS_HOOK_ERROR
:
882 case self
::AS_FILTERING
:
885 case self
::AS_SUCCESS_NEW_ARTICLE
:
886 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
887 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
888 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
891 case self
::AS_SUCCESS_UPDATE
:
893 $sectionanchor = $resultDetails['sectionanchor'];
895 // Give extensions a chance to modify URL query on update
896 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
898 if ( $resultDetails['redirect'] ) {
899 if ( $extraQuery == '' ) {
900 $extraQuery = 'redirect=no';
902 $extraQuery = 'redirect=no&' . $extraQuery;
905 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
908 case self
::AS_BLANK_ARTICLE
:
909 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
912 case self
::AS_SPAM_ERROR
:
913 $this->spamPageWithContent( $resultDetails['spam'] );
916 case self
::AS_BLOCKED_PAGE_FOR_USER
:
917 throw new UserBlockedError( $wgUser->mBlock
);
919 case self
::AS_IMAGE_REDIRECT_ANON
:
920 case self
::AS_IMAGE_REDIRECT_LOGGED
:
921 throw new PermissionsError( 'upload' );
923 case self
::AS_READ_ONLY_PAGE_ANON
:
924 case self
::AS_READ_ONLY_PAGE_LOGGED
:
925 throw new PermissionsError( 'edit' );
927 case self
::AS_READ_ONLY_PAGE
:
928 throw new ReadOnlyError
;
930 case self
::AS_RATE_LIMITED
:
931 throw new ThrottledError();
933 case self
::AS_NO_CREATE_PERMISSION
:
934 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
935 throw new PermissionsError( $permission );
942 * Attempt submission (no UI)
947 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
949 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
950 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
951 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
953 function internalAttemptSave( &$result, $bot = false ) {
954 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
955 global $wgMaxArticleSize;
957 $status = Status
::newGood();
959 wfProfileIn( __METHOD__
);
960 wfProfileIn( __METHOD__
. '-checks' );
962 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
963 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
964 $status->fatal( 'hookaborted' );
965 $status->value
= self
::AS_HOOK_ERROR
;
966 wfProfileOut( __METHOD__
. '-checks' );
967 wfProfileOut( __METHOD__
);
971 # Check image redirect
972 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
973 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
974 !$wgUser->isAllowed( 'upload' ) ) {
975 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
976 $status->setResult( false, $code );
978 wfProfileOut( __METHOD__
. '-checks' );
979 wfProfileOut( __METHOD__
);
985 $match = self
::matchSummarySpamRegex( $this->summary
);
986 if ( $match === false ) {
987 $match = self
::matchSpamRegex( $this->textbox1
);
989 if ( $match !== false ) {
990 $result['spam'] = $match;
991 $ip = $wgRequest->getIP();
992 $pdbk = $this->mTitle
->getPrefixedDBkey();
993 $match = str_replace( "\n", '', $match );
994 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
995 $status->fatal( 'spamprotectionmatch', $match );
996 $status->value
= self
::AS_SPAM_ERROR
;
997 wfProfileOut( __METHOD__
. '-checks' );
998 wfProfileOut( __METHOD__
);
1001 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
1002 # Error messages or other handling should be performed by the filter function
1003 $status->setResult( false, self
::AS_FILTERING
);
1004 wfProfileOut( __METHOD__
. '-checks' );
1005 wfProfileOut( __METHOD__
);
1008 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1009 # Error messages etc. could be handled within the hook...
1010 $status->fatal( 'hookaborted' );
1011 $status->value
= self
::AS_HOOK_ERROR
;
1012 wfProfileOut( __METHOD__
. '-checks' );
1013 wfProfileOut( __METHOD__
);
1015 } elseif ( $this->hookError
!= '' ) {
1016 # ...or the hook could be expecting us to produce an error
1017 $status->fatal( 'hookaborted' );
1018 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1019 wfProfileOut( __METHOD__
. '-checks' );
1020 wfProfileOut( __METHOD__
);
1024 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1025 // Auto-block user's IP if the account was "hard" blocked
1026 $wgUser->spreadAnyEditBlock();
1027 # Check block state against master, thus 'false'.
1028 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1029 wfProfileOut( __METHOD__
. '-checks' );
1030 wfProfileOut( __METHOD__
);
1034 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1035 if ( $this->kblength
> $wgMaxArticleSize ) {
1036 // Error will be displayed by showEditForm()
1037 $this->tooBig
= true;
1038 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1039 wfProfileOut( __METHOD__
. '-checks' );
1040 wfProfileOut( __METHOD__
);
1044 if ( !$wgUser->isAllowed( 'edit' ) ) {
1045 if ( $wgUser->isAnon() ) {
1046 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1047 wfProfileOut( __METHOD__
. '-checks' );
1048 wfProfileOut( __METHOD__
);
1051 $status->fatal( 'readonlytext' );
1052 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1053 wfProfileOut( __METHOD__
. '-checks' );
1054 wfProfileOut( __METHOD__
);
1059 if ( wfReadOnly() ) {
1060 $status->fatal( 'readonlytext' );
1061 $status->value
= self
::AS_READ_ONLY_PAGE
;
1062 wfProfileOut( __METHOD__
. '-checks' );
1063 wfProfileOut( __METHOD__
);
1066 if ( $wgUser->pingLimiter() ) {
1067 $status->fatal( 'actionthrottledtext' );
1068 $status->value
= self
::AS_RATE_LIMITED
;
1069 wfProfileOut( __METHOD__
. '-checks' );
1070 wfProfileOut( __METHOD__
);
1074 # If the article has been deleted while editing, don't save it without
1076 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1077 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1078 wfProfileOut( __METHOD__
. '-checks' );
1079 wfProfileOut( __METHOD__
);
1083 wfProfileOut( __METHOD__
. '-checks' );
1085 # If article is new, insert it.
1086 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1087 $new = ( $aid == 0 );
1090 // Late check for create permission, just in case *PARANOIA*
1091 if ( !$this->mTitle
->userCan( 'create' ) ) {
1092 $status->fatal( 'nocreatetext' );
1093 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1094 wfDebug( __METHOD__
. ": no create permission\n" );
1095 wfProfileOut( __METHOD__
);
1099 # Don't save a new article if it's blank.
1100 if ( $this->textbox1
== '' ) {
1101 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1102 wfProfileOut( __METHOD__
);
1106 // Run post-section-merge edit filter
1107 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1108 # Error messages etc. could be handled within the hook...
1109 $status->fatal( 'hookaborted' );
1110 $status->value
= self
::AS_HOOK_ERROR
;
1111 wfProfileOut( __METHOD__
);
1113 } elseif ( $this->hookError
!= '' ) {
1114 # ...or the hook could be expecting us to produce an error
1115 $status->fatal( 'hookaborted' );
1116 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1117 wfProfileOut( __METHOD__
);
1121 # Handle the user preference to force summaries here. Check if it's not a redirect.
1122 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
1123 if ( md5( $this->summary
) == $this->autoSumm
) {
1124 $this->missingSummary
= true;
1125 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1126 $status->value
= self
::AS_SUMMARY_NEEDED
;
1127 wfProfileOut( __METHOD__
);
1132 $text = $this->textbox1
;
1133 $result['sectionanchor'] = '';
1134 if ( $this->section
== 'new' ) {
1135 if ( $this->sectiontitle
!== '' ) {
1136 // Insert the section title above the content.
1137 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle
) . "\n\n" . $text;
1139 // Jump to the new section
1140 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1142 // If no edit summary was specified, create one automatically from the section
1143 // title and have it link to the new section. Otherwise, respect the summary as
1145 if ( $this->summary
=== '' ) {
1146 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1147 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1149 } elseif ( $this->summary
!== '' ) {
1150 // Insert the section title above the content.
1151 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $text;
1153 // Jump to the new section
1154 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1156 // Create a link to the new section from the edit summary.
1157 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1158 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1162 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1166 # Article exists. Check for edit conflict.
1168 $this->mArticle
->clear(); # Force reload of dates, etc.
1170 wfDebug( "timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n" );
1172 if ( $this->mArticle
->getTimestamp() != $this->edittime
) {
1173 $this->isConflict
= true;
1174 if ( $this->section
== 'new' ) {
1175 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1176 $this->mArticle
->getComment() == $this->summary
) {
1177 // Probably a duplicate submission of a new comment.
1178 // This can happen when squid resends a request after
1179 // a timeout but the first one actually went through.
1180 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1182 // New comment; suppress conflict.
1183 $this->isConflict
= false;
1184 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1186 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1187 # Suppress edit conflict with self, except for section edits where merging is required.
1188 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1189 $this->isConflict
= false;
1193 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1194 // backwards compatibility with old forms/bots).
1195 if ( $this->sectiontitle
!== '' ) {
1196 $sectionTitle = $this->sectiontitle
;
1198 $sectionTitle = $this->summary
;
1201 if ( $this->isConflict
) {
1202 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
1203 $this->mArticle
->getTimestamp() . "')\n" );
1204 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle, $this->edittime
);
1206 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1207 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle );
1209 if ( is_null( $text ) ) {
1210 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1211 $this->isConflict
= true;
1212 $text = $this->textbox1
; // do not try to merge here!
1213 } elseif ( $this->isConflict
) {
1215 if ( $this->mergeChangesInto( $text ) ) {
1216 // Successful merge! Maybe we should tell the user the good news?
1217 $this->isConflict
= false;
1218 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1220 $this->section
= '';
1221 $this->textbox1
= $text;
1222 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1226 if ( $this->isConflict
) {
1227 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1228 wfProfileOut( __METHOD__
);
1232 // Run post-section-merge edit filter
1233 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
1234 # Error messages etc. could be handled within the hook...
1235 $status->fatal( 'hookaborted' );
1236 $status->value
= self
::AS_HOOK_ERROR
;
1237 wfProfileOut( __METHOD__
);
1239 } elseif ( $this->hookError
!= '' ) {
1240 # ...or the hook could be expecting us to produce an error
1241 $status->fatal( 'hookaborted' );
1242 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1243 wfProfileOut( __METHOD__
);
1247 # Handle the user preference to force summaries here, but not for null edits
1248 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1249 && 0 != strcmp( $this->mArticle
->getContent(), $text )
1250 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1252 if ( md5( $this->summary
) == $this->autoSumm
) {
1253 $this->missingSummary
= true;
1254 $status->fatal( 'missingsummary' );
1255 $status->value
= self
::AS_SUMMARY_NEEDED
;
1256 wfProfileOut( __METHOD__
);
1261 # And a similar thing for new sections
1262 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1263 if ( trim( $this->summary
) == '' ) {
1264 $this->missingSummary
= true;
1265 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1266 $status->value
= self
::AS_SUMMARY_NEEDED
;
1267 wfProfileOut( __METHOD__
);
1273 wfProfileIn( __METHOD__
. '-sectionanchor' );
1274 $sectionanchor = '';
1275 if ( $this->section
== 'new' ) {
1276 if ( $this->textbox1
== '' ) {
1277 $this->missingComment
= true;
1278 $status->fatal( 'missingcommenttext' );
1279 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1280 wfProfileOut( __METHOD__
. '-sectionanchor' );
1281 wfProfileOut( __METHOD__
);
1284 if ( $this->sectiontitle
!== '' ) {
1285 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1286 // If no edit summary was specified, create one automatically from the section
1287 // title and have it link to the new section. Otherwise, respect the summary as
1289 if ( $this->summary
=== '' ) {
1290 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1291 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1293 } elseif ( $this->summary
!== '' ) {
1294 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1295 # This is a new section, so create a link to the new section
1296 # in the revision summary.
1297 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1298 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1300 } elseif ( $this->section
!= '' ) {
1301 # Try to get a section anchor from the section source, redirect to edited section if header found
1302 # XXX: might be better to integrate this into Article::replaceSection
1303 # for duplicate heading checking and maybe parsing
1304 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1305 # we can't deal with anchors, includes, html etc in the header for now,
1306 # headline would need to be parsed to improve this
1307 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1308 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1311 $result['sectionanchor'] = $sectionanchor;
1312 wfProfileOut( __METHOD__
. '-sectionanchor' );
1314 // Save errors may fall down to the edit form, but we've now
1315 // merged the section into full text. Clear the section field
1316 // so that later submission of conflict forms won't try to
1317 // replace that into a duplicated mess.
1318 $this->textbox1
= $text;
1319 $this->section
= '';
1321 $status->value
= self
::AS_SUCCESS_UPDATE
;
1324 // Check for length errors again now that the section is merged in
1325 $this->kblength
= (int)( strlen( $text ) / 1024 );
1326 if ( $this->kblength
> $wgMaxArticleSize ) {
1327 $this->tooBig
= true;
1328 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1329 wfProfileOut( __METHOD__
);
1333 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1334 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1335 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1336 ( $bot ? EDIT_FORCE_BOT
: 0 );
1338 $doEditStatus = $this->mArticle
->doEdit( $text, $this->summary
, $flags );
1340 if ( $doEditStatus->isOK() ) {
1341 $result['redirect'] = Title
::newFromRedirect( $text ) !== null;
1342 $this->commitWatch();
1343 wfProfileOut( __METHOD__
);
1346 $this->isConflict
= true;
1347 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1348 wfProfileOut( __METHOD__
);
1349 return $doEditStatus;
1354 * Commit the change of watch status
1356 protected function commitWatch() {
1358 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1359 $dbw = wfGetDB( DB_MASTER
);
1361 if ( $this->watchthis
) {
1362 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1364 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1371 * Check if no edits were made by other users since
1372 * the time a user started editing the page. Limit to
1373 * 50 revisions for the sake of performance.
1376 * @param $edittime string
1380 protected function userWasLastToEdit( $id, $edittime ) {
1381 if( !$id ) return false;
1382 $dbw = wfGetDB( DB_MASTER
);
1383 $res = $dbw->select( 'revision',
1386 'rev_page' => $this->mArticle
->getId(),
1387 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1390 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1391 foreach ( $res as $row ) {
1392 if( $row->rev_user
!= $id ) {
1403 * @parma $editText string
1407 function mergeChangesInto( &$editText ){
1408 wfProfileIn( __METHOD__
);
1410 $db = wfGetDB( DB_MASTER
);
1412 // This is the revision the editor started from
1413 $baseRevision = $this->getBaseRevision();
1414 if ( is_null( $baseRevision ) ) {
1415 wfProfileOut( __METHOD__
);
1418 $baseText = $baseRevision->getText();
1420 // The current state, we want to merge updates into it
1421 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1422 if ( is_null( $currentRevision ) ) {
1423 wfProfileOut( __METHOD__
);
1426 $currentText = $currentRevision->getText();
1429 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1430 $editText = $result;
1431 wfProfileOut( __METHOD__
);
1434 wfProfileOut( __METHOD__
);
1442 function getBaseRevision() {
1443 if ( !$this->mBaseRevision
) {
1444 $db = wfGetDB( DB_MASTER
);
1445 $baseRevision = Revision
::loadFromTimestamp(
1446 $db, $this->mTitle
, $this->edittime
);
1447 return $this->mBaseRevision
= $baseRevision;
1449 return $this->mBaseRevision
;
1454 * Check given input text against $wgSpamRegex, and return the text of the first match.
1456 * @param $text string
1458 * @return string|false matching string or false
1460 public static function matchSpamRegex( $text ) {
1461 global $wgSpamRegex;
1462 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1463 $regexes = (array)$wgSpamRegex;
1464 return self
::matchSpamRegexInternal( $text, $regexes );
1468 * Check given input text against $wgSpamRegex, and return the text of the first match.
1470 * @parma $text string
1472 * @return string|false matching string or false
1474 public static function matchSummarySpamRegex( $text ) {
1475 global $wgSummarySpamRegex;
1476 $regexes = (array)$wgSummarySpamRegex;
1477 return self
::matchSpamRegexInternal( $text, $regexes );
1481 * @param $text string
1482 * @param $regexes array
1483 * @return bool|string
1485 protected static function matchSpamRegexInternal( $text, $regexes ) {
1486 foreach( $regexes as $regex ) {
1488 if( preg_match( $regex, $text, $matches ) ) {
1495 function setHeaders() {
1497 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1498 if ( $this->isConflict
) {
1499 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1500 } elseif ( $this->section
!= '' ) {
1501 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1502 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1504 # Use the title defined by DISPLAYTITLE magic word when present
1505 if ( isset( $this->mParserOutput
)
1506 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1509 $title = $this->getContextTitle()->getPrefixedText();
1511 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1516 * Show all applicable editing introductions
1518 protected function showIntro() {
1519 global $wgOut, $wgUser;
1520 if ( $this->suppressIntro
) {
1524 $namespace = $this->mTitle
->getNamespace();
1526 if ( $namespace == NS_MEDIAWIKI
) {
1527 # Show a warning if editing an interface message
1528 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1531 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1532 # Show log extract when the user is currently blocked
1533 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1534 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1535 $username = $parts[0];
1536 $user = User
::newFromName( $username, false /* allow IP users*/ );
1537 $ip = User
::isIP( $username );
1538 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1539 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1540 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1541 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1542 LogEventsList
::showLogExtract(
1545 $user->getUserPage(),
1549 'showIfEmpty' => false,
1551 'blocked-notice-logextract',
1552 $user->getName() # Support GENDER in notice
1558 # Try to add a custom edit intro, or use the standard one if this is not possible.
1559 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1560 if ( $wgUser->isLoggedIn() ) {
1561 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1563 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1566 # Give a notice if the user is editing a deleted/moved page...
1567 if ( !$this->mTitle
->exists() ) {
1568 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1569 '', array( 'lim' => 10,
1570 'conds' => array( "log_action != 'revision'" ),
1571 'showIfEmpty' => false,
1572 'msgKey' => array( 'recreate-moveddeleted-warn') )
1578 * Attempt to show a custom editing introduction, if supplied
1582 protected function showCustomIntro() {
1583 if ( $this->editintro
) {
1584 $title = Title
::newFromText( $this->editintro
);
1585 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1587 // Added using template syntax, to take <noinclude>'s into account.
1588 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1599 * Send the edit form and related headers to $wgOut
1600 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1601 * during form output near the top, for captchas and the like.
1603 function showEditForm( $formCallback = null ) {
1604 global $wgOut, $wgUser;
1606 wfProfileIn( __METHOD__
);
1608 #need to parse the preview early so that we know which templates are used,
1609 #otherwise users with "show preview after edit box" will get a blank list
1610 #we parse this near the beginning so that setHeaders can do the title
1611 #setting work instead of leaving it in getPreviewText
1612 $previewOutput = '';
1613 if ( $this->formtype
== 'preview' ) {
1614 $previewOutput = $this->getPreviewText();
1617 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1619 $this->setHeaders();
1621 # Enabled article-related sidebar, toplinks, etc.
1622 $wgOut->setArticleRelated( true );
1624 if ( $this->showHeader() === false ) {
1625 wfProfileOut( __METHOD__
);
1629 $action = htmlspecialchars( $this->getActionURL( $this->getContextTitle() ) );
1631 if ( $wgUser->getOption( 'showtoolbar' ) and !$this->isCssJsSubpage
) {
1632 # prepare toolbar for edit buttons
1633 $toolbar = EditPage
::getEditToolbar();
1639 $wgOut->addHTML( $this->editFormPageTop
);
1641 if ( $wgUser->getOption( 'previewontop' ) ) {
1642 $this->displayPreviewArea( $previewOutput, true );
1645 $wgOut->addHTML( $this->editFormTextTop
);
1647 $templates = $this->getTemplates();
1648 $formattedtemplates = Linker
::formatTemplates( $templates, $this->preview
, $this->section
!= '');
1650 $hiddencats = $this->mArticle
->getHiddenCategories();
1651 $formattedhiddencats = Linker
::formatHiddenCategories( $hiddencats );
1653 if ( $this->wasDeletedSinceLastEdit() && 'save' != $this->formtype
) {
1654 $wgOut->wrapWikiMsg(
1655 "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1656 'deletedwhileediting' );
1657 } elseif ( $this->wasDeletedSinceLastEdit() ) {
1658 // Hide the toolbar and edit area, user can click preview to get it back
1659 // Add an confirmation checkbox and explanation.
1661 // @todo move this to a cleaner conditional instead of blanking a variable
1663 $wgOut->addHTML( <<<HTML
1664 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1668 if ( is_callable( $formCallback ) ) {
1669 call_user_func_array( $formCallback, array( &$wgOut ) );
1672 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1674 // Put these up at the top to ensure they aren't lost on early form submission
1675 $this->showFormBeforeText();
1677 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1678 $username = $this->lastDelete
->user_name
;
1679 $comment = $this->lastDelete
->log_comment
;
1681 // It is better to not parse the comment at all than to have templates expanded in the middle
1682 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1683 $key = $comment === ''
1684 ?
'confirmrecreate-noreason'
1685 : 'confirmrecreate';
1687 '<div class="mw-confirm-recreate">' .
1688 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1689 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1690 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1696 # If a blank edit summary was previously provided, and the appropriate
1697 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1698 # user being bounced back more than once in the event that a summary
1701 # For a bit more sophisticated detection of blank summaries, hash the
1702 # automatic one and pass that in the hidden field wpAutoSummary.
1703 if ( $this->missingSummary ||
1704 ( $this->section
== 'new' && $this->nosummary
) )
1705 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1706 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1707 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1709 $wgOut->addHTML( Html
::hidden( 'oldid', $this->mArticle
->getOldID() ) );
1711 if ( $this->section
== 'new' ) {
1712 $this->showSummaryInput( true, $this->summary
);
1713 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1716 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1718 $wgOut->addHTML( $toolbar );
1720 if ( $this->isConflict
) {
1721 // In an edit conflict bypass the overrideable content form method
1722 // and fallback to the raw wpTextbox1 since editconflicts can't be
1723 // resolved between page source edits and custom ui edits using the
1725 $this->showTextbox1( null, $this->getContent() );
1727 $this->showContentForm();
1730 $wgOut->addHTML( $this->editFormTextAfterContent
);
1732 $wgOut->addWikiText( $this->getCopywarn() );
1733 if ( isset($this->editFormTextAfterWarn
) && $this->editFormTextAfterWarn
!== '' )
1734 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1736 $this->showStandardInputs();
1738 $this->showFormAfterText();
1740 $this->showTosSummary();
1741 $this->showEditTools();
1743 $wgOut->addHTML( <<<HTML
1744 {$this->editFormTextAfterTools}
1745 <div class='templatesUsed'>
1746 {$formattedtemplates}
1748 <div class='hiddencats'>
1749 {$formattedhiddencats}
1754 if ( $this->isConflict
)
1755 $this->showConflict();
1757 $wgOut->addHTML( $this->editFormTextBottom
);
1758 $wgOut->addHTML( "</form>\n" );
1759 if ( !$wgUser->getOption( 'previewontop' ) ) {
1760 $this->displayPreviewArea( $previewOutput, false );
1763 wfProfileOut( __METHOD__
);
1767 * Extract the section title from current section text, if any.
1769 * @param string $text
1770 * @return Mixed|string or false
1772 public static function extractSectionTitle( $text ) {
1773 preg_match( "/^(=+)(.+)\\1(\n|$)/i", $text, $matches );
1774 if ( !empty( $matches[2] ) ) {
1776 return $wgParser->stripSectionName(trim($matches[2]));
1782 protected function showHeader() {
1783 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1784 if ( $this->isConflict
) {
1785 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1786 $this->edittime
= $this->mArticle
->getTimestamp();
1788 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
1789 // We use $this->section to much before this and getVal('wgSection') directly in other places
1790 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1791 // Someone is welcome to try refactoring though
1792 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1796 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1798 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1799 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
1800 if ( $sectionTitle !== false ) {
1801 $this->summary
= "/* $sectionTitle */ ";
1806 if ( $this->missingComment
) {
1807 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1810 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1811 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1814 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1815 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1818 if ( $this->hookError
!== '' ) {
1819 $wgOut->addWikiText( $this->hookError
);
1822 if ( !$this->checkUnicodeCompliantBrowser() ) {
1823 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1826 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1827 // Let sysop know that this will make private content public if saved
1829 if ( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1830 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1831 } elseif ( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1832 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1835 if ( !$this->mArticle
->mRevision
->isCurrent() ) {
1836 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1837 $wgOut->addWikiMsg( 'editingold' );
1842 if ( wfReadOnly() ) {
1843 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1844 } elseif ( $wgUser->isAnon() ) {
1845 if ( $this->formtype
!= 'preview' ) {
1846 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1848 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
1851 if ( $this->isCssJsSubpage
) {
1852 # Check the skin exists
1853 if ( $this->isWrongCaseCssJsPage
) {
1854 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
1856 if ( $this->formtype
!== 'preview' ) {
1857 if ( $this->isCssSubpage
)
1858 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
1859 if ( $this->isJsSubpage
)
1860 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
1865 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
1866 # Is the title semi-protected?
1867 if ( $this->mTitle
->isSemiProtected() ) {
1868 $noticeMsg = 'semiprotectedpagewarning';
1870 # Then it must be protected based on static groups (regular)
1871 $noticeMsg = 'protectedpagewarning';
1873 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1874 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1876 if ( $this->mTitle
->isCascadeProtected() ) {
1877 # Is this page under cascading protection from some source pages?
1878 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1879 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
1880 $cascadeSourcesCount = count( $cascadeSources );
1881 if ( $cascadeSourcesCount > 0 ) {
1882 # Explain, and list the titles responsible
1883 foreach( $cascadeSources as $page ) {
1884 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1887 $notice .= '</div>';
1888 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1890 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1891 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1893 'showIfEmpty' => false,
1894 'msgKey' => array( 'titleprotectedwarning' ),
1895 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
1898 if ( $this->kblength
=== false ) {
1899 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1902 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1903 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
1904 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
1906 if( !wfMessage('longpage-hint')->isDisabled() ) {
1907 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
1908 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
1915 * Standard summary input and label (wgSummary), abstracted so EditPage
1916 * subclasses may reorganize the form.
1917 * Note that you do not need to worry about the label's for=, it will be
1918 * inferred by the id given to the input. You can remove them both by
1919 * passing array( 'id' => false ) to $userInputAttrs.
1921 * @param $summary string The value of the summary input
1922 * @param $labelText string The html to place inside the label
1923 * @param $inputAttrs array of attrs to use on the input
1924 * @param $spanLabelAttrs array of attrs to use on the span inside the label
1926 * @return array An array in the format array( $label, $input )
1928 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
1929 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
1930 $inputAttrs = ( is_array($inputAttrs) ?
$inputAttrs : array() ) +
array(
1931 'id' => 'wpSummary',
1932 'maxlength' => '200',
1935 'spellcheck' => 'true',
1936 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
1938 $spanLabelAttrs = ( is_array($spanLabelAttrs) ?
$spanLabelAttrs : array() ) +
array(
1939 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
1940 'id' => "wpSummaryLabel"
1945 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1946 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
1949 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
1951 return array( $label, $input );
1955 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1956 * up top, or false if this is the comment summary
1957 * down below the textarea
1958 * @param $summary String: The text of the summary to display
1961 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1962 global $wgOut, $wgContLang;
1963 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1964 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1965 if ( $isSubjectPreview ) {
1966 if ( $this->nosummary
) {
1970 if ( !$this->mShowSummaryField
) {
1974 $summary = $wgContLang->recodeForEdit( $summary );
1975 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
1976 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
1977 $wgOut->addHTML("{$label} {$input}");
1981 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1982 * up top, or false if this is the comment summary
1983 * down below the textarea
1984 * @param $summary String: the text of the summary to display
1987 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
1988 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
1993 if ( $isSubjectPreview )
1994 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
1996 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
1998 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
1999 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2002 protected function showFormBeforeText() {
2004 $section = htmlspecialchars( $this->section
);
2005 $wgOut->addHTML( <<<HTML
2006 <input type='hidden' value="{$section}" name="wpSection" />
2007 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2008 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2009 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2013 if ( !$this->checkUnicodeCompliantBrowser() )
2014 $wgOut->addHTML(Html
::hidden( 'safemode', '1' ));
2017 protected function showFormAfterText() {
2018 global $wgOut, $wgUser;
2020 * To make it harder for someone to slip a user a page
2021 * which submits an edit form to the wiki without their
2022 * knowledge, a random token is associated with the login
2023 * session. If it's not passed back with the submission,
2024 * we won't save the page, or render user JavaScript and
2027 * For anon editors, who may not have a session, we just
2028 * include the constant suffix to prevent editing from
2029 * broken text-mangling proxies.
2031 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2035 * Subpage overridable method for printing the form for page content editing
2036 * By default this simply outputs wpTextbox1
2037 * Subclasses can override this to provide a custom UI for editing;
2038 * be it a form, or simply wpTextbox1 with a modified content that will be
2039 * reverse modified when extracted from the post data.
2040 * Note that this is basically the inverse for importContentFormData
2042 protected function showContentForm() {
2043 $this->showTextbox1();
2047 * Method to output wpTextbox1
2048 * The $textoverride method can be used by subclasses overriding showContentForm
2049 * to pass back to this method.
2051 * @param $customAttribs An array of html attributes to use in the textarea
2052 * @param $textoverride String: optional text to override $this->textarea1 with
2054 protected function showTextbox1($customAttribs = null, $textoverride = null) {
2055 $classes = array(); // Textarea CSS
2056 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2057 # Is the title semi-protected?
2058 if ( $this->mTitle
->isSemiProtected() ) {
2059 $classes[] = 'mw-textarea-sprotected';
2061 # Then it must be protected based on static groups (regular)
2062 $classes[] = 'mw-textarea-protected';
2064 # Is the title cascade-protected?
2065 if ( $this->mTitle
->isCascadeProtected() ) {
2066 $classes[] = 'mw-textarea-cprotected';
2069 $attribs = array( 'tabindex' => 1 );
2070 if ( is_array($customAttribs) )
2071 $attribs +
= $customAttribs;
2073 if ( $this->wasDeletedSinceLastEdit() )
2074 $attribs['type'] = 'hidden';
2075 if ( !empty( $classes ) ) {
2076 if ( isset($attribs['class']) )
2077 $classes[] = $attribs['class'];
2078 $attribs['class'] = implode( ' ', $classes );
2081 $this->showTextbox( isset($textoverride) ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2084 protected function showTextbox2() {
2085 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2088 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2089 global $wgOut, $wgUser;
2091 $wikitext = $this->safeUnicodeOutput( $content );
2092 if ( strval($wikitext) !== '' ) {
2093 // Ensure there's a newline at the end, otherwise adding lines
2095 // But don't add a newline if the ext is empty, or Firefox in XHTML
2096 // mode will show an extra newline. A bit annoying.
2100 $attribs = $customAttribs +
array(
2103 'rows' => $wgUser->getIntOption( 'rows' ),
2104 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2107 $pageLang = $this->mTitle
->getPageLanguage();
2108 $attribs['lang'] = $pageLang->getCode();
2109 $attribs['dir'] = $pageLang->getDir();
2111 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2114 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2118 $classes[] = 'ontop';
2120 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2122 if ( $this->formtype
!= 'preview' )
2123 $attribs['style'] = 'display: none;';
2125 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2127 if ( $this->formtype
== 'preview' ) {
2128 $this->showPreview( $previewOutput );
2131 $wgOut->addHTML( '</div>' );
2133 if ( $this->formtype
== 'diff') {
2139 * Append preview output to $wgOut.
2140 * Includes category rendering if this is a category page.
2142 * @param $text String: the HTML to be output for the preview.
2144 protected function showPreview( $text ) {
2146 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2147 $this->mArticle
->openShowCategory();
2149 # This hook seems slightly odd here, but makes things more
2150 # consistent for extensions.
2151 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
2152 $wgOut->addHTML( $text );
2153 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2154 $this->mArticle
->closeShowCategory();
2159 * Get a diff between the current contents of the edit box and the
2160 * version of the page we're editing from.
2162 * If this is a section edit, we'll replace the section as for final
2163 * save and then make a comparison.
2165 function showDiff() {
2166 global $wgUser, $wgContLang, $wgParser;
2168 $oldtext = $this->mArticle
->fetchContent();
2169 $newtext = $this->mArticle
->replaceSection(
2170 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2172 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2174 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2175 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle
, $wgUser, $popts );
2176 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2177 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2178 if ( $oldtext !== false ||
$newtext != '' ) {
2179 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2180 $de->setText( $oldtext, $newtext );
2181 $difftext = $de->getDiff( $oldtitle, $newtitle );
2182 $de->showDiffStyle();
2188 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2192 * Give a chance for site and per-namespace customizations of
2193 * terms of service summary link that might exist separately
2194 * from the copyright notice.
2196 * This will display between the save button and the edit tools,
2197 * so should remain short!
2199 protected function showTosSummary() {
2200 $msg = 'editpage-tos-summary';
2201 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2202 if( !wfMessage( $msg )->isDisabled() ) {
2204 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2205 $wgOut->addWikiMsg( $msg );
2206 $wgOut->addHTML( '</div>' );
2210 protected function showEditTools() {
2212 $wgOut->addHTML( '<div class="mw-editTools">' .
2213 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2217 protected function getCopywarn() {
2218 global $wgRightsText;
2219 if ( $wgRightsText ) {
2220 $copywarnMsg = array( 'copyrightwarning',
2221 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2224 $copywarnMsg = array( 'copyrightwarning2',
2225 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2227 // Allow for site and per-namespace customization of contribution/copyright notice.
2228 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2230 return "<div id=\"editpage-copywarn\">\n" .
2231 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
2234 protected function showStandardInputs( &$tabindex = 2 ) {
2236 $wgOut->addHTML( "<div class='editOptions'>\n" );
2238 if ( $this->section
!= 'new' ) {
2239 $this->showSummaryInput( false, $this->summary
);
2240 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2243 $checkboxes = $this->getCheckboxes( $tabindex,
2244 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2245 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2246 $wgOut->addHTML( "<div class='editButtons'>\n" );
2247 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2249 $cancel = $this->getCancelLink();
2250 if ( $cancel !== '' ) {
2251 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2253 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2254 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
2255 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
2256 htmlspecialchars( wfMsg( 'newwindow' ) );
2257 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2258 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2262 * Show an edit conflict. textbox1 is already shown in showEditForm().
2263 * If you want to use another entry point to this function, be careful.
2265 protected function showConflict() {
2267 $this->textbox2
= $this->textbox1
;
2268 $this->textbox1
= $this->getContent();
2269 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2270 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2272 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2273 $de->setText( $this->textbox2
, $this->textbox1
);
2274 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2276 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2277 $this->showTextbox2();
2284 public function getCancelLink() {
2285 $cancelParams = array();
2286 if ( !$this->isConflict
&& $this->mArticle
->getOldID() > 0 ) {
2287 $cancelParams['oldid'] = $this->mArticle
->getOldID();
2290 return Linker
::linkKnown(
2291 $this->getContextTitle(),
2292 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2293 array( 'id' => 'mw-editform-cancel' ),
2299 * Returns the URL to use in the form's action attribute.
2300 * This is used by EditPage subclasses when simply customizing the action
2301 * variable in the constructor is not enough. This can be used when the
2302 * EditPage lives inside of a Special page rather than a custom page action.
2304 * @param $title Title object for which is being edited (where we go to for &action= links)
2307 protected function getActionURL( Title
$title ) {
2308 return $title->getLocalURL( array( 'action' => $this->action
) );
2312 * Check if a page was deleted while the user was editing it, before submit.
2313 * Note that we rely on the logging table, which hasn't been always there,
2314 * but that doesn't matter, because this only applies to brand new
2317 protected function wasDeletedSinceLastEdit() {
2318 if ( $this->deletedSinceEdit
!== null ) {
2319 return $this->deletedSinceEdit
;
2322 $this->deletedSinceEdit
= false;
2324 if ( $this->mTitle
->isDeletedQuick() ) {
2325 $this->lastDelete
= $this->getLastDelete();
2326 if ( $this->lastDelete
) {
2327 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2328 if ( $deleteTime > $this->starttime
) {
2329 $this->deletedSinceEdit
= true;
2334 return $this->deletedSinceEdit
;
2337 protected function getLastDelete() {
2338 $dbr = wfGetDB( DB_SLAVE
);
2339 $data = $dbr->selectRow(
2340 array( 'logging', 'user' ),
2351 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2352 'log_title' => $this->mTitle
->getDBkey(),
2353 'log_type' => 'delete',
2354 'log_action' => 'delete',
2355 'user_id=log_user' ),
2357 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2359 // Quick paranoid permission checks...
2360 if( is_object( $data ) ) {
2361 if( $data->log_deleted
& LogPage
::DELETED_USER
)
2362 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2363 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2364 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2370 * Get the rendered text for previewing.
2373 function getPreviewText() {
2374 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2376 wfProfileIn( __METHOD__
);
2378 if ( $wgRawHtml && !$this->mTokenOk
) {
2379 // Could be an offsite preview attempt. This is very unsafe if
2380 // HTML is enabled, as it could be an attack.
2382 if ( $this->textbox1
!== '' ) {
2383 // Do not put big scary notice, if previewing the empty
2384 // string, which happens when you initially edit
2385 // a category page, due to automatic preview-on-open.
2386 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2387 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2389 wfProfileOut( __METHOD__
);
2393 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2394 if ( $this->mTokenOkExceptSuffix
) {
2395 $note = wfMsg( 'token_suffix_mismatch' );
2397 $note = wfMsg( 'session_fail_preview' );
2399 } elseif ( $this->incompleteForm
) {
2400 $note = wfMsg( 'edit_form_incomplete' );
2402 $note = wfMsg( 'previewnote' );
2405 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2406 $parserOptions->setEditSection( false );
2407 $parserOptions->setTidy( true );
2408 $parserOptions->setIsPreview( true );
2409 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2411 # don't parse non-wikitext pages, show message about preview
2412 # 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?
2414 if ( $this->isCssJsSubpage ||
!$this->mTitle
->isWikitextPage() ) {
2415 if( $this->mTitle
->isCssJsSubpage() ) {
2417 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2423 # Used messages to make sure grep find them:
2424 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2426 if (preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2427 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2428 $class = "mw-code mw-css";
2429 } elseif (preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2430 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2431 $class = "mw-code mw-js";
2433 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2437 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2438 $previewHTML = $parserOutput->mText
;
2439 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2441 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2443 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2445 $toparse = $this->textbox1
;
2447 # If we're adding a comment, we need to show the
2448 # summary as the headline
2449 if ( $this->section
== "new" && $this->summary
!= "" ) {
2450 $toparse = "== {$this->summary} ==\n\n" . $toparse;
2453 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2455 $parserOptions->enableLimitReport();
2457 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle
, $wgUser, $parserOptions );
2458 $parserOutput = $wgParser->parse( $toparse, $this->mTitle
, $parserOptions );
2460 $previewHTML = $parserOutput->getText();
2461 $this->mParserOutput
= $parserOutput;
2462 $wgOut->addParserOutputNoText( $parserOutput );
2464 if ( count( $parserOutput->getWarnings() ) ) {
2465 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2470 if( $this->isConflict
) {
2471 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2473 $conflict = '<hr />';
2476 $previewhead = "<div class='previewnote'>\n" .
2477 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2478 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2480 $pageLang = $this->mTitle
->getPageLanguage();
2481 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2482 'class' => 'mw-content-'.$pageLang->getDir() );
2483 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2485 wfProfileOut( __METHOD__
);
2486 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2492 function getTemplates() {
2493 if ( $this->preview ||
$this->section
!= '' ) {
2494 $templates = array();
2495 if ( !isset( $this->mParserOutput
) ) {
2498 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
2499 foreach( array_keys( $template ) as $dbk ) {
2500 $templates[] = Title
::makeTitle($ns, $dbk);
2505 return $this->mArticle
->getUsedTemplates();
2510 * Shows a bulletin board style toolbar for common editing functions.
2511 * It can be disabled in the user preferences.
2512 * The necessary JavaScript code can be found in skins/common/edit.js.
2516 static function getEditToolbar() {
2517 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2518 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2520 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2523 * $toolarray is an array of arrays each of which includes the
2524 * filename of the button image (without path), the opening
2525 * tag, the closing tag, optionally a sample text that is
2526 * inserted between the two when no selection is highlighted
2527 * and. The tip text is shown when the user moves the mouse
2530 * Also here: accesskeys (key), which are not used yet until
2531 * someone can figure out a way to make them work in
2532 * IE. However, we should make sure these keys are not defined
2537 'image' => $wgLang->getImageFile( 'button-bold' ),
2538 'id' => 'mw-editbutton-bold',
2540 'close' => '\'\'\'',
2541 'sample' => wfMsg( 'bold_sample' ),
2542 'tip' => wfMsg( 'bold_tip' ),
2546 'image' => $wgLang->getImageFile( 'button-italic' ),
2547 'id' => 'mw-editbutton-italic',
2550 'sample' => wfMsg( 'italic_sample' ),
2551 'tip' => wfMsg( 'italic_tip' ),
2555 'image' => $wgLang->getImageFile( 'button-link' ),
2556 'id' => 'mw-editbutton-link',
2559 'sample' => wfMsg( 'link_sample' ),
2560 'tip' => wfMsg( 'link_tip' ),
2564 'image' => $wgLang->getImageFile( 'button-extlink' ),
2565 'id' => 'mw-editbutton-extlink',
2568 'sample' => wfMsg( 'extlink_sample' ),
2569 'tip' => wfMsg( 'extlink_tip' ),
2573 'image' => $wgLang->getImageFile( 'button-headline' ),
2574 'id' => 'mw-editbutton-headline',
2577 'sample' => wfMsg( 'headline_sample' ),
2578 'tip' => wfMsg( 'headline_tip' ),
2581 $imagesAvailable ?
array(
2582 'image' => $wgLang->getImageFile( 'button-image' ),
2583 'id' => 'mw-editbutton-image',
2584 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2586 'sample' => wfMsg( 'image_sample' ),
2587 'tip' => wfMsg( 'image_tip' ),
2590 $imagesAvailable ?
array(
2591 'image' => $wgLang->getImageFile( 'button-media' ),
2592 'id' => 'mw-editbutton-media',
2593 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2595 'sample' => wfMsg( 'media_sample' ),
2596 'tip' => wfMsg( 'media_tip' ),
2600 'image' => $wgLang->getImageFile( 'button-math' ),
2601 'id' => 'mw-editbutton-math',
2603 'close' => "</math>",
2604 'sample' => wfMsg( 'math_sample' ),
2605 'tip' => wfMsg( 'math_tip' ),
2609 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2610 'id' => 'mw-editbutton-nowiki',
2611 'open' => "<nowiki>",
2612 'close' => "</nowiki>",
2613 'sample' => wfMsg( 'nowiki_sample' ),
2614 'tip' => wfMsg( 'nowiki_tip' ),
2618 'image' => $wgLang->getImageFile( 'button-sig' ),
2619 'id' => 'mw-editbutton-signature',
2623 'tip' => wfMsg( 'sig_tip' ),
2627 'image' => $wgLang->getImageFile( 'button-hr' ),
2628 'id' => 'mw-editbutton-hr',
2629 'open' => "\n----\n",
2632 'tip' => wfMsg( 'hr_tip' ),
2638 foreach ( $toolarray as $tool ) {
2644 $image = $wgStylePath . '/common/images/' . $tool['image'],
2645 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2646 // Older browsers show a "speedtip" type message only for ALT.
2647 // Ideally these should be different, realistically they
2648 // probably don't need to be.
2649 $tip = $tool['tip'],
2650 $open = $tool['open'],
2651 $close = $tool['close'],
2652 $sample = $tool['sample'],
2653 $cssId = $tool['id'],
2656 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2658 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2660 $toolbar = '<div id="toolbar"></div>';
2662 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2668 * Returns an array of html code of the following checkboxes:
2671 * @param $tabindex Current tabindex
2672 * @param $checked Array of checkbox => bool, where bool indicates the checked
2673 * status of the checkbox
2677 public function getCheckboxes( &$tabindex, $checked ) {
2680 $checkboxes = array();
2682 // don't show the minor edit checkbox if it's a new page or section
2683 if ( !$this->isNew
) {
2684 $checkboxes['minor'] = '';
2685 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2686 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2688 'tabindex' => ++
$tabindex,
2689 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2690 'id' => 'wpMinoredit',
2692 $checkboxes['minor'] =
2693 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2694 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2695 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2696 ">{$minorLabel}</label>";
2700 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2701 $checkboxes['watch'] = '';
2702 if ( $wgUser->isLoggedIn() ) {
2704 'tabindex' => ++
$tabindex,
2705 'accesskey' => wfMsg( 'accesskey-watch' ),
2706 'id' => 'wpWatchthis',
2708 $checkboxes['watch'] =
2709 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2710 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2711 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2712 ">{$watchLabel}</label>";
2714 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2719 * Returns an array of html code of the following buttons:
2720 * save, diff, preview and live
2722 * @param $tabindex Current tabindex
2726 public function getEditButtons( &$tabindex ) {
2733 'tabindex' => ++
$tabindex,
2734 'value' => wfMsg( 'savearticle' ),
2735 'accesskey' => wfMsg( 'accesskey-save' ),
2736 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2738 $buttons['save'] = Xml
::element('input', $temp, '');
2740 ++
$tabindex; // use the same for preview and live preview
2742 'id' => 'wpPreview',
2743 'name' => 'wpPreview',
2745 'tabindex' => $tabindex,
2746 'value' => wfMsg( 'showpreview' ),
2747 'accesskey' => wfMsg( 'accesskey-preview' ),
2748 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2750 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
2751 $buttons['live'] = '';
2757 'tabindex' => ++
$tabindex,
2758 'value' => wfMsg( 'showdiff' ),
2759 'accesskey' => wfMsg( 'accesskey-diff' ),
2760 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2762 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
2764 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2769 * Output preview text only. This can be sucked into the edit page
2770 * via JavaScript, and saves the server time rendering the skin as
2771 * well as theoretically being more robust on the client (doesn't
2772 * disturb the edit box's undo history, won't eat your text on
2775 * @todo This doesn't include category or interlanguage links.
2776 * Would need to enhance it a bit, <s>maybe wrap them in XML
2777 * or something...</s> that might also require more skin
2778 * initialization, so check whether that's a problem.
2780 function livePreview() {
2783 header( 'Content-type: text/xml; charset=utf-8' );
2784 header( 'Cache-control: no-cache' );
2786 $previewText = $this->getPreviewText();
2787 #$categories = $skin->getCategoryLinks();
2790 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2791 Xml
::tags( 'livepreview', null,
2792 Xml
::element( 'preview', null, $previewText )
2793 #. Xml::element( 'category', null, $categories )
2799 * Call the stock "user is blocked" page
2801 * @deprecated in 1.19; throw an exception directly instead
2803 function blockedPage() {
2804 wfDeprecated( __METHOD__
, '1.19' );
2807 throw new UserBlockedError( $wgUser->mBlock
);
2811 * Produce the stock "please login to edit pages" page
2813 * @deprecated in 1.19; throw an exception directly instead
2815 function userNotLoggedInPage() {
2816 wfDeprecated( __METHOD__
, '1.19' );
2817 throw new PermissionsError( 'edit' );
2821 * Show an error page saying to the user that he has insufficient permissions
2822 * to create a new page
2824 * @deprecated in 1.19; throw an exception directly instead
2826 function noCreatePermission() {
2827 wfDeprecated( __METHOD__
, '1.19' );
2828 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
2829 throw new PermissionsError( $permission );
2833 * Creates a basic error page which informs the user that
2834 * they have attempted to edit a nonexistent section.
2836 function noSuchSectionPage() {
2839 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
2841 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
2842 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2843 $wgOut->addHTML( $res );
2845 $wgOut->returnToMain( false, $this->mTitle
);
2849 * Produce the stock "your edit contains spam" page
2851 * @param $match Text which triggered one or more filters
2852 * @deprecated since 1.17 Use method spamPageWithContent() instead
2854 static function spamPage( $match = false ) {
2855 wfDeprecated( __METHOD__
, '1.17' );
2857 global $wgOut, $wgTitle;
2859 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2861 $wgOut->addHTML( '<div id="spamprotected">' );
2862 $wgOut->addWikiMsg( 'spamprotectiontext' );
2864 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2866 $wgOut->addHTML( '</div>' );
2868 $wgOut->returnToMain( false, $wgTitle );
2872 * Show "your edit contains spam" page with your diff and text
2874 * @param $match Text which triggered one or more filters
2876 public function spamPageWithContent( $match = false ) {
2878 $this->textbox2
= $this->textbox1
;
2880 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2882 $wgOut->addHTML( '<div id="spamprotected">' );
2883 $wgOut->addWikiMsg( 'spamprotectiontext' );
2885 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2887 $wgOut->addHTML( '</div>' );
2889 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2890 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2891 $de->setText( $this->getContent(), $this->textbox2
);
2892 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
2894 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2895 $this->showTextbox2();
2897 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
2901 * Format an anchor fragment as it would appear for a given section name
2902 * @param $text String
2906 function sectionAnchor( $text ) {
2908 return $wgParser->guessSectionNameFromWikiText( $text );
2912 * Check if the browser is on a blacklist of user-agents known to
2913 * mangle UTF-8 data on form submission. Returns true if Unicode
2914 * should make it through, false if it's known to be a problem.
2918 function checkUnicodeCompliantBrowser() {
2919 global $wgBrowserBlackList;
2920 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2921 // No User-Agent header sent? Trust it by default...
2924 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2925 foreach ( $wgBrowserBlackList as $browser ) {
2926 if ( preg_match($browser, $currentbrowser) ) {
2934 * Filter an input field through a Unicode de-armoring process if it
2935 * came from an old browser with known broken Unicode editing issues.
2937 * @param $request WebRequest
2938 * @param $field String
2942 function safeUnicodeInput( $request, $field ) {
2943 $text = rtrim( $request->getText( $field ) );
2944 return $request->getBool( 'safemode' )
2945 ?
$this->unmakesafe( $text )
2950 * @param $request WebRequest
2951 * @param $text string
2954 function safeUnicodeText( $request, $text ) {
2955 $text = rtrim( $text );
2956 return $request->getBool( 'safemode' )
2957 ?
$this->unmakesafe( $text )
2962 * Filter an output field through a Unicode armoring process if it is
2963 * going to an old browser with known broken Unicode editing issues.
2965 * @param $text String
2969 function safeUnicodeOutput( $text ) {
2971 $codedText = $wgContLang->recodeForEdit( $text );
2972 return $this->checkUnicodeCompliantBrowser()
2974 : $this->makesafe( $codedText );
2978 * A number of web browsers are known to corrupt non-ASCII characters
2979 * in a UTF-8 text editing environment. To protect against this,
2980 * detected browsers will be served an armored version of the text,
2981 * with non-ASCII chars converted to numeric HTML character references.
2983 * Preexisting such character references will have a 0 added to them
2984 * to ensure that round-trips do not alter the original data.
2986 * @param $invalue String
2990 function makesafe( $invalue ) {
2991 // Armor existing references for reversability.
2992 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2997 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2998 $bytevalue = ord( $invalue[$i] );
2999 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
3000 $result .= chr( $bytevalue );
3002 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
3003 $working = $working << 6;
3004 $working +
= ($bytevalue & 0x3F);
3006 if ( $bytesleft <= 0 ) {
3007 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3009 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
3010 $working = $bytevalue & 0x1F;
3012 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
3013 $working = $bytevalue & 0x0F;
3015 } else { //1111 0xxx
3016 $working = $bytevalue & 0x07;
3024 * Reverse the previously applied transliteration of non-ASCII characters
3025 * back to UTF-8. Used to protect data from corruption by broken web browsers
3026 * as listed in $wgBrowserBlackList.
3028 * @param $invalue String
3032 function unmakesafe( $invalue ) {
3034 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3035 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+
3] != '0' ) ) {
3039 $hexstring .= $invalue[$i];
3041 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3043 // Do some sanity checks. These aren't needed for reversability,
3044 // but should help keep the breakage down if the editor
3045 // breaks one of the entities whilst editing.
3046 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
3047 $codepoint = hexdec($hexstring);
3048 $result .= codepointToUtf8( $codepoint );
3050 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3053 $result .= substr( $invalue, $i, 1 );
3056 // reverse the transform that we made for reversability reasons.
3057 return strtr( $result, array( "�" => "&#x" ) );