3 * Contains the EditPage class
8 * The edit page/HTML interface (split from Article)
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
13 * EditPage cares about two distinct titles:
14 * $this->mContextTitle is the page that forms submit to, links point to,
15 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
16 * page in the database that is actually being edited. These are
17 * usually the same, but they are now allowed to be different.
19 * Surgeon General's Warning: prolonged exposure to this class is known to cause
20 * headaches, which may be fatal.
23 const AS_SUCCESS_UPDATE
= 200;
24 const AS_SUCCESS_NEW_ARTICLE
= 201;
25 const AS_HOOK_ERROR
= 210;
26 const AS_FILTERING
= 211;
27 const AS_HOOK_ERROR_EXPECTED
= 212;
28 const AS_BLOCKED_PAGE_FOR_USER
= 215;
29 const AS_CONTENT_TOO_BIG
= 216;
30 const AS_USER_CANNOT_EDIT
= 217;
31 const AS_READ_ONLY_PAGE_ANON
= 218;
32 const AS_READ_ONLY_PAGE_LOGGED
= 219;
33 const AS_READ_ONLY_PAGE
= 220;
34 const AS_RATE_LIMITED
= 221;
35 const AS_ARTICLE_WAS_DELETED
= 222;
36 const AS_NO_CREATE_PERMISSION
= 223;
37 const AS_BLANK_ARTICLE
= 224;
38 const AS_CONFLICT_DETECTED
= 225;
39 const AS_SUMMARY_NEEDED
= 226;
40 const AS_TEXTBOX_EMPTY
= 228;
41 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
44 const AS_SPAM_ERROR
= 232;
45 const AS_IMAGE_REDIRECT_ANON
= 233;
46 const AS_IMAGE_REDIRECT_LOGGED
= 234;
57 private $mContextTitle = null;
58 var $action = 'submit';
59 var $isConflict = false;
60 var $isCssJsSubpage = false;
61 var $isCssSubpage = false;
62 var $isJsSubpage = false;
63 var $isWrongCaseCssJsPage = false;
64 var $isNew = false; // new page or new section
65 var $deletedSinceEdit;
69 var $mTokenOk = false;
70 var $mTokenOkExceptSuffix = false;
71 var $mTriedSave = false;
72 var $incompleteForm = false;
74 var $kblength = false;
75 var $missingComment = false;
76 var $missingSummary = false;
77 var $allowBlankSummary = false;
80 #var $mPreviewTemplates;
87 var $mBaseRevision = false;
88 var $mShowSummaryField = true;
91 var $save = false, $preview = false, $diff = false;
92 var $minoredit = false, $watchthis = false, $recreate = false;
93 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
94 var $edittime = '', $section = '', $starttime = '';
95 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
97 # Placeholders for text injection by hooks (must be HTML)
98 # extensions should take care to _append_ to the present value
99 public $editFormPageTop = ''; // Before even the preview
100 public $editFormTextTop = '';
101 public $editFormTextBeforeContent = '';
102 public $editFormTextAfterWarn = '';
103 public $editFormTextAfterTools = '';
104 public $editFormTextBottom = '';
105 public $editFormTextAfterContent = '';
106 public $previewTextAfterContent = '';
107 public $mPreloadText = '';
109 /* $didSave should be set to true whenever an article was succesfully altered. */
110 public $didSave = false;
111 public $undidRev = 0;
113 public $suppressIntro = false;
117 * @param $article Article
119 public function __construct( $article ) {
120 $this->mArticle
= $article;
121 $this->mTitle
= $article->getTitle();
127 public function getArticle() {
128 return $this->mArticle
;
135 public function getTitle() {
136 return $this->mTitle
;
140 * Set the context Title object
142 * @param $title Title object or null
144 public function setContextTitle( $title ) {
145 $this->mContextTitle
= $title;
149 * Get the context title object.
150 * If not set, $wgTitle will be returned. This behavior might changed in
151 * the future to return $this->mTitle instead.
153 * @return Title object
155 public function getContextTitle() {
156 if ( is_null( $this->mContextTitle
) ) {
160 return $this->mContextTitle
;
165 * Fetch initial editing page content.
167 * @param $def_text string
168 * @return mixed string on success, $def_text for invalid sections
171 function getContent( $def_text = '' ) {
172 global $wgOut, $wgRequest, $wgParser;
174 wfProfileIn( __METHOD__
);
175 # Get variables from query string :P
176 $section = $wgRequest->getVal( 'section' );
178 $preload = $wgRequest->getVal( 'preload',
179 // Custom preload text for new sections
180 $section === 'new' ?
'MediaWiki:addsection-preload' : '' );
181 $undoafter = $wgRequest->getVal( 'undoafter' );
182 $undo = $wgRequest->getVal( 'undo' );
184 // For message page not locally set, use the i18n message.
185 // For other non-existent articles, use preload text if any.
186 if ( !$this->mTitle
->exists() ) {
187 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
188 # If this is a system message, get the default text.
189 $text = $this->mTitle
->getDefaultMessageText();
190 if( $text === false ) {
191 $text = $this->getPreloadedText( $preload );
194 # If requested, preload some text.
195 $text = $this->getPreloadedText( $preload );
197 // For existing pages, get text based on "undo" or section parameters.
199 $text = $this->mArticle
->getContent();
200 if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
201 # If they got undoafter and undo round the wrong way, switch them
202 list( $undo, $undoafter ) = array( $undoafter, $undo );
204 if ( $undo > 0 && $undo > $undoafter ) {
205 # Undoing a specific edit overrides section editing; section-editing
206 # doesn't work with undoing.
208 $undorev = Revision
::newFromId( $undo );
209 $oldrev = Revision
::newFromId( $undoafter );
211 $undorev = Revision
::newFromId( $undo );
212 $oldrev = $undorev ?
$undorev->getPrevious() : null;
215 # Sanity check, make sure it's the right page,
216 # the revisions exist and they were not deleted.
217 # Otherwise, $text will be left as-is.
218 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
219 $undorev->getPage() == $oldrev->getPage() &&
220 $undorev->getPage() == $this->mArticle
->getID() &&
221 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
222 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
224 $undotext = $this->mArticle
->getUndoText( $undorev, $oldrev );
225 if ( $undotext === false ) {
226 # Warn the user that something went wrong
227 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-failure">' .
228 wfMsgNoTrans( 'undo-failure' ) . '</div>', true, /* interface */true );
231 # Inform the user of our success and set an automatic edit summary
232 $this->editFormPageTop
.= $wgOut->parse( '<div class="mw-undo-success">' .
233 wfMsgNoTrans( 'undo-success' ) . '</div>', true, /* interface */true );
234 $firstrev = $oldrev->getNext();
235 # If we just undid one rev, use an autosummary
236 if ( $firstrev->getId() == $undo ) {
237 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
238 if ( $this->summary
=== '' ) {
239 $this->summary
= $undoSummary;
241 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
243 $this->undidRev
= $undo;
245 $this->formtype
= 'diff';
248 // Failed basic sanity checks.
249 // Older revisions may have been removed since the link
250 // was created, or we may simply have got bogus input.
251 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-norev">' .
252 wfMsgNoTrans( 'undo-norev' ) . '</div>', true, /* interface */true );
254 } elseif ( $section != '' ) {
255 if ( $section == 'new' ) {
256 $text = $this->getPreloadedText( $preload );
258 // Get section edit text (returns $def_text for invalid sections)
259 $text = $wgParser->getSection( $text, $section, $def_text );
264 wfProfileOut( __METHOD__
);
269 * Use this method before edit() to preload some text into the edit box
271 * @param $text string
273 public function setPreloadedText( $text ) {
274 $this->mPreloadText
= $text;
278 * Get the contents to be preloaded into the box, either set by
279 * an earlier setPreloadText() or by loading the given page.
281 * @param $preload String: representing the title to preload from.
284 protected function getPreloadedText( $preload ) {
285 global $wgUser, $wgParser;
286 if ( !empty( $this->mPreloadText
) ) {
287 return $this->mPreloadText
;
288 } elseif ( $preload !== '' ) {
289 $title = Title
::newFromText( $preload );
290 # Check for existence to avoid getting MediaWiki:Noarticletext
291 if ( isset( $title ) && $title->exists() && $title->userCanRead() ) {
292 $article = new Article( $title );
294 if ( $article->isRedirect() ) {
295 $title = Title
::newFromRedirectRecurse( $article->getContent() );
296 # Redirects to missing titles are displayed, to hidden pages are followed
297 # Copying observed behaviour from ?action=view
298 if ( $title->exists() ) {
299 if ($title->userCanRead() ) {
300 $article = new Article( $title );
306 $parserOptions = ParserOptions
::newFromUser( $wgUser );
307 return $wgParser->getPreloadText( $article->getContent(), $title, $parserOptions );
314 * Check if a page was deleted while the user was editing it, before submit.
315 * Note that we rely on the logging table, which hasn't been always there,
316 * but that doesn't matter, because this only applies to brand new
319 protected function wasDeletedSinceLastEdit() {
320 if ( $this->deletedSinceEdit
!== null ) {
321 return $this->deletedSinceEdit
;
324 $this->deletedSinceEdit
= false;
326 if ( $this->mTitle
->isDeletedQuick() ) {
327 $this->lastDelete
= $this->getLastDelete();
328 if ( $this->lastDelete
) {
329 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
330 if ( $deleteTime > $this->starttime
) {
331 $this->deletedSinceEdit
= true;
336 return $this->deletedSinceEdit
;
340 * Checks whether the user entered a skin name in uppercase,
341 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
345 protected function isWrongCaseCssJsPage() {
346 if( $this->mTitle
->isCssJsSubpage() ) {
347 $name = $this->mTitle
->getSkinFromCssJsSubpage();
348 $skins = array_merge(
349 array_keys( Skin
::getSkinNames() ),
352 return !in_array( $name, $skins )
353 && in_array( strtolower( $name ), $skins );
364 * This is the function that gets called for "action=edit". It
365 * sets up various member variables, then passes execution to
366 * another function, usually showEditForm()
368 * The edit form is self-submitting, so that when things like
369 * preview and edit conflicts occur, we get the same form back
370 * with the extra stuff added. Only when the final submission
371 * is made and all is well do we actually save and redirect to
372 * the newly-edited page.
375 global $wgOut, $wgRequest, $wgUser;
376 // Allow extensions to modify/prevent this form or submission
377 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
381 wfProfileIn( __METHOD__
);
382 wfDebug( __METHOD__
.": enter\n" );
384 // If they used redlink=1 and the page exists, redirect to the main article
385 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
386 $wgOut->redirect( $this->mTitle
->getFullURL() );
387 wfProfileOut( __METHOD__
);
391 $this->importFormData( $wgRequest );
392 $this->firsttime
= false;
395 $this->livePreview();
396 wfProfileOut( __METHOD__
);
400 if ( wfReadOnly() && $this->save
) {
403 $this->preview
= true;
407 $this->formtype
= 'save';
408 } elseif ( $this->preview
) {
409 $this->formtype
= 'preview';
410 } elseif ( $this->diff
) {
411 $this->formtype
= 'diff';
412 } else { # First time through
413 $this->firsttime
= true;
414 if ( $this->previewOnOpen() ) {
415 $this->formtype
= 'preview';
417 $this->formtype
= 'initial';
421 $permErrors = $this->getEditPermissionErrors();
423 wfDebug( __METHOD__
. ": User can't edit\n" );
424 // Auto-block user's IP if the account was "hard" blocked
425 $wgUser->spreadAnyEditBlock();
427 $this->displayPermissionsError( $permErrors );
429 wfProfileOut( __METHOD__
);
433 $wgOut->addModules( array( 'mediawiki.action.edit' ) );
435 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
436 $wgOut->addModules( 'mediawiki.legacy.preview' );
438 // Bug #19334: textarea jumps when editing articles in IE8
439 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
441 wfProfileIn( __METHOD__
."-business-end" );
443 $this->isConflict
= false;
444 // css / js subpages of user pages get a special treatment
445 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
446 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
447 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
448 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
449 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
451 # Show applicable editing introductions
452 if ( $this->formtype
== 'initial' ||
$this->firsttime
)
455 if ( $this->mTitle
->isTalkPage() ) {
456 $wgOut->addWikiMsg( 'talkpagetext' );
459 # Optional notices on a per-namespace and per-page basis
460 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
461 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
462 if ( $editnotice_ns_message->exists() ) {
463 $wgOut->addWikiText( $editnotice_ns_message->plain() );
465 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
466 $parts = explode( '/', $this->mTitle
->getDBkey() );
467 $editnotice_base = $editnotice_ns;
468 while ( count( $parts ) > 0 ) {
469 $editnotice_base .= '-'.array_shift( $parts );
470 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
471 if ( $editnotice_base_msg->exists() ) {
472 $wgOut->addWikiText( $editnotice_base_msg->plain() );
476 # Even if there are no subpages in namespace, we still don't want / in MW ns.
477 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
478 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
479 if ( $editnoticeMsg->exists() ) {
480 $wgOut->addWikiText( $editnoticeMsg->plain() );
484 # Attempt submission here. This will check for edit conflicts,
485 # and redundantly check for locked database, blocked IPs, etc.
486 # that edit() already checked just in case someone tries to sneak
487 # in the back door with a hand-edited submission URL.
489 if ( 'save' == $this->formtype
) {
490 if ( !$this->attemptSave() ) {
491 wfProfileOut( __METHOD__
."-business-end" );
492 wfProfileOut( __METHOD__
);
497 # First time through: get contents, set time for conflict
499 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
500 if ( $this->initialiseForm() === false ) {
501 $this->noSuchSectionPage();
502 wfProfileOut( __METHOD__
."-business-end" );
503 wfProfileOut( __METHOD__
);
506 if ( !$this->mTitle
->getArticleId() )
507 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
509 wfRunHooks( 'EditFormInitialText', array( $this ) );
512 $this->showEditForm();
513 wfProfileOut( __METHOD__
."-business-end" );
514 wfProfileOut( __METHOD__
);
520 protected function getEditPermissionErrors() {
522 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
523 # Can this title be created?
524 if ( !$this->mTitle
->exists() ) {
525 $permErrors = array_merge( $permErrors,
526 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
528 # Ignore some permissions errors when a user is just previewing/viewing diffs
530 foreach( $permErrors as $error ) {
531 if ( ( $this->preview ||
$this->diff
) &&
532 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
537 $permErrors = wfArrayDiff2( $permErrors, $remove );
542 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
543 * but with the following differences:
544 * - If redlink=1, the user will be redirect to the page
545 * - If there is content to display or the error occurs while either saving,
546 * previewing or showing the difference, it will be a
547 * "View source for ..." page displaying the source code after the error message.
550 * @param $permErrors Array of permissions errors, as returned by
551 * Title::getUserPermissionsErrors().
553 protected function displayPermissionsError( array $permErrors ) {
554 global $wgRequest, $wgOut;
556 if ( $wgRequest->getBool( 'redlink' ) ) {
557 // The edit page was reached via a red link.
558 // Redirect to the article page and let them click the edit tab if
559 // they really want a permission error.
560 $wgOut->redirect( $this->mTitle
->getFullUrl() );
564 $content = $this->getContent();
566 # Use the normal message if there's nothing to display
567 if ( $this->firsttime
&& $content === '' ) {
568 $action = $this->mTitle
->exists() ?
'edit' :
569 ( $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
570 throw new PermissionsError( $action, $permErrors );
573 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
574 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
575 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
576 $wgOut->addHTML( "<hr />\n" );
578 # If the user made changes, preserve them when showing the markup
579 # (This happens when a user is blocked during edit, for instance)
580 if ( !$this->firsttime
) {
581 $content = $this->textbox1
;
582 $wgOut->addWikiMsg( 'viewyourtext' );
584 $wgOut->addWikiMsg( 'viewsourcetext' );
587 $this->showTextbox( $content, 'wpTextbox1', array( 'readonly' ) );
589 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
590 Linker
::formatTemplates( $this->getTemplates() ) ) );
592 if ( $this->mTitle
->exists() ) {
593 $wgOut->returnToMain( null, $this->mTitle
);
598 * Show a read-only error
599 * Parameters are the same as OutputPage:readOnlyPage()
600 * Redirect to the article page if redlink=1
601 * @deprecated in 1.19; use displayPermissionsError() instead
603 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
604 global $wgRequest, $wgOut;
605 if ( $wgRequest->getBool( 'redlink' ) ) {
606 // The edit page was reached via a red link.
607 // Redirect to the article page and let them click the edit tab if
608 // they really want a permission error.
609 $wgOut->redirect( $this->mTitle
->getFullUrl() );
611 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
616 * Should we show a preview when the edit form is first shown?
620 protected function previewOnOpen() {
621 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
622 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
623 // Explicit override from request
625 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
626 // Explicit override from request
628 } elseif ( $this->section
== 'new' ) {
629 // Nothing *to* preview for new sections
631 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
632 // Standard preference behaviour
634 } elseif ( !$this->mTitle
->exists() &&
635 isset($wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]) &&
636 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
638 // Categories are special
646 * Does this EditPage class support section editing?
647 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
651 protected function isSectionEditSupported() {
656 * Returns the URL to use in the form's action attribute.
657 * This is used by EditPage subclasses when simply customizing the action
658 * variable in the constructor is not enough. This can be used when the
659 * EditPage lives inside of a Special page rather than a custom page action.
661 * @param $title Title object for which is being edited (where we go to for &action= links)
664 protected function getActionURL( Title
$title ) {
665 return $title->getLocalURL( array( 'action' => $this->action
) );
670 * @param $request WebRequest
672 function importFormData( &$request ) {
673 global $wgLang, $wgUser;
675 wfProfileIn( __METHOD__
);
677 # Section edit can come from either the form or a link
678 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
680 if ( $request->wasPosted() ) {
681 # These fields need to be checked for encoding.
682 # Also remove trailing whitespace, but don't remove _initial_
683 # whitespace from the text boxes. This may be significant formatting.
684 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
685 if ( !$request->getCheck('wpTextbox2') ) {
686 // Skip this if wpTextbox2 has input, it indicates that we came
687 // from a conflict page with raw page text, not a custom form
688 // modified by subclasses
689 wfProfileIn( get_class($this)."::importContentFormData" );
690 $textbox1 = $this->importContentFormData( $request );
691 if ( isset($textbox1) )
692 $this->textbox1
= $textbox1;
693 wfProfileOut( get_class($this)."::importContentFormData" );
696 # Truncate for whole multibyte characters. +5 bytes for ellipsis
697 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
699 # Remove extra headings from summaries and new sections.
700 $this->summary
= preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
702 $this->edittime
= $request->getVal( 'wpEdittime' );
703 $this->starttime
= $request->getVal( 'wpStarttime' );
705 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
707 if ($this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null) {
708 // wpTextbox1 field is missing, possibly due to being "too big"
709 // according to some filter rules such as Suhosin's setting for
710 // suhosin.request.max_value_length (d'oh)
711 $this->incompleteForm
= true;
713 // edittime should be one of our last fields; if it's missing,
714 // the submission probably broke somewhere in the middle.
715 $this->incompleteForm
= is_null( $this->edittime
);
717 if ( $this->incompleteForm
) {
718 # If the form is incomplete, force to preview.
719 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
720 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
721 $this->preview
= true;
723 /* Fallback for live preview */
724 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
725 $this->diff
= $request->getCheck( 'wpDiff' );
727 // Remember whether a save was requested, so we can indicate
728 // if we forced preview due to session failure.
729 $this->mTriedSave
= !$this->preview
;
731 if ( $this->tokenOk( $request ) ) {
732 # Some browsers will not report any submit button
733 # if the user hits enter in the comment box.
734 # The unmarked state will be assumed to be a save,
735 # if the form seems otherwise complete.
736 wfDebug( __METHOD__
. ": Passed token check.\n" );
737 } elseif ( $this->diff
) {
738 # Failed token check, but only requested "Show Changes".
739 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
741 # Page might be a hack attempt posted from
742 # an external site. Preview instead of saving.
743 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
744 $this->preview
= true;
747 $this->save
= !$this->preview
&& !$this->diff
;
748 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
749 $this->edittime
= null;
752 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
753 $this->starttime
= null;
756 $this->recreate
= $request->getCheck( 'wpRecreate' );
758 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
759 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
761 # Don't force edit summaries when a user is editing their own user or talk page
762 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
763 $this->mTitle
->getText() == $wgUser->getName() )
765 $this->allowBlankSummary
= true;
767 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
770 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
772 # Not a posted form? Start with nothing.
773 wfDebug( __METHOD__
. ": Not a posted form.\n" );
774 $this->textbox1
= '';
776 $this->edittime
= '';
777 $this->starttime
= wfTimestampNow();
779 $this->preview
= false;
782 $this->minoredit
= false;
783 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
784 $this->recreate
= false;
786 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
787 $this->summary
= $request->getVal( 'preloadtitle' );
789 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
790 $this->summary
= $request->getText( 'summary' );
793 if ( $request->getVal( 'minor' ) ) {
794 $this->minoredit
= true;
798 $this->bot
= $request->getBool( 'bot', true );
799 $this->nosummary
= $request->getBool( 'nosummary' );
801 // @todo FIXME: Unused variable?
802 $this->oldid
= $request->getInt( 'oldid' );
804 $this->live
= $request->getCheck( 'live' );
805 $this->editintro
= $request->getText( 'editintro',
806 // Custom edit intro for new sections
807 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
809 // Allow extensions to modify form data
810 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
812 wfProfileOut( __METHOD__
);
816 * Subpage overridable method for extracting the page content data from the
817 * posted form to be placed in $this->textbox1, if using customized input
818 * this method should be overrided and return the page text that will be used
819 * for saving, preview parsing and so on...
821 * @param $request WebRequest
823 protected function importContentFormData( &$request ) {
824 return; // Don't do anything, EditPage already extracted wpTextbox1
828 * Make sure the form isn't faking a user's credentials.
830 * @param $request WebRequest
834 function tokenOk( &$request ) {
836 $token = $request->getVal( 'wpEditToken' );
837 $this->mTokenOk
= $wgUser->matchEditToken( $token );
838 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
839 return $this->mTokenOk
;
843 * Show all applicable editing introductions
845 protected function showIntro() {
846 global $wgOut, $wgUser;
847 if ( $this->suppressIntro
) {
851 $namespace = $this->mTitle
->getNamespace();
853 if ( $namespace == NS_MEDIAWIKI
) {
854 # Show a warning if editing an interface message
855 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
858 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
859 # Show log extract when the user is currently blocked
860 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
861 $parts = explode( '/', $this->mTitle
->getText(), 2 );
862 $username = $parts[0];
863 $user = User
::newFromName( $username, false /* allow IP users*/ );
864 $ip = User
::isIP( $username );
865 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
866 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
867 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
868 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
869 LogEventsList
::showLogExtract(
872 $user->getUserPage(),
876 'showIfEmpty' => false,
878 'blocked-notice-logextract',
879 $user->getName() # Support GENDER in notice
885 # Try to add a custom edit intro, or use the standard one if this is not possible.
886 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
887 if ( $wgUser->isLoggedIn() ) {
888 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
890 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
893 # Give a notice if the user is editing a deleted/moved page...
894 if ( !$this->mTitle
->exists() ) {
895 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
896 '', array( 'lim' => 10,
897 'conds' => array( "log_action != 'revision'" ),
898 'showIfEmpty' => false,
899 'msgKey' => array( 'recreate-moveddeleted-warn') )
905 * Attempt to show a custom editing introduction, if supplied
909 protected function showCustomIntro() {
910 if ( $this->editintro
) {
911 $title = Title
::newFromText( $this->editintro
);
912 if ( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
914 // Added using template syntax, to take <noinclude>'s into account.
915 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
926 * Attempt submission (no UI)
931 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
933 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
934 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
935 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
937 function internalAttemptSave( &$result, $bot = false ) {
938 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
939 global $wgMaxArticleSize;
941 $status = Status
::newGood();
943 wfProfileIn( __METHOD__
);
944 wfProfileIn( __METHOD__
. '-checks' );
946 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
947 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
948 $status->fatal( 'hookaborted' );
949 $status->value
= self
::AS_HOOK_ERROR
;
950 wfProfileOut( __METHOD__
. '-checks' );
951 wfProfileOut( __METHOD__
);
955 # Check image redirect
956 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
957 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
958 !$wgUser->isAllowed( 'upload' ) ) {
959 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
960 $status->setResult( false, $code );
962 wfProfileOut( __METHOD__
. '-checks' );
963 wfProfileOut( __METHOD__
);
969 $match = self
::matchSummarySpamRegex( $this->summary
);
970 if ( $match === false ) {
971 $match = self
::matchSpamRegex( $this->textbox1
);
973 if ( $match !== false ) {
974 $result['spam'] = $match;
975 $ip = $wgRequest->getIP();
976 $pdbk = $this->mTitle
->getPrefixedDBkey();
977 $match = str_replace( "\n", '', $match );
978 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
979 $status->fatal( 'spamprotectionmatch', $match );
980 $status->value
= self
::AS_SPAM_ERROR
;
981 wfProfileOut( __METHOD__
. '-checks' );
982 wfProfileOut( __METHOD__
);
985 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
986 # Error messages or other handling should be performed by the filter function
987 $status->setResult( false, self
::AS_FILTERING
);
988 wfProfileOut( __METHOD__
. '-checks' );
989 wfProfileOut( __METHOD__
);
992 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
993 # Error messages etc. could be handled within the hook...
994 $status->fatal( 'hookaborted' );
995 $status->value
= self
::AS_HOOK_ERROR
;
996 wfProfileOut( __METHOD__
. '-checks' );
997 wfProfileOut( __METHOD__
);
999 } elseif ( $this->hookError
!= '' ) {
1000 # ...or the hook could be expecting us to produce an error
1001 $status->fatal( 'hookaborted' );
1002 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1003 wfProfileOut( __METHOD__
. '-checks' );
1004 wfProfileOut( __METHOD__
);
1008 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1009 // Auto-block user's IP if the account was "hard" blocked
1010 $wgUser->spreadAnyEditBlock();
1011 # Check block state against master, thus 'false'.
1012 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1013 wfProfileOut( __METHOD__
. '-checks' );
1014 wfProfileOut( __METHOD__
);
1018 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1019 if ( $this->kblength
> $wgMaxArticleSize ) {
1020 // Error will be displayed by showEditForm()
1021 $this->tooBig
= true;
1022 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1023 wfProfileOut( __METHOD__
. '-checks' );
1024 wfProfileOut( __METHOD__
);
1028 if ( !$wgUser->isAllowed( 'edit' ) ) {
1029 if ( $wgUser->isAnon() ) {
1030 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1031 wfProfileOut( __METHOD__
. '-checks' );
1032 wfProfileOut( __METHOD__
);
1035 $status->fatal( 'readonlytext' );
1036 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1037 wfProfileOut( __METHOD__
. '-checks' );
1038 wfProfileOut( __METHOD__
);
1043 if ( wfReadOnly() ) {
1044 $status->fatal( 'readonlytext' );
1045 $status->value
= self
::AS_READ_ONLY_PAGE
;
1046 wfProfileOut( __METHOD__
. '-checks' );
1047 wfProfileOut( __METHOD__
);
1050 if ( $wgUser->pingLimiter() ) {
1051 $status->fatal( 'actionthrottledtext' );
1052 $status->value
= self
::AS_RATE_LIMITED
;
1053 wfProfileOut( __METHOD__
. '-checks' );
1054 wfProfileOut( __METHOD__
);
1058 # If the article has been deleted while editing, don't save it without
1060 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1061 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1062 wfProfileOut( __METHOD__
. '-checks' );
1063 wfProfileOut( __METHOD__
);
1067 wfProfileOut( __METHOD__
. '-checks' );
1069 # If article is new, insert it.
1070 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1071 $new = ( $aid == 0 );
1074 // Late check for create permission, just in case *PARANOIA*
1075 if ( !$this->mTitle
->userCan( 'create' ) ) {
1076 $status->fatal( 'nocreatetext' );
1077 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1078 wfDebug( __METHOD__
. ": no create permission\n" );
1079 wfProfileOut( __METHOD__
);
1083 # Don't save a new article if it's blank.
1084 if ( $this->textbox1
== '' ) {
1085 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1086 wfProfileOut( __METHOD__
);
1090 // Run post-section-merge edit filter
1091 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1092 # Error messages etc. could be handled within the hook...
1093 $status->fatal( 'hookaborted' );
1094 $status->value
= self
::AS_HOOK_ERROR
;
1095 wfProfileOut( __METHOD__
);
1097 } elseif ( $this->hookError
!= '' ) {
1098 # ...or the hook could be expecting us to produce an error
1099 $status->fatal( 'hookaborted' );
1100 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1101 wfProfileOut( __METHOD__
);
1105 # Handle the user preference to force summaries here. Check if it's not a redirect.
1106 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
1107 if ( md5( $this->summary
) == $this->autoSumm
) {
1108 $this->missingSummary
= true;
1109 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1110 $status->value
= self
::AS_SUMMARY_NEEDED
;
1111 wfProfileOut( __METHOD__
);
1116 $text = $this->textbox1
;
1117 if ( $this->section
== 'new' && $this->summary
!= '' ) {
1118 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $text;
1121 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1125 # Article exists. Check for edit conflict.
1127 $this->mArticle
->clear(); # Force reload of dates, etc.
1129 wfDebug( "timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n" );
1131 if ( $this->mArticle
->getTimestamp() != $this->edittime
) {
1132 $this->isConflict
= true;
1133 if ( $this->section
== 'new' ) {
1134 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1135 $this->mArticle
->getComment() == $this->summary
) {
1136 // Probably a duplicate submission of a new comment.
1137 // This can happen when squid resends a request after
1138 // a timeout but the first one actually went through.
1139 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1141 // New comment; suppress conflict.
1142 $this->isConflict
= false;
1143 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1145 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1146 # Suppress edit conflict with self, except for section edits where merging is required.
1147 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1148 $this->isConflict
= false;
1152 if ( $this->isConflict
) {
1153 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
1154 $this->mArticle
->getTimestamp() . "')\n" );
1155 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1157 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1158 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
1160 if ( is_null( $text ) ) {
1161 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1162 $this->isConflict
= true;
1163 $text = $this->textbox1
; // do not try to merge here!
1164 } elseif ( $this->isConflict
) {
1166 if ( $this->mergeChangesInto( $text ) ) {
1167 // Successful merge! Maybe we should tell the user the good news?
1168 $this->isConflict
= false;
1169 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1171 $this->section
= '';
1172 $this->textbox1
= $text;
1173 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1177 if ( $this->isConflict
) {
1178 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1179 wfProfileOut( __METHOD__
);
1183 // Run post-section-merge edit filter
1184 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
1185 # Error messages etc. could be handled within the hook...
1186 $status->fatal( 'hookaborted' );
1187 $status->value
= self
::AS_HOOK_ERROR
;
1188 wfProfileOut( __METHOD__
);
1190 } elseif ( $this->hookError
!= '' ) {
1191 # ...or the hook could be expecting us to produce an error
1192 $status->fatal( 'hookaborted' );
1193 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1194 wfProfileOut( __METHOD__
);
1198 # Handle the user preference to force summaries here, but not for null edits
1199 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1200 && 0 != strcmp( $this->mArticle
->getContent(), $text )
1201 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1203 if ( md5( $this->summary
) == $this->autoSumm
) {
1204 $this->missingSummary
= true;
1205 $status->fatal( 'missingsummary' );
1206 $status->value
= self
::AS_SUMMARY_NEEDED
;
1207 wfProfileOut( __METHOD__
);
1212 # And a similar thing for new sections
1213 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1214 if ( trim( $this->summary
) == '' ) {
1215 $this->missingSummary
= true;
1216 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1217 $status->value
= self
::AS_SUMMARY_NEEDED
;
1218 wfProfileOut( __METHOD__
);
1224 wfProfileIn( __METHOD__
. '-sectionanchor' );
1225 $sectionanchor = '';
1226 if ( $this->section
== 'new' ) {
1227 if ( $this->textbox1
== '' ) {
1228 $this->missingComment
= true;
1229 $status->fatal( 'missingcommenttext' );
1230 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1231 wfProfileOut( __METHOD__
. '-sectionanchor' );
1232 wfProfileOut( __METHOD__
);
1235 if ( $this->summary
!= '' ) {
1236 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1237 # This is a new section, so create a link to the new section
1238 # in the revision summary.
1239 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1240 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1242 } elseif ( $this->section
!= '' ) {
1243 # Try to get a section anchor from the section source, redirect to edited section if header found
1244 # XXX: might be better to integrate this into Article::replaceSection
1245 # for duplicate heading checking and maybe parsing
1246 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1247 # we can't deal with anchors, includes, html etc in the header for now,
1248 # headline would need to be parsed to improve this
1249 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1250 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1253 $result['sectionanchor'] = $sectionanchor;
1254 wfProfileOut( __METHOD__
. '-sectionanchor' );
1256 // Save errors may fall down to the edit form, but we've now
1257 // merged the section into full text. Clear the section field
1258 // so that later submission of conflict forms won't try to
1259 // replace that into a duplicated mess.
1260 $this->textbox1
= $text;
1261 $this->section
= '';
1263 $status->value
= self
::AS_SUCCESS_UPDATE
;
1266 // Check for length errors again now that the section is merged in
1267 $this->kblength
= (int)( strlen( $text ) / 1024 );
1268 if ( $this->kblength
> $wgMaxArticleSize ) {
1269 $this->tooBig
= true;
1270 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1271 wfProfileOut( __METHOD__
);
1275 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1276 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1277 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1278 ( $bot ? EDIT_FORCE_BOT
: 0 );
1280 $doEditStatus = $this->mArticle
->doEdit( $text, $this->summary
, $flags );
1282 if ( $doEditStatus->isOK() ) {
1283 $result['redirect'] = Title
::newFromRedirect( $text ) !== null;
1284 $this->commitWatch();
1285 wfProfileOut( __METHOD__
);
1288 $this->isConflict
= true;
1289 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1290 wfProfileOut( __METHOD__
);
1291 return $doEditStatus;
1296 * Commit the change of watch status
1298 protected function commitWatch() {
1300 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1301 $dbw = wfGetDB( DB_MASTER
);
1303 if ( $this->watchthis
) {
1304 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1306 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1313 * Check if no edits were made by other users since
1314 * the time a user started editing the page. Limit to
1315 * 50 revisions for the sake of performance.
1318 * @param $edittime string
1322 protected function userWasLastToEdit( $id, $edittime ) {
1323 if( !$id ) return false;
1324 $dbw = wfGetDB( DB_MASTER
);
1325 $res = $dbw->select( 'revision',
1328 'rev_page' => $this->mArticle
->getId(),
1329 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1332 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1333 foreach ( $res as $row ) {
1334 if( $row->rev_user
!= $id ) {
1342 * Check given input text against $wgSpamRegex, and return the text of the first match.
1344 * @param $text string
1346 * @return string|false matching string or false
1348 public static function matchSpamRegex( $text ) {
1349 global $wgSpamRegex;
1350 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1351 $regexes = (array)$wgSpamRegex;
1352 return self
::matchSpamRegexInternal( $text, $regexes );
1356 * Check given input text against $wgSpamRegex, and return the text of the first match.
1358 * @parma $text string
1360 * @return string|false matching string or false
1362 public static function matchSummarySpamRegex( $text ) {
1363 global $wgSummarySpamRegex;
1364 $regexes = (array)$wgSummarySpamRegex;
1365 return self
::matchSpamRegexInternal( $text, $regexes );
1369 * @param $text string
1370 * @param $regexes array
1371 * @return bool|string
1373 protected static function matchSpamRegexInternal( $text, $regexes ) {
1374 foreach( $regexes as $regex ) {
1376 if( preg_match( $regex, $text, $matches ) ) {
1384 * Initialise form fields in the object
1385 * Called on the first invocation, e.g. when a user clicks an edit link
1386 * @return bool -- if the requested section is valid
1388 function initialiseForm() {
1390 $this->edittime
= $this->mArticle
->getTimestamp();
1391 $this->textbox1
= $this->getContent( false );
1392 // activate checkboxes if user wants them to be always active
1393 # Sort out the "watch" checkbox
1394 if ( $wgUser->getOption( 'watchdefault' ) ) {
1396 $this->watchthis
= true;
1397 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1399 $this->watchthis
= true;
1400 } elseif ( $this->mTitle
->userIsWatching() ) {
1402 $this->watchthis
= true;
1404 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
1405 $this->minoredit
= true;
1407 if ( $this->textbox1
=== false ) {
1414 function setHeaders() {
1416 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1417 if ( $this->isConflict
) {
1418 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1419 } elseif ( $this->section
!= '' ) {
1420 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1421 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1423 # Use the title defined by DISPLAYTITLE magic word when present
1424 if ( isset( $this->mParserOutput
)
1425 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1428 $title = $this->getContextTitle()->getPrefixedText();
1430 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1435 * Send the edit form and related headers to $wgOut
1436 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1437 * during form output near the top, for captchas and the like.
1439 function showEditForm( $formCallback = null ) {
1440 global $wgOut, $wgUser;
1442 wfProfileIn( __METHOD__
);
1444 #need to parse the preview early so that we know which templates are used,
1445 #otherwise users with "show preview after edit box" will get a blank list
1446 #we parse this near the beginning so that setHeaders can do the title
1447 #setting work instead of leaving it in getPreviewText
1448 $previewOutput = '';
1449 if ( $this->formtype
== 'preview' ) {
1450 $previewOutput = $this->getPreviewText();
1453 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1455 $this->setHeaders();
1457 # Enabled article-related sidebar, toplinks, etc.
1458 $wgOut->setArticleRelated( true );
1460 if ( $this->showHeader() === false ) {
1461 wfProfileOut( __METHOD__
);
1465 $action = htmlspecialchars( $this->getActionURL( $this->getContextTitle() ) );
1467 if ( $wgUser->getOption( 'showtoolbar' ) and !$this->isCssJsSubpage
) {
1468 # prepare toolbar for edit buttons
1469 $toolbar = EditPage
::getEditToolbar();
1475 $wgOut->addHTML( $this->editFormPageTop
);
1477 if ( $wgUser->getOption( 'previewontop' ) ) {
1478 $this->displayPreviewArea( $previewOutput, true );
1481 $wgOut->addHTML( $this->editFormTextTop
);
1483 $templates = $this->getTemplates();
1484 $formattedtemplates = Linker
::formatTemplates( $templates, $this->preview
, $this->section
!= '');
1486 $hiddencats = $this->mArticle
->getHiddenCategories();
1487 $formattedhiddencats = Linker
::formatHiddenCategories( $hiddencats );
1489 if ( $this->wasDeletedSinceLastEdit() && 'save' != $this->formtype
) {
1490 $wgOut->wrapWikiMsg(
1491 "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1492 'deletedwhileediting' );
1493 } elseif ( $this->wasDeletedSinceLastEdit() ) {
1494 // Hide the toolbar and edit area, user can click preview to get it back
1495 // Add an confirmation checkbox and explanation.
1497 // @todo move this to a cleaner conditional instead of blanking a variable
1499 $wgOut->addHTML( <<<HTML
1500 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1504 if ( is_callable( $formCallback ) ) {
1505 call_user_func_array( $formCallback, array( &$wgOut ) );
1508 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1510 // Put these up at the top to ensure they aren't lost on early form submission
1511 $this->showFormBeforeText();
1513 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1514 $username = $this->lastDelete
->user_name
;
1515 $comment = $this->lastDelete
->log_comment
;
1517 // It is better to not parse the comment at all than to have templates expanded in the middle
1518 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1519 $key = $comment === ''
1520 ?
'confirmrecreate-noreason'
1521 : 'confirmrecreate';
1523 '<div class="mw-confirm-recreate">' .
1524 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1525 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1526 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1532 # If a blank edit summary was previously provided, and the appropriate
1533 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1534 # user being bounced back more than once in the event that a summary
1537 # For a bit more sophisticated detection of blank summaries, hash the
1538 # automatic one and pass that in the hidden field wpAutoSummary.
1539 if ( $this->missingSummary ||
1540 ( $this->section
== 'new' && $this->nosummary
) )
1541 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1542 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1543 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1545 $wgOut->addHTML( Html
::hidden( 'oldid', $this->mArticle
->getOldID() ) );
1547 if ( $this->section
== 'new' ) {
1548 $this->showSummaryInput( true, $this->summary
);
1549 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1552 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1554 $wgOut->addHTML( $toolbar );
1556 if ( $this->isConflict
) {
1557 // In an edit conflict bypass the overrideable content form method
1558 // and fallback to the raw wpTextbox1 since editconflicts can't be
1559 // resolved between page source edits and custom ui edits using the
1561 $this->showTextbox1( null, $this->getContent() );
1563 $this->showContentForm();
1566 $wgOut->addHTML( $this->editFormTextAfterContent
);
1568 $wgOut->addWikiText( $this->getCopywarn() );
1569 if ( isset($this->editFormTextAfterWarn
) && $this->editFormTextAfterWarn
!== '' )
1570 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1572 $this->showStandardInputs();
1574 $this->showFormAfterText();
1576 $this->showTosSummary();
1577 $this->showEditTools();
1579 $wgOut->addHTML( <<<HTML
1580 {$this->editFormTextAfterTools}
1581 <div class='templatesUsed'>
1582 {$formattedtemplates}
1584 <div class='hiddencats'>
1585 {$formattedhiddencats}
1590 if ( $this->isConflict
)
1591 $this->showConflict();
1593 $wgOut->addHTML( $this->editFormTextBottom
);
1594 $wgOut->addHTML( "</form>\n" );
1595 if ( !$wgUser->getOption( 'previewontop' ) ) {
1596 $this->displayPreviewArea( $previewOutput, false );
1599 wfProfileOut( __METHOD__
);
1602 protected function showHeader() {
1603 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1604 if ( $this->isConflict
) {
1605 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1606 $this->edittime
= $this->mArticle
->getTimestamp();
1608 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
1609 // We use $this->section to much before this and getVal('wgSection') directly in other places
1610 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1611 // Someone is welcome to try refactoring though
1612 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1616 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1618 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1619 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1
, $matches );
1620 if ( !empty( $matches[2] ) ) {
1622 $this->summary
= "/* " .
1623 $wgParser->stripSectionName(trim($matches[2])) .
1629 if ( $this->missingComment
) {
1630 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1633 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1634 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1637 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1638 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1641 if ( $this->hookError
!== '' ) {
1642 $wgOut->addWikiText( $this->hookError
);
1645 if ( !$this->checkUnicodeCompliantBrowser() ) {
1646 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1649 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1650 // Let sysop know that this will make private content public if saved
1652 if ( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1653 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1654 } elseif ( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1655 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1658 if ( !$this->mArticle
->mRevision
->isCurrent() ) {
1659 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1660 $wgOut->addWikiMsg( 'editingold' );
1665 if ( wfReadOnly() ) {
1666 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1667 } elseif ( $wgUser->isAnon() ) {
1668 if ( $this->formtype
!= 'preview' ) {
1669 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1671 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
1674 if ( $this->isCssJsSubpage
) {
1675 # Check the skin exists
1676 if ( $this->isWrongCaseCssJsPage
) {
1677 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
1679 if ( $this->formtype
!== 'preview' ) {
1680 if ( $this->isCssSubpage
)
1681 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
1682 if ( $this->isJsSubpage
)
1683 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
1688 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
1689 # Is the title semi-protected?
1690 if ( $this->mTitle
->isSemiProtected() ) {
1691 $noticeMsg = 'semiprotectedpagewarning';
1693 # Then it must be protected based on static groups (regular)
1694 $noticeMsg = 'protectedpagewarning';
1696 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1697 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1699 if ( $this->mTitle
->isCascadeProtected() ) {
1700 # Is this page under cascading protection from some source pages?
1701 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1702 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
1703 $cascadeSourcesCount = count( $cascadeSources );
1704 if ( $cascadeSourcesCount > 0 ) {
1705 # Explain, and list the titles responsible
1706 foreach( $cascadeSources as $page ) {
1707 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1710 $notice .= '</div>';
1711 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1713 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1714 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1716 'showIfEmpty' => false,
1717 'msgKey' => array( 'titleprotectedwarning' ),
1718 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
1721 if ( $this->kblength
=== false ) {
1722 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1725 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1726 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
1727 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
1729 if( !wfMessage('longpage-hint')->isDisabled() ) {
1730 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
1731 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
1738 * Standard summary input and label (wgSummary), abstracted so EditPage
1739 * subclasses may reorganize the form.
1740 * Note that you do not need to worry about the label's for=, it will be
1741 * inferred by the id given to the input. You can remove them both by
1742 * passing array( 'id' => false ) to $userInputAttrs.
1744 * @param $summary string The value of the summary input
1745 * @param $labelText string The html to place inside the label
1746 * @param $inputAttrs array of attrs to use on the input
1747 * @param $spanLabelAttrs array of attrs to use on the span inside the label
1749 * @return array An array in the format array( $label, $input )
1751 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
1752 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
1753 $inputAttrs = ( is_array($inputAttrs) ?
$inputAttrs : array() ) +
array(
1754 'id' => 'wpSummary',
1755 'maxlength' => '200',
1758 'spellcheck' => 'true',
1759 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
1761 $spanLabelAttrs = ( is_array($spanLabelAttrs) ?
$spanLabelAttrs : array() ) +
array(
1762 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
1763 'id' => "wpSummaryLabel"
1768 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1769 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
1772 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
1774 return array( $label, $input );
1778 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1779 * up top, or false if this is the comment summary
1780 * down below the textarea
1781 * @param $summary String: The text of the summary to display
1784 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1785 global $wgOut, $wgContLang;
1786 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1787 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1788 if ( $isSubjectPreview ) {
1789 if ( $this->nosummary
) {
1793 if ( !$this->mShowSummaryField
) {
1797 $summary = $wgContLang->recodeForEdit( $summary );
1798 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
1799 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
1800 $wgOut->addHTML("{$label} {$input}");
1804 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1805 * up top, or false if this is the comment summary
1806 * down below the textarea
1807 * @param $summary String: the text of the summary to display
1810 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
1811 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
1816 if ( $isSubjectPreview )
1817 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
1819 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
1821 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
1822 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
1825 protected function showFormBeforeText() {
1827 $section = htmlspecialchars( $this->section
);
1828 $wgOut->addHTML( <<<HTML
1829 <input type='hidden' value="{$section}" name="wpSection" />
1830 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
1831 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
1832 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
1836 if ( !$this->checkUnicodeCompliantBrowser() )
1837 $wgOut->addHTML(Html
::hidden( 'safemode', '1' ));
1840 protected function showFormAfterText() {
1841 global $wgOut, $wgUser;
1843 * To make it harder for someone to slip a user a page
1844 * which submits an edit form to the wiki without their
1845 * knowledge, a random token is associated with the login
1846 * session. If it's not passed back with the submission,
1847 * we won't save the page, or render user JavaScript and
1850 * For anon editors, who may not have a session, we just
1851 * include the constant suffix to prevent editing from
1852 * broken text-mangling proxies.
1854 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->editToken() ) . "\n" );
1858 * Subpage overridable method for printing the form for page content editing
1859 * By default this simply outputs wpTextbox1
1860 * Subclasses can override this to provide a custom UI for editing;
1861 * be it a form, or simply wpTextbox1 with a modified content that will be
1862 * reverse modified when extracted from the post data.
1863 * Note that this is basically the inverse for importContentFormData
1865 protected function showContentForm() {
1866 $this->showTextbox1();
1870 * Method to output wpTextbox1
1871 * The $textoverride method can be used by subclasses overriding showContentForm
1872 * to pass back to this method.
1874 * @param $customAttribs An array of html attributes to use in the textarea
1875 * @param $textoverride String: optional text to override $this->textarea1 with
1877 protected function showTextbox1($customAttribs = null, $textoverride = null) {
1878 $classes = array(); // Textarea CSS
1879 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
1880 # Is the title semi-protected?
1881 if ( $this->mTitle
->isSemiProtected() ) {
1882 $classes[] = 'mw-textarea-sprotected';
1884 # Then it must be protected based on static groups (regular)
1885 $classes[] = 'mw-textarea-protected';
1887 # Is the title cascade-protected?
1888 if ( $this->mTitle
->isCascadeProtected() ) {
1889 $classes[] = 'mw-textarea-cprotected';
1892 $attribs = array( 'tabindex' => 1 );
1893 if ( is_array($customAttribs) )
1894 $attribs +
= $customAttribs;
1896 if ( $this->wasDeletedSinceLastEdit() )
1897 $attribs['type'] = 'hidden';
1898 if ( !empty( $classes ) ) {
1899 if ( isset($attribs['class']) )
1900 $classes[] = $attribs['class'];
1901 $attribs['class'] = implode( ' ', $classes );
1904 $this->showTextbox( isset($textoverride) ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
1907 protected function showTextbox2() {
1908 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
1911 protected function showTextbox( $content, $name, $customAttribs = array() ) {
1912 global $wgOut, $wgUser;
1914 $wikitext = $this->safeUnicodeOutput( $content );
1915 if ( strval($wikitext) !== '' ) {
1916 // Ensure there's a newline at the end, otherwise adding lines
1918 // But don't add a newline if the ext is empty, or Firefox in XHTML
1919 // mode will show an extra newline. A bit annoying.
1923 $attribs = $customAttribs +
array(
1926 'cols' => $wgUser->getIntOption( 'cols' ),
1927 'rows' => $wgUser->getIntOption( 'rows' ),
1928 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
1931 $pageLang = $this->mTitle
->getPageLanguage();
1932 $attribs['lang'] = $pageLang->getCode();
1933 $attribs['dir'] = $pageLang->getDir();
1935 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
1938 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1942 $classes[] = 'ontop';
1944 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1946 if ( $this->formtype
!= 'preview' )
1947 $attribs['style'] = 'display: none;';
1949 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
1951 if ( $this->formtype
== 'preview' ) {
1952 $this->showPreview( $previewOutput );
1955 $wgOut->addHTML( '</div>' );
1957 if ( $this->formtype
== 'diff') {
1963 * Append preview output to $wgOut.
1964 * Includes category rendering if this is a category page.
1966 * @param $text String: the HTML to be output for the preview.
1968 protected function showPreview( $text ) {
1970 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1971 $this->mArticle
->openShowCategory();
1973 # This hook seems slightly odd here, but makes things more
1974 # consistent for extensions.
1975 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1976 $wgOut->addHTML( $text );
1977 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1978 $this->mArticle
->closeShowCategory();
1983 * Give a chance for site and per-namespace customizations of
1984 * terms of service summary link that might exist separately
1985 * from the copyright notice.
1987 * This will display between the save button and the edit tools,
1988 * so should remain short!
1990 protected function showTosSummary() {
1991 $msg = 'editpage-tos-summary';
1992 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
1993 if( !wfMessage( $msg )->isDisabled() ) {
1995 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1996 $wgOut->addWikiMsg( $msg );
1997 $wgOut->addHTML( '</div>' );
2001 protected function showEditTools() {
2003 $wgOut->addHTML( '<div class="mw-editTools">' .
2004 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2008 protected function getCopywarn() {
2009 global $wgRightsText;
2010 if ( $wgRightsText ) {
2011 $copywarnMsg = array( 'copyrightwarning',
2012 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2015 $copywarnMsg = array( 'copyrightwarning2',
2016 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2018 // Allow for site and per-namespace customization of contribution/copyright notice.
2019 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2021 return "<div id=\"editpage-copywarn\">\n" .
2022 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
2025 protected function showStandardInputs( &$tabindex = 2 ) {
2027 $wgOut->addHTML( "<div class='editOptions'>\n" );
2029 if ( $this->section
!= 'new' ) {
2030 $this->showSummaryInput( false, $this->summary
);
2031 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2034 $checkboxes = $this->getCheckboxes( $tabindex,
2035 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2036 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2037 $wgOut->addHTML( "<div class='editButtons'>\n" );
2038 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2040 $cancel = $this->getCancelLink();
2041 if ( $cancel !== '' ) {
2042 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2044 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2045 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
2046 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
2047 htmlspecialchars( wfMsg( 'newwindow' ) );
2048 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2049 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2053 * Show an edit conflict. textbox1 is already shown in showEditForm().
2054 * If you want to use another entry point to this function, be careful.
2056 protected function showConflict() {
2058 $this->textbox2
= $this->textbox1
;
2059 $this->textbox1
= $this->getContent();
2060 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2061 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2063 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2064 $de->setText( $this->textbox2
, $this->textbox1
);
2065 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2067 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2068 $this->showTextbox2();
2072 protected function getLastDelete() {
2073 $dbr = wfGetDB( DB_SLAVE
);
2074 $data = $dbr->selectRow(
2075 array( 'logging', 'user' ),
2086 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2087 'log_title' => $this->mTitle
->getDBkey(),
2088 'log_type' => 'delete',
2089 'log_action' => 'delete',
2090 'user_id=log_user' ),
2092 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2094 // Quick paranoid permission checks...
2095 if( is_object( $data ) ) {
2096 if( $data->log_deleted
& LogPage
::DELETED_USER
)
2097 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2098 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2099 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2105 * Get the rendered text for previewing.
2108 function getPreviewText() {
2109 global $wgOut, $wgUser, $wgParser;
2111 wfProfileIn( __METHOD__
);
2113 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2114 if ( $this->mTokenOkExceptSuffix
) {
2115 $note = wfMsg( 'token_suffix_mismatch' );
2117 $note = wfMsg( 'session_fail_preview' );
2119 } elseif ( $this->incompleteForm
) {
2120 $note = wfMsg( 'edit_form_incomplete' );
2122 $note = wfMsg( 'previewnote' );
2125 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2126 $parserOptions->setEditSection( false );
2127 $parserOptions->setIsPreview( true );
2128 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2131 if ( $wgRawHtml && !$this->mTokenOk
) {
2132 // Could be an offsite preview attempt. This is very unsafe if
2133 // HTML is enabled, as it could be an attack.
2135 if ( $this->textbox1
!== '' ) {
2136 // Do not put big scary notice, if previewing the empty
2137 // string, which happens when you initially edit
2138 // a category page, due to automatic preview-on-open.
2139 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2140 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2142 wfProfileOut( __METHOD__
);
2146 # don't parse non-wikitext pages, show message about preview
2147 # 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?
2149 if ( $this->isCssJsSubpage ||
!$this->mTitle
->isWikitextPage() ) {
2150 if( $this->mTitle
->isCssJsSubpage() ) {
2152 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2158 # Used messages to make sure grep find them:
2159 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2161 if (preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2162 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2163 $class = "mw-code mw-css";
2164 } elseif (preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2165 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2166 $class = "mw-code mw-js";
2168 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2172 $parserOptions->setTidy( true );
2173 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2174 $previewHTML = $parserOutput->mText
;
2175 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2177 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2179 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2181 $toparse = $this->textbox1
;
2183 # If we're adding a comment, we need to show the
2184 # summary as the headline
2185 if ( $this->section
== "new" && $this->summary
!= "" ) {
2186 $toparse = "== {$this->summary} ==\n\n" . $toparse;
2189 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2191 $parserOptions->setTidy( true );
2192 $parserOptions->enableLimitReport();
2193 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ),
2194 $this->mTitle
, $parserOptions );
2196 $previewHTML = $parserOutput->getText();
2197 $this->mParserOutput
= $parserOutput;
2198 $wgOut->addParserOutputNoText( $parserOutput );
2200 if ( count( $parserOutput->getWarnings() ) ) {
2201 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2206 if( $this->isConflict
) {
2207 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2209 $conflict = '<hr />';
2212 $previewhead = "<div class='previewnote'>\n" .
2213 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2214 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2216 $pageLang = $this->mTitle
->getPageLanguage();
2217 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2218 'class' => 'mw-content-'.$pageLang->getDir() );
2219 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2221 wfProfileOut( __METHOD__
);
2222 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2228 function getTemplates() {
2229 if ( $this->preview ||
$this->section
!= '' ) {
2230 $templates = array();
2231 if ( !isset( $this->mParserOutput
) ) {
2234 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
2235 foreach( array_keys( $template ) as $dbk ) {
2236 $templates[] = Title
::makeTitle($ns, $dbk);
2241 return $this->mArticle
->getUsedTemplates();
2246 * Call the stock "user is blocked" page
2248 * @deprecated in 1.19; throw an exception directly instead
2250 function blockedPage() {
2253 throw new UserBlockedError( $wgUser->mBlock
);
2257 * Produce the stock "please login to edit pages" page
2259 * @deprecated in 1.19; throw an exception directly instead
2261 function userNotLoggedInPage() {
2262 throw new PermissionsError( 'edit' );
2266 * Show an error page saying to the user that he has insufficient permissions
2267 * to create a new page
2269 * @deprecated in 1.19; throw an exception directly instead
2271 function noCreatePermission() {
2272 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
2273 throw new PermissionsError( $permission );
2277 * Creates a basic error page which informs the user that
2278 * they have attempted to edit a nonexistent section.
2280 function noSuchSectionPage() {
2283 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
2285 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
2286 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2287 $wgOut->addHTML( $res );
2289 $wgOut->returnToMain( false, $this->mTitle
);
2293 * Produce the stock "your edit contains spam" page
2295 * @param $match Text which triggered one or more filters
2296 * @deprecated since 1.17 Use method spamPageWithContent() instead
2298 static function spamPage( $match = false ) {
2299 global $wgOut, $wgTitle;
2301 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2303 $wgOut->addHTML( '<div id="spamprotected">' );
2304 $wgOut->addWikiMsg( 'spamprotectiontext' );
2306 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2308 $wgOut->addHTML( '</div>' );
2310 $wgOut->returnToMain( false, $wgTitle );
2314 * Show "your edit contains spam" page with your diff and text
2316 * @param $match Text which triggered one or more filters
2318 public function spamPageWithContent( $match = false ) {
2320 $this->textbox2
= $this->textbox1
;
2322 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2324 $wgOut->addHTML( '<div id="spamprotected">' );
2325 $wgOut->addWikiMsg( 'spamprotectiontext' );
2327 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2329 $wgOut->addHTML( '</div>' );
2331 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2332 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2333 $de->setText( $this->getContent(), $this->textbox2
);
2334 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
2336 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2337 $this->showTextbox2();
2339 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
2347 * @parma $editText string
2351 function mergeChangesInto( &$editText ){
2352 wfProfileIn( __METHOD__
);
2354 $db = wfGetDB( DB_MASTER
);
2356 // This is the revision the editor started from
2357 $baseRevision = $this->getBaseRevision();
2358 if ( is_null( $baseRevision ) ) {
2359 wfProfileOut( __METHOD__
);
2362 $baseText = $baseRevision->getText();
2364 // The current state, we want to merge updates into it
2365 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2366 if ( is_null( $currentRevision ) ) {
2367 wfProfileOut( __METHOD__
);
2370 $currentText = $currentRevision->getText();
2373 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
2374 $editText = $result;
2375 wfProfileOut( __METHOD__
);
2378 wfProfileOut( __METHOD__
);
2384 * Check if the browser is on a blacklist of user-agents known to
2385 * mangle UTF-8 data on form submission. Returns true if Unicode
2386 * should make it through, false if it's known to be a problem.
2390 function checkUnicodeCompliantBrowser() {
2391 global $wgBrowserBlackList;
2392 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2393 // No User-Agent header sent? Trust it by default...
2396 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2397 foreach ( $wgBrowserBlackList as $browser ) {
2398 if ( preg_match($browser, $currentbrowser) ) {
2406 * Format an anchor fragment as it would appear for a given section name
2407 * @param $text String
2411 function sectionAnchor( $text ) {
2413 return $wgParser->guessSectionNameFromWikiText( $text );
2417 * Shows a bulletin board style toolbar for common editing functions.
2418 * It can be disabled in the user preferences.
2419 * The necessary JavaScript code can be found in skins/common/edit.js.
2423 static function getEditToolbar() {
2424 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2425 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2427 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2430 * $toolarray is an array of arrays each of which includes the
2431 * filename of the button image (without path), the opening
2432 * tag, the closing tag, optionally a sample text that is
2433 * inserted between the two when no selection is highlighted
2434 * and. The tip text is shown when the user moves the mouse
2437 * Also here: accesskeys (key), which are not used yet until
2438 * someone can figure out a way to make them work in
2439 * IE. However, we should make sure these keys are not defined
2444 'image' => $wgLang->getImageFile( 'button-bold' ),
2445 'id' => 'mw-editbutton-bold',
2447 'close' => '\'\'\'',
2448 'sample' => wfMsg( 'bold_sample' ),
2449 'tip' => wfMsg( 'bold_tip' ),
2453 'image' => $wgLang->getImageFile( 'button-italic' ),
2454 'id' => 'mw-editbutton-italic',
2457 'sample' => wfMsg( 'italic_sample' ),
2458 'tip' => wfMsg( 'italic_tip' ),
2462 'image' => $wgLang->getImageFile( 'button-link' ),
2463 'id' => 'mw-editbutton-link',
2466 'sample' => wfMsg( 'link_sample' ),
2467 'tip' => wfMsg( 'link_tip' ),
2471 'image' => $wgLang->getImageFile( 'button-extlink' ),
2472 'id' => 'mw-editbutton-extlink',
2475 'sample' => wfMsg( 'extlink_sample' ),
2476 'tip' => wfMsg( 'extlink_tip' ),
2480 'image' => $wgLang->getImageFile( 'button-headline' ),
2481 'id' => 'mw-editbutton-headline',
2484 'sample' => wfMsg( 'headline_sample' ),
2485 'tip' => wfMsg( 'headline_tip' ),
2488 $imagesAvailable ?
array(
2489 'image' => $wgLang->getImageFile( 'button-image' ),
2490 'id' => 'mw-editbutton-image',
2491 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2493 'sample' => wfMsg( 'image_sample' ),
2494 'tip' => wfMsg( 'image_tip' ),
2497 $imagesAvailable ?
array(
2498 'image' => $wgLang->getImageFile( 'button-media' ),
2499 'id' => 'mw-editbutton-media',
2500 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2502 'sample' => wfMsg( 'media_sample' ),
2503 'tip' => wfMsg( 'media_tip' ),
2507 'image' => $wgLang->getImageFile( 'button-math' ),
2508 'id' => 'mw-editbutton-math',
2510 'close' => "</math>",
2511 'sample' => wfMsg( 'math_sample' ),
2512 'tip' => wfMsg( 'math_tip' ),
2516 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2517 'id' => 'mw-editbutton-nowiki',
2518 'open' => "<nowiki>",
2519 'close' => "</nowiki>",
2520 'sample' => wfMsg( 'nowiki_sample' ),
2521 'tip' => wfMsg( 'nowiki_tip' ),
2525 'image' => $wgLang->getImageFile( 'button-sig' ),
2526 'id' => 'mw-editbutton-signature',
2530 'tip' => wfMsg( 'sig_tip' ),
2534 'image' => $wgLang->getImageFile( 'button-hr' ),
2535 'id' => 'mw-editbutton-hr',
2536 'open' => "\n----\n",
2539 'tip' => wfMsg( 'hr_tip' ),
2545 foreach ( $toolarray as $tool ) {
2551 $image = $wgStylePath . '/common/images/' . $tool['image'],
2552 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2553 // Older browsers show a "speedtip" type message only for ALT.
2554 // Ideally these should be different, realistically they
2555 // probably don't need to be.
2556 $tip = $tool['tip'],
2557 $open = $tool['open'],
2558 $close = $tool['close'],
2559 $sample = $tool['sample'],
2560 $cssId = $tool['id'],
2563 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2565 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2567 $toolbar = '<div id="toolbar"></div>';
2569 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2575 * Returns an array of html code of the following checkboxes:
2578 * @param $tabindex Current tabindex
2579 * @param $checked Array of checkbox => bool, where bool indicates the checked
2580 * status of the checkbox
2584 public function getCheckboxes( &$tabindex, $checked ) {
2587 $checkboxes = array();
2589 // don't show the minor edit checkbox if it's a new page or section
2590 if ( !$this->isNew
) {
2591 $checkboxes['minor'] = '';
2592 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2593 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2595 'tabindex' => ++
$tabindex,
2596 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2597 'id' => 'wpMinoredit',
2599 $checkboxes['minor'] =
2600 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2601 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2602 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2603 ">{$minorLabel}</label>";
2607 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2608 $checkboxes['watch'] = '';
2609 if ( $wgUser->isLoggedIn() ) {
2611 'tabindex' => ++
$tabindex,
2612 'accesskey' => wfMsg( 'accesskey-watch' ),
2613 'id' => 'wpWatchthis',
2615 $checkboxes['watch'] =
2616 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2617 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2618 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2619 ">{$watchLabel}</label>";
2621 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2626 * Returns an array of html code of the following buttons:
2627 * save, diff, preview and live
2629 * @param $tabindex Current tabindex
2633 public function getEditButtons( &$tabindex ) {
2640 'tabindex' => ++
$tabindex,
2641 'value' => wfMsg( 'savearticle' ),
2642 'accesskey' => wfMsg( 'accesskey-save' ),
2643 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2645 $buttons['save'] = Xml
::element('input', $temp, '');
2647 ++
$tabindex; // use the same for preview and live preview
2649 'id' => 'wpPreview',
2650 'name' => 'wpPreview',
2652 'tabindex' => $tabindex,
2653 'value' => wfMsg( 'showpreview' ),
2654 'accesskey' => wfMsg( 'accesskey-preview' ),
2655 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2657 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
2658 $buttons['live'] = '';
2664 'tabindex' => ++
$tabindex,
2665 'value' => wfMsg( 'showdiff' ),
2666 'accesskey' => wfMsg( 'accesskey-diff' ),
2667 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2669 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
2671 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2676 * Output preview text only. This can be sucked into the edit page
2677 * via JavaScript, and saves the server time rendering the skin as
2678 * well as theoretically being more robust on the client (doesn't
2679 * disturb the edit box's undo history, won't eat your text on
2682 * @todo This doesn't include category or interlanguage links.
2683 * Would need to enhance it a bit, <s>maybe wrap them in XML
2684 * or something...</s> that might also require more skin
2685 * initialization, so check whether that's a problem.
2687 function livePreview() {
2690 header( 'Content-type: text/xml; charset=utf-8' );
2691 header( 'Cache-control: no-cache' );
2693 $previewText = $this->getPreviewText();
2694 #$categories = $skin->getCategoryLinks();
2697 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2698 Xml
::tags( 'livepreview', null,
2699 Xml
::element( 'preview', null, $previewText )
2700 #. Xml::element( 'category', null, $categories )
2708 public function getCancelLink() {
2709 $cancelParams = array();
2710 if ( !$this->isConflict
&& $this->mArticle
->getOldID() > 0 ) {
2711 $cancelParams['oldid'] = $this->mArticle
->getOldID();
2714 return Linker
::linkKnown(
2715 $this->getContextTitle(),
2716 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2717 array( 'id' => 'mw-editform-cancel' ),
2723 * Get a diff between the current contents of the edit box and the
2724 * version of the page we're editing from.
2726 * If this is a section edit, we'll replace the section as for final
2727 * save and then make a comparison.
2729 function showDiff() {
2730 $oldtext = $this->mArticle
->fetchContent();
2731 $newtext = $this->mArticle
->replaceSection(
2732 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2734 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2736 $newtext = $this->mArticle
->preSaveTransform( $newtext );
2737 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2738 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2739 if ( $oldtext !== false ||
$newtext != '' ) {
2740 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2741 $de->setText( $oldtext, $newtext );
2742 $difftext = $de->getDiff( $oldtitle, $newtitle );
2743 $de->showDiffStyle();
2749 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2753 * Filter an input field through a Unicode de-armoring process if it
2754 * came from an old browser with known broken Unicode editing issues.
2756 * @param $request WebRequest
2757 * @param $field String
2761 function safeUnicodeInput( $request, $field ) {
2762 $text = rtrim( $request->getText( $field ) );
2763 return $request->getBool( 'safemode' )
2764 ?
$this->unmakesafe( $text )
2769 * @param $request WebRequest
2770 * @param $text string
2773 function safeUnicodeText( $request, $text ) {
2774 $text = rtrim( $text );
2775 return $request->getBool( 'safemode' )
2776 ?
$this->unmakesafe( $text )
2781 * Filter an output field through a Unicode armoring process if it is
2782 * going to an old browser with known broken Unicode editing issues.
2784 * @param $text String
2788 function safeUnicodeOutput( $text ) {
2790 $codedText = $wgContLang->recodeForEdit( $text );
2791 return $this->checkUnicodeCompliantBrowser()
2793 : $this->makesafe( $codedText );
2797 * A number of web browsers are known to corrupt non-ASCII characters
2798 * in a UTF-8 text editing environment. To protect against this,
2799 * detected browsers will be served an armored version of the text,
2800 * with non-ASCII chars converted to numeric HTML character references.
2802 * Preexisting such character references will have a 0 added to them
2803 * to ensure that round-trips do not alter the original data.
2805 * @param $invalue String
2809 function makesafe( $invalue ) {
2810 // Armor existing references for reversability.
2811 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2816 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2817 $bytevalue = ord( $invalue[$i] );
2818 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2819 $result .= chr( $bytevalue );
2821 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2822 $working = $working << 6;
2823 $working +
= ($bytevalue & 0x3F);
2825 if ( $bytesleft <= 0 ) {
2826 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2828 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2829 $working = $bytevalue & 0x1F;
2831 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2832 $working = $bytevalue & 0x0F;
2834 } else { //1111 0xxx
2835 $working = $bytevalue & 0x07;
2843 * Reverse the previously applied transliteration of non-ASCII characters
2844 * back to UTF-8. Used to protect data from corruption by broken web browsers
2845 * as listed in $wgBrowserBlackList.
2847 * @param $invalue String
2851 function unmakesafe( $invalue ) {
2853 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2854 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+
3] != '0' ) ) {
2858 $hexstring .= $invalue[$i];
2860 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
2862 // Do some sanity checks. These aren't needed for reversability,
2863 // but should help keep the breakage down if the editor
2864 // breaks one of the entities whilst editing.
2865 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2866 $codepoint = hexdec($hexstring);
2867 $result .= codepointToUtf8( $codepoint );
2869 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2872 $result .= substr( $invalue, $i, 1 );
2875 // reverse the transform that we made for reversability reasons.
2876 return strtr( $result, array( "�" => "&#x" ) );
2880 * Attempt submission
2881 * @return bool false if output is done, true if the rest of the form should be displayed
2883 function attemptSave() {
2884 global $wgUser, $wgOut;
2886 $resultDetails = false;
2887 # Allow bots to exempt some edits from bot flagging
2888 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
2889 $status = $this->internalAttemptSave( $resultDetails, $bot );
2890 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
2892 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
2893 $this->didSave
= true;
2896 switch ( $status->value
) {
2897 case self
::AS_HOOK_ERROR_EXPECTED
:
2898 case self
::AS_CONTENT_TOO_BIG
:
2899 case self
::AS_ARTICLE_WAS_DELETED
:
2900 case self
::AS_CONFLICT_DETECTED
:
2901 case self
::AS_SUMMARY_NEEDED
:
2902 case self
::AS_TEXTBOX_EMPTY
:
2903 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
2907 case self
::AS_HOOK_ERROR
:
2908 case self
::AS_FILTERING
:
2911 case self
::AS_SUCCESS_NEW_ARTICLE
:
2912 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
2913 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) );
2916 case self
::AS_SUCCESS_UPDATE
:
2918 $sectionanchor = $resultDetails['sectionanchor'];
2920 // Give extensions a chance to modify URL query on update
2921 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
2923 if ( $resultDetails['redirect'] ) {
2924 if ( $extraQuery == '' ) {
2925 $extraQuery = 'redirect=no';
2927 $extraQuery = 'redirect=no&' . $extraQuery;
2930 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
2933 case self
::AS_BLANK_ARTICLE
:
2934 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
2937 case self
::AS_SPAM_ERROR
:
2938 $this->spamPageWithContent( $resultDetails['spam'] );
2941 case self
::AS_BLOCKED_PAGE_FOR_USER
:
2942 throw new UserBlockedError( $wgUser->mBlock
);
2944 case self
::AS_IMAGE_REDIRECT_ANON
:
2945 case self
::AS_IMAGE_REDIRECT_LOGGED
:
2946 throw new PermissionsError( 'upload' );
2948 case self
::AS_READ_ONLY_PAGE_ANON
:
2949 case self
::AS_READ_ONLY_PAGE_LOGGED
:
2950 throw new PermissionsError( 'edit' );
2952 case self
::AS_READ_ONLY_PAGE
:
2953 throw new ReadOnlyError
;
2955 case self
::AS_RATE_LIMITED
:
2956 throw new ThrottledError();
2958 case self
::AS_NO_CREATE_PERMISSION
:
2959 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
2960 throw new PermissionsError( $permission );
2969 function getBaseRevision() {
2970 if ( !$this->mBaseRevision
) {
2971 $db = wfGetDB( DB_MASTER
);
2972 $baseRevision = Revision
::loadFromTimestamp(
2973 $db, $this->mTitle
, $this->edittime
);
2974 return $this->mBaseRevision
= $baseRevision;
2976 return $this->mBaseRevision
;