3 * Page edition user interface.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * The edit page/HTML interface (split from Article)
25 * The actual database and text munging is still in Article,
26 * but it should get easier to call those from alternate
29 * EditPage cares about two distinct titles:
30 * $this->mContextTitle is the page that forms submit to, links point to,
31 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
32 * page in the database that is actually being edited. These are
33 * usually the same, but they are now allowed to be different.
35 * Surgeon General's Warning: prolonged exposure to this class is known to cause
36 * headaches, which may be fatal.
41 * Status: Article successfully updated
43 const AS_SUCCESS_UPDATE
= 200;
46 * Status: Article successfully created
48 const AS_SUCCESS_NEW_ARTICLE
= 201;
51 * Status: Article update aborted by a hook function
53 const AS_HOOK_ERROR
= 210;
56 * Status: A hook function returned an error
58 const AS_HOOK_ERROR_EXPECTED
= 212;
61 * Status: User is blocked from editting this page
63 const AS_BLOCKED_PAGE_FOR_USER
= 215;
66 * Status: Content too big (> $wgMaxArticleSize)
68 const AS_CONTENT_TOO_BIG
= 216;
71 * Status: User cannot edit? (not used)
73 const AS_USER_CANNOT_EDIT
= 217;
76 * Status: this anonymous user is not allowed to edit this page
78 const AS_READ_ONLY_PAGE_ANON
= 218;
81 * Status: this logged in user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_LOGGED
= 219;
86 * Status: wiki is in readonly mode (wfReadOnly() == true)
88 const AS_READ_ONLY_PAGE
= 220;
91 * Status: rate limiter for action 'edit' was tripped
93 const AS_RATE_LIMITED
= 221;
96 * Status: article was deleted while editting and param wpRecreate == false or form
99 const AS_ARTICLE_WAS_DELETED
= 222;
102 * Status: user tried to create this page, but is not allowed to do that
103 * ( Title->usercan('create') == false )
105 const AS_NO_CREATE_PERMISSION
= 223;
108 * Status: user tried to create a blank page
110 const AS_BLANK_ARTICLE
= 224;
113 * Status: (non-resolvable) edit conflict
115 const AS_CONFLICT_DETECTED
= 225;
118 * Status: no edit summary given and the user has forceeditsummary set and the user is not
119 * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
121 const AS_SUMMARY_NEEDED
= 226;
124 * Status: user tried to create a new section without content
126 const AS_TEXTBOX_EMPTY
= 228;
129 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
131 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
139 * Status: WikiPage::doEdit() was unsuccessfull
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
146 const AS_SPAM_ERROR
= 232;
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
151 const AS_IMAGE_REDIRECT_ANON
= 233;
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
156 const AS_IMAGE_REDIRECT_LOGGED
= 234;
159 * HTML id and name for the beginning of the edit form.
161 const EDITFORM_ID
= 'editform';
172 private $mContextTitle = null;
173 var $action = 'submit';
174 var $isConflict = false;
175 var $isCssJsSubpage = false;
176 var $isCssSubpage = false;
177 var $isJsSubpage = false;
178 var $isWrongCaseCssJsPage = false;
179 var $isNew = false; // new page or new section
180 var $deletedSinceEdit;
184 var $mTokenOk = false;
185 var $mTokenOkExceptSuffix = false;
186 var $mTriedSave = false;
187 var $incompleteForm = false;
189 var $kblength = false;
190 var $missingComment = false;
191 var $missingSummary = false;
192 var $allowBlankSummary = false;
195 #var $mPreviewTemplates;
203 * Has a summary been preset using GET parameter &summary= ?
206 var $hasPresetSummary = false;
208 var $mBaseRevision = false;
209 var $mShowSummaryField = true;
212 var $save = false, $preview = false, $diff = false;
213 var $minoredit = false, $watchthis = false, $recreate = false;
214 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
215 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
216 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
218 # Placeholders for text injection by hooks (must be HTML)
219 # extensions should take care to _append_ to the present value
220 public $editFormPageTop = ''; // Before even the preview
221 public $editFormTextTop = '';
222 public $editFormTextBeforeContent = '';
223 public $editFormTextAfterWarn = '';
224 public $editFormTextAfterTools = '';
225 public $editFormTextBottom = '';
226 public $editFormTextAfterContent = '';
227 public $previewTextAfterContent = '';
228 public $mPreloadText = '';
230 /* $didSave should be set to true whenever an article was succesfully altered. */
231 public $didSave = false;
232 public $undidRev = 0;
234 public $suppressIntro = false;
237 * @param $article Article
239 public function __construct( Article
$article ) {
240 $this->mArticle
= $article;
241 $this->mTitle
= $article->getTitle();
247 public function getArticle() {
248 return $this->mArticle
;
255 public function getTitle() {
256 return $this->mTitle
;
260 * Set the context Title object
262 * @param $title Title object or null
264 public function setContextTitle( $title ) {
265 $this->mContextTitle
= $title;
269 * Get the context title object.
270 * If not set, $wgTitle will be returned. This behavior might changed in
271 * the future to return $this->mTitle instead.
273 * @return Title object
275 public function getContextTitle() {
276 if ( is_null( $this->mContextTitle
) ) {
280 return $this->mContextTitle
;
289 * This is the function that gets called for "action=edit". It
290 * sets up various member variables, then passes execution to
291 * another function, usually showEditForm()
293 * The edit form is self-submitting, so that when things like
294 * preview and edit conflicts occur, we get the same form back
295 * with the extra stuff added. Only when the final submission
296 * is made and all is well do we actually save and redirect to
297 * the newly-edited page.
300 global $wgOut, $wgRequest, $wgUser;
301 // Allow extensions to modify/prevent this form or submission
302 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
306 wfProfileIn( __METHOD__
);
307 wfDebug( __METHOD__
. ": enter\n" );
309 // If they used redlink=1 and the page exists, redirect to the main article
310 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
311 $wgOut->redirect( $this->mTitle
->getFullURL() );
312 wfProfileOut( __METHOD__
);
316 $this->importFormData( $wgRequest );
317 $this->firsttime
= false;
320 $this->livePreview();
321 wfProfileOut( __METHOD__
);
325 if ( wfReadOnly() && $this->save
) {
328 $this->preview
= true;
332 $this->formtype
= 'save';
333 } elseif ( $this->preview
) {
334 $this->formtype
= 'preview';
335 } elseif ( $this->diff
) {
336 $this->formtype
= 'diff';
337 } else { # First time through
338 $this->firsttime
= true;
339 if ( $this->previewOnOpen() ) {
340 $this->formtype
= 'preview';
342 $this->formtype
= 'initial';
346 $permErrors = $this->getEditPermissionErrors();
348 wfDebug( __METHOD__
. ": User can't edit\n" );
349 // Auto-block user's IP if the account was "hard" blocked
350 $wgUser->spreadAnyEditBlock();
352 $this->displayPermissionsError( $permErrors );
354 wfProfileOut( __METHOD__
);
358 wfProfileIn( __METHOD__
. "-business-end" );
360 $this->isConflict
= false;
361 // css / js subpages of user pages get a special treatment
362 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
363 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
364 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
365 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
366 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
368 # Show applicable editing introductions
369 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
373 # Attempt submission here. This will check for edit conflicts,
374 # and redundantly check for locked database, blocked IPs, etc.
375 # that edit() already checked just in case someone tries to sneak
376 # in the back door with a hand-edited submission URL.
378 if ( 'save' == $this->formtype
) {
379 if ( !$this->attemptSave() ) {
380 wfProfileOut( __METHOD__
. "-business-end" );
381 wfProfileOut( __METHOD__
);
386 # First time through: get contents, set time for conflict
388 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
389 if ( $this->initialiseForm() === false ) {
390 $this->noSuchSectionPage();
391 wfProfileOut( __METHOD__
. "-business-end" );
392 wfProfileOut( __METHOD__
);
396 if ( !$this->mTitle
->getArticleID() ) {
397 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
400 wfRunHooks( 'EditFormInitialText', array( $this ) );
405 $this->showEditForm();
406 wfProfileOut( __METHOD__
. "-business-end" );
407 wfProfileOut( __METHOD__
);
413 protected function getEditPermissionErrors() {
415 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
416 # Can this title be created?
417 if ( !$this->mTitle
->exists() ) {
418 $permErrors = array_merge( $permErrors,
419 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
421 # Ignore some permissions errors when a user is just previewing/viewing diffs
423 foreach ( $permErrors as $error ) {
424 if ( ( $this->preview ||
$this->diff
) &&
425 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
430 $permErrors = wfArrayDiff2( $permErrors, $remove );
435 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
436 * but with the following differences:
437 * - If redlink=1, the user will be redirected to the page
438 * - If there is content to display or the error occurs while either saving,
439 * previewing or showing the difference, it will be a
440 * "View source for ..." page displaying the source code after the error message.
443 * @param $permErrors Array of permissions errors, as returned by
444 * Title::getUserPermissionsErrors().
446 protected function displayPermissionsError( array $permErrors ) {
447 global $wgRequest, $wgOut;
449 if ( $wgRequest->getBool( 'redlink' ) ) {
450 // The edit page was reached via a red link.
451 // Redirect to the article page and let them click the edit tab if
452 // they really want a permission error.
453 $wgOut->redirect( $this->mTitle
->getFullUrl() );
457 $content = $this->getContent();
459 # Use the normal message if there's nothing to display
460 if ( $this->firsttime
&& $content === '' ) {
461 $action = $this->mTitle
->exists() ?
'edit' :
462 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
463 throw new PermissionsError( $action, $permErrors );
466 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
467 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
468 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
469 $wgOut->addHTML( "<hr />\n" );
471 # If the user made changes, preserve them when showing the markup
472 # (This happens when a user is blocked during edit, for instance)
473 if ( !$this->firsttime
) {
474 $content = $this->textbox1
;
475 $wgOut->addWikiMsg( 'viewyourtext' );
477 $wgOut->addWikiMsg( 'viewsourcetext' );
480 $this->showTextbox( $content, 'wpTextbox1', array( 'readonly' ) );
482 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
483 Linker
::formatTemplates( $this->getTemplates() ) ) );
485 if ( $this->mTitle
->exists() ) {
486 $wgOut->returnToMain( null, $this->mTitle
);
491 * Show a read-only error
492 * Parameters are the same as OutputPage:readOnlyPage()
493 * Redirect to the article page if redlink=1
494 * @deprecated in 1.19; use displayPermissionsError() instead
496 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
497 wfDeprecated( __METHOD__
, '1.19' );
499 global $wgRequest, $wgOut;
500 if ( $wgRequest->getBool( 'redlink' ) ) {
501 // The edit page was reached via a red link.
502 // Redirect to the article page and let them click the edit tab if
503 // they really want a permission error.
504 $wgOut->redirect( $this->mTitle
->getFullUrl() );
506 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
511 * Should we show a preview when the edit form is first shown?
515 protected function previewOnOpen() {
516 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
517 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
518 // Explicit override from request
520 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
521 // Explicit override from request
523 } elseif ( $this->section
== 'new' ) {
524 // Nothing *to* preview for new sections
526 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
527 // Standard preference behaviour
529 } elseif ( !$this->mTitle
->exists() &&
530 isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] ) &&
531 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
533 // Categories are special
541 * Checks whether the user entered a skin name in uppercase,
542 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
546 protected function isWrongCaseCssJsPage() {
547 if ( $this->mTitle
->isCssJsSubpage() ) {
548 $name = $this->mTitle
->getSkinFromCssJsSubpage();
549 $skins = array_merge(
550 array_keys( Skin
::getSkinNames() ),
553 return !in_array( $name, $skins )
554 && in_array( strtolower( $name ), $skins );
561 * Does this EditPage class support section editing?
562 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
566 protected function isSectionEditSupported() {
571 * This function collects the form data and uses it to populate various member variables.
572 * @param $request WebRequest
574 function importFormData( &$request ) {
575 global $wgLang, $wgUser;
577 wfProfileIn( __METHOD__
);
579 # Section edit can come from either the form or a link
580 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
582 if ( $request->wasPosted() ) {
583 # These fields need to be checked for encoding.
584 # Also remove trailing whitespace, but don't remove _initial_
585 # whitespace from the text boxes. This may be significant formatting.
586 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
587 if ( !$request->getCheck( 'wpTextbox2' ) ) {
588 // Skip this if wpTextbox2 has input, it indicates that we came
589 // from a conflict page with raw page text, not a custom form
590 // modified by subclasses
591 wfProfileIn( get_class( $this ) . "::importContentFormData" );
592 $textbox1 = $this->importContentFormData( $request );
593 if ( isset( $textbox1 ) ) {
594 $this->textbox1
= $textbox1;
597 wfProfileOut( get_class( $this ) . "::importContentFormData" );
600 # Truncate for whole multibyte characters
601 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 255 );
603 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
604 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
606 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
608 # Treat sectiontitle the same way as summary.
609 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
610 # currently doing double duty as both edit summary and section title. Right now this
611 # is just to allow API edits to work around this limitation, but this should be
612 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
613 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
614 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
616 $this->edittime
= $request->getVal( 'wpEdittime' );
617 $this->starttime
= $request->getVal( 'wpStarttime' );
619 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
621 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
622 // wpTextbox1 field is missing, possibly due to being "too big"
623 // according to some filter rules such as Suhosin's setting for
624 // suhosin.request.max_value_length (d'oh)
625 $this->incompleteForm
= true;
627 // edittime should be one of our last fields; if it's missing,
628 // the submission probably broke somewhere in the middle.
629 $this->incompleteForm
= is_null( $this->edittime
);
631 if ( $this->incompleteForm
) {
632 # If the form is incomplete, force to preview.
633 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
634 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
635 $this->preview
= true;
637 /* Fallback for live preview */
638 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
639 $this->diff
= $request->getCheck( 'wpDiff' );
641 // Remember whether a save was requested, so we can indicate
642 // if we forced preview due to session failure.
643 $this->mTriedSave
= !$this->preview
;
645 if ( $this->tokenOk( $request ) ) {
646 # Some browsers will not report any submit button
647 # if the user hits enter in the comment box.
648 # The unmarked state will be assumed to be a save,
649 # if the form seems otherwise complete.
650 wfDebug( __METHOD__
. ": Passed token check.\n" );
651 } elseif ( $this->diff
) {
652 # Failed token check, but only requested "Show Changes".
653 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
655 # Page might be a hack attempt posted from
656 # an external site. Preview instead of saving.
657 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
658 $this->preview
= true;
661 $this->save
= !$this->preview
&& !$this->diff
;
662 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
663 $this->edittime
= null;
666 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
667 $this->starttime
= null;
670 $this->recreate
= $request->getCheck( 'wpRecreate' );
672 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
673 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
675 # Don't force edit summaries when a user is editing their own user or talk page
676 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
677 $this->mTitle
->getText() == $wgUser->getName() )
679 $this->allowBlankSummary
= true;
681 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary' );
684 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
686 # Not a posted form? Start with nothing.
687 wfDebug( __METHOD__
. ": Not a posted form.\n" );
688 $this->textbox1
= '';
690 $this->sectiontitle
= '';
691 $this->edittime
= '';
692 $this->starttime
= wfTimestampNow();
694 $this->preview
= false;
697 $this->minoredit
= false;
698 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
699 $this->recreate
= false;
701 // When creating a new section, we can preload a section title by passing it as the
702 // preloadtitle parameter in the URL (Bug 13100)
703 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
704 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
705 // Once wpSummary isn't being use for setting section titles, we should delete this.
706 $this->summary
= $request->getVal( 'preloadtitle' );
708 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
709 $this->summary
= $request->getText( 'summary' );
710 if ( $this->summary
!== '' ) {
711 $this->hasPresetSummary
= true;
715 if ( $request->getVal( 'minor' ) ) {
716 $this->minoredit
= true;
720 $this->bot
= $request->getBool( 'bot', true );
721 $this->nosummary
= $request->getBool( 'nosummary' );
723 $this->oldid
= $request->getInt( 'oldid' );
725 $this->live
= $request->getCheck( 'live' );
726 $this->editintro
= $request->getText( 'editintro',
727 // Custom edit intro for new sections
728 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
730 // Allow extensions to modify form data
731 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
733 wfProfileOut( __METHOD__
);
737 * Subpage overridable method for extracting the page content data from the
738 * posted form to be placed in $this->textbox1, if using customized input
739 * this method should be overrided and return the page text that will be used
740 * for saving, preview parsing and so on...
742 * @param $request WebRequest
744 protected function importContentFormData( &$request ) {
745 return; // Don't do anything, EditPage already extracted wpTextbox1
749 * Initialise form fields in the object
750 * Called on the first invocation, e.g. when a user clicks an edit link
751 * @return bool -- if the requested section is valid
753 function initialiseForm() {
755 $this->edittime
= $this->mArticle
->getTimestamp();
756 $this->textbox1
= $this->getContent( false );
757 // activate checkboxes if user wants them to be always active
758 # Sort out the "watch" checkbox
759 if ( $wgUser->getOption( 'watchdefault' ) ) {
761 $this->watchthis
= true;
762 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
764 $this->watchthis
= true;
765 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
767 $this->watchthis
= true;
769 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
770 $this->minoredit
= true;
772 if ( $this->textbox1
=== false ) {
780 * Fetch initial editing page content.
782 * @param $def_text string
783 * @return mixed string on success, $def_text for invalid sections
786 function getContent( $def_text = '' ) {
787 global $wgOut, $wgRequest, $wgParser;
789 wfProfileIn( __METHOD__
);
793 // For message page not locally set, use the i18n message.
794 // For other non-existent articles, use preload text if any.
795 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
796 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
797 # If this is a system message, get the default text.
798 $text = $this->mTitle
->getDefaultMessageText();
800 if ( $text === false ) {
801 # If requested, preload some text.
802 $preload = $wgRequest->getVal( 'preload',
803 // Custom preload text for new sections
804 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
805 $text = $this->getPreloadedText( $preload );
807 // For existing pages, get text based on "undo" or section parameters.
809 if ( $this->section
!= '' ) {
810 // Get section edit text (returns $def_text for invalid sections)
811 $text = $wgParser->getSection( $this->getOriginalContent(), $this->section
, $def_text );
813 $undoafter = $wgRequest->getInt( 'undoafter' );
814 $undo = $wgRequest->getInt( 'undo' );
816 if ( $undo > 0 && $undoafter > 0 ) {
817 if ( $undo < $undoafter ) {
818 # If they got undoafter and undo round the wrong way, switch them
819 list( $undo, $undoafter ) = array( $undoafter, $undo );
822 $undorev = Revision
::newFromId( $undo );
823 $oldrev = Revision
::newFromId( $undoafter );
825 # Sanity check, make sure it's the right page,
826 # the revisions exist and they were not deleted.
827 # Otherwise, $text will be left as-is.
828 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
829 $undorev->getPage() == $oldrev->getPage() &&
830 $undorev->getPage() == $this->mTitle
->getArticleID() &&
831 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
832 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
834 $text = $this->mArticle
->getUndoText( $undorev, $oldrev );
835 if ( $text === false ) {
836 # Warn the user that something went wrong
837 $undoMsg = 'failure';
839 # Inform the user of our success and set an automatic edit summary
840 $undoMsg = 'success';
842 # If we just undid one rev, use an autosummary
843 $firstrev = $oldrev->getNext();
844 if ( $firstrev && $firstrev->getId() == $undo ) {
845 $undoSummary = wfMessage( 'undo-summary', $undo, $undorev->getUserText() )->inContentLanguage()->text();
846 if ( $this->summary
=== '' ) {
847 $this->summary
= $undoSummary;
849 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
850 ->inContentLanguage()->text() . $this->summary
;
852 $this->undidRev
= $undo;
854 $this->formtype
= 'diff';
857 // Failed basic sanity checks.
858 // Older revisions may have been removed since the link
859 // was created, or we may simply have got bogus input.
863 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
864 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
865 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
868 if ( $text === false ) {
869 $text = $this->getOriginalContent();
874 wfProfileOut( __METHOD__
);
879 * Get the content of the wanted revision, without section extraction.
881 * The result of this function can be used to compare user's input with
882 * section replaced in its context (using WikiPage::replaceSection())
883 * to the original text of the edit.
885 * This difers from Article::getContent() that when a missing revision is
886 * encountered the result will be an empty string and not the
887 * 'missing-revision' message.
892 private function getOriginalContent() {
893 if ( $this->section
== 'new' ) {
894 return $this->getCurrentText();
896 $revision = $this->mArticle
->getRevisionFetched();
897 if ( $revision === null ) {
900 return $this->mArticle
->getContent();
904 * Get the actual text of the page. This is basically similar to
905 * WikiPage::getRawText() except that when the page doesn't exist an empty
906 * string is returned instead of false.
911 private function getCurrentText() {
912 $text = $this->mArticle
->getRawText();
913 if ( $text === false ) {
921 * Use this method before edit() to preload some text into the edit box
923 * @param $text string
925 public function setPreloadedText( $text ) {
926 $this->mPreloadText
= $text;
930 * Get the contents to be preloaded into the box, either set by
931 * an earlier setPreloadText() or by loading the given page.
933 * @param $preload String: representing the title to preload from.
936 protected function getPreloadedText( $preload ) {
937 global $wgUser, $wgParser;
939 if ( !empty( $this->mPreloadText
) ) {
940 return $this->mPreloadText
;
943 if ( $preload === '' ) {
947 $title = Title
::newFromText( $preload );
948 # Check for existence to avoid getting MediaWiki:Noarticletext
949 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
953 $page = WikiPage
::factory( $title );
954 if ( $page->isRedirect() ) {
955 $title = $page->getRedirectTarget();
957 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
960 $page = WikiPage
::factory( $title );
963 $parserOptions = ParserOptions
::newFromUser( $wgUser );
964 return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
968 * Make sure the form isn't faking a user's credentials.
970 * @param $request WebRequest
974 function tokenOk( &$request ) {
976 $token = $request->getVal( 'wpEditToken' );
977 $this->mTokenOk
= $wgUser->matchEditToken( $token );
978 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
979 return $this->mTokenOk
;
984 * @return bool false if output is done, true if the rest of the form should be displayed
986 function attemptSave() {
987 global $wgUser, $wgOut;
989 $resultDetails = false;
990 # Allow bots to exempt some edits from bot flagging
991 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
992 $status = $this->internalAttemptSave( $resultDetails, $bot );
993 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
994 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
995 $this->didSave
= true;
998 switch ( $status->value
) {
999 case self
::AS_HOOK_ERROR_EXPECTED
:
1000 case self
::AS_CONTENT_TOO_BIG
:
1001 case self
::AS_ARTICLE_WAS_DELETED
:
1002 case self
::AS_CONFLICT_DETECTED
:
1003 case self
::AS_SUMMARY_NEEDED
:
1004 case self
::AS_TEXTBOX_EMPTY
:
1005 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1009 case self
::AS_HOOK_ERROR
:
1012 case self
::AS_SUCCESS_NEW_ARTICLE
:
1013 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1014 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1015 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1018 case self
::AS_SUCCESS_UPDATE
:
1020 $sectionanchor = $resultDetails['sectionanchor'];
1022 // Give extensions a chance to modify URL query on update
1023 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1025 if ( $resultDetails['redirect'] ) {
1026 if ( $extraQuery == '' ) {
1027 $extraQuery = 'redirect=no';
1029 $extraQuery = 'redirect=no&' . $extraQuery;
1032 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1035 case self
::AS_BLANK_ARTICLE
:
1036 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1039 case self
::AS_SPAM_ERROR
:
1040 $this->spamPageWithContent( $resultDetails['spam'] );
1043 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1044 throw new UserBlockedError( $wgUser->getBlock() );
1046 case self
::AS_IMAGE_REDIRECT_ANON
:
1047 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1048 throw new PermissionsError( 'upload' );
1050 case self
::AS_READ_ONLY_PAGE_ANON
:
1051 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1052 throw new PermissionsError( 'edit' );
1054 case self
::AS_READ_ONLY_PAGE
:
1055 throw new ReadOnlyError
;
1057 case self
::AS_RATE_LIMITED
:
1058 throw new ThrottledError();
1060 case self
::AS_NO_CREATE_PERMISSION
:
1061 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1062 throw new PermissionsError( $permission );
1065 // We don't recognize $status->value. The only way that can happen
1066 // is if an extension hook aborted from inside ArticleSave.
1067 // Render the status object into $this->hookError
1068 // FIXME this sucks, we should just use the Status object throughout
1069 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1076 * Attempt submission (no UI)
1081 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1083 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1084 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1085 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1087 function internalAttemptSave( &$result, $bot = false ) {
1088 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1090 $status = Status
::newGood();
1092 wfProfileIn( __METHOD__
);
1093 wfProfileIn( __METHOD__
. '-checks' );
1095 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1096 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1097 $status->fatal( 'hookaborted' );
1098 $status->value
= self
::AS_HOOK_ERROR
;
1099 wfProfileOut( __METHOD__
. '-checks' );
1100 wfProfileOut( __METHOD__
);
1104 # Check image redirect
1105 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1106 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
1107 !$wgUser->isAllowed( 'upload' ) ) {
1108 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1109 $status->setResult( false, $code );
1111 wfProfileOut( __METHOD__
. '-checks' );
1112 wfProfileOut( __METHOD__
);
1118 $match = self
::matchSummarySpamRegex( $this->summary
);
1119 if ( $match === false ) {
1120 $match = self
::matchSpamRegex( $this->textbox1
);
1122 if ( $match !== false ) {
1123 $result['spam'] = $match;
1124 $ip = $wgRequest->getIP();
1125 $pdbk = $this->mTitle
->getPrefixedDBkey();
1126 $match = str_replace( "\n", '', $match );
1127 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1128 $status->fatal( 'spamprotectionmatch', $match );
1129 $status->value
= self
::AS_SPAM_ERROR
;
1130 wfProfileOut( __METHOD__
. '-checks' );
1131 wfProfileOut( __METHOD__
);
1134 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1135 # Error messages etc. could be handled within the hook...
1136 $status->fatal( 'hookaborted' );
1137 $status->value
= self
::AS_HOOK_ERROR
;
1138 wfProfileOut( __METHOD__
. '-checks' );
1139 wfProfileOut( __METHOD__
);
1141 } elseif ( $this->hookError
!= '' ) {
1142 # ...or the hook could be expecting us to produce an error
1143 $status->fatal( 'hookaborted' );
1144 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1145 wfProfileOut( __METHOD__
. '-checks' );
1146 wfProfileOut( __METHOD__
);
1150 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1151 // Auto-block user's IP if the account was "hard" blocked
1152 $wgUser->spreadAnyEditBlock();
1153 # Check block state against master, thus 'false'.
1154 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1155 wfProfileOut( __METHOD__
. '-checks' );
1156 wfProfileOut( __METHOD__
);
1160 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1161 if ( $this->kblength
> $wgMaxArticleSize ) {
1162 // Error will be displayed by showEditForm()
1163 $this->tooBig
= true;
1164 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1165 wfProfileOut( __METHOD__
. '-checks' );
1166 wfProfileOut( __METHOD__
);
1170 if ( !$wgUser->isAllowed( 'edit' ) ) {
1171 if ( $wgUser->isAnon() ) {
1172 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1173 wfProfileOut( __METHOD__
. '-checks' );
1174 wfProfileOut( __METHOD__
);
1177 $status->fatal( 'readonlytext' );
1178 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1179 wfProfileOut( __METHOD__
. '-checks' );
1180 wfProfileOut( __METHOD__
);
1185 if ( wfReadOnly() ) {
1186 $status->fatal( 'readonlytext' );
1187 $status->value
= self
::AS_READ_ONLY_PAGE
;
1188 wfProfileOut( __METHOD__
. '-checks' );
1189 wfProfileOut( __METHOD__
);
1192 if ( $wgUser->pingLimiter() ) {
1193 $status->fatal( 'actionthrottledtext' );
1194 $status->value
= self
::AS_RATE_LIMITED
;
1195 wfProfileOut( __METHOD__
. '-checks' );
1196 wfProfileOut( __METHOD__
);
1200 # If the article has been deleted while editing, don't save it without
1202 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1203 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1204 wfProfileOut( __METHOD__
. '-checks' );
1205 wfProfileOut( __METHOD__
);
1209 wfProfileOut( __METHOD__
. '-checks' );
1211 # Load the page data from the master. If anything changes in the meantime,
1212 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1213 $this->mArticle
->loadPageData( 'fromdbmaster' );
1214 $new = !$this->mArticle
->exists();
1217 // Late check for create permission, just in case *PARANOIA*
1218 if ( !$this->mTitle
->userCan( 'create' ) ) {
1219 $status->fatal( 'nocreatetext' );
1220 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1221 wfDebug( __METHOD__
. ": no create permission\n" );
1222 wfProfileOut( __METHOD__
);
1226 # Don't save a new article if it's blank.
1227 if ( $this->textbox1
== '' ) {
1228 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1229 wfProfileOut( __METHOD__
);
1233 // Run post-section-merge edit filter
1234 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1235 # Error messages etc. could be handled within the hook...
1236 $status->fatal( 'hookaborted' );
1237 $status->value
= self
::AS_HOOK_ERROR
;
1238 wfProfileOut( __METHOD__
);
1240 } elseif ( $this->hookError
!= '' ) {
1241 # ...or the hook could be expecting us to produce an error
1242 $status->fatal( 'hookaborted' );
1243 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1244 wfProfileOut( __METHOD__
);
1248 $text = $this->textbox1
;
1249 $result['sectionanchor'] = '';
1250 if ( $this->section
== 'new' ) {
1251 if ( $this->sectiontitle
!== '' ) {
1252 // Insert the section title above the content.
1253 $text = wfMessage( 'newsectionheaderdefaultlevel' )->rawParams( $this->sectiontitle
)
1254 ->inContentLanguage()->text() . "\n\n" . $text;
1256 // Jump to the new section
1257 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1259 // If no edit summary was specified, create one automatically from the section
1260 // title and have it link to the new section. Otherwise, respect the summary as
1262 if ( $this->summary
=== '' ) {
1263 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1264 $this->summary
= wfMessage( 'newsectionsummary' )
1265 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1267 } elseif ( $this->summary
!== '' ) {
1268 // Insert the section title above the content.
1269 $text = wfMessage( 'newsectionheaderdefaultlevel' )->rawParams( $this->summary
)
1270 ->inContentLanguage()->text() . "\n\n" . $text;
1272 // Jump to the new section
1273 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1275 // Create a link to the new section from the edit summary.
1276 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1277 $this->summary
= wfMessage( 'newsectionsummary' )
1278 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1282 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1286 # Article exists. Check for edit conflict.
1287 $timestamp = $this->mArticle
->getTimestamp();
1288 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1290 if ( $timestamp != $this->edittime
) {
1291 $this->isConflict
= true;
1292 if ( $this->section
== 'new' ) {
1293 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1294 $this->mArticle
->getComment() == $this->summary
) {
1295 // Probably a duplicate submission of a new comment.
1296 // This can happen when squid resends a request after
1297 // a timeout but the first one actually went through.
1298 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1300 // New comment; suppress conflict.
1301 $this->isConflict
= false;
1302 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1304 } elseif ( $this->section
== '' && Revision
::userWasLastToEdit( DB_MASTER
, $this->mTitle
->getArticleID(), $wgUser->getId(), $this->edittime
) ) {
1305 # Suppress edit conflict with self, except for section edits where merging is required.
1306 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1307 $this->isConflict
= false;
1311 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1312 // backwards compatibility with old forms/bots).
1313 if ( $this->sectiontitle
!== '' ) {
1314 $sectionTitle = $this->sectiontitle
;
1316 $sectionTitle = $this->summary
;
1319 if ( $this->isConflict
) {
1320 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1321 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle, $this->edittime
);
1323 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1324 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle );
1326 if ( is_null( $text ) ) {
1327 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1328 $this->isConflict
= true;
1329 $text = $this->textbox1
; // do not try to merge here!
1330 } elseif ( $this->isConflict
) {
1332 if ( $this->mergeChangesInto( $text ) ) {
1333 // Successful merge! Maybe we should tell the user the good news?
1334 $this->isConflict
= false;
1335 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1337 $this->section
= '';
1338 $this->textbox1
= $text;
1339 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1343 if ( $this->isConflict
) {
1344 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1345 wfProfileOut( __METHOD__
);
1349 // Run post-section-merge edit filter
1350 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
1351 # Error messages etc. could be handled within the hook...
1352 $status->fatal( 'hookaborted' );
1353 $status->value
= self
::AS_HOOK_ERROR
;
1354 wfProfileOut( __METHOD__
);
1356 } elseif ( $this->hookError
!= '' ) {
1357 # ...or the hook could be expecting us to produce an error
1358 $status->fatal( 'hookaborted' );
1359 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1360 wfProfileOut( __METHOD__
);
1364 # Handle the user preference to force summaries here, but not for null edits
1365 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1366 && $this->getOriginalContent() != $text
1367 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1369 if ( md5( $this->summary
) == $this->autoSumm
) {
1370 $this->missingSummary
= true;
1371 $status->fatal( 'missingsummary' );
1372 $status->value
= self
::AS_SUMMARY_NEEDED
;
1373 wfProfileOut( __METHOD__
);
1378 # And a similar thing for new sections
1379 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1380 if ( trim( $this->summary
) == '' ) {
1381 $this->missingSummary
= true;
1382 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1383 $status->value
= self
::AS_SUMMARY_NEEDED
;
1384 wfProfileOut( __METHOD__
);
1390 wfProfileIn( __METHOD__
. '-sectionanchor' );
1391 $sectionanchor = '';
1392 if ( $this->section
== 'new' ) {
1393 if ( $this->textbox1
== '' ) {
1394 $this->missingComment
= true;
1395 $status->fatal( 'missingcommenttext' );
1396 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1397 wfProfileOut( __METHOD__
. '-sectionanchor' );
1398 wfProfileOut( __METHOD__
);
1401 if ( $this->sectiontitle
!== '' ) {
1402 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1403 // If no edit summary was specified, create one automatically from the section
1404 // title and have it link to the new section. Otherwise, respect the summary as
1406 if ( $this->summary
=== '' ) {
1407 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1408 $this->summary
= wfMessage( 'newsectionsummary' )
1409 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1411 } elseif ( $this->summary
!== '' ) {
1412 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1413 # This is a new section, so create a link to the new section
1414 # in the revision summary.
1415 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1416 $this->summary
= wfMessage( 'newsectionsummary' )
1417 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1419 } elseif ( $this->section
!= '' ) {
1420 # Try to get a section anchor from the section source, redirect to edited section if header found
1421 # XXX: might be better to integrate this into Article::replaceSection
1422 # for duplicate heading checking and maybe parsing
1423 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1424 # we can't deal with anchors, includes, html etc in the header for now,
1425 # headline would need to be parsed to improve this
1426 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1427 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1430 $result['sectionanchor'] = $sectionanchor;
1431 wfProfileOut( __METHOD__
. '-sectionanchor' );
1433 // Save errors may fall down to the edit form, but we've now
1434 // merged the section into full text. Clear the section field
1435 // so that later submission of conflict forms won't try to
1436 // replace that into a duplicated mess.
1437 $this->textbox1
= $text;
1438 $this->section
= '';
1440 $status->value
= self
::AS_SUCCESS_UPDATE
;
1443 // Check for length errors again now that the section is merged in
1444 $this->kblength
= (int)( strlen( $text ) / 1024 );
1445 if ( $this->kblength
> $wgMaxArticleSize ) {
1446 $this->tooBig
= true;
1447 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1448 wfProfileOut( __METHOD__
);
1452 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1453 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1454 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1455 ( $bot ? EDIT_FORCE_BOT
: 0 );
1457 $doEditStatus = $this->mArticle
->doEdit( $text, $this->summary
, $flags );
1459 if ( $doEditStatus->isOK() ) {
1460 $result['redirect'] = Title
::newFromRedirect( $text ) !== null;
1461 $this->commitWatch();
1462 wfProfileOut( __METHOD__
);
1465 // Failure from doEdit()
1466 // Show the edit conflict page for certain recognized errors from doEdit(),
1467 // but don't show it for errors from extension hooks
1468 $errors = $doEditStatus->getErrorsArray();
1469 if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
1470 'edit-already-exists' ) ) )
1472 $this->isConflict
= true;
1473 // Destroys data doEdit() put in $status->value but who cares
1474 $doEditStatus->value
= self
::AS_END
;
1476 wfProfileOut( __METHOD__
);
1477 return $doEditStatus;
1482 * Commit the change of watch status
1484 protected function commitWatch() {
1486 if ( $wgUser->isLoggedIn() && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
) ) {
1487 $dbw = wfGetDB( DB_MASTER
);
1488 $dbw->begin( __METHOD__
);
1489 if ( $this->watchthis
) {
1490 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1492 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1494 $dbw->commit( __METHOD__
);
1502 * @param $editText string
1506 function mergeChangesInto( &$editText ) {
1507 wfProfileIn( __METHOD__
);
1509 $db = wfGetDB( DB_MASTER
);
1511 // This is the revision the editor started from
1512 $baseRevision = $this->getBaseRevision();
1513 if ( is_null( $baseRevision ) ) {
1514 wfProfileOut( __METHOD__
);
1517 $baseText = $baseRevision->getText();
1519 // The current state, we want to merge updates into it
1520 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1521 if ( is_null( $currentRevision ) ) {
1522 wfProfileOut( __METHOD__
);
1525 $currentText = $currentRevision->getText();
1528 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1529 $editText = $result;
1530 wfProfileOut( __METHOD__
);
1533 wfProfileOut( __METHOD__
);
1541 function getBaseRevision() {
1542 if ( !$this->mBaseRevision
) {
1543 $db = wfGetDB( DB_MASTER
);
1544 $baseRevision = Revision
::loadFromTimestamp(
1545 $db, $this->mTitle
, $this->edittime
);
1546 return $this->mBaseRevision
= $baseRevision;
1548 return $this->mBaseRevision
;
1553 * Check given input text against $wgSpamRegex, and return the text of the first match.
1555 * @param $text string
1557 * @return string|bool matching string or false
1559 public static function matchSpamRegex( $text ) {
1560 global $wgSpamRegex;
1561 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1562 $regexes = (array)$wgSpamRegex;
1563 return self
::matchSpamRegexInternal( $text, $regexes );
1567 * Check given input text against $wgSpamRegex, and return the text of the first match.
1569 * @param $text string
1571 * @return string|bool matching string or false
1573 public static function matchSummarySpamRegex( $text ) {
1574 global $wgSummarySpamRegex;
1575 $regexes = (array)$wgSummarySpamRegex;
1576 return self
::matchSpamRegexInternal( $text, $regexes );
1580 * @param $text string
1581 * @param $regexes array
1582 * @return bool|string
1584 protected static function matchSpamRegexInternal( $text, $regexes ) {
1585 foreach ( $regexes as $regex ) {
1587 if ( preg_match( $regex, $text, $matches ) ) {
1594 function setHeaders() {
1595 global $wgOut, $wgUser;
1597 $wgOut->addModules( 'mediawiki.action.edit' );
1599 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1600 $wgOut->addModules( 'mediawiki.action.edit.preview' );
1602 // Bug #19334: textarea jumps when editing articles in IE8
1603 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1605 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1607 # Enabled article-related sidebar, toplinks, etc.
1608 $wgOut->setArticleRelated( true );
1610 $contextTitle = $this->getContextTitle();
1611 if ( $this->isConflict
) {
1612 $msg = 'editconflict';
1613 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1614 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1616 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1617 'editing' : 'creating';
1619 # Use the title defined by DISPLAYTITLE magic word when present
1620 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1621 if ( $displayTitle === false ) {
1622 $displayTitle = $contextTitle->getPrefixedText();
1624 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1628 * Show all applicable editing introductions
1630 protected function showIntro() {
1631 global $wgOut, $wgUser;
1632 if ( $this->suppressIntro
) {
1636 $namespace = $this->mTitle
->getNamespace();
1638 if ( $namespace == NS_MEDIAWIKI
) {
1639 # Show a warning if editing an interface message
1640 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1641 } else if( $namespace == NS_FILE
) {
1642 # Show a hint to shared repo
1643 $file = wfFindFile( $this->mTitle
);
1644 if( $file && !$file->isLocal() ) {
1645 $descUrl = $file->getDescriptionUrl();
1646 # there must be a description url to show a hint to shared repo
1648 if( !$this->mTitle
->exists() ) {
1649 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1650 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1653 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1654 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1661 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1662 # Show log extract when the user is currently blocked
1663 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1664 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1665 $username = $parts[0];
1666 $user = User
::newFromName( $username, false /* allow IP users*/ );
1667 $ip = User
::isIP( $username );
1668 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1669 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1670 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1671 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1672 LogEventsList
::showLogExtract(
1675 $user->getUserPage(),
1679 'showIfEmpty' => false,
1681 'blocked-notice-logextract',
1682 $user->getName() # Support GENDER in notice
1688 # Try to add a custom edit intro, or use the standard one if this is not possible.
1689 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1690 if ( $wgUser->isLoggedIn() ) {
1691 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1693 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1696 # Give a notice if the user is editing a deleted/moved page...
1697 if ( !$this->mTitle
->exists() ) {
1698 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1699 '', array( 'lim' => 10,
1700 'conds' => array( "log_action != 'revision'" ),
1701 'showIfEmpty' => false,
1702 'msgKey' => array( 'recreate-moveddeleted-warn' ) )
1708 * Attempt to show a custom editing introduction, if supplied
1712 protected function showCustomIntro() {
1713 if ( $this->editintro
) {
1714 $title = Title
::newFromText( $this->editintro
);
1715 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1717 // Added using template syntax, to take <noinclude>'s into account.
1718 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1729 * Send the edit form and related headers to $wgOut
1730 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1731 * during form output near the top, for captchas and the like.
1733 function showEditForm( $formCallback = null ) {
1734 global $wgOut, $wgUser;
1736 wfProfileIn( __METHOD__
);
1738 # need to parse the preview early so that we know which templates are used,
1739 # otherwise users with "show preview after edit box" will get a blank list
1740 # we parse this near the beginning so that setHeaders can do the title
1741 # setting work instead of leaving it in getPreviewText
1742 $previewOutput = '';
1743 if ( $this->formtype
== 'preview' ) {
1744 $previewOutput = $this->getPreviewText();
1747 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
1749 $this->setHeaders();
1751 if ( $this->showHeader() === false ) {
1752 wfProfileOut( __METHOD__
);
1756 $wgOut->addHTML( $this->editFormPageTop
);
1758 if ( $wgUser->getOption( 'previewontop' ) ) {
1759 $this->displayPreviewArea( $previewOutput, true );
1762 $wgOut->addHTML( $this->editFormTextTop
);
1764 $showToolbar = true;
1765 if ( $this->wasDeletedSinceLastEdit() ) {
1766 if ( $this->formtype
== 'save' ) {
1767 // Hide the toolbar and edit area, user can click preview to get it back
1768 // Add an confirmation checkbox and explanation.
1769 $showToolbar = false;
1771 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1772 'deletedwhileediting' );
1776 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => self
::EDITFORM_ID
, 'name' => self
::EDITFORM_ID
,
1777 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1778 'enctype' => 'multipart/form-data' ) ) );
1780 if ( is_callable( $formCallback ) ) {
1781 call_user_func_array( $formCallback, array( &$wgOut ) );
1784 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1786 // Put these up at the top to ensure they aren't lost on early form submission
1787 $this->showFormBeforeText();
1789 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1790 $username = $this->lastDelete
->user_name
;
1791 $comment = $this->lastDelete
->log_comment
;
1793 // It is better to not parse the comment at all than to have templates expanded in the middle
1794 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1795 $key = $comment === ''
1796 ?
'confirmrecreate-noreason'
1797 : 'confirmrecreate';
1799 '<div class="mw-confirm-recreate">' .
1800 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
1801 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
1802 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1808 # When the summary is hidden, also hide them on preview/show changes
1809 if( $this->nosummary
) {
1810 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
1813 # If a blank edit summary was previously provided, and the appropriate
1814 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1815 # user being bounced back more than once in the event that a summary
1818 # For a bit more sophisticated detection of blank summaries, hash the
1819 # automatic one and pass that in the hidden field wpAutoSummary.
1820 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
1821 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1824 if ( $this->undidRev
) {
1825 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
1828 if ( $this->hasPresetSummary
) {
1829 // If a summary has been preset using &summary= we dont want to prompt for
1830 // a different summary. Only prompt for a summary if the summary is blanked.
1832 $this->autoSumm
= md5( '' );
1835 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1836 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1838 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
1840 if ( $this->section
== 'new' ) {
1841 $this->showSummaryInput( true, $this->summary
);
1842 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1845 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1847 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1848 $wgOut->addHTML( EditPage
::getEditToolbar() );
1851 if ( $this->isConflict
) {
1852 // In an edit conflict bypass the overrideable content form method
1853 // and fallback to the raw wpTextbox1 since editconflicts can't be
1854 // resolved between page source edits and custom ui edits using the
1856 $this->textbox2
= $this->textbox1
;
1857 $this->textbox1
= $this->getCurrentText();
1859 $this->showTextbox1();
1861 $this->showContentForm();
1864 $wgOut->addHTML( $this->editFormTextAfterContent
);
1866 $this->showStandardInputs();
1868 $this->showFormAfterText();
1870 $this->showTosSummary();
1872 $this->showEditTools();
1874 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
1876 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
1877 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
1879 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
1880 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
1882 if ( $this->isConflict
) {
1883 $this->showConflict();
1886 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
1888 if ( !$wgUser->getOption( 'previewontop' ) ) {
1889 $this->displayPreviewArea( $previewOutput, false );
1892 wfProfileOut( __METHOD__
);
1896 * Extract the section title from current section text, if any.
1898 * @param string $text
1899 * @return Mixed|string or false
1901 public static function extractSectionTitle( $text ) {
1902 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
1903 if ( !empty( $matches[2] ) ) {
1905 return $wgParser->stripSectionName( trim( $matches[2] ) );
1911 protected function showHeader() {
1912 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1914 if ( $this->mTitle
->isTalkPage() ) {
1915 $wgOut->addWikiMsg( 'talkpagetext' );
1918 # Optional notices on a per-namespace and per-page basis
1919 $editnotice_ns = 'editnotice-' . $this->mTitle
->getNamespace();
1920 $editnotice_ns_message = wfMessage( $editnotice_ns );
1921 if ( $editnotice_ns_message->exists() ) {
1922 $wgOut->addWikiText( $editnotice_ns_message->plain() );
1924 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
1925 $parts = explode( '/', $this->mTitle
->getDBkey() );
1926 $editnotice_base = $editnotice_ns;
1927 while ( count( $parts ) > 0 ) {
1928 $editnotice_base .= '-' . array_shift( $parts );
1929 $editnotice_base_msg = wfMessage( $editnotice_base );
1930 if ( $editnotice_base_msg->exists() ) {
1931 $wgOut->addWikiText( $editnotice_base_msg->plain() );
1935 # Even if there are no subpages in namespace, we still don't want / in MW ns.
1936 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
1937 $editnoticeMsg = wfMessage( $editnoticeText );
1938 if ( $editnoticeMsg->exists() ) {
1939 $wgOut->addWikiText( $editnoticeMsg->plain() );
1943 if ( $this->isConflict
) {
1944 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1945 $this->edittime
= $this->mArticle
->getTimestamp();
1947 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
1948 // We use $this->section to much before this and getVal('wgSection') directly in other places
1949 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1950 // Someone is welcome to try refactoring though
1951 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1955 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1956 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1957 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
1958 if ( $sectionTitle !== false ) {
1959 $this->summary
= "/* $sectionTitle */ ";
1964 if ( $this->missingComment
) {
1965 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1968 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1969 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1972 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1973 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1976 if ( $this->hookError
!== '' ) {
1977 $wgOut->addWikiText( $this->hookError
);
1980 if ( !$this->checkUnicodeCompliantBrowser() ) {
1981 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1984 if ( $this->section
!= 'new' ) {
1985 $revision = $this->mArticle
->getRevisionFetched();
1987 // Let sysop know that this will make private content public if saved
1989 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
1990 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1991 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
1992 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1995 if ( !$revision->isCurrent() ) {
1996 $this->mArticle
->setOldSubtitle( $revision->getId() );
1997 $wgOut->addWikiMsg( 'editingold' );
1999 } elseif ( $this->mTitle
->exists() ) {
2000 // Something went wrong
2002 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2003 array( 'missing-revision', $this->oldid
) );
2008 if ( wfReadOnly() ) {
2009 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2010 } elseif ( $wgUser->isAnon() ) {
2011 if ( $this->formtype
!= 'preview' ) {
2012 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2014 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2017 if ( $this->isCssJsSubpage
) {
2018 # Check the skin exists
2019 if ( $this->isWrongCaseCssJsPage
) {
2020 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2022 if ( $this->formtype
!== 'preview' ) {
2023 if ( $this->isCssSubpage
) {
2024 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2027 if ( $this->isJsSubpage
) {
2028 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2034 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2035 # Is the title semi-protected?
2036 if ( $this->mTitle
->isSemiProtected() ) {
2037 $noticeMsg = 'semiprotectedpagewarning';
2039 # Then it must be protected based on static groups (regular)
2040 $noticeMsg = 'protectedpagewarning';
2042 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2043 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2045 if ( $this->mTitle
->isCascadeProtected() ) {
2046 # Is this page under cascading protection from some source pages?
2047 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2048 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2049 $cascadeSourcesCount = count( $cascadeSources );
2050 if ( $cascadeSourcesCount > 0 ) {
2051 # Explain, and list the titles responsible
2052 foreach ( $cascadeSources as $page ) {
2053 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2056 $notice .= '</div>';
2057 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2059 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2060 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2062 'showIfEmpty' => false,
2063 'msgKey' => array( 'titleprotectedwarning' ),
2064 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2067 if ( $this->kblength
=== false ) {
2068 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2071 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2072 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2073 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2075 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2076 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2077 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2081 # Add header copyright warning
2082 $this->showHeaderCopyrightWarning();
2087 * Standard summary input and label (wgSummary), abstracted so EditPage
2088 * subclasses may reorganize the form.
2089 * Note that you do not need to worry about the label's for=, it will be
2090 * inferred by the id given to the input. You can remove them both by
2091 * passing array( 'id' => false ) to $userInputAttrs.
2093 * @param $summary string The value of the summary input
2094 * @param $labelText string The html to place inside the label
2095 * @param $inputAttrs array of attrs to use on the input
2096 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2098 * @return array An array in the format array( $label, $input )
2100 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2101 // Note: the maxlength is overriden in JS to 255 and to make it use UTF-8 bytes, not characters.
2102 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2103 'id' => 'wpSummary',
2104 'maxlength' => '200',
2107 'spellcheck' => 'true',
2108 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2110 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2111 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2112 'id' => "wpSummaryLabel"
2117 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2118 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2121 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2123 return array( $label, $input );
2127 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2128 * up top, or false if this is the comment summary
2129 * down below the textarea
2130 * @param $summary String: The text of the summary to display
2133 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2134 global $wgOut, $wgContLang;
2135 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2136 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2137 if ( $isSubjectPreview ) {
2138 if ( $this->nosummary
) {
2142 if ( !$this->mShowSummaryField
) {
2146 $summary = $wgContLang->recodeForEdit( $summary );
2147 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2148 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2149 $wgOut->addHTML( "{$label} {$input}" );
2153 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2154 * up top, or false if this is the comment summary
2155 * down below the textarea
2156 * @param $summary String: the text of the summary to display
2159 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2160 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2166 if ( $isSubjectPreview ) {
2167 $summary = wfMessage( 'newsectionsummary', $wgParser->stripSectionName( $summary ) )
2168 ->inContentLanguage()->text();
2171 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2173 $summary = wfMessage( $message )->parse() . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2174 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2177 protected function showFormBeforeText() {
2179 $section = htmlspecialchars( $this->section
);
2180 $wgOut->addHTML( <<<HTML
2181 <input type='hidden' value="{$section}" name="wpSection" />
2182 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2183 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2184 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2188 if ( !$this->checkUnicodeCompliantBrowser() ) {
2189 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2193 protected function showFormAfterText() {
2194 global $wgOut, $wgUser;
2196 * To make it harder for someone to slip a user a page
2197 * which submits an edit form to the wiki without their
2198 * knowledge, a random token is associated with the login
2199 * session. If it's not passed back with the submission,
2200 * we won't save the page, or render user JavaScript and
2203 * For anon editors, who may not have a session, we just
2204 * include the constant suffix to prevent editing from
2205 * broken text-mangling proxies.
2207 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2211 * Subpage overridable method for printing the form for page content editing
2212 * By default this simply outputs wpTextbox1
2213 * Subclasses can override this to provide a custom UI for editing;
2214 * be it a form, or simply wpTextbox1 with a modified content that will be
2215 * reverse modified when extracted from the post data.
2216 * Note that this is basically the inverse for importContentFormData
2218 protected function showContentForm() {
2219 $this->showTextbox1();
2223 * Method to output wpTextbox1
2224 * The $textoverride method can be used by subclasses overriding showContentForm
2225 * to pass back to this method.
2227 * @param $customAttribs array of html attributes to use in the textarea
2228 * @param $textoverride String: optional text to override $this->textarea1 with
2230 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2231 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2232 $attribs = array( 'style' => 'display:none;' );
2234 $classes = array(); // Textarea CSS
2235 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2236 # Is the title semi-protected?
2237 if ( $this->mTitle
->isSemiProtected() ) {
2238 $classes[] = 'mw-textarea-sprotected';
2240 # Then it must be protected based on static groups (regular)
2241 $classes[] = 'mw-textarea-protected';
2243 # Is the title cascade-protected?
2244 if ( $this->mTitle
->isCascadeProtected() ) {
2245 $classes[] = 'mw-textarea-cprotected';
2249 $attribs = array( 'tabindex' => 1 );
2251 if ( is_array( $customAttribs ) ) {
2252 $attribs +
= $customAttribs;
2255 if ( count( $classes ) ) {
2256 if ( isset( $attribs['class'] ) ) {
2257 $classes[] = $attribs['class'];
2259 $attribs['class'] = implode( ' ', $classes );
2263 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2266 protected function showTextbox2() {
2267 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2270 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2271 global $wgOut, $wgUser;
2273 $wikitext = $this->safeUnicodeOutput( $content );
2274 if ( strval( $wikitext ) !== '' ) {
2275 // Ensure there's a newline at the end, otherwise adding lines
2277 // But don't add a newline if the ext is empty, or Firefox in XHTML
2278 // mode will show an extra newline. A bit annoying.
2282 $attribs = $customAttribs +
array(
2285 'cols' => $wgUser->getIntOption( 'cols' ),
2286 'rows' => $wgUser->getIntOption( 'rows' ),
2287 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2290 $pageLang = $this->mTitle
->getPageLanguage();
2291 $attribs['lang'] = $pageLang->getCode();
2292 $attribs['dir'] = $pageLang->getDir();
2294 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2297 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2301 $classes[] = 'ontop';
2304 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2306 if ( $this->formtype
!= 'preview' ) {
2307 $attribs['style'] = 'display: none;';
2310 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2312 if ( $this->formtype
== 'preview' ) {
2313 $this->showPreview( $previewOutput );
2316 $wgOut->addHTML( '</div>' );
2318 if ( $this->formtype
== 'diff' ) {
2324 * Append preview output to $wgOut.
2325 * Includes category rendering if this is a category page.
2327 * @param $text String: the HTML to be output for the preview.
2329 protected function showPreview( $text ) {
2331 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2332 $this->mArticle
->openShowCategory();
2334 # This hook seems slightly odd here, but makes things more
2335 # consistent for extensions.
2336 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2337 $wgOut->addHTML( $text );
2338 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2339 $this->mArticle
->closeShowCategory();
2344 * Get a diff between the current contents of the edit box and the
2345 * version of the page we're editing from.
2347 * If this is a section edit, we'll replace the section as for final
2348 * save and then make a comparison.
2350 function showDiff() {
2351 global $wgUser, $wgContLang, $wgParser, $wgOut;
2353 $oldtitlemsg = 'currentrev';
2354 # if message does not exist, show diff against the preloaded default
2355 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2356 $oldtext = $this->mTitle
->getDefaultMessageText();
2357 if( $oldtext !== false ) {
2358 $oldtitlemsg = 'defaultmessagetext';
2361 $oldtext = $this->mArticle
->getRawText();
2363 $newtext = $this->mArticle
->replaceSection(
2364 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2366 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2368 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2369 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle
, $wgUser, $popts );
2371 if ( $oldtext !== false ||
$newtext != '' ) {
2372 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2373 $newtitle = wfMessage( 'yourtext' )->parse();
2375 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2376 $de->setText( $oldtext, $newtext );
2377 $difftext = $de->getDiff( $oldtitle, $newtitle );
2378 $de->showDiffStyle();
2383 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2387 * Show the header copyright warning.
2389 protected function showHeaderCopyrightWarning() {
2390 $msg = 'editpage-head-copy-warn';
2391 if ( !wfMessage( $msg )->isDisabled() ) {
2393 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2394 'editpage-head-copy-warn' );
2399 * Give a chance for site and per-namespace customizations of
2400 * terms of service summary link that might exist separately
2401 * from the copyright notice.
2403 * This will display between the save button and the edit tools,
2404 * so should remain short!
2406 protected function showTosSummary() {
2407 $msg = 'editpage-tos-summary';
2408 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2409 if ( !wfMessage( $msg )->isDisabled() ) {
2411 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2412 $wgOut->addWikiMsg( $msg );
2413 $wgOut->addHTML( '</div>' );
2417 protected function showEditTools() {
2419 $wgOut->addHTML( '<div class="mw-editTools">' .
2420 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2425 * Get the copyright warning
2427 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2429 protected function getCopywarn() {
2430 return self
::getCopyrightWarning( $this->mTitle
);
2433 public static function getCopyrightWarning( $title ) {
2434 global $wgRightsText;
2435 if ( $wgRightsText ) {
2436 $copywarnMsg = array( 'copyrightwarning',
2437 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2440 $copywarnMsg = array( 'copyrightwarning2',
2441 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2443 // Allow for site and per-namespace customization of contribution/copyright notice.
2444 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2446 return "<div id=\"editpage-copywarn\">\n" .
2447 call_user_func_array( 'wfMessage', $copywarnMsg )->plain() . "\n</div>";
2450 protected function showStandardInputs( &$tabindex = 2 ) {
2452 $wgOut->addHTML( "<div class='editOptions'>\n" );
2454 if ( $this->section
!= 'new' ) {
2455 $this->showSummaryInput( false, $this->summary
);
2456 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2459 $checkboxes = $this->getCheckboxes( $tabindex,
2460 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2461 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2463 // Show copyright warning.
2464 $wgOut->addWikiText( $this->getCopywarn() );
2465 $wgOut->addHTML( $this->editFormTextAfterWarn
);
2467 $wgOut->addHTML( "<div class='editButtons'>\n" );
2468 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2470 $cancel = $this->getCancelLink();
2471 if ( $cancel !== '' ) {
2472 $cancel .= wfMessage( 'pipe-separator' )->text();
2474 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
2475 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2476 wfMessage( 'edithelp' )->escaped() . '</a> ' .
2477 wfMessage( 'newwindow' )->parse();
2478 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
2479 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
2480 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2484 * Show an edit conflict. textbox1 is already shown in showEditForm().
2485 * If you want to use another entry point to this function, be careful.
2487 protected function showConflict() {
2490 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2491 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2493 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2494 $de->setText( $this->textbox2
, $this->textbox1
);
2496 wfMessage( 'yourtext' )->parse(),
2497 wfMessage( 'storedversion' )->text()
2500 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2501 $this->showTextbox2();
2508 public function getCancelLink() {
2509 $cancelParams = array();
2510 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2511 $cancelParams['oldid'] = $this->oldid
;
2514 return Linker
::linkKnown(
2515 $this->getContextTitle(),
2516 wfMessage( 'cancel' )->parse(),
2517 array( 'id' => 'mw-editform-cancel' ),
2523 * Returns the URL to use in the form's action attribute.
2524 * This is used by EditPage subclasses when simply customizing the action
2525 * variable in the constructor is not enough. This can be used when the
2526 * EditPage lives inside of a Special page rather than a custom page action.
2528 * @param $title Title object for which is being edited (where we go to for &action= links)
2531 protected function getActionURL( Title
$title ) {
2532 return $title->getLocalURL( array( 'action' => $this->action
) );
2536 * Check if a page was deleted while the user was editing it, before submit.
2537 * Note that we rely on the logging table, which hasn't been always there,
2538 * but that doesn't matter, because this only applies to brand new
2541 protected function wasDeletedSinceLastEdit() {
2542 if ( $this->deletedSinceEdit
!== null ) {
2543 return $this->deletedSinceEdit
;
2546 $this->deletedSinceEdit
= false;
2548 if ( $this->mTitle
->isDeletedQuick() ) {
2549 $this->lastDelete
= $this->getLastDelete();
2550 if ( $this->lastDelete
) {
2551 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2552 if ( $deleteTime > $this->starttime
) {
2553 $this->deletedSinceEdit
= true;
2558 return $this->deletedSinceEdit
;
2561 protected function getLastDelete() {
2562 $dbr = wfGetDB( DB_SLAVE
);
2563 $data = $dbr->selectRow(
2564 array( 'logging', 'user' ),
2575 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2576 'log_title' => $this->mTitle
->getDBkey(),
2577 'log_type' => 'delete',
2578 'log_action' => 'delete',
2579 'user_id=log_user' ),
2581 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2583 // Quick paranoid permission checks...
2584 if ( is_object( $data ) ) {
2585 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
2586 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
2589 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
2590 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
2597 * Get the rendered text for previewing.
2600 function getPreviewText() {
2601 global $wgOut, $wgUser, $wgParser, $wgRawHtml, $wgLang;
2603 wfProfileIn( __METHOD__
);
2605 if ( $wgRawHtml && !$this->mTokenOk
) {
2606 // Could be an offsite preview attempt. This is very unsafe if
2607 // HTML is enabled, as it could be an attack.
2609 if ( $this->textbox1
!== '' ) {
2610 // Do not put big scary notice, if previewing the empty
2611 // string, which happens when you initially edit
2612 // a category page, due to automatic preview-on-open.
2613 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2614 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
2616 wfProfileOut( __METHOD__
);
2620 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2621 if ( $this->mTokenOkExceptSuffix
) {
2622 $note = wfMessage( 'token_suffix_mismatch' )->plain();
2624 $note = wfMessage( 'session_fail_preview' )->plain();
2626 } elseif ( $this->incompleteForm
) {
2627 $note = wfMessage( 'edit_form_incomplete' )->plain();
2629 $note = wfMessage( 'previewnote' )->plain() .
2630 ' [[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' . wfMessage( 'continue-editing' )->text() . ']]';
2633 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
2635 $parserOptions->setEditSection( false );
2636 $parserOptions->setIsPreview( true );
2637 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
2639 # don't parse non-wikitext pages, show message about preview
2640 if ( $this->mTitle
->isCssJsSubpage() ||
!$this->mTitle
->isWikitextPage() ) {
2641 if ( $this->mTitle
->isCssJsSubpage() ) {
2643 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
2649 # Used messages to make sure grep find them:
2650 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2653 if ( preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2654 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMessage( "{$level}csspreview" )->text() . "\n</div>";
2655 $class .= " mw-css";
2656 } elseif ( preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2657 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMessage( "{$level}jspreview" )->text() . "\n</div>";
2660 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2662 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2663 $previewHTML = $parserOutput->getText();
2668 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2670 $toparse = $this->textbox1
;
2672 # If we're adding a comment, we need to show the
2673 # summary as the headline
2674 if ( $this->section
== "new" && $this->summary
!= "" ) {
2675 $toparse = wfMessage( 'newsectionheaderdefaultlevel', $this->summary
)->inContentLanguage()->text() . "\n\n" . $toparse;
2678 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2680 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle
, $wgUser, $parserOptions );
2681 $parserOutput = $wgParser->parse( $toparse, $this->mTitle
, $parserOptions );
2683 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2685 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2687 $previewHTML = $parserOutput->getText();
2690 $this->mParserOutput
= $parserOutput;
2691 $wgOut->addParserOutputNoText( $parserOutput );
2693 if ( count( $parserOutput->getWarnings() ) ) {
2694 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2698 if ( $this->isConflict
) {
2699 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
2701 $conflict = '<hr />';
2704 $previewhead = "<div class='previewnote'>\n" .
2705 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
2706 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2708 $pageLang = $this->mTitle
->getPageLanguage();
2709 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2710 'class' => 'mw-content-' . $pageLang->getDir() );
2711 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2713 wfProfileOut( __METHOD__
);
2714 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2720 function getTemplates() {
2721 if ( $this->preview ||
$this->section
!= '' ) {
2722 $templates = array();
2723 if ( !isset( $this->mParserOutput
) ) {
2726 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
2727 foreach ( array_keys( $template ) as $dbk ) {
2728 $templates[] = Title
::makeTitle( $ns, $dbk );
2733 return $this->mTitle
->getTemplateLinksFrom();
2738 * Shows a bulletin board style toolbar for common editing functions.
2739 * It can be disabled in the user preferences.
2740 * The necessary JavaScript code can be found in skins/common/edit.js.
2744 static function getEditToolbar() {
2745 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2746 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2748 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2751 * $toolarray is an array of arrays each of which includes the
2752 * filename of the button image (without path), the opening
2753 * tag, the closing tag, optionally a sample text that is
2754 * inserted between the two when no selection is highlighted
2755 * and. The tip text is shown when the user moves the mouse
2758 * Also here: accesskeys (key), which are not used yet until
2759 * someone can figure out a way to make them work in
2760 * IE. However, we should make sure these keys are not defined
2765 'image' => $wgLang->getImageFile( 'button-bold' ),
2766 'id' => 'mw-editbutton-bold',
2768 'close' => '\'\'\'',
2769 'sample' => wfMessage( 'bold_sample' )->text(),
2770 'tip' => wfMessage( 'bold_tip' )->text(),
2774 'image' => $wgLang->getImageFile( 'button-italic' ),
2775 'id' => 'mw-editbutton-italic',
2778 'sample' => wfMessage( 'italic_sample' )->text(),
2779 'tip' => wfMessage( 'italic_tip' )->text(),
2783 'image' => $wgLang->getImageFile( 'button-link' ),
2784 'id' => 'mw-editbutton-link',
2787 'sample' => wfMessage( 'link_sample' )->text(),
2788 'tip' => wfMessage( 'link_tip' )->text(),
2792 'image' => $wgLang->getImageFile( 'button-extlink' ),
2793 'id' => 'mw-editbutton-extlink',
2796 'sample' => wfMessage( 'extlink_sample' )->text(),
2797 'tip' => wfMessage( 'extlink_tip' )->text(),
2801 'image' => $wgLang->getImageFile( 'button-headline' ),
2802 'id' => 'mw-editbutton-headline',
2805 'sample' => wfMessage( 'headline_sample' )->text(),
2806 'tip' => wfMessage( 'headline_tip' )->text(),
2809 $imagesAvailable ?
array(
2810 'image' => $wgLang->getImageFile( 'button-image' ),
2811 'id' => 'mw-editbutton-image',
2812 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2814 'sample' => wfMessage( 'image_sample' )->text(),
2815 'tip' => wfMessage( 'image_tip' )->text(),
2818 $imagesAvailable ?
array(
2819 'image' => $wgLang->getImageFile( 'button-media' ),
2820 'id' => 'mw-editbutton-media',
2821 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2823 'sample' => wfMessage( 'media_sample' )->text(),
2824 'tip' => wfMessage( 'media_tip' )->text(),
2828 'image' => $wgLang->getImageFile( 'button-math' ),
2829 'id' => 'mw-editbutton-math',
2831 'close' => "</math>",
2832 'sample' => wfMessage( 'math_sample' )->text(),
2833 'tip' => wfMessage( 'math_tip' )->text(),
2837 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2838 'id' => 'mw-editbutton-nowiki',
2839 'open' => "<nowiki>",
2840 'close' => "</nowiki>",
2841 'sample' => wfMessage( 'nowiki_sample' )->text(),
2842 'tip' => wfMessage( 'nowiki_tip' )->text(),
2846 'image' => $wgLang->getImageFile( 'button-sig' ),
2847 'id' => 'mw-editbutton-signature',
2851 'tip' => wfMessage( 'sig_tip' )->text(),
2855 'image' => $wgLang->getImageFile( 'button-hr' ),
2856 'id' => 'mw-editbutton-hr',
2857 'open' => "\n----\n",
2860 'tip' => wfMessage( 'hr_tip' )->text(),
2865 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
2866 foreach ( $toolarray as $tool ) {
2872 $image = $wgStylePath . '/common/images/' . $tool['image'],
2873 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2874 // Older browsers show a "speedtip" type message only for ALT.
2875 // Ideally these should be different, realistically they
2876 // probably don't need to be.
2877 $tip = $tool['tip'],
2878 $open = $tool['open'],
2879 $close = $tool['close'],
2880 $sample = $tool['sample'],
2881 $cssId = $tool['id'],
2884 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2887 // This used to be called on DOMReady from mediawiki.action.edit, which
2888 // ended up causing race conditions with the setup code above.
2890 "// Create button bar\n" .
2891 "$(function() { mw.toolbar.init(); } );\n";
2894 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2896 $toolbar = '<div id="toolbar"></div>';
2898 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2904 * Returns an array of html code of the following checkboxes:
2907 * @param $tabindex int Current tabindex
2908 * @param $checked Array of checkbox => bool, where bool indicates the checked
2909 * status of the checkbox
2913 public function getCheckboxes( &$tabindex, $checked ) {
2916 $checkboxes = array();
2918 // don't show the minor edit checkbox if it's a new page or section
2919 if ( !$this->isNew
) {
2920 $checkboxes['minor'] = '';
2921 $minorLabel = wfMessage( 'minoredit' )->parse();
2922 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2924 'tabindex' => ++
$tabindex,
2925 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
2926 'id' => 'wpMinoredit',
2928 $checkboxes['minor'] =
2929 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2930 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2931 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2932 ">{$minorLabel}</label>";
2936 $watchLabel = wfMessage( 'watchthis' )->parse();
2937 $checkboxes['watch'] = '';
2938 if ( $wgUser->isLoggedIn() ) {
2940 'tabindex' => ++
$tabindex,
2941 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
2942 'id' => 'wpWatchthis',
2944 $checkboxes['watch'] =
2945 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2946 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2947 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2948 ">{$watchLabel}</label>";
2950 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2955 * Returns an array of html code of the following buttons:
2956 * save, diff, preview and live
2958 * @param $tabindex int Current tabindex
2962 public function getEditButtons( &$tabindex ) {
2969 'tabindex' => ++
$tabindex,
2970 'value' => wfMessage( 'savearticle' )->text(),
2971 'accesskey' => wfMessage( 'accesskey-save' )->text(),
2972 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
2974 $buttons['save'] = Xml
::element( 'input', $temp, '' );
2976 ++
$tabindex; // use the same for preview and live preview
2978 'id' => 'wpPreview',
2979 'name' => 'wpPreview',
2981 'tabindex' => $tabindex,
2982 'value' => wfMessage( 'showpreview' )->text(),
2983 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
2984 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
2986 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
2987 $buttons['live'] = '';
2993 'tabindex' => ++
$tabindex,
2994 'value' => wfMessage( 'showdiff' )->text(),
2995 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
2996 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
2998 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3000 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3005 * Output preview text only. This can be sucked into the edit page
3006 * via JavaScript, and saves the server time rendering the skin as
3007 * well as theoretically being more robust on the client (doesn't
3008 * disturb the edit box's undo history, won't eat your text on
3011 * @todo This doesn't include category or interlanguage links.
3012 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3013 * or something...</s>" that might also require more skin
3014 * initialization, so check whether that's a problem.
3016 function livePreview() {
3019 header( 'Content-type: text/xml; charset=utf-8' );
3020 header( 'Cache-control: no-cache' );
3022 $previewText = $this->getPreviewText();
3023 #$categories = $skin->getCategoryLinks();
3026 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3027 Xml
::tags( 'livepreview', null,
3028 Xml
::element( 'preview', null, $previewText )
3029 #. Xml::element( 'category', null, $categories )
3035 * Call the stock "user is blocked" page
3037 * @deprecated in 1.19; throw an exception directly instead
3039 function blockedPage() {
3040 wfDeprecated( __METHOD__
, '1.19' );
3043 throw new UserBlockedError( $wgUser->getBlock() );
3047 * Produce the stock "please login to edit pages" page
3049 * @deprecated in 1.19; throw an exception directly instead
3051 function userNotLoggedInPage() {
3052 wfDeprecated( __METHOD__
, '1.19' );
3053 throw new PermissionsError( 'edit' );
3057 * Show an error page saying to the user that he has insufficient permissions
3058 * to create a new page
3060 * @deprecated in 1.19; throw an exception directly instead
3062 function noCreatePermission() {
3063 wfDeprecated( __METHOD__
, '1.19' );
3064 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3065 throw new PermissionsError( $permission );
3069 * Creates a basic error page which informs the user that
3070 * they have attempted to edit a nonexistent section.
3072 function noSuchSectionPage() {
3075 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3077 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3078 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3079 $wgOut->addHTML( $res );
3081 $wgOut->returnToMain( false, $this->mTitle
);
3085 * Produce the stock "your edit contains spam" page
3087 * @param $match string Text which triggered one or more filters
3088 * @deprecated since 1.17 Use method spamPageWithContent() instead
3090 static function spamPage( $match = false ) {
3091 wfDeprecated( __METHOD__
, '1.17' );
3093 global $wgOut, $wgTitle;
3095 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3097 $wgOut->addHTML( '<div id="spamprotected">' );
3098 $wgOut->addWikiMsg( 'spamprotectiontext' );
3100 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3102 $wgOut->addHTML( '</div>' );
3104 $wgOut->returnToMain( false, $wgTitle );
3108 * Show "your edit contains spam" page with your diff and text
3110 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3112 public function spamPageWithContent( $match = false ) {
3113 global $wgOut, $wgLang;
3114 $this->textbox2
= $this->textbox1
;
3116 if( is_array( $match ) ){
3117 $match = $wgLang->listToText( $match );
3119 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3121 $wgOut->addHTML( '<div id="spamprotected">' );
3122 $wgOut->addWikiMsg( 'spamprotectiontext' );
3124 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3126 $wgOut->addHTML( '</div>' );
3128 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3131 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3132 $this->showTextbox2();
3134 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3138 * Format an anchor fragment as it would appear for a given section name
3139 * @param $text String
3143 function sectionAnchor( $text ) {
3145 return $wgParser->guessSectionNameFromWikiText( $text );
3149 * Check if the browser is on a blacklist of user-agents known to
3150 * mangle UTF-8 data on form submission. Returns true if Unicode
3151 * should make it through, false if it's known to be a problem.
3155 function checkUnicodeCompliantBrowser() {
3156 global $wgBrowserBlackList, $wgRequest;
3158 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3159 if ( $currentbrowser === false ) {
3160 // No User-Agent header sent? Trust it by default...
3164 foreach ( $wgBrowserBlackList as $browser ) {
3165 if ( preg_match( $browser, $currentbrowser ) ) {
3173 * Filter an input field through a Unicode de-armoring process if it
3174 * came from an old browser with known broken Unicode editing issues.
3176 * @param $request WebRequest
3177 * @param $field String
3181 function safeUnicodeInput( $request, $field ) {
3182 $text = rtrim( $request->getText( $field ) );
3183 return $request->getBool( 'safemode' )
3184 ?
$this->unmakesafe( $text )
3189 * @param $request WebRequest
3190 * @param $text string
3193 function safeUnicodeText( $request, $text ) {
3194 $text = rtrim( $text );
3195 return $request->getBool( 'safemode' )
3196 ?
$this->unmakesafe( $text )
3201 * Filter an output field through a Unicode armoring process if it is
3202 * going to an old browser with known broken Unicode editing issues.
3204 * @param $text String
3208 function safeUnicodeOutput( $text ) {
3210 $codedText = $wgContLang->recodeForEdit( $text );
3211 return $this->checkUnicodeCompliantBrowser()
3213 : $this->makesafe( $codedText );
3217 * A number of web browsers are known to corrupt non-ASCII characters
3218 * in a UTF-8 text editing environment. To protect against this,
3219 * detected browsers will be served an armored version of the text,
3220 * with non-ASCII chars converted to numeric HTML character references.
3222 * Preexisting such character references will have a 0 added to them
3223 * to ensure that round-trips do not alter the original data.
3225 * @param $invalue String
3229 function makesafe( $invalue ) {
3230 // Armor existing references for reversability.
3231 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3236 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3237 $bytevalue = ord( $invalue[$i] );
3238 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3239 $result .= chr( $bytevalue );
3241 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3242 $working = $working << 6;
3243 $working +
= ( $bytevalue & 0x3F );
3245 if ( $bytesleft <= 0 ) {
3246 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3248 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3249 $working = $bytevalue & 0x1F;
3251 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3252 $working = $bytevalue & 0x0F;
3254 } else { // 1111 0xxx
3255 $working = $bytevalue & 0x07;
3263 * Reverse the previously applied transliteration of non-ASCII characters
3264 * back to UTF-8. Used to protect data from corruption by broken web browsers
3265 * as listed in $wgBrowserBlackList.
3267 * @param $invalue String
3271 function unmakesafe( $invalue ) {
3273 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3274 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3278 $hexstring .= $invalue[$i];
3280 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3282 // Do some sanity checks. These aren't needed for reversability,
3283 // but should help keep the breakage down if the editor
3284 // breaks one of the entities whilst editing.
3285 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3286 $codepoint = hexdec( $hexstring );
3287 $result .= codepointToUtf8( $codepoint );
3289 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3292 $result .= substr( $invalue, $i, 1 );
3295 // reverse the transform that we made for reversability reasons.
3296 return strtr( $result, array( "�" => "&#x" ) );