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 editing 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 editing 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 * editing 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 unsuccessful
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 * Status: can't parse content
161 const AS_PARSE_ERROR
= 240;
164 * HTML id and name for the beginning of the edit form.
166 const EDITFORM_ID
= 'editform';
169 * Prefix of key for cookie used to pass post-edit state.
170 * The revision id edited is added after this
172 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
175 * Duration of PostEdit cookie, in seconds.
176 * The cookie will be removed instantly if the JavaScript runs.
178 * Otherwise, though, we don't want the cookies to accumulate.
179 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible limit of only 20 cookies per domain.
180 * This still applies at least to some versions of IE without full updates:
181 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
183 * A value of 20 minutes should be enough to take into account slow loads and minor
184 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
186 const POST_EDIT_COOKIE_DURATION
= 1200;
197 private $mContextTitle = null;
198 var $action = 'submit';
199 var $isConflict = false;
200 var $isCssJsSubpage = false;
201 var $isCssSubpage = false;
202 var $isJsSubpage = false;
203 var $isWrongCaseCssJsPage = false;
204 var $isNew = false; // new page or new section
205 var $deletedSinceEdit;
209 var $mTokenOk = false;
210 var $mTokenOkExceptSuffix = false;
211 var $mTriedSave = false;
212 var $incompleteForm = false;
214 var $kblength = false;
215 var $missingComment = false;
216 var $missingSummary = false;
217 var $allowBlankSummary = false;
220 #var $mPreviewTemplates;
228 * Has a summary been preset using GET parameter &summary= ?
231 var $hasPresetSummary = false;
233 var $mBaseRevision = false;
234 var $mShowSummaryField = true;
237 var $save = false, $preview = false, $diff = false;
238 var $minoredit = false, $watchthis = false, $recreate = false;
239 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
240 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
241 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
242 var $contentModel = null, $contentFormat = null;
244 # Placeholders for text injection by hooks (must be HTML)
245 # extensions should take care to _append_ to the present value
246 public $editFormPageTop = ''; // Before even the preview
247 public $editFormTextTop = '';
248 public $editFormTextBeforeContent = '';
249 public $editFormTextAfterWarn = '';
250 public $editFormTextAfterTools = '';
251 public $editFormTextBottom = '';
252 public $editFormTextAfterContent = '';
253 public $previewTextAfterContent = '';
254 public $mPreloadContent = null;
256 /* $didSave should be set to true whenever an article was successfully altered. */
257 public $didSave = false;
258 public $undidRev = 0;
260 public $suppressIntro = false;
263 * Set to true to allow editing of non-text content types.
267 public $allowNonTextContent = false;
270 * @param $article Article
272 public function __construct( Article
$article ) {
273 $this->mArticle
= $article;
274 $this->mTitle
= $article->getTitle();
276 $this->contentModel
= $this->mTitle
->getContentModel();
278 $handler = ContentHandler
::getForModelID( $this->contentModel
);
279 $this->contentFormat
= $handler->getDefaultFormat();
285 public function getArticle() {
286 return $this->mArticle
;
293 public function getTitle() {
294 return $this->mTitle
;
298 * Set the context Title object
300 * @param $title Title object or null
302 public function setContextTitle( $title ) {
303 $this->mContextTitle
= $title;
307 * Get the context title object.
308 * If not set, $wgTitle will be returned. This behavior might change in
309 * the future to return $this->mTitle instead.
311 * @return Title object
313 public function getContextTitle() {
314 if ( is_null( $this->mContextTitle
) ) {
318 return $this->mContextTitle
;
327 * This is the function that gets called for "action=edit". It
328 * sets up various member variables, then passes execution to
329 * another function, usually showEditForm()
331 * The edit form is self-submitting, so that when things like
332 * preview and edit conflicts occur, we get the same form back
333 * with the extra stuff added. Only when the final submission
334 * is made and all is well do we actually save and redirect to
335 * the newly-edited page.
338 global $wgOut, $wgRequest, $wgUser;
339 // Allow extensions to modify/prevent this form or submission
340 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
344 wfProfileIn( __METHOD__
);
345 wfDebug( __METHOD__
. ": enter\n" );
347 // If they used redlink=1 and the page exists, redirect to the main article
348 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
349 $wgOut->redirect( $this->mTitle
->getFullURL() );
350 wfProfileOut( __METHOD__
);
354 $this->importFormData( $wgRequest );
355 $this->firsttime
= false;
358 $this->livePreview();
359 wfProfileOut( __METHOD__
);
363 if ( wfReadOnly() && $this->save
) {
366 $this->preview
= true;
370 $this->formtype
= 'save';
371 } elseif ( $this->preview
) {
372 $this->formtype
= 'preview';
373 } elseif ( $this->diff
) {
374 $this->formtype
= 'diff';
375 } else { # First time through
376 $this->firsttime
= true;
377 if ( $this->previewOnOpen() ) {
378 $this->formtype
= 'preview';
380 $this->formtype
= 'initial';
384 $permErrors = $this->getEditPermissionErrors();
386 wfDebug( __METHOD__
. ": User can't edit\n" );
387 // Auto-block user's IP if the account was "hard" blocked
388 $wgUser->spreadAnyEditBlock();
390 $this->displayPermissionsError( $permErrors );
392 wfProfileOut( __METHOD__
);
396 wfProfileIn( __METHOD__
. "-business-end" );
398 $this->isConflict
= false;
399 // css / js subpages of user pages get a special treatment
400 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
401 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
402 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
403 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
405 # Show applicable editing introductions
406 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
410 # Attempt submission here. This will check for edit conflicts,
411 # and redundantly check for locked database, blocked IPs, etc.
412 # that edit() already checked just in case someone tries to sneak
413 # in the back door with a hand-edited submission URL.
415 if ( 'save' == $this->formtype
) {
416 if ( !$this->attemptSave() ) {
417 wfProfileOut( __METHOD__
. "-business-end" );
418 wfProfileOut( __METHOD__
);
423 # First time through: get contents, set time for conflict
425 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
426 if ( $this->initialiseForm() === false ) {
427 $this->noSuchSectionPage();
428 wfProfileOut( __METHOD__
. "-business-end" );
429 wfProfileOut( __METHOD__
);
433 if ( !$this->mTitle
->getArticleID() ) {
434 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
436 wfRunHooks( 'EditFormInitialText', array( $this ) );
441 $this->showEditForm();
442 wfProfileOut( __METHOD__
. "-business-end" );
443 wfProfileOut( __METHOD__
);
449 protected function getEditPermissionErrors() {
451 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
452 # Can this title be created?
453 if ( !$this->mTitle
->exists() ) {
454 $permErrors = array_merge( $permErrors,
455 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
457 # Ignore some permissions errors when a user is just previewing/viewing diffs
459 foreach ( $permErrors as $error ) {
460 if ( ( $this->preview ||
$this->diff
) &&
461 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
466 $permErrors = wfArrayDiff2( $permErrors, $remove );
471 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
472 * but with the following differences:
473 * - If redlink=1, the user will be redirected to the page
474 * - If there is content to display or the error occurs while either saving,
475 * previewing or showing the difference, it will be a
476 * "View source for ..." page displaying the source code after the error message.
479 * @param array $permErrors of permissions errors, as returned by
480 * Title::getUserPermissionsErrors().
481 * @throws PermissionsError
483 protected function displayPermissionsError( array $permErrors ) {
484 global $wgRequest, $wgOut;
486 if ( $wgRequest->getBool( 'redlink' ) ) {
487 // The edit page was reached via a red link.
488 // Redirect to the article page and let them click the edit tab if
489 // they really want a permission error.
490 $wgOut->redirect( $this->mTitle
->getFullURL() );
494 $content = $this->getContentObject();
496 # Use the normal message if there's nothing to display
497 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
498 $action = $this->mTitle
->exists() ?
'edit' :
499 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
500 throw new PermissionsError( $action, $permErrors );
503 $wgOut->setRobotPolicy( 'noindex,nofollow' );
504 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
505 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
506 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
507 $wgOut->addHTML( "<hr />\n" );
509 # If the user made changes, preserve them when showing the markup
510 # (This happens when a user is blocked during edit, for instance)
511 if ( !$this->firsttime
) {
512 $text = $this->textbox1
;
513 $wgOut->addWikiMsg( 'viewyourtext' );
515 $text = $this->toEditText( $content );
516 $wgOut->addWikiMsg( 'viewsourcetext' );
519 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
521 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
522 Linker
::formatTemplates( $this->getTemplates() ) ) );
524 if ( $this->mTitle
->exists() ) {
525 $wgOut->returnToMain( null, $this->mTitle
);
530 * Show a read-only error
531 * Parameters are the same as OutputPage:readOnlyPage()
532 * Redirect to the article page if redlink=1
533 * @deprecated in 1.19; use displayPermissionsError() instead
535 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
536 wfDeprecated( __METHOD__
, '1.19' );
538 global $wgRequest, $wgOut;
539 if ( $wgRequest->getBool( 'redlink' ) ) {
540 // The edit page was reached via a red link.
541 // Redirect to the article page and let them click the edit tab if
542 // they really want a permission error.
543 $wgOut->redirect( $this->mTitle
->getFullURL() );
545 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
550 * Should we show a preview when the edit form is first shown?
554 protected function previewOnOpen() {
555 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
556 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
557 // Explicit override from request
559 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
560 // Explicit override from request
562 } elseif ( $this->section
== 'new' ) {
563 // Nothing *to* preview for new sections
565 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
566 // Standard preference behavior
568 } elseif ( !$this->mTitle
->exists() &&
569 isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] ) &&
570 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
572 // Categories are special
580 * Checks whether the user entered a skin name in uppercase,
581 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
585 protected function isWrongCaseCssJsPage() {
586 if ( $this->mTitle
->isCssJsSubpage() ) {
587 $name = $this->mTitle
->getSkinFromCssJsSubpage();
588 $skins = array_merge(
589 array_keys( Skin
::getSkinNames() ),
592 return !in_array( $name, $skins )
593 && in_array( strtolower( $name ), $skins );
600 * Returns whether section editing is supported for the current page.
601 * Subclasses may override this to replace the default behavior, which is
602 * to check ContentHandler::supportsSections.
604 * @return bool true if this edit page supports sections, false otherwise.
606 protected function isSectionEditSupported() {
607 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
608 return $contentHandler->supportsSections();
612 * This function collects the form data and uses it to populate various member variables.
613 * @param $request WebRequest
615 function importFormData( &$request ) {
616 global $wgContLang, $wgUser;
618 wfProfileIn( __METHOD__
);
620 # Section edit can come from either the form or a link
621 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
623 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
624 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
627 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
629 if ( $request->wasPosted() ) {
630 # These fields need to be checked for encoding.
631 # Also remove trailing whitespace, but don't remove _initial_
632 # whitespace from the text boxes. This may be significant formatting.
633 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
634 if ( !$request->getCheck( 'wpTextbox2' ) ) {
635 // Skip this if wpTextbox2 has input, it indicates that we came
636 // from a conflict page with raw page text, not a custom form
637 // modified by subclasses
638 wfProfileIn( get_class( $this ) . "::importContentFormData" );
639 $textbox1 = $this->importContentFormData( $request );
640 if ( $textbox1 !== null ) {
641 $this->textbox1
= $textbox1;
644 wfProfileOut( get_class( $this ) . "::importContentFormData" );
647 # Truncate for whole multibyte characters
648 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
650 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
651 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
653 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
655 # Treat sectiontitle the same way as summary.
656 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
657 # currently doing double duty as both edit summary and section title. Right now this
658 # is just to allow API edits to work around this limitation, but this should be
659 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
660 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
661 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
663 $this->edittime
= $request->getVal( 'wpEdittime' );
664 $this->starttime
= $request->getVal( 'wpStarttime' );
666 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
668 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
669 // wpTextbox1 field is missing, possibly due to being "too big"
670 // according to some filter rules such as Suhosin's setting for
671 // suhosin.request.max_value_length (d'oh)
672 $this->incompleteForm
= true;
674 // edittime should be one of our last fields; if it's missing,
675 // the submission probably broke somewhere in the middle.
676 $this->incompleteForm
= is_null( $this->edittime
);
678 if ( $this->incompleteForm
) {
679 # If the form is incomplete, force to preview.
680 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
681 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
682 $this->preview
= true;
684 /* Fallback for live preview */
685 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
686 $this->diff
= $request->getCheck( 'wpDiff' );
688 // Remember whether a save was requested, so we can indicate
689 // if we forced preview due to session failure.
690 $this->mTriedSave
= !$this->preview
;
692 if ( $this->tokenOk( $request ) ) {
693 # Some browsers will not report any submit button
694 # if the user hits enter in the comment box.
695 # The unmarked state will be assumed to be a save,
696 # if the form seems otherwise complete.
697 wfDebug( __METHOD__
. ": Passed token check.\n" );
698 } elseif ( $this->diff
) {
699 # Failed token check, but only requested "Show Changes".
700 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
702 # Page might be a hack attempt posted from
703 # an external site. Preview instead of saving.
704 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
705 $this->preview
= true;
708 $this->save
= !$this->preview
&& !$this->diff
;
709 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
710 $this->edittime
= null;
713 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
714 $this->starttime
= null;
717 $this->recreate
= $request->getCheck( 'wpRecreate' );
719 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
720 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
722 # Don't force edit summaries when a user is editing their own user or talk page
723 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
724 $this->mTitle
->getText() == $wgUser->getName() )
726 $this->allowBlankSummary
= true;
728 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary' );
731 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
733 # Not a posted form? Start with nothing.
734 wfDebug( __METHOD__
. ": Not a posted form.\n" );
735 $this->textbox1
= '';
737 $this->sectiontitle
= '';
738 $this->edittime
= '';
739 $this->starttime
= wfTimestampNow();
741 $this->preview
= false;
744 $this->minoredit
= false;
745 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overridden by request parameters
746 $this->recreate
= false;
748 // When creating a new section, we can preload a section title by passing it as the
749 // preloadtitle parameter in the URL (Bug 13100)
750 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
751 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
752 // Once wpSummary isn't being use for setting section titles, we should delete this.
753 $this->summary
= $request->getVal( 'preloadtitle' );
755 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
756 $this->summary
= $request->getText( 'summary' );
757 if ( $this->summary
!== '' ) {
758 $this->hasPresetSummary
= true;
762 if ( $request->getVal( 'minor' ) ) {
763 $this->minoredit
= true;
767 $this->oldid
= $request->getInt( 'oldid' );
769 $this->bot
= $request->getBool( 'bot', true );
770 $this->nosummary
= $request->getBool( 'nosummary' );
772 $content_handler = ContentHandler
::getForTitle( $this->mTitle
);
773 $this->contentModel
= $request->getText( 'model', $content_handler->getModelID() ); #may be overridden by revision
774 $this->contentFormat
= $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
776 #TODO: check if the desired model is allowed in this namespace, and if a transition from the page's current model to the new model is allowed
777 #TODO: check if the desired content model supports the given content format!
779 $this->live
= $request->getCheck( 'live' );
780 $this->editintro
= $request->getText( 'editintro',
781 // Custom edit intro for new sections
782 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
784 // Allow extensions to modify form data
785 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
787 wfProfileOut( __METHOD__
);
791 * Subpage overridable method for extracting the page content data from the
792 * posted form to be placed in $this->textbox1, if using customized input
793 * this method should be overridden and return the page text that will be used
794 * for saving, preview parsing and so on...
796 * @param $request WebRequest
798 protected function importContentFormData( &$request ) {
799 return; // Don't do anything, EditPage already extracted wpTextbox1
803 * Initialise form fields in the object
804 * Called on the first invocation, e.g. when a user clicks an edit link
805 * @return bool -- if the requested section is valid
807 function initialiseForm() {
809 $this->edittime
= $this->mArticle
->getTimestamp();
811 $content = $this->getContentObject( false ); #TODO: track content object?!
812 if ( $content === false ) {
815 $this->textbox1
= $this->toEditText( $content );
817 // activate checkboxes if user wants them to be always active
818 # Sort out the "watch" checkbox
819 if ( $wgUser->getOption( 'watchdefault' ) ) {
821 $this->watchthis
= true;
822 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
824 $this->watchthis
= true;
825 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
827 $this->watchthis
= true;
829 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
830 $this->minoredit
= true;
832 if ( $this->textbox1
=== false ) {
840 * Fetch initial editing page content.
842 * @param $def_text string|bool
843 * @return mixed string on success, $def_text for invalid sections
845 * @deprecated since 1.21, get WikiPage::getContent() instead.
847 function getContent( $def_text = false ) {
848 ContentHandler
::deprecated( __METHOD__
, '1.21' );
850 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
851 $def_content = $this->toEditContent( $def_text );
853 $def_content = false;
856 $content = $this->getContentObject( $def_content );
858 // Note: EditPage should only be used with text based content anyway.
859 return $this->toEditText( $content );
863 * @param Content|null $def_content The default value to return
865 * @return mixed Content on success, $def_content for invalid sections
869 protected function getContentObject( $def_content = null ) {
870 global $wgOut, $wgRequest;
872 wfProfileIn( __METHOD__
);
876 // For message page not locally set, use the i18n message.
877 // For other non-existent articles, use preload text if any.
878 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
879 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
880 # If this is a system message, get the default text.
881 $msg = $this->mTitle
->getDefaultMessageText();
883 $content = $this->toEditContent( $msg );
885 if ( $content === false ) {
886 # If requested, preload some text.
887 $preload = $wgRequest->getVal( 'preload',
888 // Custom preload text for new sections
889 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
891 $content = $this->getPreloadedContent( $preload );
893 // For existing pages, get text based on "undo" or section parameters.
895 if ( $this->section
!= '' ) {
896 // Get section edit text (returns $def_text for invalid sections)
897 $orig = $this->getOriginalContent();
898 $content = $orig ?
$orig->getSection( $this->section
) : null;
900 if ( !$content ) $content = $def_content;
902 $undoafter = $wgRequest->getInt( 'undoafter' );
903 $undo = $wgRequest->getInt( 'undo' );
905 if ( $undo > 0 && $undoafter > 0 ) {
906 if ( $undo < $undoafter ) {
907 # If they got undoafter and undo round the wrong way, switch them
908 list( $undo, $undoafter ) = array( $undoafter, $undo );
911 $undorev = Revision
::newFromId( $undo );
912 $oldrev = Revision
::newFromId( $undoafter );
914 # Sanity check, make sure it's the right page,
915 # the revisions exist and they were not deleted.
916 # Otherwise, $content will be left as-is.
917 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
918 $undorev->getPage() == $oldrev->getPage() &&
919 $undorev->getPage() == $this->mTitle
->getArticleID() &&
920 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
921 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
923 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
925 if ( $content === false ) {
926 # Warn the user that something went wrong
927 $undoMsg = 'failure';
929 # Inform the user of our success and set an automatic edit summary
930 $undoMsg = 'success';
932 # If we just undid one rev, use an autosummary
933 $firstrev = $oldrev->getNext();
934 if ( $firstrev && $firstrev->getId() == $undo ) {
935 $undoSummary = wfMessage( 'undo-summary', $undo, $undorev->getUserText() )->inContentLanguage()->text();
936 if ( $this->summary
=== '' ) {
937 $this->summary
= $undoSummary;
939 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
940 ->inContentLanguage()->text() . $this->summary
;
942 $this->undidRev
= $undo;
944 $this->formtype
= 'diff';
947 // Failed basic sanity checks.
948 // Older revisions may have been removed since the link
949 // was created, or we may simply have got bogus input.
953 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
954 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
955 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
958 if ( $content === false ) {
959 $content = $this->getOriginalContent();
964 wfProfileOut( __METHOD__
);
969 * Get the content of the wanted revision, without section extraction.
971 * The result of this function can be used to compare user's input with
972 * section replaced in its context (using WikiPage::replaceSection())
973 * to the original text of the edit.
975 * This differs from Article::getContent() that when a missing revision is
976 * encountered the result will be null and not the
977 * 'missing-revision' message.
980 * @return Content|null
982 private function getOriginalContent() {
983 if ( $this->section
== 'new' ) {
984 return $this->getCurrentContent();
986 $revision = $this->mArticle
->getRevisionFetched();
987 if ( $revision === null ) {
988 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
989 $handler = ContentHandler
::getForModelID( $this->contentModel
);
991 return $handler->makeEmptyContent();
993 $content = $revision->getContent();
998 * Get the current content of the page. This is basically similar to
999 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1000 * content object is returned instead of null.
1005 protected function getCurrentContent() {
1006 $rev = $this->mArticle
->getRevision();
1007 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1009 if ( $content === false ||
$content === null ) {
1010 if ( !$this->contentModel
) $this->contentModel
= $this->getTitle()->getContentModel();
1011 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1013 return $handler->makeEmptyContent();
1015 # nasty side-effect, but needed for consistency
1016 $this->contentModel
= $rev->getContentModel();
1017 $this->contentFormat
= $rev->getContentFormat();
1024 * Use this method before edit() to preload some text into the edit box
1026 * @param $text string
1027 * @deprecated since 1.21, use setPreloadedContent() instead.
1029 public function setPreloadedText( $text ) {
1030 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1032 $content = $this->toEditContent( $text );
1034 $this->setPreloadedContent( $content );
1038 * Use this method before edit() to preload some content into the edit box
1040 * @param $content Content
1044 public function setPreloadedContent( Content
$content ) {
1045 $this->mPreloadContent
= $content;
1049 * Get the contents to be preloaded into the box, either set by
1050 * an earlier setPreloadText() or by loading the given page.
1052 * @param string $preload representing the title to preload from.
1056 * @deprecated since 1.21, use getPreloadedContent() instead
1058 protected function getPreloadedText( $preload ) {
1059 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1061 $content = $this->getPreloadedContent( $preload );
1062 $text = $this->toEditText( $content );
1068 * Get the contents to be preloaded into the box, either set by
1069 * an earlier setPreloadText() or by loading the given page.
1071 * @param string $preload representing the title to preload from.
1077 protected function getPreloadedContent( $preload ) {
1080 if ( !empty( $this->mPreloadContent
) ) {
1081 return $this->mPreloadContent
;
1084 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1086 if ( $preload === '' ) {
1087 return $handler->makeEmptyContent();
1090 $title = Title
::newFromText( $preload );
1091 # Check for existence to avoid getting MediaWiki:Noarticletext
1092 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1093 //TODO: somehow show a warning to the user!
1094 return $handler->makeEmptyContent();
1097 $page = WikiPage
::factory( $title );
1098 if ( $page->isRedirect() ) {
1099 $title = $page->getRedirectTarget();
1101 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1102 //TODO: somehow show a warning to the user!
1103 return $handler->makeEmptyContent();
1105 $page = WikiPage
::factory( $title );
1108 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1109 $content = $page->getContent( Revision
::RAW
);
1112 //TODO: somehow show a warning to the user!
1113 return $handler->makeEmptyContent();
1116 if ( $content->getModel() !== $handler->getModelID() ) {
1117 $converted = $content->convert( $handler->getModelID() );
1119 if ( !$converted ) {
1120 //TODO: somehow show a warning to the user!
1121 wfDebug( "Attempt to preload incompatible content: "
1122 . "can't convert " . $content->getModel()
1123 . " to " . $handler->getModelID() );
1125 return $handler->makeEmptyContent();
1128 $content = $converted;
1131 return $content->preloadTransform( $title, $parserOptions );
1135 * Make sure the form isn't faking a user's credentials.
1137 * @param $request WebRequest
1141 function tokenOk( &$request ) {
1143 $token = $request->getVal( 'wpEditToken' );
1144 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1145 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1146 return $this->mTokenOk
;
1150 * Sets post-edit cookie indicating the user just saved a particular revision.
1152 * This uses a temporary cookie for each revision ID so separate saves will never
1153 * interfere with each other.
1155 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1156 * the redirect. It must be clearable by JavaScript code, so it must not be
1157 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1160 * Since WebResponse::setcookie does not allow forcing HttpOnly for a single
1161 * cookie, we have to use PHP's setcookie() directly.
1163 * We use a path of '/' since wgCookiePath is not exposed to JS
1165 * If the variable were set on the server, it would be cached, which is unwanted
1166 * since the post-edit state should only apply to the load right after the save.
1168 protected function setPostEditCookie() {
1169 global $wgCookiePrefix, $wgCookieDomain;
1170 $revisionId = $this->mArticle
->getLatest();
1171 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1173 setcookie( $wgCookiePrefix . $postEditKey, '1', time() + self
::POST_EDIT_COOKIE_DURATION
, '/', $wgCookieDomain );
1177 * Attempt submission
1178 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1179 * @return bool false if output is done, true if the rest of the form should be displayed
1181 function attemptSave() {
1182 global $wgUser, $wgOut;
1184 $resultDetails = false;
1185 # Allow bots to exempt some edits from bot flagging
1186 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1187 $status = $this->internalAttemptSave( $resultDetails, $bot );
1188 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1189 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1190 $this->didSave
= true;
1191 if ( !$resultDetails['nullEdit'] ) {
1192 $this->setPostEditCookie();
1196 switch ( $status->value
) {
1197 case self
::AS_HOOK_ERROR_EXPECTED
:
1198 case self
::AS_CONTENT_TOO_BIG
:
1199 case self
::AS_ARTICLE_WAS_DELETED
:
1200 case self
::AS_CONFLICT_DETECTED
:
1201 case self
::AS_SUMMARY_NEEDED
:
1202 case self
::AS_TEXTBOX_EMPTY
:
1203 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1207 case self
::AS_HOOK_ERROR
:
1210 case self
::AS_PARSE_ERROR
:
1211 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1214 case self
::AS_SUCCESS_NEW_ARTICLE
:
1215 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1216 $anchor = isset ( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1217 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1220 case self
::AS_SUCCESS_UPDATE
:
1222 $sectionanchor = $resultDetails['sectionanchor'];
1224 // Give extensions a chance to modify URL query on update
1225 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1227 if ( $resultDetails['redirect'] ) {
1228 if ( $extraQuery == '' ) {
1229 $extraQuery = 'redirect=no';
1231 $extraQuery = 'redirect=no&' . $extraQuery;
1234 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1237 case self
::AS_BLANK_ARTICLE
:
1238 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1241 case self
::AS_SPAM_ERROR
:
1242 $this->spamPageWithContent( $resultDetails['spam'] );
1245 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1246 throw new UserBlockedError( $wgUser->getBlock() );
1248 case self
::AS_IMAGE_REDIRECT_ANON
:
1249 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1250 throw new PermissionsError( 'upload' );
1252 case self
::AS_READ_ONLY_PAGE_ANON
:
1253 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1254 throw new PermissionsError( 'edit' );
1256 case self
::AS_READ_ONLY_PAGE
:
1257 throw new ReadOnlyError
;
1259 case self
::AS_RATE_LIMITED
:
1260 throw new ThrottledError();
1262 case self
::AS_NO_CREATE_PERMISSION
:
1263 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1264 throw new PermissionsError( $permission );
1267 // We don't recognize $status->value. The only way that can happen
1268 // is if an extension hook aborted from inside ArticleSave.
1269 // Render the status object into $this->hookError
1270 // FIXME this sucks, we should just use the Status object throughout
1271 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1278 * Run hooks that can filter edits just before they get saved.
1280 * @param Content $content the Content to filter.
1281 * @param Status $status for reporting the outcome to the caller
1282 * @param User $user the user performing the edit
1286 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1287 // Run old style post-section-merge edit filter
1288 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1289 array( $this, $content, &$this->hookError
, $this->summary
) ) ) {
1291 # Error messages etc. could be handled within the hook...
1292 $status->fatal( 'hookaborted' );
1293 $status->value
= self
::AS_HOOK_ERROR
;
1295 } elseif ( $this->hookError
!= '' ) {
1296 # ...or the hook could be expecting us to produce an error
1297 $status->fatal( 'hookaborted' );
1298 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1302 // Run new style post-section-merge edit filter
1303 if ( !wfRunHooks( 'EditFilterMergedContent',
1304 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1305 $user, $this->minoredit
) ) ) {
1307 # Error messages etc. could be handled within the hook...
1308 // XXX: $status->value may already be something informative...
1309 $this->hookError
= $status->getWikiText();
1310 $status->fatal( 'hookaborted' );
1311 $status->value
= self
::AS_HOOK_ERROR
;
1313 } elseif ( !$status->isOK() ) {
1314 # ...or the hook could be expecting us to produce an error
1315 // FIXME this sucks, we should just use the Status object throughout
1316 $this->hookError
= $status->getWikiText();
1317 $status->fatal( 'hookaborted' );
1318 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1326 * Attempt submission (no UI)
1328 * @param array $result array to add statuses to, currently with the possible keys:
1329 * spam - string - Spam string from content if any spam is detected by matchSpamRegex
1330 * sectionanchor - string - Section anchor for a section save
1331 * nullEdit - boolean - Set if doEditContent is OK. True if null edit, false otherwise.
1332 * redirect - boolean - Set if doEditContent is OK. True if resulting revision is a redirect
1333 * @param bool $bot True if edit is being made under the bot right.
1335 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1337 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1338 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1339 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1341 function internalAttemptSave( &$result, $bot = false ) {
1342 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1344 $status = Status
::newGood();
1346 wfProfileIn( __METHOD__
);
1347 wfProfileIn( __METHOD__
. '-checks' );
1349 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1350 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1351 $status->fatal( 'hookaborted' );
1352 $status->value
= self
::AS_HOOK_ERROR
;
1353 wfProfileOut( __METHOD__
. '-checks' );
1354 wfProfileOut( __METHOD__
);
1359 # Construct Content object
1360 $textbox_content = $this->toEditContent( $this->textbox1
);
1361 } catch ( MWContentSerializationException
$ex ) {
1362 $status->fatal( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
1363 $status->value
= self
::AS_PARSE_ERROR
;
1364 wfProfileOut( __METHOD__
. '-checks' );
1365 wfProfileOut( __METHOD__
);
1369 # Check image redirect
1370 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1371 $textbox_content->isRedirect() &&
1372 !$wgUser->isAllowed( 'upload' ) ) {
1373 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1374 $status->setResult( false, $code );
1376 wfProfileOut( __METHOD__
. '-checks' );
1377 wfProfileOut( __METHOD__
);
1383 $match = self
::matchSummarySpamRegex( $this->summary
);
1384 if ( $match === false ) {
1385 $match = self
::matchSpamRegex( $this->textbox1
);
1387 if ( $match !== false ) {
1388 $result['spam'] = $match;
1389 $ip = $wgRequest->getIP();
1390 $pdbk = $this->mTitle
->getPrefixedDBkey();
1391 $match = str_replace( "\n", '', $match );
1392 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1393 $status->fatal( 'spamprotectionmatch', $match );
1394 $status->value
= self
::AS_SPAM_ERROR
;
1395 wfProfileOut( __METHOD__
. '-checks' );
1396 wfProfileOut( __METHOD__
);
1399 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1400 # Error messages etc. could be handled within the hook...
1401 $status->fatal( 'hookaborted' );
1402 $status->value
= self
::AS_HOOK_ERROR
;
1403 wfProfileOut( __METHOD__
. '-checks' );
1404 wfProfileOut( __METHOD__
);
1406 } elseif ( $this->hookError
!= '' ) {
1407 # ...or the hook could be expecting us to produce an error
1408 $status->fatal( 'hookaborted' );
1409 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1410 wfProfileOut( __METHOD__
. '-checks' );
1411 wfProfileOut( __METHOD__
);
1415 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1416 // Auto-block user's IP if the account was "hard" blocked
1417 $wgUser->spreadAnyEditBlock();
1418 # Check block state against master, thus 'false'.
1419 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1420 wfProfileOut( __METHOD__
. '-checks' );
1421 wfProfileOut( __METHOD__
);
1425 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1426 if ( $this->kblength
> $wgMaxArticleSize ) {
1427 // Error will be displayed by showEditForm()
1428 $this->tooBig
= true;
1429 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1430 wfProfileOut( __METHOD__
. '-checks' );
1431 wfProfileOut( __METHOD__
);
1435 if ( !$wgUser->isAllowed( 'edit' ) ) {
1436 if ( $wgUser->isAnon() ) {
1437 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1438 wfProfileOut( __METHOD__
. '-checks' );
1439 wfProfileOut( __METHOD__
);
1442 $status->fatal( 'readonlytext' );
1443 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1444 wfProfileOut( __METHOD__
. '-checks' );
1445 wfProfileOut( __METHOD__
);
1450 if ( wfReadOnly() ) {
1451 $status->fatal( 'readonlytext' );
1452 $status->value
= self
::AS_READ_ONLY_PAGE
;
1453 wfProfileOut( __METHOD__
. '-checks' );
1454 wfProfileOut( __METHOD__
);
1457 if ( $wgUser->pingLimiter() ) {
1458 $status->fatal( 'actionthrottledtext' );
1459 $status->value
= self
::AS_RATE_LIMITED
;
1460 wfProfileOut( __METHOD__
. '-checks' );
1461 wfProfileOut( __METHOD__
);
1465 # If the article has been deleted while editing, don't save it without
1467 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1468 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1469 wfProfileOut( __METHOD__
. '-checks' );
1470 wfProfileOut( __METHOD__
);
1474 wfProfileOut( __METHOD__
. '-checks' );
1476 # Load the page data from the master. If anything changes in the meantime,
1477 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1478 $this->mArticle
->loadPageData( 'fromdbmaster' );
1479 $new = !$this->mArticle
->exists();
1482 // Late check for create permission, just in case *PARANOIA*
1483 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1484 $status->fatal( 'nocreatetext' );
1485 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1486 wfDebug( __METHOD__
. ": no create permission\n" );
1487 wfProfileOut( __METHOD__
);
1491 # Don't save a new article if it's blank.
1492 if ( $this->textbox1
== '' ) {
1493 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1494 wfProfileOut( __METHOD__
);
1498 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1499 wfProfileOut( __METHOD__
);
1503 $content = $textbox_content;
1505 $result['sectionanchor'] = '';
1506 if ( $this->section
== 'new' ) {
1507 if ( $this->sectiontitle
!== '' ) {
1508 // Insert the section title above the content.
1509 $content = $content->addSectionHeader( $this->sectiontitle
);
1511 // Jump to the new section
1512 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1514 // If no edit summary was specified, create one automatically from the section
1515 // title and have it link to the new section. Otherwise, respect the summary as
1517 if ( $this->summary
=== '' ) {
1518 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1519 $this->summary
= wfMessage( 'newsectionsummary' )
1520 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1522 } elseif ( $this->summary
!== '' ) {
1523 // Insert the section title above the content.
1524 $content = $content->addSectionHeader( $this->summary
);
1526 // Jump to the new section
1527 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1529 // Create a link to the new section from the edit summary.
1530 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1531 $this->summary
= wfMessage( 'newsectionsummary' )
1532 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1536 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1540 # Article exists. Check for edit conflict.
1542 $this->mArticle
->clear(); # Force reload of dates, etc.
1543 $timestamp = $this->mArticle
->getTimestamp();
1545 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1547 if ( $timestamp != $this->edittime
) {
1548 $this->isConflict
= true;
1549 if ( $this->section
== 'new' ) {
1550 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1551 $this->mArticle
->getComment() == $this->summary
) {
1552 // Probably a duplicate submission of a new comment.
1553 // This can happen when squid resends a request after
1554 // a timeout but the first one actually went through.
1555 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1557 // New comment; suppress conflict.
1558 $this->isConflict
= false;
1559 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1561 } elseif ( $this->section
== '' && Revision
::userWasLastToEdit( DB_MASTER
, $this->mTitle
->getArticleID(),
1562 $wgUser->getId(), $this->edittime
) ) {
1563 # Suppress edit conflict with self, except for section edits where merging is required.
1564 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1565 $this->isConflict
= false;
1569 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1570 // backwards compatibility with old forms/bots).
1571 if ( $this->sectiontitle
!== '' ) {
1572 $sectionTitle = $this->sectiontitle
;
1574 $sectionTitle = $this->summary
;
1579 if ( $this->isConflict
) {
1580 wfDebug( __METHOD__
. ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1581 . " (article time '{$timestamp}')\n" );
1583 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1585 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1586 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1589 if ( is_null( $content ) ) {
1590 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1591 $this->isConflict
= true;
1592 $content = $textbox_content; // do not try to merge here!
1593 } elseif ( $this->isConflict
) {
1595 if ( $this->mergeChangesIntoContent( $content ) ) {
1596 // Successful merge! Maybe we should tell the user the good news?
1597 $this->isConflict
= false;
1598 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1600 $this->section
= '';
1601 $this->textbox1
= ContentHandler
::getContentText( $content );
1602 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1606 if ( $this->isConflict
) {
1607 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1608 wfProfileOut( __METHOD__
);
1612 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1613 wfProfileOut( __METHOD__
);
1617 if ( $this->section
== 'new' ) {
1618 // Handle the user preference to force summaries here
1619 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1620 $this->missingSummary
= true;
1621 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1622 $status->value
= self
::AS_SUMMARY_NEEDED
;
1623 wfProfileOut( __METHOD__
);
1627 // Do not allow the user to post an empty comment
1628 if ( $this->textbox1
== '' ) {
1629 $this->missingComment
= true;
1630 $status->fatal( 'missingcommenttext' );
1631 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1632 wfProfileOut( __METHOD__
);
1635 } elseif ( !$this->allowBlankSummary
1636 && !$content->equals( $this->getOriginalContent() )
1637 && !$content->isRedirect()
1638 && md5( $this->summary
) == $this->autoSumm
1640 $this->missingSummary
= true;
1641 $status->fatal( 'missingsummary' );
1642 $status->value
= self
::AS_SUMMARY_NEEDED
;
1643 wfProfileOut( __METHOD__
);
1648 wfProfileIn( __METHOD__
. '-sectionanchor' );
1649 $sectionanchor = '';
1650 if ( $this->section
== 'new' ) {
1651 if ( $this->sectiontitle
!== '' ) {
1652 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1653 // If no edit summary was specified, create one automatically from the section
1654 // title and have it link to the new section. Otherwise, respect the summary as
1656 if ( $this->summary
=== '' ) {
1657 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1658 $this->summary
= wfMessage( 'newsectionsummary' )
1659 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1661 } elseif ( $this->summary
!== '' ) {
1662 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1663 # This is a new section, so create a link to the new section
1664 # in the revision summary.
1665 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1666 $this->summary
= wfMessage( 'newsectionsummary' )
1667 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1669 } elseif ( $this->section
!= '' ) {
1670 # Try to get a section anchor from the section source, redirect to edited section if header found
1671 # XXX: might be better to integrate this into Article::replaceSection
1672 # for duplicate heading checking and maybe parsing
1673 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1674 # we can't deal with anchors, includes, html etc in the header for now,
1675 # headline would need to be parsed to improve this
1676 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1677 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1680 $result['sectionanchor'] = $sectionanchor;
1681 wfProfileOut( __METHOD__
. '-sectionanchor' );
1683 // Save errors may fall down to the edit form, but we've now
1684 // merged the section into full text. Clear the section field
1685 // so that later submission of conflict forms won't try to
1686 // replace that into a duplicated mess.
1687 $this->textbox1
= $this->toEditText( $content );
1688 $this->section
= '';
1690 $status->value
= self
::AS_SUCCESS_UPDATE
;
1693 // Check for length errors again now that the section is merged in
1694 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1695 if ( $this->kblength
> $wgMaxArticleSize ) {
1696 $this->tooBig
= true;
1697 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1698 wfProfileOut( __METHOD__
);
1702 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1703 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1704 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1705 ( $bot ? EDIT_FORCE_BOT
: 0 );
1707 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags,
1708 false, null, $this->contentFormat
);
1710 if ( !$doEditStatus->isOK() ) {
1711 // Failure from doEdit()
1712 // Show the edit conflict page for certain recognized errors from doEdit(),
1713 // but don't show it for errors from extension hooks
1714 $errors = $doEditStatus->getErrorsArray();
1715 if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
1716 'edit-already-exists' ) ) )
1718 $this->isConflict
= true;
1719 // Destroys data doEdit() put in $status->value but who cares
1720 $doEditStatus->value
= self
::AS_END
;
1722 wfProfileOut( __METHOD__
);
1723 return $doEditStatus;
1726 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1727 $result['redirect'] = $content->isRedirect();
1728 $this->updateWatchlist();
1729 wfProfileOut( __METHOD__
);
1734 * Register the change of watch status
1736 protected function updateWatchlist() {
1739 if ( $wgUser->isLoggedIn() && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
) ) {
1740 $fname = __METHOD__
;
1741 $title = $this->mTitle
;
1742 $watch = $this->watchthis
;
1744 // Do this in its own transaction to reduce contention...
1745 $dbw = wfGetDB( DB_MASTER
);
1746 $dbw->onTransactionIdle( function() use ( $dbw, $title, $watch, $wgUser, $fname ) {
1747 $dbw->begin( $fname );
1749 WatchAction
::doWatch( $title, $wgUser );
1751 WatchAction
::doUnwatch( $title, $wgUser );
1753 $dbw->commit( $fname );
1759 * Attempts to merge text content with base and current revisions
1761 * @param $editText string
1764 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1766 function mergeChangesInto( &$editText ) {
1767 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1769 $editContent = $this->toEditContent( $editText );
1771 $ok = $this->mergeChangesIntoContent( $editContent );
1774 $editText = $this->toEditText( $editContent );
1781 * Attempts to do 3-way merge of edit content with a base revision
1782 * and current content, in case of edit conflict, in whichever way appropriate
1783 * for the content type.
1787 * @param $editContent
1791 private function mergeChangesIntoContent( &$editContent ) {
1792 wfProfileIn( __METHOD__
);
1794 $db = wfGetDB( DB_MASTER
);
1796 // This is the revision the editor started from
1797 $baseRevision = $this->getBaseRevision();
1798 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
1800 if ( is_null( $baseContent ) ) {
1801 wfProfileOut( __METHOD__
);
1805 // The current state, we want to merge updates into it
1806 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1807 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
1809 if ( is_null( $currentContent ) ) {
1810 wfProfileOut( __METHOD__
);
1814 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
1816 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1819 $editContent = $result;
1820 wfProfileOut( __METHOD__
);
1824 wfProfileOut( __METHOD__
);
1831 function getBaseRevision() {
1832 if ( !$this->mBaseRevision
) {
1833 $db = wfGetDB( DB_MASTER
);
1834 $baseRevision = Revision
::loadFromTimestamp(
1835 $db, $this->mTitle
, $this->edittime
);
1836 return $this->mBaseRevision
= $baseRevision;
1838 return $this->mBaseRevision
;
1843 * Check given input text against $wgSpamRegex, and return the text of the first match.
1845 * @param $text string
1847 * @return string|bool matching string or false
1849 public static function matchSpamRegex( $text ) {
1850 global $wgSpamRegex;
1851 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1852 $regexes = (array)$wgSpamRegex;
1853 return self
::matchSpamRegexInternal( $text, $regexes );
1857 * Check given input text against $wgSpamRegex, and return the text of the first match.
1859 * @param $text string
1861 * @return string|bool matching string or false
1863 public static function matchSummarySpamRegex( $text ) {
1864 global $wgSummarySpamRegex;
1865 $regexes = (array)$wgSummarySpamRegex;
1866 return self
::matchSpamRegexInternal( $text, $regexes );
1870 * @param $text string
1871 * @param $regexes array
1872 * @return bool|string
1874 protected static function matchSpamRegexInternal( $text, $regexes ) {
1875 foreach ( $regexes as $regex ) {
1877 if ( preg_match( $regex, $text, $matches ) ) {
1884 function setHeaders() {
1885 global $wgOut, $wgUser;
1887 $wgOut->addModules( 'mediawiki.action.edit' );
1889 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1890 $wgOut->addModules( 'mediawiki.action.edit.preview' );
1892 // Bug #19334: textarea jumps when editing articles in IE8
1893 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1895 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1897 # Enabled article-related sidebar, toplinks, etc.
1898 $wgOut->setArticleRelated( true );
1900 $contextTitle = $this->getContextTitle();
1901 if ( $this->isConflict
) {
1902 $msg = 'editconflict';
1903 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1904 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1906 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1907 'editing' : 'creating';
1909 # Use the title defined by DISPLAYTITLE magic word when present
1910 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1911 if ( $displayTitle === false ) {
1912 $displayTitle = $contextTitle->getPrefixedText();
1914 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1918 * Show all applicable editing introductions
1920 protected function showIntro() {
1921 global $wgOut, $wgUser;
1922 if ( $this->suppressIntro
) {
1926 $namespace = $this->mTitle
->getNamespace();
1928 if ( $namespace == NS_MEDIAWIKI
) {
1929 # Show a warning if editing an interface message
1930 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1931 } else if( $namespace == NS_FILE
) {
1932 # Show a hint to shared repo
1933 $file = wfFindFile( $this->mTitle
);
1934 if( $file && !$file->isLocal() ) {
1935 $descUrl = $file->getDescriptionUrl();
1936 # there must be a description url to show a hint to shared repo
1938 if( !$this->mTitle
->exists() ) {
1939 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1940 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1943 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1944 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1951 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1952 # Show log extract when the user is currently blocked
1953 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1954 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1955 $username = $parts[0];
1956 $user = User
::newFromName( $username, false /* allow IP users*/ );
1957 $ip = User
::isIP( $username );
1958 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1959 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1960 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1961 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1962 LogEventsList
::showLogExtract(
1965 $user->getUserPage(),
1969 'showIfEmpty' => false,
1971 'blocked-notice-logextract',
1972 $user->getName() # Support GENDER in notice
1978 # Try to add a custom edit intro, or use the standard one if this is not possible.
1979 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
1980 if ( $wgUser->isLoggedIn() ) {
1981 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1983 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1986 # Give a notice if the user is editing a deleted/moved page...
1987 if ( !$this->mTitle
->exists() ) {
1988 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
1992 'conds' => array( "log_action != 'revision'" ),
1993 'showIfEmpty' => false,
1994 'msgKey' => array( 'recreate-moveddeleted-warn' )
2001 * Attempt to show a custom editing introduction, if supplied
2005 protected function showCustomIntro() {
2006 if ( $this->editintro
) {
2007 $title = Title
::newFromText( $this->editintro
);
2008 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2010 // Added using template syntax, to take <noinclude>'s into account.
2011 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
2019 * Gets an editable textual representation of $content.
2020 * The textual representation can be turned by into a Content object by the
2021 * toEditContent() method.
2023 * If $content is null or false or a string, $content is returned unchanged.
2025 * If the given Content object is not of a type that can be edited using the text base EditPage,
2026 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2029 * @param Content|null|bool|string $content
2030 * @return String the editable text form of the content.
2032 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
2034 protected function toEditText( $content ) {
2035 if ( $content === null ||
$content === false ) {
2039 if ( is_string( $content ) ) {
2043 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
2044 throw new MWException( "This content model can not be edited as text: "
2045 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2048 return $content->serialize( $this->contentFormat
);
2052 * Turns the given text into a Content object by unserializing it.
2054 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
2055 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2058 * @param string|null|bool $text Text to unserialize
2059 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
2062 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
2063 * and $this->allowNonTextContent is not true.
2065 protected function toEditContent( $text ) {
2066 if ( $text === false ||
$text === null ) {
2070 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2071 $this->contentModel
, $this->contentFormat
);
2073 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
2074 throw new MWException( "This content model can not be edited as text: "
2075 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2082 * Send the edit form and related headers to $wgOut
2083 * @param $formCallback Callback|null that takes an OutputPage parameter; will be called
2084 * during form output near the top, for captchas and the like.
2086 function showEditForm( $formCallback = null ) {
2087 global $wgOut, $wgUser;
2089 wfProfileIn( __METHOD__
);
2091 # need to parse the preview early so that we know which templates are used,
2092 # otherwise users with "show preview after edit box" will get a blank list
2093 # we parse this near the beginning so that setHeaders can do the title
2094 # setting work instead of leaving it in getPreviewText
2095 $previewOutput = '';
2096 if ( $this->formtype
== 'preview' ) {
2097 $previewOutput = $this->getPreviewText();
2100 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2102 $this->setHeaders();
2104 if ( $this->showHeader() === false ) {
2105 wfProfileOut( __METHOD__
);
2109 $wgOut->addHTML( $this->editFormPageTop
);
2111 if ( $wgUser->getOption( 'previewontop' ) ) {
2112 $this->displayPreviewArea( $previewOutput, true );
2115 $wgOut->addHTML( $this->editFormTextTop
);
2117 $showToolbar = true;
2118 if ( $this->wasDeletedSinceLastEdit() ) {
2119 if ( $this->formtype
== 'save' ) {
2120 // Hide the toolbar and edit area, user can click preview to get it back
2121 // Add an confirmation checkbox and explanation.
2122 $showToolbar = false;
2124 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2125 'deletedwhileediting' );
2129 //@todo: add EditForm plugin interface and use it here!
2130 // search for textarea1 and textares2, and allow EditForm to override all uses.
2131 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => self
::EDITFORM_ID
, 'name' => self
::EDITFORM_ID
,
2132 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
2133 'enctype' => 'multipart/form-data' ) ) );
2135 if ( is_callable( $formCallback ) ) {
2136 call_user_func_array( $formCallback, array( &$wgOut ) );
2139 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2141 // Put these up at the top to ensure they aren't lost on early form submission
2142 $this->showFormBeforeText();
2144 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2145 $username = $this->lastDelete
->user_name
;
2146 $comment = $this->lastDelete
->log_comment
;
2148 // It is better to not parse the comment at all than to have templates expanded in the middle
2149 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2150 $key = $comment === ''
2151 ?
'confirmrecreate-noreason'
2152 : 'confirmrecreate';
2154 '<div class="mw-confirm-recreate">' .
2155 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2156 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2157 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2163 # When the summary is hidden, also hide them on preview/show changes
2164 if( $this->nosummary
) {
2165 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2168 # If a blank edit summary was previously provided, and the appropriate
2169 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2170 # user being bounced back more than once in the event that a summary
2173 # For a bit more sophisticated detection of blank summaries, hash the
2174 # automatic one and pass that in the hidden field wpAutoSummary.
2175 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2176 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2179 if ( $this->undidRev
) {
2180 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2183 if ( $this->hasPresetSummary
) {
2184 // If a summary has been preset using &summary= we don't want to prompt for
2185 // a different summary. Only prompt for a summary if the summary is blanked.
2187 $this->autoSumm
= md5( '' );
2190 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2191 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2193 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2195 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2196 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2198 if ( $this->section
== 'new' ) {
2199 $this->showSummaryInput( true, $this->summary
);
2200 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2203 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2205 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2206 $wgOut->addHTML( EditPage
::getEditToolbar() );
2209 if ( $this->isConflict
) {
2210 // In an edit conflict bypass the overridable content form method
2211 // and fallback to the raw wpTextbox1 since editconflicts can't be
2212 // resolved between page source edits and custom ui edits using the
2214 $this->textbox2
= $this->textbox1
;
2216 $content = $this->getCurrentContent();
2217 $this->textbox1
= $this->toEditText( $content );
2219 $this->showTextbox1();
2221 $this->showContentForm();
2224 $wgOut->addHTML( $this->editFormTextAfterContent
);
2226 $this->showStandardInputs();
2228 $this->showFormAfterText();
2230 $this->showTosSummary();
2232 $this->showEditTools();
2234 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2236 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2237 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2239 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2240 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2242 if ( $this->isConflict
) {
2244 $this->showConflict();
2245 } catch ( MWContentSerializationException
$ex ) {
2246 // this can't really happen, but be nice if it does.
2247 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2248 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2252 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2254 if ( !$wgUser->getOption( 'previewontop' ) ) {
2255 $this->displayPreviewArea( $previewOutput, false );
2258 wfProfileOut( __METHOD__
);
2262 * Extract the section title from current section text, if any.
2264 * @param string $text
2265 * @return Mixed|string or false
2267 public static function extractSectionTitle( $text ) {
2268 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2269 if ( !empty( $matches[2] ) ) {
2271 return $wgParser->stripSectionName( trim( $matches[2] ) );
2277 protected function showHeader() {
2278 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2280 if ( $this->mTitle
->isTalkPage() ) {
2281 $wgOut->addWikiMsg( 'talkpagetext' );
2285 $wgOut->addHTML( implode( "\n", $this->mTitle
->getEditNotices() ) );
2287 if ( $this->isConflict
) {
2288 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2289 $this->edittime
= $this->mArticle
->getTimestamp();
2291 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2292 // We use $this->section to much before this and getVal('wgSection') directly in other places
2293 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2294 // Someone is welcome to try refactoring though
2295 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2299 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2300 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2301 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2302 if ( $sectionTitle !== false ) {
2303 $this->summary
= "/* $sectionTitle */ ";
2308 if ( $this->missingComment
) {
2309 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2312 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2313 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2316 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2317 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2320 if ( $this->hookError
!== '' ) {
2321 $wgOut->addWikiText( $this->hookError
);
2324 if ( !$this->checkUnicodeCompliantBrowser() ) {
2325 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2328 if ( $this->section
!= 'new' ) {
2329 $revision = $this->mArticle
->getRevisionFetched();
2331 // Let sysop know that this will make private content public if saved
2333 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2334 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2335 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2336 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2339 if ( !$revision->isCurrent() ) {
2340 $this->mArticle
->setOldSubtitle( $revision->getId() );
2341 $wgOut->addWikiMsg( 'editingold' );
2343 } elseif ( $this->mTitle
->exists() ) {
2344 // Something went wrong
2346 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2347 array( 'missing-revision', $this->oldid
) );
2352 if ( wfReadOnly() ) {
2353 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2354 } elseif ( $wgUser->isAnon() ) {
2355 if ( $this->formtype
!= 'preview' ) {
2356 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2358 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2361 if ( $this->isCssJsSubpage
) {
2362 # Check the skin exists
2363 if ( $this->isWrongCaseCssJsPage
) {
2364 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2366 if ( $this->formtype
!== 'preview' ) {
2367 if ( $this->isCssSubpage
) {
2368 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2371 if ( $this->isJsSubpage
) {
2372 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2378 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2379 # Is the title semi-protected?
2380 if ( $this->mTitle
->isSemiProtected() ) {
2381 $noticeMsg = 'semiprotectedpagewarning';
2383 # Then it must be protected based on static groups (regular)
2384 $noticeMsg = 'protectedpagewarning';
2386 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2387 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2389 if ( $this->mTitle
->isCascadeProtected() ) {
2390 # Is this page under cascading protection from some source pages?
2391 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2392 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2393 $cascadeSourcesCount = count( $cascadeSources );
2394 if ( $cascadeSourcesCount > 0 ) {
2395 # Explain, and list the titles responsible
2396 foreach ( $cascadeSources as $page ) {
2397 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2400 $notice .= '</div>';
2401 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2403 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2404 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2406 'showIfEmpty' => false,
2407 'msgKey' => array( 'titleprotectedwarning' ),
2408 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2411 if ( $this->kblength
=== false ) {
2412 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2415 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2416 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2417 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2419 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2420 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2421 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2425 # Add header copyright warning
2426 $this->showHeaderCopyrightWarning();
2430 * Standard summary input and label (wgSummary), abstracted so EditPage
2431 * subclasses may reorganize the form.
2432 * Note that you do not need to worry about the label's for=, it will be
2433 * inferred by the id given to the input. You can remove them both by
2434 * passing array( 'id' => false ) to $userInputAttrs.
2436 * @param string $summary The value of the summary input
2437 * @param string $labelText The html to place inside the label
2438 * @param array $inputAttrs of attrs to use on the input
2439 * @param array $spanLabelAttrs of attrs to use on the span inside the label
2441 * @return array An array in the format array( $label, $input )
2443 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2444 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2445 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2446 'id' => 'wpSummary',
2447 'maxlength' => '200',
2450 'spellcheck' => 'true',
2451 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2453 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2454 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2455 'id' => "wpSummaryLabel"
2460 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2461 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2464 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2466 return array( $label, $input );
2470 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2471 * up top, or false if this is the comment summary
2472 * down below the textarea
2473 * @param string $summary The text of the summary to display
2476 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2477 global $wgOut, $wgContLang;
2478 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2479 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2480 if ( $isSubjectPreview ) {
2481 if ( $this->nosummary
) {
2485 if ( !$this->mShowSummaryField
) {
2489 $summary = $wgContLang->recodeForEdit( $summary );
2490 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2491 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2492 $wgOut->addHTML( "{$label} {$input}" );
2496 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2497 * up top, or false if this is the comment summary
2498 * down below the textarea
2499 * @param string $summary the text of the summary to display
2502 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2503 // avoid spaces in preview, gets always trimmed on save
2504 $summary = trim( $summary );
2505 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2511 if ( $isSubjectPreview ) {
2512 $summary = wfMessage( 'newsectionsummary', $wgParser->stripSectionName( $summary ) )
2513 ->inContentLanguage()->text();
2516 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2518 $summary = wfMessage( $message )->parse() . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2519 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2522 protected function showFormBeforeText() {
2524 $section = htmlspecialchars( $this->section
);
2525 $wgOut->addHTML( <<<HTML
2526 <input type='hidden' value="{$section}" name="wpSection" />
2527 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2528 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2529 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2533 if ( !$this->checkUnicodeCompliantBrowser() ) {
2534 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2538 protected function showFormAfterText() {
2539 global $wgOut, $wgUser;
2541 * To make it harder for someone to slip a user a page
2542 * which submits an edit form to the wiki without their
2543 * knowledge, a random token is associated with the login
2544 * session. If it's not passed back with the submission,
2545 * we won't save the page, or render user JavaScript and
2548 * For anon editors, who may not have a session, we just
2549 * include the constant suffix to prevent editing from
2550 * broken text-mangling proxies.
2552 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2556 * Subpage overridable method for printing the form for page content editing
2557 * By default this simply outputs wpTextbox1
2558 * Subclasses can override this to provide a custom UI for editing;
2559 * be it a form, or simply wpTextbox1 with a modified content that will be
2560 * reverse modified when extracted from the post data.
2561 * Note that this is basically the inverse for importContentFormData
2563 protected function showContentForm() {
2564 $this->showTextbox1();
2568 * Method to output wpTextbox1
2569 * The $textoverride method can be used by subclasses overriding showContentForm
2570 * to pass back to this method.
2572 * @param array $customAttribs of html attributes to use in the textarea
2573 * @param string $textoverride optional text to override $this->textarea1 with
2575 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2576 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2577 $attribs = array( 'style' => 'display:none;' );
2579 $classes = array(); // Textarea CSS
2580 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2581 # Is the title semi-protected?
2582 if ( $this->mTitle
->isSemiProtected() ) {
2583 $classes[] = 'mw-textarea-sprotected';
2585 # Then it must be protected based on static groups (regular)
2586 $classes[] = 'mw-textarea-protected';
2588 # Is the title cascade-protected?
2589 if ( $this->mTitle
->isCascadeProtected() ) {
2590 $classes[] = 'mw-textarea-cprotected';
2594 $attribs = array( 'tabindex' => 1 );
2596 if ( is_array( $customAttribs ) ) {
2597 $attribs +
= $customAttribs;
2600 if ( count( $classes ) ) {
2601 if ( isset( $attribs['class'] ) ) {
2602 $classes[] = $attribs['class'];
2604 $attribs['class'] = implode( ' ', $classes );
2608 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2611 protected function showTextbox2() {
2612 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2615 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2616 global $wgOut, $wgUser;
2618 $wikitext = $this->safeUnicodeOutput( $text );
2619 if ( strval( $wikitext ) !== '' ) {
2620 // Ensure there's a newline at the end, otherwise adding lines
2622 // But don't add a newline if the ext is empty, or Firefox in XHTML
2623 // mode will show an extra newline. A bit annoying.
2627 $attribs = $customAttribs +
array(
2630 'cols' => $wgUser->getIntOption( 'cols' ),
2631 'rows' => $wgUser->getIntOption( 'rows' ),
2632 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2635 $pageLang = $this->mTitle
->getPageLanguage();
2636 $attribs['lang'] = $pageLang->getCode();
2637 $attribs['dir'] = $pageLang->getDir();
2639 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2642 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2646 $classes[] = 'ontop';
2649 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2651 if ( $this->formtype
!= 'preview' ) {
2652 $attribs['style'] = 'display: none;';
2655 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2657 if ( $this->formtype
== 'preview' ) {
2658 $this->showPreview( $previewOutput );
2661 $wgOut->addHTML( '</div>' );
2663 if ( $this->formtype
== 'diff' ) {
2666 } catch ( MWContentSerializationException
$ex ) {
2667 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2668 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2674 * Append preview output to $wgOut.
2675 * Includes category rendering if this is a category page.
2677 * @param string $text the HTML to be output for the preview.
2679 protected function showPreview( $text ) {
2681 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2682 $this->mArticle
->openShowCategory();
2684 # This hook seems slightly odd here, but makes things more
2685 # consistent for extensions.
2686 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2687 $wgOut->addHTML( $text );
2688 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2689 $this->mArticle
->closeShowCategory();
2694 * Get a diff between the current contents of the edit box and the
2695 * version of the page we're editing from.
2697 * If this is a section edit, we'll replace the section as for final
2698 * save and then make a comparison.
2700 function showDiff() {
2701 global $wgUser, $wgContLang, $wgOut;
2703 $oldtitlemsg = 'currentrev';
2704 # if message does not exist, show diff against the preloaded default
2705 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2706 $oldtext = $this->mTitle
->getDefaultMessageText();
2707 if( $oldtext !== false ) {
2708 $oldtitlemsg = 'defaultmessagetext';
2709 $oldContent = $this->toEditContent( $oldtext );
2714 $oldContent = $this->getCurrentContent();
2717 $textboxContent = $this->toEditContent( $this->textbox1
);
2719 $newContent = $this->mArticle
->replaceSectionContent(
2720 $this->section
, $textboxContent,
2721 $this->summary
, $this->edittime
);
2723 if ( $newContent ) {
2724 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2725 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2727 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2728 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2731 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2732 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2733 $newtitle = wfMessage( 'yourtext' )->parse();
2735 if ( !$oldContent ) {
2736 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
2739 if ( !$newContent ) {
2740 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
2743 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
2744 $de->setContent( $oldContent, $newContent );
2746 $difftext = $de->getDiff( $oldtitle, $newtitle );
2747 $de->showDiffStyle();
2752 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2756 * Show the header copyright warning.
2758 protected function showHeaderCopyrightWarning() {
2759 $msg = 'editpage-head-copy-warn';
2760 if ( !wfMessage( $msg )->isDisabled() ) {
2762 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2763 'editpage-head-copy-warn' );
2768 * Give a chance for site and per-namespace customizations of
2769 * terms of service summary link that might exist separately
2770 * from the copyright notice.
2772 * This will display between the save button and the edit tools,
2773 * so should remain short!
2775 protected function showTosSummary() {
2776 $msg = 'editpage-tos-summary';
2777 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2778 if ( !wfMessage( $msg )->isDisabled() ) {
2780 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2781 $wgOut->addWikiMsg( $msg );
2782 $wgOut->addHTML( '</div>' );
2786 protected function showEditTools() {
2788 $wgOut->addHTML( '<div class="mw-editTools">' .
2789 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2794 * Get the copyright warning
2796 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2798 protected function getCopywarn() {
2799 return self
::getCopyrightWarning( $this->mTitle
);
2802 public static function getCopyrightWarning( $title ) {
2803 global $wgRightsText;
2804 if ( $wgRightsText ) {
2805 $copywarnMsg = array( 'copyrightwarning',
2806 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2809 $copywarnMsg = array( 'copyrightwarning2',
2810 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2812 // Allow for site and per-namespace customization of contribution/copyright notice.
2813 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2815 return "<div id=\"editpage-copywarn\">\n" .
2816 call_user_func_array( 'wfMessage', $copywarnMsg )->plain() . "\n</div>";
2819 protected function showStandardInputs( &$tabindex = 2 ) {
2821 $wgOut->addHTML( "<div class='editOptions'>\n" );
2823 if ( $this->section
!= 'new' ) {
2824 $this->showSummaryInput( false, $this->summary
);
2825 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2828 $checkboxes = $this->getCheckboxes( $tabindex,
2829 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2830 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2832 // Show copyright warning.
2833 $wgOut->addWikiText( $this->getCopywarn() );
2834 $wgOut->addHTML( $this->editFormTextAfterWarn
);
2836 $wgOut->addHTML( "<div class='editButtons'>\n" );
2837 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2839 $cancel = $this->getCancelLink();
2840 if ( $cancel !== '' ) {
2841 $cancel .= wfMessage( 'pipe-separator' )->text();
2843 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
2844 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2845 wfMessage( 'edithelp' )->escaped() . '</a> ' .
2846 wfMessage( 'newwindow' )->parse();
2847 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
2848 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
2849 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
2850 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
2851 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
2855 * Show an edit conflict. textbox1 is already shown in showEditForm().
2856 * If you want to use another entry point to this function, be careful.
2858 protected function showConflict() {
2861 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2862 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2864 $content1 = $this->toEditContent( $this->textbox1
);
2865 $content2 = $this->toEditContent( $this->textbox2
);
2867 $handler = ContentHandler
::getForModelID( $this->contentModel
);
2868 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
2869 $de->setContent( $content2, $content1 );
2871 wfMessage( 'yourtext' )->parse(),
2872 wfMessage( 'storedversion' )->text()
2875 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2876 $this->showTextbox2();
2883 public function getCancelLink() {
2884 $cancelParams = array();
2885 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2886 $cancelParams['oldid'] = $this->oldid
;
2889 return Linker
::linkKnown(
2890 $this->getContextTitle(),
2891 wfMessage( 'cancel' )->parse(),
2892 array( 'id' => 'mw-editform-cancel' ),
2898 * Returns the URL to use in the form's action attribute.
2899 * This is used by EditPage subclasses when simply customizing the action
2900 * variable in the constructor is not enough. This can be used when the
2901 * EditPage lives inside of a Special page rather than a custom page action.
2903 * @param $title Title object for which is being edited (where we go to for &action= links)
2906 protected function getActionURL( Title
$title ) {
2907 return $title->getLocalURL( array( 'action' => $this->action
) );
2911 * Check if a page was deleted while the user was editing it, before submit.
2912 * Note that we rely on the logging table, which hasn't been always there,
2913 * but that doesn't matter, because this only applies to brand new
2916 protected function wasDeletedSinceLastEdit() {
2917 if ( $this->deletedSinceEdit
!== null ) {
2918 return $this->deletedSinceEdit
;
2921 $this->deletedSinceEdit
= false;
2923 if ( $this->mTitle
->isDeletedQuick() ) {
2924 $this->lastDelete
= $this->getLastDelete();
2925 if ( $this->lastDelete
) {
2926 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
2927 if ( $deleteTime > $this->starttime
) {
2928 $this->deletedSinceEdit
= true;
2933 return $this->deletedSinceEdit
;
2936 protected function getLastDelete() {
2937 $dbr = wfGetDB( DB_SLAVE
);
2938 $data = $dbr->selectRow(
2939 array( 'logging', 'user' ),
2952 'log_namespace' => $this->mTitle
->getNamespace(),
2953 'log_title' => $this->mTitle
->getDBkey(),
2954 'log_type' => 'delete',
2955 'log_action' => 'delete',
2959 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2961 // Quick paranoid permission checks...
2962 if ( is_object( $data ) ) {
2963 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
2964 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
2967 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
2968 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
2975 * Get the rendered text for previewing.
2976 * @throws MWException
2979 function getPreviewText() {
2980 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
2982 wfProfileIn( __METHOD__
);
2984 if ( $wgRawHtml && !$this->mTokenOk
) {
2985 // Could be an offsite preview attempt. This is very unsafe if
2986 // HTML is enabled, as it could be an attack.
2988 if ( $this->textbox1
!== '' ) {
2989 // Do not put big scary notice, if previewing the empty
2990 // string, which happens when you initially edit
2991 // a category page, due to automatic preview-on-open.
2992 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2993 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
2995 wfProfileOut( __METHOD__
);
3002 $content = $this->toEditContent( $this->textbox1
);
3005 if ( !wfRunHooks( 'AlternateEditPreview', array( $this, &$content, &$previewHTML, &$this->mParserOutput
) ) ) {
3006 wfProfileOut( __METHOD__
);
3007 return $previewHTML;
3010 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3011 if ( $this->mTokenOkExceptSuffix
) {
3012 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3015 $note = wfMessage( 'session_fail_preview' )->plain();
3017 } elseif ( $this->incompleteForm
) {
3018 $note = wfMessage( 'edit_form_incomplete' )->plain();
3020 $note = wfMessage( 'previewnote' )->plain() .
3021 ' [[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' . wfMessage( 'continue-editing' )->text() . ']]';
3024 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
3025 $parserOptions->setEditSection( false );
3026 $parserOptions->setIsPreview( true );
3027 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3029 # don't parse non-wikitext pages, show message about preview
3030 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3031 if( $this->mTitle
->isCssJsSubpage() ) {
3033 } elseif( $this->mTitle
->isCssOrJsPage() ) {
3039 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3041 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3047 # Used messages to make sure grep find them:
3048 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3049 if( $level && $format ) {
3050 $note = "<div id='mw-{$level}{$format}preview'>" . wfMessage( "{$level}{$format}preview" )->text() . "</div>";
3054 $rt = $content->getRedirectChain();
3056 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
3059 # If we're adding a comment, we need to show the
3060 # summary as the headline
3061 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3062 $content = $content->addSectionHeader( $this->summary
);
3065 $hook_args = array( $this, &$content );
3066 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3067 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3069 $parserOptions->enableLimitReport();
3071 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3072 # But it's now deprecated, so never mind
3074 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3075 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
3077 $previewHTML = $parserOutput->getText();
3078 $this->mParserOutput
= $parserOutput;
3079 $wgOut->addParserOutputNoText( $parserOutput );
3081 if ( count( $parserOutput->getWarnings() ) ) {
3082 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3085 } catch ( MWContentSerializationException
$ex ) {
3086 $m = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
3087 $note .= "\n\n" . $m->parse();
3091 if ( $this->isConflict
) {
3092 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3094 $conflict = '<hr />';
3097 $previewhead = "<div class='previewnote'>\n" .
3098 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3099 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3101 $pageLang = $this->mTitle
->getPageLanguage();
3102 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
3103 'class' => 'mw-content-' . $pageLang->getDir() );
3104 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3106 wfProfileOut( __METHOD__
);
3107 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3113 function getTemplates() {
3114 if ( $this->preview ||
$this->section
!= '' ) {
3115 $templates = array();
3116 if ( !isset( $this->mParserOutput
) ) {
3119 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3120 foreach ( array_keys( $template ) as $dbk ) {
3121 $templates[] = Title
::makeTitle( $ns, $dbk );
3126 return $this->mTitle
->getTemplateLinksFrom();
3131 * Shows a bulletin board style toolbar for common editing functions.
3132 * It can be disabled in the user preferences.
3133 * The necessary JavaScript code can be found in skins/common/edit.js.
3137 static function getEditToolbar() {
3138 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3139 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
3141 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3144 * $toolarray is an array of arrays each of which includes the
3145 * filename of the button image (without path), the opening
3146 * tag, the closing tag, optionally a sample text that is
3147 * inserted between the two when no selection is highlighted
3148 * and. The tip text is shown when the user moves the mouse
3151 * Also here: accesskeys (key), which are not used yet until
3152 * someone can figure out a way to make them work in
3153 * IE. However, we should make sure these keys are not defined
3158 'image' => $wgLang->getImageFile( 'button-bold' ),
3159 'id' => 'mw-editbutton-bold',
3161 'close' => '\'\'\'',
3162 'sample' => wfMessage( 'bold_sample' )->text(),
3163 'tip' => wfMessage( 'bold_tip' )->text(),
3167 'image' => $wgLang->getImageFile( 'button-italic' ),
3168 'id' => 'mw-editbutton-italic',
3171 'sample' => wfMessage( 'italic_sample' )->text(),
3172 'tip' => wfMessage( 'italic_tip' )->text(),
3176 'image' => $wgLang->getImageFile( 'button-link' ),
3177 'id' => 'mw-editbutton-link',
3180 'sample' => wfMessage( 'link_sample' )->text(),
3181 'tip' => wfMessage( 'link_tip' )->text(),
3185 'image' => $wgLang->getImageFile( 'button-extlink' ),
3186 'id' => 'mw-editbutton-extlink',
3189 'sample' => wfMessage( 'extlink_sample' )->text(),
3190 'tip' => wfMessage( 'extlink_tip' )->text(),
3194 'image' => $wgLang->getImageFile( 'button-headline' ),
3195 'id' => 'mw-editbutton-headline',
3198 'sample' => wfMessage( 'headline_sample' )->text(),
3199 'tip' => wfMessage( 'headline_tip' )->text(),
3202 $imagesAvailable ?
array(
3203 'image' => $wgLang->getImageFile( 'button-image' ),
3204 'id' => 'mw-editbutton-image',
3205 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3207 'sample' => wfMessage( 'image_sample' )->text(),
3208 'tip' => wfMessage( 'image_tip' )->text(),
3211 $imagesAvailable ?
array(
3212 'image' => $wgLang->getImageFile( 'button-media' ),
3213 'id' => 'mw-editbutton-media',
3214 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3216 'sample' => wfMessage( 'media_sample' )->text(),
3217 'tip' => wfMessage( 'media_tip' )->text(),
3221 'image' => $wgLang->getImageFile( 'button-math' ),
3222 'id' => 'mw-editbutton-math',
3224 'close' => "</math>",
3225 'sample' => wfMessage( 'math_sample' )->text(),
3226 'tip' => wfMessage( 'math_tip' )->text(),
3230 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3231 'id' => 'mw-editbutton-nowiki',
3232 'open' => "<nowiki>",
3233 'close' => "</nowiki>",
3234 'sample' => wfMessage( 'nowiki_sample' )->text(),
3235 'tip' => wfMessage( 'nowiki_tip' )->text(),
3239 'image' => $wgLang->getImageFile( 'button-sig' ),
3240 'id' => 'mw-editbutton-signature',
3244 'tip' => wfMessage( 'sig_tip' )->text(),
3248 'image' => $wgLang->getImageFile( 'button-hr' ),
3249 'id' => 'mw-editbutton-hr',
3250 'open' => "\n----\n",
3253 'tip' => wfMessage( 'hr_tip' )->text(),
3258 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3259 foreach ( $toolarray as $tool ) {
3265 $image = $wgStylePath . '/common/images/' . $tool['image'],
3266 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3267 // Older browsers show a "speedtip" type message only for ALT.
3268 // Ideally these should be different, realistically they
3269 // probably don't need to be.
3270 $tip = $tool['tip'],
3271 $open = $tool['open'],
3272 $close = $tool['close'],
3273 $sample = $tool['sample'],
3274 $cssId = $tool['id'],
3277 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3280 // This used to be called on DOMReady from mediawiki.action.edit, which
3281 // ended up causing race conditions with the setup code above.
3283 "// Create button bar\n" .
3284 "$(function() { mw.toolbar.init(); } );\n";
3287 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3289 $toolbar = '<div id="toolbar"></div>';
3291 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3297 * Returns an array of html code of the following checkboxes:
3300 * @param int $tabindex Current tabindex
3301 * @param array $checked of checkbox => bool, where bool indicates the checked
3302 * status of the checkbox
3306 public function getCheckboxes( &$tabindex, $checked ) {
3309 $checkboxes = array();
3311 // don't show the minor edit checkbox if it's a new page or section
3312 if ( !$this->isNew
) {
3313 $checkboxes['minor'] = '';
3314 $minorLabel = wfMessage( 'minoredit' )->parse();
3315 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3317 'tabindex' => ++
$tabindex,
3318 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3319 'id' => 'wpMinoredit',
3321 $checkboxes['minor'] =
3322 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3323 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3324 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3325 ">{$minorLabel}</label>";
3329 $watchLabel = wfMessage( 'watchthis' )->parse();
3330 $checkboxes['watch'] = '';
3331 if ( $wgUser->isLoggedIn() ) {
3333 'tabindex' => ++
$tabindex,
3334 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3335 'id' => 'wpWatchthis',
3337 $checkboxes['watch'] =
3338 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3339 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3340 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3341 ">{$watchLabel}</label>";
3343 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3348 * Returns an array of html code of the following buttons:
3349 * save, diff, preview and live
3351 * @param int $tabindex Current tabindex
3355 public function getEditButtons( &$tabindex ) {
3362 'tabindex' => ++
$tabindex,
3363 'value' => wfMessage( 'savearticle' )->text(),
3364 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3365 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3367 $buttons['save'] = Xml
::element( 'input', $temp, '' );
3369 ++
$tabindex; // use the same for preview and live preview
3371 'id' => 'wpPreview',
3372 'name' => 'wpPreview',
3374 'tabindex' => $tabindex,
3375 'value' => wfMessage( 'showpreview' )->text(),
3376 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3377 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3379 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3380 $buttons['live'] = '';
3386 'tabindex' => ++
$tabindex,
3387 'value' => wfMessage( 'showdiff' )->text(),
3388 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3389 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3391 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3393 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3398 * Output preview text only. This can be sucked into the edit page
3399 * via JavaScript, and saves the server time rendering the skin as
3400 * well as theoretically being more robust on the client (doesn't
3401 * disturb the edit box's undo history, won't eat your text on
3404 * @todo This doesn't include category or interlanguage links.
3405 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3406 * or something...</s>" that might also require more skin
3407 * initialization, so check whether that's a problem.
3409 function livePreview() {
3412 header( 'Content-type: text/xml; charset=utf-8' );
3413 header( 'Cache-control: no-cache' );
3415 $previewText = $this->getPreviewText();
3416 #$categories = $skin->getCategoryLinks();
3419 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3420 Xml
::tags( 'livepreview', null,
3421 Xml
::element( 'preview', null, $previewText )
3422 #. Xml::element( 'category', null, $categories )
3428 * Call the stock "user is blocked" page
3430 * @deprecated in 1.19; throw an exception directly instead
3432 function blockedPage() {
3433 wfDeprecated( __METHOD__
, '1.19' );
3436 throw new UserBlockedError( $wgUser->getBlock() );
3440 * Produce the stock "please login to edit pages" page
3442 * @deprecated in 1.19; throw an exception directly instead
3444 function userNotLoggedInPage() {
3445 wfDeprecated( __METHOD__
, '1.19' );
3446 throw new PermissionsError( 'edit' );
3450 * Show an error page saying to the user that he has insufficient permissions
3451 * to create a new page
3453 * @deprecated in 1.19; throw an exception directly instead
3455 function noCreatePermission() {
3456 wfDeprecated( __METHOD__
, '1.19' );
3457 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3458 throw new PermissionsError( $permission );
3462 * Creates a basic error page which informs the user that
3463 * they have attempted to edit a nonexistent section.
3465 function noSuchSectionPage() {
3468 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3470 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3471 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3472 $wgOut->addHTML( $res );
3474 $wgOut->returnToMain( false, $this->mTitle
);
3478 * Produce the stock "your edit contains spam" page
3480 * @param string|bool $match Text which triggered one or more filters
3481 * @deprecated since 1.17 Use method spamPageWithContent() instead
3483 static function spamPage( $match = false ) {
3484 wfDeprecated( __METHOD__
, '1.17' );
3486 global $wgOut, $wgTitle;
3488 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3490 $wgOut->addHTML( '<div id="spamprotected">' );
3491 $wgOut->addWikiMsg( 'spamprotectiontext' );
3493 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3495 $wgOut->addHTML( '</div>' );
3497 $wgOut->returnToMain( false, $wgTitle );
3501 * Show "your edit contains spam" page with your diff and text
3503 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3505 public function spamPageWithContent( $match = false ) {
3506 global $wgOut, $wgLang;
3507 $this->textbox2
= $this->textbox1
;
3509 if( is_array( $match ) ) {
3510 $match = $wgLang->listToText( $match );
3512 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3514 $wgOut->addHTML( '<div id="spamprotected">' );
3515 $wgOut->addWikiMsg( 'spamprotectiontext' );
3517 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3519 $wgOut->addHTML( '</div>' );
3521 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3524 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3525 $this->showTextbox2();
3527 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3531 * Format an anchor fragment as it would appear for a given section name
3532 * @param $text String
3536 function sectionAnchor( $text ) {
3538 return $wgParser->guessSectionNameFromWikiText( $text );
3542 * Check if the browser is on a blacklist of user-agents known to
3543 * mangle UTF-8 data on form submission. Returns true if Unicode
3544 * should make it through, false if it's known to be a problem.
3548 function checkUnicodeCompliantBrowser() {
3549 global $wgBrowserBlackList, $wgRequest;
3551 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3552 if ( $currentbrowser === false ) {
3553 // No User-Agent header sent? Trust it by default...
3557 foreach ( $wgBrowserBlackList as $browser ) {
3558 if ( preg_match( $browser, $currentbrowser ) ) {
3566 * Filter an input field through a Unicode de-armoring process if it
3567 * came from an old browser with known broken Unicode editing issues.
3569 * @param $request WebRequest
3570 * @param $field String
3574 function safeUnicodeInput( $request, $field ) {
3575 $text = rtrim( $request->getText( $field ) );
3576 return $request->getBool( 'safemode' )
3577 ?
$this->unmakesafe( $text )
3582 * @param $request WebRequest
3583 * @param $text string
3586 function safeUnicodeText( $request, $text ) {
3587 $text = rtrim( $text );
3588 return $request->getBool( 'safemode' )
3589 ?
$this->unmakesafe( $text )
3594 * Filter an output field through a Unicode armoring process if it is
3595 * going to an old browser with known broken Unicode editing issues.
3597 * @param $text String
3601 function safeUnicodeOutput( $text ) {
3603 $codedText = $wgContLang->recodeForEdit( $text );
3604 return $this->checkUnicodeCompliantBrowser()
3606 : $this->makesafe( $codedText );
3610 * A number of web browsers are known to corrupt non-ASCII characters
3611 * in a UTF-8 text editing environment. To protect against this,
3612 * detected browsers will be served an armored version of the text,
3613 * with non-ASCII chars converted to numeric HTML character references.
3615 * Preexisting such character references will have a 0 added to them
3616 * to ensure that round-trips do not alter the original data.
3618 * @param $invalue String
3622 function makesafe( $invalue ) {
3623 // Armor existing references for reversibility.
3624 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3629 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3630 $bytevalue = ord( $invalue[$i] );
3631 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3632 $result .= chr( $bytevalue );
3634 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3635 $working = $working << 6;
3636 $working +
= ( $bytevalue & 0x3F );
3638 if ( $bytesleft <= 0 ) {
3639 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3641 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3642 $working = $bytevalue & 0x1F;
3644 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3645 $working = $bytevalue & 0x0F;
3647 } else { // 1111 0xxx
3648 $working = $bytevalue & 0x07;
3656 * Reverse the previously applied transliteration of non-ASCII characters
3657 * back to UTF-8. Used to protect data from corruption by broken web browsers
3658 * as listed in $wgBrowserBlackList.
3660 * @param $invalue String
3664 function unmakesafe( $invalue ) {
3666 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3667 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3671 $hexstring .= $invalue[$i];
3673 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3675 // Do some sanity checks. These aren't needed for reversibility,
3676 // but should help keep the breakage down if the editor
3677 // breaks one of the entities whilst editing.
3678 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3679 $codepoint = hexdec( $hexstring );
3680 $result .= codepointToUtf8( $codepoint );
3682 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3685 $result .= substr( $invalue, $i, 1 );
3688 // reverse the transform that we made for reversibility reasons.
3689 return strtr( $result, array( "�" => "&#x" ) );