3 * User interface for page editing.
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.
40 * Status: Article successfully updated
42 const AS_SUCCESS_UPDATE
= 200;
45 * Status: Article successfully created
47 const AS_SUCCESS_NEW_ARTICLE
= 201;
50 * Status: Article update aborted by a hook function
52 const AS_HOOK_ERROR
= 210;
55 * Status: A hook function returned an error
57 const AS_HOOK_ERROR_EXPECTED
= 212;
60 * Status: User is blocked from editing this page
62 const AS_BLOCKED_PAGE_FOR_USER
= 215;
65 * Status: Content too big (> $wgMaxArticleSize)
67 const AS_CONTENT_TOO_BIG
= 216;
70 * Status: this anonymous user is not allowed to edit this page
72 const AS_READ_ONLY_PAGE_ANON
= 218;
75 * Status: this logged in user is not allowed to edit this page
77 const AS_READ_ONLY_PAGE_LOGGED
= 219;
80 * Status: wiki is in readonly mode (wfReadOnly() == true)
82 const AS_READ_ONLY_PAGE
= 220;
85 * Status: rate limiter for action 'edit' was tripped
87 const AS_RATE_LIMITED
= 221;
90 * Status: article was deleted while editing and param wpRecreate == false or form
93 const AS_ARTICLE_WAS_DELETED
= 222;
96 * Status: user tried to create this page, but is not allowed to do that
97 * ( Title->userCan('create') == false )
99 const AS_NO_CREATE_PERMISSION
= 223;
102 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
104 const AS_BLANK_ARTICLE
= 224;
107 * Status: (non-resolvable) edit conflict
109 const AS_CONFLICT_DETECTED
= 225;
112 * Status: no edit summary given and the user has forceeditsummary set and the user is not
113 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
115 const AS_SUMMARY_NEEDED
= 226;
118 * Status: user tried to create a new section without content
120 const AS_TEXTBOX_EMPTY
= 228;
123 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
125 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
128 * Status: WikiPage::doEdit() was unsuccessful
133 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
135 const AS_SPAM_ERROR
= 232;
138 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
140 const AS_IMAGE_REDIRECT_ANON
= 233;
143 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
145 const AS_IMAGE_REDIRECT_LOGGED
= 234;
148 * Status: can't parse content
150 const AS_PARSE_ERROR
= 240;
153 * HTML id and name for the beginning of the edit form.
155 const EDITFORM_ID
= 'editform';
158 * Prefix of key for cookie used to pass post-edit state.
159 * The revision id edited is added after this
161 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
164 * Duration of PostEdit cookie, in seconds.
165 * The cookie will be removed instantly if the JavaScript runs.
167 * Otherwise, though, we don't want the cookies to accumulate.
168 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
169 * limit of only 20 cookies per domain. This still applies at least to some
170 * versions of IE without full updates:
171 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
173 * A value of 20 minutes should be enough to take into account slow loads and minor
174 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
176 const POST_EDIT_COOKIE_DURATION
= 1200;
184 /** @var null|Title */
185 private $mContextTitle = null;
188 protected $action = 'submit';
191 public $isConflict = false;
194 public $isCssJsSubpage = false;
197 public $isCssSubpage = false;
200 public $isJsSubpage = false;
203 protected $isWrongCaseCssJsPage = false;
205 /** @var bool New page or new section */
206 protected $isNew = false;
209 protected $deletedSinceEdit;
217 /** @var bool|stdClass */
218 protected $lastDelete;
221 * This is public because SemanticForms uses it (bug 67522).
222 * However, please consider using this property publicly
226 public $mTokenOk = false;
229 protected $mTokenOkExceptSuffix = false;
232 protected $mTriedSave = false;
235 protected $incompleteForm = false;
238 protected $tooBig = false;
241 protected $kblength = false;
244 protected $missingComment = false;
247 protected $missingSummary = false;
250 protected $allowBlankSummary = false;
253 protected $blankArticle = false;
256 protected $allowBlankArticle = false;
259 protected $autoSumm = '';
262 public $hookError = '';
264 /** @var ParserOutput */
265 protected $mParserOutput;
267 /** @var bool Has a summary been preset using GET parameter &summary= ? */
268 protected $hasPresetSummary = false;
271 protected $mBaseRevision = false;
274 public $mShowSummaryField = true;
279 public $save = false;
282 public $preview = false;
285 protected $diff = false;
288 public $minoredit = false;
291 protected $watchthis = false;
294 protected $recreate = false;
297 public $textbox1 = '';
300 public $textbox2 = '';
303 public $summary = '';
306 protected $nosummary = false;
309 public $edittime = '';
312 public $section = '';
315 public $sectiontitle = '';
318 protected $starttime = '';
324 protected $editintro = '';
327 public $scrolltop = null;
332 /** @var null|string */
333 public $contentModel = null;
335 /** @var null|string */
336 public $contentFormat = null;
338 # Placeholders for text injection by hooks (must be HTML)
339 # extensions should take care to _append_ to the present value
341 /** @var string Before even the preview */
342 public $editFormPageTop = '';
343 public $editFormTextTop = '';
344 public $editFormTextBeforeContent = '';
345 public $editFormTextAfterWarn = '';
346 public $editFormTextAfterTools = '';
347 public $editFormTextBottom = '';
348 public $editFormTextAfterContent = '';
349 public $previewTextAfterContent = '';
350 public $mPreloadContent = null;
352 /* $didSave should be set to true whenever an article was successfully altered. */
353 public $didSave = false;
354 public $undidRev = 0;
356 public $suppressIntro = false;
358 /** @var bool Set to true to allow editing of non-text content types. */
359 public $allowNonTextContent = false;
368 * @param Article $article
370 public function __construct( Article
$article ) {
371 $this->mArticle
= $article;
372 $this->mTitle
= $article->getTitle();
374 $this->contentModel
= $this->mTitle
->getContentModel();
376 $handler = ContentHandler
::getForModelID( $this->contentModel
);
377 $this->contentFormat
= $handler->getDefaultFormat();
383 public function getArticle() {
384 return $this->mArticle
;
391 public function getTitle() {
392 return $this->mTitle
;
396 * Set the context Title object
398 * @param Title|null $title Title object or null
400 public function setContextTitle( $title ) {
401 $this->mContextTitle
= $title;
405 * Get the context title object.
406 * If not set, $wgTitle will be returned. This behavior might change in
407 * the future to return $this->mTitle instead.
411 public function getContextTitle() {
412 if ( is_null( $this->mContextTitle
) ) {
416 return $this->mContextTitle
;
421 * Returns if the given content model is editable.
423 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
425 * @throws MWException If $modelId has no known handler
427 public function isSupportedContentModel( $modelId ) {
428 return $this->allowNonTextContent ||
429 ContentHandler
::getForModelID( $modelId ) instanceof TextContentHandler
;
437 * This is the function that gets called for "action=edit". It
438 * sets up various member variables, then passes execution to
439 * another function, usually showEditForm()
441 * The edit form is self-submitting, so that when things like
442 * preview and edit conflicts occur, we get the same form back
443 * with the extra stuff added. Only when the final submission
444 * is made and all is well do we actually save and redirect to
445 * the newly-edited page.
448 global $wgOut, $wgRequest, $wgUser;
449 // Allow extensions to modify/prevent this form or submission
450 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
454 wfProfileIn( __METHOD__
);
455 wfDebug( __METHOD__
. ": enter\n" );
457 // If they used redlink=1 and the page exists, redirect to the main article
458 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
459 $wgOut->redirect( $this->mTitle
->getFullURL() );
460 wfProfileOut( __METHOD__
);
464 $this->importFormData( $wgRequest );
465 $this->firsttime
= false;
468 $this->livePreview();
469 wfProfileOut( __METHOD__
);
473 if ( wfReadOnly() && $this->save
) {
476 $this->preview
= true;
480 $this->formtype
= 'save';
481 } elseif ( $this->preview
) {
482 $this->formtype
= 'preview';
483 } elseif ( $this->diff
) {
484 $this->formtype
= 'diff';
485 } else { # First time through
486 $this->firsttime
= true;
487 if ( $this->previewOnOpen() ) {
488 $this->formtype
= 'preview';
490 $this->formtype
= 'initial';
494 $permErrors = $this->getEditPermissionErrors();
496 wfDebug( __METHOD__
. ": User can't edit\n" );
497 // Auto-block user's IP if the account was "hard" blocked
498 $wgUser->spreadAnyEditBlock();
500 $this->displayPermissionsError( $permErrors );
502 wfProfileOut( __METHOD__
);
506 wfProfileIn( __METHOD__
. "-business-end" );
508 $this->isConflict
= false;
509 // css / js subpages of user pages get a special treatment
510 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
511 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
512 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
513 // @todo FIXME: Silly assignment.
514 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
516 # Show applicable editing introductions
517 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
521 # Attempt submission here. This will check for edit conflicts,
522 # and redundantly check for locked database, blocked IPs, etc.
523 # that edit() already checked just in case someone tries to sneak
524 # in the back door with a hand-edited submission URL.
526 if ( 'save' == $this->formtype
) {
527 if ( !$this->attemptSave() ) {
528 wfProfileOut( __METHOD__
. "-business-end" );
529 wfProfileOut( __METHOD__
);
534 # First time through: get contents, set time for conflict
536 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
537 if ( $this->initialiseForm() === false ) {
538 $this->noSuchSectionPage();
539 wfProfileOut( __METHOD__
. "-business-end" );
540 wfProfileOut( __METHOD__
);
544 if ( !$this->mTitle
->getArticleID() ) {
545 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
547 wfRunHooks( 'EditFormInitialText', array( $this ) );
552 $this->showEditForm();
553 wfProfileOut( __METHOD__
. "-business-end" );
554 wfProfileOut( __METHOD__
);
560 protected function getEditPermissionErrors() {
562 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
563 # Can this title be created?
564 if ( !$this->mTitle
->exists() ) {
565 $permErrors = array_merge( $permErrors,
566 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
568 # Ignore some permissions errors when a user is just previewing/viewing diffs
570 foreach ( $permErrors as $error ) {
571 if ( ( $this->preview ||
$this->diff
)
572 && ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' )
577 $permErrors = wfArrayDiff2( $permErrors, $remove );
582 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
583 * but with the following differences:
584 * - If redlink=1, the user will be redirected to the page
585 * - If there is content to display or the error occurs while either saving,
586 * previewing or showing the difference, it will be a
587 * "View source for ..." page displaying the source code after the error message.
590 * @param array $permErrors Array of permissions errors, as returned by
591 * Title::getUserPermissionsErrors().
592 * @throws PermissionsError
594 protected function displayPermissionsError( array $permErrors ) {
595 global $wgRequest, $wgOut;
597 if ( $wgRequest->getBool( 'redlink' ) ) {
598 // The edit page was reached via a red link.
599 // Redirect to the article page and let them click the edit tab if
600 // they really want a permission error.
601 $wgOut->redirect( $this->mTitle
->getFullURL() );
605 $content = $this->getContentObject();
607 # Use the normal message if there's nothing to display
608 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
609 $action = $this->mTitle
->exists() ?
'edit' :
610 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
611 throw new PermissionsError( $action, $permErrors );
614 wfRunHooks( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
616 $wgOut->setRobotPolicy( 'noindex,nofollow' );
617 $wgOut->setPageTitle( wfMessage(
619 $this->getContextTitle()->getPrefixedText()
621 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
622 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
623 $wgOut->addHTML( "<hr />\n" );
625 # If the user made changes, preserve them when showing the markup
626 # (This happens when a user is blocked during edit, for instance)
627 if ( !$this->firsttime
) {
628 $text = $this->textbox1
;
629 $wgOut->addWikiMsg( 'viewyourtext' );
631 $text = $this->toEditText( $content );
632 $wgOut->addWikiMsg( 'viewsourcetext' );
635 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
637 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
638 Linker
::formatTemplates( $this->getTemplates() ) ) );
640 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
642 if ( $this->mTitle
->exists() ) {
643 $wgOut->returnToMain( null, $this->mTitle
);
648 * Should we show a preview when the edit form is first shown?
652 protected function previewOnOpen() {
653 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
654 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
655 // Explicit override from request
657 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
658 // Explicit override from request
660 } elseif ( $this->section
== 'new' ) {
661 // Nothing *to* preview for new sections
663 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
664 && $wgUser->getOption( 'previewonfirst' )
666 // Standard preference behavior
668 } elseif ( !$this->mTitle
->exists()
669 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
670 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
672 // Categories are special
680 * Checks whether the user entered a skin name in uppercase,
681 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
685 protected function isWrongCaseCssJsPage() {
686 if ( $this->mTitle
->isCssJsSubpage() ) {
687 $name = $this->mTitle
->getSkinFromCssJsSubpage();
688 $skins = array_merge(
689 array_keys( Skin
::getSkinNames() ),
692 return !in_array( $name, $skins )
693 && in_array( strtolower( $name ), $skins );
700 * Returns whether section editing is supported for the current page.
701 * Subclasses may override this to replace the default behavior, which is
702 * to check ContentHandler::supportsSections.
704 * @return bool True if this edit page supports sections, false otherwise.
706 protected function isSectionEditSupported() {
707 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
708 return $contentHandler->supportsSections();
712 * This function collects the form data and uses it to populate various member variables.
713 * @param WebRequest $request
714 * @throws ErrorPageError
716 function importFormData( &$request ) {
717 global $wgContLang, $wgUser;
719 wfProfileIn( __METHOD__
);
721 # Section edit can come from either the form or a link
722 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
724 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
725 wfProfileOut( __METHOD__
);
726 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
729 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
731 if ( $request->wasPosted() ) {
732 # These fields need to be checked for encoding.
733 # Also remove trailing whitespace, but don't remove _initial_
734 # whitespace from the text boxes. This may be significant formatting.
735 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
736 if ( !$request->getCheck( 'wpTextbox2' ) ) {
737 // Skip this if wpTextbox2 has input, it indicates that we came
738 // from a conflict page with raw page text, not a custom form
739 // modified by subclasses
740 wfProfileIn( get_class( $this ) . "::importContentFormData" );
741 $textbox1 = $this->importContentFormData( $request );
742 if ( $textbox1 !== null ) {
743 $this->textbox1
= $textbox1;
746 wfProfileOut( get_class( $this ) . "::importContentFormData" );
749 # Truncate for whole multibyte characters
750 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
752 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
753 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
755 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
757 # Treat sectiontitle the same way as summary.
758 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
759 # currently doing double duty as both edit summary and section title. Right now this
760 # is just to allow API edits to work around this limitation, but this should be
761 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
762 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
763 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
765 $this->edittime
= $request->getVal( 'wpEdittime' );
766 $this->starttime
= $request->getVal( 'wpStarttime' );
768 $undidRev = $request->getInt( 'wpUndidRevision' );
770 $this->undidRev
= $undidRev;
773 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
775 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
776 // wpTextbox1 field is missing, possibly due to being "too big"
777 // according to some filter rules such as Suhosin's setting for
778 // suhosin.request.max_value_length (d'oh)
779 $this->incompleteForm
= true;
781 // If we receive the last parameter of the request, we can fairly
782 // claim the POST request has not been truncated.
784 // TODO: softened the check for cutover. Once we determine
785 // that it is safe, we should complete the transition by
786 // removing the "edittime" clause.
787 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' ) && is_null( $this->edittime
) );
789 if ( $this->incompleteForm
) {
790 # If the form is incomplete, force to preview.
791 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
792 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
793 $this->preview
= true;
795 /* Fallback for live preview */
796 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
797 $this->diff
= $request->getCheck( 'wpDiff' );
799 // Remember whether a save was requested, so we can indicate
800 // if we forced preview due to session failure.
801 $this->mTriedSave
= !$this->preview
;
803 if ( $this->tokenOk( $request ) ) {
804 # Some browsers will not report any submit button
805 # if the user hits enter in the comment box.
806 # The unmarked state will be assumed to be a save,
807 # if the form seems otherwise complete.
808 wfDebug( __METHOD__
. ": Passed token check.\n" );
809 } elseif ( $this->diff
) {
810 # Failed token check, but only requested "Show Changes".
811 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
813 # Page might be a hack attempt posted from
814 # an external site. Preview instead of saving.
815 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
816 $this->preview
= true;
819 $this->save
= !$this->preview
&& !$this->diff
;
820 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
821 $this->edittime
= null;
824 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
825 $this->starttime
= null;
828 $this->recreate
= $request->getCheck( 'wpRecreate' );
830 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
831 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
833 # Don't force edit summaries when a user is editing their own user or talk page
834 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
835 && $this->mTitle
->getText() == $wgUser->getName()
837 $this->allowBlankSummary
= true;
839 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
840 ||
!$wgUser->getOption( 'forceeditsummary' );
843 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
845 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
847 # Not a posted form? Start with nothing.
848 wfDebug( __METHOD__
. ": Not a posted form.\n" );
849 $this->textbox1
= '';
851 $this->sectiontitle
= '';
852 $this->edittime
= '';
853 $this->starttime
= wfTimestampNow();
855 $this->preview
= false;
858 $this->minoredit
= false;
859 // Watch may be overridden by request parameters
860 $this->watchthis
= $request->getBool( 'watchthis', false );
861 $this->recreate
= false;
863 // When creating a new section, we can preload a section title by passing it as the
864 // preloadtitle parameter in the URL (Bug 13100)
865 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
866 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
867 // Once wpSummary isn't being use for setting section titles, we should delete this.
868 $this->summary
= $request->getVal( 'preloadtitle' );
869 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
870 $this->summary
= $request->getText( 'summary' );
871 if ( $this->summary
!== '' ) {
872 $this->hasPresetSummary
= true;
876 if ( $request->getVal( 'minor' ) ) {
877 $this->minoredit
= true;
881 $this->oldid
= $request->getInt( 'oldid' );
883 $this->bot
= $request->getBool( 'bot', true );
884 $this->nosummary
= $request->getBool( 'nosummary' );
886 // May be overridden by revision.
887 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
888 // May be overridden by revision.
889 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
891 if ( !ContentHandler
::getForModelID( $this->contentModel
)
892 ->isSupportedFormat( $this->contentFormat
)
894 throw new ErrorPageError(
895 'editpage-notsupportedcontentformat-title',
896 'editpage-notsupportedcontentformat-text',
897 array( $this->contentFormat
, ContentHandler
::getLocalizedName( $this->contentModel
) )
902 * @todo Check if the desired model is allowed in this namespace, and if
903 * a transition from the page's current model to the new model is
907 $this->live
= $request->getCheck( 'live' );
908 $this->editintro
= $request->getText( 'editintro',
909 // Custom edit intro for new sections
910 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
912 // Allow extensions to modify form data
913 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
915 wfProfileOut( __METHOD__
);
919 * Subpage overridable method for extracting the page content data from the
920 * posted form to be placed in $this->textbox1, if using customized input
921 * this method should be overridden and return the page text that will be used
922 * for saving, preview parsing and so on...
924 * @param WebRequest $request
926 protected function importContentFormData( &$request ) {
927 return; // Don't do anything, EditPage already extracted wpTextbox1
931 * Initialise form fields in the object
932 * Called on the first invocation, e.g. when a user clicks an edit link
933 * @return bool If the requested section is valid
935 function initialiseForm() {
937 $this->edittime
= $this->mArticle
->getTimestamp();
939 $content = $this->getContentObject( false ); #TODO: track content object?!
940 if ( $content === false ) {
943 $this->textbox1
= $this->toEditText( $content );
945 // activate checkboxes if user wants them to be always active
946 # Sort out the "watch" checkbox
947 if ( $wgUser->getOption( 'watchdefault' ) ) {
949 $this->watchthis
= true;
950 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
952 $this->watchthis
= true;
953 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
955 $this->watchthis
= true;
957 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
958 $this->minoredit
= true;
960 if ( $this->textbox1
=== false ) {
967 * @param Content|null $def_content The default value to return
969 * @return Content|null Content on success, $def_content for invalid sections
973 protected function getContentObject( $def_content = null ) {
974 global $wgOut, $wgRequest, $wgUser, $wgContLang;
976 wfProfileIn( __METHOD__
);
980 // For message page not locally set, use the i18n message.
981 // For other non-existent articles, use preload text if any.
982 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
983 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
984 # If this is a system message, get the default text.
985 $msg = $this->mTitle
->getDefaultMessageText();
987 $content = $this->toEditContent( $msg );
989 if ( $content === false ) {
990 # If requested, preload some text.
991 $preload = $wgRequest->getVal( 'preload',
992 // Custom preload text for new sections
993 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
994 $params = $wgRequest->getArray( 'preloadparams', array() );
996 $content = $this->getPreloadedContent( $preload, $params );
998 // For existing pages, get text based on "undo" or section parameters.
1000 if ( $this->section
!= '' ) {
1001 // Get section edit text (returns $def_text for invalid sections)
1002 $orig = $this->getOriginalContent( $wgUser );
1003 $content = $orig ?
$orig->getSection( $this->section
) : null;
1006 $content = $def_content;
1009 $undoafter = $wgRequest->getInt( 'undoafter' );
1010 $undo = $wgRequest->getInt( 'undo' );
1012 if ( $undo > 0 && $undoafter > 0 ) {
1014 $undorev = Revision
::newFromId( $undo );
1015 $oldrev = Revision
::newFromId( $undoafter );
1017 # Sanity check, make sure it's the right page,
1018 # the revisions exist and they were not deleted.
1019 # Otherwise, $content will be left as-is.
1020 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1021 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1022 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
1024 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
1026 if ( $content === false ) {
1027 # Warn the user that something went wrong
1028 $undoMsg = 'failure';
1030 $oldContent = $this->mArticle
->getPage()->getContent( Revision
::RAW
);
1031 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
1032 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
1034 if ( $newContent->equals( $oldContent ) ) {
1035 # Tell the user that the undo results in no change,
1036 # i.e. the revisions were already undone.
1037 $undoMsg = 'nochange';
1040 # Inform the user of our success and set an automatic edit summary
1041 $undoMsg = 'success';
1043 # If we just undid one rev, use an autosummary
1044 $firstrev = $oldrev->getNext();
1045 if ( $firstrev && $firstrev->getId() == $undo ) {
1046 $userText = $undorev->getUserText();
1047 if ( $userText === '' ) {
1048 $undoSummary = wfMessage(
1049 'undo-summary-username-hidden',
1051 )->inContentLanguage()->text();
1053 $undoSummary = wfMessage(
1057 )->inContentLanguage()->text();
1059 if ( $this->summary
=== '' ) {
1060 $this->summary
= $undoSummary;
1062 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
1063 ->inContentLanguage()->text() . $this->summary
;
1065 $this->undidRev
= $undo;
1067 $this->formtype
= 'diff';
1071 // Failed basic sanity checks.
1072 // Older revisions may have been removed since the link
1073 // was created, or we may simply have got bogus input.
1077 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1078 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1079 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
1080 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1083 if ( $content === false ) {
1084 $content = $this->getOriginalContent( $wgUser );
1089 wfProfileOut( __METHOD__
);
1094 * Get the content of the wanted revision, without section extraction.
1096 * The result of this function can be used to compare user's input with
1097 * section replaced in its context (using WikiPage::replaceSection())
1098 * to the original text of the edit.
1100 * This differs from Article::getContent() that when a missing revision is
1101 * encountered the result will be null and not the
1102 * 'missing-revision' message.
1105 * @param User $user The user to get the revision for
1106 * @return Content|null
1108 private function getOriginalContent( User
$user ) {
1109 if ( $this->section
== 'new' ) {
1110 return $this->getCurrentContent();
1112 $revision = $this->mArticle
->getRevisionFetched();
1113 if ( $revision === null ) {
1114 if ( !$this->contentModel
) {
1115 $this->contentModel
= $this->getTitle()->getContentModel();
1117 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1119 return $handler->makeEmptyContent();
1121 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1126 * Get the current content of the page. This is basically similar to
1127 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1128 * content object is returned instead of null.
1133 protected function getCurrentContent() {
1134 $rev = $this->mArticle
->getRevision();
1135 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1137 if ( $content === false ||
$content === null ) {
1138 if ( !$this->contentModel
) {
1139 $this->contentModel
= $this->getTitle()->getContentModel();
1141 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1143 return $handler->makeEmptyContent();
1145 # nasty side-effect, but needed for consistency
1146 $this->contentModel
= $rev->getContentModel();
1147 $this->contentFormat
= $rev->getContentFormat();
1154 * Use this method before edit() to preload some content into the edit box
1156 * @param Content $content
1160 public function setPreloadedContent( Content
$content ) {
1161 $this->mPreloadContent
= $content;
1165 * Get the contents to be preloaded into the box, either set by
1166 * an earlier setPreloadText() or by loading the given page.
1168 * @param string $preload Representing the title to preload from.
1169 * @param array $params Parameters to use (interface-message style) in the preloaded text
1175 protected function getPreloadedContent( $preload, $params = array() ) {
1178 if ( !empty( $this->mPreloadContent
) ) {
1179 return $this->mPreloadContent
;
1182 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1184 if ( $preload === '' ) {
1185 return $handler->makeEmptyContent();
1188 $title = Title
::newFromText( $preload );
1189 # Check for existence to avoid getting MediaWiki:Noarticletext
1190 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1191 //TODO: somehow show a warning to the user!
1192 return $handler->makeEmptyContent();
1195 $page = WikiPage
::factory( $title );
1196 if ( $page->isRedirect() ) {
1197 $title = $page->getRedirectTarget();
1199 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1200 //TODO: somehow show a warning to the user!
1201 return $handler->makeEmptyContent();
1203 $page = WikiPage
::factory( $title );
1206 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1207 $content = $page->getContent( Revision
::RAW
);
1210 //TODO: somehow show a warning to the user!
1211 return $handler->makeEmptyContent();
1214 if ( $content->getModel() !== $handler->getModelID() ) {
1215 $converted = $content->convert( $handler->getModelID() );
1217 if ( !$converted ) {
1218 //TODO: somehow show a warning to the user!
1219 wfDebug( "Attempt to preload incompatible content: "
1220 . "can't convert " . $content->getModel()
1221 . " to " . $handler->getModelID() );
1223 return $handler->makeEmptyContent();
1226 $content = $converted;
1229 return $content->preloadTransform( $title, $parserOptions, $params );
1233 * Make sure the form isn't faking a user's credentials.
1235 * @param WebRequest $request
1239 function tokenOk( &$request ) {
1241 $token = $request->getVal( 'wpEditToken' );
1242 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1243 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1244 return $this->mTokenOk
;
1248 * Sets post-edit cookie indicating the user just saved a particular revision.
1250 * This uses a temporary cookie for each revision ID so separate saves will never
1251 * interfere with each other.
1253 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1254 * the redirect. It must be clearable by JavaScript code, so it must not be
1255 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1258 * If the variable were set on the server, it would be cached, which is unwanted
1259 * since the post-edit state should only apply to the load right after the save.
1261 * @param int $statusValue The status value (to check for new article status)
1263 protected function setPostEditCookie( $statusValue ) {
1264 $revisionId = $this->mArticle
->getLatest();
1265 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1268 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1270 } elseif ( $this->oldid
) {
1274 $response = RequestContext
::getMain()->getRequest()->response();
1275 $response->setcookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
, array(
1276 'httpOnly' => false,
1281 * Attempt submission
1282 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1283 * @return bool False if output is done, true if the rest of the form should be displayed
1285 public function attemptSave() {
1288 $resultDetails = false;
1289 # Allow bots to exempt some edits from bot flagging
1290 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1291 $status = $this->internalAttemptSave( $resultDetails, $bot );
1293 return $this->handleStatus( $status, $resultDetails );
1297 * Handle status, such as after attempt save
1299 * @param Status $status
1300 * @param array|bool $resultDetails
1302 * @throws ErrorPageError
1303 * @return bool False, if output is done, true if rest of the form should be displayed
1305 private function handleStatus( Status
$status, $resultDetails ) {
1306 global $wgUser, $wgOut;
1309 * @todo FIXME: once the interface for internalAttemptSave() is made
1310 * nicer, this should use the message in $status
1312 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1313 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1315 $this->didSave
= true;
1316 if ( !$resultDetails['nullEdit'] ) {
1317 $this->setPostEditCookie( $status->value
);
1321 switch ( $status->value
) {
1322 case self
::AS_HOOK_ERROR_EXPECTED
:
1323 case self
::AS_CONTENT_TOO_BIG
:
1324 case self
::AS_ARTICLE_WAS_DELETED
:
1325 case self
::AS_CONFLICT_DETECTED
:
1326 case self
::AS_SUMMARY_NEEDED
:
1327 case self
::AS_TEXTBOX_EMPTY
:
1328 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1330 case self
::AS_BLANK_ARTICLE
:
1333 case self
::AS_HOOK_ERROR
:
1336 case self
::AS_PARSE_ERROR
:
1337 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1340 case self
::AS_SUCCESS_NEW_ARTICLE
:
1341 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1342 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1343 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1346 case self
::AS_SUCCESS_UPDATE
:
1348 $sectionanchor = $resultDetails['sectionanchor'];
1350 // Give extensions a chance to modify URL query on update
1352 'ArticleUpdateBeforeRedirect',
1353 array( $this->mArticle
, &$sectionanchor, &$extraQuery )
1356 if ( $resultDetails['redirect'] ) {
1357 if ( $extraQuery == '' ) {
1358 $extraQuery = 'redirect=no';
1360 $extraQuery = 'redirect=no&' . $extraQuery;
1363 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1366 case self
::AS_SPAM_ERROR
:
1367 $this->spamPageWithContent( $resultDetails['spam'] );
1370 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1371 throw new UserBlockedError( $wgUser->getBlock() );
1373 case self
::AS_IMAGE_REDIRECT_ANON
:
1374 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1375 throw new PermissionsError( 'upload' );
1377 case self
::AS_READ_ONLY_PAGE_ANON
:
1378 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1379 throw new PermissionsError( 'edit' );
1381 case self
::AS_READ_ONLY_PAGE
:
1382 throw new ReadOnlyError
;
1384 case self
::AS_RATE_LIMITED
:
1385 throw new ThrottledError();
1387 case self
::AS_NO_CREATE_PERMISSION
:
1388 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1389 throw new PermissionsError( $permission );
1392 // We don't recognize $status->value. The only way that can happen
1393 // is if an extension hook aborted from inside ArticleSave.
1394 // Render the status object into $this->hookError
1395 // FIXME this sucks, we should just use the Status object throughout
1396 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1403 * Run hooks that can filter edits just before they get saved.
1405 * @param Content $content The Content to filter.
1406 * @param Status $status For reporting the outcome to the caller
1407 * @param User $user The user performing the edit
1411 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1412 // Run old style post-section-merge edit filter
1413 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1414 array( $this, $content, &$this->hookError
, $this->summary
) ) ) {
1416 # Error messages etc. could be handled within the hook...
1417 $status->fatal( 'hookaborted' );
1418 $status->value
= self
::AS_HOOK_ERROR
;
1420 } elseif ( $this->hookError
!= '' ) {
1421 # ...or the hook could be expecting us to produce an error
1422 $status->fatal( 'hookaborted' );
1423 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1427 // Run new style post-section-merge edit filter
1428 if ( !wfRunHooks( 'EditFilterMergedContent',
1429 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1430 $user, $this->minoredit
) ) ) {
1432 # Error messages etc. could be handled within the hook...
1433 // XXX: $status->value may already be something informative...
1434 $this->hookError
= $status->getWikiText();
1435 $status->fatal( 'hookaborted' );
1436 $status->value
= self
::AS_HOOK_ERROR
;
1438 } elseif ( !$status->isOK() ) {
1439 # ...or the hook could be expecting us to produce an error
1440 // FIXME this sucks, we should just use the Status object throughout
1441 $this->hookError
= $status->getWikiText();
1442 $status->fatal( 'hookaborted' );
1443 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1451 * Return the summary to be used for a new section.
1453 * @param string $sectionanchor Set to the section anchor text
1456 private function newSectionSummary( &$sectionanchor = null ) {
1459 if ( $this->sectiontitle
!== '' ) {
1460 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1461 // If no edit summary was specified, create one automatically from the section
1462 // title and have it link to the new section. Otherwise, respect the summary as
1464 if ( $this->summary
=== '' ) {
1465 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1466 return wfMessage( 'newsectionsummary' )
1467 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1469 } elseif ( $this->summary
!== '' ) {
1470 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1471 # This is a new section, so create a link to the new section
1472 # in the revision summary.
1473 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1474 return wfMessage( 'newsectionsummary' )
1475 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1477 return $this->summary
;
1481 * Attempt submission (no UI)
1483 * @param array $result Array to add statuses to, currently with the
1485 * - spam (string): Spam string from content if any spam is detected by
1487 * - sectionanchor (string): Section anchor for a section save.
1488 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1490 * - redirect (bool): Set if doEditContent is OK. True if resulting
1491 * revision is a redirect.
1492 * @param bool $bot True if edit is being made under the bot right.
1494 * @return Status Status object, possibly with a message, but always with
1495 * one of the AS_* constants in $status->value,
1497 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1498 * various error display idiosyncrasies. There are also lots of cases
1499 * where error metadata is set in the object and retrieved later instead
1500 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1501 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1504 function internalAttemptSave( &$result, $bot = false ) {
1505 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1507 $status = Status
::newGood();
1509 wfProfileIn( __METHOD__
);
1510 wfProfileIn( __METHOD__
. '-checks' );
1512 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1513 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1514 $status->fatal( 'hookaborted' );
1515 $status->value
= self
::AS_HOOK_ERROR
;
1516 wfProfileOut( __METHOD__
. '-checks' );
1517 wfProfileOut( __METHOD__
);
1521 $spam = $wgRequest->getText( 'wpAntispam' );
1522 if ( $spam !== '' ) {
1525 $wgUser->getName() .
1527 $this->mTitle
->getPrefixedText() .
1528 '" submitted bogus field "' .
1532 $status->fatal( 'spamprotectionmatch', false );
1533 $status->value
= self
::AS_SPAM_ERROR
;
1534 wfProfileOut( __METHOD__
. '-checks' );
1535 wfProfileOut( __METHOD__
);
1540 # Construct Content object
1541 $textbox_content = $this->toEditContent( $this->textbox1
);
1542 } catch ( MWContentSerializationException
$ex ) {
1544 'content-failed-to-parse',
1545 $this->contentModel
,
1546 $this->contentFormat
,
1549 $status->value
= self
::AS_PARSE_ERROR
;
1550 wfProfileOut( __METHOD__
. '-checks' );
1551 wfProfileOut( __METHOD__
);
1555 # Check image redirect
1556 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1557 $textbox_content->isRedirect() &&
1558 !$wgUser->isAllowed( 'upload' )
1560 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1561 $status->setResult( false, $code );
1563 wfProfileOut( __METHOD__
. '-checks' );
1564 wfProfileOut( __METHOD__
);
1570 $match = self
::matchSummarySpamRegex( $this->summary
);
1571 if ( $match === false && $this->section
== 'new' ) {
1572 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1573 # regular summaries, it is added to the actual wikitext.
1574 if ( $this->sectiontitle
!== '' ) {
1575 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1576 $match = self
::matchSpamRegex( $this->sectiontitle
);
1578 # This branch is taken when the "Add Topic" user interface is used, or the API
1579 # is used with the 'summary' parameter.
1580 $match = self
::matchSpamRegex( $this->summary
);
1583 if ( $match === false ) {
1584 $match = self
::matchSpamRegex( $this->textbox1
);
1586 if ( $match !== false ) {
1587 $result['spam'] = $match;
1588 $ip = $wgRequest->getIP();
1589 $pdbk = $this->mTitle
->getPrefixedDBkey();
1590 $match = str_replace( "\n", '', $match );
1591 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1592 $status->fatal( 'spamprotectionmatch', $match );
1593 $status->value
= self
::AS_SPAM_ERROR
;
1594 wfProfileOut( __METHOD__
. '-checks' );
1595 wfProfileOut( __METHOD__
);
1600 array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) )
1602 # Error messages etc. could be handled within the hook...
1603 $status->fatal( 'hookaborted' );
1604 $status->value
= self
::AS_HOOK_ERROR
;
1605 wfProfileOut( __METHOD__
. '-checks' );
1606 wfProfileOut( __METHOD__
);
1608 } elseif ( $this->hookError
!= '' ) {
1609 # ...or the hook could be expecting us to produce an error
1610 $status->fatal( 'hookaborted' );
1611 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1612 wfProfileOut( __METHOD__
. '-checks' );
1613 wfProfileOut( __METHOD__
);
1617 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1618 // Auto-block user's IP if the account was "hard" blocked
1619 $wgUser->spreadAnyEditBlock();
1620 # Check block state against master, thus 'false'.
1621 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1622 wfProfileOut( __METHOD__
. '-checks' );
1623 wfProfileOut( __METHOD__
);
1627 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1628 if ( $this->kblength
> $wgMaxArticleSize ) {
1629 // Error will be displayed by showEditForm()
1630 $this->tooBig
= true;
1631 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1632 wfProfileOut( __METHOD__
. '-checks' );
1633 wfProfileOut( __METHOD__
);
1637 if ( !$wgUser->isAllowed( 'edit' ) ) {
1638 if ( $wgUser->isAnon() ) {
1639 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1640 wfProfileOut( __METHOD__
. '-checks' );
1641 wfProfileOut( __METHOD__
);
1644 $status->fatal( 'readonlytext' );
1645 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1646 wfProfileOut( __METHOD__
. '-checks' );
1647 wfProfileOut( __METHOD__
);
1652 if ( wfReadOnly() ) {
1653 $status->fatal( 'readonlytext' );
1654 $status->value
= self
::AS_READ_ONLY_PAGE
;
1655 wfProfileOut( __METHOD__
. '-checks' );
1656 wfProfileOut( __METHOD__
);
1659 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1660 $status->fatal( 'actionthrottledtext' );
1661 $status->value
= self
::AS_RATE_LIMITED
;
1662 wfProfileOut( __METHOD__
. '-checks' );
1663 wfProfileOut( __METHOD__
);
1667 # If the article has been deleted while editing, don't save it without
1669 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1670 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1671 wfProfileOut( __METHOD__
. '-checks' );
1672 wfProfileOut( __METHOD__
);
1676 wfProfileOut( __METHOD__
. '-checks' );
1678 # Load the page data from the master. If anything changes in the meantime,
1679 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1680 $this->mArticle
->loadPageData( 'fromdbmaster' );
1681 $new = !$this->mArticle
->exists();
1684 // Late check for create permission, just in case *PARANOIA*
1685 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1686 $status->fatal( 'nocreatetext' );
1687 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1688 wfDebug( __METHOD__
. ": no create permission\n" );
1689 wfProfileOut( __METHOD__
);
1693 // Don't save a new page if it's blank or if it's a MediaWiki:
1694 // message with content equivalent to default (allow empty pages
1695 // in this case to disable messages, see bug 50124)
1696 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1697 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1698 $defaultText = $defaultMessageText;
1703 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1704 $this->blankArticle
= true;
1705 $status->fatal( 'blankarticle' );
1706 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1707 wfProfileOut( __METHOD__
);
1711 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1712 wfProfileOut( __METHOD__
);
1716 $content = $textbox_content;
1718 $result['sectionanchor'] = '';
1719 if ( $this->section
== 'new' ) {
1720 if ( $this->sectiontitle
!== '' ) {
1721 // Insert the section title above the content.
1722 $content = $content->addSectionHeader( $this->sectiontitle
);
1723 } elseif ( $this->summary
!== '' ) {
1724 // Insert the section title above the content.
1725 $content = $content->addSectionHeader( $this->summary
);
1727 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1730 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1734 # Article exists. Check for edit conflict.
1736 $this->mArticle
->clear(); # Force reload of dates, etc.
1737 $timestamp = $this->mArticle
->getTimestamp();
1739 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1741 if ( $timestamp != $this->edittime
) {
1742 $this->isConflict
= true;
1743 if ( $this->section
== 'new' ) {
1744 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1745 $this->mArticle
->getComment() == $this->newSectionSummary()
1747 // Probably a duplicate submission of a new comment.
1748 // This can happen when squid resends a request after
1749 // a timeout but the first one actually went through.
1751 . ": duplicate new section submission; trigger edit conflict!\n" );
1753 // New comment; suppress conflict.
1754 $this->isConflict
= false;
1755 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1757 } elseif ( $this->section
== ''
1758 && Revision
::userWasLastToEdit(
1759 DB_MASTER
, $this->mTitle
->getArticleID(),
1760 $wgUser->getId(), $this->edittime
1763 # Suppress edit conflict with self, except for section edits where merging is required.
1764 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1765 $this->isConflict
= false;
1769 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1770 if ( $this->sectiontitle
!== '' ) {
1771 $sectionTitle = $this->sectiontitle
;
1773 $sectionTitle = $this->summary
;
1778 if ( $this->isConflict
) {
1780 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1781 . " (article time '{$timestamp}')\n" );
1783 $content = $this->mArticle
->replaceSectionContent(
1790 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1791 $content = $this->mArticle
->replaceSectionContent(
1798 if ( is_null( $content ) ) {
1799 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1800 $this->isConflict
= true;
1801 $content = $textbox_content; // do not try to merge here!
1802 } elseif ( $this->isConflict
) {
1804 if ( $this->mergeChangesIntoContent( $content ) ) {
1805 // Successful merge! Maybe we should tell the user the good news?
1806 $this->isConflict
= false;
1807 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1809 $this->section
= '';
1810 $this->textbox1
= ContentHandler
::getContentText( $content );
1811 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1815 if ( $this->isConflict
) {
1816 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1817 wfProfileOut( __METHOD__
);
1821 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1822 wfProfileOut( __METHOD__
);
1826 if ( $this->section
== 'new' ) {
1827 // Handle the user preference to force summaries here
1828 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1829 $this->missingSummary
= true;
1830 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1831 $status->value
= self
::AS_SUMMARY_NEEDED
;
1832 wfProfileOut( __METHOD__
);
1836 // Do not allow the user to post an empty comment
1837 if ( $this->textbox1
== '' ) {
1838 $this->missingComment
= true;
1839 $status->fatal( 'missingcommenttext' );
1840 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1841 wfProfileOut( __METHOD__
);
1844 } elseif ( !$this->allowBlankSummary
1845 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1846 && !$content->isRedirect()
1847 && md5( $this->summary
) == $this->autoSumm
1849 $this->missingSummary
= true;
1850 $status->fatal( 'missingsummary' );
1851 $status->value
= self
::AS_SUMMARY_NEEDED
;
1852 wfProfileOut( __METHOD__
);
1857 wfProfileIn( __METHOD__
. '-sectionanchor' );
1858 $sectionanchor = '';
1859 if ( $this->section
== 'new' ) {
1860 $this->summary
= $this->newSectionSummary( $sectionanchor );
1861 } elseif ( $this->section
!= '' ) {
1862 # Try to get a section anchor from the section source, redirect
1863 # to edited section if header found.
1864 # XXX: Might be better to integrate this into Article::replaceSection
1865 # for duplicate heading checking and maybe parsing.
1866 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1867 # We can't deal with anchors, includes, html etc in the header for now,
1868 # headline would need to be parsed to improve this.
1869 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1870 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1873 $result['sectionanchor'] = $sectionanchor;
1874 wfProfileOut( __METHOD__
. '-sectionanchor' );
1876 // Save errors may fall down to the edit form, but we've now
1877 // merged the section into full text. Clear the section field
1878 // so that later submission of conflict forms won't try to
1879 // replace that into a duplicated mess.
1880 $this->textbox1
= $this->toEditText( $content );
1881 $this->section
= '';
1883 $status->value
= self
::AS_SUCCESS_UPDATE
;
1886 // Check for length errors again now that the section is merged in
1887 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1888 if ( $this->kblength
> $wgMaxArticleSize ) {
1889 $this->tooBig
= true;
1890 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1891 wfProfileOut( __METHOD__
);
1895 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1896 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1897 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1898 ( $bot ? EDIT_FORCE_BOT
: 0 );
1900 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags,
1901 false, null, $this->contentFormat
);
1903 if ( !$doEditStatus->isOK() ) {
1904 // Failure from doEdit()
1905 // Show the edit conflict page for certain recognized errors from doEdit(),
1906 // but don't show it for errors from extension hooks
1907 $errors = $doEditStatus->getErrorsArray();
1908 if ( in_array( $errors[0][0],
1909 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1911 $this->isConflict
= true;
1912 // Destroys data doEdit() put in $status->value but who cares
1913 $doEditStatus->value
= self
::AS_END
;
1915 wfProfileOut( __METHOD__
);
1916 return $doEditStatus;
1919 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1920 if ( $result['nullEdit'] ) {
1921 // We don't know if it was a null edit until now, so increment here
1922 $wgUser->pingLimiter( 'linkpurge' );
1924 $result['redirect'] = $content->isRedirect();
1925 $this->updateWatchlist();
1926 wfProfileOut( __METHOD__
);
1931 * Register the change of watch status
1933 protected function updateWatchlist() {
1936 if ( $wgUser->isLoggedIn()
1937 && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
, WatchedItem
::IGNORE_USER_RIGHTS
)
1939 $fname = __METHOD__
;
1940 $title = $this->mTitle
;
1941 $watch = $this->watchthis
;
1943 // Do this in its own transaction to reduce contention...
1944 $dbw = wfGetDB( DB_MASTER
);
1945 $dbw->onTransactionIdle( function () use ( $dbw, $title, $watch, $wgUser, $fname ) {
1946 $dbw->begin( $fname );
1947 WatchAction
::doWatchOrUnwatch( $watch, $title, $wgUser );
1948 $dbw->commit( $fname );
1954 * Attempts to do 3-way merge of edit content with a base revision
1955 * and current content, in case of edit conflict, in whichever way appropriate
1956 * for the content type.
1960 * @param Content $editContent
1964 private function mergeChangesIntoContent( &$editContent ) {
1965 wfProfileIn( __METHOD__
);
1967 $db = wfGetDB( DB_MASTER
);
1969 // This is the revision the editor started from
1970 $baseRevision = $this->getBaseRevision();
1971 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
1973 if ( is_null( $baseContent ) ) {
1974 wfProfileOut( __METHOD__
);
1978 // The current state, we want to merge updates into it
1979 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1980 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
1982 if ( is_null( $currentContent ) ) {
1983 wfProfileOut( __METHOD__
);
1987 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
1989 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1992 $editContent = $result;
1993 wfProfileOut( __METHOD__
);
1997 wfProfileOut( __METHOD__
);
2004 function getBaseRevision() {
2005 if ( !$this->mBaseRevision
) {
2006 $db = wfGetDB( DB_MASTER
);
2007 $this->mBaseRevision
= Revision
::loadFromTimestamp(
2008 $db, $this->mTitle
, $this->edittime
);
2010 return $this->mBaseRevision
;
2014 * Check given input text against $wgSpamRegex, and return the text of the first match.
2016 * @param string $text
2018 * @return string|bool Matching string or false
2020 public static function matchSpamRegex( $text ) {
2021 global $wgSpamRegex;
2022 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2023 $regexes = (array)$wgSpamRegex;
2024 return self
::matchSpamRegexInternal( $text, $regexes );
2028 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2030 * @param string $text
2032 * @return string|bool Matching string or false
2034 public static function matchSummarySpamRegex( $text ) {
2035 global $wgSummarySpamRegex;
2036 $regexes = (array)$wgSummarySpamRegex;
2037 return self
::matchSpamRegexInternal( $text, $regexes );
2041 * @param string $text
2042 * @param array $regexes
2043 * @return bool|string
2045 protected static function matchSpamRegexInternal( $text, $regexes ) {
2046 foreach ( $regexes as $regex ) {
2048 if ( preg_match( $regex, $text, $matches ) ) {
2055 function setHeaders() {
2056 global $wgOut, $wgUser;
2058 $wgOut->addModules( 'mediawiki.action.edit' );
2059 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2061 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
2062 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2065 if ( $wgUser->getOption( 'useeditwarning', false ) ) {
2066 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2069 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2071 # Enabled article-related sidebar, toplinks, etc.
2072 $wgOut->setArticleRelated( true );
2074 $contextTitle = $this->getContextTitle();
2075 if ( $this->isConflict
) {
2076 $msg = 'editconflict';
2077 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2078 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2080 $msg = $contextTitle->exists()
2081 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2082 && $contextTitle->getDefaultMessageText() !== false
2088 # Use the title defined by DISPLAYTITLE magic word when present
2089 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2090 if ( $displayTitle === false ) {
2091 $displayTitle = $contextTitle->getPrefixedText();
2093 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2097 * Show all applicable editing introductions
2099 protected function showIntro() {
2100 global $wgOut, $wgUser;
2101 if ( $this->suppressIntro
) {
2105 $namespace = $this->mTitle
->getNamespace();
2107 if ( $namespace == NS_MEDIAWIKI
) {
2108 # Show a warning if editing an interface message
2109 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2110 } elseif ( $namespace == NS_FILE
) {
2111 # Show a hint to shared repo
2112 $file = wfFindFile( $this->mTitle
);
2113 if ( $file && !$file->isLocal() ) {
2114 $descUrl = $file->getDescriptionUrl();
2115 # there must be a description url to show a hint to shared repo
2117 if ( !$this->mTitle
->exists() ) {
2118 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2119 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2122 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2123 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2130 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2131 # Show log extract when the user is currently blocked
2132 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2133 $parts = explode( '/', $this->mTitle
->getText(), 2 );
2134 $username = $parts[0];
2135 $user = User
::newFromName( $username, false /* allow IP users*/ );
2136 $ip = User
::isIP( $username );
2137 $block = Block
::newFromTarget( $user, $user );
2138 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2139 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2140 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2141 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) { # Show log extract if the user is currently blocked
2142 LogEventsList
::showLogExtract(
2145 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2149 'showIfEmpty' => false,
2151 'blocked-notice-logextract',
2152 $user->getName() # Support GENDER in notice
2158 # Try to add a custom edit intro, or use the standard one if this is not possible.
2159 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2160 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2161 wfMessage( 'helppage' )->inContentLanguage()->text()
2163 if ( $wgUser->isLoggedIn() ) {
2164 $wgOut->wrapWikiMsg(
2165 // Suppress the external link icon, consider the help url an internal one
2166 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2173 $wgOut->wrapWikiMsg(
2174 // Suppress the external link icon, consider the help url an internal one
2175 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2177 'newarticletextanon',
2183 # Give a notice if the user is editing a deleted/moved page...
2184 if ( !$this->mTitle
->exists() ) {
2185 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
2189 'conds' => array( "log_action != 'revision'" ),
2190 'showIfEmpty' => false,
2191 'msgKey' => array( 'recreate-moveddeleted-warn' )
2198 * Attempt to show a custom editing introduction, if supplied
2202 protected function showCustomIntro() {
2203 if ( $this->editintro
) {
2204 $title = Title
::newFromText( $this->editintro
);
2205 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2207 // Added using template syntax, to take <noinclude>'s into account.
2208 $wgOut->addWikiTextTitleTidy( '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>', $this->mTitle
);
2216 * Gets an editable textual representation of $content.
2217 * The textual representation can be turned by into a Content object by the
2218 * toEditContent() method.
2220 * If $content is null or false or a string, $content is returned unchanged.
2222 * If the given Content object is not of a type that can be edited using
2223 * the text base EditPage, an exception will be raised. Set
2224 * $this->allowNonTextContent to true to allow editing of non-textual
2227 * @param Content|null|bool|string $content
2228 * @return string The editable text form of the content.
2230 * @throws MWException If $content is not an instance of TextContent and
2231 * $this->allowNonTextContent is not true.
2233 protected function toEditText( $content ) {
2234 if ( $content === null ||
$content === false ) {
2238 if ( is_string( $content ) ) {
2242 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2243 throw new MWException( 'This content model is not supported: '
2244 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2247 return $content->serialize( $this->contentFormat
);
2251 * Turns the given text into a Content object by unserializing it.
2253 * If the resulting Content object is not of a type that can be edited using
2254 * the text base EditPage, an exception will be raised. Set
2255 * $this->allowNonTextContent to true to allow editing of non-textual
2258 * @param string|null|bool $text Text to unserialize
2259 * @return Content The content object created from $text. If $text was false
2260 * or null, false resp. null will be returned instead.
2262 * @throws MWException If unserializing the text results in a Content
2263 * object that is not an instance of TextContent and
2264 * $this->allowNonTextContent is not true.
2266 protected function toEditContent( $text ) {
2267 if ( $text === false ||
$text === null ) {
2271 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2272 $this->contentModel
, $this->contentFormat
);
2274 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2275 throw new MWException( 'This content model is not supported: '
2276 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2283 * Send the edit form and related headers to $wgOut
2284 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2285 * during form output near the top, for captchas and the like.
2287 function showEditForm( $formCallback = null ) {
2288 global $wgOut, $wgUser;
2290 wfProfileIn( __METHOD__
);
2292 # need to parse the preview early so that we know which templates are used,
2293 # otherwise users with "show preview after edit box" will get a blank list
2294 # we parse this near the beginning so that setHeaders can do the title
2295 # setting work instead of leaving it in getPreviewText
2296 $previewOutput = '';
2297 if ( $this->formtype
== 'preview' ) {
2298 $previewOutput = $this->getPreviewText();
2301 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2303 $this->setHeaders();
2305 if ( $this->showHeader() === false ) {
2306 wfProfileOut( __METHOD__
);
2310 $wgOut->addHTML( $this->editFormPageTop
);
2312 if ( $wgUser->getOption( 'previewontop' ) ) {
2313 $this->displayPreviewArea( $previewOutput, true );
2316 $wgOut->addHTML( $this->editFormTextTop
);
2318 $showToolbar = true;
2319 if ( $this->wasDeletedSinceLastEdit() ) {
2320 if ( $this->formtype
== 'save' ) {
2321 // Hide the toolbar and edit area, user can click preview to get it back
2322 // Add an confirmation checkbox and explanation.
2323 $showToolbar = false;
2325 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2326 'deletedwhileediting' );
2330 // @todo add EditForm plugin interface and use it here!
2331 // search for textarea1 and textares2, and allow EditForm to override all uses.
2332 $wgOut->addHTML( Html
::openElement(
2335 'id' => self
::EDITFORM_ID
,
2336 'name' => self
::EDITFORM_ID
,
2338 'action' => $this->getActionURL( $this->getContextTitle() ),
2339 'enctype' => 'multipart/form-data'
2343 if ( is_callable( $formCallback ) ) {
2344 call_user_func_array( $formCallback, array( &$wgOut ) );
2347 // Add an empty field to trip up spambots
2349 Xml
::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2352 array( 'for' => 'wpAntiSpam' ),
2353 wfMessage( 'simpleantispam-label' )->parse()
2359 'name' => 'wpAntispam',
2360 'id' => 'wpAntispam',
2364 . Xml
::closeElement( 'div' )
2367 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2369 // Put these up at the top to ensure they aren't lost on early form submission
2370 $this->showFormBeforeText();
2372 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2373 $username = $this->lastDelete
->user_name
;
2374 $comment = $this->lastDelete
->log_comment
;
2376 // It is better to not parse the comment at all than to have templates expanded in the middle
2377 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2378 $key = $comment === ''
2379 ?
'confirmrecreate-noreason'
2380 : 'confirmrecreate';
2382 '<div class="mw-confirm-recreate">' .
2383 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2384 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2385 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2391 # When the summary is hidden, also hide them on preview/show changes
2392 if ( $this->nosummary
) {
2393 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2396 # If a blank edit summary was previously provided, and the appropriate
2397 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2398 # user being bounced back more than once in the event that a summary
2401 # For a bit more sophisticated detection of blank summaries, hash the
2402 # automatic one and pass that in the hidden field wpAutoSummary.
2403 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2404 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2407 if ( $this->undidRev
) {
2408 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2411 if ( $this->hasPresetSummary
) {
2412 // If a summary has been preset using &summary= we don't want to prompt for
2413 // a different summary. Only prompt for a summary if the summary is blanked.
2415 $this->autoSumm
= md5( '' );
2418 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2419 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2421 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2423 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2424 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2426 if ( $this->section
== 'new' ) {
2427 $this->showSummaryInput( true, $this->summary
);
2428 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2431 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2433 if ( $this->contentModel
=== CONTENT_MODEL_WIKITEXT
&&
2434 $showToolbar && $wgUser->getOption( 'showtoolbar' ) )
2436 $wgOut->addHTML( EditPage
::getEditToolbar() );
2439 if ( $this->blankArticle
) {
2440 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2443 if ( $this->isConflict
) {
2444 // In an edit conflict bypass the overridable content form method
2445 // and fallback to the raw wpTextbox1 since editconflicts can't be
2446 // resolved between page source edits and custom ui edits using the
2448 $this->textbox2
= $this->textbox1
;
2450 $content = $this->getCurrentContent();
2451 $this->textbox1
= $this->toEditText( $content );
2453 $this->showTextbox1();
2455 $this->showContentForm();
2458 $wgOut->addHTML( $this->editFormTextAfterContent
);
2460 $this->showStandardInputs();
2462 $this->showFormAfterText();
2464 $this->showTosSummary();
2466 $this->showEditTools();
2468 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2470 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2471 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2473 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2474 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2476 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'limitreport' ),
2477 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2479 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2481 if ( $this->isConflict
) {
2483 $this->showConflict();
2484 } catch ( MWContentSerializationException
$ex ) {
2485 // this can't really happen, but be nice if it does.
2487 'content-failed-to-parse',
2488 $this->contentModel
,
2489 $this->contentFormat
,
2492 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2496 // Marker for detecting truncated form data. This must be the last
2497 // parameter sent in order to be of use, so do not move me.
2498 $wgOut->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2499 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2501 if ( !$wgUser->getOption( 'previewontop' ) ) {
2502 $this->displayPreviewArea( $previewOutput, false );
2505 wfProfileOut( __METHOD__
);
2509 * Extract the section title from current section text, if any.
2511 * @param string $text
2512 * @return string|bool String or false
2514 public static function extractSectionTitle( $text ) {
2515 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2516 if ( !empty( $matches[2] ) ) {
2518 return $wgParser->stripSectionName( trim( $matches[2] ) );
2527 protected function showHeader() {
2528 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2529 global $wgAllowUserCss, $wgAllowUserJs;
2531 if ( $this->mTitle
->isTalkPage() ) {
2532 $wgOut->addWikiMsg( 'talkpagetext' );
2536 $wgOut->addHTML( implode( "\n", $this->mTitle
->getEditNotices( $this->oldid
) ) );
2538 if ( $this->isConflict
) {
2539 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2540 $this->edittime
= $this->mArticle
->getTimestamp();
2542 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2543 // We use $this->section to much before this and getVal('wgSection') directly in other places
2544 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2545 // Someone is welcome to try refactoring though
2546 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2550 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2551 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2552 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2553 if ( $sectionTitle !== false ) {
2554 $this->summary
= "/* $sectionTitle */ ";
2559 if ( $this->missingComment
) {
2560 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2563 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2564 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2567 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2568 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2571 if ( $this->blankArticle
) {
2572 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2575 if ( $this->hookError
!== '' ) {
2576 $wgOut->addWikiText( $this->hookError
);
2579 if ( !$this->checkUnicodeCompliantBrowser() ) {
2580 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2583 if ( $this->section
!= 'new' ) {
2584 $revision = $this->mArticle
->getRevisionFetched();
2586 // Let sysop know that this will make private content public if saved
2588 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2589 $wgOut->wrapWikiMsg(
2590 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2591 'rev-deleted-text-permission'
2593 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2594 $wgOut->wrapWikiMsg(
2595 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2596 'rev-deleted-text-view'
2600 if ( !$revision->isCurrent() ) {
2601 $this->mArticle
->setOldSubtitle( $revision->getId() );
2602 $wgOut->addWikiMsg( 'editingold' );
2604 } elseif ( $this->mTitle
->exists() ) {
2605 // Something went wrong
2607 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2608 array( 'missing-revision', $this->oldid
) );
2613 if ( wfReadOnly() ) {
2614 $wgOut->wrapWikiMsg(
2615 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2616 array( 'readonlywarning', wfReadOnlyReason() )
2618 } elseif ( $wgUser->isAnon() ) {
2619 if ( $this->formtype
!= 'preview' ) {
2620 $wgOut->wrapWikiMsg(
2621 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2622 array( 'anoneditwarning',
2624 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2626 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2629 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2630 'anonpreviewwarning'
2634 if ( $this->isCssJsSubpage
) {
2635 # Check the skin exists
2636 if ( $this->isWrongCaseCssJsPage
) {
2637 $wgOut->wrapWikiMsg(
2638 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2639 array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() )
2642 if ( $this->formtype
!== 'preview' ) {
2643 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
2644 $wgOut->wrapWikiMsg(
2645 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2646 array( 'usercssyoucanpreview' )
2650 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
2651 $wgOut->wrapWikiMsg(
2652 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2653 array( 'userjsyoucanpreview' )
2660 if ( $this->mTitle
->isProtected( 'edit' ) &&
2661 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2663 # Is the title semi-protected?
2664 if ( $this->mTitle
->isSemiProtected() ) {
2665 $noticeMsg = 'semiprotectedpagewarning';
2667 # Then it must be protected based on static groups (regular)
2668 $noticeMsg = 'protectedpagewarning';
2670 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2671 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2673 if ( $this->mTitle
->isCascadeProtected() ) {
2674 # Is this page under cascading protection from some source pages?
2675 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2676 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2677 $cascadeSourcesCount = count( $cascadeSources );
2678 if ( $cascadeSourcesCount > 0 ) {
2679 # Explain, and list the titles responsible
2680 foreach ( $cascadeSources as $page ) {
2681 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2684 $notice .= '</div>';
2685 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2687 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2688 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2690 'showIfEmpty' => false,
2691 'msgKey' => array( 'titleprotectedwarning' ),
2692 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2695 if ( $this->kblength
=== false ) {
2696 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2699 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2700 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2703 $wgLang->formatNum( $this->kblength
),
2704 $wgLang->formatNum( $wgMaxArticleSize )
2708 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2709 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2712 $wgLang->formatSize( strlen( $this->textbox1
) ),
2713 strlen( $this->textbox1
)
2718 # Add header copyright warning
2719 $this->showHeaderCopyrightWarning();
2725 * Standard summary input and label (wgSummary), abstracted so EditPage
2726 * subclasses may reorganize the form.
2727 * Note that you do not need to worry about the label's for=, it will be
2728 * inferred by the id given to the input. You can remove them both by
2729 * passing array( 'id' => false ) to $userInputAttrs.
2731 * @param string $summary The value of the summary input
2732 * @param string $labelText The html to place inside the label
2733 * @param array $inputAttrs Array of attrs to use on the input
2734 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2736 * @return array An array in the format array( $label, $input )
2738 function getSummaryInput( $summary = "", $labelText = null,
2739 $inputAttrs = null, $spanLabelAttrs = null
2741 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2742 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2743 'id' => 'wpSummary',
2744 'maxlength' => '200',
2747 'spellcheck' => 'true',
2748 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2750 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2751 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2752 'id' => "wpSummaryLabel"
2759 $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null,
2762 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2765 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2767 return array( $label, $input );
2771 * @param bool $isSubjectPreview True if this is the section subject/title
2772 * up top, or false if this is the comment summary
2773 * down below the textarea
2774 * @param string $summary The text of the summary to display
2776 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2777 global $wgOut, $wgContLang;
2778 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2779 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2780 if ( $isSubjectPreview ) {
2781 if ( $this->nosummary
) {
2785 if ( !$this->mShowSummaryField
) {
2789 $summary = $wgContLang->recodeForEdit( $summary );
2790 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2791 list( $label, $input ) = $this->getSummaryInput(
2794 array( 'class' => $summaryClass ),
2797 $wgOut->addHTML( "{$label} {$input}" );
2801 * @param bool $isSubjectPreview True if this is the section subject/title
2802 * up top, or false if this is the comment summary
2803 * down below the textarea
2804 * @param string $summary The text of the summary to display
2807 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2808 // avoid spaces in preview, gets always trimmed on save
2809 $summary = trim( $summary );
2810 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2816 if ( $isSubjectPreview ) {
2817 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2818 ->inContentLanguage()->text();
2821 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2823 $summary = wfMessage( $message )->parse()
2824 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2825 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2828 protected function showFormBeforeText() {
2830 $section = htmlspecialchars( $this->section
);
2831 $wgOut->addHTML( <<<HTML
2832 <input type='hidden' value="{$section}" name="wpSection" />
2833 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2834 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2835 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2839 if ( !$this->checkUnicodeCompliantBrowser() ) {
2840 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2844 protected function showFormAfterText() {
2845 global $wgOut, $wgUser;
2847 * To make it harder for someone to slip a user a page
2848 * which submits an edit form to the wiki without their
2849 * knowledge, a random token is associated with the login
2850 * session. If it's not passed back with the submission,
2851 * we won't save the page, or render user JavaScript and
2854 * For anon editors, who may not have a session, we just
2855 * include the constant suffix to prevent editing from
2856 * broken text-mangling proxies.
2858 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2862 * Subpage overridable method for printing the form for page content editing
2863 * By default this simply outputs wpTextbox1
2864 * Subclasses can override this to provide a custom UI for editing;
2865 * be it a form, or simply wpTextbox1 with a modified content that will be
2866 * reverse modified when extracted from the post data.
2867 * Note that this is basically the inverse for importContentFormData
2869 protected function showContentForm() {
2870 $this->showTextbox1();
2874 * Method to output wpTextbox1
2875 * The $textoverride method can be used by subclasses overriding showContentForm
2876 * to pass back to this method.
2878 * @param array $customAttribs Array of html attributes to use in the textarea
2879 * @param string $textoverride Optional text to override $this->textarea1 with
2881 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2882 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2883 $attribs = array( 'style' => 'display:none;' );
2885 $classes = array(); // Textarea CSS
2886 if ( $this->mTitle
->isProtected( 'edit' ) &&
2887 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2889 # Is the title semi-protected?
2890 if ( $this->mTitle
->isSemiProtected() ) {
2891 $classes[] = 'mw-textarea-sprotected';
2893 # Then it must be protected based on static groups (regular)
2894 $classes[] = 'mw-textarea-protected';
2896 # Is the title cascade-protected?
2897 if ( $this->mTitle
->isCascadeProtected() ) {
2898 $classes[] = 'mw-textarea-cprotected';
2902 $attribs = array( 'tabindex' => 1 );
2904 if ( is_array( $customAttribs ) ) {
2905 $attribs +
= $customAttribs;
2908 if ( count( $classes ) ) {
2909 if ( isset( $attribs['class'] ) ) {
2910 $classes[] = $attribs['class'];
2912 $attribs['class'] = implode( ' ', $classes );
2917 $textoverride !== null ?
$textoverride : $this->textbox1
,
2923 protected function showTextbox2() {
2924 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2927 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2928 global $wgOut, $wgUser;
2930 $wikitext = $this->safeUnicodeOutput( $text );
2931 if ( strval( $wikitext ) !== '' ) {
2932 // Ensure there's a newline at the end, otherwise adding lines
2934 // But don't add a newline if the ext is empty, or Firefox in XHTML
2935 // mode will show an extra newline. A bit annoying.
2939 $attribs = $customAttribs +
array(
2942 'cols' => $wgUser->getIntOption( 'cols' ),
2943 'rows' => $wgUser->getIntOption( 'rows' ),
2944 // Avoid PHP notices when appending preferences
2945 // (appending allows customAttribs['style'] to still work).
2949 $pageLang = $this->mTitle
->getPageLanguage();
2950 $attribs['lang'] = $pageLang->getCode();
2951 $attribs['dir'] = $pageLang->getDir();
2953 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2956 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2960 $classes[] = 'ontop';
2963 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2965 if ( $this->formtype
!= 'preview' ) {
2966 $attribs['style'] = 'display: none;';
2969 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2971 if ( $this->formtype
== 'preview' ) {
2972 $this->showPreview( $previewOutput );
2975 $wgOut->addHTML( '</div>' );
2977 if ( $this->formtype
== 'diff' ) {
2980 } catch ( MWContentSerializationException
$ex ) {
2982 'content-failed-to-parse',
2983 $this->contentModel
,
2984 $this->contentFormat
,
2987 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2993 * Append preview output to $wgOut.
2994 * Includes category rendering if this is a category page.
2996 * @param string $text The HTML to be output for the preview.
2998 protected function showPreview( $text ) {
3000 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3001 $this->mArticle
->openShowCategory();
3003 # This hook seems slightly odd here, but makes things more
3004 # consistent for extensions.
3005 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3006 $wgOut->addHTML( $text );
3007 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3008 $this->mArticle
->closeShowCategory();
3013 * Get a diff between the current contents of the edit box and the
3014 * version of the page we're editing from.
3016 * If this is a section edit, we'll replace the section as for final
3017 * save and then make a comparison.
3019 function showDiff() {
3020 global $wgUser, $wgContLang, $wgOut;
3022 $oldtitlemsg = 'currentrev';
3023 # if message does not exist, show diff against the preloaded default
3024 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3025 $oldtext = $this->mTitle
->getDefaultMessageText();
3026 if ( $oldtext !== false ) {
3027 $oldtitlemsg = 'defaultmessagetext';
3028 $oldContent = $this->toEditContent( $oldtext );
3033 $oldContent = $this->getCurrentContent();
3036 $textboxContent = $this->toEditContent( $this->textbox1
);
3038 $newContent = $this->mArticle
->replaceSectionContent(
3039 $this->section
, $textboxContent,
3040 $this->summary
, $this->edittime
);
3042 if ( $newContent ) {
3043 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3044 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3046 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
3047 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
3050 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3051 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3052 $newtitle = wfMessage( 'yourtext' )->parse();
3054 if ( !$oldContent ) {
3055 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3058 if ( !$newContent ) {
3059 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3062 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3063 $de->setContent( $oldContent, $newContent );
3065 $difftext = $de->getDiff( $oldtitle, $newtitle );
3066 $de->showDiffStyle();
3071 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3075 * Show the header copyright warning.
3077 protected function showHeaderCopyrightWarning() {
3078 $msg = 'editpage-head-copy-warn';
3079 if ( !wfMessage( $msg )->isDisabled() ) {
3081 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3082 'editpage-head-copy-warn' );
3087 * Give a chance for site and per-namespace customizations of
3088 * terms of service summary link that might exist separately
3089 * from the copyright notice.
3091 * This will display between the save button and the edit tools,
3092 * so should remain short!
3094 protected function showTosSummary() {
3095 $msg = 'editpage-tos-summary';
3096 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
3097 if ( !wfMessage( $msg )->isDisabled() ) {
3099 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3100 $wgOut->addWikiMsg( $msg );
3101 $wgOut->addHTML( '</div>' );
3105 protected function showEditTools() {
3107 $wgOut->addHTML( '<div class="mw-editTools">' .
3108 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3113 * Get the copyright warning
3115 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3118 protected function getCopywarn() {
3119 return self
::getCopyrightWarning( $this->mTitle
);
3123 * Get the copyright warning, by default returns wikitext
3125 * @param Title $title
3126 * @param string $format Output format, valid values are any function of a Message object
3129 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3130 global $wgRightsText;
3131 if ( $wgRightsText ) {
3132 $copywarnMsg = array( 'copyrightwarning',
3133 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3136 $copywarnMsg = array( 'copyrightwarning2',
3137 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3139 // Allow for site and per-namespace customization of contribution/copyright notice.
3140 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3142 return "<div id=\"editpage-copywarn\">\n" .
3143 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3147 * Get the Limit report for page previews
3150 * @param ParserOutput $output ParserOutput object from the parse
3151 * @return string HTML
3153 public static function getPreviewLimitReport( $output ) {
3154 if ( !$output ||
!$output->getLimitReportData() ) {
3158 wfProfileIn( __METHOD__
);
3160 $limitReport = Html
::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3161 wfMessage( 'limitreport-title' )->parseAsBlock()
3164 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3165 $limitReport .= Html
::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3167 $limitReport .= Html
::openElement( 'table', array(
3168 'class' => 'preview-limit-report wikitable'
3170 Html
::openElement( 'tbody' );
3172 foreach ( $output->getLimitReportData() as $key => $value ) {
3173 if ( wfRunHooks( 'ParserLimitReportFormat',
3174 array( $key, &$value, &$limitReport, true, true )
3176 $keyMsg = wfMessage( $key );
3177 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3178 if ( !$valueMsg->exists() ) {
3179 $valueMsg = new RawMessage( '$1' );
3181 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3182 $limitReport .= Html
::openElement( 'tr' ) .
3183 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3184 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3185 Html
::closeElement( 'tr' );
3190 $limitReport .= Html
::closeElement( 'tbody' ) .
3191 Html
::closeElement( 'table' ) .
3192 Html
::closeElement( 'div' );
3194 wfProfileOut( __METHOD__
);
3196 return $limitReport;
3199 protected function showStandardInputs( &$tabindex = 2 ) {
3200 global $wgOut, $wgUseMediaWikiUIEverywhere;
3201 $wgOut->addHTML( "<div class='editOptions'>\n" );
3203 if ( $this->section
!= 'new' ) {
3204 $this->showSummaryInput( false, $this->summary
);
3205 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3208 $checkboxes = $this->getCheckboxes( $tabindex,
3209 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
3210 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3212 // Show copyright warning.
3213 $wgOut->addWikiText( $this->getCopywarn() );
3214 $wgOut->addHTML( $this->editFormTextAfterWarn
);
3216 $wgOut->addHTML( "<div class='editButtons'>\n" );
3217 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3219 $cancel = $this->getCancelLink();
3220 if ( $cancel !== '' ) {
3221 $cancel .= Html
::element( 'span',
3222 array( 'class' => 'mw-editButtons-pipe-separator' ),
3223 wfMessage( 'pipe-separator' )->text() );
3226 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3227 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3229 'target' => 'helpwindow',
3230 'href' => $edithelpurl,
3232 if ( $wgUseMediaWikiUIEverywhere ) {
3233 $attrs['class'] = 'mw-ui-button mw-ui-quiet';
3235 $edithelp = Html
::element( 'a', $attrs, wfMessage( 'edithelp' )->text() ) .
3236 wfMessage( 'newwindow' )->parse();
3238 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3239 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3240 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3242 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3244 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3248 * Show an edit conflict. textbox1 is already shown in showEditForm().
3249 * If you want to use another entry point to this function, be careful.
3251 protected function showConflict() {
3254 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3255 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3257 $content1 = $this->toEditContent( $this->textbox1
);
3258 $content2 = $this->toEditContent( $this->textbox2
);
3260 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3261 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3262 $de->setContent( $content2, $content1 );
3264 wfMessage( 'yourtext' )->parse(),
3265 wfMessage( 'storedversion' )->text()
3268 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3269 $this->showTextbox2();
3276 public function getCancelLink() {
3277 global $wgUseMediaWikiUIEverywhere;
3278 $cancelParams = array();
3279 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3280 $cancelParams['oldid'] = $this->oldid
;
3282 $attrs = array( 'id' => 'mw-editform-cancel' );
3283 if ( $wgUseMediaWikiUIEverywhere ) {
3284 $attrs['class'] = 'mw-ui-button mw-ui-quiet';
3287 return Linker
::linkKnown(
3288 $this->getContextTitle(),
3289 wfMessage( 'cancel' )->parse(),
3296 * Returns the URL to use in the form's action attribute.
3297 * This is used by EditPage subclasses when simply customizing the action
3298 * variable in the constructor is not enough. This can be used when the
3299 * EditPage lives inside of a Special page rather than a custom page action.
3301 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3304 protected function getActionURL( Title
$title ) {
3305 return $title->getLocalURL( array( 'action' => $this->action
) );
3309 * Check if a page was deleted while the user was editing it, before submit.
3310 * Note that we rely on the logging table, which hasn't been always there,
3311 * but that doesn't matter, because this only applies to brand new
3315 protected function wasDeletedSinceLastEdit() {
3316 if ( $this->deletedSinceEdit
!== null ) {
3317 return $this->deletedSinceEdit
;
3320 $this->deletedSinceEdit
= false;
3322 if ( $this->mTitle
->isDeletedQuick() ) {
3323 $this->lastDelete
= $this->getLastDelete();
3324 if ( $this->lastDelete
) {
3325 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3326 if ( $deleteTime > $this->starttime
) {
3327 $this->deletedSinceEdit
= true;
3332 return $this->deletedSinceEdit
;
3336 * @return bool|stdClass
3338 protected function getLastDelete() {
3339 $dbr = wfGetDB( DB_SLAVE
);
3340 $data = $dbr->selectRow(
3341 array( 'logging', 'user' ),
3354 'log_namespace' => $this->mTitle
->getNamespace(),
3355 'log_title' => $this->mTitle
->getDBkey(),
3356 'log_type' => 'delete',
3357 'log_action' => 'delete',
3361 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3363 // Quick paranoid permission checks...
3364 if ( is_object( $data ) ) {
3365 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3366 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
3369 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3370 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
3378 * Get the rendered text for previewing.
3379 * @throws MWException
3382 function getPreviewText() {
3383 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3384 global $wgAllowUserCss, $wgAllowUserJs;
3386 wfProfileIn( __METHOD__
);
3388 if ( $wgRawHtml && !$this->mTokenOk
) {
3389 // Could be an offsite preview attempt. This is very unsafe if
3390 // HTML is enabled, as it could be an attack.
3392 if ( $this->textbox1
!== '' ) {
3393 // Do not put big scary notice, if previewing the empty
3394 // string, which happens when you initially edit
3395 // a category page, due to automatic preview-on-open.
3396 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3397 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3399 wfProfileOut( __METHOD__
);
3406 $content = $this->toEditContent( $this->textbox1
);
3410 'AlternateEditPreview',
3411 array( $this, &$content, &$previewHTML, &$this->mParserOutput
) )
3413 wfProfileOut( __METHOD__
);
3414 return $previewHTML;
3417 # provide a anchor link to the editform
3418 $continueEditing = '<span class="mw-continue-editing">' .
3419 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3420 wfMessage( 'continue-editing' )->text() . ']]</span>';
3421 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3422 if ( $this->mTokenOkExceptSuffix
) {
3423 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3425 $note = wfMessage( 'session_fail_preview' )->plain();
3427 } elseif ( $this->incompleteForm
) {
3428 $note = wfMessage( 'edit_form_incomplete' )->plain();
3430 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3433 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
3434 $parserOptions->setEditSection( false );
3435 $parserOptions->setIsPreview( true );
3436 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3438 # don't parse non-wikitext pages, show message about preview
3439 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3440 if ( $this->mTitle
->isCssJsSubpage() ) {
3442 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3448 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3450 if ( $level === 'user' && !$wgAllowUserCss ) {
3453 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3455 if ( $level === 'user' && !$wgAllowUserJs ) {
3462 # Used messages to make sure grep find them:
3463 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3464 if ( $level && $format ) {
3465 $note = "<div id='mw-{$level}{$format}preview'>" .
3466 wfMessage( "{$level}{$format}preview" )->text() .
3467 ' ' . $continueEditing . "</div>";
3471 # If we're adding a comment, we need to show the
3472 # summary as the headline
3473 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3474 $content = $content->addSectionHeader( $this->summary
);
3477 $hook_args = array( $this, &$content );
3478 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3479 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3481 $parserOptions->enableLimitReport();
3483 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3484 # But it's now deprecated, so never mind
3486 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3487 $parserOutput = $content->getParserOutput(
3488 $this->getArticle()->getTitle(),
3493 $previewHTML = $parserOutput->getText();
3494 $this->mParserOutput
= $parserOutput;
3495 $wgOut->addParserOutputMetadata( $parserOutput );
3497 if ( count( $parserOutput->getWarnings() ) ) {
3498 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3500 } catch ( MWContentSerializationException
$ex ) {
3502 'content-failed-to-parse',
3503 $this->contentModel
,
3504 $this->contentFormat
,
3507 $note .= "\n\n" . $m->parse();
3511 if ( $this->isConflict
) {
3512 $conflict = '<h2 id="mw-previewconflict">'
3513 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3515 $conflict = '<hr />';
3518 $previewhead = "<div class='previewnote'>\n" .
3519 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3520 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3522 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3523 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3524 'class' => 'mw-content-' . $pageViewLang->getDir() );
3525 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3527 wfProfileOut( __METHOD__
);
3528 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3534 function getTemplates() {
3535 if ( $this->preview ||
$this->section
!= '' ) {
3536 $templates = array();
3537 if ( !isset( $this->mParserOutput
) ) {
3540 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3541 foreach ( array_keys( $template ) as $dbk ) {
3542 $templates[] = Title
::makeTitle( $ns, $dbk );
3547 return $this->mTitle
->getTemplateLinksFrom();
3552 * Shows a bulletin board style toolbar for common editing functions.
3553 * It can be disabled in the user preferences.
3557 static function getEditToolbar() {
3558 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3559 global $wgEnableUploads, $wgForeignFileRepos;
3561 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3564 * $toolarray is an array of arrays each of which includes the
3565 * filename of the button image (without path), the opening
3566 * tag, the closing tag, optionally a sample text that is
3567 * inserted between the two when no selection is highlighted
3568 * and. The tip text is shown when the user moves the mouse
3573 'image' => $wgLang->getImageFile( 'button-bold' ),
3574 'id' => 'mw-editbutton-bold',
3576 'close' => '\'\'\'',
3577 'sample' => wfMessage( 'bold_sample' )->text(),
3578 'tip' => wfMessage( 'bold_tip' )->text(),
3581 'image' => $wgLang->getImageFile( 'button-italic' ),
3582 'id' => 'mw-editbutton-italic',
3585 'sample' => wfMessage( 'italic_sample' )->text(),
3586 'tip' => wfMessage( 'italic_tip' )->text(),
3589 'image' => $wgLang->getImageFile( 'button-link' ),
3590 'id' => 'mw-editbutton-link',
3593 'sample' => wfMessage( 'link_sample' )->text(),
3594 'tip' => wfMessage( 'link_tip' )->text(),
3597 'image' => $wgLang->getImageFile( 'button-extlink' ),
3598 'id' => 'mw-editbutton-extlink',
3601 'sample' => wfMessage( 'extlink_sample' )->text(),
3602 'tip' => wfMessage( 'extlink_tip' )->text(),
3605 'image' => $wgLang->getImageFile( 'button-headline' ),
3606 'id' => 'mw-editbutton-headline',
3609 'sample' => wfMessage( 'headline_sample' )->text(),
3610 'tip' => wfMessage( 'headline_tip' )->text(),
3612 $imagesAvailable ?
array(
3613 'image' => $wgLang->getImageFile( 'button-image' ),
3614 'id' => 'mw-editbutton-image',
3615 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3617 'sample' => wfMessage( 'image_sample' )->text(),
3618 'tip' => wfMessage( 'image_tip' )->text(),
3620 $imagesAvailable ?
array(
3621 'image' => $wgLang->getImageFile( 'button-media' ),
3622 'id' => 'mw-editbutton-media',
3623 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3625 'sample' => wfMessage( 'media_sample' )->text(),
3626 'tip' => wfMessage( 'media_tip' )->text(),
3629 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3630 'id' => 'mw-editbutton-nowiki',
3631 'open' => "<nowiki>",
3632 'close' => "</nowiki>",
3633 'sample' => wfMessage( 'nowiki_sample' )->text(),
3634 'tip' => wfMessage( 'nowiki_tip' )->text(),
3637 'image' => $wgLang->getImageFile( 'button-sig' ),
3638 'id' => 'mw-editbutton-signature',
3642 'tip' => wfMessage( 'sig_tip' )->text(),
3645 'image' => $wgLang->getImageFile( 'button-hr' ),
3646 'id' => 'mw-editbutton-hr',
3647 'open' => "\n----\n",
3650 'tip' => wfMessage( 'hr_tip' )->text(),
3654 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3655 foreach ( $toolarray as $tool ) {
3661 $wgStylePath . '/common/images/' . $tool['image'],
3662 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3663 // Older browsers show a "speedtip" type message only for ALT.
3664 // Ideally these should be different, realistically they
3665 // probably don't need to be.
3673 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3676 // This used to be called on DOMReady from mediawiki.action.edit, which
3677 // ended up causing race conditions with the setup code above.
3679 "// Create button bar\n" .
3680 "$(function() { mw.toolbar.init(); } );\n";
3683 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3685 $toolbar = '<div id="toolbar"></div>';
3687 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3693 * Returns an array of html code of the following checkboxes:
3696 * @param int $tabindex Current tabindex
3697 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3698 * status of the checkbox
3702 public function getCheckboxes( &$tabindex, $checked ) {
3703 global $wgUser, $wgUseMediaWikiUIEverywhere;
3705 $checkboxes = array();
3707 // don't show the minor edit checkbox if it's a new page or section
3708 if ( !$this->isNew
) {
3709 $checkboxes['minor'] = '';
3710 $minorLabel = wfMessage( 'minoredit' )->parse();
3711 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3713 'tabindex' => ++
$tabindex,
3714 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3715 'id' => 'wpMinoredit',
3718 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3719 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3720 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3721 ">{$minorLabel}</label>";
3723 if ( $wgUseMediaWikiUIEverywhere ) {
3724 $checkboxes['minor'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3726 Html
::closeElement( 'div' );
3728 $checkboxes['minor'] = $minorEditHtml;
3733 $watchLabel = wfMessage( 'watchthis' )->parse();
3734 $checkboxes['watch'] = '';
3735 if ( $wgUser->isLoggedIn() ) {
3737 'tabindex' => ++
$tabindex,
3738 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3739 'id' => 'wpWatchthis',
3742 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3743 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3744 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3745 ">{$watchLabel}</label>";
3746 if ( $wgUseMediaWikiUIEverywhere ) {
3747 $checkboxes['watch'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3749 Html
::closeElement( 'div' );
3751 $checkboxes['watch'] = $watchThisHtml;
3754 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3759 * Returns an array of html code of the following buttons:
3760 * save, diff, preview and live
3762 * @param int $tabindex Current tabindex
3766 public function getEditButtons( &$tabindex ) {
3767 global $wgUseMediaWikiUIEverywhere;
3775 'tabindex' => ++
$tabindex,
3776 'value' => wfMessage( 'savearticle' )->text(),
3777 ) + Linker
::tooltipAndAccesskeyAttribs( 'save' );
3778 if ( $wgUseMediaWikiUIEverywhere ) {
3779 $attribs['class'] = 'mw-ui-button mw-ui-constructive';
3781 $buttons['save'] = Xml
::element( 'input', $attribs, '' );
3783 ++
$tabindex; // use the same for preview and live preview
3785 'id' => 'wpPreview',
3786 'name' => 'wpPreview',
3788 'tabindex' => $tabindex,
3789 'value' => wfMessage( 'showpreview' )->text(),
3790 ) + Linker
::tooltipAndAccesskeyAttribs( 'preview' );
3791 if ( $wgUseMediaWikiUIEverywhere ) {
3792 $attribs['class'] = 'mw-ui-button mw-ui-progressive';
3794 $buttons['preview'] = Xml
::element( 'input', $attribs, '' );
3795 $buttons['live'] = '';
3801 'tabindex' => ++
$tabindex,
3802 'value' => wfMessage( 'showdiff' )->text(),
3803 ) + Linker
::tooltipAndAccesskeyAttribs( 'diff' );
3804 if ( $wgUseMediaWikiUIEverywhere ) {
3805 $attribs['class'] = 'mw-ui-button mw-ui-progressive';
3807 $buttons['diff'] = Xml
::element( 'input', $attribs, '' );
3809 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3814 * Output preview text only. This can be sucked into the edit page
3815 * via JavaScript, and saves the server time rendering the skin as
3816 * well as theoretically being more robust on the client (doesn't
3817 * disturb the edit box's undo history, won't eat your text on
3820 * @todo This doesn't include category or interlanguage links.
3821 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3822 * or something...</s>" that might also require more skin
3823 * initialization, so check whether that's a problem.
3825 function livePreview() {
3828 header( 'Content-type: text/xml; charset=utf-8' );
3829 header( 'Cache-control: no-cache' );
3831 $previewText = $this->getPreviewText();
3832 #$categories = $skin->getCategoryLinks();
3835 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3836 Xml
::tags( 'livepreview', null,
3837 Xml
::element( 'preview', null, $previewText )
3838 #. Xml::element( 'category', null, $categories )
3844 * Creates a basic error page which informs the user that
3845 * they have attempted to edit a nonexistent section.
3847 function noSuchSectionPage() {
3850 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3852 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3853 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3854 $wgOut->addHTML( $res );
3856 $wgOut->returnToMain( false, $this->mTitle
);
3860 * Show "your edit contains spam" page with your diff and text
3862 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3864 public function spamPageWithContent( $match = false ) {
3865 global $wgOut, $wgLang;
3866 $this->textbox2
= $this->textbox1
;
3868 if ( is_array( $match ) ) {
3869 $match = $wgLang->listToText( $match );
3871 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3873 $wgOut->addHTML( '<div id="spamprotected">' );
3874 $wgOut->addWikiMsg( 'spamprotectiontext' );
3876 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3878 $wgOut->addHTML( '</div>' );
3880 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3883 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3884 $this->showTextbox2();
3886 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3890 * Check if the browser is on a blacklist of user-agents known to
3891 * mangle UTF-8 data on form submission. Returns true if Unicode
3892 * should make it through, false if it's known to be a problem.
3895 private function checkUnicodeCompliantBrowser() {
3896 global $wgBrowserBlackList, $wgRequest;
3898 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3899 if ( $currentbrowser === false ) {
3900 // No User-Agent header sent? Trust it by default...
3904 foreach ( $wgBrowserBlackList as $browser ) {
3905 if ( preg_match( $browser, $currentbrowser ) ) {
3913 * Filter an input field through a Unicode de-armoring process if it
3914 * came from an old browser with known broken Unicode editing issues.
3916 * @param WebRequest $request
3917 * @param string $field
3920 protected function safeUnicodeInput( $request, $field ) {
3921 $text = rtrim( $request->getText( $field ) );
3922 return $request->getBool( 'safemode' )
3923 ?
$this->unmakeSafe( $text )
3928 * Filter an output field through a Unicode armoring process if it is
3929 * going to an old browser with known broken Unicode editing issues.
3931 * @param string $text
3934 protected function safeUnicodeOutput( $text ) {
3936 $codedText = $wgContLang->recodeForEdit( $text );
3937 return $this->checkUnicodeCompliantBrowser()
3939 : $this->makeSafe( $codedText );
3943 * A number of web browsers are known to corrupt non-ASCII characters
3944 * in a UTF-8 text editing environment. To protect against this,
3945 * detected browsers will be served an armored version of the text,
3946 * with non-ASCII chars converted to numeric HTML character references.
3948 * Preexisting such character references will have a 0 added to them
3949 * to ensure that round-trips do not alter the original data.
3951 * @param string $invalue
3954 private function makeSafe( $invalue ) {
3955 // Armor existing references for reversibility.
3956 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3961 $valueLength = strlen( $invalue );
3962 for ( $i = 0; $i < $valueLength; $i++
) {
3963 $bytevalue = ord( $invalue[$i] );
3964 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3965 $result .= chr( $bytevalue );
3967 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3968 $working = $working << 6;
3969 $working +
= ( $bytevalue & 0x3F );
3971 if ( $bytesleft <= 0 ) {
3972 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3974 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3975 $working = $bytevalue & 0x1F;
3977 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3978 $working = $bytevalue & 0x0F;
3980 } else { // 1111 0xxx
3981 $working = $bytevalue & 0x07;
3989 * Reverse the previously applied transliteration of non-ASCII characters
3990 * back to UTF-8. Used to protect data from corruption by broken web browsers
3991 * as listed in $wgBrowserBlackList.
3993 * @param string $invalue
3996 private function unmakeSafe( $invalue ) {
3998 $valueLength = strlen( $invalue );
3999 for ( $i = 0; $i < $valueLength; $i++
) {
4000 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4004 $hexstring .= $invalue[$i];
4006 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4008 // Do some sanity checks. These aren't needed for reversibility,
4009 // but should help keep the breakage down if the editor
4010 // breaks one of the entities whilst editing.
4011 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
4012 $codepoint = hexdec( $hexstring );
4013 $result .= codepointToUtf8( $codepoint );
4015 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4018 $result .= substr( $invalue, $i, 1 );
4021 // reverse the transform that we made for reversibility reasons.
4022 return strtr( $result, array( "�" => "&#x" ) );