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 wfProfileIn( __METHOD__
."-business-end" );
239 $this->isConflict
= false;
240 // css / js subpages of user pages get a special treatment
241 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
242 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
243 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
244 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
245 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
247 # Show applicable editing introductions
248 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
252 # Attempt submission here. This will check for edit conflicts,
253 # and redundantly check for locked database, blocked IPs, etc.
254 # that edit() already checked just in case someone tries to sneak
255 # in the back door with a hand-edited submission URL.
257 if ( 'save' == $this->formtype
) {
258 if ( !$this->attemptSave() ) {
259 wfProfileOut( __METHOD__
."-business-end" );
260 wfProfileOut( __METHOD__
);
265 # First time through: get contents, set time for conflict
267 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
268 if ( $this->initialiseForm() === false ) {
269 $this->noSuchSectionPage();
270 wfProfileOut( __METHOD__
."-business-end" );
271 wfProfileOut( __METHOD__
);
274 if ( !$this->mTitle
->getArticleId() )
275 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
277 wfRunHooks( 'EditFormInitialText', array( $this ) );
280 $this->showEditForm();
281 wfProfileOut( __METHOD__
."-business-end" );
282 wfProfileOut( __METHOD__
);
288 protected function getEditPermissionErrors() {
290 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
291 # Can this title be created?
292 if ( !$this->mTitle
->exists() ) {
293 $permErrors = array_merge( $permErrors,
294 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
296 # Ignore some permissions errors when a user is just previewing/viewing diffs
298 foreach( $permErrors as $error ) {
299 if ( ( $this->preview ||
$this->diff
) &&
300 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
305 $permErrors = wfArrayDiff2( $permErrors, $remove );
310 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
311 * but with the following differences:
312 * - If redlink=1, the user will be redirected to the page
313 * - If there is content to display or the error occurs while either saving,
314 * previewing or showing the difference, it will be a
315 * "View source for ..." page displaying the source code after the error message.
318 * @param $permErrors Array of permissions errors, as returned by
319 * Title::getUserPermissionsErrors().
321 protected function displayPermissionsError( array $permErrors ) {
322 global $wgRequest, $wgOut;
324 if ( $wgRequest->getBool( 'redlink' ) ) {
325 // The edit page was reached via a red link.
326 // Redirect to the article page and let them click the edit tab if
327 // they really want a permission error.
328 $wgOut->redirect( $this->mTitle
->getFullUrl() );
332 $content = $this->getContent();
334 # Use the normal message if there's nothing to display
335 if ( $this->firsttime
&& $content === '' ) {
336 $action = $this->mTitle
->exists() ?
'edit' :
337 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
338 throw new PermissionsError( $action, $permErrors );
341 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
342 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
343 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
344 $wgOut->addHTML( "<hr />\n" );
346 # If the user made changes, preserve them when showing the markup
347 # (This happens when a user is blocked during edit, for instance)
348 if ( !$this->firsttime
) {
349 $content = $this->textbox1
;
350 $wgOut->addWikiMsg( 'viewyourtext' );
352 $wgOut->addWikiMsg( 'viewsourcetext' );
355 $this->showTextbox( $content, 'wpTextbox1', array( 'readonly' ) );
357 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
358 Linker
::formatTemplates( $this->getTemplates() ) ) );
360 if ( $this->mTitle
->exists() ) {
361 $wgOut->returnToMain( null, $this->mTitle
);
366 * Show a read-only error
367 * Parameters are the same as OutputPage:readOnlyPage()
368 * Redirect to the article page if redlink=1
369 * @deprecated in 1.19; use displayPermissionsError() instead
371 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
372 wfDeprecated( __METHOD__
, '1.19' );
374 global $wgRequest, $wgOut;
375 if ( $wgRequest->getBool( 'redlink' ) ) {
376 // The edit page was reached via a red link.
377 // Redirect to the article page and let them click the edit tab if
378 // they really want a permission error.
379 $wgOut->redirect( $this->mTitle
->getFullUrl() );
381 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
386 * Should we show a preview when the edit form is first shown?
390 protected function previewOnOpen() {
391 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
392 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
393 // Explicit override from request
395 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
396 // Explicit override from request
398 } elseif ( $this->section
== 'new' ) {
399 // Nothing *to* preview for new sections
401 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
402 // Standard preference behaviour
404 } elseif ( !$this->mTitle
->exists() &&
405 isset($wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]) &&
406 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
408 // Categories are special
416 * Checks whether the user entered a skin name in uppercase,
417 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
421 protected function isWrongCaseCssJsPage() {
422 if( $this->mTitle
->isCssJsSubpage() ) {
423 $name = $this->mTitle
->getSkinFromCssJsSubpage();
424 $skins = array_merge(
425 array_keys( Skin
::getSkinNames() ),
428 return !in_array( $name, $skins )
429 && in_array( strtolower( $name ), $skins );
436 * Does this EditPage class support section editing?
437 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
441 protected function isSectionEditSupported() {
446 * This function collects the form data and uses it to populate various member variables.
447 * @param $request WebRequest
449 function importFormData( &$request ) {
450 global $wgLang, $wgUser;
452 wfProfileIn( __METHOD__
);
454 # Section edit can come from either the form or a link
455 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
457 if ( $request->wasPosted() ) {
458 # These fields need to be checked for encoding.
459 # Also remove trailing whitespace, but don't remove _initial_
460 # whitespace from the text boxes. This may be significant formatting.
461 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
462 if ( !$request->getCheck('wpTextbox2') ) {
463 // Skip this if wpTextbox2 has input, it indicates that we came
464 // from a conflict page with raw page text, not a custom form
465 // modified by subclasses
466 wfProfileIn( get_class($this)."::importContentFormData" );
467 $textbox1 = $this->importContentFormData( $request );
468 if ( isset($textbox1) )
469 $this->textbox1
= $textbox1;
470 wfProfileOut( get_class($this)."::importContentFormData" );
473 # Truncate for whole multibyte characters. +5 bytes for ellipsis
474 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
476 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
477 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
479 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
481 # Treat sectiontitle the same way as summary.
482 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
483 # currently doing double duty as both edit summary and section title. Right now this
484 # is just to allow API edits to work around this limitation, but this should be
485 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
486 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 250 );
487 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
489 $this->edittime
= $request->getVal( 'wpEdittime' );
490 $this->starttime
= $request->getVal( 'wpStarttime' );
492 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
494 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
495 // wpTextbox1 field is missing, possibly due to being "too big"
496 // according to some filter rules such as Suhosin's setting for
497 // suhosin.request.max_value_length (d'oh)
498 $this->incompleteForm
= true;
500 // edittime should be one of our last fields; if it's missing,
501 // the submission probably broke somewhere in the middle.
502 $this->incompleteForm
= is_null( $this->edittime
);
504 if ( $this->incompleteForm
) {
505 # If the form is incomplete, force to preview.
506 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
507 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
508 $this->preview
= true;
510 /* Fallback for live preview */
511 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
512 $this->diff
= $request->getCheck( 'wpDiff' );
514 // Remember whether a save was requested, so we can indicate
515 // if we forced preview due to session failure.
516 $this->mTriedSave
= !$this->preview
;
518 if ( $this->tokenOk( $request ) ) {
519 # Some browsers will not report any submit button
520 # if the user hits enter in the comment box.
521 # The unmarked state will be assumed to be a save,
522 # if the form seems otherwise complete.
523 wfDebug( __METHOD__
. ": Passed token check.\n" );
524 } elseif ( $this->diff
) {
525 # Failed token check, but only requested "Show Changes".
526 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
528 # Page might be a hack attempt posted from
529 # an external site. Preview instead of saving.
530 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
531 $this->preview
= true;
534 $this->save
= !$this->preview
&& !$this->diff
;
535 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
536 $this->edittime
= null;
539 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
540 $this->starttime
= null;
543 $this->recreate
= $request->getCheck( 'wpRecreate' );
545 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
546 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
548 # Don't force edit summaries when a user is editing their own user or talk page
549 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
550 $this->mTitle
->getText() == $wgUser->getName() )
552 $this->allowBlankSummary
= true;
554 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
557 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
559 # Not a posted form? Start with nothing.
560 wfDebug( __METHOD__
. ": Not a posted form.\n" );
561 $this->textbox1
= '';
563 $this->sectiontitle
= '';
564 $this->edittime
= '';
565 $this->starttime
= wfTimestampNow();
567 $this->preview
= false;
570 $this->minoredit
= false;
571 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
572 $this->recreate
= false;
574 // When creating a new section, we can preload a section title by passing it as the
575 // preloadtitle parameter in the URL (Bug 13100)
576 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
577 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
578 // Once wpSummary isn't being use for setting section titles, we should delete this.
579 $this->summary
= $request->getVal( 'preloadtitle' );
581 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
582 $this->summary
= $request->getText( 'summary' );
585 if ( $request->getVal( 'minor' ) ) {
586 $this->minoredit
= true;
590 $this->bot
= $request->getBool( 'bot', true );
591 $this->nosummary
= $request->getBool( 'nosummary' );
593 $this->oldid
= $request->getInt( 'oldid' );
595 $this->live
= $request->getCheck( 'live' );
596 $this->editintro
= $request->getText( 'editintro',
597 // Custom edit intro for new sections
598 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
600 // Allow extensions to modify form data
601 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
603 wfProfileOut( __METHOD__
);
607 * Subpage overridable method for extracting the page content data from the
608 * posted form to be placed in $this->textbox1, if using customized input
609 * this method should be overrided and return the page text that will be used
610 * for saving, preview parsing and so on...
612 * @param $request WebRequest
614 protected function importContentFormData( &$request ) {
615 return; // Don't do anything, EditPage already extracted wpTextbox1
619 * Initialise form fields in the object
620 * Called on the first invocation, e.g. when a user clicks an edit link
621 * @return bool -- if the requested section is valid
623 function initialiseForm() {
625 $this->edittime
= $this->mArticle
->getTimestamp();
626 $this->textbox1
= $this->getContent( false );
627 // activate checkboxes if user wants them to be always active
628 # Sort out the "watch" checkbox
629 if ( $wgUser->getOption( 'watchdefault' ) ) {
631 $this->watchthis
= true;
632 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
634 $this->watchthis
= true;
635 } elseif ( $this->mTitle
->userIsWatching() ) {
637 $this->watchthis
= true;
639 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
640 $this->minoredit
= true;
642 if ( $this->textbox1
=== false ) {
650 * Fetch initial editing page content.
652 * @param $def_text string
653 * @return mixed string on success, $def_text for invalid sections
656 function getContent( $def_text = '' ) {
657 global $wgOut, $wgRequest, $wgParser;
659 wfProfileIn( __METHOD__
);
663 // For message page not locally set, use the i18n message.
664 // For other non-existent articles, use preload text if any.
665 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
666 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
667 # If this is a system message, get the default text.
668 $text = $this->mTitle
->getDefaultMessageText();
670 if ( $text === false ) {
671 # If requested, preload some text.
672 $preload = $wgRequest->getVal( 'preload',
673 // Custom preload text for new sections
674 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
675 $text = $this->getPreloadedText( $preload );
677 // For existing pages, get text based on "undo" or section parameters.
679 if ( $this->section
!= '' ) {
680 // Get section edit text (returns $def_text for invalid sections)
681 $text = $wgParser->getSection( $this->getOriginalContent(), $this->section
, $def_text );
683 $undoafter = $wgRequest->getInt( 'undoafter' );
684 $undo = $wgRequest->getInt( 'undo' );
686 if ( $undo > 0 && $undoafter > 0 ) {
687 if ( $undo < $undoafter ) {
688 # If they got undoafter and undo round the wrong way, switch them
689 list( $undo, $undoafter ) = array( $undoafter, $undo );
692 $undorev = Revision
::newFromId( $undo );
693 $oldrev = Revision
::newFromId( $undoafter );
695 # Sanity check, make sure it's the right page,
696 # the revisions exist and they were not deleted.
697 # Otherwise, $text will be left as-is.
698 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
699 $undorev->getPage() == $oldrev->getPage() &&
700 $undorev->getPage() == $this->mTitle
->getArticleId() &&
701 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
702 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
704 $text = $this->mArticle
->getUndoText( $undorev, $oldrev );
705 if ( $text === false ) {
706 # Warn the user that something went wrong
707 $undoMsg = 'failure';
709 # Inform the user of our success and set an automatic edit summary
710 $undoMsg = 'success';
712 # If we just undid one rev, use an autosummary
713 $firstrev = $oldrev->getNext();
714 if ( $firstrev->getId() == $undo ) {
715 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
716 if ( $this->summary
=== '' ) {
717 $this->summary
= $undoSummary;
719 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
721 $this->undidRev
= $undo;
723 $this->formtype
= 'diff';
726 // Failed basic sanity checks.
727 // Older revisions may have been removed since the link
728 // was created, or we may simply have got bogus input.
732 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"error mw-undo-{$undoMsg}\">" .
733 wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
736 if ( $text === false ) {
737 $text = $this->getOriginalContent();
742 wfProfileOut( __METHOD__
);
747 * Get the content of the wanted revision, without section extraction.
749 * The result of this function can be used to compare user's input with
750 * section replaced in its context (using WikiPage::replaceSection())
751 * to the original text of the edit.
753 * This difers from Article::getContent() that when a missing revision is
754 * encountered the result will be an empty string and not the
755 * 'missing-article' message.
760 private function getOriginalContent() {
761 if ( $this->section
== 'new' ) {
762 return $this->getCurrentText();
764 $revision = $this->mArticle
->getRevisionFetched();
765 if ( $revision === null ) {
768 return $this->mArticle
->getContent();
772 * Get the actual text of the page. This is basically similar to
773 * WikiPage::getRawText() except that when the page doesn't exist an empty
774 * string is returned instead of false.
779 private function getCurrentText() {
780 $text = $this->mArticle
->getRawText();
781 if ( $text === false ) {
789 * Use this method before edit() to preload some text into the edit box
791 * @param $text string
793 public function setPreloadedText( $text ) {
794 $this->mPreloadText
= $text;
798 * Get the contents to be preloaded into the box, either set by
799 * an earlier setPreloadText() or by loading the given page.
801 * @param $preload String: representing the title to preload from.
804 protected function getPreloadedText( $preload ) {
805 global $wgUser, $wgParser;
807 if ( !empty( $this->mPreloadText
) ) {
808 return $this->mPreloadText
;
811 if ( $preload === '' ) {
815 $title = Title
::newFromText( $preload );
816 # Check for existence to avoid getting MediaWiki:Noarticletext
817 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
821 $page = WikiPage
::factory( $title );
822 if ( $page->isRedirect() ) {
823 $title = $page->getRedirectTarget();
825 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
828 $page = WikiPage
::factory( $title );
831 $parserOptions = ParserOptions
::newFromUser( $wgUser );
832 return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
836 * Make sure the form isn't faking a user's credentials.
838 * @param $request WebRequest
842 function tokenOk( &$request ) {
844 $token = $request->getVal( 'wpEditToken' );
845 $this->mTokenOk
= $wgUser->matchEditToken( $token );
846 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
847 return $this->mTokenOk
;
852 * @return bool false if output is done, true if the rest of the form should be displayed
854 function attemptSave() {
855 global $wgUser, $wgOut;
857 $resultDetails = false;
858 # Allow bots to exempt some edits from bot flagging
859 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
860 $status = $this->internalAttemptSave( $resultDetails, $bot );
861 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
863 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
864 $this->didSave
= true;
867 switch ( $status->value
) {
868 case self
::AS_HOOK_ERROR_EXPECTED
:
869 case self
::AS_CONTENT_TOO_BIG
:
870 case self
::AS_ARTICLE_WAS_DELETED
:
871 case self
::AS_CONFLICT_DETECTED
:
872 case self
::AS_SUMMARY_NEEDED
:
873 case self
::AS_TEXTBOX_EMPTY
:
874 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
878 case self
::AS_HOOK_ERROR
:
879 case self
::AS_FILTERING
:
882 case self
::AS_SUCCESS_NEW_ARTICLE
:
883 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
884 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
885 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
888 case self
::AS_SUCCESS_UPDATE
:
890 $sectionanchor = $resultDetails['sectionanchor'];
892 // Give extensions a chance to modify URL query on update
893 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
895 if ( $resultDetails['redirect'] ) {
896 if ( $extraQuery == '' ) {
897 $extraQuery = 'redirect=no';
899 $extraQuery = 'redirect=no&' . $extraQuery;
902 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
905 case self
::AS_BLANK_ARTICLE
:
906 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
909 case self
::AS_SPAM_ERROR
:
910 $this->spamPageWithContent( $resultDetails['spam'] );
913 case self
::AS_BLOCKED_PAGE_FOR_USER
:
914 throw new UserBlockedError( $wgUser->mBlock
);
916 case self
::AS_IMAGE_REDIRECT_ANON
:
917 case self
::AS_IMAGE_REDIRECT_LOGGED
:
918 throw new PermissionsError( 'upload' );
920 case self
::AS_READ_ONLY_PAGE_ANON
:
921 case self
::AS_READ_ONLY_PAGE_LOGGED
:
922 throw new PermissionsError( 'edit' );
924 case self
::AS_READ_ONLY_PAGE
:
925 throw new ReadOnlyError
;
927 case self
::AS_RATE_LIMITED
:
928 throw new ThrottledError();
930 case self
::AS_NO_CREATE_PERMISSION
:
931 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
932 throw new PermissionsError( $permission );
939 * Attempt submission (no UI)
944 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
946 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
947 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
948 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
950 function internalAttemptSave( &$result, $bot = false ) {
951 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
952 global $wgMaxArticleSize;
954 $status = Status
::newGood();
956 wfProfileIn( __METHOD__
);
957 wfProfileIn( __METHOD__
. '-checks' );
959 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
960 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
961 $status->fatal( 'hookaborted' );
962 $status->value
= self
::AS_HOOK_ERROR
;
963 wfProfileOut( __METHOD__
. '-checks' );
964 wfProfileOut( __METHOD__
);
968 # Check image redirect
969 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
970 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
971 !$wgUser->isAllowed( 'upload' ) ) {
972 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
973 $status->setResult( false, $code );
975 wfProfileOut( __METHOD__
. '-checks' );
976 wfProfileOut( __METHOD__
);
982 $match = self
::matchSummarySpamRegex( $this->summary
);
983 if ( $match === false ) {
984 $match = self
::matchSpamRegex( $this->textbox1
);
986 if ( $match !== false ) {
987 $result['spam'] = $match;
988 $ip = $wgRequest->getIP();
989 $pdbk = $this->mTitle
->getPrefixedDBkey();
990 $match = str_replace( "\n", '', $match );
991 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
992 $status->fatal( 'spamprotectionmatch', $match );
993 $status->value
= self
::AS_SPAM_ERROR
;
994 wfProfileOut( __METHOD__
. '-checks' );
995 wfProfileOut( __METHOD__
);
998 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
999 # Error messages or other handling should be performed by the filter function
1000 $status->setResult( false, self
::AS_FILTERING
);
1001 wfProfileOut( __METHOD__
. '-checks' );
1002 wfProfileOut( __METHOD__
);
1005 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1006 # Error messages etc. could be handled within the hook...
1007 $status->fatal( 'hookaborted' );
1008 $status->value
= self
::AS_HOOK_ERROR
;
1009 wfProfileOut( __METHOD__
. '-checks' );
1010 wfProfileOut( __METHOD__
);
1012 } elseif ( $this->hookError
!= '' ) {
1013 # ...or the hook could be expecting us to produce an error
1014 $status->fatal( 'hookaborted' );
1015 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1016 wfProfileOut( __METHOD__
. '-checks' );
1017 wfProfileOut( __METHOD__
);
1021 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1022 // Auto-block user's IP if the account was "hard" blocked
1023 $wgUser->spreadAnyEditBlock();
1024 # Check block state against master, thus 'false'.
1025 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1026 wfProfileOut( __METHOD__
. '-checks' );
1027 wfProfileOut( __METHOD__
);
1031 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1032 if ( $this->kblength
> $wgMaxArticleSize ) {
1033 // Error will be displayed by showEditForm()
1034 $this->tooBig
= true;
1035 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1036 wfProfileOut( __METHOD__
. '-checks' );
1037 wfProfileOut( __METHOD__
);
1041 if ( !$wgUser->isAllowed( 'edit' ) ) {
1042 if ( $wgUser->isAnon() ) {
1043 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1044 wfProfileOut( __METHOD__
. '-checks' );
1045 wfProfileOut( __METHOD__
);
1048 $status->fatal( 'readonlytext' );
1049 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1050 wfProfileOut( __METHOD__
. '-checks' );
1051 wfProfileOut( __METHOD__
);
1056 if ( wfReadOnly() ) {
1057 $status->fatal( 'readonlytext' );
1058 $status->value
= self
::AS_READ_ONLY_PAGE
;
1059 wfProfileOut( __METHOD__
. '-checks' );
1060 wfProfileOut( __METHOD__
);
1063 if ( $wgUser->pingLimiter() ) {
1064 $status->fatal( 'actionthrottledtext' );
1065 $status->value
= self
::AS_RATE_LIMITED
;
1066 wfProfileOut( __METHOD__
. '-checks' );
1067 wfProfileOut( __METHOD__
);
1071 # If the article has been deleted while editing, don't save it without
1073 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1074 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1075 wfProfileOut( __METHOD__
. '-checks' );
1076 wfProfileOut( __METHOD__
);
1080 wfProfileOut( __METHOD__
. '-checks' );
1082 # If article is new, insert it.
1083 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1084 $new = ( $aid == 0 );
1087 // Late check for create permission, just in case *PARANOIA*
1088 if ( !$this->mTitle
->userCan( 'create' ) ) {
1089 $status->fatal( 'nocreatetext' );
1090 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1091 wfDebug( __METHOD__
. ": no create permission\n" );
1092 wfProfileOut( __METHOD__
);
1096 # Don't save a new article if it's blank.
1097 if ( $this->textbox1
== '' ) {
1098 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1099 wfProfileOut( __METHOD__
);
1103 // Run post-section-merge edit filter
1104 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1105 # Error messages etc. could be handled within the hook...
1106 $status->fatal( 'hookaborted' );
1107 $status->value
= self
::AS_HOOK_ERROR
;
1108 wfProfileOut( __METHOD__
);
1110 } elseif ( $this->hookError
!= '' ) {
1111 # ...or the hook could be expecting us to produce an error
1112 $status->fatal( 'hookaborted' );
1113 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1114 wfProfileOut( __METHOD__
);
1118 # Handle the user preference to force summaries here. Check if it's not a redirect.
1119 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
1120 if ( md5( $this->summary
) == $this->autoSumm
) {
1121 $this->missingSummary
= true;
1122 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1123 $status->value
= self
::AS_SUMMARY_NEEDED
;
1124 wfProfileOut( __METHOD__
);
1129 $text = $this->textbox1
;
1130 $result['sectionanchor'] = '';
1131 if ( $this->section
== 'new' ) {
1132 if ( $this->sectiontitle
!== '' ) {
1133 // Insert the section title above the content.
1134 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle
) . "\n\n" . $text;
1136 // Jump to the new section
1137 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1139 // If no edit summary was specified, create one automatically from the section
1140 // title and have it link to the new section. Otherwise, respect the summary as
1142 if ( $this->summary
=== '' ) {
1143 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1144 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1146 } elseif ( $this->summary
!== '' ) {
1147 // Insert the section title above the content.
1148 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $text;
1150 // Jump to the new section
1151 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1153 // Create a link to the new section from the edit summary.
1154 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1155 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1159 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1163 # Article exists. Check for edit conflict.
1165 $this->mArticle
->clear(); # Force reload of dates, etc.
1166 $timestamp = $this->mArticle
->getTimestamp();
1168 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1170 if ( $timestamp != $this->edittime
) {
1171 $this->isConflict
= true;
1172 if ( $this->section
== 'new' ) {
1173 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1174 $this->mArticle
->getComment() == $this->summary
) {
1175 // Probably a duplicate submission of a new comment.
1176 // This can happen when squid resends a request after
1177 // a timeout but the first one actually went through.
1178 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1180 // New comment; suppress conflict.
1181 $this->isConflict
= false;
1182 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1184 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1185 # Suppress edit conflict with self, except for section edits where merging is required.
1186 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1187 $this->isConflict
= false;
1191 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1192 // backwards compatibility with old forms/bots).
1193 if ( $this->sectiontitle
!== '' ) {
1194 $sectionTitle = $this->sectiontitle
;
1196 $sectionTitle = $this->summary
;
1199 if ( $this->isConflict
) {
1200 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1201 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle, $this->edittime
);
1203 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1204 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle );
1206 if ( is_null( $text ) ) {
1207 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1208 $this->isConflict
= true;
1209 $text = $this->textbox1
; // do not try to merge here!
1210 } elseif ( $this->isConflict
) {
1212 if ( $this->mergeChangesInto( $text ) ) {
1213 // Successful merge! Maybe we should tell the user the good news?
1214 $this->isConflict
= false;
1215 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1217 $this->section
= '';
1218 $this->textbox1
= $text;
1219 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1223 if ( $this->isConflict
) {
1224 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1225 wfProfileOut( __METHOD__
);
1229 // Run post-section-merge edit filter
1230 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
1231 # Error messages etc. could be handled within the hook...
1232 $status->fatal( 'hookaborted' );
1233 $status->value
= self
::AS_HOOK_ERROR
;
1234 wfProfileOut( __METHOD__
);
1236 } elseif ( $this->hookError
!= '' ) {
1237 # ...or the hook could be expecting us to produce an error
1238 $status->fatal( 'hookaborted' );
1239 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1240 wfProfileOut( __METHOD__
);
1244 # Handle the user preference to force summaries here, but not for null edits
1245 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1246 && $this->getOriginalContent() != $text
1247 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1249 if ( md5( $this->summary
) == $this->autoSumm
) {
1250 $this->missingSummary
= true;
1251 $status->fatal( 'missingsummary' );
1252 $status->value
= self
::AS_SUMMARY_NEEDED
;
1253 wfProfileOut( __METHOD__
);
1258 # And a similar thing for new sections
1259 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1260 if ( trim( $this->summary
) == '' ) {
1261 $this->missingSummary
= true;
1262 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1263 $status->value
= self
::AS_SUMMARY_NEEDED
;
1264 wfProfileOut( __METHOD__
);
1270 wfProfileIn( __METHOD__
. '-sectionanchor' );
1271 $sectionanchor = '';
1272 if ( $this->section
== 'new' ) {
1273 if ( $this->textbox1
== '' ) {
1274 $this->missingComment
= true;
1275 $status->fatal( 'missingcommenttext' );
1276 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1277 wfProfileOut( __METHOD__
. '-sectionanchor' );
1278 wfProfileOut( __METHOD__
);
1281 if ( $this->sectiontitle
!== '' ) {
1282 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1283 // If no edit summary was specified, create one automatically from the section
1284 // title and have it link to the new section. Otherwise, respect the summary as
1286 if ( $this->summary
=== '' ) {
1287 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1288 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1290 } elseif ( $this->summary
!== '' ) {
1291 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1292 # This is a new section, so create a link to the new section
1293 # in the revision summary.
1294 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1295 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1297 } elseif ( $this->section
!= '' ) {
1298 # Try to get a section anchor from the section source, redirect to edited section if header found
1299 # XXX: might be better to integrate this into Article::replaceSection
1300 # for duplicate heading checking and maybe parsing
1301 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1302 # we can't deal with anchors, includes, html etc in the header for now,
1303 # headline would need to be parsed to improve this
1304 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1305 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1308 $result['sectionanchor'] = $sectionanchor;
1309 wfProfileOut( __METHOD__
. '-sectionanchor' );
1311 // Save errors may fall down to the edit form, but we've now
1312 // merged the section into full text. Clear the section field
1313 // so that later submission of conflict forms won't try to
1314 // replace that into a duplicated mess.
1315 $this->textbox1
= $text;
1316 $this->section
= '';
1318 $status->value
= self
::AS_SUCCESS_UPDATE
;
1321 // Check for length errors again now that the section is merged in
1322 $this->kblength
= (int)( strlen( $text ) / 1024 );
1323 if ( $this->kblength
> $wgMaxArticleSize ) {
1324 $this->tooBig
= true;
1325 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1326 wfProfileOut( __METHOD__
);
1330 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1331 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1332 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1333 ( $bot ? EDIT_FORCE_BOT
: 0 );
1335 $doEditStatus = $this->mArticle
->doEdit( $text, $this->summary
, $flags );
1337 if ( $doEditStatus->isOK() ) {
1338 $result['redirect'] = Title
::newFromRedirect( $text ) !== null;
1339 $this->commitWatch();
1340 wfProfileOut( __METHOD__
);
1343 $this->isConflict
= true;
1344 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1345 wfProfileOut( __METHOD__
);
1346 return $doEditStatus;
1351 * Commit the change of watch status
1353 protected function commitWatch() {
1355 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1356 $dbw = wfGetDB( DB_MASTER
);
1358 if ( $this->watchthis
) {
1359 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1361 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1368 * Check if no edits were made by other users since
1369 * the time a user started editing the page. Limit to
1370 * 50 revisions for the sake of performance.
1373 * @param $edittime string
1377 protected function userWasLastToEdit( $id, $edittime ) {
1378 if( !$id ) return false;
1379 $dbw = wfGetDB( DB_MASTER
);
1380 $res = $dbw->select( 'revision',
1383 'rev_page' => $this->mTitle
->getArticleId(),
1384 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1387 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1388 foreach ( $res as $row ) {
1389 if( $row->rev_user
!= $id ) {
1400 * @parma $editText string
1404 function mergeChangesInto( &$editText ){
1405 wfProfileIn( __METHOD__
);
1407 $db = wfGetDB( DB_MASTER
);
1409 // This is the revision the editor started from
1410 $baseRevision = $this->getBaseRevision();
1411 if ( is_null( $baseRevision ) ) {
1412 wfProfileOut( __METHOD__
);
1415 $baseText = $baseRevision->getText();
1417 // The current state, we want to merge updates into it
1418 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1419 if ( is_null( $currentRevision ) ) {
1420 wfProfileOut( __METHOD__
);
1423 $currentText = $currentRevision->getText();
1426 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1427 $editText = $result;
1428 wfProfileOut( __METHOD__
);
1431 wfProfileOut( __METHOD__
);
1439 function getBaseRevision() {
1440 if ( !$this->mBaseRevision
) {
1441 $db = wfGetDB( DB_MASTER
);
1442 $baseRevision = Revision
::loadFromTimestamp(
1443 $db, $this->mTitle
, $this->edittime
);
1444 return $this->mBaseRevision
= $baseRevision;
1446 return $this->mBaseRevision
;
1451 * Check given input text against $wgSpamRegex, and return the text of the first match.
1453 * @param $text string
1455 * @return string|false matching string or false
1457 public static function matchSpamRegex( $text ) {
1458 global $wgSpamRegex;
1459 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1460 $regexes = (array)$wgSpamRegex;
1461 return self
::matchSpamRegexInternal( $text, $regexes );
1465 * Check given input text against $wgSpamRegex, and return the text of the first match.
1467 * @parma $text string
1469 * @return string|false matching string or false
1471 public static function matchSummarySpamRegex( $text ) {
1472 global $wgSummarySpamRegex;
1473 $regexes = (array)$wgSummarySpamRegex;
1474 return self
::matchSpamRegexInternal( $text, $regexes );
1478 * @param $text string
1479 * @param $regexes array
1480 * @return bool|string
1482 protected static function matchSpamRegexInternal( $text, $regexes ) {
1483 foreach( $regexes as $regex ) {
1485 if( preg_match( $regex, $text, $matches ) ) {
1492 function setHeaders() {
1493 global $wgOut, $wgUser;
1495 $wgOut->addModules( 'mediawiki.action.edit' );
1497 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1498 $wgOut->addModules( 'mediawiki.legacy.preview' );
1500 // Bug #19334: textarea jumps when editing articles in IE8
1501 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1503 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1505 # Enabled article-related sidebar, toplinks, etc.
1506 $wgOut->setArticleRelated( true );
1508 if ( $this->isConflict
) {
1509 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1510 } elseif ( $this->section
!= '' ) {
1511 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1512 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1514 # Use the title defined by DISPLAYTITLE magic word when present
1515 if ( isset( $this->mParserOutput
)
1516 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1519 $title = $this->getContextTitle()->getPrefixedText();
1521 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1526 * Show all applicable editing introductions
1528 protected function showIntro() {
1529 global $wgOut, $wgUser;
1530 if ( $this->suppressIntro
) {
1534 $namespace = $this->mTitle
->getNamespace();
1536 if ( $namespace == NS_MEDIAWIKI
) {
1537 # Show a warning if editing an interface message
1538 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1541 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1542 # Show log extract when the user is currently blocked
1543 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1544 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1545 $username = $parts[0];
1546 $user = User
::newFromName( $username, false /* allow IP users*/ );
1547 $ip = User
::isIP( $username );
1548 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1549 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1550 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1551 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1552 LogEventsList
::showLogExtract(
1555 $user->getUserPage(),
1559 'showIfEmpty' => false,
1561 'blocked-notice-logextract',
1562 $user->getName() # Support GENDER in notice
1568 # Try to add a custom edit intro, or use the standard one if this is not possible.
1569 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1570 if ( $wgUser->isLoggedIn() ) {
1571 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1573 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1576 # Give a notice if the user is editing a deleted/moved page...
1577 if ( !$this->mTitle
->exists() ) {
1578 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1579 '', array( 'lim' => 10,
1580 'conds' => array( "log_action != 'revision'" ),
1581 'showIfEmpty' => false,
1582 'msgKey' => array( 'recreate-moveddeleted-warn') )
1588 * Attempt to show a custom editing introduction, if supplied
1592 protected function showCustomIntro() {
1593 if ( $this->editintro
) {
1594 $title = Title
::newFromText( $this->editintro
);
1595 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1597 // Added using template syntax, to take <noinclude>'s into account.
1598 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1609 * Send the edit form and related headers to $wgOut
1610 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1611 * during form output near the top, for captchas and the like.
1613 function showEditForm( $formCallback = null ) {
1614 global $wgOut, $wgUser;
1616 wfProfileIn( __METHOD__
);
1618 #need to parse the preview early so that we know which templates are used,
1619 #otherwise users with "show preview after edit box" will get a blank list
1620 #we parse this near the beginning so that setHeaders can do the title
1621 #setting work instead of leaving it in getPreviewText
1622 $previewOutput = '';
1623 if ( $this->formtype
== 'preview' ) {
1624 $previewOutput = $this->getPreviewText();
1627 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1629 $this->setHeaders();
1631 if ( $this->showHeader() === false ) {
1632 wfProfileOut( __METHOD__
);
1636 $wgOut->addHTML( $this->editFormPageTop
);
1638 if ( $wgUser->getOption( 'previewontop' ) ) {
1639 $this->displayPreviewArea( $previewOutput, true );
1642 $wgOut->addHTML( $this->editFormTextTop
);
1644 $showToolbar = true;
1645 if ( $this->wasDeletedSinceLastEdit() ) {
1646 if ( $this->formtype
== 'save' ) {
1647 // Hide the toolbar and edit area, user can click preview to get it back
1648 // Add an confirmation checkbox and explanation.
1649 $showToolbar = false;
1651 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1652 'deletedwhileediting' );
1656 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
1657 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1658 'enctype' => 'multipart/form-data' ) ) );
1660 if ( is_callable( $formCallback ) ) {
1661 call_user_func_array( $formCallback, array( &$wgOut ) );
1664 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1666 // Put these up at the top to ensure they aren't lost on early form submission
1667 $this->showFormBeforeText();
1669 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1670 $username = $this->lastDelete
->user_name
;
1671 $comment = $this->lastDelete
->log_comment
;
1673 // It is better to not parse the comment at all than to have templates expanded in the middle
1674 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1675 $key = $comment === ''
1676 ?
'confirmrecreate-noreason'
1677 : 'confirmrecreate';
1679 '<div class="mw-confirm-recreate">' .
1680 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1681 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1682 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1688 # If a blank edit summary was previously provided, and the appropriate
1689 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1690 # user being bounced back more than once in the event that a summary
1693 # For a bit more sophisticated detection of blank summaries, hash the
1694 # automatic one and pass that in the hidden field wpAutoSummary.
1695 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
1696 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1699 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1700 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1702 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
1704 if ( $this->section
== 'new' ) {
1705 $this->showSummaryInput( true, $this->summary
);
1706 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1709 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1711 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1712 $wgOut->addHTML( EditPage
::getEditToolbar() );
1715 if ( $this->isConflict
) {
1716 // In an edit conflict bypass the overrideable content form method
1717 // and fallback to the raw wpTextbox1 since editconflicts can't be
1718 // resolved between page source edits and custom ui edits using the
1720 $this->textbox2
= $this->textbox1
;
1721 $this->textbox1
= $this->getCurrentText();
1723 $this->showTextbox1();
1725 $this->showContentForm();
1728 $wgOut->addHTML( $this->editFormTextAfterContent
);
1730 $wgOut->addWikiText( $this->getCopywarn() );
1732 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1734 $this->showStandardInputs();
1736 $this->showFormAfterText();
1738 $this->showTosSummary();
1740 $this->showEditTools();
1742 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
1744 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
1745 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
1747 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
1748 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
1750 if ( $this->isConflict
) {
1751 $this->showConflict();
1754 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
1756 if ( !$wgUser->getOption( 'previewontop' ) ) {
1757 $this->displayPreviewArea( $previewOutput, false );
1760 wfProfileOut( __METHOD__
);
1764 * Extract the section title from current section text, if any.
1766 * @param string $text
1767 * @return Mixed|string or false
1769 public static function extractSectionTitle( $text ) {
1770 preg_match( "/^(=+)(.+)\\1(\n|$)/i", $text, $matches );
1771 if ( !empty( $matches[2] ) ) {
1773 return $wgParser->stripSectionName(trim($matches[2]));
1779 protected function showHeader() {
1780 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1782 if ( $this->mTitle
->isTalkPage() ) {
1783 $wgOut->addWikiMsg( 'talkpagetext' );
1786 # Optional notices on a per-namespace and per-page basis
1787 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
1788 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
1789 if ( $editnotice_ns_message->exists() ) {
1790 $wgOut->addWikiText( $editnotice_ns_message->plain() );
1792 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
1793 $parts = explode( '/', $this->mTitle
->getDBkey() );
1794 $editnotice_base = $editnotice_ns;
1795 while ( count( $parts ) > 0 ) {
1796 $editnotice_base .= '-'.array_shift( $parts );
1797 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
1798 if ( $editnotice_base_msg->exists() ) {
1799 $wgOut->addWikiText( $editnotice_base_msg->plain() );
1803 # Even if there are no subpages in namespace, we still don't want / in MW ns.
1804 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
1805 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
1806 if ( $editnoticeMsg->exists() ) {
1807 $wgOut->addWikiText( $editnoticeMsg->plain() );
1811 if ( $this->isConflict
) {
1812 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1813 $this->edittime
= $this->mArticle
->getTimestamp();
1815 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
1816 // We use $this->section to much before this and getVal('wgSection') directly in other places
1817 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1818 // Someone is welcome to try refactoring though
1819 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1823 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1824 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1825 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
1826 if ( $sectionTitle !== false ) {
1827 $this->summary
= "/* $sectionTitle */ ";
1832 if ( $this->missingComment
) {
1833 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1836 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1837 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1840 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1841 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1844 if ( $this->hookError
!== '' ) {
1845 $wgOut->addWikiText( $this->hookError
);
1848 if ( !$this->checkUnicodeCompliantBrowser() ) {
1849 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1852 if ( $this->section
!= 'new' ) {
1853 $revision = $this->mArticle
->getRevisionFetched();
1855 // Let sysop know that this will make private content public if saved
1857 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
1858 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1859 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
1860 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1863 if ( !$revision->isCurrent() ) {
1864 $this->mArticle
->setOldSubtitle( $revision->getId() );
1865 $wgOut->addWikiMsg( 'editingold' );
1867 } elseif ( $this->mTitle
->exists() ) {
1868 // Something went wrong
1870 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
1871 array( 'missing-article', $this->mTitle
->getPrefixedText(),
1872 wfMsgNoTrans( 'missingarticle-rev', $this->oldid
) ) );
1877 if ( wfReadOnly() ) {
1878 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1879 } elseif ( $wgUser->isAnon() ) {
1880 if ( $this->formtype
!= 'preview' ) {
1881 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1883 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
1886 if ( $this->isCssJsSubpage
) {
1887 # Check the skin exists
1888 if ( $this->isWrongCaseCssJsPage
) {
1889 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
1891 if ( $this->formtype
!== 'preview' ) {
1892 if ( $this->isCssSubpage
)
1893 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
1894 if ( $this->isJsSubpage
)
1895 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
1900 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
1901 # Is the title semi-protected?
1902 if ( $this->mTitle
->isSemiProtected() ) {
1903 $noticeMsg = 'semiprotectedpagewarning';
1905 # Then it must be protected based on static groups (regular)
1906 $noticeMsg = 'protectedpagewarning';
1908 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1909 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1911 if ( $this->mTitle
->isCascadeProtected() ) {
1912 # Is this page under cascading protection from some source pages?
1913 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1914 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
1915 $cascadeSourcesCount = count( $cascadeSources );
1916 if ( $cascadeSourcesCount > 0 ) {
1917 # Explain, and list the titles responsible
1918 foreach( $cascadeSources as $page ) {
1919 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1922 $notice .= '</div>';
1923 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1925 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1926 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1928 'showIfEmpty' => false,
1929 'msgKey' => array( 'titleprotectedwarning' ),
1930 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
1933 if ( $this->kblength
=== false ) {
1934 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1937 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1938 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
1939 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
1941 if( !wfMessage('longpage-hint')->isDisabled() ) {
1942 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
1943 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
1950 * Standard summary input and label (wgSummary), abstracted so EditPage
1951 * subclasses may reorganize the form.
1952 * Note that you do not need to worry about the label's for=, it will be
1953 * inferred by the id given to the input. You can remove them both by
1954 * passing array( 'id' => false ) to $userInputAttrs.
1956 * @param $summary string The value of the summary input
1957 * @param $labelText string The html to place inside the label
1958 * @param $inputAttrs array of attrs to use on the input
1959 * @param $spanLabelAttrs array of attrs to use on the span inside the label
1961 * @return array An array in the format array( $label, $input )
1963 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
1964 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
1965 $inputAttrs = ( is_array($inputAttrs) ?
$inputAttrs : array() ) +
array(
1966 'id' => 'wpSummary',
1967 'maxlength' => '200',
1970 'spellcheck' => 'true',
1971 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
1973 $spanLabelAttrs = ( is_array($spanLabelAttrs) ?
$spanLabelAttrs : array() ) +
array(
1974 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
1975 'id' => "wpSummaryLabel"
1980 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1981 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
1984 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
1986 return array( $label, $input );
1990 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1991 * up top, or false if this is the comment summary
1992 * down below the textarea
1993 * @param $summary String: The text of the summary to display
1996 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1997 global $wgOut, $wgContLang;
1998 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1999 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2000 if ( $isSubjectPreview ) {
2001 if ( $this->nosummary
) {
2005 if ( !$this->mShowSummaryField
) {
2009 $summary = $wgContLang->recodeForEdit( $summary );
2010 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
2011 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
2012 $wgOut->addHTML("{$label} {$input}");
2016 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2017 * up top, or false if this is the comment summary
2018 * down below the textarea
2019 * @param $summary String: the text of the summary to display
2022 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2023 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2028 if ( $isSubjectPreview )
2029 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2031 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2033 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2034 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2037 protected function showFormBeforeText() {
2039 $section = htmlspecialchars( $this->section
);
2040 $wgOut->addHTML( <<<HTML
2041 <input type='hidden' value="{$section}" name="wpSection" />
2042 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2043 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2044 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2048 if ( !$this->checkUnicodeCompliantBrowser() )
2049 $wgOut->addHTML(Html
::hidden( 'safemode', '1' ));
2052 protected function showFormAfterText() {
2053 global $wgOut, $wgUser;
2055 * To make it harder for someone to slip a user a page
2056 * which submits an edit form to the wiki without their
2057 * knowledge, a random token is associated with the login
2058 * session. If it's not passed back with the submission,
2059 * we won't save the page, or render user JavaScript and
2062 * For anon editors, who may not have a session, we just
2063 * include the constant suffix to prevent editing from
2064 * broken text-mangling proxies.
2066 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2070 * Subpage overridable method for printing the form for page content editing
2071 * By default this simply outputs wpTextbox1
2072 * Subclasses can override this to provide a custom UI for editing;
2073 * be it a form, or simply wpTextbox1 with a modified content that will be
2074 * reverse modified when extracted from the post data.
2075 * Note that this is basically the inverse for importContentFormData
2077 protected function showContentForm() {
2078 $this->showTextbox1();
2082 * Method to output wpTextbox1
2083 * The $textoverride method can be used by subclasses overriding showContentForm
2084 * to pass back to this method.
2086 * @param $customAttribs An array of html attributes to use in the textarea
2087 * @param $textoverride String: optional text to override $this->textarea1 with
2089 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2090 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2091 $attribs = array( 'style' => 'display:none;' );
2093 $classes = array(); // Textarea CSS
2094 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2095 # Is the title semi-protected?
2096 if ( $this->mTitle
->isSemiProtected() ) {
2097 $classes[] = 'mw-textarea-sprotected';
2099 # Then it must be protected based on static groups (regular)
2100 $classes[] = 'mw-textarea-protected';
2102 # Is the title cascade-protected?
2103 if ( $this->mTitle
->isCascadeProtected() ) {
2104 $classes[] = 'mw-textarea-cprotected';
2108 $attribs = array( 'tabindex' => 1 );
2110 if ( is_array( $customAttribs ) ) {
2111 $attribs +
= $customAttribs;
2114 if ( count( $classes ) ) {
2115 if ( isset( $attribs['class'] ) ) {
2116 $classes[] = $attribs['class'];
2118 $attribs['class'] = implode( ' ', $classes );
2122 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2125 protected function showTextbox2() {
2126 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2129 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2130 global $wgOut, $wgUser;
2132 $wikitext = $this->safeUnicodeOutput( $content );
2133 if ( strval($wikitext) !== '' ) {
2134 // Ensure there's a newline at the end, otherwise adding lines
2136 // But don't add a newline if the ext is empty, or Firefox in XHTML
2137 // mode will show an extra newline. A bit annoying.
2141 $attribs = $customAttribs +
array(
2144 'rows' => $wgUser->getIntOption( 'rows' ),
2145 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2148 $pageLang = $this->mTitle
->getPageLanguage();
2149 $attribs['lang'] = $pageLang->getCode();
2150 $attribs['dir'] = $pageLang->getDir();
2152 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2155 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2159 $classes[] = 'ontop';
2161 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2163 if ( $this->formtype
!= 'preview' )
2164 $attribs['style'] = 'display: none;';
2166 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2168 if ( $this->formtype
== 'preview' ) {
2169 $this->showPreview( $previewOutput );
2172 $wgOut->addHTML( '</div>' );
2174 if ( $this->formtype
== 'diff') {
2180 * Append preview output to $wgOut.
2181 * Includes category rendering if this is a category page.
2183 * @param $text String: the HTML to be output for the preview.
2185 protected function showPreview( $text ) {
2187 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2188 $this->mArticle
->openShowCategory();
2190 # This hook seems slightly odd here, but makes things more
2191 # consistent for extensions.
2192 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
2193 $wgOut->addHTML( $text );
2194 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2195 $this->mArticle
->closeShowCategory();
2200 * Get a diff between the current contents of the edit box and the
2201 * version of the page we're editing from.
2203 * If this is a section edit, we'll replace the section as for final
2204 * save and then make a comparison.
2206 function showDiff() {
2207 global $wgUser, $wgContLang, $wgParser, $wgOut;
2209 $oldtext = $this->getOriginalContent();
2210 $newtext = $this->mArticle
->replaceSection(
2211 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2213 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2215 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2216 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle
, $wgUser, $popts );
2218 if ( $oldtext !== false ||
$newtext != '' ) {
2219 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2220 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2222 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2223 $de->setText( $oldtext, $newtext );
2224 $difftext = $de->getDiff( $oldtitle, $newtitle );
2225 $de->showDiffStyle();
2230 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2234 * Give a chance for site and per-namespace customizations of
2235 * terms of service summary link that might exist separately
2236 * from the copyright notice.
2238 * This will display between the save button and the edit tools,
2239 * so should remain short!
2241 protected function showTosSummary() {
2242 $msg = 'editpage-tos-summary';
2243 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2244 if( !wfMessage( $msg )->isDisabled() ) {
2246 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2247 $wgOut->addWikiMsg( $msg );
2248 $wgOut->addHTML( '</div>' );
2252 protected function showEditTools() {
2254 $wgOut->addHTML( '<div class="mw-editTools">' .
2255 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2259 protected function getCopywarn() {
2260 global $wgRightsText;
2261 if ( $wgRightsText ) {
2262 $copywarnMsg = array( 'copyrightwarning',
2263 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2266 $copywarnMsg = array( 'copyrightwarning2',
2267 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2269 // Allow for site and per-namespace customization of contribution/copyright notice.
2270 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2272 return "<div id=\"editpage-copywarn\">\n" .
2273 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
2276 protected function showStandardInputs( &$tabindex = 2 ) {
2278 $wgOut->addHTML( "<div class='editOptions'>\n" );
2280 if ( $this->section
!= 'new' ) {
2281 $this->showSummaryInput( false, $this->summary
);
2282 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2285 $checkboxes = $this->getCheckboxes( $tabindex,
2286 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2287 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2288 $wgOut->addHTML( "<div class='editButtons'>\n" );
2289 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2291 $cancel = $this->getCancelLink();
2292 if ( $cancel !== '' ) {
2293 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2295 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2296 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
2297 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
2298 htmlspecialchars( wfMsg( 'newwindow' ) );
2299 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2300 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2304 * Show an edit conflict. textbox1 is already shown in showEditForm().
2305 * If you want to use another entry point to this function, be careful.
2307 protected function showConflict() {
2310 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2311 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2313 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2314 $de->setText( $this->textbox2
, $this->textbox1
);
2315 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2317 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2318 $this->showTextbox2();
2325 public function getCancelLink() {
2326 $cancelParams = array();
2327 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2328 $cancelParams['oldid'] = $this->oldid
;
2331 return Linker
::linkKnown(
2332 $this->getContextTitle(),
2333 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2334 array( 'id' => 'mw-editform-cancel' ),
2340 * Returns the URL to use in the form's action attribute.
2341 * This is used by EditPage subclasses when simply customizing the action
2342 * variable in the constructor is not enough. This can be used when the
2343 * EditPage lives inside of a Special page rather than a custom page action.
2345 * @param $title Title object for which is being edited (where we go to for &action= links)
2348 protected function getActionURL( Title
$title ) {
2349 return $title->getLocalURL( array( 'action' => $this->action
) );
2353 * Check if a page was deleted while the user was editing it, before submit.
2354 * Note that we rely on the logging table, which hasn't been always there,
2355 * but that doesn't matter, because this only applies to brand new
2358 protected function wasDeletedSinceLastEdit() {
2359 if ( $this->deletedSinceEdit
!== null ) {
2360 return $this->deletedSinceEdit
;
2363 $this->deletedSinceEdit
= false;
2365 if ( $this->mTitle
->isDeletedQuick() ) {
2366 $this->lastDelete
= $this->getLastDelete();
2367 if ( $this->lastDelete
) {
2368 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2369 if ( $deleteTime > $this->starttime
) {
2370 $this->deletedSinceEdit
= true;
2375 return $this->deletedSinceEdit
;
2378 protected function getLastDelete() {
2379 $dbr = wfGetDB( DB_SLAVE
);
2380 $data = $dbr->selectRow(
2381 array( 'logging', 'user' ),
2392 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2393 'log_title' => $this->mTitle
->getDBkey(),
2394 'log_type' => 'delete',
2395 'log_action' => 'delete',
2396 'user_id=log_user' ),
2398 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2400 // Quick paranoid permission checks...
2401 if( is_object( $data ) ) {
2402 if( $data->log_deleted
& LogPage
::DELETED_USER
)
2403 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2404 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2405 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2411 * Get the rendered text for previewing.
2414 function getPreviewText() {
2415 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2417 wfProfileIn( __METHOD__
);
2419 if ( $wgRawHtml && !$this->mTokenOk
) {
2420 // Could be an offsite preview attempt. This is very unsafe if
2421 // HTML is enabled, as it could be an attack.
2423 if ( $this->textbox1
!== '' ) {
2424 // Do not put big scary notice, if previewing the empty
2425 // string, which happens when you initially edit
2426 // a category page, due to automatic preview-on-open.
2427 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2428 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2430 wfProfileOut( __METHOD__
);
2434 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2435 if ( $this->mTokenOkExceptSuffix
) {
2436 $note = wfMsg( 'token_suffix_mismatch' );
2438 $note = wfMsg( 'session_fail_preview' );
2440 } elseif ( $this->incompleteForm
) {
2441 $note = wfMsg( 'edit_form_incomplete' );
2443 $note = wfMsg( 'previewnote' );
2446 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2447 $parserOptions->setEditSection( false );
2448 $parserOptions->setTidy( true );
2449 $parserOptions->setIsPreview( true );
2450 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2452 # don't parse non-wikitext pages, show message about preview
2453 # 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?
2455 if ( $this->isCssJsSubpage ||
!$this->mTitle
->isWikitextPage() ) {
2456 if( $this->mTitle
->isCssJsSubpage() ) {
2458 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2464 # Used messages to make sure grep find them:
2465 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2467 if (preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2468 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2469 $class = "mw-code mw-css";
2470 } elseif (preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2471 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2472 $class = "mw-code mw-js";
2474 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2478 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2479 $previewHTML = $parserOutput->mText
;
2480 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2482 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2484 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2486 $toparse = $this->textbox1
;
2488 # If we're adding a comment, we need to show the
2489 # summary as the headline
2490 if ( $this->section
== "new" && $this->summary
!= "" ) {
2491 $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $toparse;
2494 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2496 $parserOptions->enableLimitReport();
2498 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle
, $wgUser, $parserOptions );
2499 $parserOutput = $wgParser->parse( $toparse, $this->mTitle
, $parserOptions );
2501 $previewHTML = $parserOutput->getText();
2502 $this->mParserOutput
= $parserOutput;
2503 $wgOut->addParserOutputNoText( $parserOutput );
2505 if ( count( $parserOutput->getWarnings() ) ) {
2506 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2511 if( $this->isConflict
) {
2512 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2514 $conflict = '<hr />';
2517 $previewhead = "<div class='previewnote'>\n" .
2518 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2519 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2521 $pageLang = $this->mTitle
->getPageLanguage();
2522 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2523 'class' => 'mw-content-'.$pageLang->getDir() );
2524 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2526 wfProfileOut( __METHOD__
);
2527 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2533 function getTemplates() {
2534 if ( $this->preview ||
$this->section
!= '' ) {
2535 $templates = array();
2536 if ( !isset( $this->mParserOutput
) ) {
2539 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
2540 foreach( array_keys( $template ) as $dbk ) {
2541 $templates[] = Title
::makeTitle($ns, $dbk);
2546 return $this->mTitle
->getTemplateLinksFrom();
2551 * Shows a bulletin board style toolbar for common editing functions.
2552 * It can be disabled in the user preferences.
2553 * The necessary JavaScript code can be found in skins/common/edit.js.
2557 static function getEditToolbar() {
2558 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2559 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2561 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2564 * $toolarray is an array of arrays each of which includes the
2565 * filename of the button image (without path), the opening
2566 * tag, the closing tag, optionally a sample text that is
2567 * inserted between the two when no selection is highlighted
2568 * and. The tip text is shown when the user moves the mouse
2571 * Also here: accesskeys (key), which are not used yet until
2572 * someone can figure out a way to make them work in
2573 * IE. However, we should make sure these keys are not defined
2578 'image' => $wgLang->getImageFile( 'button-bold' ),
2579 'id' => 'mw-editbutton-bold',
2581 'close' => '\'\'\'',
2582 'sample' => wfMsg( 'bold_sample' ),
2583 'tip' => wfMsg( 'bold_tip' ),
2587 'image' => $wgLang->getImageFile( 'button-italic' ),
2588 'id' => 'mw-editbutton-italic',
2591 'sample' => wfMsg( 'italic_sample' ),
2592 'tip' => wfMsg( 'italic_tip' ),
2596 'image' => $wgLang->getImageFile( 'button-link' ),
2597 'id' => 'mw-editbutton-link',
2600 'sample' => wfMsg( 'link_sample' ),
2601 'tip' => wfMsg( 'link_tip' ),
2605 'image' => $wgLang->getImageFile( 'button-extlink' ),
2606 'id' => 'mw-editbutton-extlink',
2609 'sample' => wfMsg( 'extlink_sample' ),
2610 'tip' => wfMsg( 'extlink_tip' ),
2614 'image' => $wgLang->getImageFile( 'button-headline' ),
2615 'id' => 'mw-editbutton-headline',
2618 'sample' => wfMsg( 'headline_sample' ),
2619 'tip' => wfMsg( 'headline_tip' ),
2622 $imagesAvailable ?
array(
2623 'image' => $wgLang->getImageFile( 'button-image' ),
2624 'id' => 'mw-editbutton-image',
2625 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2627 'sample' => wfMsg( 'image_sample' ),
2628 'tip' => wfMsg( 'image_tip' ),
2631 $imagesAvailable ?
array(
2632 'image' => $wgLang->getImageFile( 'button-media' ),
2633 'id' => 'mw-editbutton-media',
2634 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2636 'sample' => wfMsg( 'media_sample' ),
2637 'tip' => wfMsg( 'media_tip' ),
2641 'image' => $wgLang->getImageFile( 'button-math' ),
2642 'id' => 'mw-editbutton-math',
2644 'close' => "</math>",
2645 'sample' => wfMsg( 'math_sample' ),
2646 'tip' => wfMsg( 'math_tip' ),
2650 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2651 'id' => 'mw-editbutton-nowiki',
2652 'open' => "<nowiki>",
2653 'close' => "</nowiki>",
2654 'sample' => wfMsg( 'nowiki_sample' ),
2655 'tip' => wfMsg( 'nowiki_tip' ),
2659 'image' => $wgLang->getImageFile( 'button-sig' ),
2660 'id' => 'mw-editbutton-signature',
2664 'tip' => wfMsg( 'sig_tip' ),
2668 'image' => $wgLang->getImageFile( 'button-hr' ),
2669 'id' => 'mw-editbutton-hr',
2670 'open' => "\n----\n",
2673 'tip' => wfMsg( 'hr_tip' ),
2678 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
2679 foreach ( $toolarray as $tool ) {
2685 $image = $wgStylePath . '/common/images/' . $tool['image'],
2686 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2687 // Older browsers show a "speedtip" type message only for ALT.
2688 // Ideally these should be different, realistically they
2689 // probably don't need to be.
2690 $tip = $tool['tip'],
2691 $open = $tool['open'],
2692 $close = $tool['close'],
2693 $sample = $tool['sample'],
2694 $cssId = $tool['id'],
2697 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2700 // This used to be called on DOMReady from mediawiki.action.edit, which
2701 // ended up causing race conditions with the setup code above.
2703 "// Create button bar\n" .
2704 "$(function() { mw.toolbar.init(); } );\n";
2707 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2709 $toolbar = '<div id="toolbar"></div>';
2711 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2717 * Returns an array of html code of the following checkboxes:
2720 * @param $tabindex Current tabindex
2721 * @param $checked Array of checkbox => bool, where bool indicates the checked
2722 * status of the checkbox
2726 public function getCheckboxes( &$tabindex, $checked ) {
2729 $checkboxes = array();
2731 // don't show the minor edit checkbox if it's a new page or section
2732 if ( !$this->isNew
) {
2733 $checkboxes['minor'] = '';
2734 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2735 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2737 'tabindex' => ++
$tabindex,
2738 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2739 'id' => 'wpMinoredit',
2741 $checkboxes['minor'] =
2742 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2743 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2744 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2745 ">{$minorLabel}</label>";
2749 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2750 $checkboxes['watch'] = '';
2751 if ( $wgUser->isLoggedIn() ) {
2753 'tabindex' => ++
$tabindex,
2754 'accesskey' => wfMsg( 'accesskey-watch' ),
2755 'id' => 'wpWatchthis',
2757 $checkboxes['watch'] =
2758 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2759 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2760 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2761 ">{$watchLabel}</label>";
2763 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2768 * Returns an array of html code of the following buttons:
2769 * save, diff, preview and live
2771 * @param $tabindex Current tabindex
2775 public function getEditButtons( &$tabindex ) {
2782 'tabindex' => ++
$tabindex,
2783 'value' => wfMsg( 'savearticle' ),
2784 'accesskey' => wfMsg( 'accesskey-save' ),
2785 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2787 $buttons['save'] = Xml
::element('input', $temp, '');
2789 ++
$tabindex; // use the same for preview and live preview
2791 'id' => 'wpPreview',
2792 'name' => 'wpPreview',
2794 'tabindex' => $tabindex,
2795 'value' => wfMsg( 'showpreview' ),
2796 'accesskey' => wfMsg( 'accesskey-preview' ),
2797 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2799 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
2800 $buttons['live'] = '';
2806 'tabindex' => ++
$tabindex,
2807 'value' => wfMsg( 'showdiff' ),
2808 'accesskey' => wfMsg( 'accesskey-diff' ),
2809 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2811 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
2813 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2818 * Output preview text only. This can be sucked into the edit page
2819 * via JavaScript, and saves the server time rendering the skin as
2820 * well as theoretically being more robust on the client (doesn't
2821 * disturb the edit box's undo history, won't eat your text on
2824 * @todo This doesn't include category or interlanguage links.
2825 * Would need to enhance it a bit, <s>maybe wrap them in XML
2826 * or something...</s> that might also require more skin
2827 * initialization, so check whether that's a problem.
2829 function livePreview() {
2832 header( 'Content-type: text/xml; charset=utf-8' );
2833 header( 'Cache-control: no-cache' );
2835 $previewText = $this->getPreviewText();
2836 #$categories = $skin->getCategoryLinks();
2839 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2840 Xml
::tags( 'livepreview', null,
2841 Xml
::element( 'preview', null, $previewText )
2842 #. Xml::element( 'category', null, $categories )
2848 * Call the stock "user is blocked" page
2850 * @deprecated in 1.19; throw an exception directly instead
2852 function blockedPage() {
2853 wfDeprecated( __METHOD__
, '1.19' );
2856 throw new UserBlockedError( $wgUser->mBlock
);
2860 * Produce the stock "please login to edit pages" page
2862 * @deprecated in 1.19; throw an exception directly instead
2864 function userNotLoggedInPage() {
2865 wfDeprecated( __METHOD__
, '1.19' );
2866 throw new PermissionsError( 'edit' );
2870 * Show an error page saying to the user that he has insufficient permissions
2871 * to create a new page
2873 * @deprecated in 1.19; throw an exception directly instead
2875 function noCreatePermission() {
2876 wfDeprecated( __METHOD__
, '1.19' );
2877 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
2878 throw new PermissionsError( $permission );
2882 * Creates a basic error page which informs the user that
2883 * they have attempted to edit a nonexistent section.
2885 function noSuchSectionPage() {
2888 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
2890 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
2891 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2892 $wgOut->addHTML( $res );
2894 $wgOut->returnToMain( false, $this->mTitle
);
2898 * Produce the stock "your edit contains spam" page
2900 * @param $match Text which triggered one or more filters
2901 * @deprecated since 1.17 Use method spamPageWithContent() instead
2903 static function spamPage( $match = false ) {
2904 wfDeprecated( __METHOD__
, '1.17' );
2906 global $wgOut, $wgTitle;
2908 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2910 $wgOut->addHTML( '<div id="spamprotected">' );
2911 $wgOut->addWikiMsg( 'spamprotectiontext' );
2913 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2915 $wgOut->addHTML( '</div>' );
2917 $wgOut->returnToMain( false, $wgTitle );
2921 * Show "your edit contains spam" page with your diff and text
2923 * @param $match Text which triggered one or more filters
2925 public function spamPageWithContent( $match = false ) {
2927 $this->textbox2
= $this->textbox1
;
2929 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2931 $wgOut->addHTML( '<div id="spamprotected">' );
2932 $wgOut->addWikiMsg( 'spamprotectiontext' );
2934 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2936 $wgOut->addHTML( '</div>' );
2938 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2939 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2940 $de->setText( $this->getCurrentText(), $this->textbox2
);
2941 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
2943 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2944 $this->showTextbox2();
2946 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
2950 * Format an anchor fragment as it would appear for a given section name
2951 * @param $text String
2955 function sectionAnchor( $text ) {
2957 return $wgParser->guessSectionNameFromWikiText( $text );
2961 * Check if the browser is on a blacklist of user-agents known to
2962 * mangle UTF-8 data on form submission. Returns true if Unicode
2963 * should make it through, false if it's known to be a problem.
2967 function checkUnicodeCompliantBrowser() {
2968 global $wgBrowserBlackList;
2969 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2970 // No User-Agent header sent? Trust it by default...
2973 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2974 foreach ( $wgBrowserBlackList as $browser ) {
2975 if ( preg_match($browser, $currentbrowser) ) {
2983 * Filter an input field through a Unicode de-armoring process if it
2984 * came from an old browser with known broken Unicode editing issues.
2986 * @param $request WebRequest
2987 * @param $field String
2991 function safeUnicodeInput( $request, $field ) {
2992 $text = rtrim( $request->getText( $field ) );
2993 return $request->getBool( 'safemode' )
2994 ?
$this->unmakesafe( $text )
2999 * @param $request WebRequest
3000 * @param $text string
3003 function safeUnicodeText( $request, $text ) {
3004 $text = rtrim( $text );
3005 return $request->getBool( 'safemode' )
3006 ?
$this->unmakesafe( $text )
3011 * Filter an output field through a Unicode armoring process if it is
3012 * going to an old browser with known broken Unicode editing issues.
3014 * @param $text String
3018 function safeUnicodeOutput( $text ) {
3020 $codedText = $wgContLang->recodeForEdit( $text );
3021 return $this->checkUnicodeCompliantBrowser()
3023 : $this->makesafe( $codedText );
3027 * A number of web browsers are known to corrupt non-ASCII characters
3028 * in a UTF-8 text editing environment. To protect against this,
3029 * detected browsers will be served an armored version of the text,
3030 * with non-ASCII chars converted to numeric HTML character references.
3032 * Preexisting such character references will have a 0 added to them
3033 * to ensure that round-trips do not alter the original data.
3035 * @param $invalue String
3039 function makesafe( $invalue ) {
3040 // Armor existing references for reversability.
3041 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3046 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3047 $bytevalue = ord( $invalue[$i] );
3048 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
3049 $result .= chr( $bytevalue );
3051 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
3052 $working = $working << 6;
3053 $working +
= ($bytevalue & 0x3F);
3055 if ( $bytesleft <= 0 ) {
3056 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3058 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
3059 $working = $bytevalue & 0x1F;
3061 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
3062 $working = $bytevalue & 0x0F;
3064 } else { //1111 0xxx
3065 $working = $bytevalue & 0x07;
3073 * Reverse the previously applied transliteration of non-ASCII characters
3074 * back to UTF-8. Used to protect data from corruption by broken web browsers
3075 * as listed in $wgBrowserBlackList.
3077 * @param $invalue String
3081 function unmakesafe( $invalue ) {
3083 for( $i = 0; $i < strlen( $invalue ); $i++
) {
3084 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+
3] != '0' ) ) {
3088 $hexstring .= $invalue[$i];
3090 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3092 // Do some sanity checks. These aren't needed for reversability,
3093 // but should help keep the breakage down if the editor
3094 // breaks one of the entities whilst editing.
3095 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
3096 $codepoint = hexdec($hexstring);
3097 $result .= codepointToUtf8( $codepoint );
3099 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3102 $result .= substr( $invalue, $i, 1 );
3105 // reverse the transform that we made for reversability reasons.
3106 return strtr( $result, array( "�" => "&#x" ) );