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: user tried to modify the content model, but is not allowed to do that
149 * ( User::isAllowed('editcontentmodel') == false )
151 const AS_NO_CHANGE_CONTENT_MODEL
= 235;
154 * Status: user tried to create self-redirect (redirect to the same article) and
155 * wpIgnoreSelfRedirect == false
157 const AS_SELF_REDIRECT
= 236;
160 * Status: can't parse content
162 const AS_PARSE_ERROR
= 240;
165 * HTML id and name for the beginning of the edit form.
167 const EDITFORM_ID
= 'editform';
170 * Prefix of key for cookie used to pass post-edit state.
171 * The revision id edited is added after this
173 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
176 * Duration of PostEdit cookie, in seconds.
177 * The cookie will be removed instantly if the JavaScript runs.
179 * Otherwise, though, we don't want the cookies to accumulate.
180 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
181 * limit of only 20 cookies per domain. This still applies at least to some
182 * versions of IE without full updates:
183 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
185 * A value of 20 minutes should be enough to take into account slow loads and minor
186 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
188 const POST_EDIT_COOKIE_DURATION
= 1200;
196 /** @var null|Title */
197 private $mContextTitle = null;
200 public $action = 'submit';
203 public $isConflict = false;
206 public $isCssJsSubpage = false;
209 public $isCssSubpage = false;
212 public $isJsSubpage = false;
215 public $isWrongCaseCssJsPage = false;
217 /** @var bool New page or new section */
218 public $isNew = false;
221 public $deletedSinceEdit;
229 /** @var bool|stdClass */
233 public $mTokenOk = false;
236 public $mTokenOkExceptSuffix = false;
239 public $mTriedSave = false;
242 public $incompleteForm = false;
245 public $tooBig = false;
248 public $kblength = false;
251 public $missingComment = false;
254 public $missingSummary = false;
257 public $allowBlankSummary = false;
260 protected $blankArticle = false;
263 protected $allowBlankArticle = false;
266 protected $selfRedirect = false;
269 protected $allowSelfRedirect = false;
272 public $autoSumm = '';
275 public $hookError = '';
277 /** @var ParserOutput */
278 public $mParserOutput;
280 /** @var bool Has a summary been preset using GET parameter &summary= ? */
281 public $hasPresetSummary = false;
284 public $mBaseRevision = false;
287 public $mShowSummaryField = true;
292 public $save = false;
295 public $preview = false;
298 public $diff = false;
301 public $minoredit = false;
304 public $watchthis = false;
307 public $recreate = false;
310 public $textbox1 = '';
313 public $textbox2 = '';
316 public $summary = '';
319 public $nosummary = false;
322 public $edittime = '';
325 public $section = '';
328 public $sectiontitle = '';
331 public $starttime = '';
337 public $parentRevId = 0;
340 public $editintro = '';
343 public $scrolltop = null;
348 /** @var null|string */
349 public $contentModel = null;
351 /** @var null|string */
352 public $contentFormat = null;
354 # Placeholders for text injection by hooks (must be HTML)
355 # extensions should take care to _append_ to the present value
357 /** @var string Before even the preview */
358 public $editFormPageTop = '';
359 public $editFormTextTop = '';
360 public $editFormTextBeforeContent = '';
361 public $editFormTextAfterWarn = '';
362 public $editFormTextAfterTools = '';
363 public $editFormTextBottom = '';
364 public $editFormTextAfterContent = '';
365 public $previewTextAfterContent = '';
366 public $mPreloadContent = null;
368 /* $didSave should be set to true whenever an article was successfully altered. */
369 public $didSave = false;
370 public $undidRev = 0;
372 public $suppressIntro = false;
374 /** @var bool Set to true to allow editing of non-text content types. */
375 public $allowNonTextContent = false;
384 * @param Article $article
386 public function __construct( Article
$article ) {
387 $this->mArticle
= $article;
388 $this->mTitle
= $article->getTitle();
390 $this->contentModel
= $this->mTitle
->getContentModel();
392 $handler = ContentHandler
::getForModelID( $this->contentModel
);
393 $this->contentFormat
= $handler->getDefaultFormat();
399 public function getArticle() {
400 return $this->mArticle
;
407 public function getTitle() {
408 return $this->mTitle
;
412 * Set the context Title object
414 * @param Title|null $title Title object or null
416 public function setContextTitle( $title ) {
417 $this->mContextTitle
= $title;
421 * Get the context title object.
422 * If not set, $wgTitle will be returned. This behavior might change in
423 * the future to return $this->mTitle instead.
427 public function getContextTitle() {
428 if ( is_null( $this->mContextTitle
) ) {
432 return $this->mContextTitle
;
437 * Returns if the given content model is editable.
439 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
441 * @throws MWException If $modelId has no known handler
443 public function isSupportedContentModel( $modelId ) {
444 return $this->allowNonTextContent ||
445 ContentHandler
::getForModelID( $modelId ) instanceof TextContentHandler
;
453 * This is the function that gets called for "action=edit". It
454 * sets up various member variables, then passes execution to
455 * another function, usually showEditForm()
457 * The edit form is self-submitting, so that when things like
458 * preview and edit conflicts occur, we get the same form back
459 * with the extra stuff added. Only when the final submission
460 * is made and all is well do we actually save and redirect to
461 * the newly-edited page.
464 global $wgOut, $wgRequest, $wgUser;
465 // Allow extensions to modify/prevent this form or submission
466 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
470 wfProfileIn( __METHOD__
);
471 wfDebug( __METHOD__
. ": enter\n" );
473 // If they used redlink=1 and the page exists, redirect to the main article
474 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
475 $wgOut->redirect( $this->mTitle
->getFullURL() );
476 wfProfileOut( __METHOD__
);
480 $this->importFormData( $wgRequest );
481 $this->firsttime
= false;
484 $this->livePreview();
485 wfProfileOut( __METHOD__
);
489 if ( wfReadOnly() && $this->save
) {
492 $this->preview
= true;
496 $this->formtype
= 'save';
497 } elseif ( $this->preview
) {
498 $this->formtype
= 'preview';
499 } elseif ( $this->diff
) {
500 $this->formtype
= 'diff';
501 } else { # First time through
502 $this->firsttime
= true;
503 if ( $this->previewOnOpen() ) {
504 $this->formtype
= 'preview';
506 $this->formtype
= 'initial';
510 $permErrors = $this->getEditPermissionErrors();
512 wfDebug( __METHOD__
. ": User can't edit\n" );
513 // Auto-block user's IP if the account was "hard" blocked
514 $wgUser->spreadAnyEditBlock();
516 $this->displayPermissionsError( $permErrors );
518 wfProfileOut( __METHOD__
);
522 wfProfileIn( __METHOD__
. "-business-end" );
524 $this->isConflict
= false;
525 // css / js subpages of user pages get a special treatment
526 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
527 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
528 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
529 // @todo FIXME: Silly assignment.
530 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
532 # Show applicable editing introductions
533 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
537 # Attempt submission here. This will check for edit conflicts,
538 # and redundantly check for locked database, blocked IPs, etc.
539 # that edit() already checked just in case someone tries to sneak
540 # in the back door with a hand-edited submission URL.
542 if ( 'save' == $this->formtype
) {
543 if ( !$this->attemptSave() ) {
544 wfProfileOut( __METHOD__
. "-business-end" );
545 wfProfileOut( __METHOD__
);
550 # First time through: get contents, set time for conflict
552 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
553 if ( $this->initialiseForm() === false ) {
554 $this->noSuchSectionPage();
555 wfProfileOut( __METHOD__
. "-business-end" );
556 wfProfileOut( __METHOD__
);
560 if ( !$this->mTitle
->getArticleID() ) {
561 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
563 wfRunHooks( 'EditFormInitialText', array( $this ) );
568 $this->showEditForm();
569 wfProfileOut( __METHOD__
. "-business-end" );
570 wfProfileOut( __METHOD__
);
576 protected function getEditPermissionErrors() {
578 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
579 # Can this title be created?
580 if ( !$this->mTitle
->exists() ) {
581 $permErrors = array_merge( $permErrors,
582 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
584 # Ignore some permissions errors when a user is just previewing/viewing diffs
586 foreach ( $permErrors as $error ) {
587 if ( ( $this->preview ||
$this->diff
)
588 && ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' )
593 $permErrors = wfArrayDiff2( $permErrors, $remove );
598 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
599 * but with the following differences:
600 * - If redlink=1, the user will be redirected to the page
601 * - If there is content to display or the error occurs while either saving,
602 * previewing or showing the difference, it will be a
603 * "View source for ..." page displaying the source code after the error message.
606 * @param array $permErrors Array of permissions errors, as returned by
607 * Title::getUserPermissionsErrors().
608 * @throws PermissionsError
610 protected function displayPermissionsError( array $permErrors ) {
611 global $wgRequest, $wgOut;
613 if ( $wgRequest->getBool( 'redlink' ) ) {
614 // The edit page was reached via a red link.
615 // Redirect to the article page and let them click the edit tab if
616 // they really want a permission error.
617 $wgOut->redirect( $this->mTitle
->getFullURL() );
621 $content = $this->getContentObject();
623 # Use the normal message if there's nothing to display
624 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
625 $action = $this->mTitle
->exists() ?
'edit' :
626 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
627 throw new PermissionsError( $action, $permErrors );
630 wfRunHooks( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
632 $wgOut->setRobotPolicy( 'noindex,nofollow' );
633 $wgOut->setPageTitle( wfMessage(
635 $this->getContextTitle()->getPrefixedText()
637 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
638 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
639 $wgOut->addHTML( "<hr />\n" );
641 # If the user made changes, preserve them when showing the markup
642 # (This happens when a user is blocked during edit, for instance)
643 if ( !$this->firsttime
) {
644 $text = $this->textbox1
;
645 $wgOut->addWikiMsg( 'viewyourtext' );
647 $text = $this->toEditText( $content );
648 $wgOut->addWikiMsg( 'viewsourcetext' );
651 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
653 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
654 Linker
::formatTemplates( $this->getTemplates() ) ) );
656 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
658 if ( $this->mTitle
->exists() ) {
659 $wgOut->returnToMain( null, $this->mTitle
);
664 * Should we show a preview when the edit form is first shown?
668 protected function previewOnOpen() {
669 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
670 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
671 // Explicit override from request
673 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
674 // Explicit override from request
676 } elseif ( $this->section
== 'new' ) {
677 // Nothing *to* preview for new sections
679 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
680 && $wgUser->getOption( 'previewonfirst' )
682 // Standard preference behavior
684 } elseif ( !$this->mTitle
->exists()
685 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
686 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
688 // Categories are special
696 * Checks whether the user entered a skin name in uppercase,
697 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
701 protected function isWrongCaseCssJsPage() {
702 if ( $this->mTitle
->isCssJsSubpage() ) {
703 $name = $this->mTitle
->getSkinFromCssJsSubpage();
704 $skins = array_merge(
705 array_keys( Skin
::getSkinNames() ),
708 return !in_array( $name, $skins )
709 && in_array( strtolower( $name ), $skins );
716 * Returns whether section editing is supported for the current page.
717 * Subclasses may override this to replace the default behavior, which is
718 * to check ContentHandler::supportsSections.
720 * @return bool True if this edit page supports sections, false otherwise.
722 protected function isSectionEditSupported() {
723 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
724 return $contentHandler->supportsSections();
728 * This function collects the form data and uses it to populate various member variables.
729 * @param WebRequest $request
730 * @throws ErrorPageError
732 function importFormData( &$request ) {
733 global $wgContLang, $wgUser;
735 wfProfileIn( __METHOD__
);
737 # Section edit can come from either the form or a link
738 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
740 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
741 wfProfileOut( __METHOD__
);
742 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
745 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
747 if ( $request->wasPosted() ) {
748 # These fields need to be checked for encoding.
749 # Also remove trailing whitespace, but don't remove _initial_
750 # whitespace from the text boxes. This may be significant formatting.
751 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
752 if ( !$request->getCheck( 'wpTextbox2' ) ) {
753 // Skip this if wpTextbox2 has input, it indicates that we came
754 // from a conflict page with raw page text, not a custom form
755 // modified by subclasses
756 wfProfileIn( get_class( $this ) . "::importContentFormData" );
757 $textbox1 = $this->importContentFormData( $request );
758 if ( $textbox1 !== null ) {
759 $this->textbox1
= $textbox1;
762 wfProfileOut( get_class( $this ) . "::importContentFormData" );
765 # Truncate for whole multibyte characters
766 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
768 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
769 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
771 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
773 # Treat sectiontitle the same way as summary.
774 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
775 # currently doing double duty as both edit summary and section title. Right now this
776 # is just to allow API edits to work around this limitation, but this should be
777 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
778 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
779 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
781 $this->edittime
= $request->getVal( 'wpEdittime' );
782 $this->starttime
= $request->getVal( 'wpStarttime' );
784 $undidRev = $request->getInt( 'wpUndidRevision' );
786 $this->undidRev
= $undidRev;
789 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
791 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
792 // wpTextbox1 field is missing, possibly due to being "too big"
793 // according to some filter rules such as Suhosin's setting for
794 // suhosin.request.max_value_length (d'oh)
795 $this->incompleteForm
= true;
797 // If we receive the last parameter of the request, we can fairly
798 // claim the POST request has not been truncated.
800 // TODO: softened the check for cutover. Once we determine
801 // that it is safe, we should complete the transition by
802 // removing the "edittime" clause.
803 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
804 && is_null( $this->edittime
) );
806 if ( $this->incompleteForm
) {
807 # If the form is incomplete, force to preview.
808 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
809 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
810 $this->preview
= true;
812 /* Fallback for live preview */
813 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
814 $this->diff
= $request->getCheck( 'wpDiff' );
816 // Remember whether a save was requested, so we can indicate
817 // if we forced preview due to session failure.
818 $this->mTriedSave
= !$this->preview
;
820 if ( $this->tokenOk( $request ) ) {
821 # Some browsers will not report any submit button
822 # if the user hits enter in the comment box.
823 # The unmarked state will be assumed to be a save,
824 # if the form seems otherwise complete.
825 wfDebug( __METHOD__
. ": Passed token check.\n" );
826 } elseif ( $this->diff
) {
827 # Failed token check, but only requested "Show Changes".
828 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
830 # Page might be a hack attempt posted from
831 # an external site. Preview instead of saving.
832 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
833 $this->preview
= true;
836 $this->save
= !$this->preview
&& !$this->diff
;
837 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
838 $this->edittime
= null;
841 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
842 $this->starttime
= null;
845 $this->recreate
= $request->getCheck( 'wpRecreate' );
847 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
848 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
850 # Don't force edit summaries when a user is editing their own user or talk page
851 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
852 && $this->mTitle
->getText() == $wgUser->getName()
854 $this->allowBlankSummary
= true;
856 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
857 ||
!$wgUser->getOption( 'forceeditsummary' );
860 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
862 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
863 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
865 # Not a posted form? Start with nothing.
866 wfDebug( __METHOD__
. ": Not a posted form.\n" );
867 $this->textbox1
= '';
869 $this->sectiontitle
= '';
870 $this->edittime
= '';
871 $this->starttime
= wfTimestampNow();
873 $this->preview
= false;
876 $this->minoredit
= false;
877 // Watch may be overridden by request parameters
878 $this->watchthis
= $request->getBool( 'watchthis', false );
879 $this->recreate
= false;
881 // When creating a new section, we can preload a section title by passing it as the
882 // preloadtitle parameter in the URL (Bug 13100)
883 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
884 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
885 // Once wpSummary isn't being use for setting section titles, we should delete this.
886 $this->summary
= $request->getVal( 'preloadtitle' );
887 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
888 $this->summary
= $request->getText( 'summary' );
889 if ( $this->summary
!== '' ) {
890 $this->hasPresetSummary
= true;
894 if ( $request->getVal( 'minor' ) ) {
895 $this->minoredit
= true;
899 $this->oldid
= $request->getInt( 'oldid' );
900 $this->parentRevId
= $request->getInt( 'parentRevId' );
902 $this->bot
= $request->getBool( 'bot', true );
903 $this->nosummary
= $request->getBool( 'nosummary' );
905 // May be overridden by revision.
906 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
907 // May be overridden by revision.
908 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
910 if ( !ContentHandler
::getForModelID( $this->contentModel
)
911 ->isSupportedFormat( $this->contentFormat
)
913 throw new ErrorPageError(
914 'editpage-notsupportedcontentformat-title',
915 'editpage-notsupportedcontentformat-text',
916 array( $this->contentFormat
, ContentHandler
::getLocalizedName( $this->contentModel
) )
921 * @todo Check if the desired model is allowed in this namespace, and if
922 * a transition from the page's current model to the new model is
926 $this->live
= $request->getCheck( 'live' );
927 $this->editintro
= $request->getText( 'editintro',
928 // Custom edit intro for new sections
929 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
931 // Allow extensions to modify form data
932 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
934 wfProfileOut( __METHOD__
);
938 * Subpage overridable method for extracting the page content data from the
939 * posted form to be placed in $this->textbox1, if using customized input
940 * this method should be overridden and return the page text that will be used
941 * for saving, preview parsing and so on...
943 * @param WebRequest $request
945 protected function importContentFormData( &$request ) {
946 return; // Don't do anything, EditPage already extracted wpTextbox1
950 * Initialise form fields in the object
951 * Called on the first invocation, e.g. when a user clicks an edit link
952 * @return bool If the requested section is valid
954 function initialiseForm() {
956 $this->edittime
= $this->mArticle
->getTimestamp();
958 $content = $this->getContentObject( false ); #TODO: track content object?!
959 if ( $content === false ) {
962 $this->textbox1
= $this->toEditText( $content );
964 // activate checkboxes if user wants them to be always active
965 # Sort out the "watch" checkbox
966 if ( $wgUser->getOption( 'watchdefault' ) ) {
968 $this->watchthis
= true;
969 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
971 $this->watchthis
= true;
972 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
974 $this->watchthis
= true;
976 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
977 $this->minoredit
= true;
979 if ( $this->textbox1
=== false ) {
986 * @param Content|null $def_content The default value to return
988 * @return Content|null Content on success, $def_content for invalid sections
992 protected function getContentObject( $def_content = null ) {
993 global $wgOut, $wgRequest, $wgUser, $wgContLang;
995 wfProfileIn( __METHOD__
);
999 // For message page not locally set, use the i18n message.
1000 // For other non-existent articles, use preload text if any.
1001 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1002 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1003 # If this is a system message, get the default text.
1004 $msg = $this->mTitle
->getDefaultMessageText();
1006 $content = $this->toEditContent( $msg );
1008 if ( $content === false ) {
1009 # If requested, preload some text.
1010 $preload = $wgRequest->getVal( 'preload',
1011 // Custom preload text for new sections
1012 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1013 $params = $wgRequest->getArray( 'preloadparams', array() );
1015 $content = $this->getPreloadedContent( $preload, $params );
1017 // For existing pages, get text based on "undo" or section parameters.
1019 if ( $this->section
!= '' ) {
1020 // Get section edit text (returns $def_text for invalid sections)
1021 $orig = $this->getOriginalContent( $wgUser );
1022 $content = $orig ?
$orig->getSection( $this->section
) : null;
1025 $content = $def_content;
1028 $undoafter = $wgRequest->getInt( 'undoafter' );
1029 $undo = $wgRequest->getInt( 'undo' );
1031 if ( $undo > 0 && $undoafter > 0 ) {
1033 $undorev = Revision
::newFromId( $undo );
1034 $oldrev = Revision
::newFromId( $undoafter );
1036 # Sanity check, make sure it's the right page,
1037 # the revisions exist and they were not deleted.
1038 # Otherwise, $content will be left as-is.
1039 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1040 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1041 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
1043 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
1045 if ( $content === false ) {
1046 # Warn the user that something went wrong
1047 $undoMsg = 'failure';
1049 $oldContent = $this->mArticle
->getPage()->getContent( Revision
::RAW
);
1050 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
1051 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
1053 if ( $newContent->equals( $oldContent ) ) {
1054 # Tell the user that the undo results in no change,
1055 # i.e. the revisions were already undone.
1056 $undoMsg = 'nochange';
1059 # Inform the user of our success and set an automatic edit summary
1060 $undoMsg = 'success';
1062 # If we just undid one rev, use an autosummary
1063 $firstrev = $oldrev->getNext();
1064 if ( $firstrev && $firstrev->getId() == $undo ) {
1065 $userText = $undorev->getUserText();
1066 if ( $userText === '' ) {
1067 $undoSummary = wfMessage(
1068 'undo-summary-username-hidden',
1070 )->inContentLanguage()->text();
1072 $undoSummary = wfMessage(
1076 )->inContentLanguage()->text();
1078 if ( $this->summary
=== '' ) {
1079 $this->summary
= $undoSummary;
1081 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
1082 ->inContentLanguage()->text() . $this->summary
;
1084 $this->undidRev
= $undo;
1086 $this->formtype
= 'diff';
1090 // Failed basic sanity checks.
1091 // Older revisions may have been removed since the link
1092 // was created, or we may simply have got bogus input.
1096 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1097 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1098 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
1099 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1102 if ( $content === false ) {
1103 $content = $this->getOriginalContent( $wgUser );
1108 wfProfileOut( __METHOD__
);
1113 * Get the content of the wanted revision, without section extraction.
1115 * The result of this function can be used to compare user's input with
1116 * section replaced in its context (using WikiPage::replaceSection())
1117 * to the original text of the edit.
1119 * This differs from Article::getContent() that when a missing revision is
1120 * encountered the result will be null and not the
1121 * 'missing-revision' message.
1124 * @param User $user The user to get the revision for
1125 * @return Content|null
1127 private function getOriginalContent( User
$user ) {
1128 if ( $this->section
== 'new' ) {
1129 return $this->getCurrentContent();
1131 $revision = $this->mArticle
->getRevisionFetched();
1132 if ( $revision === null ) {
1133 if ( !$this->contentModel
) {
1134 $this->contentModel
= $this->getTitle()->getContentModel();
1136 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1138 return $handler->makeEmptyContent();
1140 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1145 * Get the current content of the page. This is basically similar to
1146 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1147 * content object is returned instead of null.
1152 protected function getCurrentContent() {
1153 $rev = $this->mArticle
->getRevision();
1154 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1156 if ( $content === false ||
$content === null ) {
1157 if ( !$this->contentModel
) {
1158 $this->contentModel
= $this->getTitle()->getContentModel();
1160 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1162 return $handler->makeEmptyContent();
1164 # nasty side-effect, but needed for consistency
1165 $this->contentModel
= $rev->getContentModel();
1166 $this->contentFormat
= $rev->getContentFormat();
1173 * Use this method before edit() to preload some content into the edit box
1175 * @param Content $content
1179 public function setPreloadedContent( Content
$content ) {
1180 $this->mPreloadContent
= $content;
1184 * Get the contents to be preloaded into the box, either set by
1185 * an earlier setPreloadText() or by loading the given page.
1187 * @param string $preload Representing the title to preload from.
1188 * @param array $params Parameters to use (interface-message style) in the preloaded text
1194 protected function getPreloadedContent( $preload, $params = array() ) {
1197 if ( !empty( $this->mPreloadContent
) ) {
1198 return $this->mPreloadContent
;
1201 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1203 if ( $preload === '' ) {
1204 return $handler->makeEmptyContent();
1207 $title = Title
::newFromText( $preload );
1208 # Check for existence to avoid getting MediaWiki:Noarticletext
1209 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1210 //TODO: somehow show a warning to the user!
1211 return $handler->makeEmptyContent();
1214 $page = WikiPage
::factory( $title );
1215 if ( $page->isRedirect() ) {
1216 $title = $page->getRedirectTarget();
1218 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1219 //TODO: somehow show a warning to the user!
1220 return $handler->makeEmptyContent();
1222 $page = WikiPage
::factory( $title );
1225 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1226 $content = $page->getContent( Revision
::RAW
);
1229 //TODO: somehow show a warning to the user!
1230 return $handler->makeEmptyContent();
1233 if ( $content->getModel() !== $handler->getModelID() ) {
1234 $converted = $content->convert( $handler->getModelID() );
1236 if ( !$converted ) {
1237 //TODO: somehow show a warning to the user!
1238 wfDebug( "Attempt to preload incompatible content: "
1239 . "can't convert " . $content->getModel()
1240 . " to " . $handler->getModelID() );
1242 return $handler->makeEmptyContent();
1245 $content = $converted;
1248 return $content->preloadTransform( $title, $parserOptions, $params );
1252 * Make sure the form isn't faking a user's credentials.
1254 * @param WebRequest $request
1258 function tokenOk( &$request ) {
1260 $token = $request->getVal( 'wpEditToken' );
1261 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1262 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1263 return $this->mTokenOk
;
1267 * Sets post-edit cookie indicating the user just saved a particular revision.
1269 * This uses a temporary cookie for each revision ID so separate saves will never
1270 * interfere with each other.
1272 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1273 * the redirect. It must be clearable by JavaScript code, so it must not be
1274 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1277 * If the variable were set on the server, it would be cached, which is unwanted
1278 * since the post-edit state should only apply to the load right after the save.
1280 * @param int $statusValue The status value (to check for new article status)
1282 protected function setPostEditCookie( $statusValue ) {
1283 $revisionId = $this->mArticle
->getLatest();
1284 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1287 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1289 } elseif ( $this->oldid
) {
1293 $response = RequestContext
::getMain()->getRequest()->response();
1294 $response->setcookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
, array(
1295 'httpOnly' => false,
1300 * Attempt submission
1301 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1302 * @return bool False if output is done, true if the rest of the form should be displayed
1304 public function attemptSave() {
1307 $resultDetails = false;
1308 # Allow bots to exempt some edits from bot flagging
1309 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1310 $status = $this->internalAttemptSave( $resultDetails, $bot );
1312 return $this->handleStatus( $status, $resultDetails );
1316 * Handle status, such as after attempt save
1318 * @param Status $status
1319 * @param array|bool $resultDetails
1321 * @throws ErrorPageError
1322 * @return bool False, if output is done, true if rest of the form should be displayed
1324 private function handleStatus( Status
$status, $resultDetails ) {
1325 global $wgUser, $wgOut;
1328 * @todo FIXME: once the interface for internalAttemptSave() is made
1329 * nicer, this should use the message in $status
1331 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1332 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1334 $this->didSave
= true;
1335 if ( !$resultDetails['nullEdit'] ) {
1336 $this->setPostEditCookie( $status->value
);
1340 switch ( $status->value
) {
1341 case self
::AS_HOOK_ERROR_EXPECTED
:
1342 case self
::AS_CONTENT_TOO_BIG
:
1343 case self
::AS_ARTICLE_WAS_DELETED
:
1344 case self
::AS_CONFLICT_DETECTED
:
1345 case self
::AS_SUMMARY_NEEDED
:
1346 case self
::AS_TEXTBOX_EMPTY
:
1347 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1349 case self
::AS_BLANK_ARTICLE
:
1350 case self
::AS_SELF_REDIRECT
:
1353 case self
::AS_HOOK_ERROR
:
1356 case self
::AS_PARSE_ERROR
:
1357 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1360 case self
::AS_SUCCESS_NEW_ARTICLE
:
1361 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1362 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1363 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1366 case self
::AS_SUCCESS_UPDATE
:
1368 $sectionanchor = $resultDetails['sectionanchor'];
1370 // Give extensions a chance to modify URL query on update
1372 'ArticleUpdateBeforeRedirect',
1373 array( $this->mArticle
, &$sectionanchor, &$extraQuery )
1376 if ( $resultDetails['redirect'] ) {
1377 if ( $extraQuery == '' ) {
1378 $extraQuery = 'redirect=no';
1380 $extraQuery = 'redirect=no&' . $extraQuery;
1383 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1386 case self
::AS_SPAM_ERROR
:
1387 $this->spamPageWithContent( $resultDetails['spam'] );
1390 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1391 throw new UserBlockedError( $wgUser->getBlock() );
1393 case self
::AS_IMAGE_REDIRECT_ANON
:
1394 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1395 throw new PermissionsError( 'upload' );
1397 case self
::AS_READ_ONLY_PAGE_ANON
:
1398 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1399 throw new PermissionsError( 'edit' );
1401 case self
::AS_READ_ONLY_PAGE
:
1402 throw new ReadOnlyError
;
1404 case self
::AS_RATE_LIMITED
:
1405 throw new ThrottledError();
1407 case self
::AS_NO_CREATE_PERMISSION
:
1408 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1409 throw new PermissionsError( $permission );
1411 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1412 throw new PermissionsError( 'editcontentmodel' );
1415 // We don't recognize $status->value. The only way that can happen
1416 // is if an extension hook aborted from inside ArticleSave.
1417 // Render the status object into $this->hookError
1418 // FIXME this sucks, we should just use the Status object throughout
1419 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1426 * Run hooks that can filter edits just before they get saved.
1428 * @param Content $content The Content to filter.
1429 * @param Status $status For reporting the outcome to the caller
1430 * @param User $user The user performing the edit
1434 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1435 // Run old style post-section-merge edit filter
1436 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1437 array( $this, $content, &$this->hookError
, $this->summary
) ) ) {
1439 # Error messages etc. could be handled within the hook...
1440 $status->fatal( 'hookaborted' );
1441 $status->value
= self
::AS_HOOK_ERROR
;
1443 } elseif ( $this->hookError
!= '' ) {
1444 # ...or the hook could be expecting us to produce an error
1445 $status->fatal( 'hookaborted' );
1446 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1450 // Run new style post-section-merge edit filter
1451 if ( !wfRunHooks( 'EditFilterMergedContent',
1452 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1453 $user, $this->minoredit
) ) ) {
1455 # Error messages etc. could be handled within the hook...
1456 // XXX: $status->value may already be something informative...
1457 $this->hookError
= $status->getWikiText();
1458 $status->fatal( 'hookaborted' );
1459 $status->value
= self
::AS_HOOK_ERROR
;
1461 } elseif ( !$status->isOK() ) {
1462 # ...or the hook could be expecting us to produce an error
1463 // FIXME this sucks, we should just use the Status object throughout
1464 $this->hookError
= $status->getWikiText();
1465 $status->fatal( 'hookaborted' );
1466 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1474 * Return the summary to be used for a new section.
1476 * @param string $sectionanchor Set to the section anchor text
1479 private function newSectionSummary( &$sectionanchor = null ) {
1482 if ( $this->sectiontitle
!== '' ) {
1483 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1484 // If no edit summary was specified, create one automatically from the section
1485 // title and have it link to the new section. Otherwise, respect the summary as
1487 if ( $this->summary
=== '' ) {
1488 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1489 return wfMessage( 'newsectionsummary' )
1490 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1492 } elseif ( $this->summary
!== '' ) {
1493 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1494 # This is a new section, so create a link to the new section
1495 # in the revision summary.
1496 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1497 return wfMessage( 'newsectionsummary' )
1498 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1500 return $this->summary
;
1504 * Attempt submission (no UI)
1506 * @param array $result Array to add statuses to, currently with the
1508 * - spam (string): Spam string from content if any spam is detected by
1510 * - sectionanchor (string): Section anchor for a section save.
1511 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1513 * - redirect (bool): Set if doEditContent is OK. True if resulting
1514 * revision is a redirect.
1515 * @param bool $bot True if edit is being made under the bot right.
1517 * @return Status Status object, possibly with a message, but always with
1518 * one of the AS_* constants in $status->value,
1520 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1521 * various error display idiosyncrasies. There are also lots of cases
1522 * where error metadata is set in the object and retrieved later instead
1523 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1524 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1527 function internalAttemptSave( &$result, $bot = false ) {
1528 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1530 $status = Status
::newGood();
1532 wfProfileIn( __METHOD__
);
1533 wfProfileIn( __METHOD__
. '-checks' );
1535 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1536 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1537 $status->fatal( 'hookaborted' );
1538 $status->value
= self
::AS_HOOK_ERROR
;
1539 wfProfileOut( __METHOD__
. '-checks' );
1540 wfProfileOut( __METHOD__
);
1544 $spam = $wgRequest->getText( 'wpAntispam' );
1545 if ( $spam !== '' ) {
1548 $wgUser->getName() .
1550 $this->mTitle
->getPrefixedText() .
1551 '" submitted bogus field "' .
1555 $status->fatal( 'spamprotectionmatch', false );
1556 $status->value
= self
::AS_SPAM_ERROR
;
1557 wfProfileOut( __METHOD__
. '-checks' );
1558 wfProfileOut( __METHOD__
);
1563 # Construct Content object
1564 $textbox_content = $this->toEditContent( $this->textbox1
);
1565 } catch ( MWContentSerializationException
$ex ) {
1567 'content-failed-to-parse',
1568 $this->contentModel
,
1569 $this->contentFormat
,
1572 $status->value
= self
::AS_PARSE_ERROR
;
1573 wfProfileOut( __METHOD__
. '-checks' );
1574 wfProfileOut( __METHOD__
);
1578 # Check image redirect
1579 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1580 $textbox_content->isRedirect() &&
1581 !$wgUser->isAllowed( 'upload' )
1583 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1584 $status->setResult( false, $code );
1586 wfProfileOut( __METHOD__
. '-checks' );
1587 wfProfileOut( __METHOD__
);
1593 $match = self
::matchSummarySpamRegex( $this->summary
);
1594 if ( $match === false && $this->section
== 'new' ) {
1595 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1596 # regular summaries, it is added to the actual wikitext.
1597 if ( $this->sectiontitle
!== '' ) {
1598 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1599 $match = self
::matchSpamRegex( $this->sectiontitle
);
1601 # This branch is taken when the "Add Topic" user interface is used, or the API
1602 # is used with the 'summary' parameter.
1603 $match = self
::matchSpamRegex( $this->summary
);
1606 if ( $match === false ) {
1607 $match = self
::matchSpamRegex( $this->textbox1
);
1609 if ( $match !== false ) {
1610 $result['spam'] = $match;
1611 $ip = $wgRequest->getIP();
1612 $pdbk = $this->mTitle
->getPrefixedDBkey();
1613 $match = str_replace( "\n", '', $match );
1614 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1615 $status->fatal( 'spamprotectionmatch', $match );
1616 $status->value
= self
::AS_SPAM_ERROR
;
1617 wfProfileOut( __METHOD__
. '-checks' );
1618 wfProfileOut( __METHOD__
);
1623 array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) )
1625 # Error messages etc. could be handled within the hook...
1626 $status->fatal( 'hookaborted' );
1627 $status->value
= self
::AS_HOOK_ERROR
;
1628 wfProfileOut( __METHOD__
. '-checks' );
1629 wfProfileOut( __METHOD__
);
1631 } elseif ( $this->hookError
!= '' ) {
1632 # ...or the hook could be expecting us to produce an error
1633 $status->fatal( 'hookaborted' );
1634 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1635 wfProfileOut( __METHOD__
. '-checks' );
1636 wfProfileOut( __METHOD__
);
1640 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1641 // Auto-block user's IP if the account was "hard" blocked
1642 $wgUser->spreadAnyEditBlock();
1643 # Check block state against master, thus 'false'.
1644 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1645 wfProfileOut( __METHOD__
. '-checks' );
1646 wfProfileOut( __METHOD__
);
1650 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1651 if ( $this->kblength
> $wgMaxArticleSize ) {
1652 // Error will be displayed by showEditForm()
1653 $this->tooBig
= true;
1654 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1655 wfProfileOut( __METHOD__
. '-checks' );
1656 wfProfileOut( __METHOD__
);
1660 if ( !$wgUser->isAllowed( 'edit' ) ) {
1661 if ( $wgUser->isAnon() ) {
1662 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1663 wfProfileOut( __METHOD__
. '-checks' );
1664 wfProfileOut( __METHOD__
);
1667 $status->fatal( 'readonlytext' );
1668 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1669 wfProfileOut( __METHOD__
. '-checks' );
1670 wfProfileOut( __METHOD__
);
1675 if ( $this->contentModel
!== $this->mTitle
->getContentModel()
1676 && !$wgUser->isAllowed( 'editcontentmodel' )
1678 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1679 wfProfileOut( __METHOD__
. '-checks' );
1680 wfProfileOut( __METHOD__
);
1684 if ( wfReadOnly() ) {
1685 $status->fatal( 'readonlytext' );
1686 $status->value
= self
::AS_READ_ONLY_PAGE
;
1687 wfProfileOut( __METHOD__
. '-checks' );
1688 wfProfileOut( __METHOD__
);
1691 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1692 $status->fatal( 'actionthrottledtext' );
1693 $status->value
= self
::AS_RATE_LIMITED
;
1694 wfProfileOut( __METHOD__
. '-checks' );
1695 wfProfileOut( __METHOD__
);
1699 # If the article has been deleted while editing, don't save it without
1701 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1702 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1703 wfProfileOut( __METHOD__
. '-checks' );
1704 wfProfileOut( __METHOD__
);
1708 wfProfileOut( __METHOD__
. '-checks' );
1710 # Load the page data from the master. If anything changes in the meantime,
1711 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1712 $this->mArticle
->loadPageData( 'fromdbmaster' );
1713 $new = !$this->mArticle
->exists();
1716 // Late check for create permission, just in case *PARANOIA*
1717 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1718 $status->fatal( 'nocreatetext' );
1719 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1720 wfDebug( __METHOD__
. ": no create permission\n" );
1721 wfProfileOut( __METHOD__
);
1725 // Don't save a new page if it's blank or if it's a MediaWiki:
1726 // message with content equivalent to default (allow empty pages
1727 // in this case to disable messages, see bug 50124)
1728 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1729 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1730 $defaultText = $defaultMessageText;
1735 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1736 $this->blankArticle
= true;
1737 $status->fatal( 'blankarticle' );
1738 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1739 wfProfileOut( __METHOD__
);
1743 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1744 wfProfileOut( __METHOD__
);
1748 $content = $textbox_content;
1750 $result['sectionanchor'] = '';
1751 if ( $this->section
== 'new' ) {
1752 if ( $this->sectiontitle
!== '' ) {
1753 // Insert the section title above the content.
1754 $content = $content->addSectionHeader( $this->sectiontitle
);
1755 } elseif ( $this->summary
!== '' ) {
1756 // Insert the section title above the content.
1757 $content = $content->addSectionHeader( $this->summary
);
1759 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1762 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1766 # Article exists. Check for edit conflict.
1768 $this->mArticle
->clear(); # Force reload of dates, etc.
1769 $timestamp = $this->mArticle
->getTimestamp();
1771 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1773 if ( $timestamp != $this->edittime
) {
1774 $this->isConflict
= true;
1775 if ( $this->section
== 'new' ) {
1776 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1777 $this->mArticle
->getComment() == $this->newSectionSummary()
1779 // Probably a duplicate submission of a new comment.
1780 // This can happen when squid resends a request after
1781 // a timeout but the first one actually went through.
1783 . ": duplicate new section submission; trigger edit conflict!\n" );
1785 // New comment; suppress conflict.
1786 $this->isConflict
= false;
1787 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1789 } elseif ( $this->section
== ''
1790 && Revision
::userWasLastToEdit(
1791 DB_MASTER
, $this->mTitle
->getArticleID(),
1792 $wgUser->getId(), $this->edittime
1795 # Suppress edit conflict with self, except for section edits where merging is required.
1796 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1797 $this->isConflict
= false;
1801 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1802 if ( $this->sectiontitle
!== '' ) {
1803 $sectionTitle = $this->sectiontitle
;
1805 $sectionTitle = $this->summary
;
1810 if ( $this->isConflict
) {
1812 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1813 . " (article time '{$timestamp}')\n" );
1815 $content = $this->mArticle
->replaceSectionContent(
1822 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1823 $content = $this->mArticle
->replaceSectionContent(
1830 if ( is_null( $content ) ) {
1831 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1832 $this->isConflict
= true;
1833 $content = $textbox_content; // do not try to merge here!
1834 } elseif ( $this->isConflict
) {
1836 if ( $this->mergeChangesIntoContent( $content ) ) {
1837 // Successful merge! Maybe we should tell the user the good news?
1838 $this->isConflict
= false;
1839 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1841 $this->section
= '';
1842 $this->textbox1
= ContentHandler
::getContentText( $content );
1843 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1847 if ( $this->isConflict
) {
1848 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1849 wfProfileOut( __METHOD__
);
1853 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1854 wfProfileOut( __METHOD__
);
1858 if ( $this->section
== 'new' ) {
1859 // Handle the user preference to force summaries here
1860 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1861 $this->missingSummary
= true;
1862 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1863 $status->value
= self
::AS_SUMMARY_NEEDED
;
1864 wfProfileOut( __METHOD__
);
1868 // Do not allow the user to post an empty comment
1869 if ( $this->textbox1
== '' ) {
1870 $this->missingComment
= true;
1871 $status->fatal( 'missingcommenttext' );
1872 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1873 wfProfileOut( __METHOD__
);
1876 } elseif ( !$this->allowBlankSummary
1877 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1878 && !$content->isRedirect()
1879 && md5( $this->summary
) == $this->autoSumm
1881 $this->missingSummary
= true;
1882 $status->fatal( 'missingsummary' );
1883 $status->value
= self
::AS_SUMMARY_NEEDED
;
1884 wfProfileOut( __METHOD__
);
1889 wfProfileIn( __METHOD__
. '-sectionanchor' );
1890 $sectionanchor = '';
1891 if ( $this->section
== 'new' ) {
1892 $this->summary
= $this->newSectionSummary( $sectionanchor );
1893 } elseif ( $this->section
!= '' ) {
1894 # Try to get a section anchor from the section source, redirect
1895 # to edited section if header found.
1896 # XXX: Might be better to integrate this into Article::replaceSection
1897 # for duplicate heading checking and maybe parsing.
1898 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1899 # We can't deal with anchors, includes, html etc in the header for now,
1900 # headline would need to be parsed to improve this.
1901 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1902 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1905 $result['sectionanchor'] = $sectionanchor;
1906 wfProfileOut( __METHOD__
. '-sectionanchor' );
1908 // Save errors may fall down to the edit form, but we've now
1909 // merged the section into full text. Clear the section field
1910 // so that later submission of conflict forms won't try to
1911 // replace that into a duplicated mess.
1912 $this->textbox1
= $this->toEditText( $content );
1913 $this->section
= '';
1915 $status->value
= self
::AS_SUCCESS_UPDATE
;
1918 if ( !$this->allowSelfRedirect
1919 && $content->isRedirect()
1920 && $content->getRedirectTarget()->equals( $this->getTitle() )
1922 $this->selfRedirect
= true;
1923 $status->fatal( 'selfredirect' );
1924 $status->value
= self
::AS_SELF_REDIRECT
;
1925 wfProfileOut( __METHOD__
);
1929 // Check for length errors again now that the section is merged in
1930 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1931 if ( $this->kblength
> $wgMaxArticleSize ) {
1932 $this->tooBig
= true;
1933 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1934 wfProfileOut( __METHOD__
);
1938 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1939 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1940 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1941 ( $bot ? EDIT_FORCE_BOT
: 0 );
1943 $doEditStatus = $this->mArticle
->doEditContent(
1949 $content->getDefaultFormat()
1952 if ( !$doEditStatus->isOK() ) {
1953 // Failure from doEdit()
1954 // Show the edit conflict page for certain recognized errors from doEdit(),
1955 // but don't show it for errors from extension hooks
1956 $errors = $doEditStatus->getErrorsArray();
1957 if ( in_array( $errors[0][0],
1958 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1960 $this->isConflict
= true;
1961 // Destroys data doEdit() put in $status->value but who cares
1962 $doEditStatus->value
= self
::AS_END
;
1964 wfProfileOut( __METHOD__
);
1965 return $doEditStatus;
1968 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1969 if ( $result['nullEdit'] ) {
1970 // We don't know if it was a null edit until now, so increment here
1971 $wgUser->pingLimiter( 'linkpurge' );
1973 $result['redirect'] = $content->isRedirect();
1974 $this->updateWatchlist();
1975 wfProfileOut( __METHOD__
);
1980 * Register the change of watch status
1982 protected function updateWatchlist() {
1985 if ( $wgUser->isLoggedIn()
1986 && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
, WatchedItem
::IGNORE_USER_RIGHTS
)
1988 $fname = __METHOD__
;
1989 $title = $this->mTitle
;
1990 $watch = $this->watchthis
;
1992 // Do this in its own transaction to reduce contention...
1993 $dbw = wfGetDB( DB_MASTER
);
1994 $dbw->onTransactionIdle( function () use ( $dbw, $title, $watch, $wgUser, $fname ) {
1995 WatchAction
::doWatchOrUnwatch( $watch, $title, $wgUser );
2001 * Attempts to do 3-way merge of edit content with a base revision
2002 * and current content, in case of edit conflict, in whichever way appropriate
2003 * for the content type.
2007 * @param Content $editContent
2011 private function mergeChangesIntoContent( &$editContent ) {
2012 wfProfileIn( __METHOD__
);
2014 $db = wfGetDB( DB_MASTER
);
2016 // This is the revision the editor started from
2017 $baseRevision = $this->getBaseRevision();
2018 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2020 if ( is_null( $baseContent ) ) {
2021 wfProfileOut( __METHOD__
);
2025 // The current state, we want to merge updates into it
2026 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2027 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2029 if ( is_null( $currentContent ) ) {
2030 wfProfileOut( __METHOD__
);
2034 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2036 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2039 $editContent = $result;
2040 wfProfileOut( __METHOD__
);
2044 wfProfileOut( __METHOD__
);
2051 function getBaseRevision() {
2052 if ( !$this->mBaseRevision
) {
2053 $db = wfGetDB( DB_MASTER
);
2054 $this->mBaseRevision
= Revision
::loadFromTimestamp(
2055 $db, $this->mTitle
, $this->edittime
);
2057 return $this->mBaseRevision
;
2061 * Check given input text against $wgSpamRegex, and return the text of the first match.
2063 * @param string $text
2065 * @return string|bool Matching string or false
2067 public static function matchSpamRegex( $text ) {
2068 global $wgSpamRegex;
2069 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2070 $regexes = (array)$wgSpamRegex;
2071 return self
::matchSpamRegexInternal( $text, $regexes );
2075 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2077 * @param string $text
2079 * @return string|bool Matching string or false
2081 public static function matchSummarySpamRegex( $text ) {
2082 global $wgSummarySpamRegex;
2083 $regexes = (array)$wgSummarySpamRegex;
2084 return self
::matchSpamRegexInternal( $text, $regexes );
2088 * @param string $text
2089 * @param array $regexes
2090 * @return bool|string
2092 protected static function matchSpamRegexInternal( $text, $regexes ) {
2093 foreach ( $regexes as $regex ) {
2095 if ( preg_match( $regex, $text, $matches ) ) {
2102 function setHeaders() {
2103 global $wgOut, $wgUser, $wgAjaxEditStash;
2105 $wgOut->addModules( 'mediawiki.action.edit' );
2106 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2108 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
2109 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2112 if ( $wgUser->getOption( 'useeditwarning', false ) ) {
2113 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2116 if ( $wgAjaxEditStash ) {
2117 $wgOut->addModules( 'mediawiki.action.edit.stash' );
2120 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2122 # Enabled article-related sidebar, toplinks, etc.
2123 $wgOut->setArticleRelated( true );
2125 $contextTitle = $this->getContextTitle();
2126 if ( $this->isConflict
) {
2127 $msg = 'editconflict';
2128 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2129 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2131 $msg = $contextTitle->exists()
2132 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2133 && $contextTitle->getDefaultMessageText() !== false
2139 # Use the title defined by DISPLAYTITLE magic word when present
2140 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2141 if ( $displayTitle === false ) {
2142 $displayTitle = $contextTitle->getPrefixedText();
2144 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2148 * Show all applicable editing introductions
2150 protected function showIntro() {
2151 global $wgOut, $wgUser;
2152 if ( $this->suppressIntro
) {
2156 $namespace = $this->mTitle
->getNamespace();
2158 if ( $namespace == NS_MEDIAWIKI
) {
2159 # Show a warning if editing an interface message
2160 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2161 # If this is a default message (but not css or js),
2162 # show a hint that it is translatable on translatewiki.net
2163 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2164 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2166 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2167 if ( $defaultMessageText !== false ) {
2168 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2169 'translateinterface' );
2172 } elseif ( $namespace == NS_FILE
) {
2173 # Show a hint to shared repo
2174 $file = wfFindFile( $this->mTitle
);
2175 if ( $file && !$file->isLocal() ) {
2176 $descUrl = $file->getDescriptionUrl();
2177 # there must be a description url to show a hint to shared repo
2179 if ( !$this->mTitle
->exists() ) {
2180 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2181 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2184 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2185 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2192 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2193 # Show log extract when the user is currently blocked
2194 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2195 $parts = explode( '/', $this->mTitle
->getText(), 2 );
2196 $username = $parts[0];
2197 $user = User
::newFromName( $username, false /* allow IP users*/ );
2198 $ip = User
::isIP( $username );
2199 $block = Block
::newFromTarget( $user, $user );
2200 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2201 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2202 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2203 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2204 # Show log extract if the user is currently blocked
2205 LogEventsList
::showLogExtract(
2208 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2212 'showIfEmpty' => false,
2214 'blocked-notice-logextract',
2215 $user->getName() # Support GENDER in notice
2221 # Try to add a custom edit intro, or use the standard one if this is not possible.
2222 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2223 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2224 wfMessage( 'helppage' )->inContentLanguage()->text()
2226 if ( $wgUser->isLoggedIn() ) {
2227 $wgOut->wrapWikiMsg(
2228 // Suppress the external link icon, consider the help url an internal one
2229 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2236 $wgOut->wrapWikiMsg(
2237 // Suppress the external link icon, consider the help url an internal one
2238 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2240 'newarticletextanon',
2246 # Give a notice if the user is editing a deleted/moved page...
2247 if ( !$this->mTitle
->exists() ) {
2248 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
2252 'conds' => array( "log_action != 'revision'" ),
2253 'showIfEmpty' => false,
2254 'msgKey' => array( 'recreate-moveddeleted-warn' )
2261 * Attempt to show a custom editing introduction, if supplied
2265 protected function showCustomIntro() {
2266 if ( $this->editintro
) {
2267 $title = Title
::newFromText( $this->editintro
);
2268 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2270 // Added using template syntax, to take <noinclude>'s into account.
2271 $wgOut->addWikiTextTitleTidy(
2272 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2282 * Gets an editable textual representation of $content.
2283 * The textual representation can be turned by into a Content object by the
2284 * toEditContent() method.
2286 * If $content is null or false or a string, $content is returned unchanged.
2288 * If the given Content object is not of a type that can be edited using
2289 * the text base EditPage, an exception will be raised. Set
2290 * $this->allowNonTextContent to true to allow editing of non-textual
2293 * @param Content|null|bool|string $content
2294 * @return string The editable text form of the content.
2296 * @throws MWException If $content is not an instance of TextContent and
2297 * $this->allowNonTextContent is not true.
2299 protected function toEditText( $content ) {
2300 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2304 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2305 throw new MWException( 'This content model is not supported: '
2306 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2309 return $content->serialize( $this->contentFormat
);
2313 * Turns the given text into a Content object by unserializing it.
2315 * If the resulting Content object is not of a type that can be edited using
2316 * the text base EditPage, an exception will be raised. Set
2317 * $this->allowNonTextContent to true to allow editing of non-textual
2320 * @param string|null|bool $text Text to unserialize
2321 * @return Content The content object created from $text. If $text was false
2322 * or null, false resp. null will be returned instead.
2324 * @throws MWException If unserializing the text results in a Content
2325 * object that is not an instance of TextContent and
2326 * $this->allowNonTextContent is not true.
2328 protected function toEditContent( $text ) {
2329 if ( $text === false ||
$text === null ) {
2333 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2334 $this->contentModel
, $this->contentFormat
);
2336 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2337 throw new MWException( 'This content model is not supported: '
2338 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2345 * Send the edit form and related headers to $wgOut
2346 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2347 * during form output near the top, for captchas and the like.
2349 function showEditForm( $formCallback = null ) {
2350 global $wgOut, $wgUser;
2352 wfProfileIn( __METHOD__
);
2354 # need to parse the preview early so that we know which templates are used,
2355 # otherwise users with "show preview after edit box" will get a blank list
2356 # we parse this near the beginning so that setHeaders can do the title
2357 # setting work instead of leaving it in getPreviewText
2358 $previewOutput = '';
2359 if ( $this->formtype
== 'preview' ) {
2360 $previewOutput = $this->getPreviewText();
2363 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2365 $this->setHeaders();
2367 if ( $this->showHeader() === false ) {
2368 wfProfileOut( __METHOD__
);
2372 $wgOut->addHTML( $this->editFormPageTop
);
2374 if ( $wgUser->getOption( 'previewontop' ) ) {
2375 $this->displayPreviewArea( $previewOutput, true );
2378 $wgOut->addHTML( $this->editFormTextTop
);
2380 $showToolbar = true;
2381 if ( $this->wasDeletedSinceLastEdit() ) {
2382 if ( $this->formtype
== 'save' ) {
2383 // Hide the toolbar and edit area, user can click preview to get it back
2384 // Add an confirmation checkbox and explanation.
2385 $showToolbar = false;
2387 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2388 'deletedwhileediting' );
2392 // @todo add EditForm plugin interface and use it here!
2393 // search for textarea1 and textares2, and allow EditForm to override all uses.
2394 $wgOut->addHTML( Html
::openElement(
2397 'id' => self
::EDITFORM_ID
,
2398 'name' => self
::EDITFORM_ID
,
2400 'action' => $this->getActionURL( $this->getContextTitle() ),
2401 'enctype' => 'multipart/form-data'
2405 if ( is_callable( $formCallback ) ) {
2406 call_user_func_array( $formCallback, array( &$wgOut ) );
2409 // Add an empty field to trip up spambots
2411 Xml
::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2414 array( 'for' => 'wpAntiSpam' ),
2415 wfMessage( 'simpleantispam-label' )->parse()
2421 'name' => 'wpAntispam',
2422 'id' => 'wpAntispam',
2426 . Xml
::closeElement( 'div' )
2429 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2431 // Put these up at the top to ensure they aren't lost on early form submission
2432 $this->showFormBeforeText();
2434 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2435 $username = $this->lastDelete
->user_name
;
2436 $comment = $this->lastDelete
->log_comment
;
2438 // It is better to not parse the comment at all than to have templates expanded in the middle
2439 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2440 $key = $comment === ''
2441 ?
'confirmrecreate-noreason'
2442 : 'confirmrecreate';
2444 '<div class="mw-confirm-recreate">' .
2445 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2446 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2447 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2453 # When the summary is hidden, also hide them on preview/show changes
2454 if ( $this->nosummary
) {
2455 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2458 # If a blank edit summary was previously provided, and the appropriate
2459 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2460 # user being bounced back more than once in the event that a summary
2463 # For a bit more sophisticated detection of blank summaries, hash the
2464 # automatic one and pass that in the hidden field wpAutoSummary.
2465 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2466 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2469 if ( $this->undidRev
) {
2470 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2473 if ( $this->selfRedirect
) {
2474 $wgOut->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2477 if ( $this->hasPresetSummary
) {
2478 // If a summary has been preset using &summary= we don't want to prompt for
2479 // a different summary. Only prompt for a summary if the summary is blanked.
2481 $this->autoSumm
= md5( '' );
2484 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2485 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2487 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2488 $wgOut->addHTML( Html
::hidden( 'parentRevId',
2489 $this->parentRevId ?
: $this->mArticle
->getRevIdFetched() ) );
2491 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2492 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2494 if ( $this->section
== 'new' ) {
2495 $this->showSummaryInput( true, $this->summary
);
2496 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2499 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2501 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2502 $wgOut->addHTML( EditPage
::getEditToolbar() );
2505 if ( $this->blankArticle
) {
2506 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2509 if ( $this->isConflict
) {
2510 // In an edit conflict bypass the overridable content form method
2511 // and fallback to the raw wpTextbox1 since editconflicts can't be
2512 // resolved between page source edits and custom ui edits using the
2514 $this->textbox2
= $this->textbox1
;
2516 $content = $this->getCurrentContent();
2517 $this->textbox1
= $this->toEditText( $content );
2519 $this->showTextbox1();
2521 $this->showContentForm();
2524 $wgOut->addHTML( $this->editFormTextAfterContent
);
2526 $this->showStandardInputs();
2528 $this->showFormAfterText();
2530 $this->showTosSummary();
2532 $this->showEditTools();
2534 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2536 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2537 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2539 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2540 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2542 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'limitreport' ),
2543 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2545 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2547 if ( $this->isConflict
) {
2549 $this->showConflict();
2550 } catch ( MWContentSerializationException
$ex ) {
2551 // this can't really happen, but be nice if it does.
2553 'content-failed-to-parse',
2554 $this->contentModel
,
2555 $this->contentFormat
,
2558 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2562 // Marker for detecting truncated form data. This must be the last
2563 // parameter sent in order to be of use, so do not move me.
2564 $wgOut->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2565 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2567 if ( !$wgUser->getOption( 'previewontop' ) ) {
2568 $this->displayPreviewArea( $previewOutput, false );
2571 wfProfileOut( __METHOD__
);
2575 * Extract the section title from current section text, if any.
2577 * @param string $text
2578 * @return string|bool String or false
2580 public static function extractSectionTitle( $text ) {
2581 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2582 if ( !empty( $matches[2] ) ) {
2584 return $wgParser->stripSectionName( trim( $matches[2] ) );
2593 protected function showHeader() {
2594 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2595 global $wgAllowUserCss, $wgAllowUserJs;
2597 if ( $this->mTitle
->isTalkPage() ) {
2598 $wgOut->addWikiMsg( 'talkpagetext' );
2602 $wgOut->addHTML( implode( "\n", $this->mTitle
->getEditNotices( $this->oldid
) ) );
2604 if ( $this->isConflict
) {
2605 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2606 $this->edittime
= $this->mArticle
->getTimestamp();
2608 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2609 // We use $this->section to much before this and getVal('wgSection') directly in other places
2610 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2611 // Someone is welcome to try refactoring though
2612 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2616 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2617 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2618 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2619 if ( $sectionTitle !== false ) {
2620 $this->summary
= "/* $sectionTitle */ ";
2625 if ( $this->missingComment
) {
2626 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2629 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2630 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2633 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2634 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2637 if ( $this->blankArticle
) {
2638 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2641 if ( $this->selfRedirect
) {
2642 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2645 if ( $this->hookError
!== '' ) {
2646 $wgOut->addWikiText( $this->hookError
);
2649 if ( !$this->checkUnicodeCompliantBrowser() ) {
2650 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2653 if ( $this->section
!= 'new' ) {
2654 $revision = $this->mArticle
->getRevisionFetched();
2656 // Let sysop know that this will make private content public if saved
2658 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2659 $wgOut->wrapWikiMsg(
2660 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2661 'rev-deleted-text-permission'
2663 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2664 $wgOut->wrapWikiMsg(
2665 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2666 'rev-deleted-text-view'
2670 if ( !$revision->isCurrent() ) {
2671 $this->mArticle
->setOldSubtitle( $revision->getId() );
2672 $wgOut->addWikiMsg( 'editingold' );
2674 } elseif ( $this->mTitle
->exists() ) {
2675 // Something went wrong
2677 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2678 array( 'missing-revision', $this->oldid
) );
2683 if ( wfReadOnly() ) {
2684 $wgOut->wrapWikiMsg(
2685 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2686 array( 'readonlywarning', wfReadOnlyReason() )
2688 } elseif ( $wgUser->isAnon() ) {
2689 if ( $this->formtype
!= 'preview' ) {
2690 $wgOut->wrapWikiMsg(
2691 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2692 array( 'anoneditwarning',
2694 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2696 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2699 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2700 'anonpreviewwarning'
2704 if ( $this->isCssJsSubpage
) {
2705 # Check the skin exists
2706 if ( $this->isWrongCaseCssJsPage
) {
2707 $wgOut->wrapWikiMsg(
2708 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2709 array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() )
2712 if ( $this->formtype
!== 'preview' ) {
2713 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
2714 $wgOut->wrapWikiMsg(
2715 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2716 array( 'usercssyoucanpreview' )
2720 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
2721 $wgOut->wrapWikiMsg(
2722 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2723 array( 'userjsyoucanpreview' )
2730 if ( $this->mTitle
->isProtected( 'edit' ) &&
2731 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2733 # Is the title semi-protected?
2734 if ( $this->mTitle
->isSemiProtected() ) {
2735 $noticeMsg = 'semiprotectedpagewarning';
2737 # Then it must be protected based on static groups (regular)
2738 $noticeMsg = 'protectedpagewarning';
2740 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2741 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2743 if ( $this->mTitle
->isCascadeProtected() ) {
2744 # Is this page under cascading protection from some source pages?
2745 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2746 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2747 $cascadeSourcesCount = count( $cascadeSources );
2748 if ( $cascadeSourcesCount > 0 ) {
2749 # Explain, and list the titles responsible
2750 foreach ( $cascadeSources as $page ) {
2751 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2754 $notice .= '</div>';
2755 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2757 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2758 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2760 'showIfEmpty' => false,
2761 'msgKey' => array( 'titleprotectedwarning' ),
2762 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2765 if ( $this->kblength
=== false ) {
2766 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2769 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2770 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2773 $wgLang->formatNum( $this->kblength
),
2774 $wgLang->formatNum( $wgMaxArticleSize )
2778 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2779 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2782 $wgLang->formatSize( strlen( $this->textbox1
) ),
2783 strlen( $this->textbox1
)
2788 # Add header copyright warning
2789 $this->showHeaderCopyrightWarning();
2795 * Standard summary input and label (wgSummary), abstracted so EditPage
2796 * subclasses may reorganize the form.
2797 * Note that you do not need to worry about the label's for=, it will be
2798 * inferred by the id given to the input. You can remove them both by
2799 * passing array( 'id' => false ) to $userInputAttrs.
2801 * @param string $summary The value of the summary input
2802 * @param string $labelText The html to place inside the label
2803 * @param array $inputAttrs Array of attrs to use on the input
2804 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2806 * @return array An array in the format array( $label, $input )
2808 function getSummaryInput( $summary = "", $labelText = null,
2809 $inputAttrs = null, $spanLabelAttrs = null
2811 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2812 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2813 'id' => 'wpSummary',
2814 'maxlength' => '200',
2817 'spellcheck' => 'true',
2818 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2820 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2821 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2822 'id' => "wpSummaryLabel"
2829 $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null,
2832 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2835 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2837 return array( $label, $input );
2841 * @param bool $isSubjectPreview True if this is the section subject/title
2842 * up top, or false if this is the comment summary
2843 * down below the textarea
2844 * @param string $summary The text of the summary to display
2846 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2847 global $wgOut, $wgContLang;
2848 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2849 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2850 if ( $isSubjectPreview ) {
2851 if ( $this->nosummary
) {
2855 if ( !$this->mShowSummaryField
) {
2859 $summary = $wgContLang->recodeForEdit( $summary );
2860 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2861 list( $label, $input ) = $this->getSummaryInput(
2864 array( 'class' => $summaryClass ),
2867 $wgOut->addHTML( "{$label} {$input}" );
2871 * @param bool $isSubjectPreview True if this is the section subject/title
2872 * up top, or false if this is the comment summary
2873 * down below the textarea
2874 * @param string $summary The text of the summary to display
2877 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2878 // avoid spaces in preview, gets always trimmed on save
2879 $summary = trim( $summary );
2880 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2886 if ( $isSubjectPreview ) {
2887 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2888 ->inContentLanguage()->text();
2891 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2893 $summary = wfMessage( $message )->parse()
2894 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2895 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2898 protected function showFormBeforeText() {
2900 $section = htmlspecialchars( $this->section
);
2901 $wgOut->addHTML( <<<HTML
2902 <input type='hidden' value="{$section}" name="wpSection"/>
2903 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2904 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2905 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2909 if ( !$this->checkUnicodeCompliantBrowser() ) {
2910 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2914 protected function showFormAfterText() {
2915 global $wgOut, $wgUser;
2917 * To make it harder for someone to slip a user a page
2918 * which submits an edit form to the wiki without their
2919 * knowledge, a random token is associated with the login
2920 * session. If it's not passed back with the submission,
2921 * we won't save the page, or render user JavaScript and
2924 * For anon editors, who may not have a session, we just
2925 * include the constant suffix to prevent editing from
2926 * broken text-mangling proxies.
2928 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2932 * Subpage overridable method for printing the form for page content editing
2933 * By default this simply outputs wpTextbox1
2934 * Subclasses can override this to provide a custom UI for editing;
2935 * be it a form, or simply wpTextbox1 with a modified content that will be
2936 * reverse modified when extracted from the post data.
2937 * Note that this is basically the inverse for importContentFormData
2939 protected function showContentForm() {
2940 $this->showTextbox1();
2944 * Method to output wpTextbox1
2945 * The $textoverride method can be used by subclasses overriding showContentForm
2946 * to pass back to this method.
2948 * @param array $customAttribs Array of html attributes to use in the textarea
2949 * @param string $textoverride Optional text to override $this->textarea1 with
2951 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2952 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2953 $attribs = array( 'style' => 'display:none;' );
2955 $classes = array(); // Textarea CSS
2956 if ( $this->mTitle
->isProtected( 'edit' ) &&
2957 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2959 # Is the title semi-protected?
2960 if ( $this->mTitle
->isSemiProtected() ) {
2961 $classes[] = 'mw-textarea-sprotected';
2963 # Then it must be protected based on static groups (regular)
2964 $classes[] = 'mw-textarea-protected';
2966 # Is the title cascade-protected?
2967 if ( $this->mTitle
->isCascadeProtected() ) {
2968 $classes[] = 'mw-textarea-cprotected';
2972 $attribs = array( 'tabindex' => 1 );
2974 if ( is_array( $customAttribs ) ) {
2975 $attribs +
= $customAttribs;
2978 if ( count( $classes ) ) {
2979 if ( isset( $attribs['class'] ) ) {
2980 $classes[] = $attribs['class'];
2982 $attribs['class'] = implode( ' ', $classes );
2987 $textoverride !== null ?
$textoverride : $this->textbox1
,
2993 protected function showTextbox2() {
2994 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2997 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2998 global $wgOut, $wgUser;
3000 $wikitext = $this->safeUnicodeOutput( $text );
3001 if ( strval( $wikitext ) !== '' ) {
3002 // Ensure there's a newline at the end, otherwise adding lines
3004 // But don't add a newline if the ext is empty, or Firefox in XHTML
3005 // mode will show an extra newline. A bit annoying.
3009 $attribs = $customAttribs +
array(
3012 'cols' => $wgUser->getIntOption( 'cols' ),
3013 'rows' => $wgUser->getIntOption( 'rows' ),
3014 // Avoid PHP notices when appending preferences
3015 // (appending allows customAttribs['style'] to still work).
3019 $pageLang = $this->mTitle
->getPageLanguage();
3020 $attribs['lang'] = $pageLang->getHtmlCode();
3021 $attribs['dir'] = $pageLang->getDir();
3023 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3026 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3030 $classes[] = 'ontop';
3033 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3035 if ( $this->formtype
!= 'preview' ) {
3036 $attribs['style'] = 'display: none;';
3039 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
3041 if ( $this->formtype
== 'preview' ) {
3042 $this->showPreview( $previewOutput );
3045 $wgOut->addHTML( '</div>' );
3047 if ( $this->formtype
== 'diff' ) {
3050 } catch ( MWContentSerializationException
$ex ) {
3052 'content-failed-to-parse',
3053 $this->contentModel
,
3054 $this->contentFormat
,
3057 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3063 * Append preview output to $wgOut.
3064 * Includes category rendering if this is a category page.
3066 * @param string $text The HTML to be output for the preview.
3068 protected function showPreview( $text ) {
3070 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3071 $this->mArticle
->openShowCategory();
3073 # This hook seems slightly odd here, but makes things more
3074 # consistent for extensions.
3075 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3076 $wgOut->addHTML( $text );
3077 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3078 $this->mArticle
->closeShowCategory();
3083 * Get a diff between the current contents of the edit box and the
3084 * version of the page we're editing from.
3086 * If this is a section edit, we'll replace the section as for final
3087 * save and then make a comparison.
3089 function showDiff() {
3090 global $wgUser, $wgContLang, $wgOut;
3092 $oldtitlemsg = 'currentrev';
3093 # if message does not exist, show diff against the preloaded default
3094 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3095 $oldtext = $this->mTitle
->getDefaultMessageText();
3096 if ( $oldtext !== false ) {
3097 $oldtitlemsg = 'defaultmessagetext';
3098 $oldContent = $this->toEditContent( $oldtext );
3103 $oldContent = $this->getCurrentContent();
3106 $textboxContent = $this->toEditContent( $this->textbox1
);
3108 $newContent = $this->mArticle
->replaceSectionContent(
3109 $this->section
, $textboxContent,
3110 $this->summary
, $this->edittime
);
3112 if ( $newContent ) {
3113 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3114 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3116 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
3117 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
3120 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3121 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3122 $newtitle = wfMessage( 'yourtext' )->parse();
3124 if ( !$oldContent ) {
3125 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3128 if ( !$newContent ) {
3129 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3132 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3133 $de->setContent( $oldContent, $newContent );
3135 $difftext = $de->getDiff( $oldtitle, $newtitle );
3136 $de->showDiffStyle();
3141 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3145 * Show the header copyright warning.
3147 protected function showHeaderCopyrightWarning() {
3148 $msg = 'editpage-head-copy-warn';
3149 if ( !wfMessage( $msg )->isDisabled() ) {
3151 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3152 'editpage-head-copy-warn' );
3157 * Give a chance for site and per-namespace customizations of
3158 * terms of service summary link that might exist separately
3159 * from the copyright notice.
3161 * This will display between the save button and the edit tools,
3162 * so should remain short!
3164 protected function showTosSummary() {
3165 $msg = 'editpage-tos-summary';
3166 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
3167 if ( !wfMessage( $msg )->isDisabled() ) {
3169 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3170 $wgOut->addWikiMsg( $msg );
3171 $wgOut->addHTML( '</div>' );
3175 protected function showEditTools() {
3177 $wgOut->addHTML( '<div class="mw-editTools">' .
3178 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3183 * Get the copyright warning
3185 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3188 protected function getCopywarn() {
3189 return self
::getCopyrightWarning( $this->mTitle
);
3193 * Get the copyright warning, by default returns wikitext
3195 * @param Title $title
3196 * @param string $format Output format, valid values are any function of a Message object
3199 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3200 global $wgRightsText;
3201 if ( $wgRightsText ) {
3202 $copywarnMsg = array( 'copyrightwarning',
3203 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3206 $copywarnMsg = array( 'copyrightwarning2',
3207 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3209 // Allow for site and per-namespace customization of contribution/copyright notice.
3210 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3212 return "<div id=\"editpage-copywarn\">\n" .
3213 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3217 * Get the Limit report for page previews
3220 * @param ParserOutput $output ParserOutput object from the parse
3221 * @return string HTML
3223 public static function getPreviewLimitReport( $output ) {
3224 if ( !$output ||
!$output->getLimitReportData() ) {
3228 wfProfileIn( __METHOD__
);
3230 $limitReport = Html
::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3231 wfMessage( 'limitreport-title' )->parseAsBlock()
3234 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3235 $limitReport .= Html
::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3237 $limitReport .= Html
::openElement( 'table', array(
3238 'class' => 'preview-limit-report wikitable'
3240 Html
::openElement( 'tbody' );
3242 foreach ( $output->getLimitReportData() as $key => $value ) {
3243 if ( wfRunHooks( 'ParserLimitReportFormat',
3244 array( $key, &$value, &$limitReport, true, true )
3246 $keyMsg = wfMessage( $key );
3247 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3248 if ( !$valueMsg->exists() ) {
3249 $valueMsg = new RawMessage( '$1' );
3251 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3252 $limitReport .= Html
::openElement( 'tr' ) .
3253 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3254 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3255 Html
::closeElement( 'tr' );
3260 $limitReport .= Html
::closeElement( 'tbody' ) .
3261 Html
::closeElement( 'table' ) .
3262 Html
::closeElement( 'div' );
3264 wfProfileOut( __METHOD__
);
3266 return $limitReport;
3269 protected function showStandardInputs( &$tabindex = 2 ) {
3271 $wgOut->addHTML( "<div class='editOptions'>\n" );
3273 if ( $this->section
!= 'new' ) {
3274 $this->showSummaryInput( false, $this->summary
);
3275 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3278 $checkboxes = $this->getCheckboxes( $tabindex,
3279 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
3280 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3282 // Show copyright warning.
3283 $wgOut->addWikiText( $this->getCopywarn() );
3284 $wgOut->addHTML( $this->editFormTextAfterWarn
);
3286 $wgOut->addHTML( "<div class='editButtons'>\n" );
3287 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3289 $cancel = $this->getCancelLink();
3290 if ( $cancel !== '' ) {
3291 $cancel .= Html
::element( 'span',
3292 array( 'class' => 'mw-editButtons-pipe-separator' ),
3293 wfMessage( 'pipe-separator' )->text() );
3296 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3297 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3299 'target' => 'helpwindow',
3300 'href' => $edithelpurl,
3302 $edithelp = Html
::linkButton( wfMessage( 'edithelp' )->text(),
3303 $attrs, array( 'mw-ui-quiet' ) ) .
3304 wfMessage( 'word-separator' )->escaped() .
3305 wfMessage( 'newwindow' )->parse();
3307 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3308 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3309 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3311 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3313 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3317 * Show an edit conflict. textbox1 is already shown in showEditForm().
3318 * If you want to use another entry point to this function, be careful.
3320 protected function showConflict() {
3323 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3324 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3326 $content1 = $this->toEditContent( $this->textbox1
);
3327 $content2 = $this->toEditContent( $this->textbox2
);
3329 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3330 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3331 $de->setContent( $content2, $content1 );
3333 wfMessage( 'yourtext' )->parse(),
3334 wfMessage( 'storedversion' )->text()
3337 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3338 $this->showTextbox2();
3345 public function getCancelLink() {
3346 $cancelParams = array();
3347 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3348 $cancelParams['oldid'] = $this->oldid
;
3350 $attrs = array( 'id' => 'mw-editform-cancel' );
3352 return Linker
::linkKnown(
3353 $this->getContextTitle(),
3354 wfMessage( 'cancel' )->parse(),
3355 Html
::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3361 * Returns the URL to use in the form's action attribute.
3362 * This is used by EditPage subclasses when simply customizing the action
3363 * variable in the constructor is not enough. This can be used when the
3364 * EditPage lives inside of a Special page rather than a custom page action.
3366 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3369 protected function getActionURL( Title
$title ) {
3370 return $title->getLocalURL( array( 'action' => $this->action
) );
3374 * Check if a page was deleted while the user was editing it, before submit.
3375 * Note that we rely on the logging table, which hasn't been always there,
3376 * but that doesn't matter, because this only applies to brand new
3380 protected function wasDeletedSinceLastEdit() {
3381 if ( $this->deletedSinceEdit
!== null ) {
3382 return $this->deletedSinceEdit
;
3385 $this->deletedSinceEdit
= false;
3387 if ( $this->mTitle
->isDeletedQuick() ) {
3388 $this->lastDelete
= $this->getLastDelete();
3389 if ( $this->lastDelete
) {
3390 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3391 if ( $deleteTime > $this->starttime
) {
3392 $this->deletedSinceEdit
= true;
3397 return $this->deletedSinceEdit
;
3401 * @return bool|stdClass
3403 protected function getLastDelete() {
3404 $dbr = wfGetDB( DB_SLAVE
);
3405 $data = $dbr->selectRow(
3406 array( 'logging', 'user' ),
3419 'log_namespace' => $this->mTitle
->getNamespace(),
3420 'log_title' => $this->mTitle
->getDBkey(),
3421 'log_type' => 'delete',
3422 'log_action' => 'delete',
3426 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3428 // Quick paranoid permission checks...
3429 if ( is_object( $data ) ) {
3430 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3431 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
3434 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3435 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
3443 * Get the rendered text for previewing.
3444 * @throws MWException
3447 function getPreviewText() {
3448 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3449 global $wgAllowUserCss, $wgAllowUserJs;
3451 wfProfileIn( __METHOD__
);
3453 if ( $wgRawHtml && !$this->mTokenOk
) {
3454 // Could be an offsite preview attempt. This is very unsafe if
3455 // HTML is enabled, as it could be an attack.
3457 if ( $this->textbox1
!== '' ) {
3458 // Do not put big scary notice, if previewing the empty
3459 // string, which happens when you initially edit
3460 // a category page, due to automatic preview-on-open.
3461 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3462 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3464 wfProfileOut( __METHOD__
);
3471 $content = $this->toEditContent( $this->textbox1
);
3475 'AlternateEditPreview',
3476 array( $this, &$content, &$previewHTML, &$this->mParserOutput
) )
3478 wfProfileOut( __METHOD__
);
3479 return $previewHTML;
3482 # provide a anchor link to the editform
3483 $continueEditing = '<span class="mw-continue-editing">' .
3484 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3485 wfMessage( 'continue-editing' )->text() . ']]</span>';
3486 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3487 if ( $this->mTokenOkExceptSuffix
) {
3488 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3490 $note = wfMessage( 'session_fail_preview' )->plain();
3492 } elseif ( $this->incompleteForm
) {
3493 $note = wfMessage( 'edit_form_incomplete' )->plain();
3495 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3498 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
3499 $parserOptions->setEditSection( false );
3500 $parserOptions->setIsPreview( true );
3501 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3503 # don't parse non-wikitext pages, show message about preview
3504 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3505 if ( $this->mTitle
->isCssJsSubpage() ) {
3507 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3513 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3515 if ( $level === 'user' && !$wgAllowUserCss ) {
3518 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3520 if ( $level === 'user' && !$wgAllowUserJs ) {
3527 # Used messages to make sure grep find them:
3528 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3529 if ( $level && $format ) {
3530 $note = "<div id='mw-{$level}{$format}preview'>" .
3531 wfMessage( "{$level}{$format}preview" )->text() .
3532 ' ' . $continueEditing . "</div>";
3536 # If we're adding a comment, we need to show the
3537 # summary as the headline
3538 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3539 $content = $content->addSectionHeader( $this->summary
);
3542 $hook_args = array( $this, &$content );
3543 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3544 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3546 $parserOptions->enableLimitReport();
3548 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3549 # But it's now deprecated, so never mind
3551 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3552 $parserOutput = $content->getParserOutput(
3553 $this->getArticle()->getTitle(),
3558 $previewHTML = $parserOutput->getText();
3559 $this->mParserOutput
= $parserOutput;
3560 $wgOut->addParserOutputMetadata( $parserOutput );
3562 if ( count( $parserOutput->getWarnings() ) ) {
3563 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3565 } catch ( MWContentSerializationException
$ex ) {
3567 'content-failed-to-parse',
3568 $this->contentModel
,
3569 $this->contentFormat
,
3572 $note .= "\n\n" . $m->parse();
3576 if ( $this->isConflict
) {
3577 $conflict = '<h2 id="mw-previewconflict">'
3578 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3580 $conflict = '<hr />';
3583 $previewhead = "<div class='previewnote'>\n" .
3584 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3585 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3587 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3588 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3589 'class' => 'mw-content-' . $pageViewLang->getDir() );
3590 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3592 wfProfileOut( __METHOD__
);
3593 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3599 function getTemplates() {
3600 if ( $this->preview ||
$this->section
!= '' ) {
3601 $templates = array();
3602 if ( !isset( $this->mParserOutput
) ) {
3605 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3606 foreach ( array_keys( $template ) as $dbk ) {
3607 $templates[] = Title
::makeTitle( $ns, $dbk );
3612 return $this->mTitle
->getTemplateLinksFrom();
3617 * Shows a bulletin board style toolbar for common editing functions.
3618 * It can be disabled in the user preferences.
3622 static function getEditToolbar() {
3623 global $wgContLang, $wgOut;
3624 global $wgEnableUploads, $wgForeignFileRepos;
3626 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3629 * $toolarray is an array of arrays each of which includes the
3630 * opening tag, the closing tag, optionally a sample text that is
3631 * inserted between the two when no selection is highlighted
3632 * and. The tip text is shown when the user moves the mouse
3635 * Images are defined in ResourceLoaderEditToolbarModule.
3639 'id' => 'mw-editbutton-bold',
3641 'close' => '\'\'\'',
3642 'sample' => wfMessage( 'bold_sample' )->text(),
3643 'tip' => wfMessage( 'bold_tip' )->text(),
3646 'id' => 'mw-editbutton-italic',
3649 'sample' => wfMessage( 'italic_sample' )->text(),
3650 'tip' => wfMessage( 'italic_tip' )->text(),
3653 'id' => 'mw-editbutton-link',
3656 'sample' => wfMessage( 'link_sample' )->text(),
3657 'tip' => wfMessage( 'link_tip' )->text(),
3660 'id' => 'mw-editbutton-extlink',
3663 'sample' => wfMessage( 'extlink_sample' )->text(),
3664 'tip' => wfMessage( 'extlink_tip' )->text(),
3667 'id' => 'mw-editbutton-headline',
3670 'sample' => wfMessage( 'headline_sample' )->text(),
3671 'tip' => wfMessage( 'headline_tip' )->text(),
3673 $imagesAvailable ?
array(
3674 'id' => 'mw-editbutton-image',
3675 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3677 'sample' => wfMessage( 'image_sample' )->text(),
3678 'tip' => wfMessage( 'image_tip' )->text(),
3680 $imagesAvailable ?
array(
3681 'id' => 'mw-editbutton-media',
3682 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3684 'sample' => wfMessage( 'media_sample' )->text(),
3685 'tip' => wfMessage( 'media_tip' )->text(),
3688 'id' => 'mw-editbutton-nowiki',
3689 'open' => "<nowiki>",
3690 'close' => "</nowiki>",
3691 'sample' => wfMessage( 'nowiki_sample' )->text(),
3692 'tip' => wfMessage( 'nowiki_tip' )->text(),
3695 'id' => 'mw-editbutton-signature',
3699 'tip' => wfMessage( 'sig_tip' )->text(),
3702 'id' => 'mw-editbutton-hr',
3703 'open' => "\n----\n",
3706 'tip' => wfMessage( 'hr_tip' )->text(),
3710 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3711 foreach ( $toolarray as $tool ) {
3717 // Images are defined in ResourceLoaderEditToolbarModule
3719 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3720 // Older browsers show a "speedtip" type message only for ALT.
3721 // Ideally these should be different, realistically they
3722 // probably don't need to be.
3730 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3734 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3736 $toolbar = '<div id="toolbar"></div>';
3738 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3744 * Returns an array of html code of the following checkboxes:
3747 * @param int $tabindex Current tabindex
3748 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3749 * status of the checkbox
3753 public function getCheckboxes( &$tabindex, $checked ) {
3754 global $wgUser, $wgUseMediaWikiUIEverywhere;
3756 $checkboxes = array();
3758 // don't show the minor edit checkbox if it's a new page or section
3759 if ( !$this->isNew
) {
3760 $checkboxes['minor'] = '';
3761 $minorLabel = wfMessage( 'minoredit' )->parse();
3762 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3764 'tabindex' => ++
$tabindex,
3765 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3766 'id' => 'wpMinoredit',
3769 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3770 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3771 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3772 ">{$minorLabel}</label>";
3774 if ( $wgUseMediaWikiUIEverywhere ) {
3775 $checkboxes['minor'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3777 Html
::closeElement( 'div' );
3779 $checkboxes['minor'] = $minorEditHtml;
3784 $watchLabel = wfMessage( 'watchthis' )->parse();
3785 $checkboxes['watch'] = '';
3786 if ( $wgUser->isLoggedIn() ) {
3788 'tabindex' => ++
$tabindex,
3789 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3790 'id' => 'wpWatchthis',
3793 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3794 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3795 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3796 ">{$watchLabel}</label>";
3797 if ( $wgUseMediaWikiUIEverywhere ) {
3798 $checkboxes['watch'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3800 Html
::closeElement( 'div' );
3802 $checkboxes['watch'] = $watchThisHtml;
3805 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3810 * Returns an array of html code of the following buttons:
3811 * save, diff, preview and live
3813 * @param int $tabindex Current tabindex
3817 public function getEditButtons( &$tabindex ) {
3823 'tabindex' => ++
$tabindex,
3824 ) + Linker
::tooltipAndAccesskeyAttribs( 'save' );
3825 $buttons['save'] = Html
::submitButton( wfMessage( 'savearticle' )->text(),
3826 $attribs, array( 'mw-ui-constructive' ) );
3828 ++
$tabindex; // use the same for preview and live preview
3830 'id' => 'wpPreview',
3831 'name' => 'wpPreview',
3832 'tabindex' => $tabindex,
3833 ) + Linker
::tooltipAndAccesskeyAttribs( 'preview' );
3834 $buttons['preview'] = Html
::submitButton( wfMessage( 'showpreview' )->text(),
3836 $buttons['live'] = '';
3841 'tabindex' => ++
$tabindex,
3842 ) + Linker
::tooltipAndAccesskeyAttribs( 'diff' );
3843 $buttons['diff'] = Html
::submitButton( wfMessage( 'showdiff' )->text(),
3846 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3851 * Output preview text only. This can be sucked into the edit page
3852 * via JavaScript, and saves the server time rendering the skin as
3853 * well as theoretically being more robust on the client (doesn't
3854 * disturb the edit box's undo history, won't eat your text on
3857 * @todo This doesn't include category or interlanguage links.
3858 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3859 * or something...</s>" that might also require more skin
3860 * initialization, so check whether that's a problem.
3862 function livePreview() {
3865 header( 'Content-type: text/xml; charset=utf-8' );
3866 header( 'Cache-control: no-cache' );
3868 $previewText = $this->getPreviewText();
3869 #$categories = $skin->getCategoryLinks();
3872 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3873 Xml
::tags( 'livepreview', null,
3874 Xml
::element( 'preview', null, $previewText )
3875 #. Xml::element( 'category', null, $categories )
3881 * Creates a basic error page which informs the user that
3882 * they have attempted to edit a nonexistent section.
3884 function noSuchSectionPage() {
3887 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3889 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3890 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3891 $wgOut->addHTML( $res );
3893 $wgOut->returnToMain( false, $this->mTitle
);
3897 * Show "your edit contains spam" page with your diff and text
3899 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3901 public function spamPageWithContent( $match = false ) {
3902 global $wgOut, $wgLang;
3903 $this->textbox2
= $this->textbox1
;
3905 if ( is_array( $match ) ) {
3906 $match = $wgLang->listToText( $match );
3908 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3910 $wgOut->addHTML( '<div id="spamprotected">' );
3911 $wgOut->addWikiMsg( 'spamprotectiontext' );
3913 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3915 $wgOut->addHTML( '</div>' );
3917 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3920 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3921 $this->showTextbox2();
3923 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3927 * Check if the browser is on a blacklist of user-agents known to
3928 * mangle UTF-8 data on form submission. Returns true if Unicode
3929 * should make it through, false if it's known to be a problem.
3932 private function checkUnicodeCompliantBrowser() {
3933 global $wgBrowserBlackList, $wgRequest;
3935 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3936 if ( $currentbrowser === false ) {
3937 // No User-Agent header sent? Trust it by default...
3941 foreach ( $wgBrowserBlackList as $browser ) {
3942 if ( preg_match( $browser, $currentbrowser ) ) {
3950 * Filter an input field through a Unicode de-armoring process if it
3951 * came from an old browser with known broken Unicode editing issues.
3953 * @param WebRequest $request
3954 * @param string $field
3957 protected function safeUnicodeInput( $request, $field ) {
3958 $text = rtrim( $request->getText( $field ) );
3959 return $request->getBool( 'safemode' )
3960 ?
$this->unmakeSafe( $text )
3965 * Filter an output field through a Unicode armoring process if it is
3966 * going to an old browser with known broken Unicode editing issues.
3968 * @param string $text
3971 protected function safeUnicodeOutput( $text ) {
3973 $codedText = $wgContLang->recodeForEdit( $text );
3974 return $this->checkUnicodeCompliantBrowser()
3976 : $this->makeSafe( $codedText );
3980 * A number of web browsers are known to corrupt non-ASCII characters
3981 * in a UTF-8 text editing environment. To protect against this,
3982 * detected browsers will be served an armored version of the text,
3983 * with non-ASCII chars converted to numeric HTML character references.
3985 * Preexisting such character references will have a 0 added to them
3986 * to ensure that round-trips do not alter the original data.
3988 * @param string $invalue
3991 private function makeSafe( $invalue ) {
3992 // Armor existing references for reversibility.
3993 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3998 $valueLength = strlen( $invalue );
3999 for ( $i = 0; $i < $valueLength; $i++
) {
4000 $bytevalue = ord( $invalue[$i] );
4001 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4002 $result .= chr( $bytevalue );
4004 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4005 $working = $working << 6;
4006 $working +
= ( $bytevalue & 0x3F );
4008 if ( $bytesleft <= 0 ) {
4009 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4011 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4012 $working = $bytevalue & 0x1F;
4014 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4015 $working = $bytevalue & 0x0F;
4017 } else { // 1111 0xxx
4018 $working = $bytevalue & 0x07;
4026 * Reverse the previously applied transliteration of non-ASCII characters
4027 * back to UTF-8. Used to protect data from corruption by broken web browsers
4028 * as listed in $wgBrowserBlackList.
4030 * @param string $invalue
4033 private function unmakeSafe( $invalue ) {
4035 $valueLength = strlen( $invalue );
4036 for ( $i = 0; $i < $valueLength; $i++
) {
4037 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4041 $hexstring .= $invalue[$i];
4043 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4045 // Do some sanity checks. These aren't needed for reversibility,
4046 // but should help keep the breakage down if the editor
4047 // breaks one of the entities whilst editing.
4048 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4049 $codepoint = hexdec( $hexstring );
4050 $result .= codepointToUtf8( $codepoint );
4052 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4055 $result .= substr( $invalue, $i, 1 );
4058 // reverse the transform that we made for reversibility reasons.
4059 return strtr( $result, array( "�" => "&#x" ) );