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__
);
395 if ( !$this->mTitle
->getArticleID() )
396 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
398 wfRunHooks( 'EditFormInitialText', array( $this ) );
401 $this->showEditForm();
402 wfProfileOut( __METHOD__
. "-business-end" );
403 wfProfileOut( __METHOD__
);
409 protected function getEditPermissionErrors() {
411 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
412 # Can this title be created?
413 if ( !$this->mTitle
->exists() ) {
414 $permErrors = array_merge( $permErrors,
415 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
417 # Ignore some permissions errors when a user is just previewing/viewing diffs
419 foreach ( $permErrors as $error ) {
420 if ( ( $this->preview ||
$this->diff
) &&
421 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
426 $permErrors = wfArrayDiff2( $permErrors, $remove );
431 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
432 * but with the following differences:
433 * - If redlink=1, the user will be redirected to the page
434 * - If there is content to display or the error occurs while either saving,
435 * previewing or showing the difference, it will be a
436 * "View source for ..." page displaying the source code after the error message.
439 * @param $permErrors Array of permissions errors, as returned by
440 * Title::getUserPermissionsErrors().
442 protected function displayPermissionsError( array $permErrors ) {
443 global $wgRequest, $wgOut;
445 if ( $wgRequest->getBool( 'redlink' ) ) {
446 // The edit page was reached via a red link.
447 // Redirect to the article page and let them click the edit tab if
448 // they really want a permission error.
449 $wgOut->redirect( $this->mTitle
->getFullUrl() );
453 $content = $this->getContent();
455 # Use the normal message if there's nothing to display
456 if ( $this->firsttime
&& $content === '' ) {
457 $action = $this->mTitle
->exists() ?
'edit' :
458 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
459 throw new PermissionsError( $action, $permErrors );
462 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
463 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
464 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
465 $wgOut->addHTML( "<hr />\n" );
467 # If the user made changes, preserve them when showing the markup
468 # (This happens when a user is blocked during edit, for instance)
469 if ( !$this->firsttime
) {
470 $content = $this->textbox1
;
471 $wgOut->addWikiMsg( 'viewyourtext' );
473 $wgOut->addWikiMsg( 'viewsourcetext' );
476 $this->showTextbox( $content, 'wpTextbox1', array( 'readonly' ) );
478 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
479 Linker
::formatTemplates( $this->getTemplates() ) ) );
481 if ( $this->mTitle
->exists() ) {
482 $wgOut->returnToMain( null, $this->mTitle
);
487 * Show a read-only error
488 * Parameters are the same as OutputPage:readOnlyPage()
489 * Redirect to the article page if redlink=1
490 * @deprecated in 1.19; use displayPermissionsError() instead
492 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
493 wfDeprecated( __METHOD__
, '1.19' );
495 global $wgRequest, $wgOut;
496 if ( $wgRequest->getBool( 'redlink' ) ) {
497 // The edit page was reached via a red link.
498 // Redirect to the article page and let them click the edit tab if
499 // they really want a permission error.
500 $wgOut->redirect( $this->mTitle
->getFullUrl() );
502 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
507 * Should we show a preview when the edit form is first shown?
511 protected function previewOnOpen() {
512 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
513 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
514 // Explicit override from request
516 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
517 // Explicit override from request
519 } elseif ( $this->section
== 'new' ) {
520 // Nothing *to* preview for new sections
522 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
523 // Standard preference behaviour
525 } elseif ( !$this->mTitle
->exists() &&
526 isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] ) &&
527 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
529 // Categories are special
537 * Checks whether the user entered a skin name in uppercase,
538 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
542 protected function isWrongCaseCssJsPage() {
543 if ( $this->mTitle
->isCssJsSubpage() ) {
544 $name = $this->mTitle
->getSkinFromCssJsSubpage();
545 $skins = array_merge(
546 array_keys( Skin
::getSkinNames() ),
549 return !in_array( $name, $skins )
550 && in_array( strtolower( $name ), $skins );
557 * Does this EditPage class support section editing?
558 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
562 protected function isSectionEditSupported() {
567 * This function collects the form data and uses it to populate various member variables.
568 * @param $request WebRequest
570 function importFormData( &$request ) {
571 global $wgLang, $wgUser;
573 wfProfileIn( __METHOD__
);
575 # Section edit can come from either the form or a link
576 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
578 if ( $request->wasPosted() ) {
579 # These fields need to be checked for encoding.
580 # Also remove trailing whitespace, but don't remove _initial_
581 # whitespace from the text boxes. This may be significant formatting.
582 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
583 if ( !$request->getCheck( 'wpTextbox2' ) ) {
584 // Skip this if wpTextbox2 has input, it indicates that we came
585 // from a conflict page with raw page text, not a custom form
586 // modified by subclasses
587 wfProfileIn( get_class( $this ) . "::importContentFormData" );
588 $textbox1 = $this->importContentFormData( $request );
589 if ( isset( $textbox1 ) )
590 $this->textbox1
= $textbox1;
591 wfProfileOut( get_class( $this ) . "::importContentFormData" );
594 # Truncate for whole multibyte characters. +5 bytes for ellipsis
595 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
597 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
598 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
600 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
602 # Treat sectiontitle the same way as summary.
603 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
604 # currently doing double duty as both edit summary and section title. Right now this
605 # is just to allow API edits to work around this limitation, but this should be
606 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
607 $this->sectiontitle
= $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 250 );
608 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
610 $this->edittime
= $request->getVal( 'wpEdittime' );
611 $this->starttime
= $request->getVal( 'wpStarttime' );
613 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
615 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
616 // wpTextbox1 field is missing, possibly due to being "too big"
617 // according to some filter rules such as Suhosin's setting for
618 // suhosin.request.max_value_length (d'oh)
619 $this->incompleteForm
= true;
621 // edittime should be one of our last fields; if it's missing,
622 // the submission probably broke somewhere in the middle.
623 $this->incompleteForm
= is_null( $this->edittime
);
625 if ( $this->incompleteForm
) {
626 # If the form is incomplete, force to preview.
627 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
628 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
629 $this->preview
= true;
631 /* Fallback for live preview */
632 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
633 $this->diff
= $request->getCheck( 'wpDiff' );
635 // Remember whether a save was requested, so we can indicate
636 // if we forced preview due to session failure.
637 $this->mTriedSave
= !$this->preview
;
639 if ( $this->tokenOk( $request ) ) {
640 # Some browsers will not report any submit button
641 # if the user hits enter in the comment box.
642 # The unmarked state will be assumed to be a save,
643 # if the form seems otherwise complete.
644 wfDebug( __METHOD__
. ": Passed token check.\n" );
645 } elseif ( $this->diff
) {
646 # Failed token check, but only requested "Show Changes".
647 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
649 # Page might be a hack attempt posted from
650 # an external site. Preview instead of saving.
651 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
652 $this->preview
= true;
655 $this->save
= !$this->preview
&& !$this->diff
;
656 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
657 $this->edittime
= null;
660 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
661 $this->starttime
= null;
664 $this->recreate
= $request->getCheck( 'wpRecreate' );
666 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
667 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
669 # Don't force edit summaries when a user is editing their own user or talk page
670 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
671 $this->mTitle
->getText() == $wgUser->getName() )
673 $this->allowBlankSummary
= true;
675 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary' );
678 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
680 # Not a posted form? Start with nothing.
681 wfDebug( __METHOD__
. ": Not a posted form.\n" );
682 $this->textbox1
= '';
684 $this->sectiontitle
= '';
685 $this->edittime
= '';
686 $this->starttime
= wfTimestampNow();
688 $this->preview
= false;
691 $this->minoredit
= false;
692 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
693 $this->recreate
= false;
695 // When creating a new section, we can preload a section title by passing it as the
696 // preloadtitle parameter in the URL (Bug 13100)
697 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
698 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
699 // Once wpSummary isn't being use for setting section titles, we should delete this.
700 $this->summary
= $request->getVal( 'preloadtitle' );
702 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
703 $this->summary
= $request->getText( 'summary' );
704 if ( $this->summary
!== '' ) {
705 $this->hasPresetSummary
= true;
709 if ( $request->getVal( 'minor' ) ) {
710 $this->minoredit
= true;
714 $this->bot
= $request->getBool( 'bot', true );
715 $this->nosummary
= $request->getBool( 'nosummary' );
717 $this->oldid
= $request->getInt( 'oldid' );
719 $this->live
= $request->getCheck( 'live' );
720 $this->editintro
= $request->getText( 'editintro',
721 // Custom edit intro for new sections
722 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
724 // Allow extensions to modify form data
725 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
727 wfProfileOut( __METHOD__
);
731 * Subpage overridable method for extracting the page content data from the
732 * posted form to be placed in $this->textbox1, if using customized input
733 * this method should be overrided and return the page text that will be used
734 * for saving, preview parsing and so on...
736 * @param $request WebRequest
738 protected function importContentFormData( &$request ) {
739 return; // Don't do anything, EditPage already extracted wpTextbox1
743 * Initialise form fields in the object
744 * Called on the first invocation, e.g. when a user clicks an edit link
745 * @return bool -- if the requested section is valid
747 function initialiseForm() {
749 $this->edittime
= $this->mArticle
->getTimestamp();
750 $this->textbox1
= $this->getContent( false );
751 // activate checkboxes if user wants them to be always active
752 # Sort out the "watch" checkbox
753 if ( $wgUser->getOption( 'watchdefault' ) ) {
755 $this->watchthis
= true;
756 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
758 $this->watchthis
= true;
759 } elseif ( $this->mTitle
->userIsWatching() ) {
761 $this->watchthis
= true;
763 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
764 $this->minoredit
= true;
766 if ( $this->textbox1
=== false ) {
774 * Fetch initial editing page content.
776 * @param $def_text string
777 * @return mixed string on success, $def_text for invalid sections
780 function getContent( $def_text = '' ) {
781 global $wgOut, $wgRequest, $wgParser;
783 wfProfileIn( __METHOD__
);
787 // For message page not locally set, use the i18n message.
788 // For other non-existent articles, use preload text if any.
789 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
790 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
791 # If this is a system message, get the default text.
792 $text = $this->mTitle
->getDefaultMessageText();
794 if ( $text === false ) {
795 # If requested, preload some text.
796 $preload = $wgRequest->getVal( 'preload',
797 // Custom preload text for new sections
798 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
799 $text = $this->getPreloadedText( $preload );
801 // For existing pages, get text based on "undo" or section parameters.
803 if ( $this->section
!= '' ) {
804 // Get section edit text (returns $def_text for invalid sections)
805 $text = $wgParser->getSection( $this->getOriginalContent(), $this->section
, $def_text );
807 $undoafter = $wgRequest->getInt( 'undoafter' );
808 $undo = $wgRequest->getInt( 'undo' );
810 if ( $undo > 0 && $undoafter > 0 ) {
811 if ( $undo < $undoafter ) {
812 # If they got undoafter and undo round the wrong way, switch them
813 list( $undo, $undoafter ) = array( $undoafter, $undo );
816 $undorev = Revision
::newFromId( $undo );
817 $oldrev = Revision
::newFromId( $undoafter );
819 # Sanity check, make sure it's the right page,
820 # the revisions exist and they were not deleted.
821 # Otherwise, $text will be left as-is.
822 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
823 $undorev->getPage() == $oldrev->getPage() &&
824 $undorev->getPage() == $this->mTitle
->getArticleID() &&
825 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
826 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
828 $text = $this->mArticle
->getUndoText( $undorev, $oldrev );
829 if ( $text === false ) {
830 # Warn the user that something went wrong
831 $undoMsg = 'failure';
833 # Inform the user of our success and set an automatic edit summary
834 $undoMsg = 'success';
836 # If we just undid one rev, use an autosummary
837 $firstrev = $oldrev->getNext();
838 if ( $firstrev && $firstrev->getId() == $undo ) {
839 $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
840 if ( $this->summary
=== '' ) {
841 $this->summary
= $undoSummary;
843 $this->summary
= $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary
;
845 $this->undidRev
= $undo;
847 $this->formtype
= 'diff';
850 // Failed basic sanity checks.
851 // Older revisions may have been removed since the link
852 // was created, or we may simply have got bogus input.
856 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
857 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
858 wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
861 if ( $text === false ) {
862 $text = $this->getOriginalContent();
867 wfProfileOut( __METHOD__
);
872 * Get the content of the wanted revision, without section extraction.
874 * The result of this function can be used to compare user's input with
875 * section replaced in its context (using WikiPage::replaceSection())
876 * to the original text of the edit.
878 * This difers from Article::getContent() that when a missing revision is
879 * encountered the result will be an empty string and not the
880 * 'missing-article' message.
885 private function getOriginalContent() {
886 if ( $this->section
== 'new' ) {
887 return $this->getCurrentText();
889 $revision = $this->mArticle
->getRevisionFetched();
890 if ( $revision === null ) {
893 return $this->mArticle
->getContent();
897 * Get the actual text of the page. This is basically similar to
898 * WikiPage::getRawText() except that when the page doesn't exist an empty
899 * string is returned instead of false.
904 private function getCurrentText() {
905 $text = $this->mArticle
->getRawText();
906 if ( $text === false ) {
914 * Use this method before edit() to preload some text into the edit box
916 * @param $text string
918 public function setPreloadedText( $text ) {
919 $this->mPreloadText
= $text;
923 * Get the contents to be preloaded into the box, either set by
924 * an earlier setPreloadText() or by loading the given page.
926 * @param $preload String: representing the title to preload from.
929 protected function getPreloadedText( $preload ) {
930 global $wgUser, $wgParser;
932 if ( !empty( $this->mPreloadText
) ) {
933 return $this->mPreloadText
;
936 if ( $preload === '' ) {
940 $title = Title
::newFromText( $preload );
941 # Check for existence to avoid getting MediaWiki:Noarticletext
942 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
946 $page = WikiPage
::factory( $title );
947 if ( $page->isRedirect() ) {
948 $title = $page->getRedirectTarget();
950 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read' ) ) {
953 $page = WikiPage
::factory( $title );
956 $parserOptions = ParserOptions
::newFromUser( $wgUser );
957 return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
961 * Make sure the form isn't faking a user's credentials.
963 * @param $request WebRequest
967 function tokenOk( &$request ) {
969 $token = $request->getVal( 'wpEditToken' );
970 $this->mTokenOk
= $wgUser->matchEditToken( $token );
971 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
972 return $this->mTokenOk
;
977 * @return bool false if output is done, true if the rest of the form should be displayed
979 function attemptSave() {
980 global $wgUser, $wgOut;
982 $resultDetails = false;
983 # Allow bots to exempt some edits from bot flagging
984 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
985 $status = $this->internalAttemptSave( $resultDetails, $bot );
986 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
987 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
988 $this->didSave
= true;
991 switch ( $status->value
) {
992 case self
::AS_HOOK_ERROR_EXPECTED
:
993 case self
::AS_CONTENT_TOO_BIG
:
994 case self
::AS_ARTICLE_WAS_DELETED
:
995 case self
::AS_CONFLICT_DETECTED
:
996 case self
::AS_SUMMARY_NEEDED
:
997 case self
::AS_TEXTBOX_EMPTY
:
998 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1002 case self
::AS_HOOK_ERROR
:
1005 case self
::AS_SUCCESS_NEW_ARTICLE
:
1006 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1007 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1008 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1011 case self
::AS_SUCCESS_UPDATE
:
1013 $sectionanchor = $resultDetails['sectionanchor'];
1015 // Give extensions a chance to modify URL query on update
1016 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1018 if ( $resultDetails['redirect'] ) {
1019 if ( $extraQuery == '' ) {
1020 $extraQuery = 'redirect=no';
1022 $extraQuery = 'redirect=no&' . $extraQuery;
1025 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1028 case self
::AS_BLANK_ARTICLE
:
1029 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1032 case self
::AS_SPAM_ERROR
:
1033 $this->spamPageWithContent( $resultDetails['spam'] );
1036 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1037 throw new UserBlockedError( $wgUser->getBlock() );
1039 case self
::AS_IMAGE_REDIRECT_ANON
:
1040 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1041 throw new PermissionsError( 'upload' );
1043 case self
::AS_READ_ONLY_PAGE_ANON
:
1044 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1045 throw new PermissionsError( 'edit' );
1047 case self
::AS_READ_ONLY_PAGE
:
1048 throw new ReadOnlyError
;
1050 case self
::AS_RATE_LIMITED
:
1051 throw new ThrottledError();
1053 case self
::AS_NO_CREATE_PERMISSION
:
1054 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1055 throw new PermissionsError( $permission );
1058 // We don't recognize $status->value. The only way that can happen
1059 // is if an extension hook aborted from inside ArticleSave.
1060 // Render the status object into $this->hookError
1061 // FIXME this sucks, we should just use the Status object throughout
1062 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1070 * Attempt submission (no UI)
1075 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1077 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1078 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1079 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1081 function internalAttemptSave( &$result, $bot = false ) {
1082 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1084 $status = Status
::newGood();
1086 wfProfileIn( __METHOD__
);
1087 wfProfileIn( __METHOD__
. '-checks' );
1089 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1090 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1091 $status->fatal( 'hookaborted' );
1092 $status->value
= self
::AS_HOOK_ERROR
;
1093 wfProfileOut( __METHOD__
. '-checks' );
1094 wfProfileOut( __METHOD__
);
1098 # Check image redirect
1099 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1100 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
1101 !$wgUser->isAllowed( 'upload' ) ) {
1102 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1103 $status->setResult( false, $code );
1105 wfProfileOut( __METHOD__
. '-checks' );
1106 wfProfileOut( __METHOD__
);
1112 $match = self
::matchSummarySpamRegex( $this->summary
);
1113 if ( $match === false ) {
1114 $match = self
::matchSpamRegex( $this->textbox1
);
1116 if ( $match !== false ) {
1117 $result['spam'] = $match;
1118 $ip = $wgRequest->getIP();
1119 $pdbk = $this->mTitle
->getPrefixedDBkey();
1120 $match = str_replace( "\n", '', $match );
1121 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1122 $status->fatal( 'spamprotectionmatch', $match );
1123 $status->value
= self
::AS_SPAM_ERROR
;
1124 wfProfileOut( __METHOD__
. '-checks' );
1125 wfProfileOut( __METHOD__
);
1128 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1129 # Error messages etc. could be handled within the hook...
1130 $status->fatal( 'hookaborted' );
1131 $status->value
= self
::AS_HOOK_ERROR
;
1132 wfProfileOut( __METHOD__
. '-checks' );
1133 wfProfileOut( __METHOD__
);
1135 } elseif ( $this->hookError
!= '' ) {
1136 # ...or the hook could be expecting us to produce an error
1137 $status->fatal( 'hookaborted' );
1138 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1139 wfProfileOut( __METHOD__
. '-checks' );
1140 wfProfileOut( __METHOD__
);
1144 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1145 // Auto-block user's IP if the account was "hard" blocked
1146 $wgUser->spreadAnyEditBlock();
1147 # Check block state against master, thus 'false'.
1148 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1149 wfProfileOut( __METHOD__
. '-checks' );
1150 wfProfileOut( __METHOD__
);
1154 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1155 if ( $this->kblength
> $wgMaxArticleSize ) {
1156 // Error will be displayed by showEditForm()
1157 $this->tooBig
= true;
1158 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1159 wfProfileOut( __METHOD__
. '-checks' );
1160 wfProfileOut( __METHOD__
);
1164 if ( !$wgUser->isAllowed( 'edit' ) ) {
1165 if ( $wgUser->isAnon() ) {
1166 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1167 wfProfileOut( __METHOD__
. '-checks' );
1168 wfProfileOut( __METHOD__
);
1171 $status->fatal( 'readonlytext' );
1172 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1173 wfProfileOut( __METHOD__
. '-checks' );
1174 wfProfileOut( __METHOD__
);
1179 if ( wfReadOnly() ) {
1180 $status->fatal( 'readonlytext' );
1181 $status->value
= self
::AS_READ_ONLY_PAGE
;
1182 wfProfileOut( __METHOD__
. '-checks' );
1183 wfProfileOut( __METHOD__
);
1186 if ( $wgUser->pingLimiter() ) {
1187 $status->fatal( 'actionthrottledtext' );
1188 $status->value
= self
::AS_RATE_LIMITED
;
1189 wfProfileOut( __METHOD__
. '-checks' );
1190 wfProfileOut( __METHOD__
);
1194 # If the article has been deleted while editing, don't save it without
1196 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1197 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1198 wfProfileOut( __METHOD__
. '-checks' );
1199 wfProfileOut( __METHOD__
);
1203 wfProfileOut( __METHOD__
. '-checks' );
1205 // Use SELECT FOR UPDATE here to avoid transaction collision in
1206 // WikiPage::updateRevisionOn() and ending in the self::AS_END case.
1207 $this->mArticle
->loadPageData( 'forupdate' );
1208 $new = !$this->mArticle
->exists();
1211 // Late check for create permission, just in case *PARANOIA*
1212 if ( !$this->mTitle
->userCan( 'create' ) ) {
1213 $status->fatal( 'nocreatetext' );
1214 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1215 wfDebug( __METHOD__
. ": no create permission\n" );
1216 wfProfileOut( __METHOD__
);
1220 # Don't save a new article if it's blank.
1221 if ( $this->textbox1
== '' ) {
1222 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1223 wfProfileOut( __METHOD__
);
1227 // Run post-section-merge edit filter
1228 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1229 # Error messages etc. could be handled within the hook...
1230 $status->fatal( 'hookaborted' );
1231 $status->value
= self
::AS_HOOK_ERROR
;
1232 wfProfileOut( __METHOD__
);
1234 } elseif ( $this->hookError
!= '' ) {
1235 # ...or the hook could be expecting us to produce an error
1236 $status->fatal( 'hookaborted' );
1237 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1238 wfProfileOut( __METHOD__
);
1242 $text = $this->textbox1
;
1243 $result['sectionanchor'] = '';
1244 if ( $this->section
== 'new' ) {
1245 if ( $this->sectiontitle
!== '' ) {
1246 // Insert the section title above the content.
1247 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle
) . "\n\n" . $text;
1249 // Jump to the new section
1250 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1252 // If no edit summary was specified, create one automatically from the section
1253 // title and have it link to the new section. Otherwise, respect the summary as
1255 if ( $this->summary
=== '' ) {
1256 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1257 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1259 } elseif ( $this->summary
!== '' ) {
1260 // Insert the section title above the content.
1261 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $text;
1263 // Jump to the new section
1264 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1266 // Create a link to the new section from the edit summary.
1267 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1268 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1272 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1276 # Article exists. Check for edit conflict.
1277 $timestamp = $this->mArticle
->getTimestamp();
1278 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1280 if ( $timestamp != $this->edittime
) {
1281 $this->isConflict
= true;
1282 if ( $this->section
== 'new' ) {
1283 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1284 $this->mArticle
->getComment() == $this->summary
) {
1285 // Probably a duplicate submission of a new comment.
1286 // This can happen when squid resends a request after
1287 // a timeout but the first one actually went through.
1288 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1290 // New comment; suppress conflict.
1291 $this->isConflict
= false;
1292 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1294 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1295 # Suppress edit conflict with self, except for section edits where merging is required.
1296 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1297 $this->isConflict
= false;
1301 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1302 // backwards compatibility with old forms/bots).
1303 if ( $this->sectiontitle
!== '' ) {
1304 $sectionTitle = $this->sectiontitle
;
1306 $sectionTitle = $this->summary
;
1309 if ( $this->isConflict
) {
1310 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1311 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle, $this->edittime
);
1313 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1314 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $sectionTitle );
1316 if ( is_null( $text ) ) {
1317 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1318 $this->isConflict
= true;
1319 $text = $this->textbox1
; // do not try to merge here!
1320 } elseif ( $this->isConflict
) {
1322 if ( $this->mergeChangesInto( $text ) ) {
1323 // Successful merge! Maybe we should tell the user the good news?
1324 $this->isConflict
= false;
1325 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1327 $this->section
= '';
1328 $this->textbox1
= $text;
1329 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1333 if ( $this->isConflict
) {
1334 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1335 wfProfileOut( __METHOD__
);
1339 // Run post-section-merge edit filter
1340 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
1341 # Error messages etc. could be handled within the hook...
1342 $status->fatal( 'hookaborted' );
1343 $status->value
= self
::AS_HOOK_ERROR
;
1344 wfProfileOut( __METHOD__
);
1346 } elseif ( $this->hookError
!= '' ) {
1347 # ...or the hook could be expecting us to produce an error
1348 $status->fatal( 'hookaborted' );
1349 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1350 wfProfileOut( __METHOD__
);
1354 # Handle the user preference to force summaries here, but not for null edits
1355 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1356 && $this->getOriginalContent() != $text
1357 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1359 if ( md5( $this->summary
) == $this->autoSumm
) {
1360 $this->missingSummary
= true;
1361 $status->fatal( 'missingsummary' );
1362 $status->value
= self
::AS_SUMMARY_NEEDED
;
1363 wfProfileOut( __METHOD__
);
1368 # And a similar thing for new sections
1369 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1370 if ( trim( $this->summary
) == '' ) {
1371 $this->missingSummary
= true;
1372 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1373 $status->value
= self
::AS_SUMMARY_NEEDED
;
1374 wfProfileOut( __METHOD__
);
1380 wfProfileIn( __METHOD__
. '-sectionanchor' );
1381 $sectionanchor = '';
1382 if ( $this->section
== 'new' ) {
1383 if ( $this->textbox1
== '' ) {
1384 $this->missingComment
= true;
1385 $status->fatal( 'missingcommenttext' );
1386 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1387 wfProfileOut( __METHOD__
. '-sectionanchor' );
1388 wfProfileOut( __METHOD__
);
1391 if ( $this->sectiontitle
!== '' ) {
1392 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1393 // If no edit summary was specified, create one automatically from the section
1394 // title and have it link to the new section. Otherwise, respect the summary as
1396 if ( $this->summary
=== '' ) {
1397 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1398 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1400 } elseif ( $this->summary
!== '' ) {
1401 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1402 # This is a new section, so create a link to the new section
1403 # in the revision summary.
1404 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1405 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1407 } elseif ( $this->section
!= '' ) {
1408 # Try to get a section anchor from the section source, redirect to edited section if header found
1409 # XXX: might be better to integrate this into Article::replaceSection
1410 # for duplicate heading checking and maybe parsing
1411 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1412 # we can't deal with anchors, includes, html etc in the header for now,
1413 # headline would need to be parsed to improve this
1414 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1415 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1418 $result['sectionanchor'] = $sectionanchor;
1419 wfProfileOut( __METHOD__
. '-sectionanchor' );
1421 // Save errors may fall down to the edit form, but we've now
1422 // merged the section into full text. Clear the section field
1423 // so that later submission of conflict forms won't try to
1424 // replace that into a duplicated mess.
1425 $this->textbox1
= $text;
1426 $this->section
= '';
1428 $status->value
= self
::AS_SUCCESS_UPDATE
;
1431 // Check for length errors again now that the section is merged in
1432 $this->kblength
= (int)( strlen( $text ) / 1024 );
1433 if ( $this->kblength
> $wgMaxArticleSize ) {
1434 $this->tooBig
= true;
1435 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1436 wfProfileOut( __METHOD__
);
1440 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1441 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1442 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1443 ( $bot ? EDIT_FORCE_BOT
: 0 );
1445 $doEditStatus = $this->mArticle
->doEdit( $text, $this->summary
, $flags );
1447 if ( $doEditStatus->isOK() ) {
1448 $result['redirect'] = Title
::newFromRedirect( $text ) !== null;
1449 $this->commitWatch();
1450 wfProfileOut( __METHOD__
);
1453 // Failure from doEdit()
1454 // Show the edit conflict page for certain recognized errors from doEdit(),
1455 // but don't show it for errors from extension hooks
1456 $errors = $doEditStatus->getErrorsArray();
1457 if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
1458 'edit-already-exists' ) ) )
1460 $this->isConflict
= true;
1461 // Destroys data doEdit() put in $status->value but who cares
1462 $doEditStatus->value
= self
::AS_END
;
1464 wfProfileOut( __METHOD__
);
1465 return $doEditStatus;
1470 * Commit the change of watch status
1472 protected function commitWatch() {
1474 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1475 $dbw = wfGetDB( DB_MASTER
);
1476 $dbw->begin( __METHOD__
);
1477 if ( $this->watchthis
) {
1478 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1480 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1482 $dbw->commit( __METHOD__
);
1487 * Check if no edits were made by other users since
1488 * the time a user started editing the page. Limit to
1489 * 50 revisions for the sake of performance.
1492 * @param $edittime string
1496 protected function userWasLastToEdit( $id, $edittime ) {
1497 if ( !$id ) return false;
1498 $dbw = wfGetDB( DB_MASTER
);
1499 $res = $dbw->select( 'revision',
1502 'rev_page' => $this->mTitle
->getArticleID(),
1503 'rev_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $edittime ) )
1506 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1507 foreach ( $res as $row ) {
1508 if ( $row->rev_user
!= $id ) {
1519 * @parma $editText string
1523 function mergeChangesInto( &$editText ) {
1524 wfProfileIn( __METHOD__
);
1526 $db = wfGetDB( DB_MASTER
);
1528 // This is the revision the editor started from
1529 $baseRevision = $this->getBaseRevision();
1530 if ( is_null( $baseRevision ) ) {
1531 wfProfileOut( __METHOD__
);
1534 $baseText = $baseRevision->getText();
1536 // The current state, we want to merge updates into it
1537 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1538 if ( is_null( $currentRevision ) ) {
1539 wfProfileOut( __METHOD__
);
1542 $currentText = $currentRevision->getText();
1545 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1546 $editText = $result;
1547 wfProfileOut( __METHOD__
);
1550 wfProfileOut( __METHOD__
);
1558 function getBaseRevision() {
1559 if ( !$this->mBaseRevision
) {
1560 $db = wfGetDB( DB_MASTER
);
1561 $baseRevision = Revision
::loadFromTimestamp(
1562 $db, $this->mTitle
, $this->edittime
);
1563 return $this->mBaseRevision
= $baseRevision;
1565 return $this->mBaseRevision
;
1570 * Check given input text against $wgSpamRegex, and return the text of the first match.
1572 * @param $text string
1574 * @return string|bool matching string or false
1576 public static function matchSpamRegex( $text ) {
1577 global $wgSpamRegex;
1578 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1579 $regexes = (array)$wgSpamRegex;
1580 return self
::matchSpamRegexInternal( $text, $regexes );
1584 * Check given input text against $wgSpamRegex, and return the text of the first match.
1586 * @parma $text string
1588 * @return string|bool matching string or false
1590 public static function matchSummarySpamRegex( $text ) {
1591 global $wgSummarySpamRegex;
1592 $regexes = (array)$wgSummarySpamRegex;
1593 return self
::matchSpamRegexInternal( $text, $regexes );
1597 * @param $text string
1598 * @param $regexes array
1599 * @return bool|string
1601 protected static function matchSpamRegexInternal( $text, $regexes ) {
1602 foreach ( $regexes as $regex ) {
1604 if ( preg_match( $regex, $text, $matches ) ) {
1611 function setHeaders() {
1612 global $wgOut, $wgUser;
1614 $wgOut->addModules( 'mediawiki.action.edit' );
1616 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1617 $wgOut->addModules( 'mediawiki.legacy.preview' );
1619 // Bug #19334: textarea jumps when editing articles in IE8
1620 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1622 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1624 # Enabled article-related sidebar, toplinks, etc.
1625 $wgOut->setArticleRelated( true );
1627 $contextTitle = $this->getContextTitle();
1628 if ( $this->isConflict
) {
1629 $msg = 'editconflict';
1630 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1631 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1633 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1634 'editing' : 'creating';
1636 # Use the title defined by DISPLAYTITLE magic word when present
1637 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1638 if ( $displayTitle === false ) {
1639 $displayTitle = $contextTitle->getPrefixedText();
1641 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1645 * Show all applicable editing introductions
1647 protected function showIntro() {
1648 global $wgOut, $wgUser;
1649 if ( $this->suppressIntro
) {
1653 $namespace = $this->mTitle
->getNamespace();
1655 if ( $namespace == NS_MEDIAWIKI
) {
1656 # Show a warning if editing an interface message
1657 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1658 } else if( $namespace == NS_FILE
) {
1659 # Show a hint to shared repo
1660 $file = wfFindFile( $this->mTitle
);
1661 if( $file && !$file->isLocal() ) {
1662 $descUrl = $file->getDescriptionUrl();
1663 # there must be a description url to show a hint to shared repo
1665 if( !$this->mTitle
->exists() ) {
1666 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1667 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1670 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1671 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1678 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1679 # Show log extract when the user is currently blocked
1680 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1681 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1682 $username = $parts[0];
1683 $user = User
::newFromName( $username, false /* allow IP users*/ );
1684 $ip = User
::isIP( $username );
1685 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1686 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1687 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1688 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1689 LogEventsList
::showLogExtract(
1692 $user->getUserPage(),
1696 'showIfEmpty' => false,
1698 'blocked-notice-logextract',
1699 $user->getName() # Support GENDER in notice
1705 # Try to add a custom edit intro, or use the standard one if this is not possible.
1706 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1707 if ( $wgUser->isLoggedIn() ) {
1708 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1710 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1713 # Give a notice if the user is editing a deleted/moved page...
1714 if ( !$this->mTitle
->exists() ) {
1715 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1716 '', array( 'lim' => 10,
1717 'conds' => array( "log_action != 'revision'" ),
1718 'showIfEmpty' => false,
1719 'msgKey' => array( 'recreate-moveddeleted-warn' ) )
1725 * Attempt to show a custom editing introduction, if supplied
1729 protected function showCustomIntro() {
1730 if ( $this->editintro
) {
1731 $title = Title
::newFromText( $this->editintro
);
1732 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
1734 // Added using template syntax, to take <noinclude>'s into account.
1735 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
1746 * Send the edit form and related headers to $wgOut
1747 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1748 * during form output near the top, for captchas and the like.
1750 function showEditForm( $formCallback = null ) {
1751 global $wgOut, $wgUser;
1753 wfProfileIn( __METHOD__
);
1755 # need to parse the preview early so that we know which templates are used,
1756 # otherwise users with "show preview after edit box" will get a blank list
1757 # we parse this near the beginning so that setHeaders can do the title
1758 # setting work instead of leaving it in getPreviewText
1759 $previewOutput = '';
1760 if ( $this->formtype
== 'preview' ) {
1761 $previewOutput = $this->getPreviewText();
1764 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
1766 $this->setHeaders();
1768 if ( $this->showHeader() === false ) {
1769 wfProfileOut( __METHOD__
);
1773 $wgOut->addHTML( $this->editFormPageTop
);
1775 if ( $wgUser->getOption( 'previewontop' ) ) {
1776 $this->displayPreviewArea( $previewOutput, true );
1779 $wgOut->addHTML( $this->editFormTextTop
);
1781 $showToolbar = true;
1782 if ( $this->wasDeletedSinceLastEdit() ) {
1783 if ( $this->formtype
== 'save' ) {
1784 // Hide the toolbar and edit area, user can click preview to get it back
1785 // Add an confirmation checkbox and explanation.
1786 $showToolbar = false;
1788 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1789 'deletedwhileediting' );
1793 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => self
::EDITFORM_ID
, 'name' => self
::EDITFORM_ID
,
1794 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1795 'enctype' => 'multipart/form-data' ) ) );
1797 if ( is_callable( $formCallback ) ) {
1798 call_user_func_array( $formCallback, array( &$wgOut ) );
1801 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1803 // Put these up at the top to ensure they aren't lost on early form submission
1804 $this->showFormBeforeText();
1806 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1807 $username = $this->lastDelete
->user_name
;
1808 $comment = $this->lastDelete
->log_comment
;
1810 // It is better to not parse the comment at all than to have templates expanded in the middle
1811 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1812 $key = $comment === ''
1813 ?
'confirmrecreate-noreason'
1814 : 'confirmrecreate';
1816 '<div class="mw-confirm-recreate">' .
1817 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1818 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1819 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1825 # When the summary is hidden, also hide them on preview/show changes
1826 if( $this->nosummary
) {
1827 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
1830 # If a blank edit summary was previously provided, and the appropriate
1831 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1832 # user being bounced back more than once in the event that a summary
1835 # For a bit more sophisticated detection of blank summaries, hash the
1836 # automatic one and pass that in the hidden field wpAutoSummary.
1837 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
1838 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1841 if ( $this->hasPresetSummary
) {
1842 // If a summary has been preset using &summary= we dont want to prompt for
1843 // a different summary. Only prompt for a summary if the summary is blanked.
1845 $this->autoSumm
= md5( '' );
1848 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1849 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1851 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
1853 if ( $this->section
== 'new' ) {
1854 $this->showSummaryInput( true, $this->summary
);
1855 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1858 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1860 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1861 $wgOut->addHTML( EditPage
::getEditToolbar() );
1864 if ( $this->isConflict
) {
1865 // In an edit conflict bypass the overrideable content form method
1866 // and fallback to the raw wpTextbox1 since editconflicts can't be
1867 // resolved between page source edits and custom ui edits using the
1869 $this->textbox2
= $this->textbox1
;
1870 $this->textbox1
= $this->getCurrentText();
1872 $this->showTextbox1();
1874 $this->showContentForm();
1877 $wgOut->addHTML( $this->editFormTextAfterContent
);
1879 $wgOut->addWikiText( $this->getCopywarn() );
1881 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1883 $this->showStandardInputs();
1885 $this->showFormAfterText();
1887 $this->showTosSummary();
1889 $this->showEditTools();
1891 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
1893 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
1894 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
1896 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
1897 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
1899 if ( $this->isConflict
) {
1900 $this->showConflict();
1903 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
1905 if ( !$wgUser->getOption( 'previewontop' ) ) {
1906 $this->displayPreviewArea( $previewOutput, false );
1909 wfProfileOut( __METHOD__
);
1913 * Extract the section title from current section text, if any.
1915 * @param string $text
1916 * @return Mixed|string or false
1918 public static function extractSectionTitle( $text ) {
1919 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
1920 if ( !empty( $matches[2] ) ) {
1922 return $wgParser->stripSectionName( trim( $matches[2] ) );
1928 protected function showHeader() {
1929 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1931 if ( $this->mTitle
->isTalkPage() ) {
1932 $wgOut->addWikiMsg( 'talkpagetext' );
1935 # Optional notices on a per-namespace and per-page basis
1936 $editnotice_ns = 'editnotice-' . $this->mTitle
->getNamespace();
1937 $editnotice_ns_message = wfMessage( $editnotice_ns );
1938 if ( $editnotice_ns_message->exists() ) {
1939 $wgOut->addWikiText( $editnotice_ns_message->plain() );
1941 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
1942 $parts = explode( '/', $this->mTitle
->getDBkey() );
1943 $editnotice_base = $editnotice_ns;
1944 while ( count( $parts ) > 0 ) {
1945 $editnotice_base .= '-' . array_shift( $parts );
1946 $editnotice_base_msg = wfMessage( $editnotice_base );
1947 if ( $editnotice_base_msg->exists() ) {
1948 $wgOut->addWikiText( $editnotice_base_msg->plain() );
1952 # Even if there are no subpages in namespace, we still don't want / in MW ns.
1953 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
1954 $editnoticeMsg = wfMessage( $editnoticeText );
1955 if ( $editnoticeMsg->exists() ) {
1956 $wgOut->addWikiText( $editnoticeMsg->plain() );
1960 if ( $this->isConflict
) {
1961 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1962 $this->edittime
= $this->mArticle
->getTimestamp();
1964 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
1965 // We use $this->section to much before this and getVal('wgSection') directly in other places
1966 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1967 // Someone is welcome to try refactoring though
1968 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1972 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1973 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1974 $sectionTitle = self
::extractSectionTitle( $this->textbox1
);
1975 if ( $sectionTitle !== false ) {
1976 $this->summary
= "/* $sectionTitle */ ";
1981 if ( $this->missingComment
) {
1982 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1985 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1986 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1989 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1990 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1993 if ( $this->hookError
!== '' ) {
1994 $wgOut->addWikiText( $this->hookError
);
1997 if ( !$this->checkUnicodeCompliantBrowser() ) {
1998 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2001 if ( $this->section
!= 'new' ) {
2002 $revision = $this->mArticle
->getRevisionFetched();
2004 // Let sysop know that this will make private content public if saved
2006 if ( !$revision->userCan( Revision
::DELETED_TEXT
) ) {
2007 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2008 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2009 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2012 if ( !$revision->isCurrent() ) {
2013 $this->mArticle
->setOldSubtitle( $revision->getId() );
2014 $wgOut->addWikiMsg( 'editingold' );
2016 } elseif ( $this->mTitle
->exists() ) {
2017 // Something went wrong
2019 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2020 array( 'missing-article', $this->mTitle
->getPrefixedText(),
2021 wfMsgNoTrans( 'missingarticle-rev', $this->oldid
) ) );
2026 if ( wfReadOnly() ) {
2027 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2028 } elseif ( $wgUser->isAnon() ) {
2029 if ( $this->formtype
!= 'preview' ) {
2030 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2032 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2035 if ( $this->isCssJsSubpage
) {
2036 # Check the skin exists
2037 if ( $this->isWrongCaseCssJsPage
) {
2038 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2040 if ( $this->formtype
!== 'preview' ) {
2041 if ( $this->isCssSubpage
)
2042 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2043 if ( $this->isJsSubpage
)
2044 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2049 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2050 # Is the title semi-protected?
2051 if ( $this->mTitle
->isSemiProtected() ) {
2052 $noticeMsg = 'semiprotectedpagewarning';
2054 # Then it must be protected based on static groups (regular)
2055 $noticeMsg = 'protectedpagewarning';
2057 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2058 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2060 if ( $this->mTitle
->isCascadeProtected() ) {
2061 # Is this page under cascading protection from some source pages?
2062 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2063 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2064 $cascadeSourcesCount = count( $cascadeSources );
2065 if ( $cascadeSourcesCount > 0 ) {
2066 # Explain, and list the titles responsible
2067 foreach ( $cascadeSources as $page ) {
2068 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2071 $notice .= '</div>';
2072 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2074 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2075 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2077 'showIfEmpty' => false,
2078 'msgKey' => array( 'titleprotectedwarning' ),
2079 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2082 if ( $this->kblength
=== false ) {
2083 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2086 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2087 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2088 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2090 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2091 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2092 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2099 * Standard summary input and label (wgSummary), abstracted so EditPage
2100 * subclasses may reorganize the form.
2101 * Note that you do not need to worry about the label's for=, it will be
2102 * inferred by the id given to the input. You can remove them both by
2103 * passing array( 'id' => false ) to $userInputAttrs.
2105 * @param $summary string The value of the summary input
2106 * @param $labelText string The html to place inside the label
2107 * @param $inputAttrs array of attrs to use on the input
2108 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2110 * @return array An array in the format array( $label, $input )
2112 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2113 // Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
2114 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2115 'id' => 'wpSummary',
2116 'maxlength' => '200',
2119 'spellcheck' => 'true',
2120 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2122 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2123 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2124 'id' => "wpSummaryLabel"
2129 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2130 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2133 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2135 return array( $label, $input );
2139 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2140 * up top, or false if this is the comment summary
2141 * down below the textarea
2142 * @param $summary String: The text of the summary to display
2145 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2146 global $wgOut, $wgContLang;
2147 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2148 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2149 if ( $isSubjectPreview ) {
2150 if ( $this->nosummary
) {
2154 if ( !$this->mShowSummaryField
) {
2158 $summary = $wgContLang->recodeForEdit( $summary );
2159 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
2160 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2161 $wgOut->addHTML( "{$label} {$input}" );
2165 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2166 * up top, or false if this is the comment summary
2167 * down below the textarea
2168 * @param $summary String: the text of the summary to display
2171 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2172 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
2177 if ( $isSubjectPreview )
2178 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2180 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2182 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2183 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2186 protected function showFormBeforeText() {
2188 $section = htmlspecialchars( $this->section
);
2189 $wgOut->addHTML( <<<HTML
2190 <input type='hidden' value="{$section}" name="wpSection" />
2191 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2192 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2193 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2197 if ( !$this->checkUnicodeCompliantBrowser() )
2198 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2201 protected function showFormAfterText() {
2202 global $wgOut, $wgUser;
2204 * To make it harder for someone to slip a user a page
2205 * which submits an edit form to the wiki without their
2206 * knowledge, a random token is associated with the login
2207 * session. If it's not passed back with the submission,
2208 * we won't save the page, or render user JavaScript and
2211 * For anon editors, who may not have a session, we just
2212 * include the constant suffix to prevent editing from
2213 * broken text-mangling proxies.
2215 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2219 * Subpage overridable method for printing the form for page content editing
2220 * By default this simply outputs wpTextbox1
2221 * Subclasses can override this to provide a custom UI for editing;
2222 * be it a form, or simply wpTextbox1 with a modified content that will be
2223 * reverse modified when extracted from the post data.
2224 * Note that this is basically the inverse for importContentFormData
2226 protected function showContentForm() {
2227 $this->showTextbox1();
2231 * Method to output wpTextbox1
2232 * The $textoverride method can be used by subclasses overriding showContentForm
2233 * to pass back to this method.
2235 * @param $customAttribs array of html attributes to use in the textarea
2236 * @param $textoverride String: optional text to override $this->textarea1 with
2238 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2239 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2240 $attribs = array( 'style' => 'display:none;' );
2242 $classes = array(); // Textarea CSS
2243 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2244 # Is the title semi-protected?
2245 if ( $this->mTitle
->isSemiProtected() ) {
2246 $classes[] = 'mw-textarea-sprotected';
2248 # Then it must be protected based on static groups (regular)
2249 $classes[] = 'mw-textarea-protected';
2251 # Is the title cascade-protected?
2252 if ( $this->mTitle
->isCascadeProtected() ) {
2253 $classes[] = 'mw-textarea-cprotected';
2257 $attribs = array( 'tabindex' => 1 );
2259 if ( is_array( $customAttribs ) ) {
2260 $attribs +
= $customAttribs;
2263 if ( count( $classes ) ) {
2264 if ( isset( $attribs['class'] ) ) {
2265 $classes[] = $attribs['class'];
2267 $attribs['class'] = implode( ' ', $classes );
2271 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2274 protected function showTextbox2() {
2275 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2278 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2279 global $wgOut, $wgUser;
2281 $wikitext = $this->safeUnicodeOutput( $content );
2282 if ( strval( $wikitext ) !== '' ) {
2283 // Ensure there's a newline at the end, otherwise adding lines
2285 // But don't add a newline if the ext is empty, or Firefox in XHTML
2286 // mode will show an extra newline. A bit annoying.
2290 $attribs = $customAttribs +
array(
2293 'cols' => $wgUser->getIntOption( 'cols' ),
2294 'rows' => $wgUser->getIntOption( 'rows' ),
2295 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2298 $pageLang = $this->mTitle
->getPageLanguage();
2299 $attribs['lang'] = $pageLang->getCode();
2300 $attribs['dir'] = $pageLang->getDir();
2302 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2305 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2309 $classes[] = 'ontop';
2311 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2313 if ( $this->formtype
!= 'preview' )
2314 $attribs['style'] = 'display: none;';
2316 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2318 if ( $this->formtype
== 'preview' ) {
2319 $this->showPreview( $previewOutput );
2322 $wgOut->addHTML( '</div>' );
2324 if ( $this->formtype
== 'diff' ) {
2330 * Append preview output to $wgOut.
2331 * Includes category rendering if this is a category page.
2333 * @param $text String: the HTML to be output for the preview.
2335 protected function showPreview( $text ) {
2337 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2338 $this->mArticle
->openShowCategory();
2340 # This hook seems slightly odd here, but makes things more
2341 # consistent for extensions.
2342 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2343 $wgOut->addHTML( $text );
2344 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2345 $this->mArticle
->closeShowCategory();
2350 * Get a diff between the current contents of the edit box and the
2351 * version of the page we're editing from.
2353 * If this is a section edit, we'll replace the section as for final
2354 * save and then make a comparison.
2356 function showDiff() {
2357 global $wgUser, $wgContLang, $wgParser, $wgOut;
2359 $oldtitlemsg = 'currentrev';
2360 # if message does not exist, show diff against the preloaded default
2361 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2362 $oldtext = $this->mTitle
->getDefaultMessageText();
2363 if( $oldtext !== false ) {
2364 $oldtitlemsg = 'defaultmessagetext';
2367 $oldtext = $this->mArticle
->getRawText();
2369 $newtext = $this->mArticle
->replaceSection(
2370 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2372 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2374 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2375 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle
, $wgUser, $popts );
2377 if ( $oldtext !== false ||
$newtext != '' ) {
2378 $oldtitle = wfMsgExt( $oldtitlemsg, array( 'parseinline' ) );
2379 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2381 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2382 $de->setText( $oldtext, $newtext );
2383 $difftext = $de->getDiff( $oldtitle, $newtitle );
2384 $de->showDiffStyle();
2389 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2393 * Give a chance for site and per-namespace customizations of
2394 * terms of service summary link that might exist separately
2395 * from the copyright notice.
2397 * This will display between the save button and the edit tools,
2398 * so should remain short!
2400 protected function showTosSummary() {
2401 $msg = 'editpage-tos-summary';
2402 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2403 if ( !wfMessage( $msg )->isDisabled() ) {
2405 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2406 $wgOut->addWikiMsg( $msg );
2407 $wgOut->addHTML( '</div>' );
2411 protected function showEditTools() {
2413 $wgOut->addHTML( '<div class="mw-editTools">' .
2414 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2418 protected function getCopywarn() {
2419 global $wgRightsText;
2420 if ( $wgRightsText ) {
2421 $copywarnMsg = array( 'copyrightwarning',
2422 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2425 $copywarnMsg = array( 'copyrightwarning2',
2426 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2428 // Allow for site and per-namespace customization of contribution/copyright notice.
2429 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
2431 return "<div id=\"editpage-copywarn\">\n" .
2432 call_user_func_array( "wfMsgNoTrans", $copywarnMsg ) . "\n</div>";
2435 protected function showStandardInputs( &$tabindex = 2 ) {
2437 $wgOut->addHTML( "<div class='editOptions'>\n" );
2439 if ( $this->section
!= 'new' ) {
2440 $this->showSummaryInput( false, $this->summary
);
2441 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2444 $checkboxes = $this->getCheckboxes( $tabindex,
2445 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2446 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2447 $wgOut->addHTML( "<div class='editButtons'>\n" );
2448 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2450 $cancel = $this->getCancelLink();
2451 if ( $cancel !== '' ) {
2452 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2454 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2455 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2456 htmlspecialchars( wfMsg( 'edithelp' ) ) . '</a> ' .
2457 htmlspecialchars( wfMsg( 'newwindow' ) );
2458 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2459 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2463 * Show an edit conflict. textbox1 is already shown in showEditForm().
2464 * If you want to use another entry point to this function, be careful.
2466 protected function showConflict() {
2469 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2470 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2472 $de = new DifferenceEngine( $this->mArticle
->getContext() );
2473 $de->setText( $this->textbox2
, $this->textbox1
);
2474 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2476 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2477 $this->showTextbox2();
2484 public function getCancelLink() {
2485 $cancelParams = array();
2486 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2487 $cancelParams['oldid'] = $this->oldid
;
2490 return Linker
::linkKnown(
2491 $this->getContextTitle(),
2492 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2493 array( 'id' => 'mw-editform-cancel' ),
2499 * Returns the URL to use in the form's action attribute.
2500 * This is used by EditPage subclasses when simply customizing the action
2501 * variable in the constructor is not enough. This can be used when the
2502 * EditPage lives inside of a Special page rather than a custom page action.
2504 * @param $title Title object for which is being edited (where we go to for &action= links)
2507 protected function getActionURL( Title
$title ) {
2508 return $title->getLocalURL( array( 'action' => $this->action
) );
2512 * Check if a page was deleted while the user was editing it, before submit.
2513 * Note that we rely on the logging table, which hasn't been always there,
2514 * but that doesn't matter, because this only applies to brand new
2517 protected function wasDeletedSinceLastEdit() {
2518 if ( $this->deletedSinceEdit
!== null ) {
2519 return $this->deletedSinceEdit
;
2522 $this->deletedSinceEdit
= false;
2524 if ( $this->mTitle
->isDeletedQuick() ) {
2525 $this->lastDelete
= $this->getLastDelete();
2526 if ( $this->lastDelete
) {
2527 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2528 if ( $deleteTime > $this->starttime
) {
2529 $this->deletedSinceEdit
= true;
2534 return $this->deletedSinceEdit
;
2537 protected function getLastDelete() {
2538 $dbr = wfGetDB( DB_SLAVE
);
2539 $data = $dbr->selectRow(
2540 array( 'logging', 'user' ),
2551 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2552 'log_title' => $this->mTitle
->getDBkey(),
2553 'log_type' => 'delete',
2554 'log_action' => 'delete',
2555 'user_id=log_user' ),
2557 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2559 // Quick paranoid permission checks...
2560 if ( is_object( $data ) ) {
2561 if ( $data->log_deleted
& LogPage
::DELETED_USER
)
2562 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2563 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2564 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2570 * Get the rendered text for previewing.
2573 function getPreviewText() {
2574 global $wgOut, $wgUser, $wgParser, $wgRawHtml, $wgLang;
2576 wfProfileIn( __METHOD__
);
2578 if ( $wgRawHtml && !$this->mTokenOk
) {
2579 // Could be an offsite preview attempt. This is very unsafe if
2580 // HTML is enabled, as it could be an attack.
2582 if ( $this->textbox1
!== '' ) {
2583 // Do not put big scary notice, if previewing the empty
2584 // string, which happens when you initially edit
2585 // a category page, due to automatic preview-on-open.
2586 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2587 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2589 wfProfileOut( __METHOD__
);
2593 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2594 if ( $this->mTokenOkExceptSuffix
) {
2595 $note = wfMsg( 'token_suffix_mismatch' );
2597 $note = wfMsg( 'session_fail_preview' );
2599 } elseif ( $this->incompleteForm
) {
2600 $note = wfMsg( 'edit_form_incomplete' );
2602 $note = wfMsg( 'previewnote' ) .
2603 ' [[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' . wfMsg( 'continue-editing' ) . ']]';
2606 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2607 $parserOptions->setEditSection( false );
2608 $parserOptions->setTidy( true );
2609 $parserOptions->setIsPreview( true );
2610 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
2612 # don't parse non-wikitext pages, show message about preview
2613 if ( $this->mTitle
->isCssJsSubpage() ||
!$this->mTitle
->isWikitextPage() ) {
2614 if ( $this->mTitle
->isCssJsSubpage() ) {
2616 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
2622 # Used messages to make sure grep find them:
2623 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2626 if ( preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2627 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2628 $class .= " mw-css";
2629 } elseif ( preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2630 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2633 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2635 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2636 $previewHTML = $parserOutput->getText();
2641 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2643 $toparse = $this->textbox1
;
2645 # If we're adding a comment, we need to show the
2646 # summary as the headline
2647 if ( $this->section
== "new" && $this->summary
!= "" ) {
2648 $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $toparse;
2651 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2653 $parserOptions->enableLimitReport();
2655 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle
, $wgUser, $parserOptions );
2656 $parserOutput = $wgParser->parse( $toparse, $this->mTitle
, $parserOptions );
2658 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2660 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2662 $previewHTML = $parserOutput->getText();
2665 $this->mParserOutput
= $parserOutput;
2666 $wgOut->addParserOutputNoText( $parserOutput );
2668 if ( count( $parserOutput->getWarnings() ) ) {
2669 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2673 if ( $this->isConflict
) {
2674 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2676 $conflict = '<hr />';
2679 $previewhead = "<div class='previewnote'>\n" .
2680 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2681 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2683 $pageLang = $this->mTitle
->getPageLanguage();
2684 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2685 'class' => 'mw-content-' . $pageLang->getDir() );
2686 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2688 wfProfileOut( __METHOD__
);
2689 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2695 function getTemplates() {
2696 if ( $this->preview ||
$this->section
!= '' ) {
2697 $templates = array();
2698 if ( !isset( $this->mParserOutput
) ) {
2701 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
2702 foreach ( array_keys( $template ) as $dbk ) {
2703 $templates[] = Title
::makeTitle( $ns, $dbk );
2708 return $this->mTitle
->getTemplateLinksFrom();
2713 * Shows a bulletin board style toolbar for common editing functions.
2714 * It can be disabled in the user preferences.
2715 * The necessary JavaScript code can be found in skins/common/edit.js.
2719 static function getEditToolbar() {
2720 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2721 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2723 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2726 * $toolarray is an array of arrays each of which includes the
2727 * filename of the button image (without path), the opening
2728 * tag, the closing tag, optionally a sample text that is
2729 * inserted between the two when no selection is highlighted
2730 * and. The tip text is shown when the user moves the mouse
2733 * Also here: accesskeys (key), which are not used yet until
2734 * someone can figure out a way to make them work in
2735 * IE. However, we should make sure these keys are not defined
2740 'image' => $wgLang->getImageFile( 'button-bold' ),
2741 'id' => 'mw-editbutton-bold',
2743 'close' => '\'\'\'',
2744 'sample' => wfMsg( 'bold_sample' ),
2745 'tip' => wfMsg( 'bold_tip' ),
2749 'image' => $wgLang->getImageFile( 'button-italic' ),
2750 'id' => 'mw-editbutton-italic',
2753 'sample' => wfMsg( 'italic_sample' ),
2754 'tip' => wfMsg( 'italic_tip' ),
2758 'image' => $wgLang->getImageFile( 'button-link' ),
2759 'id' => 'mw-editbutton-link',
2762 'sample' => wfMsg( 'link_sample' ),
2763 'tip' => wfMsg( 'link_tip' ),
2767 'image' => $wgLang->getImageFile( 'button-extlink' ),
2768 'id' => 'mw-editbutton-extlink',
2771 'sample' => wfMsg( 'extlink_sample' ),
2772 'tip' => wfMsg( 'extlink_tip' ),
2776 'image' => $wgLang->getImageFile( 'button-headline' ),
2777 'id' => 'mw-editbutton-headline',
2780 'sample' => wfMsg( 'headline_sample' ),
2781 'tip' => wfMsg( 'headline_tip' ),
2784 $imagesAvailable ?
array(
2785 'image' => $wgLang->getImageFile( 'button-image' ),
2786 'id' => 'mw-editbutton-image',
2787 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2789 'sample' => wfMsg( 'image_sample' ),
2790 'tip' => wfMsg( 'image_tip' ),
2793 $imagesAvailable ?
array(
2794 'image' => $wgLang->getImageFile( 'button-media' ),
2795 'id' => 'mw-editbutton-media',
2796 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2798 'sample' => wfMsg( 'media_sample' ),
2799 'tip' => wfMsg( 'media_tip' ),
2803 'image' => $wgLang->getImageFile( 'button-math' ),
2804 'id' => 'mw-editbutton-math',
2806 'close' => "</math>",
2807 'sample' => wfMsg( 'math_sample' ),
2808 'tip' => wfMsg( 'math_tip' ),
2812 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2813 'id' => 'mw-editbutton-nowiki',
2814 'open' => "<nowiki>",
2815 'close' => "</nowiki>",
2816 'sample' => wfMsg( 'nowiki_sample' ),
2817 'tip' => wfMsg( 'nowiki_tip' ),
2821 'image' => $wgLang->getImageFile( 'button-sig' ),
2822 'id' => 'mw-editbutton-signature',
2826 'tip' => wfMsg( 'sig_tip' ),
2830 'image' => $wgLang->getImageFile( 'button-hr' ),
2831 'id' => 'mw-editbutton-hr',
2832 'open' => "\n----\n",
2835 'tip' => wfMsg( 'hr_tip' ),
2840 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
2841 foreach ( $toolarray as $tool ) {
2847 $image = $wgStylePath . '/common/images/' . $tool['image'],
2848 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2849 // Older browsers show a "speedtip" type message only for ALT.
2850 // Ideally these should be different, realistically they
2851 // probably don't need to be.
2852 $tip = $tool['tip'],
2853 $open = $tool['open'],
2854 $close = $tool['close'],
2855 $sample = $tool['sample'],
2856 $cssId = $tool['id'],
2859 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2862 // This used to be called on DOMReady from mediawiki.action.edit, which
2863 // ended up causing race conditions with the setup code above.
2865 "// Create button bar\n" .
2866 "$(function() { mw.toolbar.init(); } );\n";
2869 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2871 $toolbar = '<div id="toolbar"></div>';
2873 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2879 * Returns an array of html code of the following checkboxes:
2882 * @param $tabindex int Current tabindex
2883 * @param $checked Array of checkbox => bool, where bool indicates the checked
2884 * status of the checkbox
2888 public function getCheckboxes( &$tabindex, $checked ) {
2891 $checkboxes = array();
2893 // don't show the minor edit checkbox if it's a new page or section
2894 if ( !$this->isNew
) {
2895 $checkboxes['minor'] = '';
2896 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2897 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2899 'tabindex' => ++
$tabindex,
2900 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2901 'id' => 'wpMinoredit',
2903 $checkboxes['minor'] =
2904 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2905 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2906 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2907 ">{$minorLabel}</label>";
2911 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2912 $checkboxes['watch'] = '';
2913 if ( $wgUser->isLoggedIn() ) {
2915 'tabindex' => ++
$tabindex,
2916 'accesskey' => wfMsg( 'accesskey-watch' ),
2917 'id' => 'wpWatchthis',
2919 $checkboxes['watch'] =
2920 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2921 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2922 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2923 ">{$watchLabel}</label>";
2925 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2930 * Returns an array of html code of the following buttons:
2931 * save, diff, preview and live
2933 * @param $tabindex int Current tabindex
2937 public function getEditButtons( &$tabindex ) {
2944 'tabindex' => ++
$tabindex,
2945 'value' => wfMsg( 'savearticle' ),
2946 'accesskey' => wfMsg( 'accesskey-save' ),
2947 'title' => wfMsg( 'tooltip-save' ) . ' [' . wfMsg( 'accesskey-save' ) . ']',
2949 $buttons['save'] = Xml
::element( 'input', $temp, '' );
2951 ++
$tabindex; // use the same for preview and live preview
2953 'id' => 'wpPreview',
2954 'name' => 'wpPreview',
2956 'tabindex' => $tabindex,
2957 'value' => wfMsg( 'showpreview' ),
2958 'accesskey' => wfMsg( 'accesskey-preview' ),
2959 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2961 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
2962 $buttons['live'] = '';
2968 'tabindex' => ++
$tabindex,
2969 'value' => wfMsg( 'showdiff' ),
2970 'accesskey' => wfMsg( 'accesskey-diff' ),
2971 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2973 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
2975 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2980 * Output preview text only. This can be sucked into the edit page
2981 * via JavaScript, and saves the server time rendering the skin as
2982 * well as theoretically being more robust on the client (doesn't
2983 * disturb the edit box's undo history, won't eat your text on
2986 * @todo This doesn't include category or interlanguage links.
2987 * Would need to enhance it a bit, <s>maybe wrap them in XML
2988 * or something...</s> that might also require more skin
2989 * initialization, so check whether that's a problem.
2991 function livePreview() {
2994 header( 'Content-type: text/xml; charset=utf-8' );
2995 header( 'Cache-control: no-cache' );
2997 $previewText = $this->getPreviewText();
2998 #$categories = $skin->getCategoryLinks();
3001 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3002 Xml
::tags( 'livepreview', null,
3003 Xml
::element( 'preview', null, $previewText )
3004 #. Xml::element( 'category', null, $categories )
3010 * Call the stock "user is blocked" page
3012 * @deprecated in 1.19; throw an exception directly instead
3014 function blockedPage() {
3015 wfDeprecated( __METHOD__
, '1.19' );
3018 throw new UserBlockedError( $wgUser->getBlock() );
3022 * Produce the stock "please login to edit pages" page
3024 * @deprecated in 1.19; throw an exception directly instead
3026 function userNotLoggedInPage() {
3027 wfDeprecated( __METHOD__
, '1.19' );
3028 throw new PermissionsError( 'edit' );
3032 * Show an error page saying to the user that he has insufficient permissions
3033 * to create a new page
3035 * @deprecated in 1.19; throw an exception directly instead
3037 function noCreatePermission() {
3038 wfDeprecated( __METHOD__
, '1.19' );
3039 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3040 throw new PermissionsError( $permission );
3044 * Creates a basic error page which informs the user that
3045 * they have attempted to edit a nonexistent section.
3047 function noSuchSectionPage() {
3050 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3052 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
3053 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3054 $wgOut->addHTML( $res );
3056 $wgOut->returnToMain( false, $this->mTitle
);
3060 * Produce the stock "your edit contains spam" page
3062 * @param $match string Text which triggered one or more filters
3063 * @deprecated since 1.17 Use method spamPageWithContent() instead
3065 static function spamPage( $match = false ) {
3066 wfDeprecated( __METHOD__
, '1.17' );
3068 global $wgOut, $wgTitle;
3070 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3072 $wgOut->addHTML( '<div id="spamprotected">' );
3073 $wgOut->addWikiMsg( 'spamprotectiontext' );
3075 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3077 $wgOut->addHTML( '</div>' );
3079 $wgOut->returnToMain( false, $wgTitle );
3083 * Show "your edit contains spam" page with your diff and text
3085 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3087 public function spamPageWithContent( $match = false ) {
3088 global $wgOut, $wgLang;
3089 $this->textbox2
= $this->textbox1
;
3091 if( is_array( $match ) ){
3092 $match = $wgLang->listToText( $match );
3094 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3096 $wgOut->addHTML( '<div id="spamprotected">' );
3097 $wgOut->addWikiMsg( 'spamprotectiontext' );
3099 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3101 $wgOut->addHTML( '</div>' );
3103 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3106 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3107 $this->showTextbox2();
3109 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3113 * Format an anchor fragment as it would appear for a given section name
3114 * @param $text String
3118 function sectionAnchor( $text ) {
3120 return $wgParser->guessSectionNameFromWikiText( $text );
3124 * Check if the browser is on a blacklist of user-agents known to
3125 * mangle UTF-8 data on form submission. Returns true if Unicode
3126 * should make it through, false if it's known to be a problem.
3130 function checkUnicodeCompliantBrowser() {
3131 global $wgBrowserBlackList;
3132 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
3133 // No User-Agent header sent? Trust it by default...
3136 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
3137 foreach ( $wgBrowserBlackList as $browser ) {
3138 if ( preg_match( $browser, $currentbrowser ) ) {
3146 * Filter an input field through a Unicode de-armoring process if it
3147 * came from an old browser with known broken Unicode editing issues.
3149 * @param $request WebRequest
3150 * @param $field String
3154 function safeUnicodeInput( $request, $field ) {
3155 $text = rtrim( $request->getText( $field ) );
3156 return $request->getBool( 'safemode' )
3157 ?
$this->unmakesafe( $text )
3162 * @param $request WebRequest
3163 * @param $text string
3166 function safeUnicodeText( $request, $text ) {
3167 $text = rtrim( $text );
3168 return $request->getBool( 'safemode' )
3169 ?
$this->unmakesafe( $text )
3174 * Filter an output field through a Unicode armoring process if it is
3175 * going to an old browser with known broken Unicode editing issues.
3177 * @param $text String
3181 function safeUnicodeOutput( $text ) {
3183 $codedText = $wgContLang->recodeForEdit( $text );
3184 return $this->checkUnicodeCompliantBrowser()
3186 : $this->makesafe( $codedText );
3190 * A number of web browsers are known to corrupt non-ASCII characters
3191 * in a UTF-8 text editing environment. To protect against this,
3192 * detected browsers will be served an armored version of the text,
3193 * with non-ASCII chars converted to numeric HTML character references.
3195 * Preexisting such character references will have a 0 added to them
3196 * to ensure that round-trips do not alter the original data.
3198 * @param $invalue String
3202 function makesafe( $invalue ) {
3203 // Armor existing references for reversability.
3204 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3209 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3210 $bytevalue = ord( $invalue[$i] );
3211 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3212 $result .= chr( $bytevalue );
3214 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3215 $working = $working << 6;
3216 $working +
= ( $bytevalue & 0x3F );
3218 if ( $bytesleft <= 0 ) {
3219 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3221 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3222 $working = $bytevalue & 0x1F;
3224 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3225 $working = $bytevalue & 0x0F;
3227 } else { // 1111 0xxx
3228 $working = $bytevalue & 0x07;
3236 * Reverse the previously applied transliteration of non-ASCII characters
3237 * back to UTF-8. Used to protect data from corruption by broken web browsers
3238 * as listed in $wgBrowserBlackList.
3240 * @param $invalue String
3244 function unmakesafe( $invalue ) {
3246 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3247 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3251 $hexstring .= $invalue[$i];
3253 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3255 // Do some sanity checks. These aren't needed for reversability,
3256 // but should help keep the breakage down if the editor
3257 // breaks one of the entities whilst editing.
3258 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3259 $codepoint = hexdec( $hexstring );
3260 $result .= codepointToUtf8( $codepoint );
3262 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3265 $result .= substr( $invalue, $i, 1 );
3268 // reverse the transform that we made for reversability reasons.
3269 return strtr( $result, array( "�" => "&#x" ) );