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 protected $mTokenOk = false;
224 protected $mTokenOkExceptSuffix = false;
227 protected $mTriedSave = false;
230 protected $incompleteForm = false;
233 protected $tooBig = false;
236 protected $kblength = false;
239 protected $missingComment = false;
242 protected $missingSummary = false;
245 protected $allowBlankSummary = false;
248 protected $blankArticle = false;
251 protected $allowBlankArticle = false;
254 protected $autoSumm = '';
257 public $hookError = '';
259 /** @var ParserOutput */
260 protected $mParserOutput;
262 /** @var bool Has a summary been preset using GET parameter &summary= ? */
263 protected $hasPresetSummary = false;
266 protected $mBaseRevision = false;
269 public $mShowSummaryField = true;
274 public $save = false;
277 public $preview = false;
280 protected $diff = false;
283 public $minoredit = false;
286 protected $watchthis = false;
289 protected $recreate = false;
292 public $textbox1 = '';
295 public $textbox2 = '';
298 public $summary = '';
301 protected $nosummary = false;
304 public $edittime = '';
307 public $section = '';
310 public $sectiontitle = '';
313 protected $starttime = '';
319 protected $editintro = '';
322 public $scrolltop = null;
327 /** @var null|string */
328 public $contentModel = null;
330 /** @var null|string */
331 public $contentFormat = null;
333 # Placeholders for text injection by hooks (must be HTML)
334 # extensions should take care to _append_ to the present value
336 /** @var string Before even the preview */
337 public $editFormPageTop = '';
338 public $editFormTextTop = '';
339 public $editFormTextBeforeContent = '';
340 public $editFormTextAfterWarn = '';
341 public $editFormTextAfterTools = '';
342 public $editFormTextBottom = '';
343 public $editFormTextAfterContent = '';
344 public $previewTextAfterContent = '';
345 public $mPreloadContent = null;
347 /* $didSave should be set to true whenever an article was successfully altered. */
348 public $didSave = false;
349 public $undidRev = 0;
351 public $suppressIntro = false;
353 /** @var bool Set to true to allow editing of non-text content types. */
354 public $allowNonTextContent = false;
363 * @param Article $article
365 public function __construct( Article
$article ) {
366 $this->mArticle
= $article;
367 $this->mTitle
= $article->getTitle();
369 $this->contentModel
= $this->mTitle
->getContentModel();
371 $handler = ContentHandler
::getForModelID( $this->contentModel
);
372 $this->contentFormat
= $handler->getDefaultFormat();
378 public function getArticle() {
379 return $this->mArticle
;
386 public function getTitle() {
387 return $this->mTitle
;
391 * Set the context Title object
393 * @param Title|null $title Title object or null
395 public function setContextTitle( $title ) {
396 $this->mContextTitle
= $title;
400 * Get the context title object.
401 * If not set, $wgTitle will be returned. This behavior might change in
402 * the future to return $this->mTitle instead.
406 public function getContextTitle() {
407 if ( is_null( $this->mContextTitle
) ) {
411 return $this->mContextTitle
;
416 * Returns if the given content model is editable.
418 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
420 * @throws MWException If $modelId has no known handler
422 public function isSupportedContentModel( $modelId ) {
423 return $this->allowNonTextContent ||
424 ContentHandler
::getForModelID( $modelId ) instanceof TextContentHandler
;
432 * This is the function that gets called for "action=edit". It
433 * sets up various member variables, then passes execution to
434 * another function, usually showEditForm()
436 * The edit form is self-submitting, so that when things like
437 * preview and edit conflicts occur, we get the same form back
438 * with the extra stuff added. Only when the final submission
439 * is made and all is well do we actually save and redirect to
440 * the newly-edited page.
443 global $wgOut, $wgRequest, $wgUser;
444 // Allow extensions to modify/prevent this form or submission
445 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
449 wfProfileIn( __METHOD__
);
450 wfDebug( __METHOD__
. ": enter\n" );
452 // If they used redlink=1 and the page exists, redirect to the main article
453 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
454 $wgOut->redirect( $this->mTitle
->getFullURL() );
455 wfProfileOut( __METHOD__
);
459 $this->importFormData( $wgRequest );
460 $this->firsttime
= false;
463 $this->livePreview();
464 wfProfileOut( __METHOD__
);
468 if ( wfReadOnly() && $this->save
) {
471 $this->preview
= true;
475 $this->formtype
= 'save';
476 } elseif ( $this->preview
) {
477 $this->formtype
= 'preview';
478 } elseif ( $this->diff
) {
479 $this->formtype
= 'diff';
480 } else { # First time through
481 $this->firsttime
= true;
482 if ( $this->previewOnOpen() ) {
483 $this->formtype
= 'preview';
485 $this->formtype
= 'initial';
489 $permErrors = $this->getEditPermissionErrors();
491 wfDebug( __METHOD__
. ": User can't edit\n" );
492 // Auto-block user's IP if the account was "hard" blocked
493 $wgUser->spreadAnyEditBlock();
495 $this->displayPermissionsError( $permErrors );
497 wfProfileOut( __METHOD__
);
501 wfProfileIn( __METHOD__
. "-business-end" );
503 $this->isConflict
= false;
504 // css / js subpages of user pages get a special treatment
505 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
506 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
507 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
508 // @todo FIXME: Silly assignment.
509 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
511 # Show applicable editing introductions
512 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
516 # Attempt submission here. This will check for edit conflicts,
517 # and redundantly check for locked database, blocked IPs, etc.
518 # that edit() already checked just in case someone tries to sneak
519 # in the back door with a hand-edited submission URL.
521 if ( 'save' == $this->formtype
) {
522 if ( !$this->attemptSave() ) {
523 wfProfileOut( __METHOD__
. "-business-end" );
524 wfProfileOut( __METHOD__
);
529 # First time through: get contents, set time for conflict
531 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
532 if ( $this->initialiseForm() === false ) {
533 $this->noSuchSectionPage();
534 wfProfileOut( __METHOD__
. "-business-end" );
535 wfProfileOut( __METHOD__
);
539 if ( !$this->mTitle
->getArticleID() ) {
540 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
542 wfRunHooks( 'EditFormInitialText', array( $this ) );
547 $this->showEditForm();
548 wfProfileOut( __METHOD__
. "-business-end" );
549 wfProfileOut( __METHOD__
);
555 protected function getEditPermissionErrors() {
557 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
558 # Can this title be created?
559 if ( !$this->mTitle
->exists() ) {
560 $permErrors = array_merge( $permErrors,
561 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
563 # Ignore some permissions errors when a user is just previewing/viewing diffs
565 foreach ( $permErrors as $error ) {
566 if ( ( $this->preview ||
$this->diff
)
567 && ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' )
572 $permErrors = wfArrayDiff2( $permErrors, $remove );
577 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
578 * but with the following differences:
579 * - If redlink=1, the user will be redirected to the page
580 * - If there is content to display or the error occurs while either saving,
581 * previewing or showing the difference, it will be a
582 * "View source for ..." page displaying the source code after the error message.
585 * @param array $permErrors Array of permissions errors, as returned by
586 * Title::getUserPermissionsErrors().
587 * @throws PermissionsError
589 protected function displayPermissionsError( array $permErrors ) {
590 global $wgRequest, $wgOut;
592 if ( $wgRequest->getBool( 'redlink' ) ) {
593 // The edit page was reached via a red link.
594 // Redirect to the article page and let them click the edit tab if
595 // they really want a permission error.
596 $wgOut->redirect( $this->mTitle
->getFullURL() );
600 $content = $this->getContentObject();
602 # Use the normal message if there's nothing to display
603 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
604 $action = $this->mTitle
->exists() ?
'edit' :
605 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
606 throw new PermissionsError( $action, $permErrors );
609 wfRunHooks( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
611 $wgOut->setRobotPolicy( 'noindex,nofollow' );
612 $wgOut->setPageTitle( wfMessage(
614 $this->getContextTitle()->getPrefixedText()
616 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
617 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
618 $wgOut->addHTML( "<hr />\n" );
620 # If the user made changes, preserve them when showing the markup
621 # (This happens when a user is blocked during edit, for instance)
622 if ( !$this->firsttime
) {
623 $text = $this->textbox1
;
624 $wgOut->addWikiMsg( 'viewyourtext' );
626 $text = $this->toEditText( $content );
627 $wgOut->addWikiMsg( 'viewsourcetext' );
630 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
632 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
633 Linker
::formatTemplates( $this->getTemplates() ) ) );
635 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
637 if ( $this->mTitle
->exists() ) {
638 $wgOut->returnToMain( null, $this->mTitle
);
643 * Should we show a preview when the edit form is first shown?
647 protected function previewOnOpen() {
648 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
649 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
650 // Explicit override from request
652 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
653 // Explicit override from request
655 } elseif ( $this->section
== 'new' ) {
656 // Nothing *to* preview for new sections
658 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
659 && $wgUser->getOption( 'previewonfirst' )
661 // Standard preference behavior
663 } elseif ( !$this->mTitle
->exists()
664 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
665 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
667 // Categories are special
675 * Checks whether the user entered a skin name in uppercase,
676 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
680 protected function isWrongCaseCssJsPage() {
681 if ( $this->mTitle
->isCssJsSubpage() ) {
682 $name = $this->mTitle
->getSkinFromCssJsSubpage();
683 $skins = array_merge(
684 array_keys( Skin
::getSkinNames() ),
687 return !in_array( $name, $skins )
688 && in_array( strtolower( $name ), $skins );
695 * Returns whether section editing is supported for the current page.
696 * Subclasses may override this to replace the default behavior, which is
697 * to check ContentHandler::supportsSections.
699 * @return bool True if this edit page supports sections, false otherwise.
701 protected function isSectionEditSupported() {
702 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
703 return $contentHandler->supportsSections();
707 * This function collects the form data and uses it to populate various member variables.
708 * @param WebRequest $request
709 * @throws ErrorPageError
711 function importFormData( &$request ) {
712 global $wgContLang, $wgUser;
714 wfProfileIn( __METHOD__
);
716 # Section edit can come from either the form or a link
717 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
719 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
720 wfProfileOut( __METHOD__
);
721 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
724 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
726 if ( $request->wasPosted() ) {
727 # These fields need to be checked for encoding.
728 # Also remove trailing whitespace, but don't remove _initial_
729 # whitespace from the text boxes. This may be significant formatting.
730 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
731 if ( !$request->getCheck( 'wpTextbox2' ) ) {
732 // Skip this if wpTextbox2 has input, it indicates that we came
733 // from a conflict page with raw page text, not a custom form
734 // modified by subclasses
735 wfProfileIn( get_class( $this ) . "::importContentFormData" );
736 $textbox1 = $this->importContentFormData( $request );
737 if ( $textbox1 !== null ) {
738 $this->textbox1
= $textbox1;
741 wfProfileOut( get_class( $this ) . "::importContentFormData" );
744 # Truncate for whole multibyte characters
745 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
747 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
748 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
750 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
752 # Treat sectiontitle the same way as summary.
753 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
754 # currently doing double duty as both edit summary and section title. Right now this
755 # is just to allow API edits to work around this limitation, but this should be
756 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
757 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
758 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
760 $this->edittime
= $request->getVal( 'wpEdittime' );
761 $this->starttime
= $request->getVal( 'wpStarttime' );
763 $undidRev = $request->getInt( 'wpUndidRevision' );
765 $this->undidRev
= $undidRev;
768 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
770 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
771 // wpTextbox1 field is missing, possibly due to being "too big"
772 // according to some filter rules such as Suhosin's setting for
773 // suhosin.request.max_value_length (d'oh)
774 $this->incompleteForm
= true;
776 // If we receive the last parameter of the request, we can fairly
777 // claim the POST request has not been truncated.
779 // TODO: softened the check for cutover. Once we determine
780 // that it is safe, we should complete the transition by
781 // removing the "edittime" clause.
782 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' ) && is_null( $this->edittime
) );
784 if ( $this->incompleteForm
) {
785 # If the form is incomplete, force to preview.
786 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
787 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
788 $this->preview
= true;
790 /* Fallback for live preview */
791 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
792 $this->diff
= $request->getCheck( 'wpDiff' );
794 // Remember whether a save was requested, so we can indicate
795 // if we forced preview due to session failure.
796 $this->mTriedSave
= !$this->preview
;
798 if ( $this->tokenOk( $request ) ) {
799 # Some browsers will not report any submit button
800 # if the user hits enter in the comment box.
801 # The unmarked state will be assumed to be a save,
802 # if the form seems otherwise complete.
803 wfDebug( __METHOD__
. ": Passed token check.\n" );
804 } elseif ( $this->diff
) {
805 # Failed token check, but only requested "Show Changes".
806 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
808 # Page might be a hack attempt posted from
809 # an external site. Preview instead of saving.
810 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
811 $this->preview
= true;
814 $this->save
= !$this->preview
&& !$this->diff
;
815 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
816 $this->edittime
= null;
819 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
820 $this->starttime
= null;
823 $this->recreate
= $request->getCheck( 'wpRecreate' );
825 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
826 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
828 # Don't force edit summaries when a user is editing their own user or talk page
829 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
830 && $this->mTitle
->getText() == $wgUser->getName()
832 $this->allowBlankSummary
= true;
834 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
835 ||
!$wgUser->getOption( 'forceeditsummary' );
838 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
840 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
842 # Not a posted form? Start with nothing.
843 wfDebug( __METHOD__
. ": Not a posted form.\n" );
844 $this->textbox1
= '';
846 $this->sectiontitle
= '';
847 $this->edittime
= '';
848 $this->starttime
= wfTimestampNow();
850 $this->preview
= false;
853 $this->minoredit
= false;
854 // Watch may be overridden by request parameters
855 $this->watchthis
= $request->getBool( 'watchthis', false );
856 $this->recreate
= false;
858 // When creating a new section, we can preload a section title by passing it as the
859 // preloadtitle parameter in the URL (Bug 13100)
860 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
861 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
862 // Once wpSummary isn't being use for setting section titles, we should delete this.
863 $this->summary
= $request->getVal( 'preloadtitle' );
864 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
865 $this->summary
= $request->getText( 'summary' );
866 if ( $this->summary
!== '' ) {
867 $this->hasPresetSummary
= true;
871 if ( $request->getVal( 'minor' ) ) {
872 $this->minoredit
= true;
876 $this->oldid
= $request->getInt( 'oldid' );
878 $this->bot
= $request->getBool( 'bot', true );
879 $this->nosummary
= $request->getBool( 'nosummary' );
881 // May be overridden by revision.
882 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
883 // May be overridden by revision.
884 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
886 if ( !ContentHandler
::getForModelID( $this->contentModel
)
887 ->isSupportedFormat( $this->contentFormat
)
889 throw new ErrorPageError(
890 'editpage-notsupportedcontentformat-title',
891 'editpage-notsupportedcontentformat-text',
892 array( $this->contentFormat
, ContentHandler
::getLocalizedName( $this->contentModel
) )
897 * @todo Check if the desired model is allowed in this namespace, and if
898 * a transition from the page's current model to the new model is
902 $this->live
= $request->getCheck( 'live' );
903 $this->editintro
= $request->getText( 'editintro',
904 // Custom edit intro for new sections
905 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
907 // Allow extensions to modify form data
908 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
910 wfProfileOut( __METHOD__
);
914 * Subpage overridable method for extracting the page content data from the
915 * posted form to be placed in $this->textbox1, if using customized input
916 * this method should be overridden and return the page text that will be used
917 * for saving, preview parsing and so on...
919 * @param WebRequest $request
921 protected function importContentFormData( &$request ) {
922 return; // Don't do anything, EditPage already extracted wpTextbox1
926 * Initialise form fields in the object
927 * Called on the first invocation, e.g. when a user clicks an edit link
928 * @return bool If the requested section is valid
930 function initialiseForm() {
932 $this->edittime
= $this->mArticle
->getTimestamp();
934 $content = $this->getContentObject( false ); #TODO: track content object?!
935 if ( $content === false ) {
938 $this->textbox1
= $this->toEditText( $content );
940 // activate checkboxes if user wants them to be always active
941 # Sort out the "watch" checkbox
942 if ( $wgUser->getOption( 'watchdefault' ) ) {
944 $this->watchthis
= true;
945 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
947 $this->watchthis
= true;
948 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
950 $this->watchthis
= true;
952 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
953 $this->minoredit
= true;
955 if ( $this->textbox1
=== false ) {
962 * @param Content|null $def_content The default value to return
964 * @return Content|null Content on success, $def_content for invalid sections
968 protected function getContentObject( $def_content = null ) {
969 global $wgOut, $wgRequest, $wgUser, $wgContLang;
971 wfProfileIn( __METHOD__
);
975 // For message page not locally set, use the i18n message.
976 // For other non-existent articles, use preload text if any.
977 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
978 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
979 # If this is a system message, get the default text.
980 $msg = $this->mTitle
->getDefaultMessageText();
982 $content = $this->toEditContent( $msg );
984 if ( $content === false ) {
985 # If requested, preload some text.
986 $preload = $wgRequest->getVal( 'preload',
987 // Custom preload text for new sections
988 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
989 $params = $wgRequest->getArray( 'preloadparams', array() );
991 $content = $this->getPreloadedContent( $preload, $params );
993 // For existing pages, get text based on "undo" or section parameters.
995 if ( $this->section
!= '' ) {
996 // Get section edit text (returns $def_text for invalid sections)
997 $orig = $this->getOriginalContent( $wgUser );
998 $content = $orig ?
$orig->getSection( $this->section
) : null;
1001 $content = $def_content;
1004 $undoafter = $wgRequest->getInt( 'undoafter' );
1005 $undo = $wgRequest->getInt( 'undo' );
1007 if ( $undo > 0 && $undoafter > 0 ) {
1009 $undorev = Revision
::newFromId( $undo );
1010 $oldrev = Revision
::newFromId( $undoafter );
1012 # Sanity check, make sure it's the right page,
1013 # the revisions exist and they were not deleted.
1014 # Otherwise, $content will be left as-is.
1015 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1016 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1017 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
1019 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
1021 if ( $content === false ) {
1022 # Warn the user that something went wrong
1023 $undoMsg = 'failure';
1025 $oldContent = $this->mArticle
->getPage()->getContent( Revision
::RAW
);
1026 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
1027 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
1029 if ( $newContent->equals( $oldContent ) ) {
1030 # Tell the user that the undo results in no change,
1031 # i.e. the revisions were already undone.
1032 $undoMsg = 'nochange';
1035 # Inform the user of our success and set an automatic edit summary
1036 $undoMsg = 'success';
1038 # If we just undid one rev, use an autosummary
1039 $firstrev = $oldrev->getNext();
1040 if ( $firstrev && $firstrev->getId() == $undo ) {
1041 $userText = $undorev->getUserText();
1042 if ( $userText === '' ) {
1043 $undoSummary = wfMessage(
1044 'undo-summary-username-hidden',
1046 )->inContentLanguage()->text();
1048 $undoSummary = wfMessage(
1052 )->inContentLanguage()->text();
1054 if ( $this->summary
=== '' ) {
1055 $this->summary
= $undoSummary;
1057 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
1058 ->inContentLanguage()->text() . $this->summary
;
1060 $this->undidRev
= $undo;
1062 $this->formtype
= 'diff';
1066 // Failed basic sanity checks.
1067 // Older revisions may have been removed since the link
1068 // was created, or we may simply have got bogus input.
1072 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1073 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1074 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
1075 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1078 if ( $content === false ) {
1079 $content = $this->getOriginalContent( $wgUser );
1084 wfProfileOut( __METHOD__
);
1089 * Get the content of the wanted revision, without section extraction.
1091 * The result of this function can be used to compare user's input with
1092 * section replaced in its context (using WikiPage::replaceSection())
1093 * to the original text of the edit.
1095 * This differs from Article::getContent() that when a missing revision is
1096 * encountered the result will be null and not the
1097 * 'missing-revision' message.
1100 * @param User $user The user to get the revision for
1101 * @return Content|null
1103 private function getOriginalContent( User
$user ) {
1104 if ( $this->section
== 'new' ) {
1105 return $this->getCurrentContent();
1107 $revision = $this->mArticle
->getRevisionFetched();
1108 if ( $revision === null ) {
1109 if ( !$this->contentModel
) {
1110 $this->contentModel
= $this->getTitle()->getContentModel();
1112 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1114 return $handler->makeEmptyContent();
1116 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1121 * Get the current content of the page. This is basically similar to
1122 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1123 * content object is returned instead of null.
1128 protected function getCurrentContent() {
1129 $rev = $this->mArticle
->getRevision();
1130 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1132 if ( $content === false ||
$content === null ) {
1133 if ( !$this->contentModel
) {
1134 $this->contentModel
= $this->getTitle()->getContentModel();
1136 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1138 return $handler->makeEmptyContent();
1140 # nasty side-effect, but needed for consistency
1141 $this->contentModel
= $rev->getContentModel();
1142 $this->contentFormat
= $rev->getContentFormat();
1149 * Use this method before edit() to preload some content into the edit box
1151 * @param Content $content
1155 public function setPreloadedContent( Content
$content ) {
1156 $this->mPreloadContent
= $content;
1160 * Get the contents to be preloaded into the box, either set by
1161 * an earlier setPreloadText() or by loading the given page.
1163 * @param string $preload Representing the title to preload from.
1164 * @param array $params Parameters to use (interface-message style) in the preloaded text
1170 protected function getPreloadedContent( $preload, $params = array() ) {
1173 if ( !empty( $this->mPreloadContent
) ) {
1174 return $this->mPreloadContent
;
1177 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1179 if ( $preload === '' ) {
1180 return $handler->makeEmptyContent();
1183 $title = Title
::newFromText( $preload );
1184 # Check for existence to avoid getting MediaWiki:Noarticletext
1185 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1186 //TODO: somehow show a warning to the user!
1187 return $handler->makeEmptyContent();
1190 $page = WikiPage
::factory( $title );
1191 if ( $page->isRedirect() ) {
1192 $title = $page->getRedirectTarget();
1194 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1195 //TODO: somehow show a warning to the user!
1196 return $handler->makeEmptyContent();
1198 $page = WikiPage
::factory( $title );
1201 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1202 $content = $page->getContent( Revision
::RAW
);
1205 //TODO: somehow show a warning to the user!
1206 return $handler->makeEmptyContent();
1209 if ( $content->getModel() !== $handler->getModelID() ) {
1210 $converted = $content->convert( $handler->getModelID() );
1212 if ( !$converted ) {
1213 //TODO: somehow show a warning to the user!
1214 wfDebug( "Attempt to preload incompatible content: "
1215 . "can't convert " . $content->getModel()
1216 . " to " . $handler->getModelID() );
1218 return $handler->makeEmptyContent();
1221 $content = $converted;
1224 return $content->preloadTransform( $title, $parserOptions, $params );
1228 * Make sure the form isn't faking a user's credentials.
1230 * @param WebRequest $request
1234 function tokenOk( &$request ) {
1236 $token = $request->getVal( 'wpEditToken' );
1237 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1238 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1239 return $this->mTokenOk
;
1243 * Sets post-edit cookie indicating the user just saved a particular revision.
1245 * This uses a temporary cookie for each revision ID so separate saves will never
1246 * interfere with each other.
1248 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1249 * the redirect. It must be clearable by JavaScript code, so it must not be
1250 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1253 * If the variable were set on the server, it would be cached, which is unwanted
1254 * since the post-edit state should only apply to the load right after the save.
1256 * @param int $statusValue The status value (to check for new article status)
1258 protected function setPostEditCookie( $statusValue ) {
1259 $revisionId = $this->mArticle
->getLatest();
1260 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1263 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1265 } elseif ( $this->oldid
) {
1269 $response = RequestContext
::getMain()->getRequest()->response();
1270 $response->setcookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
, array(
1271 'httpOnly' => false,
1276 * Attempt submission
1277 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1278 * @return bool False if output is done, true if the rest of the form should be displayed
1280 public function attemptSave() {
1283 $resultDetails = false;
1284 # Allow bots to exempt some edits from bot flagging
1285 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1286 $status = $this->internalAttemptSave( $resultDetails, $bot );
1288 return $this->handleStatus( $status, $resultDetails );
1292 * Handle status, such as after attempt save
1294 * @param Status $status
1295 * @param array|bool $resultDetails
1297 * @throws ErrorPageError
1298 * @return bool False, if output is done, true if rest of the form should be displayed
1300 private function handleStatus( Status
$status, $resultDetails ) {
1301 global $wgUser, $wgOut;
1304 * @todo FIXME: once the interface for internalAttemptSave() is made
1305 * nicer, this should use the message in $status
1307 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1308 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1310 $this->didSave
= true;
1311 if ( !$resultDetails['nullEdit'] ) {
1312 $this->setPostEditCookie( $status->value
);
1316 switch ( $status->value
) {
1317 case self
::AS_HOOK_ERROR_EXPECTED
:
1318 case self
::AS_CONTENT_TOO_BIG
:
1319 case self
::AS_ARTICLE_WAS_DELETED
:
1320 case self
::AS_CONFLICT_DETECTED
:
1321 case self
::AS_SUMMARY_NEEDED
:
1322 case self
::AS_TEXTBOX_EMPTY
:
1323 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1325 case self
::AS_BLANK_ARTICLE
:
1328 case self
::AS_HOOK_ERROR
:
1331 case self
::AS_PARSE_ERROR
:
1332 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1335 case self
::AS_SUCCESS_NEW_ARTICLE
:
1336 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1337 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1338 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1341 case self
::AS_SUCCESS_UPDATE
:
1343 $sectionanchor = $resultDetails['sectionanchor'];
1345 // Give extensions a chance to modify URL query on update
1347 'ArticleUpdateBeforeRedirect',
1348 array( $this->mArticle
, &$sectionanchor, &$extraQuery )
1351 if ( $resultDetails['redirect'] ) {
1352 if ( $extraQuery == '' ) {
1353 $extraQuery = 'redirect=no';
1355 $extraQuery = 'redirect=no&' . $extraQuery;
1358 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1361 case self
::AS_SPAM_ERROR
:
1362 $this->spamPageWithContent( $resultDetails['spam'] );
1365 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1366 throw new UserBlockedError( $wgUser->getBlock() );
1368 case self
::AS_IMAGE_REDIRECT_ANON
:
1369 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1370 throw new PermissionsError( 'upload' );
1372 case self
::AS_READ_ONLY_PAGE_ANON
:
1373 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1374 throw new PermissionsError( 'edit' );
1376 case self
::AS_READ_ONLY_PAGE
:
1377 throw new ReadOnlyError
;
1379 case self
::AS_RATE_LIMITED
:
1380 throw new ThrottledError();
1382 case self
::AS_NO_CREATE_PERMISSION
:
1383 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1384 throw new PermissionsError( $permission );
1387 // We don't recognize $status->value. The only way that can happen
1388 // is if an extension hook aborted from inside ArticleSave.
1389 // Render the status object into $this->hookError
1390 // FIXME this sucks, we should just use the Status object throughout
1391 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1398 * Run hooks that can filter edits just before they get saved.
1400 * @param Content $content The Content to filter.
1401 * @param Status $status For reporting the outcome to the caller
1402 * @param User $user The user performing the edit
1406 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1407 // Run old style post-section-merge edit filter
1408 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1409 array( $this, $content, &$this->hookError
, $this->summary
) ) ) {
1411 # Error messages etc. could be handled within the hook...
1412 $status->fatal( 'hookaborted' );
1413 $status->value
= self
::AS_HOOK_ERROR
;
1415 } elseif ( $this->hookError
!= '' ) {
1416 # ...or the hook could be expecting us to produce an error
1417 $status->fatal( 'hookaborted' );
1418 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1422 // Run new style post-section-merge edit filter
1423 if ( !wfRunHooks( 'EditFilterMergedContent',
1424 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1425 $user, $this->minoredit
) ) ) {
1427 # Error messages etc. could be handled within the hook...
1428 // XXX: $status->value may already be something informative...
1429 $this->hookError
= $status->getWikiText();
1430 $status->fatal( 'hookaborted' );
1431 $status->value
= self
::AS_HOOK_ERROR
;
1433 } elseif ( !$status->isOK() ) {
1434 # ...or the hook could be expecting us to produce an error
1435 // FIXME this sucks, we should just use the Status object throughout
1436 $this->hookError
= $status->getWikiText();
1437 $status->fatal( 'hookaborted' );
1438 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1446 * Return the summary to be used for a new section.
1448 * @param string $sectionanchor Set to the section anchor text
1451 private function newSectionSummary( &$sectionanchor = null ) {
1454 if ( $this->sectiontitle
!== '' ) {
1455 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1456 // If no edit summary was specified, create one automatically from the section
1457 // title and have it link to the new section. Otherwise, respect the summary as
1459 if ( $this->summary
=== '' ) {
1460 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1461 return wfMessage( 'newsectionsummary' )
1462 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1464 } elseif ( $this->summary
!== '' ) {
1465 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1466 # This is a new section, so create a link to the new section
1467 # in the revision summary.
1468 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1469 return wfMessage( 'newsectionsummary' )
1470 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1472 return $this->summary
;
1477 * Attempt submission (no UI)
1479 * @param array $result Array to add statuses to, currently with the
1481 * - spam (string): Spam string from content if any spam is detected by
1483 * - sectionanchor (string): Section anchor for a section save.
1484 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1486 * - redirect (bool): Set if doEditContent is OK. True if resulting
1487 * revision is a redirect.
1488 * @param bool $bot True if edit is being made under the bot right.
1490 * @return Status Status object, possibly with a message, but always with
1491 * one of the AS_* constants in $status->value,
1493 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1494 * various error display idiosyncrasies. There are also lots of cases
1495 * where error metadata is set in the object and retrieved later instead
1496 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1497 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1500 function internalAttemptSave( &$result, $bot = false ) {
1501 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1503 $status = Status
::newGood();
1505 wfProfileIn( __METHOD__
);
1506 wfProfileIn( __METHOD__
. '-checks' );
1508 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1509 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1510 $status->fatal( 'hookaborted' );
1511 $status->value
= self
::AS_HOOK_ERROR
;
1512 wfProfileOut( __METHOD__
. '-checks' );
1513 wfProfileOut( __METHOD__
);
1517 $spam = $wgRequest->getText( 'wpAntispam' );
1518 if ( $spam !== '' ) {
1521 $wgUser->getName() .
1523 $this->mTitle
->getPrefixedText() .
1524 '" submitted bogus field "' .
1528 $status->fatal( 'spamprotectionmatch', false );
1529 $status->value
= self
::AS_SPAM_ERROR
;
1530 wfProfileOut( __METHOD__
. '-checks' );
1531 wfProfileOut( __METHOD__
);
1536 # Construct Content object
1537 $textbox_content = $this->toEditContent( $this->textbox1
);
1538 } catch ( MWContentSerializationException
$ex ) {
1540 'content-failed-to-parse',
1541 $this->contentModel
,
1542 $this->contentFormat
,
1545 $status->value
= self
::AS_PARSE_ERROR
;
1546 wfProfileOut( __METHOD__
. '-checks' );
1547 wfProfileOut( __METHOD__
);
1551 # Check image redirect
1552 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1553 $textbox_content->isRedirect() &&
1554 !$wgUser->isAllowed( 'upload' )
1556 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1557 $status->setResult( false, $code );
1559 wfProfileOut( __METHOD__
. '-checks' );
1560 wfProfileOut( __METHOD__
);
1566 $match = self
::matchSummarySpamRegex( $this->summary
);
1567 if ( $match === false && $this->section
== 'new' ) {
1568 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1569 # regular summaries, it is added to the actual wikitext.
1570 if ( $this->sectiontitle
!== '' ) {
1571 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1572 $match = self
::matchSpamRegex( $this->sectiontitle
);
1574 # This branch is taken when the "Add Topic" user interface is used, or the API
1575 # is used with the 'summary' parameter.
1576 $match = self
::matchSpamRegex( $this->summary
);
1579 if ( $match === false ) {
1580 $match = self
::matchSpamRegex( $this->textbox1
);
1582 if ( $match !== false ) {
1583 $result['spam'] = $match;
1584 $ip = $wgRequest->getIP();
1585 $pdbk = $this->mTitle
->getPrefixedDBkey();
1586 $match = str_replace( "\n", '', $match );
1587 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1588 $status->fatal( 'spamprotectionmatch', $match );
1589 $status->value
= self
::AS_SPAM_ERROR
;
1590 wfProfileOut( __METHOD__
. '-checks' );
1591 wfProfileOut( __METHOD__
);
1596 array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) )
1598 # Error messages etc. could be handled within the hook...
1599 $status->fatal( 'hookaborted' );
1600 $status->value
= self
::AS_HOOK_ERROR
;
1601 wfProfileOut( __METHOD__
. '-checks' );
1602 wfProfileOut( __METHOD__
);
1604 } elseif ( $this->hookError
!= '' ) {
1605 # ...or the hook could be expecting us to produce an error
1606 $status->fatal( 'hookaborted' );
1607 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1608 wfProfileOut( __METHOD__
. '-checks' );
1609 wfProfileOut( __METHOD__
);
1613 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1614 // Auto-block user's IP if the account was "hard" blocked
1615 $wgUser->spreadAnyEditBlock();
1616 # Check block state against master, thus 'false'.
1617 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1618 wfProfileOut( __METHOD__
. '-checks' );
1619 wfProfileOut( __METHOD__
);
1623 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1624 if ( $this->kblength
> $wgMaxArticleSize ) {
1625 // Error will be displayed by showEditForm()
1626 $this->tooBig
= true;
1627 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1628 wfProfileOut( __METHOD__
. '-checks' );
1629 wfProfileOut( __METHOD__
);
1633 if ( !$wgUser->isAllowed( 'edit' ) ) {
1634 if ( $wgUser->isAnon() ) {
1635 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1636 wfProfileOut( __METHOD__
. '-checks' );
1637 wfProfileOut( __METHOD__
);
1640 $status->fatal( 'readonlytext' );
1641 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1642 wfProfileOut( __METHOD__
. '-checks' );
1643 wfProfileOut( __METHOD__
);
1648 if ( wfReadOnly() ) {
1649 $status->fatal( 'readonlytext' );
1650 $status->value
= self
::AS_READ_ONLY_PAGE
;
1651 wfProfileOut( __METHOD__
. '-checks' );
1652 wfProfileOut( __METHOD__
);
1655 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1656 $status->fatal( 'actionthrottledtext' );
1657 $status->value
= self
::AS_RATE_LIMITED
;
1658 wfProfileOut( __METHOD__
. '-checks' );
1659 wfProfileOut( __METHOD__
);
1663 # If the article has been deleted while editing, don't save it without
1665 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1666 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1667 wfProfileOut( __METHOD__
. '-checks' );
1668 wfProfileOut( __METHOD__
);
1672 wfProfileOut( __METHOD__
. '-checks' );
1674 # Load the page data from the master. If anything changes in the meantime,
1675 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1676 $this->mArticle
->loadPageData( 'fromdbmaster' );
1677 $new = !$this->mArticle
->exists();
1680 // Late check for create permission, just in case *PARANOIA*
1681 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1682 $status->fatal( 'nocreatetext' );
1683 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1684 wfDebug( __METHOD__
. ": no create permission\n" );
1685 wfProfileOut( __METHOD__
);
1689 // Don't save a new page if it's blank or if it's a MediaWiki:
1690 // message with content equivalent to default (allow empty pages
1691 // in this case to disable messages, see bug 50124)
1692 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1693 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1694 $defaultText = $defaultMessageText;
1699 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1700 $this->blankArticle
= true;
1701 $status->fatal( 'blankarticle' );
1702 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1703 wfProfileOut( __METHOD__
);
1707 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1708 wfProfileOut( __METHOD__
);
1712 $content = $textbox_content;
1714 $result['sectionanchor'] = '';
1715 if ( $this->section
== 'new' ) {
1716 if ( $this->sectiontitle
!== '' ) {
1717 // Insert the section title above the content.
1718 $content = $content->addSectionHeader( $this->sectiontitle
);
1719 } elseif ( $this->summary
!== '' ) {
1720 // Insert the section title above the content.
1721 $content = $content->addSectionHeader( $this->summary
);
1723 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1726 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1730 # Article exists. Check for edit conflict.
1732 $this->mArticle
->clear(); # Force reload of dates, etc.
1733 $timestamp = $this->mArticle
->getTimestamp();
1735 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1737 if ( $timestamp != $this->edittime
) {
1738 $this->isConflict
= true;
1739 if ( $this->section
== 'new' ) {
1740 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1741 $this->mArticle
->getComment() == $this->newSectionSummary()
1743 // Probably a duplicate submission of a new comment.
1744 // This can happen when squid resends a request after
1745 // a timeout but the first one actually went through.
1747 . ": duplicate new section submission; trigger edit conflict!\n" );
1749 // New comment; suppress conflict.
1750 $this->isConflict
= false;
1751 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1753 } elseif ( $this->section
== ''
1754 && Revision
::userWasLastToEdit(
1755 DB_MASTER
, $this->mTitle
->getArticleID(),
1756 $wgUser->getId(), $this->edittime
1759 # Suppress edit conflict with self, except for section edits where merging is required.
1760 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1761 $this->isConflict
= false;
1765 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1766 if ( $this->sectiontitle
!== '' ) {
1767 $sectionTitle = $this->sectiontitle
;
1769 $sectionTitle = $this->summary
;
1774 if ( $this->isConflict
) {
1776 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1777 . " (article time '{$timestamp}')\n" );
1779 $content = $this->mArticle
->replaceSectionContent(
1786 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1787 $content = $this->mArticle
->replaceSectionContent(
1794 if ( is_null( $content ) ) {
1795 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1796 $this->isConflict
= true;
1797 $content = $textbox_content; // do not try to merge here!
1798 } elseif ( $this->isConflict
) {
1800 if ( $this->mergeChangesIntoContent( $content ) ) {
1801 // Successful merge! Maybe we should tell the user the good news?
1802 $this->isConflict
= false;
1803 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1805 $this->section
= '';
1806 $this->textbox1
= ContentHandler
::getContentText( $content );
1807 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1811 if ( $this->isConflict
) {
1812 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1813 wfProfileOut( __METHOD__
);
1817 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1818 wfProfileOut( __METHOD__
);
1822 if ( $this->section
== 'new' ) {
1823 // Handle the user preference to force summaries here
1824 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1825 $this->missingSummary
= true;
1826 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1827 $status->value
= self
::AS_SUMMARY_NEEDED
;
1828 wfProfileOut( __METHOD__
);
1832 // Do not allow the user to post an empty comment
1833 if ( $this->textbox1
== '' ) {
1834 $this->missingComment
= true;
1835 $status->fatal( 'missingcommenttext' );
1836 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1837 wfProfileOut( __METHOD__
);
1840 } elseif ( !$this->allowBlankSummary
1841 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1842 && !$content->isRedirect()
1843 && md5( $this->summary
) == $this->autoSumm
1845 $this->missingSummary
= true;
1846 $status->fatal( 'missingsummary' );
1847 $status->value
= self
::AS_SUMMARY_NEEDED
;
1848 wfProfileOut( __METHOD__
);
1853 wfProfileIn( __METHOD__
. '-sectionanchor' );
1854 $sectionanchor = '';
1855 if ( $this->section
== 'new' ) {
1856 $this->summary
= $this->newSectionSummary( $sectionanchor );
1857 } elseif ( $this->section
!= '' ) {
1858 # Try to get a section anchor from the section source, redirect
1859 # to edited section if header found.
1860 # XXX: Might be better to integrate this into Article::replaceSection
1861 # for duplicate heading checking and maybe parsing.
1862 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1863 # We can't deal with anchors, includes, html etc in the header for now,
1864 # headline would need to be parsed to improve this.
1865 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1866 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1869 $result['sectionanchor'] = $sectionanchor;
1870 wfProfileOut( __METHOD__
. '-sectionanchor' );
1872 // Save errors may fall down to the edit form, but we've now
1873 // merged the section into full text. Clear the section field
1874 // so that later submission of conflict forms won't try to
1875 // replace that into a duplicated mess.
1876 $this->textbox1
= $this->toEditText( $content );
1877 $this->section
= '';
1879 $status->value
= self
::AS_SUCCESS_UPDATE
;
1882 // Check for length errors again now that the section is merged in
1883 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1884 if ( $this->kblength
> $wgMaxArticleSize ) {
1885 $this->tooBig
= true;
1886 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1887 wfProfileOut( __METHOD__
);
1891 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1892 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1893 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1894 ( $bot ? EDIT_FORCE_BOT
: 0 );
1896 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags,
1897 false, null, $this->contentFormat
);
1899 if ( !$doEditStatus->isOK() ) {
1900 // Failure from doEdit()
1901 // Show the edit conflict page for certain recognized errors from doEdit(),
1902 // but don't show it for errors from extension hooks
1903 $errors = $doEditStatus->getErrorsArray();
1904 if ( in_array( $errors[0][0],
1905 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1907 $this->isConflict
= true;
1908 // Destroys data doEdit() put in $status->value but who cares
1909 $doEditStatus->value
= self
::AS_END
;
1911 wfProfileOut( __METHOD__
);
1912 return $doEditStatus;
1915 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1916 if ( $result['nullEdit'] ) {
1917 // We don't know if it was a null edit until now, so increment here
1918 $wgUser->pingLimiter( 'linkpurge' );
1920 $result['redirect'] = $content->isRedirect();
1921 $this->updateWatchlist();
1922 wfProfileOut( __METHOD__
);
1927 * Register the change of watch status
1929 protected function updateWatchlist() {
1932 if ( $wgUser->isLoggedIn()
1933 && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
, WatchedItem
::IGNORE_USER_RIGHTS
)
1935 $fname = __METHOD__
;
1936 $title = $this->mTitle
;
1937 $watch = $this->watchthis
;
1939 // Do this in its own transaction to reduce contention...
1940 $dbw = wfGetDB( DB_MASTER
);
1941 $dbw->onTransactionIdle( function () use ( $dbw, $title, $watch, $wgUser, $fname ) {
1942 $dbw->begin( $fname );
1943 WatchAction
::doWatchOrUnwatch( $watch, $title, $wgUser );
1944 $dbw->commit( $fname );
1950 * Attempts to do 3-way merge of edit content with a base revision
1951 * and current content, in case of edit conflict, in whichever way appropriate
1952 * for the content type.
1956 * @param Content $editContent
1960 private function mergeChangesIntoContent( &$editContent ) {
1961 wfProfileIn( __METHOD__
);
1963 $db = wfGetDB( DB_MASTER
);
1965 // This is the revision the editor started from
1966 $baseRevision = $this->getBaseRevision();
1967 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
1969 if ( is_null( $baseContent ) ) {
1970 wfProfileOut( __METHOD__
);
1974 // The current state, we want to merge updates into it
1975 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1976 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
1978 if ( is_null( $currentContent ) ) {
1979 wfProfileOut( __METHOD__
);
1983 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
1985 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1988 $editContent = $result;
1989 wfProfileOut( __METHOD__
);
1993 wfProfileOut( __METHOD__
);
2000 function getBaseRevision() {
2001 if ( !$this->mBaseRevision
) {
2002 $db = wfGetDB( DB_MASTER
);
2003 $this->mBaseRevision
= Revision
::loadFromTimestamp(
2004 $db, $this->mTitle
, $this->edittime
);
2006 return $this->mBaseRevision
;
2010 * Check given input text against $wgSpamRegex, and return the text of the first match.
2012 * @param string $text
2014 * @return string|bool Matching string or false
2016 public static function matchSpamRegex( $text ) {
2017 global $wgSpamRegex;
2018 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2019 $regexes = (array)$wgSpamRegex;
2020 return self
::matchSpamRegexInternal( $text, $regexes );
2024 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2026 * @param string $text
2028 * @return string|bool Matching string or false
2030 public static function matchSummarySpamRegex( $text ) {
2031 global $wgSummarySpamRegex;
2032 $regexes = (array)$wgSummarySpamRegex;
2033 return self
::matchSpamRegexInternal( $text, $regexes );
2037 * @param string $text
2038 * @param array $regexes
2039 * @return bool|string
2041 protected static function matchSpamRegexInternal( $text, $regexes ) {
2042 foreach ( $regexes as $regex ) {
2044 if ( preg_match( $regex, $text, $matches ) ) {
2051 function setHeaders() {
2052 global $wgOut, $wgUser;
2054 $wgOut->addModules( 'mediawiki.action.edit' );
2055 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2057 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
2058 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2061 if ( $wgUser->getOption( 'useeditwarning', false ) ) {
2062 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2065 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2067 # Enabled article-related sidebar, toplinks, etc.
2068 $wgOut->setArticleRelated( true );
2070 $contextTitle = $this->getContextTitle();
2071 if ( $this->isConflict
) {
2072 $msg = 'editconflict';
2073 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2074 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2076 $msg = $contextTitle->exists()
2077 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2078 && $contextTitle->getDefaultMessageText() !== false
2084 # Use the title defined by DISPLAYTITLE magic word when present
2085 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2086 if ( $displayTitle === false ) {
2087 $displayTitle = $contextTitle->getPrefixedText();
2089 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2093 * Show all applicable editing introductions
2095 protected function showIntro() {
2096 global $wgOut, $wgUser;
2097 if ( $this->suppressIntro
) {
2101 $namespace = $this->mTitle
->getNamespace();
2103 if ( $namespace == NS_MEDIAWIKI
) {
2104 # Show a warning if editing an interface message
2105 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2106 } elseif ( $namespace == NS_FILE
) {
2107 # Show a hint to shared repo
2108 $file = wfFindFile( $this->mTitle
);
2109 if ( $file && !$file->isLocal() ) {
2110 $descUrl = $file->getDescriptionUrl();
2111 # there must be a description url to show a hint to shared repo
2113 if ( !$this->mTitle
->exists() ) {
2114 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2115 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2118 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2119 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2126 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2127 # Show log extract when the user is currently blocked
2128 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2129 $parts = explode( '/', $this->mTitle
->getText(), 2 );
2130 $username = $parts[0];
2131 $user = User
::newFromName( $username, false /* allow IP users*/ );
2132 $ip = User
::isIP( $username );
2133 $block = Block
::newFromTarget( $user, $user );
2134 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2135 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2136 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2137 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) { # Show log extract if the user is currently blocked
2138 LogEventsList
::showLogExtract(
2141 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2145 'showIfEmpty' => false,
2147 'blocked-notice-logextract',
2148 $user->getName() # Support GENDER in notice
2154 # Try to add a custom edit intro, or use the standard one if this is not possible.
2155 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2156 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2157 wfMessage( 'helppage' )->inContentLanguage()->text()
2159 if ( $wgUser->isLoggedIn() ) {
2160 $wgOut->wrapWikiMsg(
2161 // Suppress the external link icon, consider the help url an internal one
2162 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2169 $wgOut->wrapWikiMsg(
2170 // Suppress the external link icon, consider the help url an internal one
2171 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2173 'newarticletextanon',
2179 # Give a notice if the user is editing a deleted/moved page...
2180 if ( !$this->mTitle
->exists() ) {
2181 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
2185 'conds' => array( "log_action != 'revision'" ),
2186 'showIfEmpty' => false,
2187 'msgKey' => array( 'recreate-moveddeleted-warn' )
2194 * Attempt to show a custom editing introduction, if supplied
2198 protected function showCustomIntro() {
2199 if ( $this->editintro
) {
2200 $title = Title
::newFromText( $this->editintro
);
2201 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2203 // Added using template syntax, to take <noinclude>'s into account.
2204 $wgOut->addWikiTextTitleTidy( '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>', $this->mTitle
);
2212 * Gets an editable textual representation of $content.
2213 * The textual representation can be turned by into a Content object by the
2214 * toEditContent() method.
2216 * If $content is null or false or a string, $content is returned unchanged.
2218 * If the given Content object is not of a type that can be edited using
2219 * the text base EditPage, an exception will be raised. Set
2220 * $this->allowNonTextContent to true to allow editing of non-textual
2223 * @param Content|null|bool|string $content
2224 * @return string The editable text form of the content.
2226 * @throws MWException If $content is not an instance of TextContent and
2227 * $this->allowNonTextContent is not true.
2229 protected function toEditText( $content ) {
2230 if ( $content === null ||
$content === false ) {
2234 if ( is_string( $content ) ) {
2238 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2239 throw new MWException( 'This content model is not supported: '
2240 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2243 return $content->serialize( $this->contentFormat
);
2247 * Turns the given text into a Content object by unserializing it.
2249 * If the resulting Content object is not of a type that can be edited using
2250 * the text base EditPage, an exception will be raised. Set
2251 * $this->allowNonTextContent to true to allow editing of non-textual
2254 * @param string|null|bool $text Text to unserialize
2255 * @return Content The content object created from $text. If $text was false
2256 * or null, false resp. null will be returned instead.
2258 * @throws MWException If unserializing the text results in a Content
2259 * object that is not an instance of TextContent and
2260 * $this->allowNonTextContent is not true.
2262 protected function toEditContent( $text ) {
2263 if ( $text === false ||
$text === null ) {
2267 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2268 $this->contentModel
, $this->contentFormat
);
2270 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2271 throw new MWException( 'This content model is not supported: '
2272 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2279 * Send the edit form and related headers to $wgOut
2280 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2281 * during form output near the top, for captchas and the like.
2283 function showEditForm( $formCallback = null ) {
2284 global $wgOut, $wgUser;
2286 wfProfileIn( __METHOD__
);
2288 # need to parse the preview early so that we know which templates are used,
2289 # otherwise users with "show preview after edit box" will get a blank list
2290 # we parse this near the beginning so that setHeaders can do the title
2291 # setting work instead of leaving it in getPreviewText
2292 $previewOutput = '';
2293 if ( $this->formtype
== 'preview' ) {
2294 $previewOutput = $this->getPreviewText();
2297 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2299 $this->setHeaders();
2301 if ( $this->showHeader() === false ) {
2302 wfProfileOut( __METHOD__
);
2306 $wgOut->addHTML( $this->editFormPageTop
);
2308 if ( $wgUser->getOption( 'previewontop' ) ) {
2309 $this->displayPreviewArea( $previewOutput, true );
2312 $wgOut->addHTML( $this->editFormTextTop
);
2314 $showToolbar = true;
2315 if ( $this->wasDeletedSinceLastEdit() ) {
2316 if ( $this->formtype
== 'save' ) {
2317 // Hide the toolbar and edit area, user can click preview to get it back
2318 // Add an confirmation checkbox and explanation.
2319 $showToolbar = false;
2321 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2322 'deletedwhileediting' );
2326 // @todo add EditForm plugin interface and use it here!
2327 // search for textarea1 and textares2, and allow EditForm to override all uses.
2328 $wgOut->addHTML( Html
::openElement(
2331 'id' => self
::EDITFORM_ID
,
2332 'name' => self
::EDITFORM_ID
,
2334 'action' => $this->getActionURL( $this->getContextTitle() ),
2335 'enctype' => 'multipart/form-data'
2339 if ( is_callable( $formCallback ) ) {
2340 call_user_func_array( $formCallback, array( &$wgOut ) );
2343 // Add an empty field to trip up spambots
2345 Xml
::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2348 array( 'for' => 'wpAntiSpam' ),
2349 wfMessage( 'simpleantispam-label' )->parse()
2355 'name' => 'wpAntispam',
2356 'id' => 'wpAntispam',
2360 . Xml
::closeElement( 'div' )
2363 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2365 // Put these up at the top to ensure they aren't lost on early form submission
2366 $this->showFormBeforeText();
2368 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2369 $username = $this->lastDelete
->user_name
;
2370 $comment = $this->lastDelete
->log_comment
;
2372 // It is better to not parse the comment at all than to have templates expanded in the middle
2373 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2374 $key = $comment === ''
2375 ?
'confirmrecreate-noreason'
2376 : 'confirmrecreate';
2378 '<div class="mw-confirm-recreate">' .
2379 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2380 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2381 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2387 # When the summary is hidden, also hide them on preview/show changes
2388 if ( $this->nosummary
) {
2389 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2392 # If a blank edit summary was previously provided, and the appropriate
2393 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2394 # user being bounced back more than once in the event that a summary
2397 # For a bit more sophisticated detection of blank summaries, hash the
2398 # automatic one and pass that in the hidden field wpAutoSummary.
2399 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2400 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2403 if ( $this->undidRev
) {
2404 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2407 if ( $this->hasPresetSummary
) {
2408 // If a summary has been preset using &summary= we don't want to prompt for
2409 // a different summary. Only prompt for a summary if the summary is blanked.
2411 $this->autoSumm
= md5( '' );
2414 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2415 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2417 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2419 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2420 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2422 if ( $this->section
== 'new' ) {
2423 $this->showSummaryInput( true, $this->summary
);
2424 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2427 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2429 if ( $this->contentModel
=== CONTENT_MODEL_WIKITEXT
&&
2430 $showToolbar && $wgUser->getOption( 'showtoolbar' ) )
2432 $wgOut->addHTML( EditPage
::getEditToolbar() );
2435 if ( $this->blankArticle
) {
2436 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2439 if ( $this->isConflict
) {
2440 // In an edit conflict bypass the overridable content form method
2441 // and fallback to the raw wpTextbox1 since editconflicts can't be
2442 // resolved between page source edits and custom ui edits using the
2444 $this->textbox2
= $this->textbox1
;
2446 $content = $this->getCurrentContent();
2447 $this->textbox1
= $this->toEditText( $content );
2449 $this->showTextbox1();
2451 $this->showContentForm();
2454 $wgOut->addHTML( $this->editFormTextAfterContent
);
2456 $this->showStandardInputs();
2458 $this->showFormAfterText();
2460 $this->showTosSummary();
2462 $this->showEditTools();
2464 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2466 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2467 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2469 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2470 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2472 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'limitreport' ),
2473 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2475 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2477 if ( $this->isConflict
) {
2479 $this->showConflict();
2480 } catch ( MWContentSerializationException
$ex ) {
2481 // this can't really happen, but be nice if it does.
2483 'content-failed-to-parse',
2484 $this->contentModel
,
2485 $this->contentFormat
,
2488 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2492 // Marker for detecting truncated form data. This must be the last
2493 // parameter sent in order to be of use, so do not move me.
2494 $wgOut->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2495 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2497 if ( !$wgUser->getOption( 'previewontop' ) ) {
2498 $this->displayPreviewArea( $previewOutput, false );
2501 wfProfileOut( __METHOD__
);
2505 * Extract the section title from current section text, if any.
2507 * @param string $text
2508 * @return string|bool String or false
2510 public static function extractSectionTitle( $text ) {
2511 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2512 if ( !empty( $matches[2] ) ) {
2514 return $wgParser->stripSectionName( trim( $matches[2] ) );
2523 protected function showHeader() {
2524 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2525 global $wgAllowUserCss, $wgAllowUserJs;
2527 if ( $this->mTitle
->isTalkPage() ) {
2528 $wgOut->addWikiMsg( 'talkpagetext' );
2532 $wgOut->addHTML( implode( "\n", $this->mTitle
->getEditNotices( $this->oldid
) ) );
2534 if ( $this->isConflict
) {
2535 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2536 $this->edittime
= $this->mArticle
->getTimestamp();
2538 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2539 // We use $this->section to much before this and getVal('wgSection') directly in other places
2540 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2541 // Someone is welcome to try refactoring though
2542 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2546 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2547 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2548 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2549 if ( $sectionTitle !== false ) {
2550 $this->summary
= "/* $sectionTitle */ ";
2555 if ( $this->missingComment
) {
2556 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2559 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2560 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2563 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2564 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2567 if ( $this->blankArticle
) {
2568 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2571 if ( $this->hookError
!== '' ) {
2572 $wgOut->addWikiText( $this->hookError
);
2575 if ( !$this->checkUnicodeCompliantBrowser() ) {
2576 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2579 if ( $this->section
!= 'new' ) {
2580 $revision = $this->mArticle
->getRevisionFetched();
2582 // Let sysop know that this will make private content public if saved
2584 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2585 $wgOut->wrapWikiMsg(
2586 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2587 'rev-deleted-text-permission'
2589 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2590 $wgOut->wrapWikiMsg(
2591 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2592 'rev-deleted-text-view'
2596 if ( !$revision->isCurrent() ) {
2597 $this->mArticle
->setOldSubtitle( $revision->getId() );
2598 $wgOut->addWikiMsg( 'editingold' );
2600 } elseif ( $this->mTitle
->exists() ) {
2601 // Something went wrong
2603 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2604 array( 'missing-revision', $this->oldid
) );
2609 if ( wfReadOnly() ) {
2610 $wgOut->wrapWikiMsg(
2611 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2612 array( 'readonlywarning', wfReadOnlyReason() )
2614 } elseif ( $wgUser->isAnon() ) {
2615 if ( $this->formtype
!= 'preview' ) {
2616 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2618 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2621 if ( $this->isCssJsSubpage
) {
2622 # Check the skin exists
2623 if ( $this->isWrongCaseCssJsPage
) {
2624 $wgOut->wrapWikiMsg(
2625 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2626 array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() )
2629 if ( $this->formtype
!== 'preview' ) {
2630 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
2631 $wgOut->wrapWikiMsg(
2632 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2633 array( 'usercssyoucanpreview' )
2637 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
2638 $wgOut->wrapWikiMsg(
2639 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2640 array( 'userjsyoucanpreview' )
2647 if ( $this->mTitle
->isProtected( 'edit' ) &&
2648 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2650 # Is the title semi-protected?
2651 if ( $this->mTitle
->isSemiProtected() ) {
2652 $noticeMsg = 'semiprotectedpagewarning';
2654 # Then it must be protected based on static groups (regular)
2655 $noticeMsg = 'protectedpagewarning';
2657 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2658 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2660 if ( $this->mTitle
->isCascadeProtected() ) {
2661 # Is this page under cascading protection from some source pages?
2662 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2663 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2664 $cascadeSourcesCount = count( $cascadeSources );
2665 if ( $cascadeSourcesCount > 0 ) {
2666 # Explain, and list the titles responsible
2667 foreach ( $cascadeSources as $page ) {
2668 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2671 $notice .= '</div>';
2672 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2674 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2675 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2677 'showIfEmpty' => false,
2678 'msgKey' => array( 'titleprotectedwarning' ),
2679 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2682 if ( $this->kblength
=== false ) {
2683 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2686 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2687 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2690 $wgLang->formatNum( $this->kblength
),
2691 $wgLang->formatNum( $wgMaxArticleSize )
2695 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2696 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2699 $wgLang->formatSize( strlen( $this->textbox1
) ),
2700 strlen( $this->textbox1
)
2705 # Add header copyright warning
2706 $this->showHeaderCopyrightWarning();
2712 * Standard summary input and label (wgSummary), abstracted so EditPage
2713 * subclasses may reorganize the form.
2714 * Note that you do not need to worry about the label's for=, it will be
2715 * inferred by the id given to the input. You can remove them both by
2716 * passing array( 'id' => false ) to $userInputAttrs.
2718 * @param string $summary The value of the summary input
2719 * @param string $labelText The html to place inside the label
2720 * @param array $inputAttrs Array of attrs to use on the input
2721 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2723 * @return array An array in the format array( $label, $input )
2725 function getSummaryInput( $summary = "", $labelText = null,
2726 $inputAttrs = null, $spanLabelAttrs = null
2728 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2729 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2730 'id' => 'wpSummary',
2731 'maxlength' => '200',
2734 'spellcheck' => 'true',
2735 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2737 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2738 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2739 'id' => "wpSummaryLabel"
2746 $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null,
2749 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2752 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2754 return array( $label, $input );
2758 * @param bool $isSubjectPreview True if this is the section subject/title
2759 * up top, or false if this is the comment summary
2760 * down below the textarea
2761 * @param string $summary The text of the summary to display
2764 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2765 global $wgOut, $wgContLang;
2766 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2767 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2768 if ( $isSubjectPreview ) {
2769 if ( $this->nosummary
) {
2773 if ( !$this->mShowSummaryField
) {
2777 $summary = $wgContLang->recodeForEdit( $summary );
2778 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2779 list( $label, $input ) = $this->getSummaryInput(
2782 array( 'class' => $summaryClass ),
2785 $wgOut->addHTML( "{$label} {$input}" );
2789 * @param bool $isSubjectPreview True if this is the section subject/title
2790 * up top, or false if this is the comment summary
2791 * down below the textarea
2792 * @param string $summary The text of the summary to display
2795 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2796 // avoid spaces in preview, gets always trimmed on save
2797 $summary = trim( $summary );
2798 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2804 if ( $isSubjectPreview ) {
2805 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2806 ->inContentLanguage()->text();
2809 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2811 $summary = wfMessage( $message )->parse()
2812 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2813 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2816 protected function showFormBeforeText() {
2818 $section = htmlspecialchars( $this->section
);
2819 $wgOut->addHTML( <<<HTML
2820 <input type='hidden' value="{$section}" name="wpSection" />
2821 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2822 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2823 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2827 if ( !$this->checkUnicodeCompliantBrowser() ) {
2828 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2832 protected function showFormAfterText() {
2833 global $wgOut, $wgUser;
2835 * To make it harder for someone to slip a user a page
2836 * which submits an edit form to the wiki without their
2837 * knowledge, a random token is associated with the login
2838 * session. If it's not passed back with the submission,
2839 * we won't save the page, or render user JavaScript and
2842 * For anon editors, who may not have a session, we just
2843 * include the constant suffix to prevent editing from
2844 * broken text-mangling proxies.
2846 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2850 * Subpage overridable method for printing the form for page content editing
2851 * By default this simply outputs wpTextbox1
2852 * Subclasses can override this to provide a custom UI for editing;
2853 * be it a form, or simply wpTextbox1 with a modified content that will be
2854 * reverse modified when extracted from the post data.
2855 * Note that this is basically the inverse for importContentFormData
2857 protected function showContentForm() {
2858 $this->showTextbox1();
2862 * Method to output wpTextbox1
2863 * The $textoverride method can be used by subclasses overriding showContentForm
2864 * to pass back to this method.
2866 * @param array $customAttribs Array of html attributes to use in the textarea
2867 * @param string $textoverride Optional text to override $this->textarea1 with
2869 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2870 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2871 $attribs = array( 'style' => 'display:none;' );
2873 $classes = array(); // Textarea CSS
2874 if ( $this->mTitle
->isProtected( 'edit' ) &&
2875 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2877 # Is the title semi-protected?
2878 if ( $this->mTitle
->isSemiProtected() ) {
2879 $classes[] = 'mw-textarea-sprotected';
2881 # Then it must be protected based on static groups (regular)
2882 $classes[] = 'mw-textarea-protected';
2884 # Is the title cascade-protected?
2885 if ( $this->mTitle
->isCascadeProtected() ) {
2886 $classes[] = 'mw-textarea-cprotected';
2890 $attribs = array( 'tabindex' => 1 );
2892 if ( is_array( $customAttribs ) ) {
2893 $attribs +
= $customAttribs;
2896 if ( count( $classes ) ) {
2897 if ( isset( $attribs['class'] ) ) {
2898 $classes[] = $attribs['class'];
2900 $attribs['class'] = implode( ' ', $classes );
2905 $textoverride !== null ?
$textoverride : $this->textbox1
,
2911 protected function showTextbox2() {
2912 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2915 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2916 global $wgOut, $wgUser;
2918 $wikitext = $this->safeUnicodeOutput( $text );
2919 if ( strval( $wikitext ) !== '' ) {
2920 // Ensure there's a newline at the end, otherwise adding lines
2922 // But don't add a newline if the ext is empty, or Firefox in XHTML
2923 // mode will show an extra newline. A bit annoying.
2927 $attribs = $customAttribs +
array(
2930 'cols' => $wgUser->getIntOption( 'cols' ),
2931 'rows' => $wgUser->getIntOption( 'rows' ),
2932 // Avoid PHP notices when appending preferences
2933 // (appending allows customAttribs['style'] to still work).
2937 $pageLang = $this->mTitle
->getPageLanguage();
2938 $attribs['lang'] = $pageLang->getCode();
2939 $attribs['dir'] = $pageLang->getDir();
2941 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2944 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2948 $classes[] = 'ontop';
2951 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2953 if ( $this->formtype
!= 'preview' ) {
2954 $attribs['style'] = 'display: none;';
2957 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2959 if ( $this->formtype
== 'preview' ) {
2960 $this->showPreview( $previewOutput );
2963 $wgOut->addHTML( '</div>' );
2965 if ( $this->formtype
== 'diff' ) {
2968 } catch ( MWContentSerializationException
$ex ) {
2970 'content-failed-to-parse',
2971 $this->contentModel
,
2972 $this->contentFormat
,
2975 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2981 * Append preview output to $wgOut.
2982 * Includes category rendering if this is a category page.
2984 * @param string $text The HTML to be output for the preview.
2986 protected function showPreview( $text ) {
2988 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2989 $this->mArticle
->openShowCategory();
2991 # This hook seems slightly odd here, but makes things more
2992 # consistent for extensions.
2993 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2994 $wgOut->addHTML( $text );
2995 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2996 $this->mArticle
->closeShowCategory();
3001 * Get a diff between the current contents of the edit box and the
3002 * version of the page we're editing from.
3004 * If this is a section edit, we'll replace the section as for final
3005 * save and then make a comparison.
3007 function showDiff() {
3008 global $wgUser, $wgContLang, $wgOut;
3010 $oldtitlemsg = 'currentrev';
3011 # if message does not exist, show diff against the preloaded default
3012 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3013 $oldtext = $this->mTitle
->getDefaultMessageText();
3014 if ( $oldtext !== false ) {
3015 $oldtitlemsg = 'defaultmessagetext';
3016 $oldContent = $this->toEditContent( $oldtext );
3021 $oldContent = $this->getCurrentContent();
3024 $textboxContent = $this->toEditContent( $this->textbox1
);
3026 $newContent = $this->mArticle
->replaceSectionContent(
3027 $this->section
, $textboxContent,
3028 $this->summary
, $this->edittime
);
3030 if ( $newContent ) {
3031 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3032 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3034 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
3035 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
3038 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3039 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3040 $newtitle = wfMessage( 'yourtext' )->parse();
3042 if ( !$oldContent ) {
3043 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3046 if ( !$newContent ) {
3047 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3050 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3051 $de->setContent( $oldContent, $newContent );
3053 $difftext = $de->getDiff( $oldtitle, $newtitle );
3054 $de->showDiffStyle();
3059 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3063 * Show the header copyright warning.
3065 protected function showHeaderCopyrightWarning() {
3066 $msg = 'editpage-head-copy-warn';
3067 if ( !wfMessage( $msg )->isDisabled() ) {
3069 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3070 'editpage-head-copy-warn' );
3075 * Give a chance for site and per-namespace customizations of
3076 * terms of service summary link that might exist separately
3077 * from the copyright notice.
3079 * This will display between the save button and the edit tools,
3080 * so should remain short!
3082 protected function showTosSummary() {
3083 $msg = 'editpage-tos-summary';
3084 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
3085 if ( !wfMessage( $msg )->isDisabled() ) {
3087 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3088 $wgOut->addWikiMsg( $msg );
3089 $wgOut->addHTML( '</div>' );
3093 protected function showEditTools() {
3095 $wgOut->addHTML( '<div class="mw-editTools">' .
3096 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3101 * Get the copyright warning
3103 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3105 protected function getCopywarn() {
3106 return self
::getCopyrightWarning( $this->mTitle
);
3110 * Get the copyright warning, by default returns wikitext
3112 * @param Title $title
3113 * @param string $format Output format, valid values are any function of a Message object
3116 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3117 global $wgRightsText;
3118 if ( $wgRightsText ) {
3119 $copywarnMsg = array( 'copyrightwarning',
3120 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3123 $copywarnMsg = array( 'copyrightwarning2',
3124 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3126 // Allow for site and per-namespace customization of contribution/copyright notice.
3127 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3129 return "<div id=\"editpage-copywarn\">\n" .
3130 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3134 * Get the Limit report for page previews
3137 * @param ParserOutput $output ParserOutput object from the parse
3138 * @return string HTML
3140 public static function getPreviewLimitReport( $output ) {
3141 if ( !$output ||
!$output->getLimitReportData() ) {
3145 wfProfileIn( __METHOD__
);
3147 $limitReport = Html
::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3148 wfMessage( 'limitreport-title' )->parseAsBlock()
3151 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3152 $limitReport .= Html
::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3154 $limitReport .= Html
::openElement( 'table', array(
3155 'class' => 'preview-limit-report wikitable'
3157 Html
::openElement( 'tbody' );
3159 foreach ( $output->getLimitReportData() as $key => $value ) {
3160 if ( wfRunHooks( 'ParserLimitReportFormat',
3161 array( $key, &$value, &$limitReport, true, true )
3163 $keyMsg = wfMessage( $key );
3164 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3165 if ( !$valueMsg->exists() ) {
3166 $valueMsg = new RawMessage( '$1' );
3168 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3169 $limitReport .= Html
::openElement( 'tr' ) .
3170 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3171 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3172 Html
::closeElement( 'tr' );
3177 $limitReport .= Html
::closeElement( 'tbody' ) .
3178 Html
::closeElement( 'table' ) .
3179 Html
::closeElement( 'div' );
3181 wfProfileOut( __METHOD__
);
3183 return $limitReport;
3186 protected function showStandardInputs( &$tabindex = 2 ) {
3188 $wgOut->addHTML( "<div class='editOptions'>\n" );
3190 if ( $this->section
!= 'new' ) {
3191 $this->showSummaryInput( false, $this->summary
);
3192 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3195 $checkboxes = $this->getCheckboxes( $tabindex,
3196 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
3197 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3199 // Show copyright warning.
3200 $wgOut->addWikiText( $this->getCopywarn() );
3201 $wgOut->addHTML( $this->editFormTextAfterWarn
);
3203 $wgOut->addHTML( "<div class='editButtons'>\n" );
3204 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3206 $cancel = $this->getCancelLink();
3207 if ( $cancel !== '' ) {
3208 $cancel .= Html
::element( 'span',
3209 array( 'class' => 'mw-editButtons-pipe-separator' ),
3210 wfMessage( 'pipe-separator' )->text() );
3213 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3214 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3215 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
3216 wfMessage( 'edithelp' )->escaped() . '</a> ' .
3217 wfMessage( 'newwindow' )->parse();
3219 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3220 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3221 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3223 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3225 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3229 * Show an edit conflict. textbox1 is already shown in showEditForm().
3230 * If you want to use another entry point to this function, be careful.
3232 protected function showConflict() {
3235 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3236 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3238 $content1 = $this->toEditContent( $this->textbox1
);
3239 $content2 = $this->toEditContent( $this->textbox2
);
3241 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3242 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3243 $de->setContent( $content2, $content1 );
3245 wfMessage( 'yourtext' )->parse(),
3246 wfMessage( 'storedversion' )->text()
3249 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3250 $this->showTextbox2();
3257 public function getCancelLink() {
3258 $cancelParams = array();
3259 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3260 $cancelParams['oldid'] = $this->oldid
;
3263 return Linker
::linkKnown(
3264 $this->getContextTitle(),
3265 wfMessage( 'cancel' )->parse(),
3266 array( 'id' => 'mw-editform-cancel' ),
3272 * Returns the URL to use in the form's action attribute.
3273 * This is used by EditPage subclasses when simply customizing the action
3274 * variable in the constructor is not enough. This can be used when the
3275 * EditPage lives inside of a Special page rather than a custom page action.
3277 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3280 protected function getActionURL( Title
$title ) {
3281 return $title->getLocalURL( array( 'action' => $this->action
) );
3285 * Check if a page was deleted while the user was editing it, before submit.
3286 * Note that we rely on the logging table, which hasn't been always there,
3287 * but that doesn't matter, because this only applies to brand new
3291 protected function wasDeletedSinceLastEdit() {
3292 if ( $this->deletedSinceEdit
!== null ) {
3293 return $this->deletedSinceEdit
;
3296 $this->deletedSinceEdit
= false;
3298 if ( $this->mTitle
->isDeletedQuick() ) {
3299 $this->lastDelete
= $this->getLastDelete();
3300 if ( $this->lastDelete
) {
3301 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3302 if ( $deleteTime > $this->starttime
) {
3303 $this->deletedSinceEdit
= true;
3308 return $this->deletedSinceEdit
;
3312 * @return bool|stdClass
3314 protected function getLastDelete() {
3315 $dbr = wfGetDB( DB_SLAVE
);
3316 $data = $dbr->selectRow(
3317 array( 'logging', 'user' ),
3330 'log_namespace' => $this->mTitle
->getNamespace(),
3331 'log_title' => $this->mTitle
->getDBkey(),
3332 'log_type' => 'delete',
3333 'log_action' => 'delete',
3337 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3339 // Quick paranoid permission checks...
3340 if ( is_object( $data ) ) {
3341 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3342 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
3345 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3346 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
3354 * Get the rendered text for previewing.
3355 * @throws MWException
3358 function getPreviewText() {
3359 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3360 global $wgAllowUserCss, $wgAllowUserJs;
3362 wfProfileIn( __METHOD__
);
3364 if ( $wgRawHtml && !$this->mTokenOk
) {
3365 // Could be an offsite preview attempt. This is very unsafe if
3366 // HTML is enabled, as it could be an attack.
3368 if ( $this->textbox1
!== '' ) {
3369 // Do not put big scary notice, if previewing the empty
3370 // string, which happens when you initially edit
3371 // a category page, due to automatic preview-on-open.
3372 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3373 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3375 wfProfileOut( __METHOD__
);
3382 $content = $this->toEditContent( $this->textbox1
);
3386 'AlternateEditPreview',
3387 array( $this, &$content, &$previewHTML, &$this->mParserOutput
) )
3389 wfProfileOut( __METHOD__
);
3390 return $previewHTML;
3393 # provide a anchor link to the editform
3394 $continueEditing = '<span class="mw-continue-editing">' .
3395 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3396 wfMessage( 'continue-editing' )->text() . ']]</span>';
3397 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3398 if ( $this->mTokenOkExceptSuffix
) {
3399 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3401 $note = wfMessage( 'session_fail_preview' )->plain();
3403 } elseif ( $this->incompleteForm
) {
3404 $note = wfMessage( 'edit_form_incomplete' )->plain();
3406 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3409 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
3410 $parserOptions->setEditSection( false );
3411 $parserOptions->setIsPreview( true );
3412 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3414 # don't parse non-wikitext pages, show message about preview
3415 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3416 if ( $this->mTitle
->isCssJsSubpage() ) {
3418 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3424 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3426 if ( $level === 'user' && !$wgAllowUserCss ) {
3429 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3431 if ( $level === 'user' && !$wgAllowUserJs ) {
3438 # Used messages to make sure grep find them:
3439 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3440 if ( $level && $format ) {
3441 $note = "<div id='mw-{$level}{$format}preview'>" .
3442 wfMessage( "{$level}{$format}preview" )->text() .
3443 ' ' . $continueEditing . "</div>";
3447 # If we're adding a comment, we need to show the
3448 # summary as the headline
3449 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3450 $content = $content->addSectionHeader( $this->summary
);
3453 $hook_args = array( $this, &$content );
3454 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3455 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3457 $parserOptions->enableLimitReport();
3459 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3460 # But it's now deprecated, so never mind
3462 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3463 $parserOutput = $content->getParserOutput(
3464 $this->getArticle()->getTitle(),
3469 $previewHTML = $parserOutput->getText();
3470 $this->mParserOutput
= $parserOutput;
3471 $wgOut->addParserOutputMetadata( $parserOutput );
3473 if ( count( $parserOutput->getWarnings() ) ) {
3474 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3476 } catch ( MWContentSerializationException
$ex ) {
3478 'content-failed-to-parse',
3479 $this->contentModel
,
3480 $this->contentFormat
,
3483 $note .= "\n\n" . $m->parse();
3487 if ( $this->isConflict
) {
3488 $conflict = '<h2 id="mw-previewconflict">'
3489 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3491 $conflict = '<hr />';
3494 $previewhead = "<div class='previewnote'>\n" .
3495 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3496 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3498 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3499 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3500 'class' => 'mw-content-' . $pageViewLang->getDir() );
3501 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3503 wfProfileOut( __METHOD__
);
3504 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3510 function getTemplates() {
3511 if ( $this->preview ||
$this->section
!= '' ) {
3512 $templates = array();
3513 if ( !isset( $this->mParserOutput
) ) {
3516 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3517 foreach ( array_keys( $template ) as $dbk ) {
3518 $templates[] = Title
::makeTitle( $ns, $dbk );
3523 return $this->mTitle
->getTemplateLinksFrom();
3528 * Shows a bulletin board style toolbar for common editing functions.
3529 * It can be disabled in the user preferences.
3533 static function getEditToolbar() {
3534 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3535 global $wgEnableUploads, $wgForeignFileRepos;
3537 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3540 * $toolarray is an array of arrays each of which includes the
3541 * filename of the button image (without path), the opening
3542 * tag, the closing tag, optionally a sample text that is
3543 * inserted between the two when no selection is highlighted
3544 * and. The tip text is shown when the user moves the mouse
3547 * Also here: accesskeys (key), which are not used yet until
3548 * someone can figure out a way to make them work in
3549 * IE. However, we should make sure these keys are not defined
3554 'image' => $wgLang->getImageFile( 'button-bold' ),
3555 'id' => 'mw-editbutton-bold',
3557 'close' => '\'\'\'',
3558 'sample' => wfMessage( 'bold_sample' )->text(),
3559 'tip' => wfMessage( 'bold_tip' )->text(),
3563 'image' => $wgLang->getImageFile( 'button-italic' ),
3564 'id' => 'mw-editbutton-italic',
3567 'sample' => wfMessage( 'italic_sample' )->text(),
3568 'tip' => wfMessage( 'italic_tip' )->text(),
3572 'image' => $wgLang->getImageFile( 'button-link' ),
3573 'id' => 'mw-editbutton-link',
3576 'sample' => wfMessage( 'link_sample' )->text(),
3577 'tip' => wfMessage( 'link_tip' )->text(),
3581 'image' => $wgLang->getImageFile( 'button-extlink' ),
3582 'id' => 'mw-editbutton-extlink',
3585 'sample' => wfMessage( 'extlink_sample' )->text(),
3586 'tip' => wfMessage( 'extlink_tip' )->text(),
3590 'image' => $wgLang->getImageFile( 'button-headline' ),
3591 'id' => 'mw-editbutton-headline',
3594 'sample' => wfMessage( 'headline_sample' )->text(),
3595 'tip' => wfMessage( 'headline_tip' )->text(),
3598 $imagesAvailable ?
array(
3599 'image' => $wgLang->getImageFile( 'button-image' ),
3600 'id' => 'mw-editbutton-image',
3601 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3603 'sample' => wfMessage( 'image_sample' )->text(),
3604 'tip' => wfMessage( 'image_tip' )->text(),
3607 $imagesAvailable ?
array(
3608 'image' => $wgLang->getImageFile( 'button-media' ),
3609 'id' => 'mw-editbutton-media',
3610 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3612 'sample' => wfMessage( 'media_sample' )->text(),
3613 'tip' => wfMessage( 'media_tip' )->text(),
3617 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3618 'id' => 'mw-editbutton-nowiki',
3619 'open' => "<nowiki>",
3620 'close' => "</nowiki>",
3621 'sample' => wfMessage( 'nowiki_sample' )->text(),
3622 'tip' => wfMessage( 'nowiki_tip' )->text(),
3626 'image' => $wgLang->getImageFile( 'button-sig' ),
3627 'id' => 'mw-editbutton-signature',
3631 'tip' => wfMessage( 'sig_tip' )->text(),
3635 'image' => $wgLang->getImageFile( 'button-hr' ),
3636 'id' => 'mw-editbutton-hr',
3637 'open' => "\n----\n",
3640 'tip' => wfMessage( 'hr_tip' )->text(),
3645 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3646 foreach ( $toolarray as $tool ) {
3652 $wgStylePath . '/common/images/' . $tool['image'],
3653 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3654 // Older browsers show a "speedtip" type message only for ALT.
3655 // Ideally these should be different, realistically they
3656 // probably don't need to be.
3664 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3667 // This used to be called on DOMReady from mediawiki.action.edit, which
3668 // ended up causing race conditions with the setup code above.
3670 "// Create button bar\n" .
3671 "$(function() { mw.toolbar.init(); } );\n";
3674 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3676 $toolbar = '<div id="toolbar"></div>';
3678 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3684 * Returns an array of html code of the following checkboxes:
3687 * @param int $tabindex Current tabindex
3688 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3689 * status of the checkbox
3693 public function getCheckboxes( &$tabindex, $checked ) {
3696 $checkboxes = array();
3698 // don't show the minor edit checkbox if it's a new page or section
3699 if ( !$this->isNew
) {
3700 $checkboxes['minor'] = '';
3701 $minorLabel = wfMessage( 'minoredit' )->parse();
3702 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3704 'tabindex' => ++
$tabindex,
3705 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3706 'id' => 'wpMinoredit',
3708 $checkboxes['minor'] =
3709 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3710 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3711 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3712 ">{$minorLabel}</label>";
3716 $watchLabel = wfMessage( 'watchthis' )->parse();
3717 $checkboxes['watch'] = '';
3718 if ( $wgUser->isLoggedIn() ) {
3720 'tabindex' => ++
$tabindex,
3721 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3722 'id' => 'wpWatchthis',
3724 $checkboxes['watch'] =
3725 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3726 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3727 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3728 ">{$watchLabel}</label>";
3730 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3735 * Returns an array of html code of the following buttons:
3736 * save, diff, preview and live
3738 * @param int $tabindex Current tabindex
3742 public function getEditButtons( &$tabindex ) {
3749 'tabindex' => ++
$tabindex,
3750 'value' => wfMessage( 'savearticle' )->text(),
3751 ) + Linker
::tooltipAndAccesskeyAttribs( 'save' );
3752 $buttons['save'] = Xml
::element( 'input', $attribs, '' );
3754 ++
$tabindex; // use the same for preview and live preview
3756 'id' => 'wpPreview',
3757 'name' => 'wpPreview',
3759 'tabindex' => $tabindex,
3760 'value' => wfMessage( 'showpreview' )->text(),
3761 ) + Linker
::tooltipAndAccesskeyAttribs( 'preview' );
3762 $buttons['preview'] = Xml
::element( 'input', $attribs, '' );
3763 $buttons['live'] = '';
3769 'tabindex' => ++
$tabindex,
3770 'value' => wfMessage( 'showdiff' )->text(),
3771 ) + Linker
::tooltipAndAccesskeyAttribs( 'diff' );
3772 $buttons['diff'] = Xml
::element( 'input', $attribs, '' );
3774 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3779 * Output preview text only. This can be sucked into the edit page
3780 * via JavaScript, and saves the server time rendering the skin as
3781 * well as theoretically being more robust on the client (doesn't
3782 * disturb the edit box's undo history, won't eat your text on
3785 * @todo This doesn't include category or interlanguage links.
3786 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3787 * or something...</s>" that might also require more skin
3788 * initialization, so check whether that's a problem.
3790 function livePreview() {
3793 header( 'Content-type: text/xml; charset=utf-8' );
3794 header( 'Cache-control: no-cache' );
3796 $previewText = $this->getPreviewText();
3797 #$categories = $skin->getCategoryLinks();
3800 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3801 Xml
::tags( 'livepreview', null,
3802 Xml
::element( 'preview', null, $previewText )
3803 #. Xml::element( 'category', null, $categories )
3809 * Creates a basic error page which informs the user that
3810 * they have attempted to edit a nonexistent section.
3812 function noSuchSectionPage() {
3815 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3817 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3818 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3819 $wgOut->addHTML( $res );
3821 $wgOut->returnToMain( false, $this->mTitle
);
3825 * Show "your edit contains spam" page with your diff and text
3827 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3829 public function spamPageWithContent( $match = false ) {
3830 global $wgOut, $wgLang;
3831 $this->textbox2
= $this->textbox1
;
3833 if ( is_array( $match ) ) {
3834 $match = $wgLang->listToText( $match );
3836 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3838 $wgOut->addHTML( '<div id="spamprotected">' );
3839 $wgOut->addWikiMsg( 'spamprotectiontext' );
3841 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3843 $wgOut->addHTML( '</div>' );
3845 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3848 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3849 $this->showTextbox2();
3851 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3855 * Check if the browser is on a blacklist of user-agents known to
3856 * mangle UTF-8 data on form submission. Returns true if Unicode
3857 * should make it through, false if it's known to be a problem.
3860 private function checkUnicodeCompliantBrowser() {
3861 global $wgBrowserBlackList, $wgRequest;
3863 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3864 if ( $currentbrowser === false ) {
3865 // No User-Agent header sent? Trust it by default...
3869 foreach ( $wgBrowserBlackList as $browser ) {
3870 if ( preg_match( $browser, $currentbrowser ) ) {
3878 * Filter an input field through a Unicode de-armoring process if it
3879 * came from an old browser with known broken Unicode editing issues.
3881 * @param WebRequest $request
3882 * @param string $field
3885 protected function safeUnicodeInput( $request, $field ) {
3886 $text = rtrim( $request->getText( $field ) );
3887 return $request->getBool( 'safemode' )
3888 ?
$this->unmakeSafe( $text )
3893 * Filter an output field through a Unicode armoring process if it is
3894 * going to an old browser with known broken Unicode editing issues.
3896 * @param string $text
3899 protected function safeUnicodeOutput( $text ) {
3901 $codedText = $wgContLang->recodeForEdit( $text );
3902 return $this->checkUnicodeCompliantBrowser()
3904 : $this->makeSafe( $codedText );
3908 * A number of web browsers are known to corrupt non-ASCII characters
3909 * in a UTF-8 text editing environment. To protect against this,
3910 * detected browsers will be served an armored version of the text,
3911 * with non-ASCII chars converted to numeric HTML character references.
3913 * Preexisting such character references will have a 0 added to them
3914 * to ensure that round-trips do not alter the original data.
3916 * @param string $invalue
3919 private function makeSafe( $invalue ) {
3920 // Armor existing references for reversibility.
3921 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3926 $valueLength = strlen( $invalue );
3927 for ( $i = 0; $i < $valueLength; $i++
) {
3928 $bytevalue = ord( $invalue[$i] );
3929 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3930 $result .= chr( $bytevalue );
3932 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3933 $working = $working << 6;
3934 $working +
= ( $bytevalue & 0x3F );
3936 if ( $bytesleft <= 0 ) {
3937 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3939 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3940 $working = $bytevalue & 0x1F;
3942 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3943 $working = $bytevalue & 0x0F;
3945 } else { // 1111 0xxx
3946 $working = $bytevalue & 0x07;
3954 * Reverse the previously applied transliteration of non-ASCII characters
3955 * back to UTF-8. Used to protect data from corruption by broken web browsers
3956 * as listed in $wgBrowserBlackList.
3958 * @param string $invalue
3961 private function unmakeSafe( $invalue ) {
3963 $valueLength = strlen( $invalue );
3964 for ( $i = 0; $i < $valueLength; $i++
) {
3965 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3969 $hexstring .= $invalue[$i];
3971 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3973 // Do some sanity checks. These aren't needed for reversibility,
3974 // but should help keep the breakage down if the editor
3975 // breaks one of the entities whilst editing.
3976 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3977 $codepoint = hexdec( $hexstring );
3978 $result .= codepointToUtf8( $codepoint );
3980 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3983 $result .= substr( $invalue, $i, 1 );
3986 // reverse the transform that we made for reversibility reasons.
3987 return strtr( $result, array( "�" => "&#x" ) );