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;
116 * @param $article Article
118 public function __construct( Article
$article ) {
119 $this->mArticle
= $article;
120 $this->mTitle
= $article->getTitle();
126 public function getArticle() {
127 return $this->mArticle
;
134 public function getTitle() {
135 return $this->mTitle
;
139 * Set the context Title object
141 * @param $title Title object or null
143 public function setContextTitle( $title ) {
144 $this->mContextTitle
= $title;
148 * Get the context title object.
149 * If not set, $wgTitle will be returned. This behavior might changed in
150 * the future to return $this->mTitle instead.
152 * @return Title object
154 public function getContextTitle() {
155 if ( is_null( $this->mContextTitle
) ) {
159 return $this->mContextTitle
;
168 * This is the function that gets called for "action=edit". It
169 * sets up various member variables, then passes execution to
170 * another function, usually showEditForm()
172 * The edit form is self-submitting, so that when things like
173 * preview and edit conflicts occur, we get the same form back
174 * with the extra stuff added. Only when the final submission
175 * is made and all is well do we actually save and redirect to
176 * the newly-edited page.
179 global $wgOut, $wgRequest, $wgUser;
180 // Allow extensions to modify/prevent this form or submission
181 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
185 wfProfileIn( __METHOD__
);
186 wfDebug( __METHOD__
.": enter\n" );
188 // If they used redlink=1 and the page exists, redirect to the main article
189 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
190 $wgOut->redirect( $this->mTitle
->getFullURL() );
191 wfProfileOut( __METHOD__
);
195 $this->importFormData( $wgRequest );
196 $this->firsttime
= false;
199 $this->livePreview();
200 wfProfileOut( __METHOD__
);
204 if ( wfReadOnly() && $this->save
) {
207 $this->preview
= true;
211 $this->formtype
= 'save';
212 } elseif ( $this->preview
) {
213 $this->formtype
= 'preview';
214 } elseif ( $this->diff
) {
215 $this->formtype
= 'diff';
216 } else { # First time through
217 $this->firsttime
= true;
218 if ( $this->previewOnOpen() ) {
219 $this->formtype
= 'preview';
221 $this->formtype
= 'initial';
225 $permErrors = $this->getEditPermissionErrors();
227 wfDebug( __METHOD__
. ": User can't edit\n" );
228 // Auto-block user's IP if the account was "hard" blocked
229 $wgUser->spreadAnyEditBlock();
231 $this->displayPermissionsError( $permErrors );
233 wfProfileOut( __METHOD__
);
237 $wgOut->addModules( 'mediawiki.action.edit' );
239 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
240 $wgOut->addModules( 'mediawiki.legacy.preview' );
242 // Bug #19334: textarea jumps when editing articles in IE8
243 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
245 wfProfileIn( __METHOD__
."-business-end" );
247 $this->isConflict
= false;
248 // css / js subpages of user pages get a special treatment
249 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
250 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
251 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
252 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
253 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
255 # Show applicable editing introductions
256 if ( $this->formtype
== 'initial' ||
$this->firsttime
)
259 if ( $this->mTitle
->isTalkPage() ) {
260 $wgOut->addWikiMsg( 'talkpagetext' );
263 # Optional notices on a per-namespace and per-page basis
264 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
265 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
266 if ( $editnotice_ns_message->exists() ) {
267 $wgOut->addWikiText( $editnotice_ns_message->plain() );
269 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
270 $parts = explode( '/', $this->mTitle
->getDBkey() );
271 $editnotice_base = $editnotice_ns;
272 while ( count( $parts ) > 0 ) {
273 $editnotice_base .= '-'.array_shift( $parts );
274 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
275 if ( $editnotice_base_msg->exists() ) {
276 $wgOut->addWikiText( $editnotice_base_msg->plain() );
280 # Even if there are no subpages in namespace, we still don't want / in MW ns.
281 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
282 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
283 if ( $editnoticeMsg->exists() ) {
284 $wgOut->addWikiText( $editnoticeMsg->plain() );
288 # Attempt submission here. This will check for edit conflicts,
289 # and redundantly check for locked database, blocked IPs, etc.
290 # that edit() already checked just in case someone tries to sneak
291 # in the back door with a hand-edited submission URL.
293 if ( 'save' == $this->formtype
) {
294 if ( !$this->attemptSave() ) {
295 wfProfileOut( __METHOD__
."-business-end" );
296 wfProfileOut( __METHOD__
);
301 # First time through: get contents, set time for conflict
303 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
304 if ( $this->initialiseForm() === false ) {
305 $this->noSuchSectionPage();
306 wfProfileOut( __METHOD__
."-business-end" );
307 wfProfileOut( __METHOD__
);
310 if ( !$this->mTitle
->getArticleId() )
311 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
313 wfRunHooks( 'EditFormInitialText', array( $this ) );
316 $this->showEditForm();
317 wfProfileOut( __METHOD__
."-business-end" );
318 wfProfileOut( __METHOD__
);
324 protected function getEditPermissionErrors() {
326 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
327 # Can this title be created?
328 if ( !$this->mTitle
->exists() ) {
329 $permErrors = array_merge( $permErrors,
330 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
332 # Ignore some permissions errors when a user is just previewing/viewing diffs
334 foreach( $permErrors as $error ) {
335 if ( ( $this->preview ||
$this->diff
) &&
336 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
341 $permErrors = wfArrayDiff2( $permErrors, $remove );
346 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
347 * but with the following differences:
348 * - If redlink=1, the user will be redirected to the page
349 * - If there is content to display or the error occurs while either saving,
350 * previewing or showing the difference, it will be a
351 * "View source for ..." page displaying the source code after the error message.
354 * @param $permErrors Array of permissions errors, as returned by
355 * Title::getUserPermissionsErrors().
357 protected function displayPermissionsError( array $permErrors ) {
358 global $wgRequest, $wgOut;
360 if ( $wgRequest->getBool( 'redlink' ) ) {
361 // The edit page was reached via a red link.
362 // Redirect to the article page and let them click the edit tab if
363 // they really want a permission error.
364 $wgOut->redirect( $this->mTitle
->getFullUrl() );
368 $content = $this->getContent();
370 # Use the normal message if there's nothing to display
371 if ( $this->firsttime
&& $content === '' ) {
372 $action = $this->mTitle
->exists() ?
'edit' :
373 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
374 throw new PermissionsError( $action, $permErrors );
377 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
378 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
379 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
380 $wgOut->addHTML( "<hr />\n" );
382 # If the user made changes, preserve them when showing the markup
383 # (This happens when a user is blocked during edit, for instance)
384 if ( !$this->firsttime
) {
385 $content = $this->textbox1
;
386 $wgOut->addWikiMsg( 'viewyourtext' );
388 $wgOut->addWikiMsg( 'viewsourcetext' );
391 $this->showTextbox( $content, 'wpTextbox1', array( 'readonly' ) );
393 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
394 Linker
::formatTemplates( $this->getTemplates() ) ) );
396 if ( $this->mTitle
->exists() ) {
397 $wgOut->returnToMain( null, $this->mTitle
);
402 * Show a read-only error
403 * Parameters are the same as OutputPage:readOnlyPage()
404 * Redirect to the article page if redlink=1
405 * @deprecated in 1.19; use displayPermissionsError() instead
407 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
408 wfDeprecated( __METHOD__
, '1.19' );
410 global $wgRequest, $wgOut;
411 if ( $wgRequest->getBool( 'redlink' ) ) {
412 // The edit page was reached via a red link.
413 // Redirect to the article page and let them click the edit tab if
414 // they really want a permission error.
415 $wgOut->redirect( $this->mTitle
->getFullUrl() );
417 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
422 * Should we show a preview when the edit form is first shown?
426 protected function previewOnOpen() {
427 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
428 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
429 // Explicit override from request
431 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
432 // Explicit override from request
434 } elseif ( $this->section
== 'new' ) {
435 // Nothing *to* preview for new sections
437 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
438 // Standard preference behaviour
440 } elseif ( !$this->mTitle
->exists() &&
441 isset($wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]) &&
442 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
444 // Categories are special
452 * Checks whether the user entered a skin name in uppercase,
453 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
457 protected function isWrongCaseCssJsPage() {
458 if( $this->mTitle
->isCssJsSubpage() ) {
459 $name = $this->mTitle
->getSkinFromCssJsSubpage();
460 $skins = array_merge(
461 array_keys( Skin
::getSkinNames() ),
464 return !in_array( $name, $skins )
465 && in_array( strtolower( $name ), $skins );
472 * Does this EditPage class support section editing?
473 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
477 protected function isSectionEditSupported() {
482 * This function collects the form data and uses it to populate various member variables.
483 * @param $request WebRequest
485 function importFormData( &$request ) {
486 global $wgLang, $wgUser;
488 wfProfileIn( __METHOD__
);
490 # Section edit can come from either the form or a link
491 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
493 if ( $request->wasPosted() ) {
494 # These fields need to be checked for encoding.
495 # Also remove trailing whitespace, but don't remove _initial_
496 # whitespace from the text boxes. This may be significant formatting.
497 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
498 if ( !$request->getCheck('wpTextbox2') ) {
499 // Skip this if wpTextbox2 has input, it indicates that we came
500 // from a conflict page with raw page text, not a custom form
501 // modified by subclasses
502 wfProfileIn( get_class($this)."::importContentFormData" );
503 $textbox1 = $this->importContentFormData( $request );
504 if ( isset($textbox1) )
505 $this->textbox1
= $textbox1;
506 wfProfileOut( get_class($this)."::importContentFormData" );
509 # Truncate for whole multibyte characters. +5 bytes for ellipsis
510 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
512 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
513 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
515 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
517 # Treat sectiontitle the same way as summary.
518 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
519 # currently doing double duty as both edit summary and section title. Right now this
520 # is just to allow API edits to work around this limitation, but this should be
521 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
522 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 250 );
523 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
525 $this->edittime
= $request->getVal( 'wpEdittime' );
526 $this->starttime
= $request->getVal( 'wpStarttime' );
528 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
530 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
531 // wpTextbox1 field is missing, possibly due to being "too big"
532 // according to some filter rules such as Suhosin's setting for
533 // suhosin.request.max_value_length (d'oh)
534 $this->incompleteForm
= true;
536 // edittime should be one of our last fields; if it's missing,
537 // the submission probably broke somewhere in the middle.
538 $this->incompleteForm
= is_null( $this->edittime
);
540 if ( $this->incompleteForm
) {
541 # If the form is incomplete, force to preview.
542 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
543 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
544 $this->preview
= true;
546 /* Fallback for live preview */
547 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
548 $this->diff
= $request->getCheck( 'wpDiff' );
550 // Remember whether a save was requested, so we can indicate
551 // if we forced preview due to session failure.
552 $this->mTriedSave
= !$this->preview
;
554 if ( $this->tokenOk( $request ) ) {
555 # Some browsers will not report any submit button
556 # if the user hits enter in the comment box.
557 # The unmarked state will be assumed to be a save,
558 # if the form seems otherwise complete.
559 wfDebug( __METHOD__
. ": Passed token check.\n" );
560 } elseif ( $this->diff
) {
561 # Failed token check, but only requested "Show Changes".
562 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
564 # Page might be a hack attempt posted from
565 # an external site. Preview instead of saving.
566 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
567 $this->preview
= true;
570 $this->save
= !$this->preview
&& !$this->diff
;
571 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
572 $this->edittime
= null;
575 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
576 $this->starttime
= null;
579 $this->recreate
= $request->getCheck( 'wpRecreate' );
581 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
582 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
584 # Don't force edit summaries when a user is editing their own user or talk page
585 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
586 $this->mTitle
->getText() == $wgUser->getName() )
588 $this->allowBlankSummary
= true;
590 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
593 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
595 # Not a posted form? Start with nothing.
596 wfDebug( __METHOD__
. ": Not a posted form.\n" );
597 $this->textbox1
= '';
599 $this->sectiontitle
= '';
600 $this->edittime
= '';
601 $this->starttime
= wfTimestampNow();
603 $this->preview
= false;
606 $this->minoredit
= false;
607 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
608 $this->recreate
= false;
610 // When creating a new section, we can preload a section title by passing it as the
611 // preloadtitle parameter in the URL (Bug 13100)
612 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
613 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
614 // Once wpSummary isn't being use for setting section titles, we should delete this.
615 $this->summary
= $request->getVal( 'preloadtitle' );
617 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
618 $this->summary
= $request->getText( 'summary' );
621 if ( $request->getVal( 'minor' ) ) {
622 $this->minoredit
= true;
626 $this->bot
= $request->getBool( 'bot', true );
627 $this->nosummary
= $request->getBool( 'nosummary' );
629 $this->oldid
= $request->getInt( 'oldid' );
631 $this->live
= $request->getCheck( 'live' );
632 $this->editintro
= $request->getText( 'editintro',
633 // Custom edit intro for new sections
634 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
636 // Allow extensions to modify form data
637 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
639 wfProfileOut( __METHOD__
);
643 * Subpage overridable method for extracting the page content data from the
644 * posted form to be placed in $this->textbox1, if using customized input
645 * this method should be overrided and return the page text that will be used
646 * for saving, preview parsing and so on...
648 * @param $request WebRequest
650 protected function importContentFormData( &$request ) {
651 return; // Don't do anything, EditPage already extracted wpTextbox1
655 * Initialise form fields in the object
656 * Called on the first invocation, e.g. when a user clicks an edit link
657 * @return bool -- if the requested section is valid
659 function initialiseForm() {
661 $this->edittime
= $this->mArticle
->getTimestamp();
662 $this->textbox1
= $this->getContent( false );
663 // activate checkboxes if user wants them to be always active
664 # Sort out the "watch" checkbox
665 if ( $wgUser->getOption( 'watchdefault' ) ) {
667 $this->watchthis
= true;
668 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
670 $this->watchthis
= true;
671 } elseif ( $this->mTitle
->userIsWatching() ) {
673 $this->watchthis
= true;
675 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
676 $this->minoredit
= true;
678 if ( $this->textbox1
=== false ) {
686 * Fetch initial editing page content.
688 * @param $def_text string
689 * @return mixed string on success, $def_text for invalid sections
692 function getContent( $def_text = '' ) {
693 global $wgOut, $wgRequest, $wgParser;
695 wfProfileIn( __METHOD__
);
699 // For message page not locally set, use the i18n message.
700 // For other non-existent articles, use preload text if any.
701 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
702 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
703 # If this is a system message, get the default text.
704 $text = $this->mTitle
->getDefaultMessageText();
706 if ( $text === false ) {
707 # If requested, preload some text.
708 $preload = $wgRequest->getVal( 'preload',
709 // Custom preload text for new sections
710 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
711 $text = $this->getPreloadedText( $preload );
713 // For existing pages, get text based on "undo" or section parameters.
715 if ( $this->section
!= '' ) {
716 // Get section edit text (returns $def_text for invalid sections)
717 $text = $wgParser->getSection( $this->getOriginalContent(), $this->section
, $def_text );
719 $undoafter = $wgRequest->getInt( 'undoafter' );
720 $undo = $wgRequest->getInt( 'undo' );
722 if ( $undo > 0 && $undoafter > 0 ) {
723 if ( $undo < $undoafter ) {
724 # If they got undoafter and undo round the wrong way, switch them
725 list( $undo, $undoafter ) = array( $undoafter, $undo );
728 $undorev = Revision
::newFromId( $undo );
729 $oldrev = Revision
::newFromId( $undoafter );
731 # Sanity check, make sure it's the right page,
732 # the revisions exist and they were not deleted.
733 # Otherwise, $text will be left as-is.
734 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
735 $undorev->getPage() == $oldrev->getPage() &&
736 $undorev->getPage() == $this->mTitle
->getArticleId() &&
737 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
738 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
740 $text = $this->mArticle
->getUndoText( $undorev, $oldrev );
741 if ( $text === false ) {
742 # Warn the user that something went wrong
743 $undoMsg = 'failure';
745 # Inform the user of our success and set an automatic edit summary
746 $undoMsg = 'success';
748 # If we just undid one rev, use an autosummary
749 $firstrev = $oldrev->getNext();
750 if ( $firstrev->getId() == $undo ) {
751 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
752 if ( $this->summary
=== '' ) {
753 $this->summary
= $undoSummary;
755 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
757 $this->undidRev
= $undo;
759 $this->formtype
= 'diff';
762 // Failed basic sanity checks.
763 // Older revisions may have been removed since the link
764 // was created, or we may simply have got bogus input.
768 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"error mw-undo-{$undoMsg}\">" .
769 wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
772 if ( $text === false ) {
773 $text = $this->getOriginalContent();
778 wfProfileOut( __METHOD__
);
783 * Get the content of the wanted revision, without section extraction.
785 * The result of this function can be used to compare user's input with
786 * section replaced in its context (using WikiPage::replaceSection())
787 * to the original text of the edit.
789 * This difers from Article::getContent() that when a missing revision is
790 * encountered the result will be an empty string and not the
791 * 'missing-article' message.
796 private function getOriginalContent() {
797 if ( $this->section
== 'new' ) {
798 return $this->getCurrentText();
800 $revision = $this->mArticle
->getRevisionFetched();
801 if ( $revision === null ) {
804 return $this->mArticle
->getContent();
808 * Get the actual text of the page. This is basically similar to
809 * WikiPage::getRawText() except that when the page doesn't exist an empty
810 * string is returned instead of false.
815 private function getCurrentText() {
816 $text = $this->mArticle
->getRawText();
817 if ( $text === false ) {
825 * Use this method before edit() to preload some text into the edit box
827 * @param $text string
829 public function setPreloadedText( $text ) {
830 $this->mPreloadText
= $text;
834 * Get the contents to be preloaded into the box, either set by
835 * an earlier setPreloadText() or by loading the given page.
837 * @param $preload String: representing the title to preload from.
840 protected function getPreloadedText( $preload ) {
841 global $wgUser, $wgParser;
843 if ( !empty( $this->mPreloadText
) ) {
844 return $this->mPreloadText
;
847 if ( $preload === '' ) {
851 $title = Title
::newFromText( $preload );
852 # Check for existence to avoid getting MediaWiki:Noarticletext
853 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
857 $page = WikiPage
::factory( $title );
858 if ( $page->isRedirect() ) {
859 $title = $page->getRedirectTarget();
861 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
864 $page = WikiPage
::factory( $title );
867 $parserOptions = ParserOptions
::newFromUser( $wgUser );
868 return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
872 * Make sure the form isn't faking a user's credentials.
874 * @param $request WebRequest
878 function tokenOk( &$request ) {
880 $token = $request->getVal( 'wpEditToken' );
881 $this->mTokenOk
= $wgUser->matchEditToken( $token );
882 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
883 return $this->mTokenOk
;
888 * @return bool false if output is done, true if the rest of the form should be displayed
890 function attemptSave() {
891 global $wgUser, $wgOut;
893 $resultDetails = false;
894 # Allow bots to exempt some edits from bot flagging
895 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
896 $status = $this->internalAttemptSave( $resultDetails, $bot );
897 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
899 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
900 $this->didSave
= true;
903 switch ( $status->value
) {
904 case self
::AS_HOOK_ERROR_EXPECTED
:
905 case self
::AS_CONTENT_TOO_BIG
:
906 case self
::AS_ARTICLE_WAS_DELETED
:
907 case self
::AS_CONFLICT_DETECTED
:
908 case self
::AS_SUMMARY_NEEDED
:
909 case self
::AS_TEXTBOX_EMPTY
:
910 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
914 case self
::AS_HOOK_ERROR
:
915 case self
::AS_FILTERING
:
918 case self
::AS_SUCCESS_NEW_ARTICLE
:
919 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
920 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
921 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
924 case self
::AS_SUCCESS_UPDATE
:
926 $sectionanchor = $resultDetails['sectionanchor'];
928 // Give extensions a chance to modify URL query on update
929 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
931 if ( $resultDetails['redirect'] ) {
932 if ( $extraQuery == '' ) {
933 $extraQuery = 'redirect=no';
935 $extraQuery = 'redirect=no&' . $extraQuery;
938 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
941 case self
::AS_BLANK_ARTICLE
:
942 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
945 case self
::AS_SPAM_ERROR
:
946 $this->spamPageWithContent( $resultDetails['spam'] );
949 case self
::AS_BLOCKED_PAGE_FOR_USER
:
950 throw new UserBlockedError( $wgUser->mBlock
);
952 case self
::AS_IMAGE_REDIRECT_ANON
:
953 case self
::AS_IMAGE_REDIRECT_LOGGED
:
954 throw new PermissionsError( 'upload' );
956 case self
::AS_READ_ONLY_PAGE_ANON
:
957 case self
::AS_READ_ONLY_PAGE_LOGGED
:
958 throw new PermissionsError( 'edit' );
960 case self
::AS_READ_ONLY_PAGE
:
961 throw new ReadOnlyError
;
963 case self
::AS_RATE_LIMITED
:
964 throw new ThrottledError();
966 case self
::AS_NO_CREATE_PERMISSION
:
967 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
968 throw new PermissionsError( $permission );
975 * Attempt submission (no UI)
980 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
982 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
983 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
984 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
986 function internalAttemptSave( &$result, $bot = false ) {
987 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
988 global $wgMaxArticleSize;
990 $status = Status
::newGood();
992 wfProfileIn( __METHOD__
);
993 wfProfileIn( __METHOD__
. '-checks' );
995 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
996 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
997 $status->fatal( 'hookaborted' );
998 $status->value
= self
::AS_HOOK_ERROR
;
999 wfProfileOut( __METHOD__
. '-checks' );
1000 wfProfileOut( __METHOD__
);
1004 # Check image redirect
1005 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1006 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
1007 !$wgUser->isAllowed( 'upload' ) ) {
1008 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1009 $status->setResult( false, $code );
1011 wfProfileOut( __METHOD__
. '-checks' );
1012 wfProfileOut( __METHOD__
);
1018 $match = self
::matchSummarySpamRegex( $this->summary
);
1019 if ( $match === false ) {
1020 $match = self
::matchSpamRegex( $this->textbox1
);
1022 if ( $match !== false ) {
1023 $result['spam'] = $match;
1024 $ip = $wgRequest->getIP();
1025 $pdbk = $this->mTitle
->getPrefixedDBkey();
1026 $match = str_replace( "\n", '', $match );
1027 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1028 $status->fatal( 'spamprotectionmatch', $match );
1029 $status->value
= self
::AS_SPAM_ERROR
;
1030 wfProfileOut( __METHOD__
. '-checks' );
1031 wfProfileOut( __METHOD__
);
1034 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
1035 # Error messages or other handling should be performed by the filter function
1036 $status->setResult( false, self
::AS_FILTERING
);
1037 wfProfileOut( __METHOD__
. '-checks' );
1038 wfProfileOut( __METHOD__
);
1041 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1042 # Error messages etc. could be handled within the hook...
1043 $status->fatal( 'hookaborted' );
1044 $status->value
= self
::AS_HOOK_ERROR
;
1045 wfProfileOut( __METHOD__
. '-checks' );
1046 wfProfileOut( __METHOD__
);
1048 } elseif ( $this->hookError
!= '' ) {
1049 # ...or the hook could be expecting us to produce an error
1050 $status->fatal( 'hookaborted' );
1051 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1052 wfProfileOut( __METHOD__
. '-checks' );
1053 wfProfileOut( __METHOD__
);
1057 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1058 // Auto-block user's IP if the account was "hard" blocked
1059 $wgUser->spreadAnyEditBlock();
1060 # Check block state against master, thus 'false'.
1061 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1062 wfProfileOut( __METHOD__
. '-checks' );
1063 wfProfileOut( __METHOD__
);
1067 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1068 if ( $this->kblength
> $wgMaxArticleSize ) {
1069 // Error will be displayed by showEditForm()
1070 $this->tooBig
= true;
1071 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1072 wfProfileOut( __METHOD__
. '-checks' );
1073 wfProfileOut( __METHOD__
);
1077 if ( !$wgUser->isAllowed( 'edit' ) ) {
1078 if ( $wgUser->isAnon() ) {
1079 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1080 wfProfileOut( __METHOD__
. '-checks' );
1081 wfProfileOut( __METHOD__
);
1084 $status->fatal( 'readonlytext' );
1085 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1086 wfProfileOut( __METHOD__
. '-checks' );
1087 wfProfileOut( __METHOD__
);
1092 if ( wfReadOnly() ) {
1093 $status->fatal( 'readonlytext' );
1094 $status->value
= self
::AS_READ_ONLY_PAGE
;
1095 wfProfileOut( __METHOD__
. '-checks' );
1096 wfProfileOut( __METHOD__
);
1099 if ( $wgUser->pingLimiter() ) {
1100 $status->fatal( 'actionthrottledtext' );
1101 $status->value
= self
::AS_RATE_LIMITED
;
1102 wfProfileOut( __METHOD__
. '-checks' );
1103 wfProfileOut( __METHOD__
);
1107 # If the article has been deleted while editing, don't save it without
1109 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1110 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1111 wfProfileOut( __METHOD__
. '-checks' );
1112 wfProfileOut( __METHOD__
);
1116 wfProfileOut( __METHOD__
. '-checks' );
1118 # If article is new, insert it.
1119 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1120 $new = ( $aid == 0 );
1123 // Late check for create permission, just in case *PARANOIA*
1124 if ( !$this->mTitle
->userCan( 'create' ) ) {
1125 $status->fatal( 'nocreatetext' );
1126 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1127 wfDebug( __METHOD__
. ": no create permission\n" );
1128 wfProfileOut( __METHOD__
);
1132 # Don't save a new article if it's blank.
1133 if ( $this->textbox1
== '' ) {
1134 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1135 wfProfileOut( __METHOD__
);
1139 // Run post-section-merge edit filter
1140 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1141 # Error messages etc. could be handled within the hook...
1142 $status->fatal( 'hookaborted' );
1143 $status->value
= self
::AS_HOOK_ERROR
;
1144 wfProfileOut( __METHOD__
);
1146 } elseif ( $this->hookError
!= '' ) {
1147 # ...or the hook could be expecting us to produce an error
1148 $status->fatal( 'hookaborted' );
1149 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1150 wfProfileOut( __METHOD__
);
1154 # Handle the user preference to force summaries here. Check if it's not a redirect.
1155 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
1156 if ( md5( $this->summary
) == $this->autoSumm
) {
1157 $this->missingSummary
= true;
1158 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1159 $status->value
= self
::AS_SUMMARY_NEEDED
;
1160 wfProfileOut( __METHOD__
);
1165 $text = $this->textbox1
;
1166 $result['sectionanchor'] = '';
1167 if ( $this->section
== 'new' ) {
1168 if ( $this->sectiontitle
!== '' ) {
1169 // Insert the section title above the content.
1170 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle
) . "\n\n" . $text;
1172 // Jump to the new section
1173 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1175 // If no edit summary was specified, create one automatically from the section
1176 // title and have it link to the new section. Otherwise, respect the summary as
1178 if ( $this->summary
=== '' ) {
1179 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1180 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1182 } elseif ( $this->summary
!== '' ) {
1183 // Insert the section title above the content.
1184 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $text;
1186 // Jump to the new section
1187 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1189 // Create a link to the new section from the edit summary.
1190 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1191 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1195 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1199 # Article exists. Check for edit conflict.
1201 $this->mArticle
->clear(); # Force reload of dates, etc.
1202 $timestamp = $this->mArticle
->getTimestamp();
1204 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1206 if ( $timestamp != $this->edittime
) {
1207 $this->isConflict
= true;
1208 if ( $this->section
== 'new' ) {
1209 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1210 $this->mArticle
->getComment() == $this->summary
) {
1211 // Probably a duplicate submission of a new comment.
1212 // This can happen when squid resends a request after
1213 // a timeout but the first one actually went through.
1214 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1216 // New comment; suppress conflict.
1217 $this->isConflict
= false;
1218 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1220 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1221 # Suppress edit conflict with self, except for section edits where merging is required.
1222 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1223 $this->isConflict
= false;
1227 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1228 // backwards compatibility with old forms/bots).
1229 if ( $this->sectiontitle
!== '' ) {
1230 $sectionTitle = $this->sectiontitle
;
1232 $sectionTitle = $this->summary
;
1235 if ( $this->isConflict
) {
1236 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1237 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle, $this->edittime
);
1239 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1240 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle );
1242 if ( is_null( $text ) ) {
1243 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1244 $this->isConflict
= true;
1245 $text = $this->textbox1
; // do not try to merge here!
1246 } elseif ( $this->isConflict
) {
1248 if ( $this->mergeChangesInto( $text ) ) {
1249 // Successful merge! Maybe we should tell the user the good news?
1250 $this->isConflict
= false;
1251 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1253 $this->section
= '';
1254 $this->textbox1
= $text;
1255 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1259 if ( $this->isConflict
) {
1260 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1261 wfProfileOut( __METHOD__
);
1265 // Run post-section-merge edit filter
1266 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
1267 # Error messages etc. could be handled within the hook...
1268 $status->fatal( 'hookaborted' );
1269 $status->value
= self
::AS_HOOK_ERROR
;
1270 wfProfileOut( __METHOD__
);
1272 } elseif ( $this->hookError
!= '' ) {
1273 # ...or the hook could be expecting us to produce an error
1274 $status->fatal( 'hookaborted' );
1275 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1276 wfProfileOut( __METHOD__
);
1280 # Handle the user preference to force summaries here, but not for null edits
1281 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1282 && $this->getOriginalContent() != $text
1283 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1285 if ( md5( $this->summary
) == $this->autoSumm
) {
1286 $this->missingSummary
= true;
1287 $status->fatal( 'missingsummary' );
1288 $status->value
= self
::AS_SUMMARY_NEEDED
;
1289 wfProfileOut( __METHOD__
);
1294 # And a similar thing for new sections
1295 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1296 if ( trim( $this->summary
) == '' ) {
1297 $this->missingSummary
= true;
1298 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1299 $status->value
= self
::AS_SUMMARY_NEEDED
;
1300 wfProfileOut( __METHOD__
);
1306 wfProfileIn( __METHOD__
. '-sectionanchor' );
1307 $sectionanchor = '';
1308 if ( $this->section
== 'new' ) {
1309 if ( $this->textbox1
== '' ) {
1310 $this->missingComment
= true;
1311 $status->fatal( 'missingcommenttext' );
1312 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1313 wfProfileOut( __METHOD__
. '-sectionanchor' );
1314 wfProfileOut( __METHOD__
);
1317 if ( $this->sectiontitle
!== '' ) {
1318 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1319 // If no edit summary was specified, create one automatically from the section
1320 // title and have it link to the new section. Otherwise, respect the summary as
1322 if ( $this->summary
=== '' ) {
1323 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1324 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1326 } elseif ( $this->summary
!== '' ) {
1327 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1328 # This is a new section, so create a link to the new section
1329 # in the revision summary.
1330 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1331 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1333 } elseif ( $this->section
!= '' ) {
1334 # Try to get a section anchor from the section source, redirect to edited section if header found
1335 # XXX: might be better to integrate this into Article::replaceSection
1336 # for duplicate heading checking and maybe parsing
1337 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1338 # we can't deal with anchors, includes, html etc in the header for now,
1339 # headline would need to be parsed to improve this
1340 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1341 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1344 $result['sectionanchor'] = $sectionanchor;
1345 wfProfileOut( __METHOD__
. '-sectionanchor' );
1347 // Save errors may fall down to the edit form, but we've now
1348 // merged the section into full text. Clear the section field
1349 // so that later submission of conflict forms won't try to
1350 // replace that into a duplicated mess.
1351 $this->textbox1
= $text;
1352 $this->section
= '';
1354 $status->value
= self
::AS_SUCCESS_UPDATE
;
1357 // Check for length errors again now that the section is merged in
1358 $this->kblength
= (int)( strlen( $text ) / 1024 );
1359 if ( $this->kblength
> $wgMaxArticleSize ) {
1360 $this->tooBig
= true;
1361 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1362 wfProfileOut( __METHOD__
);
1366 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1367 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1368 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1369 ( $bot ? EDIT_FORCE_BOT
: 0 );
1371 $doEditStatus = $this->mArticle
->doEdit( $text, $this->summary
, $flags );
1373 if ( $doEditStatus->isOK() ) {
1374 $result['redirect'] = Title
::newFromRedirect( $text ) !== null;
1375 $this->commitWatch();
1376 wfProfileOut( __METHOD__
);
1379 $this->isConflict
= true;
1380 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1381 wfProfileOut( __METHOD__
);
1382 return $doEditStatus;
1387 * Commit the change of watch status
1389 protected function commitWatch() {
1391 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1392 $dbw = wfGetDB( DB_MASTER
);
1394 if ( $this->watchthis
) {
1395 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1397 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1404 * Check if no edits were made by other users since
1405 * the time a user started editing the page. Limit to
1406 * 50 revisions for the sake of performance.
1409 * @param $edittime string
1413 protected function userWasLastToEdit( $id, $edittime ) {
1414 if( !$id ) return false;
1415 $dbw = wfGetDB( DB_MASTER
);
1416 $res = $dbw->select( 'revision',
1419 'rev_page' => $this->mTitle
->getArticleId(),
1420 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1423 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1424 foreach ( $res as $row ) {
1425 if( $row->rev_user
!= $id ) {
1436 * @parma $editText string
1440 function mergeChangesInto( &$editText ){
1441 wfProfileIn( __METHOD__
);
1443 $db = wfGetDB( DB_MASTER
);
1445 // This is the revision the editor started from
1446 $baseRevision = $this->getBaseRevision();
1447 if ( is_null( $baseRevision ) ) {
1448 wfProfileOut( __METHOD__
);
1451 $baseText = $baseRevision->getText();
1453 // The current state, we want to merge updates into it
1454 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1455 if ( is_null( $currentRevision ) ) {
1456 wfProfileOut( __METHOD__
);
1459 $currentText = $currentRevision->getText();
1462 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1463 $editText = $result;
1464 wfProfileOut( __METHOD__
);
1467 wfProfileOut( __METHOD__
);
1475 function getBaseRevision() {
1476 if ( !$this->mBaseRevision
) {
1477 $db = wfGetDB( DB_MASTER
);
1478 $baseRevision = Revision
::loadFromTimestamp(
1479 $db, $this->mTitle
, $this->edittime
);
1480 return $this->mBaseRevision
= $baseRevision;
1482 return $this->mBaseRevision
;
1487 * Check given input text against $wgSpamRegex, and return the text of the first match.
1489 * @param $text string
1491 * @return string|false matching string or false
1493 public static function matchSpamRegex( $text ) {
1494 global $wgSpamRegex;
1495 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1496 $regexes = (array)$wgSpamRegex;
1497 return self
::matchSpamRegexInternal( $text, $regexes );
1501 * Check given input text against $wgSpamRegex, and return the text of the first match.
1503 * @parma $text string
1505 * @return string|false matching string or false
1507 public static function matchSummarySpamRegex( $text ) {
1508 global $wgSummarySpamRegex;
1509 $regexes = (array)$wgSummarySpamRegex;
1510 return self
::matchSpamRegexInternal( $text, $regexes );
1514 * @param $text string
1515 * @param $regexes array
1516 * @return bool|string
1518 protected static function matchSpamRegexInternal( $text, $regexes ) {
1519 foreach( $regexes as $regex ) {
1521 if( preg_match( $regex, $text, $matches ) ) {
1528 function setHeaders() {
1530 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1531 if ( $this->isConflict
) {
1532 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1533 } elseif ( $this->section
!= '' ) {
1534 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1535 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1537 # Use the title defined by DISPLAYTITLE magic word when present
1538 if ( isset( $this->mParserOutput
)
1539 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1542 $title = $this->getContextTitle()->getPrefixedText();
1544 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1549 * Show all applicable editing introductions
1551 protected function showIntro() {
1552 global $wgOut, $wgUser;
1553 if ( $this->suppressIntro
) {
1557 $namespace = $this->mTitle
->getNamespace();
1559 if ( $namespace == NS_MEDIAWIKI
) {
1560 # Show a warning if editing an interface message
1561 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1564 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1565 # Show log extract when the user is currently blocked
1566 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1567 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1568 $username = $parts[0];
1569 $user = User
::newFromName( $username, false /* allow IP users*/ );
1570 $ip = User
::isIP( $username );
1571 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1572 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1573 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1574 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1575 LogEventsList
::showLogExtract(
1578 $user->getUserPage(),
1582 'showIfEmpty' => false,
1584 'blocked-notice-logextract',
1585 $user->getName() # Support GENDER in notice
1591 # Try to add a custom edit intro, or use the standard one if this is not possible.
1592 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1593 if ( $wgUser->isLoggedIn() ) {
1594 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1596 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1599 # Give a notice if the user is editing a deleted/moved page...
1600 if ( !$this->mTitle
->exists() ) {
1601 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1602 '', array( 'lim' => 10,
1603 'conds' => array( "log_action != 'revision'" ),
1604 'showIfEmpty' => false,
1605 'msgKey' => array( 'recreate-moveddeleted-warn') )
1611 * Attempt to show a custom editing introduction, if supplied
1615 protected function showCustomIntro() {
1616 if ( $this->editintro
) {
1617 $title = Title
::newFromText( $this->editintro
);
1618 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1620 // Added using template syntax, to take <noinclude>'s into account.
1621 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1632 * Send the edit form and related headers to $wgOut
1633 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1634 * during form output near the top, for captchas and the like.
1636 function showEditForm( $formCallback = null ) {
1637 global $wgOut, $wgUser;
1639 wfProfileIn( __METHOD__
);
1641 #need to parse the preview early so that we know which templates are used,
1642 #otherwise users with "show preview after edit box" will get a blank list
1643 #we parse this near the beginning so that setHeaders can do the title
1644 #setting work instead of leaving it in getPreviewText
1645 $previewOutput = '';
1646 if ( $this->formtype
== 'preview' ) {
1647 $previewOutput = $this->getPreviewText();
1650 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1652 $this->setHeaders();
1654 # Enabled article-related sidebar, toplinks, etc.
1655 $wgOut->setArticleRelated( true );
1657 if ( $this->showHeader() === false ) {
1658 wfProfileOut( __METHOD__
);
1662 $wgOut->addHTML( $this->editFormPageTop
);
1664 if ( $wgUser->getOption( 'previewontop' ) ) {
1665 $this->displayPreviewArea( $previewOutput, true );
1668 $wgOut->addHTML( $this->editFormTextTop
);
1670 $showToolbar = true;
1671 if ( $this->wasDeletedSinceLastEdit() ) {
1672 if ( $this->formtype
== 'save' ) {
1673 // Hide the toolbar and edit area, user can click preview to get it back
1674 // Add an confirmation checkbox and explanation.
1675 $showToolbar = false;
1677 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1678 'deletedwhileediting' );
1682 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
1683 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1684 'enctype' => 'multipart/form-data' ) ) );
1686 if ( is_callable( $formCallback ) ) {
1687 call_user_func_array( $formCallback, array( &$wgOut ) );
1690 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1692 // Put these up at the top to ensure they aren't lost on early form submission
1693 $this->showFormBeforeText();
1695 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1696 $username = $this->lastDelete
->user_name
;
1697 $comment = $this->lastDelete
->log_comment
;
1699 // It is better to not parse the comment at all than to have templates expanded in the middle
1700 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1701 $key = $comment === ''
1702 ?
'confirmrecreate-noreason'
1703 : 'confirmrecreate';
1705 '<div class="mw-confirm-recreate">' .
1706 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1707 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1708 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1714 # If a blank edit summary was previously provided, and the appropriate
1715 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1716 # user being bounced back more than once in the event that a summary
1719 # For a bit more sophisticated detection of blank summaries, hash the
1720 # automatic one and pass that in the hidden field wpAutoSummary.
1721 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
1722 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1725 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1726 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1728 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
1730 if ( $this->section
== 'new' ) {
1731 $this->showSummaryInput( true, $this->summary
);
1732 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1735 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1737 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1738 $wgOut->addHTML( EditPage
::getEditToolbar() );
1741 if ( $this->isConflict
) {
1742 // In an edit conflict bypass the overrideable content form method
1743 // and fallback to the raw wpTextbox1 since editconflicts can't be
1744 // resolved between page source edits and custom ui edits using the
1746 $this->textbox2
= $this->textbox1
;
1747 $this->textbox1
= $this->getCurrentText();
1749 $this->showTextbox1();
1751 $this->showContentForm();
1754 $wgOut->addHTML( $this->editFormTextAfterContent
);
1756 $wgOut->addWikiText( $this->getCopywarn() );
1758 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1760 $this->showStandardInputs();
1762 $this->showFormAfterText();
1764 $this->showTosSummary();
1766 $this->showEditTools();
1768 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
1770 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
1771 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
1773 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
1774 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
1776 if ( $this->isConflict
) {
1777 $this->showConflict();
1780 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
1782 if ( !$wgUser->getOption( 'previewontop' ) ) {
1783 $this->displayPreviewArea( $previewOutput, false );
1786 wfProfileOut( __METHOD__
);
1790 * Extract the section title from current section text, if any.
1792 * @param string $text
1793 * @return Mixed|string or false
1795 public static function extractSectionTitle( $text ) {
1796 preg_match( "/^(=+)(.+)\\1(\n|$)/i", $text, $matches );
1797 if ( !empty( $matches[2] ) ) {
1799 return $wgParser->stripSectionName(trim($matches[2]));
1805 protected function showHeader() {
1806 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1807 if ( $this->isConflict
) {
1808 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1809 $this->edittime
= $this->mArticle
->getTimestamp();
1811 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
1812 // We use $this->section to much before this and getVal('wgSection') directly in other places
1813 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1814 // Someone is welcome to try refactoring though
1815 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1819 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1820 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1821 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
1822 if ( $sectionTitle !== false ) {
1823 $this->summary
= "/* $sectionTitle */ ";
1828 if ( $this->missingComment
) {
1829 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1832 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1833 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1836 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1837 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1840 if ( $this->hookError
!== '' ) {
1841 $wgOut->addWikiText( $this->hookError
);
1844 if ( !$this->checkUnicodeCompliantBrowser() ) {
1845 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1848 if ( $this->section
!= 'new' ) {
1849 $revision = $this->mArticle
->getRevisionFetched();
1851 // Let sysop know that this will make private content public if saved
1853 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
1854 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1855 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
1856 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1859 if ( !$revision->isCurrent() ) {
1860 $this->mArticle
->setOldSubtitle( $revision->getId() );
1861 $wgOut->addWikiMsg( 'editingold' );
1863 } elseif ( $this->mTitle
->exists() ) {
1864 // Something went wrong
1866 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
1867 array( 'missing-article', $this->mTitle
->getPrefixedText(),
1868 wfMsgNoTrans( 'missingarticle-rev', $this->oldid
) ) );
1873 if ( wfReadOnly() ) {
1874 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1875 } elseif ( $wgUser->isAnon() ) {
1876 if ( $this->formtype
!= 'preview' ) {
1877 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1879 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
1882 if ( $this->isCssJsSubpage
) {
1883 # Check the skin exists
1884 if ( $this->isWrongCaseCssJsPage
) {
1885 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
1887 if ( $this->formtype
!== 'preview' ) {
1888 if ( $this->isCssSubpage
)
1889 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
1890 if ( $this->isJsSubpage
)
1891 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
1896 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
1897 # Is the title semi-protected?
1898 if ( $this->mTitle
->isSemiProtected() ) {
1899 $noticeMsg = 'semiprotectedpagewarning';
1901 # Then it must be protected based on static groups (regular)
1902 $noticeMsg = 'protectedpagewarning';
1904 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1905 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1907 if ( $this->mTitle
->isCascadeProtected() ) {
1908 # Is this page under cascading protection from some source pages?
1909 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1910 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
1911 $cascadeSourcesCount = count( $cascadeSources );
1912 if ( $cascadeSourcesCount > 0 ) {
1913 # Explain, and list the titles responsible
1914 foreach( $cascadeSources as $page ) {
1915 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1918 $notice .= '</div>';
1919 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1921 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1922 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1924 'showIfEmpty' => false,
1925 'msgKey' => array( 'titleprotectedwarning' ),
1926 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
1929 if ( $this->kblength
=== false ) {
1930 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1933 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1934 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
1935 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
1937 if( !wfMessage('longpage-hint')->isDisabled() ) {
1938 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
1939 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
1946 * Standard summary input and label (wgSummary), abstracted so EditPage
1947 * subclasses may reorganize the form.
1948 * Note that you do not need to worry about the label's for=, it will be
1949 * inferred by the id given to the input. You can remove them both by
1950 * passing array( 'id' => false ) to $userInputAttrs.
1952 * @param $summary string The value of the summary input
1953 * @param $labelText string The html to place inside the label
1954 * @param $inputAttrs array of attrs to use on the input
1955 * @param $spanLabelAttrs array of attrs to use on the span inside the label
1957 * @return array An array in the format array( $label, $input )
1959 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
1960 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
1961 $inputAttrs = ( is_array($inputAttrs) ?
$inputAttrs : array() ) +
array(
1962 'id' => 'wpSummary',
1963 'maxlength' => '200',
1966 'spellcheck' => 'true',
1967 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
1969 $spanLabelAttrs = ( is_array($spanLabelAttrs) ?
$spanLabelAttrs : array() ) +
array(
1970 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
1971 'id' => "wpSummaryLabel"
1976 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1977 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
1980 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
1982 return array( $label, $input );
1986 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1987 * up top, or false if this is the comment summary
1988 * down below the textarea
1989 * @param $summary String: The text of the summary to display
1992 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1993 global $wgOut, $wgContLang;
1994 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1995 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1996 if ( $isSubjectPreview ) {
1997 if ( $this->nosummary
) {
2001 if ( !$this->mShowSummaryField
) {
2005 $summary = $wgContLang->recodeForEdit( $summary );
2006 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
2007 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
2008 $wgOut->addHTML("{$label} {$input}");
2012 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2013 * up top, or false if this is the comment summary
2014 * down below the textarea
2015 * @param $summary String: the text of the summary to display
2018 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2019 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2024 if ( $isSubjectPreview )
2025 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2027 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2029 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2030 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2033 protected function showFormBeforeText() {
2035 $section = htmlspecialchars( $this->section
);
2036 $wgOut->addHTML( <<<HTML
2037 <input type='hidden' value="{$section}" name="wpSection" />
2038 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2039 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2040 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2044 if ( !$this->checkUnicodeCompliantBrowser() )
2045 $wgOut->addHTML(Html
::hidden( 'safemode', '1' ));
2048 protected function showFormAfterText() {
2049 global $wgOut, $wgUser;
2051 * To make it harder for someone to slip a user a page
2052 * which submits an edit form to the wiki without their
2053 * knowledge, a random token is associated with the login
2054 * session. If it's not passed back with the submission,
2055 * we won't save the page, or render user JavaScript and
2058 * For anon editors, who may not have a session, we just
2059 * include the constant suffix to prevent editing from
2060 * broken text-mangling proxies.
2062 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2066 * Subpage overridable method for printing the form for page content editing
2067 * By default this simply outputs wpTextbox1
2068 * Subclasses can override this to provide a custom UI for editing;
2069 * be it a form, or simply wpTextbox1 with a modified content that will be
2070 * reverse modified when extracted from the post data.
2071 * Note that this is basically the inverse for importContentFormData
2073 protected function showContentForm() {
2074 $this->showTextbox1();
2078 * Method to output wpTextbox1
2079 * The $textoverride method can be used by subclasses overriding showContentForm
2080 * to pass back to this method.
2082 * @param $customAttribs An array of html attributes to use in the textarea
2083 * @param $textoverride String: optional text to override $this->textarea1 with
2085 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2086 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2087 $attribs = array( 'style' => 'display:none;' );
2089 $classes = array(); // Textarea CSS
2090 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2091 # Is the title semi-protected?
2092 if ( $this->mTitle
->isSemiProtected() ) {
2093 $classes[] = 'mw-textarea-sprotected';
2095 # Then it must be protected based on static groups (regular)
2096 $classes[] = 'mw-textarea-protected';
2098 # Is the title cascade-protected?
2099 if ( $this->mTitle
->isCascadeProtected() ) {
2100 $classes[] = 'mw-textarea-cprotected';
2104 $attribs = array( 'tabindex' => 1 );
2106 if ( is_array( $customAttribs ) ) {
2107 $attribs +
= $customAttribs;
2110 if ( count( $classes ) ) {
2111 if ( isset( $attribs['class'] ) ) {
2112 $classes[] = $attribs['class'];
2114 $attribs['class'] = implode( ' ', $classes );
2118 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2121 protected function showTextbox2() {
2122 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2125 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2126 global $wgOut, $wgUser;
2128 $wikitext = $this->safeUnicodeOutput( $content );
2129 if ( strval($wikitext) !== '' ) {
2130 // Ensure there's a newline at the end, otherwise adding lines
2132 // But don't add a newline if the ext is empty, or Firefox in XHTML
2133 // mode will show an extra newline. A bit annoying.
2137 $attribs = $customAttribs +
array(
2140 'rows' => $wgUser->getIntOption( 'rows' ),
2141 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2144 $pageLang = $this->mTitle
->getPageLanguage();
2145 $attribs['lang'] = $pageLang->getCode();
2146 $attribs['dir'] = $pageLang->getDir();
2148 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2151 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2155 $classes[] = 'ontop';
2157 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2159 if ( $this->formtype
!= 'preview' )
2160 $attribs['style'] = 'display: none;';
2162 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2164 if ( $this->formtype
== 'preview' ) {
2165 $this->showPreview( $previewOutput );
2168 $wgOut->addHTML( '</div>' );
2170 if ( $this->formtype
== 'diff') {
2176 * Append preview output to $wgOut.
2177 * Includes category rendering if this is a category page.
2179 * @param $text String: the HTML to be output for the preview.
2181 protected function showPreview( $text ) {
2183 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2184 $this->mArticle
->openShowCategory();
2186 # This hook seems slightly odd here, but makes things more
2187 # consistent for extensions.
2188 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
2189 $wgOut->addHTML( $text );
2190 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2191 $this->mArticle
->closeShowCategory();
2196 * Get a diff between the current contents of the edit box and the
2197 * version of the page we're editing from.
2199 * If this is a section edit, we'll replace the section as for final
2200 * save and then make a comparison.
2202 function showDiff() {
2203 global $wgUser, $wgContLang, $wgParser, $wgOut;
2205 $oldtext = $this->getOriginalContent();
2206 $newtext = $this->mArticle
->replaceSection(
2207 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2209 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2211 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2212 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle
, $wgUser, $popts );
2214 if ( $oldtext !== false ||
$newtext != '' ) {
2215 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2216 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2218 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2219 $de->setText( $oldtext, $newtext );
2220 $difftext = $de->getDiff( $oldtitle, $newtitle );
2221 $de->showDiffStyle();
2226 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2230 * Give a chance for site and per-namespace customizations of
2231 * terms of service summary link that might exist separately
2232 * from the copyright notice.
2234 * This will display between the save button and the edit tools,
2235 * so should remain short!
2237 protected function showTosSummary() {
2238 $msg = 'editpage-tos-summary';
2239 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2240 if( !wfMessage( $msg )->isDisabled() ) {
2242 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2243 $wgOut->addWikiMsg( $msg );
2244 $wgOut->addHTML( '</div>' );
2248 protected function showEditTools() {
2250 $wgOut->addHTML( '<div class="mw-editTools">' .
2251 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2255 protected function getCopywarn() {
2256 global $wgRightsText;
2257 if ( $wgRightsText ) {
2258 $copywarnMsg = array( 'copyrightwarning',
2259 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2262 $copywarnMsg = array( 'copyrightwarning2',
2263 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2265 // Allow for site and per-namespace customization of contribution/copyright notice.
2266 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2268 return "<div id=\"editpage-copywarn\">\n" .
2269 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
2272 protected function showStandardInputs( &$tabindex = 2 ) {
2274 $wgOut->addHTML( "<div class='editOptions'>\n" );
2276 if ( $this->section
!= 'new' ) {
2277 $this->showSummaryInput( false, $this->summary
);
2278 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2281 $checkboxes = $this->getCheckboxes( $tabindex,
2282 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2283 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2284 $wgOut->addHTML( "<div class='editButtons'>\n" );
2285 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2287 $cancel = $this->getCancelLink();
2288 if ( $cancel !== '' ) {
2289 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2291 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2292 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
2293 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
2294 htmlspecialchars( wfMsg( 'newwindow' ) );
2295 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2296 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2300 * Show an edit conflict. textbox1 is already shown in showEditForm().
2301 * If you want to use another entry point to this function, be careful.
2303 protected function showConflict() {
2306 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2307 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2309 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2310 $de->setText( $this->textbox2
, $this->textbox1
);
2311 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2313 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2314 $this->showTextbox2();
2321 public function getCancelLink() {
2322 $cancelParams = array();
2323 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2324 $cancelParams['oldid'] = $this->oldid
;
2327 return Linker
::linkKnown(
2328 $this->getContextTitle(),
2329 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2330 array( 'id' => 'mw-editform-cancel' ),
2336 * Returns the URL to use in the form's action attribute.
2337 * This is used by EditPage subclasses when simply customizing the action
2338 * variable in the constructor is not enough. This can be used when the
2339 * EditPage lives inside of a Special page rather than a custom page action.
2341 * @param $title Title object for which is being edited (where we go to for &action= links)
2344 protected function getActionURL( Title
$title ) {
2345 return $title->getLocalURL( array( 'action' => $this->action
) );
2349 * Check if a page was deleted while the user was editing it, before submit.
2350 * Note that we rely on the logging table, which hasn't been always there,
2351 * but that doesn't matter, because this only applies to brand new
2354 protected function wasDeletedSinceLastEdit() {
2355 if ( $this->deletedSinceEdit
!== null ) {
2356 return $this->deletedSinceEdit
;
2359 $this->deletedSinceEdit
= false;
2361 if ( $this->mTitle
->isDeletedQuick() ) {
2362 $this->lastDelete
= $this->getLastDelete();
2363 if ( $this->lastDelete
) {
2364 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2365 if ( $deleteTime > $this->starttime
) {
2366 $this->deletedSinceEdit
= true;
2371 return $this->deletedSinceEdit
;
2374 protected function getLastDelete() {
2375 $dbr = wfGetDB( DB_SLAVE
);
2376 $data = $dbr->selectRow(
2377 array( 'logging', 'user' ),
2388 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2389 'log_title' => $this->mTitle
->getDBkey(),
2390 'log_type' => 'delete',
2391 'log_action' => 'delete',
2392 'user_id=log_user' ),
2394 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2396 // Quick paranoid permission checks...
2397 if( is_object( $data ) ) {
2398 if( $data->log_deleted
& LogPage
::DELETED_USER
)
2399 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2400 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2401 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2407 * Get the rendered text for previewing.
2410 function getPreviewText() {
2411 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2413 wfProfileIn( __METHOD__
);
2415 if ( $wgRawHtml && !$this->mTokenOk
) {
2416 // Could be an offsite preview attempt. This is very unsafe if
2417 // HTML is enabled, as it could be an attack.
2419 if ( $this->textbox1
!== '' ) {
2420 // Do not put big scary notice, if previewing the empty
2421 // string, which happens when you initially edit
2422 // a category page, due to automatic preview-on-open.
2423 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2424 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2426 wfProfileOut( __METHOD__
);
2430 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2431 if ( $this->mTokenOkExceptSuffix
) {
2432 $note = wfMsg( 'token_suffix_mismatch' );
2434 $note = wfMsg( 'session_fail_preview' );
2436 } elseif ( $this->incompleteForm
) {
2437 $note = wfMsg( 'edit_form_incomplete' );
2439 $note = wfMsg( 'previewnote' );
2442 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2443 $parserOptions->setEditSection( false );
2444 $parserOptions->setTidy( true );
2445 $parserOptions->setIsPreview( true );
2446 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2448 # don't parse non-wikitext pages, show message about preview
2449 # 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?
2451 if ( $this->isCssJsSubpage ||
!$this->mTitle
->isWikitextPage() ) {
2452 if( $this->mTitle
->isCssJsSubpage() ) {
2454 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2460 # Used messages to make sure grep find them:
2461 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2463 if (preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2464 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2465 $class = "mw-code mw-css";
2466 } elseif (preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2467 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2468 $class = "mw-code mw-js";
2470 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2474 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2475 $previewHTML = $parserOutput->mText
;
2476 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2478 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2480 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2482 $toparse = $this->textbox1
;
2484 # If we're adding a comment, we need to show the
2485 # summary as the headline
2486 if ( $this->section
== "new" && $this->summary
!= "" ) {
2487 $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $toparse;
2490 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2492 $parserOptions->enableLimitReport();
2494 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle
, $wgUser, $parserOptions );
2495 $parserOutput = $wgParser->parse( $toparse, $this->mTitle
, $parserOptions );
2497 $previewHTML = $parserOutput->getText();
2498 $this->mParserOutput
= $parserOutput;
2499 $wgOut->addParserOutputNoText( $parserOutput );
2501 if ( count( $parserOutput->getWarnings() ) ) {
2502 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2507 if( $this->isConflict
) {
2508 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2510 $conflict = '<hr />';
2513 $previewhead = "<div class='previewnote'>\n" .
2514 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2515 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2517 $pageLang = $this->mTitle
->getPageLanguage();
2518 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2519 'class' => 'mw-content-'.$pageLang->getDir() );
2520 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2522 wfProfileOut( __METHOD__
);
2523 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2529 function getTemplates() {
2530 if ( $this->preview ||
$this->section
!= '' ) {
2531 $templates = array();
2532 if ( !isset( $this->mParserOutput
) ) {
2535 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
2536 foreach( array_keys( $template ) as $dbk ) {
2537 $templates[] = Title
::makeTitle($ns, $dbk);
2542 return $this->mTitle
->getTemplateLinksFrom();
2547 * Shows a bulletin board style toolbar for common editing functions.
2548 * It can be disabled in the user preferences.
2549 * The necessary JavaScript code can be found in skins/common/edit.js.
2553 static function getEditToolbar() {
2554 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2555 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2557 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2560 * $toolarray is an array of arrays each of which includes the
2561 * filename of the button image (without path), the opening
2562 * tag, the closing tag, optionally a sample text that is
2563 * inserted between the two when no selection is highlighted
2564 * and. The tip text is shown when the user moves the mouse
2567 * Also here: accesskeys (key), which are not used yet until
2568 * someone can figure out a way to make them work in
2569 * IE. However, we should make sure these keys are not defined
2574 'image' => $wgLang->getImageFile( 'button-bold' ),
2575 'id' => 'mw-editbutton-bold',
2577 'close' => '\'\'\'',
2578 'sample' => wfMsg( 'bold_sample' ),
2579 'tip' => wfMsg( 'bold_tip' ),
2583 'image' => $wgLang->getImageFile( 'button-italic' ),
2584 'id' => 'mw-editbutton-italic',
2587 'sample' => wfMsg( 'italic_sample' ),
2588 'tip' => wfMsg( 'italic_tip' ),
2592 'image' => $wgLang->getImageFile( 'button-link' ),
2593 'id' => 'mw-editbutton-link',
2596 'sample' => wfMsg( 'link_sample' ),
2597 'tip' => wfMsg( 'link_tip' ),
2601 'image' => $wgLang->getImageFile( 'button-extlink' ),
2602 'id' => 'mw-editbutton-extlink',
2605 'sample' => wfMsg( 'extlink_sample' ),
2606 'tip' => wfMsg( 'extlink_tip' ),
2610 'image' => $wgLang->getImageFile( 'button-headline' ),
2611 'id' => 'mw-editbutton-headline',
2614 'sample' => wfMsg( 'headline_sample' ),
2615 'tip' => wfMsg( 'headline_tip' ),
2618 $imagesAvailable ?
array(
2619 'image' => $wgLang->getImageFile( 'button-image' ),
2620 'id' => 'mw-editbutton-image',
2621 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2623 'sample' => wfMsg( 'image_sample' ),
2624 'tip' => wfMsg( 'image_tip' ),
2627 $imagesAvailable ?
array(
2628 'image' => $wgLang->getImageFile( 'button-media' ),
2629 'id' => 'mw-editbutton-media',
2630 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2632 'sample' => wfMsg( 'media_sample' ),
2633 'tip' => wfMsg( 'media_tip' ),
2637 'image' => $wgLang->getImageFile( 'button-math' ),
2638 'id' => 'mw-editbutton-math',
2640 'close' => "</math>",
2641 'sample' => wfMsg( 'math_sample' ),
2642 'tip' => wfMsg( 'math_tip' ),
2646 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2647 'id' => 'mw-editbutton-nowiki',
2648 'open' => "<nowiki>",
2649 'close' => "</nowiki>",
2650 'sample' => wfMsg( 'nowiki_sample' ),
2651 'tip' => wfMsg( 'nowiki_tip' ),
2655 'image' => $wgLang->getImageFile( 'button-sig' ),
2656 'id' => 'mw-editbutton-signature',
2660 'tip' => wfMsg( 'sig_tip' ),
2664 'image' => $wgLang->getImageFile( 'button-hr' ),
2665 'id' => 'mw-editbutton-hr',
2666 'open' => "\n----\n",
2669 'tip' => wfMsg( 'hr_tip' ),
2674 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
2675 foreach ( $toolarray as $tool ) {
2681 $image = $wgStylePath . '/common/images/' . $tool['image'],
2682 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2683 // Older browsers show a "speedtip" type message only for ALT.
2684 // Ideally these should be different, realistically they
2685 // probably don't need to be.
2686 $tip = $tool['tip'],
2687 $open = $tool['open'],
2688 $close = $tool['close'],
2689 $sample = $tool['sample'],
2690 $cssId = $tool['id'],
2693 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2696 // This used to be called on DOMReady from mediawiki.action.edit, which
2697 // ended up causing race conditions with the setup code above.
2699 "// Create button bar\n" .
2700 "$(function() { mw.toolbar.init(); } );\n";
2703 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2705 $toolbar = '<div id="toolbar"></div>';
2707 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2713 * Returns an array of html code of the following checkboxes:
2716 * @param $tabindex Current tabindex
2717 * @param $checked Array of checkbox => bool, where bool indicates the checked
2718 * status of the checkbox
2722 public function getCheckboxes( &$tabindex, $checked ) {
2725 $checkboxes = array();
2727 // don't show the minor edit checkbox if it's a new page or section
2728 if ( !$this->isNew
) {
2729 $checkboxes['minor'] = '';
2730 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2731 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2733 'tabindex' => ++
$tabindex,
2734 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2735 'id' => 'wpMinoredit',
2737 $checkboxes['minor'] =
2738 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2739 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2740 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2741 ">{$minorLabel}</label>";
2745 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2746 $checkboxes['watch'] = '';
2747 if ( $wgUser->isLoggedIn() ) {
2749 'tabindex' => ++
$tabindex,
2750 'accesskey' => wfMsg( 'accesskey-watch' ),
2751 'id' => 'wpWatchthis',
2753 $checkboxes['watch'] =
2754 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2755 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2756 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2757 ">{$watchLabel}</label>";
2759 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2764 * Returns an array of html code of the following buttons:
2765 * save, diff, preview and live
2767 * @param $tabindex Current tabindex
2771 public function getEditButtons( &$tabindex ) {
2778 'tabindex' => ++
$tabindex,
2779 'value' => wfMsg( 'savearticle' ),
2780 'accesskey' => wfMsg( 'accesskey-save' ),
2781 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2783 $buttons['save'] = Xml
::element('input', $temp, '');
2785 ++
$tabindex; // use the same for preview and live preview
2787 'id' => 'wpPreview',
2788 'name' => 'wpPreview',
2790 'tabindex' => $tabindex,
2791 'value' => wfMsg( 'showpreview' ),
2792 'accesskey' => wfMsg( 'accesskey-preview' ),
2793 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2795 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
2796 $buttons['live'] = '';
2802 'tabindex' => ++
$tabindex,
2803 'value' => wfMsg( 'showdiff' ),
2804 'accesskey' => wfMsg( 'accesskey-diff' ),
2805 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2807 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
2809 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2814 * Output preview text only. This can be sucked into the edit page
2815 * via JavaScript, and saves the server time rendering the skin as
2816 * well as theoretically being more robust on the client (doesn't
2817 * disturb the edit box's undo history, won't eat your text on
2820 * @todo This doesn't include category or interlanguage links.
2821 * Would need to enhance it a bit, <s>maybe wrap them in XML
2822 * or something...</s> that might also require more skin
2823 * initialization, so check whether that's a problem.
2825 function livePreview() {
2828 header( 'Content-type: text/xml; charset=utf-8' );
2829 header( 'Cache-control: no-cache' );
2831 $previewText = $this->getPreviewText();
2832 #$categories = $skin->getCategoryLinks();
2835 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2836 Xml
::tags( 'livepreview', null,
2837 Xml
::element( 'preview', null, $previewText )
2838 #. Xml::element( 'category', null, $categories )
2844 * Call the stock "user is blocked" page
2846 * @deprecated in 1.19; throw an exception directly instead
2848 function blockedPage() {
2849 wfDeprecated( __METHOD__
, '1.19' );
2852 throw new UserBlockedError( $wgUser->mBlock
);
2856 * Produce the stock "please login to edit pages" page
2858 * @deprecated in 1.19; throw an exception directly instead
2860 function userNotLoggedInPage() {
2861 wfDeprecated( __METHOD__
, '1.19' );
2862 throw new PermissionsError( 'edit' );
2866 * Show an error page saying to the user that he has insufficient permissions
2867 * to create a new page
2869 * @deprecated in 1.19; throw an exception directly instead
2871 function noCreatePermission() {
2872 wfDeprecated( __METHOD__
, '1.19' );
2873 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
2874 throw new PermissionsError( $permission );
2878 * Creates a basic error page which informs the user that
2879 * they have attempted to edit a nonexistent section.
2881 function noSuchSectionPage() {
2884 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
2886 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
2887 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2888 $wgOut->addHTML( $res );
2890 $wgOut->returnToMain( false, $this->mTitle
);
2894 * Produce the stock "your edit contains spam" page
2896 * @param $match Text which triggered one or more filters
2897 * @deprecated since 1.17 Use method spamPageWithContent() instead
2899 static function spamPage( $match = false ) {
2900 wfDeprecated( __METHOD__
, '1.17' );
2902 global $wgOut, $wgTitle;
2904 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2906 $wgOut->addHTML( '<div id="spamprotected">' );
2907 $wgOut->addWikiMsg( 'spamprotectiontext' );
2909 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2911 $wgOut->addHTML( '</div>' );
2913 $wgOut->returnToMain( false, $wgTitle );
2917 * Show "your edit contains spam" page with your diff and text
2919 * @param $match Text which triggered one or more filters
2921 public function spamPageWithContent( $match = false ) {
2923 $this->textbox2
= $this->textbox1
;
2925 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2927 $wgOut->addHTML( '<div id="spamprotected">' );
2928 $wgOut->addWikiMsg( 'spamprotectiontext' );
2930 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2932 $wgOut->addHTML( '</div>' );
2934 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2935 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2936 $de->setText( $this->getCurrentText(), $this->textbox2
);
2937 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
2939 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2940 $this->showTextbox2();
2942 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
2946 * Format an anchor fragment as it would appear for a given section name
2947 * @param $text String
2951 function sectionAnchor( $text ) {
2953 return $wgParser->guessSectionNameFromWikiText( $text );
2957 * Check if the browser is on a blacklist of user-agents known to
2958 * mangle UTF-8 data on form submission. Returns true if Unicode
2959 * should make it through, false if it's known to be a problem.
2963 function checkUnicodeCompliantBrowser() {
2964 global $wgBrowserBlackList;
2965 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2966 // No User-Agent header sent? Trust it by default...
2969 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2970 foreach ( $wgBrowserBlackList as $browser ) {
2971 if ( preg_match($browser, $currentbrowser) ) {
2979 * Filter an input field through a Unicode de-armoring process if it
2980 * came from an old browser with known broken Unicode editing issues.
2982 * @param $request WebRequest
2983 * @param $field String
2987 function safeUnicodeInput( $request, $field ) {
2988 $text = rtrim( $request->getText( $field ) );
2989 return $request->getBool( 'safemode' )
2990 ?
$this->unmakesafe( $text )
2995 * @param $request WebRequest
2996 * @param $text string
2999 function safeUnicodeText( $request, $text ) {
3000 $text = rtrim( $text );
3001 return $request->getBool( 'safemode' )
3002 ?
$this->unmakesafe( $text )
3007 * Filter an output field through a Unicode armoring process if it is
3008 * going to an old browser with known broken Unicode editing issues.
3010 * @param $text String
3014 function safeUnicodeOutput( $text ) {
3016 $codedText = $wgContLang->recodeForEdit( $text );
3017 return $this->checkUnicodeCompliantBrowser()
3019 : $this->makesafe( $codedText );
3023 * A number of web browsers are known to corrupt non-ASCII characters
3024 * in a UTF-8 text editing environment. To protect against this,
3025 * detected browsers will be served an armored version of the text,
3026 * with non-ASCII chars converted to numeric HTML character references.
3028 * Preexisting such character references will have a 0 added to them
3029 * to ensure that round-trips do not alter the original data.
3031 * @param $invalue String
3035 function makesafe( $invalue ) {
3036 // Armor existing references for reversability.
3037 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3042 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3043 $bytevalue = ord( $invalue[$i] );
3044 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
3045 $result .= chr( $bytevalue );
3047 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
3048 $working = $working << 6;
3049 $working +
= ($bytevalue & 0x3F);
3051 if ( $bytesleft <= 0 ) {
3052 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3054 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
3055 $working = $bytevalue & 0x1F;
3057 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
3058 $working = $bytevalue & 0x0F;
3060 } else { //1111 0xxx
3061 $working = $bytevalue & 0x07;
3069 * Reverse the previously applied transliteration of non-ASCII characters
3070 * back to UTF-8. Used to protect data from corruption by broken web browsers
3071 * as listed in $wgBrowserBlackList.
3073 * @param $invalue String
3077 function unmakesafe( $invalue ) {
3079 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3080 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+
3] != '0' ) ) {
3084 $hexstring .= $invalue[$i];
3086 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3088 // Do some sanity checks. These aren't needed for reversability,
3089 // but should help keep the breakage down if the editor
3090 // breaks one of the entities whilst editing.
3091 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
3092 $codepoint = hexdec($hexstring);
3093 $result .= codepointToUtf8( $codepoint );
3095 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3098 $result .= substr( $invalue, $i, 1 );
3101 // reverse the transform that we made for reversability reasons.
3102 return strtr( $result, array( "�" => "&#x" ) );