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: an error relating to change tagging. Look at the message key for
163 const AS_CHANGE_TAG_ERROR
= 237;
166 * Status: can't parse content
168 const AS_PARSE_ERROR
= 240;
171 * Status: when changing the content model is disallowed due to
172 * $wgContentHandlerUseDB being false
174 const AS_CANNOT_USE_CUSTOM_MODEL
= 241;
177 * HTML id and name for the beginning of the edit form.
179 const EDITFORM_ID
= 'editform';
182 * Prefix of key for cookie used to pass post-edit state.
183 * The revision id edited is added after this
185 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
188 * Duration of PostEdit cookie, in seconds.
189 * The cookie will be removed instantly if the JavaScript runs.
191 * Otherwise, though, we don't want the cookies to accumulate.
192 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
193 * limit of only 20 cookies per domain. This still applies at least to some
194 * versions of IE without full updates:
195 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
197 * A value of 20 minutes should be enough to take into account slow loads and minor
198 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
200 const POST_EDIT_COOKIE_DURATION
= 1200;
208 /** @var null|Title */
209 private $mContextTitle = null;
212 public $action = 'submit';
215 public $isConflict = false;
218 public $isCssJsSubpage = false;
221 public $isCssSubpage = false;
224 public $isJsSubpage = false;
227 public $isWrongCaseCssJsPage = false;
229 /** @var bool New page or new section */
230 public $isNew = false;
233 public $deletedSinceEdit;
241 /** @var bool|stdClass */
245 public $mTokenOk = false;
248 public $mTokenOkExceptSuffix = false;
251 public $mTriedSave = false;
254 public $incompleteForm = false;
257 public $tooBig = false;
260 public $kblength = false;
263 public $missingComment = false;
266 public $missingSummary = false;
269 public $allowBlankSummary = false;
272 protected $blankArticle = false;
275 protected $allowBlankArticle = false;
278 protected $selfRedirect = false;
281 protected $allowSelfRedirect = false;
284 public $autoSumm = '';
287 public $hookError = '';
289 /** @var ParserOutput */
290 public $mParserOutput;
292 /** @var bool Has a summary been preset using GET parameter &summary= ? */
293 public $hasPresetSummary = false;
296 public $mBaseRevision = false;
299 public $mShowSummaryField = true;
304 public $save = false;
307 public $preview = false;
310 public $diff = false;
313 public $minoredit = false;
316 public $watchthis = false;
319 public $recreate = false;
322 public $textbox1 = '';
325 public $textbox2 = '';
328 public $summary = '';
331 public $nosummary = false;
334 public $edittime = '';
337 public $section = '';
340 public $sectiontitle = '';
343 public $starttime = '';
349 public $parentRevId = 0;
352 public $editintro = '';
355 public $scrolltop = null;
360 /** @var null|string */
361 public $contentModel = null;
363 /** @var null|string */
364 public $contentFormat = null;
366 /** @var null|array */
367 public $changeTags = null;
369 # Placeholders for text injection by hooks (must be HTML)
370 # extensions should take care to _append_ to the present value
372 /** @var string Before even the preview */
373 public $editFormPageTop = '';
374 public $editFormTextTop = '';
375 public $editFormTextBeforeContent = '';
376 public $editFormTextAfterWarn = '';
377 public $editFormTextAfterTools = '';
378 public $editFormTextBottom = '';
379 public $editFormTextAfterContent = '';
380 public $previewTextAfterContent = '';
381 public $mPreloadContent = null;
383 /* $didSave should be set to true whenever an article was successfully altered. */
384 public $didSave = false;
385 public $undidRev = 0;
387 public $suppressIntro = false;
393 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
395 private $enableApiEditOverride = false;
398 * @param Article $article
400 public function __construct( Article
$article ) {
401 $this->mArticle
= $article;
402 $this->mTitle
= $article->getTitle();
404 $this->contentModel
= $this->mTitle
->getContentModel();
406 $handler = ContentHandler
::getForModelID( $this->contentModel
);
407 $this->contentFormat
= $handler->getDefaultFormat();
413 public function getArticle() {
414 return $this->mArticle
;
421 public function getTitle() {
422 return $this->mTitle
;
426 * Set the context Title object
428 * @param Title|null $title Title object or null
430 public function setContextTitle( $title ) {
431 $this->mContextTitle
= $title;
435 * Get the context title object.
436 * If not set, $wgTitle will be returned. This behavior might change in
437 * the future to return $this->mTitle instead.
441 public function getContextTitle() {
442 if ( is_null( $this->mContextTitle
) ) {
446 return $this->mContextTitle
;
451 * Returns if the given content model is editable.
453 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
455 * @throws MWException If $modelId has no known handler
457 public function isSupportedContentModel( $modelId ) {
458 return $this->enableApiEditOverride
=== true ||
459 ContentHandler
::getForModelID( $modelId )->supportsDirectEditing();
463 * Allow editing of content that supports API direct editing, but not general
464 * direct editing. Set to false by default.
466 * @param bool $enableOverride
468 public function setApiEditOverride( $enableOverride ) {
469 $this->enableApiEditOverride
= $enableOverride;
477 * This is the function that gets called for "action=edit". It
478 * sets up various member variables, then passes execution to
479 * another function, usually showEditForm()
481 * The edit form is self-submitting, so that when things like
482 * preview and edit conflicts occur, we get the same form back
483 * with the extra stuff added. Only when the final submission
484 * is made and all is well do we actually save and redirect to
485 * the newly-edited page.
488 global $wgOut, $wgRequest, $wgUser;
489 // Allow extensions to modify/prevent this form or submission
490 if ( !Hooks
::run( 'AlternateEdit', array( $this ) ) ) {
494 wfDebug( __METHOD__
. ": enter\n" );
496 // If they used redlink=1 and the page exists, redirect to the main article
497 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
498 $wgOut->redirect( $this->mTitle
->getFullURL() );
502 $this->importFormData( $wgRequest );
503 $this->firsttime
= false;
505 if ( wfReadOnly() && $this->save
) {
508 $this->preview
= true;
512 $this->formtype
= 'save';
513 } elseif ( $this->preview
) {
514 $this->formtype
= 'preview';
515 } elseif ( $this->diff
) {
516 $this->formtype
= 'diff';
517 } else { # First time through
518 $this->firsttime
= true;
519 if ( $this->previewOnOpen() ) {
520 $this->formtype
= 'preview';
522 $this->formtype
= 'initial';
526 $permErrors = $this->getEditPermissionErrors( $this->save ?
'secure' : 'full' );
528 wfDebug( __METHOD__
. ": User can't edit\n" );
529 // Auto-block user's IP if the account was "hard" blocked
531 DeferredUpdates
::addCallableUpdate( function() use ( $user ) {
532 $user->spreadAnyEditBlock();
535 $this->displayPermissionsError( $permErrors );
540 $revision = $this->mArticle
->getRevisionFetched();
541 // Disallow editing revisions with content models different from the current one
542 if ( $revision && $revision->getContentModel() !== $this->contentModel
) {
543 $this->displayViewSourcePage(
544 $this->getContentObject(),
546 'contentmodelediterror',
547 $revision->getContentModel(),
554 $this->isConflict
= false;
555 // css / js subpages of user pages get a special treatment
556 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
557 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
558 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
559 // @todo FIXME: Silly assignment.
560 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
562 # Show applicable editing introductions
563 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
567 # Attempt submission here. This will check for edit conflicts,
568 # and redundantly check for locked database, blocked IPs, etc.
569 # that edit() already checked just in case someone tries to sneak
570 # in the back door with a hand-edited submission URL.
572 if ( 'save' == $this->formtype
) {
573 $resultDetails = null;
574 $status = $this->attemptSave( $resultDetails );
575 if ( !$this->handleStatus( $status, $resultDetails ) ) {
580 # First time through: get contents, set time for conflict
582 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
583 if ( $this->initialiseForm() === false ) {
584 $this->noSuchSectionPage();
588 if ( !$this->mTitle
->getArticleID() ) {
589 Hooks
::run( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
591 Hooks
::run( 'EditFormInitialText', array( $this ) );
596 $this->showEditForm();
600 * @param string $rigor Same format as Title::getUserPermissionErrors()
603 protected function getEditPermissionErrors( $rigor = 'secure' ) {
606 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
607 # Can this title be created?
608 if ( !$this->mTitle
->exists() ) {
609 $permErrors = array_merge(
612 $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
617 # Ignore some permissions errors when a user is just previewing/viewing diffs
619 foreach ( $permErrors as $error ) {
620 if ( ( $this->preview ||
$this->diff
)
621 && ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' )
626 $permErrors = wfArrayDiff2( $permErrors, $remove );
632 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
633 * but with the following differences:
634 * - If redlink=1, the user will be redirected to the page
635 * - If there is content to display or the error occurs while either saving,
636 * previewing or showing the difference, it will be a
637 * "View source for ..." page displaying the source code after the error message.
640 * @param array $permErrors Array of permissions errors, as returned by
641 * Title::getUserPermissionsErrors().
642 * @throws PermissionsError
644 protected function displayPermissionsError( array $permErrors ) {
645 global $wgRequest, $wgOut;
647 if ( $wgRequest->getBool( 'redlink' ) ) {
648 // The edit page was reached via a red link.
649 // Redirect to the article page and let them click the edit tab if
650 // they really want a permission error.
651 $wgOut->redirect( $this->mTitle
->getFullURL() );
655 $content = $this->getContentObject();
657 # Use the normal message if there's nothing to display
658 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
659 $action = $this->mTitle
->exists() ?
'edit' :
660 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
661 throw new PermissionsError( $action, $permErrors );
664 $this->displayViewSourcePage(
666 $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' )
671 * Display a read-only View Source page
672 * @param Content $content content object
673 * @param string $errorMessage additional wikitext error message to display
675 protected function displayViewSourcePage( Content
$content, $errorMessage = '' ) {
678 Hooks
::run( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
680 $wgOut->setRobotPolicy( 'noindex,nofollow' );
681 $wgOut->setPageTitle( wfMessage(
683 $this->getContextTitle()->getPrefixedText()
685 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
686 $wgOut->addHTML( $this->editFormPageTop
);
687 $wgOut->addHTML( $this->editFormTextTop
);
689 if ( $errorMessage !== '' ) {
690 $wgOut->addWikiText( $errorMessage );
691 $wgOut->addHTML( "<hr />\n" );
694 # If the user made changes, preserve them when showing the markup
695 # (This happens when a user is blocked during edit, for instance)
696 if ( !$this->firsttime
) {
697 $text = $this->textbox1
;
698 $wgOut->addWikiMsg( 'viewyourtext' );
701 $text = $this->toEditText( $content );
702 } catch ( MWException
$e ) {
703 # Serialize using the default format if the content model is not supported
704 # (e.g. for an old revision with a different model)
705 $text = $content->serialize();
707 $wgOut->addWikiMsg( 'viewsourcetext' );
710 $wgOut->addHTML( $this->editFormTextBeforeContent
);
711 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
712 $wgOut->addHTML( $this->editFormTextAfterContent
);
714 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
715 Linker
::formatTemplates( $this->getTemplates() ) ) );
717 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
719 $wgOut->addHTML( $this->editFormTextBottom
);
720 if ( $this->mTitle
->exists() ) {
721 $wgOut->returnToMain( null, $this->mTitle
);
726 * Should we show a preview when the edit form is first shown?
730 protected function previewOnOpen() {
731 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
732 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
733 // Explicit override from request
735 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
736 // Explicit override from request
738 } elseif ( $this->section
== 'new' ) {
739 // Nothing *to* preview for new sections
741 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
742 && $wgUser->getOption( 'previewonfirst' )
744 // Standard preference behavior
746 } elseif ( !$this->mTitle
->exists()
747 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
748 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
750 // Categories are special
758 * Checks whether the user entered a skin name in uppercase,
759 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
763 protected function isWrongCaseCssJsPage() {
764 if ( $this->mTitle
->isCssJsSubpage() ) {
765 $name = $this->mTitle
->getSkinFromCssJsSubpage();
766 $skins = array_merge(
767 array_keys( Skin
::getSkinNames() ),
770 return !in_array( $name, $skins )
771 && in_array( strtolower( $name ), $skins );
778 * Returns whether section editing is supported for the current page.
779 * Subclasses may override this to replace the default behavior, which is
780 * to check ContentHandler::supportsSections.
782 * @return bool True if this edit page supports sections, false otherwise.
784 protected function isSectionEditSupported() {
785 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
786 return $contentHandler->supportsSections();
790 * This function collects the form data and uses it to populate various member variables.
791 * @param WebRequest $request
792 * @throws ErrorPageError
794 function importFormData( &$request ) {
795 global $wgContLang, $wgUser;
797 # Section edit can come from either the form or a link
798 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
800 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
801 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
804 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
806 if ( $request->wasPosted() ) {
807 # These fields need to be checked for encoding.
808 # Also remove trailing whitespace, but don't remove _initial_
809 # whitespace from the text boxes. This may be significant formatting.
810 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
811 if ( !$request->getCheck( 'wpTextbox2' ) ) {
812 // Skip this if wpTextbox2 has input, it indicates that we came
813 // from a conflict page with raw page text, not a custom form
814 // modified by subclasses
815 $textbox1 = $this->importContentFormData( $request );
816 if ( $textbox1 !== null ) {
817 $this->textbox1
= $textbox1;
821 # Truncate for whole multibyte characters
822 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
824 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
825 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
827 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
829 # Treat sectiontitle the same way as summary.
830 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
831 # currently doing double duty as both edit summary and section title. Right now this
832 # is just to allow API edits to work around this limitation, but this should be
833 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
834 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
835 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
837 $this->edittime
= $request->getVal( 'wpEdittime' );
838 $this->starttime
= $request->getVal( 'wpStarttime' );
840 $undidRev = $request->getInt( 'wpUndidRevision' );
842 $this->undidRev
= $undidRev;
845 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
847 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
848 // wpTextbox1 field is missing, possibly due to being "too big"
849 // according to some filter rules such as Suhosin's setting for
850 // suhosin.request.max_value_length (d'oh)
851 $this->incompleteForm
= true;
853 // If we receive the last parameter of the request, we can fairly
854 // claim the POST request has not been truncated.
856 // TODO: softened the check for cutover. Once we determine
857 // that it is safe, we should complete the transition by
858 // removing the "edittime" clause.
859 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
860 && is_null( $this->edittime
) );
862 if ( $this->incompleteForm
) {
863 # If the form is incomplete, force to preview.
864 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
865 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
866 $this->preview
= true;
868 $this->preview
= $request->getCheck( 'wpPreview' );
869 $this->diff
= $request->getCheck( 'wpDiff' );
871 // Remember whether a save was requested, so we can indicate
872 // if we forced preview due to session failure.
873 $this->mTriedSave
= !$this->preview
;
875 if ( $this->tokenOk( $request ) ) {
876 # Some browsers will not report any submit button
877 # if the user hits enter in the comment box.
878 # The unmarked state will be assumed to be a save,
879 # if the form seems otherwise complete.
880 wfDebug( __METHOD__
. ": Passed token check.\n" );
881 } elseif ( $this->diff
) {
882 # Failed token check, but only requested "Show Changes".
883 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
885 # Page might be a hack attempt posted from
886 # an external site. Preview instead of saving.
887 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
888 $this->preview
= true;
891 $this->save
= !$this->preview
&& !$this->diff
;
892 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
893 $this->edittime
= null;
896 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
897 $this->starttime
= null;
900 $this->recreate
= $request->getCheck( 'wpRecreate' );
902 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
903 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
905 # Don't force edit summaries when a user is editing their own user or talk page
906 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
907 && $this->mTitle
->getText() == $wgUser->getName()
909 $this->allowBlankSummary
= true;
911 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
912 ||
!$wgUser->getOption( 'forceeditsummary' );
915 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
917 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
918 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
920 $changeTags = $request->getVal( 'wpChangeTags' );
921 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
922 $this->changeTags
= array();
924 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
928 # Not a posted form? Start with nothing.
929 wfDebug( __METHOD__
. ": Not a posted form.\n" );
930 $this->textbox1
= '';
932 $this->sectiontitle
= '';
933 $this->edittime
= '';
934 $this->starttime
= wfTimestampNow();
936 $this->preview
= false;
939 $this->minoredit
= false;
940 // Watch may be overridden by request parameters
941 $this->watchthis
= $request->getBool( 'watchthis', false );
942 $this->recreate
= false;
944 // When creating a new section, we can preload a section title by passing it as the
945 // preloadtitle parameter in the URL (Bug 13100)
946 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
947 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
948 // Once wpSummary isn't being use for setting section titles, we should delete this.
949 $this->summary
= $request->getVal( 'preloadtitle' );
950 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
951 $this->summary
= $request->getText( 'summary' );
952 if ( $this->summary
!== '' ) {
953 $this->hasPresetSummary
= true;
957 if ( $request->getVal( 'minor' ) ) {
958 $this->minoredit
= true;
962 $this->oldid
= $request->getInt( 'oldid' );
963 $this->parentRevId
= $request->getInt( 'parentRevId' );
965 $this->bot
= $request->getBool( 'bot', true );
966 $this->nosummary
= $request->getBool( 'nosummary' );
968 // May be overridden by revision.
969 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
970 // May be overridden by revision.
971 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
973 if ( !ContentHandler
::getForModelID( $this->contentModel
)
974 ->isSupportedFormat( $this->contentFormat
)
976 throw new ErrorPageError(
977 'editpage-notsupportedcontentformat-title',
978 'editpage-notsupportedcontentformat-text',
979 array( $this->contentFormat
, ContentHandler
::getLocalizedName( $this->contentModel
) )
984 * @todo Check if the desired model is allowed in this namespace, and if
985 * a transition from the page's current model to the new model is
989 $this->editintro
= $request->getText( 'editintro',
990 // Custom edit intro for new sections
991 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
993 // Allow extensions to modify form data
994 Hooks
::run( 'EditPage::importFormData', array( $this, $request ) );
999 * Subpage overridable method for extracting the page content data from the
1000 * posted form to be placed in $this->textbox1, if using customized input
1001 * this method should be overridden and return the page text that will be used
1002 * for saving, preview parsing and so on...
1004 * @param WebRequest $request
1006 protected function importContentFormData( &$request ) {
1007 return; // Don't do anything, EditPage already extracted wpTextbox1
1011 * Initialise form fields in the object
1012 * Called on the first invocation, e.g. when a user clicks an edit link
1013 * @return bool If the requested section is valid
1015 function initialiseForm() {
1017 $this->edittime
= $this->mArticle
->getTimestamp();
1019 $content = $this->getContentObject( false ); # TODO: track content object?!
1020 if ( $content === false ) {
1023 $this->textbox1
= $this->toEditText( $content );
1025 // activate checkboxes if user wants them to be always active
1026 # Sort out the "watch" checkbox
1027 if ( $wgUser->getOption( 'watchdefault' ) ) {
1029 $this->watchthis
= true;
1030 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1032 $this->watchthis
= true;
1033 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
1035 $this->watchthis
= true;
1037 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
1038 $this->minoredit
= true;
1040 if ( $this->textbox1
=== false ) {
1047 * @param Content|null $def_content The default value to return
1049 * @return Content|null Content on success, $def_content for invalid sections
1053 protected function getContentObject( $def_content = null ) {
1054 global $wgOut, $wgRequest, $wgUser, $wgContLang;
1058 // For message page not locally set, use the i18n message.
1059 // For other non-existent articles, use preload text if any.
1060 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1061 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1062 # If this is a system message, get the default text.
1063 $msg = $this->mTitle
->getDefaultMessageText();
1065 $content = $this->toEditContent( $msg );
1067 if ( $content === false ) {
1068 # If requested, preload some text.
1069 $preload = $wgRequest->getVal( 'preload',
1070 // Custom preload text for new sections
1071 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1072 $params = $wgRequest->getArray( 'preloadparams', array() );
1074 $content = $this->getPreloadedContent( $preload, $params );
1076 // For existing pages, get text based on "undo" or section parameters.
1078 if ( $this->section
!= '' ) {
1079 // Get section edit text (returns $def_text for invalid sections)
1080 $orig = $this->getOriginalContent( $wgUser );
1081 $content = $orig ?
$orig->getSection( $this->section
) : null;
1084 $content = $def_content;
1087 $undoafter = $wgRequest->getInt( 'undoafter' );
1088 $undo = $wgRequest->getInt( 'undo' );
1090 if ( $undo > 0 && $undoafter > 0 ) {
1091 $undorev = Revision
::newFromId( $undo );
1092 $oldrev = Revision
::newFromId( $undoafter );
1094 # Sanity check, make sure it's the right page,
1095 # the revisions exist and they were not deleted.
1096 # Otherwise, $content will be left as-is.
1097 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1098 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1099 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1101 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
1103 if ( $content === false ) {
1104 # Warn the user that something went wrong
1105 $undoMsg = 'failure';
1107 $oldContent = $this->mArticle
->getPage()->getContent( Revision
::RAW
);
1108 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
1109 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
1111 if ( $newContent->equals( $oldContent ) ) {
1112 # Tell the user that the undo results in no change,
1113 # i.e. the revisions were already undone.
1114 $undoMsg = 'nochange';
1117 # Inform the user of our success and set an automatic edit summary
1118 $undoMsg = 'success';
1120 # If we just undid one rev, use an autosummary
1121 $firstrev = $oldrev->getNext();
1122 if ( $firstrev && $firstrev->getId() == $undo ) {
1123 $userText = $undorev->getUserText();
1124 if ( $userText === '' ) {
1125 $undoSummary = wfMessage(
1126 'undo-summary-username-hidden',
1128 )->inContentLanguage()->text();
1130 $undoSummary = wfMessage(
1134 )->inContentLanguage()->text();
1136 if ( $this->summary
=== '' ) {
1137 $this->summary
= $undoSummary;
1139 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
1140 ->inContentLanguage()->text() . $this->summary
;
1142 $this->undidRev
= $undo;
1144 $this->formtype
= 'diff';
1148 // Failed basic sanity checks.
1149 // Older revisions may have been removed since the link
1150 // was created, or we may simply have got bogus input.
1154 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1155 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1156 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
1157 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1160 if ( $content === false ) {
1161 $content = $this->getOriginalContent( $wgUser );
1170 * Get the content of the wanted revision, without section extraction.
1172 * The result of this function can be used to compare user's input with
1173 * section replaced in its context (using WikiPage::replaceSection())
1174 * to the original text of the edit.
1176 * This differs from Article::getContent() that when a missing revision is
1177 * encountered the result will be null and not the
1178 * 'missing-revision' message.
1181 * @param User $user The user to get the revision for
1182 * @return Content|null
1184 private function getOriginalContent( User
$user ) {
1185 if ( $this->section
== 'new' ) {
1186 return $this->getCurrentContent();
1188 $revision = $this->mArticle
->getRevisionFetched();
1189 if ( $revision === null ) {
1190 if ( !$this->contentModel
) {
1191 $this->contentModel
= $this->getTitle()->getContentModel();
1193 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1195 return $handler->makeEmptyContent();
1197 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1202 * Get the edit's parent revision ID
1204 * The "parent" revision is the ancestor that should be recorded in this
1205 * page's revision history. It is either the revision ID of the in-memory
1206 * article content, or in the case of a 3-way merge in order to rebase
1207 * across a recoverable edit conflict, the ID of the newer revision to
1208 * which we have rebased this page.
1211 * @return int Revision ID
1213 public function getParentRevId() {
1214 if ( $this->parentRevId
) {
1215 return $this->parentRevId
;
1217 return $this->mArticle
->getRevIdFetched();
1222 * Get the current content of the page. This is basically similar to
1223 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1224 * content object is returned instead of null.
1229 protected function getCurrentContent() {
1230 $rev = $this->mArticle
->getRevision();
1231 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1233 if ( $content === false ||
$content === null ) {
1234 if ( !$this->contentModel
) {
1235 $this->contentModel
= $this->getTitle()->getContentModel();
1237 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1239 return $handler->makeEmptyContent();
1241 # nasty side-effect, but needed for consistency
1242 $this->contentModel
= $rev->getContentModel();
1243 $this->contentFormat
= $rev->getContentFormat();
1250 * Use this method before edit() to preload some content into the edit box
1252 * @param Content $content
1256 public function setPreloadedContent( Content
$content ) {
1257 $this->mPreloadContent
= $content;
1261 * Get the contents to be preloaded into the box, either set by
1262 * an earlier setPreloadText() or by loading the given page.
1264 * @param string $preload Representing the title to preload from.
1265 * @param array $params Parameters to use (interface-message style) in the preloaded text
1271 protected function getPreloadedContent( $preload, $params = array() ) {
1274 if ( !empty( $this->mPreloadContent
) ) {
1275 return $this->mPreloadContent
;
1278 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1280 if ( $preload === '' ) {
1281 return $handler->makeEmptyContent();
1284 $title = Title
::newFromText( $preload );
1285 # Check for existence to avoid getting MediaWiki:Noarticletext
1286 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1287 // TODO: somehow show a warning to the user!
1288 return $handler->makeEmptyContent();
1291 $page = WikiPage
::factory( $title );
1292 if ( $page->isRedirect() ) {
1293 $title = $page->getRedirectTarget();
1295 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1296 // TODO: somehow show a warning to the user!
1297 return $handler->makeEmptyContent();
1299 $page = WikiPage
::factory( $title );
1302 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1303 $content = $page->getContent( Revision
::RAW
);
1306 // TODO: somehow show a warning to the user!
1307 return $handler->makeEmptyContent();
1310 if ( $content->getModel() !== $handler->getModelID() ) {
1311 $converted = $content->convert( $handler->getModelID() );
1313 if ( !$converted ) {
1314 // TODO: somehow show a warning to the user!
1315 wfDebug( "Attempt to preload incompatible content: " .
1316 "can't convert " . $content->getModel() .
1317 " to " . $handler->getModelID() );
1319 return $handler->makeEmptyContent();
1322 $content = $converted;
1325 return $content->preloadTransform( $title, $parserOptions, $params );
1329 * Make sure the form isn't faking a user's credentials.
1331 * @param WebRequest $request
1335 function tokenOk( &$request ) {
1337 $token = $request->getVal( 'wpEditToken' );
1338 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1339 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1340 return $this->mTokenOk
;
1344 * Sets post-edit cookie indicating the user just saved a particular revision.
1346 * This uses a temporary cookie for each revision ID so separate saves will never
1347 * interfere with each other.
1349 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1350 * the redirect. It must be clearable by JavaScript code, so it must not be
1351 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1354 * If the variable were set on the server, it would be cached, which is unwanted
1355 * since the post-edit state should only apply to the load right after the save.
1357 * @param int $statusValue The status value (to check for new article status)
1359 protected function setPostEditCookie( $statusValue ) {
1360 $revisionId = $this->mArticle
->getLatest();
1361 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1364 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1366 } elseif ( $this->oldid
) {
1370 $response = RequestContext
::getMain()->getRequest()->response();
1371 $response->setCookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
, array(
1372 'httpOnly' => false,
1377 * Attempt submission
1378 * @param array $resultDetails See docs for $result in internalAttemptSave
1379 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1380 * @return Status The resulting status object.
1382 public function attemptSave( &$resultDetails = false ) {
1385 # Allow bots to exempt some edits from bot flagging
1386 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1387 $status = $this->internalAttemptSave( $resultDetails, $bot );
1389 Hooks
::run( 'EditPage::attemptSave:after', array( $this, $status, $resultDetails ) );
1395 * Handle status, such as after attempt save
1397 * @param Status $status
1398 * @param array|bool $resultDetails
1400 * @throws ErrorPageError
1401 * @return bool False, if output is done, true if rest of the form should be displayed
1403 private function handleStatus( Status
$status, $resultDetails ) {
1404 global $wgUser, $wgOut;
1407 * @todo FIXME: once the interface for internalAttemptSave() is made
1408 * nicer, this should use the message in $status
1410 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1411 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1413 $this->didSave
= true;
1414 if ( !$resultDetails['nullEdit'] ) {
1415 $this->setPostEditCookie( $status->value
);
1419 switch ( $status->value
) {
1420 case self
::AS_HOOK_ERROR_EXPECTED
:
1421 case self
::AS_CONTENT_TOO_BIG
:
1422 case self
::AS_ARTICLE_WAS_DELETED
:
1423 case self
::AS_CONFLICT_DETECTED
:
1424 case self
::AS_SUMMARY_NEEDED
:
1425 case self
::AS_TEXTBOX_EMPTY
:
1426 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1428 case self
::AS_BLANK_ARTICLE
:
1429 case self
::AS_SELF_REDIRECT
:
1432 case self
::AS_HOOK_ERROR
:
1435 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1436 case self
::AS_PARSE_ERROR
:
1437 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1440 case self
::AS_SUCCESS_NEW_ARTICLE
:
1441 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1442 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1443 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1446 case self
::AS_SUCCESS_UPDATE
:
1448 $sectionanchor = $resultDetails['sectionanchor'];
1450 // Give extensions a chance to modify URL query on update
1452 'ArticleUpdateBeforeRedirect',
1453 array( $this->mArticle
, &$sectionanchor, &$extraQuery )
1456 if ( $resultDetails['redirect'] ) {
1457 if ( $extraQuery == '' ) {
1458 $extraQuery = 'redirect=no';
1460 $extraQuery = 'redirect=no&' . $extraQuery;
1463 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1466 case self
::AS_SPAM_ERROR
:
1467 $this->spamPageWithContent( $resultDetails['spam'] );
1470 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1471 throw new UserBlockedError( $wgUser->getBlock() );
1473 case self
::AS_IMAGE_REDIRECT_ANON
:
1474 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1475 throw new PermissionsError( 'upload' );
1477 case self
::AS_READ_ONLY_PAGE_ANON
:
1478 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1479 throw new PermissionsError( 'edit' );
1481 case self
::AS_READ_ONLY_PAGE
:
1482 throw new ReadOnlyError
;
1484 case self
::AS_RATE_LIMITED
:
1485 throw new ThrottledError();
1487 case self
::AS_NO_CREATE_PERMISSION
:
1488 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1489 throw new PermissionsError( $permission );
1491 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1492 throw new PermissionsError( 'editcontentmodel' );
1495 // We don't recognize $status->value. The only way that can happen
1496 // is if an extension hook aborted from inside ArticleSave.
1497 // Render the status object into $this->hookError
1498 // FIXME this sucks, we should just use the Status object throughout
1499 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1506 * Run hooks that can filter edits just before they get saved.
1508 * @param Content $content The Content to filter.
1509 * @param Status $status For reporting the outcome to the caller
1510 * @param User $user The user performing the edit
1514 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1515 // Run old style post-section-merge edit filter
1516 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1517 array( $this, $content, &$this->hookError
, $this->summary
) )
1519 # Error messages etc. could be handled within the hook...
1520 $status->fatal( 'hookaborted' );
1521 $status->value
= self
::AS_HOOK_ERROR
;
1523 } elseif ( $this->hookError
!= '' ) {
1524 # ...or the hook could be expecting us to produce an error
1525 $status->fatal( 'hookaborted' );
1526 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1530 // Run new style post-section-merge edit filter
1531 if ( !Hooks
::run( 'EditFilterMergedContent',
1532 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1533 $user, $this->minoredit
) )
1535 # Error messages etc. could be handled within the hook...
1536 if ( $status->isGood() ) {
1537 $status->fatal( 'hookaborted' );
1538 // Not setting $this->hookError here is a hack to allow the hook
1539 // to cause a return to the edit page without $this->hookError
1540 // being set. This is used by ConfirmEdit to display a captcha
1541 // without any error message cruft.
1543 $this->hookError
= $status->getWikiText();
1545 // Use the existing $status->value if the hook set it
1546 if ( !$status->value
) {
1547 $status->value
= self
::AS_HOOK_ERROR
;
1550 } elseif ( !$status->isOK() ) {
1551 # ...or the hook could be expecting us to produce an error
1552 // FIXME this sucks, we should just use the Status object throughout
1553 $this->hookError
= $status->getWikiText();
1554 $status->fatal( 'hookaborted' );
1555 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1563 * Return the summary to be used for a new section.
1565 * @param string $sectionanchor Set to the section anchor text
1568 private function newSectionSummary( &$sectionanchor = null ) {
1571 if ( $this->sectiontitle
!== '' ) {
1572 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1573 // If no edit summary was specified, create one automatically from the section
1574 // title and have it link to the new section. Otherwise, respect the summary as
1576 if ( $this->summary
=== '' ) {
1577 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1578 return wfMessage( 'newsectionsummary' )
1579 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1581 } elseif ( $this->summary
!== '' ) {
1582 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1583 # This is a new section, so create a link to the new section
1584 # in the revision summary.
1585 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1586 return wfMessage( 'newsectionsummary' )
1587 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1589 return $this->summary
;
1593 * Attempt submission (no UI)
1595 * @param array $result Array to add statuses to, currently with the
1597 * - spam (string): Spam string from content if any spam is detected by
1599 * - sectionanchor (string): Section anchor for a section save.
1600 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1602 * - redirect (bool): Set if doEditContent is OK. True if resulting
1603 * revision is a redirect.
1604 * @param bool $bot True if edit is being made under the bot right.
1606 * @return Status Status object, possibly with a message, but always with
1607 * one of the AS_* constants in $status->value,
1609 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1610 * various error display idiosyncrasies. There are also lots of cases
1611 * where error metadata is set in the object and retrieved later instead
1612 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1613 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1616 function internalAttemptSave( &$result, $bot = false ) {
1617 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1618 global $wgContentHandlerUseDB;
1620 $status = Status
::newGood();
1622 if ( !Hooks
::run( 'EditPage::attemptSave', array( $this ) ) ) {
1623 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1624 $status->fatal( 'hookaborted' );
1625 $status->value
= self
::AS_HOOK_ERROR
;
1629 $spam = $wgRequest->getText( 'wpAntispam' );
1630 if ( $spam !== '' ) {
1633 $wgUser->getName() .
1635 $this->mTitle
->getPrefixedText() .
1636 '" submitted bogus field "' .
1640 $status->fatal( 'spamprotectionmatch', false );
1641 $status->value
= self
::AS_SPAM_ERROR
;
1646 # Construct Content object
1647 $textbox_content = $this->toEditContent( $this->textbox1
);
1648 } catch ( MWContentSerializationException
$ex ) {
1650 'content-failed-to-parse',
1651 $this->contentModel
,
1652 $this->contentFormat
,
1655 $status->value
= self
::AS_PARSE_ERROR
;
1659 # Check image redirect
1660 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1661 $textbox_content->isRedirect() &&
1662 !$wgUser->isAllowed( 'upload' )
1664 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1665 $status->setResult( false, $code );
1671 $match = self
::matchSummarySpamRegex( $this->summary
);
1672 if ( $match === false && $this->section
== 'new' ) {
1673 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1674 # regular summaries, it is added to the actual wikitext.
1675 if ( $this->sectiontitle
!== '' ) {
1676 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1677 $match = self
::matchSpamRegex( $this->sectiontitle
);
1679 # This branch is taken when the "Add Topic" user interface is used, or the API
1680 # is used with the 'summary' parameter.
1681 $match = self
::matchSpamRegex( $this->summary
);
1684 if ( $match === false ) {
1685 $match = self
::matchSpamRegex( $this->textbox1
);
1687 if ( $match !== false ) {
1688 $result['spam'] = $match;
1689 $ip = $wgRequest->getIP();
1690 $pdbk = $this->mTitle
->getPrefixedDBkey();
1691 $match = str_replace( "\n", '', $match );
1692 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1693 $status->fatal( 'spamprotectionmatch', $match );
1694 $status->value
= self
::AS_SPAM_ERROR
;
1699 array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) )
1701 # Error messages etc. could be handled within the hook...
1702 $status->fatal( 'hookaborted' );
1703 $status->value
= self
::AS_HOOK_ERROR
;
1705 } elseif ( $this->hookError
!= '' ) {
1706 # ...or the hook could be expecting us to produce an error
1707 $status->fatal( 'hookaborted' );
1708 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1712 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1713 // Auto-block user's IP if the account was "hard" blocked
1714 $wgUser->spreadAnyEditBlock();
1715 # Check block state against master, thus 'false'.
1716 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1720 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1721 if ( $this->kblength
> $wgMaxArticleSize ) {
1722 // Error will be displayed by showEditForm()
1723 $this->tooBig
= true;
1724 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1728 if ( !$wgUser->isAllowed( 'edit' ) ) {
1729 if ( $wgUser->isAnon() ) {
1730 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1733 $status->fatal( 'readonlytext' );
1734 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1739 $changingContentModel = false;
1740 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1741 if ( !$wgContentHandlerUseDB ) {
1742 $status->fatal( 'editpage-cannot-use-custom-model' );
1743 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1745 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1746 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1750 $changingContentModel = true;
1751 $oldContentModel = $this->mTitle
->getContentModel();
1754 if ( $this->changeTags
) {
1755 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1756 $this->changeTags
, $wgUser );
1757 if ( !$changeTagsStatus->isOK() ) {
1758 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1759 return $changeTagsStatus;
1763 if ( wfReadOnly() ) {
1764 $status->fatal( 'readonlytext' );
1765 $status->value
= self
::AS_READ_ONLY_PAGE
;
1768 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1769 $status->fatal( 'actionthrottledtext' );
1770 $status->value
= self
::AS_RATE_LIMITED
;
1774 # If the article has been deleted while editing, don't save it without
1776 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1777 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1781 # Load the page data from the master. If anything changes in the meantime,
1782 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1783 $this->mArticle
->loadPageData( 'fromdbmaster' );
1784 $new = !$this->mArticle
->exists();
1787 // Late check for create permission, just in case *PARANOIA*
1788 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1789 $status->fatal( 'nocreatetext' );
1790 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1791 wfDebug( __METHOD__
. ": no create permission\n" );
1795 // Don't save a new page if it's blank or if it's a MediaWiki:
1796 // message with content equivalent to default (allow empty pages
1797 // in this case to disable messages, see bug 50124)
1798 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1799 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1800 $defaultText = $defaultMessageText;
1805 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1806 $this->blankArticle
= true;
1807 $status->fatal( 'blankarticle' );
1808 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1812 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1816 $content = $textbox_content;
1818 $result['sectionanchor'] = '';
1819 if ( $this->section
== 'new' ) {
1820 if ( $this->sectiontitle
!== '' ) {
1821 // Insert the section title above the content.
1822 $content = $content->addSectionHeader( $this->sectiontitle
);
1823 } elseif ( $this->summary
!== '' ) {
1824 // Insert the section title above the content.
1825 $content = $content->addSectionHeader( $this->summary
);
1827 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1830 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1834 # Article exists. Check for edit conflict.
1836 $this->mArticle
->clear(); # Force reload of dates, etc.
1837 $timestamp = $this->mArticle
->getTimestamp();
1839 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1841 if ( $timestamp != $this->edittime
) {
1842 $this->isConflict
= true;
1843 if ( $this->section
== 'new' ) {
1844 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1845 $this->mArticle
->getComment() == $this->newSectionSummary()
1847 // Probably a duplicate submission of a new comment.
1848 // This can happen when squid resends a request after
1849 // a timeout but the first one actually went through.
1851 . ": duplicate new section submission; trigger edit conflict!\n" );
1853 // New comment; suppress conflict.
1854 $this->isConflict
= false;
1855 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1857 } elseif ( $this->section
== ''
1858 && Revision
::userWasLastToEdit(
1859 DB_MASTER
, $this->mTitle
->getArticleID(),
1860 $wgUser->getId(), $this->edittime
1863 # Suppress edit conflict with self, except for section edits where merging is required.
1864 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1865 $this->isConflict
= false;
1869 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1870 if ( $this->sectiontitle
!== '' ) {
1871 $sectionTitle = $this->sectiontitle
;
1873 $sectionTitle = $this->summary
;
1878 if ( $this->isConflict
) {
1880 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1881 . " (article time '{$timestamp}')\n" );
1883 $content = $this->mArticle
->replaceSectionContent(
1890 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1891 $content = $this->mArticle
->replaceSectionContent(
1898 if ( is_null( $content ) ) {
1899 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1900 $this->isConflict
= true;
1901 $content = $textbox_content; // do not try to merge here!
1902 } elseif ( $this->isConflict
) {
1904 if ( $this->mergeChangesIntoContent( $content ) ) {
1905 // Successful merge! Maybe we should tell the user the good news?
1906 $this->isConflict
= false;
1907 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1909 $this->section
= '';
1910 $this->textbox1
= ContentHandler
::getContentText( $content );
1911 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1915 if ( $this->isConflict
) {
1916 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1920 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1924 if ( $this->section
== 'new' ) {
1925 // Handle the user preference to force summaries here
1926 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1927 $this->missingSummary
= true;
1928 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1929 $status->value
= self
::AS_SUMMARY_NEEDED
;
1933 // Do not allow the user to post an empty comment
1934 if ( $this->textbox1
== '' ) {
1935 $this->missingComment
= true;
1936 $status->fatal( 'missingcommenttext' );
1937 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1940 } elseif ( !$this->allowBlankSummary
1941 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1942 && !$content->isRedirect()
1943 && md5( $this->summary
) == $this->autoSumm
1945 $this->missingSummary
= true;
1946 $status->fatal( 'missingsummary' );
1947 $status->value
= self
::AS_SUMMARY_NEEDED
;
1952 $sectionanchor = '';
1953 if ( $this->section
== 'new' ) {
1954 $this->summary
= $this->newSectionSummary( $sectionanchor );
1955 } elseif ( $this->section
!= '' ) {
1956 # Try to get a section anchor from the section source, redirect
1957 # to edited section if header found.
1958 # XXX: Might be better to integrate this into Article::replaceSection
1959 # for duplicate heading checking and maybe parsing.
1960 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1961 # We can't deal with anchors, includes, html etc in the header for now,
1962 # headline would need to be parsed to improve this.
1963 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1964 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1967 $result['sectionanchor'] = $sectionanchor;
1969 // Save errors may fall down to the edit form, but we've now
1970 // merged the section into full text. Clear the section field
1971 // so that later submission of conflict forms won't try to
1972 // replace that into a duplicated mess.
1973 $this->textbox1
= $this->toEditText( $content );
1974 $this->section
= '';
1976 $status->value
= self
::AS_SUCCESS_UPDATE
;
1979 if ( !$this->allowSelfRedirect
1980 && $content->isRedirect()
1981 && $content->getRedirectTarget()->equals( $this->getTitle() )
1983 // If the page already redirects to itself, don't warn.
1984 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
1985 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
1986 $this->selfRedirect
= true;
1987 $status->fatal( 'selfredirect' );
1988 $status->value
= self
::AS_SELF_REDIRECT
;
1993 // Check for length errors again now that the section is merged in
1994 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1995 if ( $this->kblength
> $wgMaxArticleSize ) {
1996 $this->tooBig
= true;
1997 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
2001 $flags = EDIT_AUTOSUMMARY |
2002 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
2003 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
2004 ( $bot ? EDIT_FORCE_BOT
: 0 );
2006 $doEditStatus = $this->mArticle
->doEditContent(
2012 $content->getDefaultFormat()
2015 if ( !$doEditStatus->isOK() ) {
2016 // Failure from doEdit()
2017 // Show the edit conflict page for certain recognized errors from doEdit(),
2018 // but don't show it for errors from extension hooks
2019 $errors = $doEditStatus->getErrorsArray();
2020 if ( in_array( $errors[0][0],
2021 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
2023 $this->isConflict
= true;
2024 // Destroys data doEdit() put in $status->value but who cares
2025 $doEditStatus->value
= self
::AS_END
;
2027 return $doEditStatus;
2030 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2031 if ( $result['nullEdit'] ) {
2032 // We don't know if it was a null edit until now, so increment here
2033 $wgUser->pingLimiter( 'linkpurge' );
2035 $result['redirect'] = $content->isRedirect();
2037 $this->updateWatchlist();
2039 if ( $this->changeTags
&& isset( $doEditStatus->value
['revision'] ) ) {
2040 // If a revision was created, apply any change tags that were requested
2041 $addTags = $this->changeTags
;
2042 $revId = $doEditStatus->value
['revision']->getId();
2043 // Defer this both for performance and so that addTags() sees the rc_id
2044 // since the recentchange entry addition is deferred first (bug T100248)
2045 DeferredUpdates
::addCallableUpdate( function() use ( $addTags, $revId ) {
2046 ChangeTags
::addTags( $addTags, null, $revId );
2050 // If the content model changed, add a log entry
2051 if ( $changingContentModel ) {
2052 $this->addContentModelChangeLogEntry(
2055 $this->contentModel
,
2065 * @param string $oldModel
2066 * @param string $newModel
2067 * @param string $reason
2069 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2070 $log = new ManualLogEntry( 'contentmodel', 'change' );
2071 $log->setPerformer( $user );
2072 $log->setTarget( $this->mTitle
);
2073 $log->setComment( $reason );
2074 $log->setParameters( array(
2075 '4::oldmodel' => $oldModel,
2076 '5::newmodel' => $newModel
2078 $logid = $log->insert();
2079 $log->publish( $logid );
2083 * Register the change of watch status
2085 protected function updateWatchlist() {
2088 if ( !$wgUser->isLoggedIn() ) {
2093 $title = $this->mTitle
;
2094 $watch = $this->watchthis
;
2095 // Do this in its own transaction to reduce contention...
2096 DeferredUpdates
::addCallableUpdate( function () use ( $user, $title, $watch ) {
2097 if ( $watch == $user->isWatched( $title, WatchedItem
::IGNORE_USER_RIGHTS
) ) {
2098 return; // nothing to change
2100 WatchAction
::doWatchOrUnwatch( $watch, $title, $user );
2105 * Attempts to do 3-way merge of edit content with a base revision
2106 * and current content, in case of edit conflict, in whichever way appropriate
2107 * for the content type.
2111 * @param Content $editContent
2115 private function mergeChangesIntoContent( &$editContent ) {
2117 $db = wfGetDB( DB_MASTER
);
2119 // This is the revision the editor started from
2120 $baseRevision = $this->getBaseRevision();
2121 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2123 if ( is_null( $baseContent ) ) {
2127 // The current state, we want to merge updates into it
2128 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2129 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2131 if ( is_null( $currentContent ) ) {
2135 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2137 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2140 $editContent = $result;
2141 // Update parentRevId to what we just merged.
2142 $this->parentRevId
= $currentRevision->getId();
2152 function getBaseRevision() {
2153 if ( !$this->mBaseRevision
) {
2154 $db = wfGetDB( DB_MASTER
);
2155 $this->mBaseRevision
= Revision
::loadFromTimestamp(
2156 $db, $this->mTitle
, $this->edittime
);
2158 return $this->mBaseRevision
;
2162 * Check given input text against $wgSpamRegex, and return the text of the first match.
2164 * @param string $text
2166 * @return string|bool Matching string or false
2168 public static function matchSpamRegex( $text ) {
2169 global $wgSpamRegex;
2170 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2171 $regexes = (array)$wgSpamRegex;
2172 return self
::matchSpamRegexInternal( $text, $regexes );
2176 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2178 * @param string $text
2180 * @return string|bool Matching string or false
2182 public static function matchSummarySpamRegex( $text ) {
2183 global $wgSummarySpamRegex;
2184 $regexes = (array)$wgSummarySpamRegex;
2185 return self
::matchSpamRegexInternal( $text, $regexes );
2189 * @param string $text
2190 * @param array $regexes
2191 * @return bool|string
2193 protected static function matchSpamRegexInternal( $text, $regexes ) {
2194 foreach ( $regexes as $regex ) {
2196 if ( preg_match( $regex, $text, $matches ) ) {
2203 function setHeaders() {
2204 global $wgOut, $wgUser, $wgAjaxEditStash;
2206 $wgOut->addModules( 'mediawiki.action.edit' );
2207 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2209 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2210 // The addition of default buttons is handled by getEditToolbar() which
2211 // has its own dependency on this module. The call here ensures the module
2212 // is loaded in time (it has position "top") for other modules to register
2213 // buttons (e.g. extensions, gadgets, user scripts).
2214 $wgOut->addModules( 'mediawiki.toolbar' );
2217 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2218 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2221 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2222 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2225 if ( $wgAjaxEditStash ) {
2226 $wgOut->addModules( 'mediawiki.action.edit.stash' );
2229 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2231 # Enabled article-related sidebar, toplinks, etc.
2232 $wgOut->setArticleRelated( true );
2234 $contextTitle = $this->getContextTitle();
2235 if ( $this->isConflict
) {
2236 $msg = 'editconflict';
2237 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2238 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2240 $msg = $contextTitle->exists()
2241 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2242 && $contextTitle->getDefaultMessageText() !== false
2248 # Use the title defined by DISPLAYTITLE magic word when present
2249 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2250 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2251 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2252 if ( $displayTitle === false ) {
2253 $displayTitle = $contextTitle->getPrefixedText();
2255 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2256 # Transmit the name of the message to JavaScript for live preview
2257 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2258 $wgOut->addJsConfigVars( 'wgEditMessage', $msg );
2262 * Show all applicable editing introductions
2264 protected function showIntro() {
2265 global $wgOut, $wgUser;
2266 if ( $this->suppressIntro
) {
2270 $namespace = $this->mTitle
->getNamespace();
2272 if ( $namespace == NS_MEDIAWIKI
) {
2273 # Show a warning if editing an interface message
2274 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2275 # If this is a default message (but not css or js),
2276 # show a hint that it is translatable on translatewiki.net
2277 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2278 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2280 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2281 if ( $defaultMessageText !== false ) {
2282 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2283 'translateinterface' );
2286 } elseif ( $namespace == NS_FILE
) {
2287 # Show a hint to shared repo
2288 $file = wfFindFile( $this->mTitle
);
2289 if ( $file && !$file->isLocal() ) {
2290 $descUrl = $file->getDescriptionUrl();
2291 # there must be a description url to show a hint to shared repo
2293 if ( !$this->mTitle
->exists() ) {
2294 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2295 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2298 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2299 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2306 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2307 # Show log extract when the user is currently blocked
2308 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2309 $parts = explode( '/', $this->mTitle
->getText(), 2 );
2310 $username = $parts[0];
2311 $user = User
::newFromName( $username, false /* allow IP users*/ );
2312 $ip = User
::isIP( $username );
2313 $block = Block
::newFromTarget( $user, $user );
2314 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2315 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2316 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2317 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2318 # Show log extract if the user is currently blocked
2319 LogEventsList
::showLogExtract(
2322 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2326 'showIfEmpty' => false,
2328 'blocked-notice-logextract',
2329 $user->getName() # Support GENDER in notice
2335 # Try to add a custom edit intro, or use the standard one if this is not possible.
2336 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2337 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2338 wfMessage( 'helppage' )->inContentLanguage()->text()
2340 if ( $wgUser->isLoggedIn() ) {
2341 $wgOut->wrapWikiMsg(
2342 // Suppress the external link icon, consider the help url an internal one
2343 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2350 $wgOut->wrapWikiMsg(
2351 // Suppress the external link icon, consider the help url an internal one
2352 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2354 'newarticletextanon',
2360 # Give a notice if the user is editing a deleted/moved page...
2361 if ( !$this->mTitle
->exists() ) {
2362 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
2366 'conds' => array( "log_action != 'revision'" ),
2367 'showIfEmpty' => false,
2368 'msgKey' => array( 'recreate-moveddeleted-warn' )
2375 * Attempt to show a custom editing introduction, if supplied
2379 protected function showCustomIntro() {
2380 if ( $this->editintro
) {
2381 $title = Title
::newFromText( $this->editintro
);
2382 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2384 // Added using template syntax, to take <noinclude>'s into account.
2385 $wgOut->addWikiTextTitleTidy(
2386 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2396 * Gets an editable textual representation of $content.
2397 * The textual representation can be turned by into a Content object by the
2398 * toEditContent() method.
2400 * If $content is null or false or a string, $content is returned unchanged.
2402 * If the given Content object is not of a type that can be edited using
2403 * the text base EditPage, an exception will be raised. Set
2404 * $this->allowNonTextContent to true to allow editing of non-textual
2407 * @param Content|null|bool|string $content
2408 * @return string The editable text form of the content.
2410 * @throws MWException If $content is not an instance of TextContent and
2411 * $this->allowNonTextContent is not true.
2413 protected function toEditText( $content ) {
2414 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2418 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2419 throw new MWException( 'This content model is not supported: '
2420 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2423 return $content->serialize( $this->contentFormat
);
2427 * Turns the given text into a Content object by unserializing it.
2429 * If the resulting Content object is not of a type that can be edited using
2430 * the text base EditPage, an exception will be raised. Set
2431 * $this->allowNonTextContent to true to allow editing of non-textual
2434 * @param string|null|bool $text Text to unserialize
2435 * @return Content The content object created from $text. If $text was false
2436 * or null, false resp. null will be returned instead.
2438 * @throws MWException If unserializing the text results in a Content
2439 * object that is not an instance of TextContent and
2440 * $this->allowNonTextContent is not true.
2442 protected function toEditContent( $text ) {
2443 if ( $text === false ||
$text === null ) {
2447 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2448 $this->contentModel
, $this->contentFormat
);
2450 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2451 throw new MWException( 'This content model is not supported: '
2452 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2459 * Send the edit form and related headers to $wgOut
2460 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2461 * during form output near the top, for captchas and the like.
2463 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2464 * use the EditPage::showEditForm:fields hook instead.
2466 function showEditForm( $formCallback = null ) {
2467 global $wgOut, $wgUser;
2469 # need to parse the preview early so that we know which templates are used,
2470 # otherwise users with "show preview after edit box" will get a blank list
2471 # we parse this near the beginning so that setHeaders can do the title
2472 # setting work instead of leaving it in getPreviewText
2473 $previewOutput = '';
2474 if ( $this->formtype
== 'preview' ) {
2475 $previewOutput = $this->getPreviewText();
2478 Hooks
::run( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2480 $this->setHeaders();
2482 if ( $this->showHeader() === false ) {
2486 $wgOut->addHTML( $this->editFormPageTop
);
2488 if ( $wgUser->getOption( 'previewontop' ) ) {
2489 $this->displayPreviewArea( $previewOutput, true );
2492 $wgOut->addHTML( $this->editFormTextTop
);
2494 $showToolbar = true;
2495 if ( $this->wasDeletedSinceLastEdit() ) {
2496 if ( $this->formtype
== 'save' ) {
2497 // Hide the toolbar and edit area, user can click preview to get it back
2498 // Add an confirmation checkbox and explanation.
2499 $showToolbar = false;
2501 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2502 'deletedwhileediting' );
2506 // @todo add EditForm plugin interface and use it here!
2507 // search for textarea1 and textares2, and allow EditForm to override all uses.
2508 $wgOut->addHTML( Html
::openElement(
2511 'id' => self
::EDITFORM_ID
,
2512 'name' => self
::EDITFORM_ID
,
2514 'action' => $this->getActionURL( $this->getContextTitle() ),
2515 'enctype' => 'multipart/form-data'
2519 if ( is_callable( $formCallback ) ) {
2520 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2521 call_user_func_array( $formCallback, array( &$wgOut ) );
2524 // Add an empty field to trip up spambots
2526 Xml
::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2529 array( 'for' => 'wpAntiSpam' ),
2530 wfMessage( 'simpleantispam-label' )->parse()
2536 'name' => 'wpAntispam',
2537 'id' => 'wpAntispam',
2541 . Xml
::closeElement( 'div' )
2544 Hooks
::run( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2546 // Put these up at the top to ensure they aren't lost on early form submission
2547 $this->showFormBeforeText();
2549 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2550 $username = $this->lastDelete
->user_name
;
2551 $comment = $this->lastDelete
->log_comment
;
2553 // It is better to not parse the comment at all than to have templates expanded in the middle
2554 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2555 $key = $comment === ''
2556 ?
'confirmrecreate-noreason'
2557 : 'confirmrecreate';
2559 '<div class="mw-confirm-recreate">' .
2560 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2561 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2562 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2568 # When the summary is hidden, also hide them on preview/show changes
2569 if ( $this->nosummary
) {
2570 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2573 # If a blank edit summary was previously provided, and the appropriate
2574 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2575 # user being bounced back more than once in the event that a summary
2578 # For a bit more sophisticated detection of blank summaries, hash the
2579 # automatic one and pass that in the hidden field wpAutoSummary.
2580 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2581 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2584 if ( $this->undidRev
) {
2585 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2588 if ( $this->selfRedirect
) {
2589 $wgOut->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2592 if ( $this->hasPresetSummary
) {
2593 // If a summary has been preset using &summary= we don't want to prompt for
2594 // a different summary. Only prompt for a summary if the summary is blanked.
2596 $this->autoSumm
= md5( '' );
2599 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2600 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2602 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2603 $wgOut->addHTML( Html
::hidden( 'parentRevId', $this->getParentRevId() ) );
2605 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2606 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2608 if ( $this->section
== 'new' ) {
2609 $this->showSummaryInput( true, $this->summary
);
2610 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2613 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2615 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2616 $wgOut->addHTML( EditPage
::getEditToolbar( $this->mTitle
) );
2619 if ( $this->blankArticle
) {
2620 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2623 if ( $this->isConflict
) {
2624 // In an edit conflict bypass the overridable content form method
2625 // and fallback to the raw wpTextbox1 since editconflicts can't be
2626 // resolved between page source edits and custom ui edits using the
2628 $this->textbox2
= $this->textbox1
;
2630 $content = $this->getCurrentContent();
2631 $this->textbox1
= $this->toEditText( $content );
2633 $this->showTextbox1();
2635 $this->showContentForm();
2638 $wgOut->addHTML( $this->editFormTextAfterContent
);
2640 $this->showStandardInputs();
2642 $this->showFormAfterText();
2644 $this->showTosSummary();
2646 $this->showEditTools();
2648 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2650 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2651 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2653 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2654 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2656 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'limitreport' ),
2657 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2659 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2661 if ( $this->isConflict
) {
2663 $this->showConflict();
2664 } catch ( MWContentSerializationException
$ex ) {
2665 // this can't really happen, but be nice if it does.
2667 'content-failed-to-parse',
2668 $this->contentModel
,
2669 $this->contentFormat
,
2672 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2676 // Marker for detecting truncated form data. This must be the last
2677 // parameter sent in order to be of use, so do not move me.
2678 $wgOut->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2679 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2681 if ( !$wgUser->getOption( 'previewontop' ) ) {
2682 $this->displayPreviewArea( $previewOutput, false );
2688 * Extract the section title from current section text, if any.
2690 * @param string $text
2691 * @return string|bool String or false
2693 public static function extractSectionTitle( $text ) {
2694 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2695 if ( !empty( $matches[2] ) ) {
2697 return $wgParser->stripSectionName( trim( $matches[2] ) );
2706 protected function showHeader() {
2707 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2708 global $wgAllowUserCss, $wgAllowUserJs;
2710 if ( $this->mTitle
->isTalkPage() ) {
2711 $wgOut->addWikiMsg( 'talkpagetext' );
2715 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
2716 if ( count( $editNotices ) ) {
2717 $wgOut->addHTML( implode( "\n", $editNotices ) );
2719 $msg = wfMessage( 'editnotice-notext' );
2720 if ( !$msg->isDisabled() ) {
2722 '<div class="mw-editnotice-notext">'
2723 . $msg->parseAsBlock()
2729 if ( $this->isConflict
) {
2730 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2731 $this->edittime
= $this->mArticle
->getTimestamp();
2733 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2734 // We use $this->section to much before this and getVal('wgSection') directly in other places
2735 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2736 // Someone is welcome to try refactoring though
2737 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2741 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2742 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2743 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); // FIXME: use Content object
2744 if ( $sectionTitle !== false ) {
2745 $this->summary
= "/* $sectionTitle */ ";
2750 if ( $this->missingComment
) {
2751 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2754 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2755 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2758 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2759 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2762 if ( $this->blankArticle
) {
2763 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2766 if ( $this->selfRedirect
) {
2767 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2770 if ( $this->hookError
!== '' ) {
2771 $wgOut->addWikiText( $this->hookError
);
2774 if ( !$this->checkUnicodeCompliantBrowser() ) {
2775 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2778 if ( $this->section
!= 'new' ) {
2779 $revision = $this->mArticle
->getRevisionFetched();
2781 // Let sysop know that this will make private content public if saved
2783 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2784 $wgOut->wrapWikiMsg(
2785 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2786 'rev-deleted-text-permission'
2788 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2789 $wgOut->wrapWikiMsg(
2790 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2791 'rev-deleted-text-view'
2795 if ( !$revision->isCurrent() ) {
2796 $this->mArticle
->setOldSubtitle( $revision->getId() );
2797 $wgOut->addWikiMsg( 'editingold' );
2799 } elseif ( $this->mTitle
->exists() ) {
2800 // Something went wrong
2802 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2803 array( 'missing-revision', $this->oldid
) );
2808 if ( wfReadOnly() ) {
2809 $wgOut->wrapWikiMsg(
2810 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2811 array( 'readonlywarning', wfReadOnlyReason() )
2813 } elseif ( $wgUser->isAnon() ) {
2814 if ( $this->formtype
!= 'preview' ) {
2815 $wgOut->wrapWikiMsg(
2816 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2817 array( 'anoneditwarning',
2819 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2821 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2824 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2825 'anonpreviewwarning'
2829 if ( $this->isCssJsSubpage
) {
2830 # Check the skin exists
2831 if ( $this->isWrongCaseCssJsPage
) {
2832 $wgOut->wrapWikiMsg(
2833 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2834 array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() )
2837 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
2838 if ( $this->formtype
!== 'preview' ) {
2839 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
2840 $wgOut->wrapWikiMsg(
2841 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2842 array( 'usercssyoucanpreview' )
2846 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
2847 $wgOut->wrapWikiMsg(
2848 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2849 array( 'userjsyoucanpreview' )
2857 if ( $this->mTitle
->isProtected( 'edit' ) &&
2858 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2860 # Is the title semi-protected?
2861 if ( $this->mTitle
->isSemiProtected() ) {
2862 $noticeMsg = 'semiprotectedpagewarning';
2864 # Then it must be protected based on static groups (regular)
2865 $noticeMsg = 'protectedpagewarning';
2867 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2868 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2870 if ( $this->mTitle
->isCascadeProtected() ) {
2871 # Is this page under cascading protection from some source pages?
2872 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2873 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2874 $cascadeSourcesCount = count( $cascadeSources );
2875 if ( $cascadeSourcesCount > 0 ) {
2876 # Explain, and list the titles responsible
2877 foreach ( $cascadeSources as $page ) {
2878 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2881 $notice .= '</div>';
2882 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2884 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2885 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2887 'showIfEmpty' => false,
2888 'msgKey' => array( 'titleprotectedwarning' ),
2889 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2892 if ( $this->kblength
=== false ) {
2893 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2896 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2897 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2900 $wgLang->formatNum( $this->kblength
),
2901 $wgLang->formatNum( $wgMaxArticleSize )
2905 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2906 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2909 $wgLang->formatSize( strlen( $this->textbox1
) ),
2910 strlen( $this->textbox1
)
2915 # Add header copyright warning
2916 $this->showHeaderCopyrightWarning();
2922 * Standard summary input and label (wgSummary), abstracted so EditPage
2923 * subclasses may reorganize the form.
2924 * Note that you do not need to worry about the label's for=, it will be
2925 * inferred by the id given to the input. You can remove them both by
2926 * passing array( 'id' => false ) to $userInputAttrs.
2928 * @param string $summary The value of the summary input
2929 * @param string $labelText The html to place inside the label
2930 * @param array $inputAttrs Array of attrs to use on the input
2931 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2933 * @return array An array in the format array( $label, $input )
2935 function getSummaryInput( $summary = "", $labelText = null,
2936 $inputAttrs = null, $spanLabelAttrs = null
2938 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2939 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2940 'id' => 'wpSummary',
2941 'maxlength' => '200',
2944 'spellcheck' => 'true',
2945 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2947 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2948 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2949 'id' => "wpSummaryLabel"
2956 $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null,
2959 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2962 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2964 return array( $label, $input );
2968 * @param bool $isSubjectPreview True if this is the section subject/title
2969 * up top, or false if this is the comment summary
2970 * down below the textarea
2971 * @param string $summary The text of the summary to display
2973 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2974 global $wgOut, $wgContLang;
2975 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2976 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2977 if ( $isSubjectPreview ) {
2978 if ( $this->nosummary
) {
2982 if ( !$this->mShowSummaryField
) {
2986 $summary = $wgContLang->recodeForEdit( $summary );
2987 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2988 list( $label, $input ) = $this->getSummaryInput(
2991 array( 'class' => $summaryClass ),
2994 $wgOut->addHTML( "{$label} {$input}" );
2998 * @param bool $isSubjectPreview True if this is the section subject/title
2999 * up top, or false if this is the comment summary
3000 * down below the textarea
3001 * @param string $summary The text of the summary to display
3004 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3005 // avoid spaces in preview, gets always trimmed on save
3006 $summary = trim( $summary );
3007 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
3013 if ( $isSubjectPreview ) {
3014 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
3015 ->inContentLanguage()->text();
3018 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
3020 $summary = wfMessage( $message )->parse()
3021 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
3022 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
3025 protected function showFormBeforeText() {
3027 $section = htmlspecialchars( $this->section
);
3028 $wgOut->addHTML( <<<HTML
3029 <input type='hidden' value="{$section}" name="wpSection"/>
3030 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
3031 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
3032 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
3036 if ( !$this->checkUnicodeCompliantBrowser() ) {
3037 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
3041 protected function showFormAfterText() {
3042 global $wgOut, $wgUser;
3044 * To make it harder for someone to slip a user a page
3045 * which submits an edit form to the wiki without their
3046 * knowledge, a random token is associated with the login
3047 * session. If it's not passed back with the submission,
3048 * we won't save the page, or render user JavaScript and
3051 * For anon editors, who may not have a session, we just
3052 * include the constant suffix to prevent editing from
3053 * broken text-mangling proxies.
3055 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
3059 * Subpage overridable method for printing the form for page content editing
3060 * By default this simply outputs wpTextbox1
3061 * Subclasses can override this to provide a custom UI for editing;
3062 * be it a form, or simply wpTextbox1 with a modified content that will be
3063 * reverse modified when extracted from the post data.
3064 * Note that this is basically the inverse for importContentFormData
3066 protected function showContentForm() {
3067 $this->showTextbox1();
3071 * Method to output wpTextbox1
3072 * The $textoverride method can be used by subclasses overriding showContentForm
3073 * to pass back to this method.
3075 * @param array $customAttribs Array of html attributes to use in the textarea
3076 * @param string $textoverride Optional text to override $this->textarea1 with
3078 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3079 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3080 $attribs = array( 'style' => 'display:none;' );
3082 $classes = array(); // Textarea CSS
3083 if ( $this->mTitle
->isProtected( 'edit' ) &&
3084 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
3086 # Is the title semi-protected?
3087 if ( $this->mTitle
->isSemiProtected() ) {
3088 $classes[] = 'mw-textarea-sprotected';
3090 # Then it must be protected based on static groups (regular)
3091 $classes[] = 'mw-textarea-protected';
3093 # Is the title cascade-protected?
3094 if ( $this->mTitle
->isCascadeProtected() ) {
3095 $classes[] = 'mw-textarea-cprotected';
3099 $attribs = array( 'tabindex' => 1 );
3101 if ( is_array( $customAttribs ) ) {
3102 $attribs +
= $customAttribs;
3105 if ( count( $classes ) ) {
3106 if ( isset( $attribs['class'] ) ) {
3107 $classes[] = $attribs['class'];
3109 $attribs['class'] = implode( ' ', $classes );
3114 $textoverride !== null ?
$textoverride : $this->textbox1
,
3120 protected function showTextbox2() {
3121 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
3124 protected function showTextbox( $text, $name, $customAttribs = array() ) {
3125 global $wgOut, $wgUser;
3127 $wikitext = $this->safeUnicodeOutput( $text );
3128 if ( strval( $wikitext ) !== '' ) {
3129 // Ensure there's a newline at the end, otherwise adding lines
3131 // But don't add a newline if the ext is empty, or Firefox in XHTML
3132 // mode will show an extra newline. A bit annoying.
3136 $attribs = $customAttribs +
array(
3139 'cols' => $wgUser->getIntOption( 'cols' ),
3140 'rows' => $wgUser->getIntOption( 'rows' ),
3141 // Avoid PHP notices when appending preferences
3142 // (appending allows customAttribs['style'] to still work).
3146 $pageLang = $this->mTitle
->getPageLanguage();
3147 $attribs['lang'] = $pageLang->getHtmlCode();
3148 $attribs['dir'] = $pageLang->getDir();
3150 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3153 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3157 $classes[] = 'ontop';
3160 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3162 if ( $this->formtype
!= 'preview' ) {
3163 $attribs['style'] = 'display: none;';
3166 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
3168 if ( $this->formtype
== 'preview' ) {
3169 $this->showPreview( $previewOutput );
3171 // Empty content container for LivePreview
3172 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3173 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3174 'class' => 'mw-content-' . $pageViewLang->getDir() );
3175 $wgOut->addHTML( Html
::rawElement( 'div', $attribs ) );
3178 $wgOut->addHTML( '</div>' );
3180 if ( $this->formtype
== 'diff' ) {
3183 } catch ( MWContentSerializationException
$ex ) {
3185 'content-failed-to-parse',
3186 $this->contentModel
,
3187 $this->contentFormat
,
3190 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3196 * Append preview output to $wgOut.
3197 * Includes category rendering if this is a category page.
3199 * @param string $text The HTML to be output for the preview.
3201 protected function showPreview( $text ) {
3203 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3204 $this->mArticle
->openShowCategory();
3206 # This hook seems slightly odd here, but makes things more
3207 # consistent for extensions.
3208 Hooks
::run( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3209 $wgOut->addHTML( $text );
3210 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3211 $this->mArticle
->closeShowCategory();
3216 * Get a diff between the current contents of the edit box and the
3217 * version of the page we're editing from.
3219 * If this is a section edit, we'll replace the section as for final
3220 * save and then make a comparison.
3222 function showDiff() {
3223 global $wgUser, $wgContLang, $wgOut;
3225 $oldtitlemsg = 'currentrev';
3226 # if message does not exist, show diff against the preloaded default
3227 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3228 $oldtext = $this->mTitle
->getDefaultMessageText();
3229 if ( $oldtext !== false ) {
3230 $oldtitlemsg = 'defaultmessagetext';
3231 $oldContent = $this->toEditContent( $oldtext );
3236 $oldContent = $this->getCurrentContent();
3239 $textboxContent = $this->toEditContent( $this->textbox1
);
3241 $newContent = $this->mArticle
->replaceSectionContent(
3242 $this->section
, $textboxContent,
3243 $this->summary
, $this->edittime
);
3245 if ( $newContent ) {
3246 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3247 Hooks
::run( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3249 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
3250 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
3253 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3254 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3255 $newtitle = wfMessage( 'yourtext' )->parse();
3257 if ( !$oldContent ) {
3258 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3261 if ( !$newContent ) {
3262 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3265 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3266 $de->setContent( $oldContent, $newContent );
3268 $difftext = $de->getDiff( $oldtitle, $newtitle );
3269 $de->showDiffStyle();
3274 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3278 * Show the header copyright warning.
3280 protected function showHeaderCopyrightWarning() {
3281 $msg = 'editpage-head-copy-warn';
3282 if ( !wfMessage( $msg )->isDisabled() ) {
3284 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3285 'editpage-head-copy-warn' );
3290 * Give a chance for site and per-namespace customizations of
3291 * terms of service summary link that might exist separately
3292 * from the copyright notice.
3294 * This will display between the save button and the edit tools,
3295 * so should remain short!
3297 protected function showTosSummary() {
3298 $msg = 'editpage-tos-summary';
3299 Hooks
::run( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
3300 if ( !wfMessage( $msg )->isDisabled() ) {
3302 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3303 $wgOut->addWikiMsg( $msg );
3304 $wgOut->addHTML( '</div>' );
3308 protected function showEditTools() {
3310 $wgOut->addHTML( '<div class="mw-editTools">' .
3311 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3316 * Get the copyright warning
3318 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3321 protected function getCopywarn() {
3322 return self
::getCopyrightWarning( $this->mTitle
);
3326 * Get the copyright warning, by default returns wikitext
3328 * @param Title $title
3329 * @param string $format Output format, valid values are any function of a Message object
3332 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3333 global $wgRightsText;
3334 if ( $wgRightsText ) {
3335 $copywarnMsg = array( 'copyrightwarning',
3336 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3339 $copywarnMsg = array( 'copyrightwarning2',
3340 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3342 // Allow for site and per-namespace customization of contribution/copyright notice.
3343 Hooks
::run( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3345 return "<div id=\"editpage-copywarn\">\n" .
3346 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3350 * Get the Limit report for page previews
3353 * @param ParserOutput $output ParserOutput object from the parse
3354 * @return string HTML
3356 public static function getPreviewLimitReport( $output ) {
3357 if ( !$output ||
!$output->getLimitReportData() ) {
3361 $limitReport = Html
::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3362 wfMessage( 'limitreport-title' )->parseAsBlock()
3365 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3366 $limitReport .= Html
::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3368 $limitReport .= Html
::openElement( 'table', array(
3369 'class' => 'preview-limit-report wikitable'
3371 Html
::openElement( 'tbody' );
3373 foreach ( $output->getLimitReportData() as $key => $value ) {
3374 if ( Hooks
::run( 'ParserLimitReportFormat',
3375 array( $key, &$value, &$limitReport, true, true )
3377 $keyMsg = wfMessage( $key );
3378 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3379 if ( !$valueMsg->exists() ) {
3380 $valueMsg = new RawMessage( '$1' );
3382 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3383 $limitReport .= Html
::openElement( 'tr' ) .
3384 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3385 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3386 Html
::closeElement( 'tr' );
3391 $limitReport .= Html
::closeElement( 'tbody' ) .
3392 Html
::closeElement( 'table' ) .
3393 Html
::closeElement( 'div' );
3395 return $limitReport;
3398 protected function showStandardInputs( &$tabindex = 2 ) {
3400 $wgOut->addHTML( "<div class='editOptions'>\n" );
3402 if ( $this->section
!= 'new' ) {
3403 $this->showSummaryInput( false, $this->summary
);
3404 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3407 $checkboxes = $this->getCheckboxes( $tabindex,
3408 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
3409 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3411 // Show copyright warning.
3412 $wgOut->addWikiText( $this->getCopywarn() );
3413 $wgOut->addHTML( $this->editFormTextAfterWarn
);
3415 $wgOut->addHTML( "<div class='editButtons'>\n" );
3416 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3418 $cancel = $this->getCancelLink();
3419 if ( $cancel !== '' ) {
3420 $cancel .= Html
::element( 'span',
3421 array( 'class' => 'mw-editButtons-pipe-separator' ),
3422 wfMessage( 'pipe-separator' )->text() );
3425 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3426 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3428 'target' => 'helpwindow',
3429 'href' => $edithelpurl,
3431 $edithelp = Html
::linkButton( wfMessage( 'edithelp' )->text(),
3432 $attrs, array( 'mw-ui-quiet' ) ) .
3433 wfMessage( 'word-separator' )->escaped() .
3434 wfMessage( 'newwindow' )->parse();
3436 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3437 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3438 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3440 Hooks
::run( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3442 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3446 * Show an edit conflict. textbox1 is already shown in showEditForm().
3447 * If you want to use another entry point to this function, be careful.
3449 protected function showConflict() {
3452 if ( Hooks
::run( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3453 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3455 $content1 = $this->toEditContent( $this->textbox1
);
3456 $content2 = $this->toEditContent( $this->textbox2
);
3458 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3459 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3460 $de->setContent( $content2, $content1 );
3462 wfMessage( 'yourtext' )->parse(),
3463 wfMessage( 'storedversion' )->text()
3466 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3467 $this->showTextbox2();
3474 public function getCancelLink() {
3475 $cancelParams = array();
3476 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3477 $cancelParams['oldid'] = $this->oldid
;
3479 $attrs = array( 'id' => 'mw-editform-cancel' );
3481 return Linker
::linkKnown(
3482 $this->getContextTitle(),
3483 wfMessage( 'cancel' )->parse(),
3484 Html
::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3490 * Returns the URL to use in the form's action attribute.
3491 * This is used by EditPage subclasses when simply customizing the action
3492 * variable in the constructor is not enough. This can be used when the
3493 * EditPage lives inside of a Special page rather than a custom page action.
3495 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3498 protected function getActionURL( Title
$title ) {
3499 return $title->getLocalURL( array( 'action' => $this->action
) );
3503 * Check if a page was deleted while the user was editing it, before submit.
3504 * Note that we rely on the logging table, which hasn't been always there,
3505 * but that doesn't matter, because this only applies to brand new
3509 protected function wasDeletedSinceLastEdit() {
3510 if ( $this->deletedSinceEdit
!== null ) {
3511 return $this->deletedSinceEdit
;
3514 $this->deletedSinceEdit
= false;
3516 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3517 $this->lastDelete
= $this->getLastDelete();
3518 if ( $this->lastDelete
) {
3519 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3520 if ( $deleteTime > $this->starttime
) {
3521 $this->deletedSinceEdit
= true;
3526 return $this->deletedSinceEdit
;
3530 * @return bool|stdClass
3532 protected function getLastDelete() {
3533 $dbr = wfGetDB( DB_SLAVE
);
3534 $data = $dbr->selectRow(
3535 array( 'logging', 'user' ),
3548 'log_namespace' => $this->mTitle
->getNamespace(),
3549 'log_title' => $this->mTitle
->getDBkey(),
3550 'log_type' => 'delete',
3551 'log_action' => 'delete',
3555 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3557 // Quick paranoid permission checks...
3558 if ( is_object( $data ) ) {
3559 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3560 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
3563 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3564 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
3572 * Get the rendered text for previewing.
3573 * @throws MWException
3576 function getPreviewText() {
3577 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3578 global $wgAllowUserCss, $wgAllowUserJs;
3580 $stats = $wgOut->getContext()->getStats();
3582 if ( $wgRawHtml && !$this->mTokenOk
) {
3583 // Could be an offsite preview attempt. This is very unsafe if
3584 // HTML is enabled, as it could be an attack.
3586 if ( $this->textbox1
!== '' ) {
3587 // Do not put big scary notice, if previewing the empty
3588 // string, which happens when you initially edit
3589 // a category page, due to automatic preview-on-open.
3590 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3591 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3593 $stats->increment( 'edit.failures.session_loss' );
3600 $content = $this->toEditContent( $this->textbox1
);
3604 'AlternateEditPreview',
3605 array( $this, &$content, &$previewHTML, &$this->mParserOutput
) )
3607 return $previewHTML;
3610 # provide a anchor link to the editform
3611 $continueEditing = '<span class="mw-continue-editing">' .
3612 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3613 wfMessage( 'continue-editing' )->text() . ']]</span>';
3614 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3615 if ( $this->mTokenOkExceptSuffix
) {
3616 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3617 $stats->increment( 'edit.failures.bad_token' );
3619 $note = wfMessage( 'session_fail_preview' )->plain();
3620 $stats->increment( 'edit.failures.session_loss' );
3622 } elseif ( $this->incompleteForm
) {
3623 $note = wfMessage( 'edit_form_incomplete' )->plain();
3624 if ( $this->mTriedSave
) {
3625 $stats->increment( 'edit.failures.incomplete_form' );
3628 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3631 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
3632 $parserOptions->setIsPreview( true );
3633 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3635 # don't parse non-wikitext pages, show message about preview
3636 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3637 if ( $this->mTitle
->isCssJsSubpage() ) {
3639 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3645 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3647 if ( $level === 'user' && !$wgAllowUserCss ) {
3650 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3652 if ( $level === 'user' && !$wgAllowUserJs ) {
3659 # Used messages to make sure grep find them:
3660 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3661 if ( $level && $format ) {
3662 $note = "<div id='mw-{$level}{$format}preview'>" .
3663 wfMessage( "{$level}{$format}preview" )->text() .
3664 ' ' . $continueEditing . "</div>";
3668 # If we're adding a comment, we need to show the
3669 # summary as the headline
3670 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3671 $content = $content->addSectionHeader( $this->summary
);
3674 $hook_args = array( $this, &$content );
3675 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3676 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3678 $parserOptions->enableLimitReport();
3680 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3681 # But it's now deprecated, so never mind
3683 $pstContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3684 $scopedCallback = $parserOptions->setupFakeRevision(
3685 $this->mTitle
, $pstContent, $wgUser );
3686 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3688 # Try to stash the edit for the final submission step
3689 # @todo: different date format preferences cause cache misses
3690 ApiStashEdit
::stashEditFromPreview(
3691 $this->getArticle(), $content, $pstContent,
3692 $parserOutput, $parserOptions, $parserOptions, wfTimestampNow()
3695 $parserOutput->setEditSectionTokens( false ); // no section edit links
3696 $previewHTML = $parserOutput->getText();
3697 $this->mParserOutput
= $parserOutput;
3698 $wgOut->addParserOutputMetadata( $parserOutput );
3700 if ( count( $parserOutput->getWarnings() ) ) {
3701 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3703 } catch ( MWContentSerializationException
$ex ) {
3705 'content-failed-to-parse',
3706 $this->contentModel
,
3707 $this->contentFormat
,
3710 $note .= "\n\n" . $m->parse();
3714 if ( $this->isConflict
) {
3715 $conflict = '<h2 id="mw-previewconflict">'
3716 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3718 $conflict = '<hr />';
3721 $previewhead = "<div class='previewnote'>\n" .
3722 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3723 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3725 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3726 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3727 'class' => 'mw-content-' . $pageViewLang->getDir() );
3728 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3730 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3736 function getTemplates() {
3737 if ( $this->preview ||
$this->section
!= '' ) {
3738 $templates = array();
3739 if ( !isset( $this->mParserOutput
) ) {
3742 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3743 foreach ( array_keys( $template ) as $dbk ) {
3744 $templates[] = Title
::makeTitle( $ns, $dbk );
3749 return $this->mTitle
->getTemplateLinksFrom();
3754 * Shows a bulletin board style toolbar for common editing functions.
3755 * It can be disabled in the user preferences.
3757 * @param $title Title object for the page being edited (optional)
3760 static function getEditToolbar( $title = null ) {
3761 global $wgContLang, $wgOut;
3762 global $wgEnableUploads, $wgForeignFileRepos;
3764 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3765 $showSignature = true;
3767 $showSignature = MWNamespace
::wantSignatures( $title->getNamespace() );
3771 * $toolarray is an array of arrays each of which includes the
3772 * opening tag, the closing tag, optionally a sample text that is
3773 * inserted between the two when no selection is highlighted
3774 * and. The tip text is shown when the user moves the mouse
3777 * Images are defined in ResourceLoaderEditToolbarModule.
3781 'id' => 'mw-editbutton-bold',
3783 'close' => '\'\'\'',
3784 'sample' => wfMessage( 'bold_sample' )->text(),
3785 'tip' => wfMessage( 'bold_tip' )->text(),
3788 'id' => 'mw-editbutton-italic',
3791 'sample' => wfMessage( 'italic_sample' )->text(),
3792 'tip' => wfMessage( 'italic_tip' )->text(),
3795 'id' => 'mw-editbutton-link',
3798 'sample' => wfMessage( 'link_sample' )->text(),
3799 'tip' => wfMessage( 'link_tip' )->text(),
3802 'id' => 'mw-editbutton-extlink',
3805 'sample' => wfMessage( 'extlink_sample' )->text(),
3806 'tip' => wfMessage( 'extlink_tip' )->text(),
3809 'id' => 'mw-editbutton-headline',
3812 'sample' => wfMessage( 'headline_sample' )->text(),
3813 'tip' => wfMessage( 'headline_tip' )->text(),
3815 $imagesAvailable ?
array(
3816 'id' => 'mw-editbutton-image',
3817 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3819 'sample' => wfMessage( 'image_sample' )->text(),
3820 'tip' => wfMessage( 'image_tip' )->text(),
3822 $imagesAvailable ?
array(
3823 'id' => 'mw-editbutton-media',
3824 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3826 'sample' => wfMessage( 'media_sample' )->text(),
3827 'tip' => wfMessage( 'media_tip' )->text(),
3830 'id' => 'mw-editbutton-nowiki',
3831 'open' => "<nowiki>",
3832 'close' => "</nowiki>",
3833 'sample' => wfMessage( 'nowiki_sample' )->text(),
3834 'tip' => wfMessage( 'nowiki_tip' )->text(),
3836 $showSignature ?
array(
3837 'id' => 'mw-editbutton-signature',
3841 'tip' => wfMessage( 'sig_tip' )->text(),
3844 'id' => 'mw-editbutton-hr',
3845 'open' => "\n----\n",
3848 'tip' => wfMessage( 'hr_tip' )->text(),
3852 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3853 foreach ( $toolarray as $tool ) {
3859 // Images are defined in ResourceLoaderEditToolbarModule
3861 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3862 // Older browsers show a "speedtip" type message only for ALT.
3863 // Ideally these should be different, realistically they
3864 // probably don't need to be.
3872 $script .= Xml
::encodeJsCall(
3873 'mw.toolbar.addButton',
3875 ResourceLoader
::inDebugMode()
3880 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
3882 $toolbar = '<div id="toolbar"></div>';
3884 Hooks
::run( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3890 * Returns an array of html code of the following checkboxes:
3893 * @param int $tabindex Current tabindex
3894 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3895 * status of the checkbox
3899 public function getCheckboxes( &$tabindex, $checked ) {
3900 global $wgUser, $wgUseMediaWikiUIEverywhere;
3902 $checkboxes = array();
3904 // don't show the minor edit checkbox if it's a new page or section
3905 if ( !$this->isNew
) {
3906 $checkboxes['minor'] = '';
3907 $minorLabel = wfMessage( 'minoredit' )->parse();
3908 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3910 'tabindex' => ++
$tabindex,
3911 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3912 'id' => 'wpMinoredit',
3915 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3916 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3917 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3918 ">{$minorLabel}</label>";
3920 if ( $wgUseMediaWikiUIEverywhere ) {
3921 $checkboxes['minor'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3923 Html
::closeElement( 'div' );
3925 $checkboxes['minor'] = $minorEditHtml;
3930 $watchLabel = wfMessage( 'watchthis' )->parse();
3931 $checkboxes['watch'] = '';
3932 if ( $wgUser->isLoggedIn() ) {
3934 'tabindex' => ++
$tabindex,
3935 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3936 'id' => 'wpWatchthis',
3939 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3940 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3941 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3942 ">{$watchLabel}</label>";
3943 if ( $wgUseMediaWikiUIEverywhere ) {
3944 $checkboxes['watch'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3946 Html
::closeElement( 'div' );
3948 $checkboxes['watch'] = $watchThisHtml;
3951 Hooks
::run( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3956 * Returns an array of html code of the following buttons:
3957 * save, diff, preview and live
3959 * @param int $tabindex Current tabindex
3963 public function getEditButtons( &$tabindex ) {
3969 'tabindex' => ++
$tabindex,
3970 ) + Linker
::tooltipAndAccesskeyAttribs( 'save' );
3971 $buttons['save'] = Html
::submitButton( wfMessage( 'savearticle' )->text(),
3972 $attribs, array( 'mw-ui-constructive' ) );
3974 ++
$tabindex; // use the same for preview and live preview
3976 'id' => 'wpPreview',
3977 'name' => 'wpPreview',
3978 'tabindex' => $tabindex,
3979 ) + Linker
::tooltipAndAccesskeyAttribs( 'preview' );
3980 $buttons['preview'] = Html
::submitButton( wfMessage( 'showpreview' )->text(),
3982 $buttons['live'] = '';
3987 'tabindex' => ++
$tabindex,
3988 ) + Linker
::tooltipAndAccesskeyAttribs( 'diff' );
3989 $buttons['diff'] = Html
::submitButton( wfMessage( 'showdiff' )->text(),
3992 Hooks
::run( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3997 * Creates a basic error page which informs the user that
3998 * they have attempted to edit a nonexistent section.
4000 function noSuchSectionPage() {
4003 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
4005 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
4006 Hooks
::run( 'EditPageNoSuchSection', array( &$this, &$res ) );
4007 $wgOut->addHTML( $res );
4009 $wgOut->returnToMain( false, $this->mTitle
);
4013 * Show "your edit contains spam" page with your diff and text
4015 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4017 public function spamPageWithContent( $match = false ) {
4018 global $wgOut, $wgLang;
4019 $this->textbox2
= $this->textbox1
;
4021 if ( is_array( $match ) ) {
4022 $match = $wgLang->listToText( $match );
4024 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
4026 $wgOut->addHTML( '<div id="spamprotected">' );
4027 $wgOut->addWikiMsg( 'spamprotectiontext' );
4029 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4031 $wgOut->addHTML( '</div>' );
4033 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4036 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4037 $this->showTextbox2();
4039 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
4043 * Check if the browser is on a blacklist of user-agents known to
4044 * mangle UTF-8 data on form submission. Returns true if Unicode
4045 * should make it through, false if it's known to be a problem.
4048 private function checkUnicodeCompliantBrowser() {
4049 global $wgBrowserBlackList, $wgRequest;
4051 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
4052 if ( $currentbrowser === false ) {
4053 // No User-Agent header sent? Trust it by default...
4057 foreach ( $wgBrowserBlackList as $browser ) {
4058 if ( preg_match( $browser, $currentbrowser ) ) {
4066 * Filter an input field through a Unicode de-armoring process if it
4067 * came from an old browser with known broken Unicode editing issues.
4069 * @param WebRequest $request
4070 * @param string $field
4073 protected function safeUnicodeInput( $request, $field ) {
4074 $text = rtrim( $request->getText( $field ) );
4075 return $request->getBool( 'safemode' )
4076 ?
$this->unmakeSafe( $text )
4081 * Filter an output field through a Unicode armoring process if it is
4082 * going to an old browser with known broken Unicode editing issues.
4084 * @param string $text
4087 protected function safeUnicodeOutput( $text ) {
4089 $codedText = $wgContLang->recodeForEdit( $text );
4090 return $this->checkUnicodeCompliantBrowser()
4092 : $this->makeSafe( $codedText );
4096 * A number of web browsers are known to corrupt non-ASCII characters
4097 * in a UTF-8 text editing environment. To protect against this,
4098 * detected browsers will be served an armored version of the text,
4099 * with non-ASCII chars converted to numeric HTML character references.
4101 * Preexisting such character references will have a 0 added to them
4102 * to ensure that round-trips do not alter the original data.
4104 * @param string $invalue
4107 private function makeSafe( $invalue ) {
4108 // Armor existing references for reversibility.
4109 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
4114 $valueLength = strlen( $invalue );
4115 for ( $i = 0; $i < $valueLength; $i++
) {
4116 $bytevalue = ord( $invalue[$i] );
4117 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4118 $result .= chr( $bytevalue );
4120 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4121 $working = $working << 6;
4122 $working +
= ( $bytevalue & 0x3F );
4124 if ( $bytesleft <= 0 ) {
4125 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4127 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4128 $working = $bytevalue & 0x1F;
4130 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4131 $working = $bytevalue & 0x0F;
4133 } else { // 1111 0xxx
4134 $working = $bytevalue & 0x07;
4142 * Reverse the previously applied transliteration of non-ASCII characters
4143 * back to UTF-8. Used to protect data from corruption by broken web browsers
4144 * as listed in $wgBrowserBlackList.
4146 * @param string $invalue
4149 private function unmakeSafe( $invalue ) {
4151 $valueLength = strlen( $invalue );
4152 for ( $i = 0; $i < $valueLength; $i++
) {
4153 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4157 $hexstring .= $invalue[$i];
4159 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4161 // Do some sanity checks. These aren't needed for reversibility,
4162 // but should help keep the breakage down if the editor
4163 // breaks one of the entities whilst editing.
4164 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4165 $codepoint = hexdec( $hexstring );
4166 $result .= UtfNormal\Utils
::codepointToUtf8( $codepoint );
4168 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4171 $result .= substr( $invalue, $i, 1 );
4174 // reverse the transform that we made for reversibility reasons.
4175 return strtr( $result, array( "�" => "&#x" ) );