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
530 $wgUser->spreadAnyEditBlock();
532 $this->displayPermissionsError( $permErrors );
537 $this->isConflict
= false;
538 // css / js subpages of user pages get a special treatment
539 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
540 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
541 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
542 // @todo FIXME: Silly assignment.
543 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
545 # Show applicable editing introductions
546 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
550 # Attempt submission here. This will check for edit conflicts,
551 # and redundantly check for locked database, blocked IPs, etc.
552 # that edit() already checked just in case someone tries to sneak
553 # in the back door with a hand-edited submission URL.
555 if ( 'save' == $this->formtype
) {
556 $resultDetails = null;
557 $status = $this->attemptSave( $resultDetails );
558 if ( !$this->handleStatus( $status, $resultDetails ) ) {
563 # First time through: get contents, set time for conflict
565 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
566 if ( $this->initialiseForm() === false ) {
567 $this->noSuchSectionPage();
571 if ( !$this->mTitle
->getArticleID() ) {
572 Hooks
::run( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
574 Hooks
::run( 'EditFormInitialText', array( $this ) );
579 $this->showEditForm();
583 * @param string $rigor Same format as Title::getUserPermissionErrors()
586 protected function getEditPermissionErrors( $rigor = 'secure' ) {
589 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
590 # Can this title be created?
591 if ( !$this->mTitle
->exists() ) {
592 $permErrors = array_merge(
595 $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
600 # Ignore some permissions errors when a user is just previewing/viewing diffs
602 foreach ( $permErrors as $error ) {
603 if ( ( $this->preview ||
$this->diff
)
604 && ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' )
609 $permErrors = wfArrayDiff2( $permErrors, $remove );
615 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
616 * but with the following differences:
617 * - If redlink=1, the user will be redirected to the page
618 * - If there is content to display or the error occurs while either saving,
619 * previewing or showing the difference, it will be a
620 * "View source for ..." page displaying the source code after the error message.
623 * @param array $permErrors Array of permissions errors, as returned by
624 * Title::getUserPermissionsErrors().
625 * @throws PermissionsError
627 protected function displayPermissionsError( array $permErrors ) {
628 global $wgRequest, $wgOut;
630 if ( $wgRequest->getBool( 'redlink' ) ) {
631 // The edit page was reached via a red link.
632 // Redirect to the article page and let them click the edit tab if
633 // they really want a permission error.
634 $wgOut->redirect( $this->mTitle
->getFullURL() );
638 $content = $this->getContentObject();
640 # Use the normal message if there's nothing to display
641 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
642 $action = $this->mTitle
->exists() ?
'edit' :
643 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
644 throw new PermissionsError( $action, $permErrors );
647 Hooks
::run( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
649 $wgOut->setRobotPolicy( 'noindex,nofollow' );
650 $wgOut->setPageTitle( wfMessage(
652 $this->getContextTitle()->getPrefixedText()
654 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
655 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
656 $wgOut->addHTML( "<hr />\n" );
658 # If the user made changes, preserve them when showing the markup
659 # (This happens when a user is blocked during edit, for instance)
660 if ( !$this->firsttime
) {
661 $text = $this->textbox1
;
662 $wgOut->addWikiMsg( 'viewyourtext' );
664 $text = $this->toEditText( $content );
665 $wgOut->addWikiMsg( 'viewsourcetext' );
668 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
670 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
671 Linker
::formatTemplates( $this->getTemplates() ) ) );
673 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
675 if ( $this->mTitle
->exists() ) {
676 $wgOut->returnToMain( null, $this->mTitle
);
681 * Should we show a preview when the edit form is first shown?
685 protected function previewOnOpen() {
686 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
687 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
688 // Explicit override from request
690 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
691 // Explicit override from request
693 } elseif ( $this->section
== 'new' ) {
694 // Nothing *to* preview for new sections
696 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
697 && $wgUser->getOption( 'previewonfirst' )
699 // Standard preference behavior
701 } elseif ( !$this->mTitle
->exists()
702 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
703 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
705 // Categories are special
713 * Checks whether the user entered a skin name in uppercase,
714 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
718 protected function isWrongCaseCssJsPage() {
719 if ( $this->mTitle
->isCssJsSubpage() ) {
720 $name = $this->mTitle
->getSkinFromCssJsSubpage();
721 $skins = array_merge(
722 array_keys( Skin
::getSkinNames() ),
725 return !in_array( $name, $skins )
726 && in_array( strtolower( $name ), $skins );
733 * Returns whether section editing is supported for the current page.
734 * Subclasses may override this to replace the default behavior, which is
735 * to check ContentHandler::supportsSections.
737 * @return bool True if this edit page supports sections, false otherwise.
739 protected function isSectionEditSupported() {
740 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
741 return $contentHandler->supportsSections();
745 * This function collects the form data and uses it to populate various member variables.
746 * @param WebRequest $request
747 * @throws ErrorPageError
749 function importFormData( &$request ) {
750 global $wgContLang, $wgUser;
752 # Section edit can come from either the form or a link
753 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
755 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
756 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
759 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
761 if ( $request->wasPosted() ) {
762 # These fields need to be checked for encoding.
763 # Also remove trailing whitespace, but don't remove _initial_
764 # whitespace from the text boxes. This may be significant formatting.
765 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
766 if ( !$request->getCheck( 'wpTextbox2' ) ) {
767 // Skip this if wpTextbox2 has input, it indicates that we came
768 // from a conflict page with raw page text, not a custom form
769 // modified by subclasses
770 $textbox1 = $this->importContentFormData( $request );
771 if ( $textbox1 !== null ) {
772 $this->textbox1
= $textbox1;
776 # Truncate for whole multibyte characters
777 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
779 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
780 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
782 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
784 # Treat sectiontitle the same way as summary.
785 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
786 # currently doing double duty as both edit summary and section title. Right now this
787 # is just to allow API edits to work around this limitation, but this should be
788 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
789 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
790 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
792 $this->edittime
= $request->getVal( 'wpEdittime' );
793 $this->starttime
= $request->getVal( 'wpStarttime' );
795 $undidRev = $request->getInt( 'wpUndidRevision' );
797 $this->undidRev
= $undidRev;
800 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
802 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
803 // wpTextbox1 field is missing, possibly due to being "too big"
804 // according to some filter rules such as Suhosin's setting for
805 // suhosin.request.max_value_length (d'oh)
806 $this->incompleteForm
= true;
808 // If we receive the last parameter of the request, we can fairly
809 // claim the POST request has not been truncated.
811 // TODO: softened the check for cutover. Once we determine
812 // that it is safe, we should complete the transition by
813 // removing the "edittime" clause.
814 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' )
815 && is_null( $this->edittime
) );
817 if ( $this->incompleteForm
) {
818 # If the form is incomplete, force to preview.
819 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
820 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
821 $this->preview
= true;
823 $this->preview
= $request->getCheck( 'wpPreview' );
824 $this->diff
= $request->getCheck( 'wpDiff' );
826 // Remember whether a save was requested, so we can indicate
827 // if we forced preview due to session failure.
828 $this->mTriedSave
= !$this->preview
;
830 if ( $this->tokenOk( $request ) ) {
831 # Some browsers will not report any submit button
832 # if the user hits enter in the comment box.
833 # The unmarked state will be assumed to be a save,
834 # if the form seems otherwise complete.
835 wfDebug( __METHOD__
. ": Passed token check.\n" );
836 } elseif ( $this->diff
) {
837 # Failed token check, but only requested "Show Changes".
838 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
840 # Page might be a hack attempt posted from
841 # an external site. Preview instead of saving.
842 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
843 $this->preview
= true;
846 $this->save
= !$this->preview
&& !$this->diff
;
847 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
848 $this->edittime
= null;
851 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
852 $this->starttime
= null;
855 $this->recreate
= $request->getCheck( 'wpRecreate' );
857 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
858 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
860 # Don't force edit summaries when a user is editing their own user or talk page
861 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
862 && $this->mTitle
->getText() == $wgUser->getName()
864 $this->allowBlankSummary
= true;
866 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
867 ||
!$wgUser->getOption( 'forceeditsummary' );
870 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
872 $this->allowBlankArticle
= $request->getBool( 'wpIgnoreBlankArticle' );
873 $this->allowSelfRedirect
= $request->getBool( 'wpIgnoreSelfRedirect' );
875 $changeTags = $request->getVal( 'wpChangeTags' );
876 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
877 $this->changeTags
= array();
879 $this->changeTags
= array_filter( array_map( 'trim', explode( ',',
883 # Not a posted form? Start with nothing.
884 wfDebug( __METHOD__
. ": Not a posted form.\n" );
885 $this->textbox1
= '';
887 $this->sectiontitle
= '';
888 $this->edittime
= '';
889 $this->starttime
= wfTimestampNow();
891 $this->preview
= false;
894 $this->minoredit
= false;
895 // Watch may be overridden by request parameters
896 $this->watchthis
= $request->getBool( 'watchthis', false );
897 $this->recreate
= false;
899 // When creating a new section, we can preload a section title by passing it as the
900 // preloadtitle parameter in the URL (Bug 13100)
901 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
902 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
903 // Once wpSummary isn't being use for setting section titles, we should delete this.
904 $this->summary
= $request->getVal( 'preloadtitle' );
905 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
906 $this->summary
= $request->getText( 'summary' );
907 if ( $this->summary
!== '' ) {
908 $this->hasPresetSummary
= true;
912 if ( $request->getVal( 'minor' ) ) {
913 $this->minoredit
= true;
917 $this->oldid
= $request->getInt( 'oldid' );
918 $this->parentRevId
= $request->getInt( 'parentRevId' );
920 $this->bot
= $request->getBool( 'bot', true );
921 $this->nosummary
= $request->getBool( 'nosummary' );
923 // May be overridden by revision.
924 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
925 // May be overridden by revision.
926 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
928 if ( !ContentHandler
::getForModelID( $this->contentModel
)
929 ->isSupportedFormat( $this->contentFormat
)
931 throw new ErrorPageError(
932 'editpage-notsupportedcontentformat-title',
933 'editpage-notsupportedcontentformat-text',
934 array( $this->contentFormat
, ContentHandler
::getLocalizedName( $this->contentModel
) )
939 * @todo Check if the desired model is allowed in this namespace, and if
940 * a transition from the page's current model to the new model is
944 $this->editintro
= $request->getText( 'editintro',
945 // Custom edit intro for new sections
946 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
948 // Allow extensions to modify form data
949 Hooks
::run( 'EditPage::importFormData', array( $this, $request ) );
954 * Subpage overridable method for extracting the page content data from the
955 * posted form to be placed in $this->textbox1, if using customized input
956 * this method should be overridden and return the page text that will be used
957 * for saving, preview parsing and so on...
959 * @param WebRequest $request
961 protected function importContentFormData( &$request ) {
962 return; // Don't do anything, EditPage already extracted wpTextbox1
966 * Initialise form fields in the object
967 * Called on the first invocation, e.g. when a user clicks an edit link
968 * @return bool If the requested section is valid
970 function initialiseForm() {
972 $this->edittime
= $this->mArticle
->getTimestamp();
974 $content = $this->getContentObject( false ); #TODO: track content object?!
975 if ( $content === false ) {
978 $this->textbox1
= $this->toEditText( $content );
980 // activate checkboxes if user wants them to be always active
981 # Sort out the "watch" checkbox
982 if ( $wgUser->getOption( 'watchdefault' ) ) {
984 $this->watchthis
= true;
985 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
987 $this->watchthis
= true;
988 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
990 $this->watchthis
= true;
992 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
993 $this->minoredit
= true;
995 if ( $this->textbox1
=== false ) {
1002 * @param Content|null $def_content The default value to return
1004 * @return Content|null Content on success, $def_content for invalid sections
1008 protected function getContentObject( $def_content = null ) {
1009 global $wgOut, $wgRequest, $wgUser, $wgContLang;
1013 // For message page not locally set, use the i18n message.
1014 // For other non-existent articles, use preload text if any.
1015 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1016 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1017 # If this is a system message, get the default text.
1018 $msg = $this->mTitle
->getDefaultMessageText();
1020 $content = $this->toEditContent( $msg );
1022 if ( $content === false ) {
1023 # If requested, preload some text.
1024 $preload = $wgRequest->getVal( 'preload',
1025 // Custom preload text for new sections
1026 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1027 $params = $wgRequest->getArray( 'preloadparams', array() );
1029 $content = $this->getPreloadedContent( $preload, $params );
1031 // For existing pages, get text based on "undo" or section parameters.
1033 if ( $this->section
!= '' ) {
1034 // Get section edit text (returns $def_text for invalid sections)
1035 $orig = $this->getOriginalContent( $wgUser );
1036 $content = $orig ?
$orig->getSection( $this->section
) : null;
1039 $content = $def_content;
1042 $undoafter = $wgRequest->getInt( 'undoafter' );
1043 $undo = $wgRequest->getInt( 'undo' );
1045 if ( $undo > 0 && $undoafter > 0 ) {
1046 $undorev = Revision
::newFromId( $undo );
1047 $oldrev = Revision
::newFromId( $undoafter );
1049 # Sanity check, make sure it's the right page,
1050 # the revisions exist and they were not deleted.
1051 # Otherwise, $content will be left as-is.
1052 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1053 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1054 !$oldrev->isDeleted( Revision
::DELETED_TEXT
)
1056 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
1058 if ( $content === false ) {
1059 # Warn the user that something went wrong
1060 $undoMsg = 'failure';
1062 $oldContent = $this->mArticle
->getPage()->getContent( Revision
::RAW
);
1063 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
1064 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
1066 if ( $newContent->equals( $oldContent ) ) {
1067 # Tell the user that the undo results in no change,
1068 # i.e. the revisions were already undone.
1069 $undoMsg = 'nochange';
1072 # Inform the user of our success and set an automatic edit summary
1073 $undoMsg = 'success';
1075 # If we just undid one rev, use an autosummary
1076 $firstrev = $oldrev->getNext();
1077 if ( $firstrev && $firstrev->getId() == $undo ) {
1078 $userText = $undorev->getUserText();
1079 if ( $userText === '' ) {
1080 $undoSummary = wfMessage(
1081 'undo-summary-username-hidden',
1083 )->inContentLanguage()->text();
1085 $undoSummary = wfMessage(
1089 )->inContentLanguage()->text();
1091 if ( $this->summary
=== '' ) {
1092 $this->summary
= $undoSummary;
1094 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
1095 ->inContentLanguage()->text() . $this->summary
;
1097 $this->undidRev
= $undo;
1099 $this->formtype
= 'diff';
1103 // Failed basic sanity checks.
1104 // Older revisions may have been removed since the link
1105 // was created, or we may simply have got bogus input.
1109 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1110 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1111 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
1112 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1115 if ( $content === false ) {
1116 $content = $this->getOriginalContent( $wgUser );
1125 * Get the content of the wanted revision, without section extraction.
1127 * The result of this function can be used to compare user's input with
1128 * section replaced in its context (using WikiPage::replaceSection())
1129 * to the original text of the edit.
1131 * This differs from Article::getContent() that when a missing revision is
1132 * encountered the result will be null and not the
1133 * 'missing-revision' message.
1136 * @param User $user The user to get the revision for
1137 * @return Content|null
1139 private function getOriginalContent( User
$user ) {
1140 if ( $this->section
== 'new' ) {
1141 return $this->getCurrentContent();
1143 $revision = $this->mArticle
->getRevisionFetched();
1144 if ( $revision === null ) {
1145 if ( !$this->contentModel
) {
1146 $this->contentModel
= $this->getTitle()->getContentModel();
1148 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1150 return $handler->makeEmptyContent();
1152 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1157 * Get the current content of the page. This is basically similar to
1158 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1159 * content object is returned instead of null.
1164 protected function getCurrentContent() {
1165 $rev = $this->mArticle
->getRevision();
1166 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1168 if ( $content === false ||
$content === null ) {
1169 if ( !$this->contentModel
) {
1170 $this->contentModel
= $this->getTitle()->getContentModel();
1172 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1174 return $handler->makeEmptyContent();
1176 # nasty side-effect, but needed for consistency
1177 $this->contentModel
= $rev->getContentModel();
1178 $this->contentFormat
= $rev->getContentFormat();
1185 * Use this method before edit() to preload some content into the edit box
1187 * @param Content $content
1191 public function setPreloadedContent( Content
$content ) {
1192 $this->mPreloadContent
= $content;
1196 * Get the contents to be preloaded into the box, either set by
1197 * an earlier setPreloadText() or by loading the given page.
1199 * @param string $preload Representing the title to preload from.
1200 * @param array $params Parameters to use (interface-message style) in the preloaded text
1206 protected function getPreloadedContent( $preload, $params = array() ) {
1209 if ( !empty( $this->mPreloadContent
) ) {
1210 return $this->mPreloadContent
;
1213 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1215 if ( $preload === '' ) {
1216 return $handler->makeEmptyContent();
1219 $title = Title
::newFromText( $preload );
1220 # Check for existence to avoid getting MediaWiki:Noarticletext
1221 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1222 //TODO: somehow show a warning to the user!
1223 return $handler->makeEmptyContent();
1226 $page = WikiPage
::factory( $title );
1227 if ( $page->isRedirect() ) {
1228 $title = $page->getRedirectTarget();
1230 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1231 //TODO: somehow show a warning to the user!
1232 return $handler->makeEmptyContent();
1234 $page = WikiPage
::factory( $title );
1237 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1238 $content = $page->getContent( Revision
::RAW
);
1241 //TODO: somehow show a warning to the user!
1242 return $handler->makeEmptyContent();
1245 if ( $content->getModel() !== $handler->getModelID() ) {
1246 $converted = $content->convert( $handler->getModelID() );
1248 if ( !$converted ) {
1249 //TODO: somehow show a warning to the user!
1250 wfDebug( "Attempt to preload incompatible content: " .
1251 "can't convert " . $content->getModel() .
1252 " to " . $handler->getModelID() );
1254 return $handler->makeEmptyContent();
1257 $content = $converted;
1260 return $content->preloadTransform( $title, $parserOptions, $params );
1264 * Make sure the form isn't faking a user's credentials.
1266 * @param WebRequest $request
1270 function tokenOk( &$request ) {
1272 $token = $request->getVal( 'wpEditToken' );
1273 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1274 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1275 return $this->mTokenOk
;
1279 * Sets post-edit cookie indicating the user just saved a particular revision.
1281 * This uses a temporary cookie for each revision ID so separate saves will never
1282 * interfere with each other.
1284 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1285 * the redirect. It must be clearable by JavaScript code, so it must not be
1286 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1289 * If the variable were set on the server, it would be cached, which is unwanted
1290 * since the post-edit state should only apply to the load right after the save.
1292 * @param int $statusValue The status value (to check for new article status)
1294 protected function setPostEditCookie( $statusValue ) {
1295 $revisionId = $this->mArticle
->getLatest();
1296 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1299 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1301 } elseif ( $this->oldid
) {
1305 $response = RequestContext
::getMain()->getRequest()->response();
1306 $response->setcookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
, array(
1307 'httpOnly' => false,
1312 * Attempt submission
1313 * @param array $resultDetails See docs for $result in internalAttemptSave
1314 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1315 * @return Status The resulting status object.
1317 public function attemptSave( &$resultDetails = false ) {
1320 # Allow bots to exempt some edits from bot flagging
1321 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1322 $status = $this->internalAttemptSave( $resultDetails, $bot );
1324 Hooks
::run( 'EditPage::attemptSave:after', array( $this, $status, $resultDetails ) );
1330 * Handle status, such as after attempt save
1332 * @param Status $status
1333 * @param array|bool $resultDetails
1335 * @throws ErrorPageError
1336 * @return bool False, if output is done, true if rest of the form should be displayed
1338 private function handleStatus( Status
$status, $resultDetails ) {
1339 global $wgUser, $wgOut;
1342 * @todo FIXME: once the interface for internalAttemptSave() is made
1343 * nicer, this should use the message in $status
1345 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1346 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1348 $this->didSave
= true;
1349 if ( !$resultDetails['nullEdit'] ) {
1350 $this->setPostEditCookie( $status->value
);
1354 switch ( $status->value
) {
1355 case self
::AS_HOOK_ERROR_EXPECTED
:
1356 case self
::AS_CONTENT_TOO_BIG
:
1357 case self
::AS_ARTICLE_WAS_DELETED
:
1358 case self
::AS_CONFLICT_DETECTED
:
1359 case self
::AS_SUMMARY_NEEDED
:
1360 case self
::AS_TEXTBOX_EMPTY
:
1361 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1363 case self
::AS_BLANK_ARTICLE
:
1364 case self
::AS_SELF_REDIRECT
:
1367 case self
::AS_HOOK_ERROR
:
1370 case self
::AS_CANNOT_USE_CUSTOM_MODEL
:
1371 case self
::AS_PARSE_ERROR
:
1372 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1375 case self
::AS_SUCCESS_NEW_ARTICLE
:
1376 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1377 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1378 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1381 case self
::AS_SUCCESS_UPDATE
:
1383 $sectionanchor = $resultDetails['sectionanchor'];
1385 // Give extensions a chance to modify URL query on update
1387 'ArticleUpdateBeforeRedirect',
1388 array( $this->mArticle
, &$sectionanchor, &$extraQuery )
1391 if ( $resultDetails['redirect'] ) {
1392 if ( $extraQuery == '' ) {
1393 $extraQuery = 'redirect=no';
1395 $extraQuery = 'redirect=no&' . $extraQuery;
1398 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1401 case self
::AS_SPAM_ERROR
:
1402 $this->spamPageWithContent( $resultDetails['spam'] );
1405 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1406 throw new UserBlockedError( $wgUser->getBlock() );
1408 case self
::AS_IMAGE_REDIRECT_ANON
:
1409 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1410 throw new PermissionsError( 'upload' );
1412 case self
::AS_READ_ONLY_PAGE_ANON
:
1413 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1414 throw new PermissionsError( 'edit' );
1416 case self
::AS_READ_ONLY_PAGE
:
1417 throw new ReadOnlyError
;
1419 case self
::AS_RATE_LIMITED
:
1420 throw new ThrottledError();
1422 case self
::AS_NO_CREATE_PERMISSION
:
1423 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1424 throw new PermissionsError( $permission );
1426 case self
::AS_NO_CHANGE_CONTENT_MODEL
:
1427 throw new PermissionsError( 'editcontentmodel' );
1430 // We don't recognize $status->value. The only way that can happen
1431 // is if an extension hook aborted from inside ArticleSave.
1432 // Render the status object into $this->hookError
1433 // FIXME this sucks, we should just use the Status object throughout
1434 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1441 * Run hooks that can filter edits just before they get saved.
1443 * @param Content $content The Content to filter.
1444 * @param Status $status For reporting the outcome to the caller
1445 * @param User $user The user performing the edit
1449 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1450 // Run old style post-section-merge edit filter
1451 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1452 array( $this, $content, &$this->hookError
, $this->summary
) )
1454 # Error messages etc. could be handled within the hook...
1455 $status->fatal( 'hookaborted' );
1456 $status->value
= self
::AS_HOOK_ERROR
;
1458 } elseif ( $this->hookError
!= '' ) {
1459 # ...or the hook could be expecting us to produce an error
1460 $status->fatal( 'hookaborted' );
1461 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1465 // Run new style post-section-merge edit filter
1466 if ( !Hooks
::run( 'EditFilterMergedContent',
1467 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1468 $user, $this->minoredit
) )
1470 # Error messages etc. could be handled within the hook...
1471 if ( $status->isGood() ) {
1472 $status->fatal( 'hookaborted' );
1473 // Not setting $this->hookError here is a hack to allow the hook
1474 // to cause a return to the edit page without $this->hookError
1475 // being set. This is used by ConfirmEdit to display a captcha
1476 // without any error message cruft.
1478 $this->hookError
= $status->getWikiText();
1480 // Use the existing $status->value if the hook set it
1481 if ( !$status->value
) {
1482 $status->value
= self
::AS_HOOK_ERROR
;
1485 } elseif ( !$status->isOK() ) {
1486 # ...or the hook could be expecting us to produce an error
1487 // FIXME this sucks, we should just use the Status object throughout
1488 $this->hookError
= $status->getWikiText();
1489 $status->fatal( 'hookaborted' );
1490 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1498 * Return the summary to be used for a new section.
1500 * @param string $sectionanchor Set to the section anchor text
1503 private function newSectionSummary( &$sectionanchor = null ) {
1506 if ( $this->sectiontitle
!== '' ) {
1507 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1508 // If no edit summary was specified, create one automatically from the section
1509 // title and have it link to the new section. Otherwise, respect the summary as
1511 if ( $this->summary
=== '' ) {
1512 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1513 return wfMessage( 'newsectionsummary' )
1514 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1516 } elseif ( $this->summary
!== '' ) {
1517 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1518 # This is a new section, so create a link to the new section
1519 # in the revision summary.
1520 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1521 return wfMessage( 'newsectionsummary' )
1522 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1524 return $this->summary
;
1528 * Attempt submission (no UI)
1530 * @param array $result Array to add statuses to, currently with the
1532 * - spam (string): Spam string from content if any spam is detected by
1534 * - sectionanchor (string): Section anchor for a section save.
1535 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1537 * - redirect (bool): Set if doEditContent is OK. True if resulting
1538 * revision is a redirect.
1539 * @param bool $bot True if edit is being made under the bot right.
1541 * @return Status Status object, possibly with a message, but always with
1542 * one of the AS_* constants in $status->value,
1544 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1545 * various error display idiosyncrasies. There are also lots of cases
1546 * where error metadata is set in the object and retrieved later instead
1547 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1548 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1551 function internalAttemptSave( &$result, $bot = false ) {
1552 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1553 global $wgContentHandlerUseDB;
1555 $status = Status
::newGood();
1557 if ( !Hooks
::run( 'EditPage::attemptSave', array( $this ) ) ) {
1558 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1559 $status->fatal( 'hookaborted' );
1560 $status->value
= self
::AS_HOOK_ERROR
;
1564 $spam = $wgRequest->getText( 'wpAntispam' );
1565 if ( $spam !== '' ) {
1568 $wgUser->getName() .
1570 $this->mTitle
->getPrefixedText() .
1571 '" submitted bogus field "' .
1575 $status->fatal( 'spamprotectionmatch', false );
1576 $status->value
= self
::AS_SPAM_ERROR
;
1581 # Construct Content object
1582 $textbox_content = $this->toEditContent( $this->textbox1
);
1583 } catch ( MWContentSerializationException
$ex ) {
1585 'content-failed-to-parse',
1586 $this->contentModel
,
1587 $this->contentFormat
,
1590 $status->value
= self
::AS_PARSE_ERROR
;
1594 # Check image redirect
1595 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1596 $textbox_content->isRedirect() &&
1597 !$wgUser->isAllowed( 'upload' )
1599 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1600 $status->setResult( false, $code );
1606 $match = self
::matchSummarySpamRegex( $this->summary
);
1607 if ( $match === false && $this->section
== 'new' ) {
1608 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1609 # regular summaries, it is added to the actual wikitext.
1610 if ( $this->sectiontitle
!== '' ) {
1611 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1612 $match = self
::matchSpamRegex( $this->sectiontitle
);
1614 # This branch is taken when the "Add Topic" user interface is used, or the API
1615 # is used with the 'summary' parameter.
1616 $match = self
::matchSpamRegex( $this->summary
);
1619 if ( $match === false ) {
1620 $match = self
::matchSpamRegex( $this->textbox1
);
1622 if ( $match !== false ) {
1623 $result['spam'] = $match;
1624 $ip = $wgRequest->getIP();
1625 $pdbk = $this->mTitle
->getPrefixedDBkey();
1626 $match = str_replace( "\n", '', $match );
1627 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1628 $status->fatal( 'spamprotectionmatch', $match );
1629 $status->value
= self
::AS_SPAM_ERROR
;
1634 array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) )
1636 # Error messages etc. could be handled within the hook...
1637 $status->fatal( 'hookaborted' );
1638 $status->value
= self
::AS_HOOK_ERROR
;
1640 } elseif ( $this->hookError
!= '' ) {
1641 # ...or the hook could be expecting us to produce an error
1642 $status->fatal( 'hookaborted' );
1643 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1647 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1648 // Auto-block user's IP if the account was "hard" blocked
1649 $wgUser->spreadAnyEditBlock();
1650 # Check block state against master, thus 'false'.
1651 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1655 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1656 if ( $this->kblength
> $wgMaxArticleSize ) {
1657 // Error will be displayed by showEditForm()
1658 $this->tooBig
= true;
1659 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1663 if ( !$wgUser->isAllowed( 'edit' ) ) {
1664 if ( $wgUser->isAnon() ) {
1665 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1668 $status->fatal( 'readonlytext' );
1669 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1674 $changingContentModel = false;
1675 if ( $this->contentModel
!== $this->mTitle
->getContentModel() ) {
1676 if ( !$wgContentHandlerUseDB ) {
1677 $status->fatal( 'editpage-cannot-use-custom-model' );
1678 $status->value
= self
::AS_CANNOT_USE_CUSTOM_MODEL
;
1680 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1681 $status->setResult( false, self
::AS_NO_CHANGE_CONTENT_MODEL
);
1685 $changingContentModel = true;
1686 $oldContentModel = $this->mTitle
->getContentModel();
1689 if ( $this->changeTags
) {
1690 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
1691 $this->changeTags
, $wgUser );
1692 if ( !$changeTagsStatus->isOK() ) {
1693 $changeTagsStatus->value
= self
::AS_CHANGE_TAG_ERROR
;
1694 return $changeTagsStatus;
1698 if ( wfReadOnly() ) {
1699 $status->fatal( 'readonlytext' );
1700 $status->value
= self
::AS_READ_ONLY_PAGE
;
1703 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1704 $status->fatal( 'actionthrottledtext' );
1705 $status->value
= self
::AS_RATE_LIMITED
;
1709 # If the article has been deleted while editing, don't save it without
1711 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1712 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1716 # Load the page data from the master. If anything changes in the meantime,
1717 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1718 $this->mArticle
->loadPageData( 'fromdbmaster' );
1719 $new = !$this->mArticle
->exists();
1722 // Late check for create permission, just in case *PARANOIA*
1723 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1724 $status->fatal( 'nocreatetext' );
1725 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1726 wfDebug( __METHOD__
. ": no create permission\n" );
1730 // Don't save a new page if it's blank or if it's a MediaWiki:
1731 // message with content equivalent to default (allow empty pages
1732 // in this case to disable messages, see bug 50124)
1733 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1734 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1735 $defaultText = $defaultMessageText;
1740 if ( !$this->allowBlankArticle
&& $this->textbox1
=== $defaultText ) {
1741 $this->blankArticle
= true;
1742 $status->fatal( 'blankarticle' );
1743 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1747 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1751 $content = $textbox_content;
1753 $result['sectionanchor'] = '';
1754 if ( $this->section
== 'new' ) {
1755 if ( $this->sectiontitle
!== '' ) {
1756 // Insert the section title above the content.
1757 $content = $content->addSectionHeader( $this->sectiontitle
);
1758 } elseif ( $this->summary
!== '' ) {
1759 // Insert the section title above the content.
1760 $content = $content->addSectionHeader( $this->summary
);
1762 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1765 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1769 # Article exists. Check for edit conflict.
1771 $this->mArticle
->clear(); # Force reload of dates, etc.
1772 $timestamp = $this->mArticle
->getTimestamp();
1774 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1776 if ( $timestamp != $this->edittime
) {
1777 $this->isConflict
= true;
1778 if ( $this->section
== 'new' ) {
1779 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1780 $this->mArticle
->getComment() == $this->newSectionSummary()
1782 // Probably a duplicate submission of a new comment.
1783 // This can happen when squid resends a request after
1784 // a timeout but the first one actually went through.
1786 . ": duplicate new section submission; trigger edit conflict!\n" );
1788 // New comment; suppress conflict.
1789 $this->isConflict
= false;
1790 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1792 } elseif ( $this->section
== ''
1793 && Revision
::userWasLastToEdit(
1794 DB_MASTER
, $this->mTitle
->getArticleID(),
1795 $wgUser->getId(), $this->edittime
1798 # Suppress edit conflict with self, except for section edits where merging is required.
1799 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1800 $this->isConflict
= false;
1804 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1805 if ( $this->sectiontitle
!== '' ) {
1806 $sectionTitle = $this->sectiontitle
;
1808 $sectionTitle = $this->summary
;
1813 if ( $this->isConflict
) {
1815 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1816 . " (article time '{$timestamp}')\n" );
1818 $content = $this->mArticle
->replaceSectionContent(
1825 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1826 $content = $this->mArticle
->replaceSectionContent(
1833 if ( is_null( $content ) ) {
1834 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1835 $this->isConflict
= true;
1836 $content = $textbox_content; // do not try to merge here!
1837 } elseif ( $this->isConflict
) {
1839 if ( $this->mergeChangesIntoContent( $content ) ) {
1840 // Successful merge! Maybe we should tell the user the good news?
1841 $this->isConflict
= false;
1842 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1844 $this->section
= '';
1845 $this->textbox1
= ContentHandler
::getContentText( $content );
1846 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1850 if ( $this->isConflict
) {
1851 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1855 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1859 if ( $this->section
== 'new' ) {
1860 // Handle the user preference to force summaries here
1861 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1862 $this->missingSummary
= true;
1863 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1864 $status->value
= self
::AS_SUMMARY_NEEDED
;
1868 // Do not allow the user to post an empty comment
1869 if ( $this->textbox1
== '' ) {
1870 $this->missingComment
= true;
1871 $status->fatal( 'missingcommenttext' );
1872 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1875 } elseif ( !$this->allowBlankSummary
1876 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1877 && !$content->isRedirect()
1878 && md5( $this->summary
) == $this->autoSumm
1880 $this->missingSummary
= true;
1881 $status->fatal( 'missingsummary' );
1882 $status->value
= self
::AS_SUMMARY_NEEDED
;
1887 $sectionanchor = '';
1888 if ( $this->section
== 'new' ) {
1889 $this->summary
= $this->newSectionSummary( $sectionanchor );
1890 } elseif ( $this->section
!= '' ) {
1891 # Try to get a section anchor from the section source, redirect
1892 # to edited section if header found.
1893 # XXX: Might be better to integrate this into Article::replaceSection
1894 # for duplicate heading checking and maybe parsing.
1895 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1896 # We can't deal with anchors, includes, html etc in the header for now,
1897 # headline would need to be parsed to improve this.
1898 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1899 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1902 $result['sectionanchor'] = $sectionanchor;
1904 // Save errors may fall down to the edit form, but we've now
1905 // merged the section into full text. Clear the section field
1906 // so that later submission of conflict forms won't try to
1907 // replace that into a duplicated mess.
1908 $this->textbox1
= $this->toEditText( $content );
1909 $this->section
= '';
1911 $status->value
= self
::AS_SUCCESS_UPDATE
;
1914 if ( !$this->allowSelfRedirect
1915 && $content->isRedirect()
1916 && $content->getRedirectTarget()->equals( $this->getTitle() )
1918 // If the page already redirects to itself, don't warn.
1919 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
1920 if ( !$currentTarget ||
!$currentTarget->equals( $this->getTitle() ) ) {
1921 $this->selfRedirect
= true;
1922 $status->fatal( 'selfredirect' );
1923 $status->value
= self
::AS_SELF_REDIRECT
;
1928 // Check for length errors again now that the section is merged in
1929 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1930 if ( $this->kblength
> $wgMaxArticleSize ) {
1931 $this->tooBig
= true;
1932 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1936 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1937 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1938 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1939 ( $bot ? EDIT_FORCE_BOT
: 0 );
1941 $doEditStatus = $this->mArticle
->doEditContent(
1947 $content->getDefaultFormat()
1950 if ( !$doEditStatus->isOK() ) {
1951 // Failure from doEdit()
1952 // Show the edit conflict page for certain recognized errors from doEdit(),
1953 // but don't show it for errors from extension hooks
1954 $errors = $doEditStatus->getErrorsArray();
1955 if ( in_array( $errors[0][0],
1956 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1958 $this->isConflict
= true;
1959 // Destroys data doEdit() put in $status->value but who cares
1960 $doEditStatus->value
= self
::AS_END
;
1962 return $doEditStatus;
1965 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1966 if ( $result['nullEdit'] ) {
1967 // We don't know if it was a null edit until now, so increment here
1968 $wgUser->pingLimiter( 'linkpurge' );
1970 $result['redirect'] = $content->isRedirect();
1972 $this->updateWatchlist();
1974 if ( $this->changeTags
&& isset( $doEditStatus->value
['revision'] ) ) {
1975 // If a revision was created, apply any change tags that were requested
1976 $addTags = $this->changeTags
;
1977 $revId = $doEditStatus->value
['revision']->getId();
1978 // Defer this both for performance and so that addTags() sees the rc_id
1979 // since the recentchange entry addition is deferred first (bug T100248)
1980 DeferredUpdates
::addCallableUpdate( function() use ( $addTags, $revId ) {
1981 ChangeTags
::addTags( $addTags, null, $revId );
1985 // If the content model changed, add a log entry
1986 if ( $changingContentModel ) {
1987 $this->addContentModelChangeLogEntry(
1990 $this->contentModel
,
1999 * @param Title $title
2000 * @param string $oldModel
2001 * @param string $newModel
2002 * @param string $reason
2004 protected function addContentModelChangeLogEntry( User
$user, $oldModel, $newModel, $reason ) {
2005 $log = new ManualLogEntry( 'contentmodel', 'change' );
2006 $log->setPerformer( $user );
2007 $log->setTarget( $this->mTitle
);
2008 $log->setComment( $reason );
2009 $log->setParameters( array(
2010 '4::oldmodel' => $oldModel,
2011 '5::newmodel' => $newModel
2013 $logid = $log->insert();
2014 $log->publish( $logid );
2019 * Register the change of watch status
2021 protected function updateWatchlist() {
2024 if ( $wgUser->isLoggedIn()
2025 && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
, WatchedItem
::IGNORE_USER_RIGHTS
)
2027 $fname = __METHOD__
;
2028 $title = $this->mTitle
;
2029 $watch = $this->watchthis
;
2031 // Do this in its own transaction to reduce contention...
2032 $dbw = wfGetDB( DB_MASTER
);
2033 $dbw->onTransactionIdle( function () use ( $dbw, $title, $watch, $wgUser, $fname ) {
2034 WatchAction
::doWatchOrUnwatch( $watch, $title, $wgUser );
2040 * Attempts to do 3-way merge of edit content with a base revision
2041 * and current content, in case of edit conflict, in whichever way appropriate
2042 * for the content type.
2046 * @param Content $editContent
2050 private function mergeChangesIntoContent( &$editContent ) {
2052 $db = wfGetDB( DB_MASTER
);
2054 // This is the revision the editor started from
2055 $baseRevision = $this->getBaseRevision();
2056 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2058 if ( is_null( $baseContent ) ) {
2062 // The current state, we want to merge updates into it
2063 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2064 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2066 if ( is_null( $currentContent ) ) {
2070 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2072 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2075 $editContent = $result;
2085 function getBaseRevision() {
2086 if ( !$this->mBaseRevision
) {
2087 $db = wfGetDB( DB_MASTER
);
2088 $this->mBaseRevision
= Revision
::loadFromTimestamp(
2089 $db, $this->mTitle
, $this->edittime
);
2091 return $this->mBaseRevision
;
2095 * Check given input text against $wgSpamRegex, and return the text of the first match.
2097 * @param string $text
2099 * @return string|bool Matching string or false
2101 public static function matchSpamRegex( $text ) {
2102 global $wgSpamRegex;
2103 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2104 $regexes = (array)$wgSpamRegex;
2105 return self
::matchSpamRegexInternal( $text, $regexes );
2109 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2111 * @param string $text
2113 * @return string|bool Matching string or false
2115 public static function matchSummarySpamRegex( $text ) {
2116 global $wgSummarySpamRegex;
2117 $regexes = (array)$wgSummarySpamRegex;
2118 return self
::matchSpamRegexInternal( $text, $regexes );
2122 * @param string $text
2123 * @param array $regexes
2124 * @return bool|string
2126 protected static function matchSpamRegexInternal( $text, $regexes ) {
2127 foreach ( $regexes as $regex ) {
2129 if ( preg_match( $regex, $text, $matches ) ) {
2136 function setHeaders() {
2137 global $wgOut, $wgUser, $wgAjaxEditStash;
2139 $wgOut->addModules( 'mediawiki.action.edit' );
2140 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2142 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2143 // The addition of default buttons is handled by getEditToolbar() which
2144 // has its own dependency on this module. The call here ensures the module
2145 // is loaded in time (it has position "top") for other modules to register
2146 // buttons (e.g. extensions, gadgets, user scripts).
2147 $wgOut->addModules( 'mediawiki.toolbar' );
2150 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2151 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2154 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2155 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2158 if ( $wgAjaxEditStash ) {
2159 $wgOut->addModules( 'mediawiki.action.edit.stash' );
2162 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2164 # Enabled article-related sidebar, toplinks, etc.
2165 $wgOut->setArticleRelated( true );
2167 $contextTitle = $this->getContextTitle();
2168 if ( $this->isConflict
) {
2169 $msg = 'editconflict';
2170 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2171 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2173 $msg = $contextTitle->exists()
2174 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2175 && $contextTitle->getDefaultMessageText() !== false
2181 # Use the title defined by DISPLAYTITLE magic word when present
2182 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2183 if ( $displayTitle === false ) {
2184 $displayTitle = $contextTitle->getPrefixedText();
2186 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2187 # Transmit the name of the message to JavaScript for live preview
2188 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2189 $wgOut->addJsConfigVars( 'wgEditMessage', $msg );
2193 * Show all applicable editing introductions
2195 protected function showIntro() {
2196 global $wgOut, $wgUser;
2197 if ( $this->suppressIntro
) {
2201 $namespace = $this->mTitle
->getNamespace();
2203 if ( $namespace == NS_MEDIAWIKI
) {
2204 # Show a warning if editing an interface message
2205 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2206 # If this is a default message (but not css or js),
2207 # show a hint that it is translatable on translatewiki.net
2208 if ( !$this->mTitle
->hasContentModel( CONTENT_MODEL_CSS
)
2209 && !$this->mTitle
->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
2211 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
2212 if ( $defaultMessageText !== false ) {
2213 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2214 'translateinterface' );
2217 } elseif ( $namespace == NS_FILE
) {
2218 # Show a hint to shared repo
2219 $file = wfFindFile( $this->mTitle
);
2220 if ( $file && !$file->isLocal() ) {
2221 $descUrl = $file->getDescriptionUrl();
2222 # there must be a description url to show a hint to shared repo
2224 if ( !$this->mTitle
->exists() ) {
2225 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2226 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2229 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2230 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2237 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2238 # Show log extract when the user is currently blocked
2239 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2240 $parts = explode( '/', $this->mTitle
->getText(), 2 );
2241 $username = $parts[0];
2242 $user = User
::newFromName( $username, false /* allow IP users*/ );
2243 $ip = User
::isIP( $username );
2244 $block = Block
::newFromTarget( $user, $user );
2245 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2246 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2247 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2248 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) {
2249 # Show log extract if the user is currently blocked
2250 LogEventsList
::showLogExtract(
2253 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2257 'showIfEmpty' => false,
2259 'blocked-notice-logextract',
2260 $user->getName() # Support GENDER in notice
2266 # Try to add a custom edit intro, or use the standard one if this is not possible.
2267 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2268 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2269 wfMessage( 'helppage' )->inContentLanguage()->text()
2271 if ( $wgUser->isLoggedIn() ) {
2272 $wgOut->wrapWikiMsg(
2273 // Suppress the external link icon, consider the help url an internal one
2274 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2281 $wgOut->wrapWikiMsg(
2282 // Suppress the external link icon, consider the help url an internal one
2283 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2285 'newarticletextanon',
2291 # Give a notice if the user is editing a deleted/moved page...
2292 if ( !$this->mTitle
->exists() ) {
2293 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
2297 'conds' => array( "log_action != 'revision'" ),
2298 'showIfEmpty' => false,
2299 'msgKey' => array( 'recreate-moveddeleted-warn' )
2306 * Attempt to show a custom editing introduction, if supplied
2310 protected function showCustomIntro() {
2311 if ( $this->editintro
) {
2312 $title = Title
::newFromText( $this->editintro
);
2313 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2315 // Added using template syntax, to take <noinclude>'s into account.
2316 $wgOut->addWikiTextTitleTidy(
2317 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2327 * Gets an editable textual representation of $content.
2328 * The textual representation can be turned by into a Content object by the
2329 * toEditContent() method.
2331 * If $content is null or false or a string, $content is returned unchanged.
2333 * If the given Content object is not of a type that can be edited using
2334 * the text base EditPage, an exception will be raised. Set
2335 * $this->allowNonTextContent to true to allow editing of non-textual
2338 * @param Content|null|bool|string $content
2339 * @return string The editable text form of the content.
2341 * @throws MWException If $content is not an instance of TextContent and
2342 * $this->allowNonTextContent is not true.
2344 protected function toEditText( $content ) {
2345 if ( $content === null ||
$content === false ||
is_string( $content ) ) {
2349 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2350 throw new MWException( 'This content model is not supported: '
2351 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2354 return $content->serialize( $this->contentFormat
);
2358 * Turns the given text into a Content object by unserializing it.
2360 * If the resulting Content object is not of a type that can be edited using
2361 * the text base EditPage, an exception will be raised. Set
2362 * $this->allowNonTextContent to true to allow editing of non-textual
2365 * @param string|null|bool $text Text to unserialize
2366 * @return Content The content object created from $text. If $text was false
2367 * or null, false resp. null will be returned instead.
2369 * @throws MWException If unserializing the text results in a Content
2370 * object that is not an instance of TextContent and
2371 * $this->allowNonTextContent is not true.
2373 protected function toEditContent( $text ) {
2374 if ( $text === false ||
$text === null ) {
2378 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2379 $this->contentModel
, $this->contentFormat
);
2381 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2382 throw new MWException( 'This content model is not supported: '
2383 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2390 * Send the edit form and related headers to $wgOut
2391 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2392 * during form output near the top, for captchas and the like.
2394 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2395 * use the EditPage::showEditForm:fields hook instead.
2397 function showEditForm( $formCallback = null ) {
2398 global $wgOut, $wgUser;
2400 # need to parse the preview early so that we know which templates are used,
2401 # otherwise users with "show preview after edit box" will get a blank list
2402 # we parse this near the beginning so that setHeaders can do the title
2403 # setting work instead of leaving it in getPreviewText
2404 $previewOutput = '';
2405 if ( $this->formtype
== 'preview' ) {
2406 $previewOutput = $this->getPreviewText();
2409 Hooks
::run( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2411 $this->setHeaders();
2413 if ( $this->showHeader() === false ) {
2417 $wgOut->addHTML( $this->editFormPageTop
);
2419 if ( $wgUser->getOption( 'previewontop' ) ) {
2420 $this->displayPreviewArea( $previewOutput, true );
2423 $wgOut->addHTML( $this->editFormTextTop
);
2425 $showToolbar = true;
2426 if ( $this->wasDeletedSinceLastEdit() ) {
2427 if ( $this->formtype
== 'save' ) {
2428 // Hide the toolbar and edit area, user can click preview to get it back
2429 // Add an confirmation checkbox and explanation.
2430 $showToolbar = false;
2432 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2433 'deletedwhileediting' );
2437 // @todo add EditForm plugin interface and use it here!
2438 // search for textarea1 and textares2, and allow EditForm to override all uses.
2439 $wgOut->addHTML( Html
::openElement(
2442 'id' => self
::EDITFORM_ID
,
2443 'name' => self
::EDITFORM_ID
,
2445 'action' => $this->getActionURL( $this->getContextTitle() ),
2446 'enctype' => 'multipart/form-data'
2450 if ( is_callable( $formCallback ) ) {
2451 wfWarn( 'The $formCallback parameter to ' . __METHOD__
. 'is deprecated' );
2452 call_user_func_array( $formCallback, array( &$wgOut ) );
2455 // Add an empty field to trip up spambots
2457 Xml
::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2460 array( 'for' => 'wpAntiSpam' ),
2461 wfMessage( 'simpleantispam-label' )->parse()
2467 'name' => 'wpAntispam',
2468 'id' => 'wpAntispam',
2472 . Xml
::closeElement( 'div' )
2475 Hooks
::run( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2477 // Put these up at the top to ensure they aren't lost on early form submission
2478 $this->showFormBeforeText();
2480 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2481 $username = $this->lastDelete
->user_name
;
2482 $comment = $this->lastDelete
->log_comment
;
2484 // It is better to not parse the comment at all than to have templates expanded in the middle
2485 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2486 $key = $comment === ''
2487 ?
'confirmrecreate-noreason'
2488 : 'confirmrecreate';
2490 '<div class="mw-confirm-recreate">' .
2491 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2492 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2493 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2499 # When the summary is hidden, also hide them on preview/show changes
2500 if ( $this->nosummary
) {
2501 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2504 # If a blank edit summary was previously provided, and the appropriate
2505 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2506 # user being bounced back more than once in the event that a summary
2509 # For a bit more sophisticated detection of blank summaries, hash the
2510 # automatic one and pass that in the hidden field wpAutoSummary.
2511 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2512 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2515 if ( $this->undidRev
) {
2516 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2519 if ( $this->selfRedirect
) {
2520 $wgOut->addHTML( Html
::hidden( 'wpIgnoreSelfRedirect', true ) );
2523 if ( $this->hasPresetSummary
) {
2524 // If a summary has been preset using &summary= we don't want to prompt for
2525 // a different summary. Only prompt for a summary if the summary is blanked.
2527 $this->autoSumm
= md5( '' );
2530 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2531 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2533 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2534 $wgOut->addHTML( Html
::hidden( 'parentRevId',
2535 $this->parentRevId ?
: $this->mArticle
->getRevIdFetched() ) );
2537 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2538 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2540 if ( $this->section
== 'new' ) {
2541 $this->showSummaryInput( true, $this->summary
);
2542 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2545 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2547 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2548 $wgOut->addHTML( EditPage
::getEditToolbar() );
2551 if ( $this->blankArticle
) {
2552 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankArticle', true ) );
2555 if ( $this->isConflict
) {
2556 // In an edit conflict bypass the overridable content form method
2557 // and fallback to the raw wpTextbox1 since editconflicts can't be
2558 // resolved between page source edits and custom ui edits using the
2560 $this->textbox2
= $this->textbox1
;
2562 $content = $this->getCurrentContent();
2563 $this->textbox1
= $this->toEditText( $content );
2565 $this->showTextbox1();
2567 $this->showContentForm();
2570 $wgOut->addHTML( $this->editFormTextAfterContent
);
2572 $this->showStandardInputs();
2574 $this->showFormAfterText();
2576 $this->showTosSummary();
2578 $this->showEditTools();
2580 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2582 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2583 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2585 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2586 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2588 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'limitreport' ),
2589 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2591 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2593 if ( $this->isConflict
) {
2595 $this->showConflict();
2596 } catch ( MWContentSerializationException
$ex ) {
2597 // this can't really happen, but be nice if it does.
2599 'content-failed-to-parse',
2600 $this->contentModel
,
2601 $this->contentFormat
,
2604 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2608 // Marker for detecting truncated form data. This must be the last
2609 // parameter sent in order to be of use, so do not move me.
2610 $wgOut->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2611 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2613 if ( !$wgUser->getOption( 'previewontop' ) ) {
2614 $this->displayPreviewArea( $previewOutput, false );
2620 * Extract the section title from current section text, if any.
2622 * @param string $text
2623 * @return string|bool String or false
2625 public static function extractSectionTitle( $text ) {
2626 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2627 if ( !empty( $matches[2] ) ) {
2629 return $wgParser->stripSectionName( trim( $matches[2] ) );
2638 protected function showHeader() {
2639 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2640 global $wgAllowUserCss, $wgAllowUserJs;
2642 if ( $this->mTitle
->isTalkPage() ) {
2643 $wgOut->addWikiMsg( 'talkpagetext' );
2647 $editNotices = $this->mTitle
->getEditNotices( $this->oldid
);
2648 if ( count( $editNotices ) ) {
2649 $wgOut->addHTML( implode( "\n", $editNotices ) );
2651 $msg = wfMessage( 'editnotice-notext' );
2652 if ( !$msg->isDisabled() ) {
2654 '<div class="mw-editnotice-notext">'
2655 . $msg->parseAsBlock()
2661 if ( $this->isConflict
) {
2662 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2663 $this->edittime
= $this->mArticle
->getTimestamp();
2665 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2666 // We use $this->section to much before this and getVal('wgSection') directly in other places
2667 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2668 // Someone is welcome to try refactoring though
2669 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2673 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2674 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2675 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2676 if ( $sectionTitle !== false ) {
2677 $this->summary
= "/* $sectionTitle */ ";
2682 if ( $this->missingComment
) {
2683 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2686 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2687 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2690 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2691 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2694 if ( $this->blankArticle
) {
2695 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2698 if ( $this->selfRedirect
) {
2699 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2702 if ( $this->hookError
!== '' ) {
2703 $wgOut->addWikiText( $this->hookError
);
2706 if ( !$this->checkUnicodeCompliantBrowser() ) {
2707 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2710 if ( $this->section
!= 'new' ) {
2711 $revision = $this->mArticle
->getRevisionFetched();
2713 // Let sysop know that this will make private content public if saved
2715 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2716 $wgOut->wrapWikiMsg(
2717 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2718 'rev-deleted-text-permission'
2720 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2721 $wgOut->wrapWikiMsg(
2722 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2723 'rev-deleted-text-view'
2727 if ( !$revision->isCurrent() ) {
2728 $this->mArticle
->setOldSubtitle( $revision->getId() );
2729 $wgOut->addWikiMsg( 'editingold' );
2731 } elseif ( $this->mTitle
->exists() ) {
2732 // Something went wrong
2734 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2735 array( 'missing-revision', $this->oldid
) );
2740 if ( wfReadOnly() ) {
2741 $wgOut->wrapWikiMsg(
2742 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2743 array( 'readonlywarning', wfReadOnlyReason() )
2745 } elseif ( $wgUser->isAnon() ) {
2746 if ( $this->formtype
!= 'preview' ) {
2747 $wgOut->wrapWikiMsg(
2748 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2749 array( 'anoneditwarning',
2751 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2753 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2756 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2757 'anonpreviewwarning'
2761 if ( $this->isCssJsSubpage
) {
2762 # Check the skin exists
2763 if ( $this->isWrongCaseCssJsPage
) {
2764 $wgOut->wrapWikiMsg(
2765 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2766 array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() )
2769 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
2770 if ( $this->formtype
!== 'preview' ) {
2771 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
2772 $wgOut->wrapWikiMsg(
2773 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2774 array( 'usercssyoucanpreview' )
2778 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
2779 $wgOut->wrapWikiMsg(
2780 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2781 array( 'userjsyoucanpreview' )
2789 if ( $this->mTitle
->isProtected( 'edit' ) &&
2790 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2792 # Is the title semi-protected?
2793 if ( $this->mTitle
->isSemiProtected() ) {
2794 $noticeMsg = 'semiprotectedpagewarning';
2796 # Then it must be protected based on static groups (regular)
2797 $noticeMsg = 'protectedpagewarning';
2799 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2800 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2802 if ( $this->mTitle
->isCascadeProtected() ) {
2803 # Is this page under cascading protection from some source pages?
2804 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2805 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2806 $cascadeSourcesCount = count( $cascadeSources );
2807 if ( $cascadeSourcesCount > 0 ) {
2808 # Explain, and list the titles responsible
2809 foreach ( $cascadeSources as $page ) {
2810 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2813 $notice .= '</div>';
2814 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2816 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2817 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2819 'showIfEmpty' => false,
2820 'msgKey' => array( 'titleprotectedwarning' ),
2821 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2824 if ( $this->kblength
=== false ) {
2825 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2828 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2829 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2832 $wgLang->formatNum( $this->kblength
),
2833 $wgLang->formatNum( $wgMaxArticleSize )
2837 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2838 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2841 $wgLang->formatSize( strlen( $this->textbox1
) ),
2842 strlen( $this->textbox1
)
2847 # Add header copyright warning
2848 $this->showHeaderCopyrightWarning();
2854 * Standard summary input and label (wgSummary), abstracted so EditPage
2855 * subclasses may reorganize the form.
2856 * Note that you do not need to worry about the label's for=, it will be
2857 * inferred by the id given to the input. You can remove them both by
2858 * passing array( 'id' => false ) to $userInputAttrs.
2860 * @param string $summary The value of the summary input
2861 * @param string $labelText The html to place inside the label
2862 * @param array $inputAttrs Array of attrs to use on the input
2863 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2865 * @return array An array in the format array( $label, $input )
2867 function getSummaryInput( $summary = "", $labelText = null,
2868 $inputAttrs = null, $spanLabelAttrs = null
2870 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2871 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2872 'id' => 'wpSummary',
2873 'maxlength' => '200',
2876 'spellcheck' => 'true',
2877 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2879 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2880 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2881 'id' => "wpSummaryLabel"
2888 $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null,
2891 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2894 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2896 return array( $label, $input );
2900 * @param bool $isSubjectPreview True if this is the section subject/title
2901 * up top, or false if this is the comment summary
2902 * down below the textarea
2903 * @param string $summary The text of the summary to display
2905 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2906 global $wgOut, $wgContLang;
2907 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2908 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2909 if ( $isSubjectPreview ) {
2910 if ( $this->nosummary
) {
2914 if ( !$this->mShowSummaryField
) {
2918 $summary = $wgContLang->recodeForEdit( $summary );
2919 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2920 list( $label, $input ) = $this->getSummaryInput(
2923 array( 'class' => $summaryClass ),
2926 $wgOut->addHTML( "{$label} {$input}" );
2930 * @param bool $isSubjectPreview True if this is the section subject/title
2931 * up top, or false if this is the comment summary
2932 * down below the textarea
2933 * @param string $summary The text of the summary to display
2936 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2937 // avoid spaces in preview, gets always trimmed on save
2938 $summary = trim( $summary );
2939 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2945 if ( $isSubjectPreview ) {
2946 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2947 ->inContentLanguage()->text();
2950 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2952 $summary = wfMessage( $message )->parse()
2953 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2954 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2957 protected function showFormBeforeText() {
2959 $section = htmlspecialchars( $this->section
);
2960 $wgOut->addHTML( <<<HTML
2961 <input type='hidden' value="{$section}" name="wpSection"/>
2962 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2963 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2964 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2968 if ( !$this->checkUnicodeCompliantBrowser() ) {
2969 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2973 protected function showFormAfterText() {
2974 global $wgOut, $wgUser;
2976 * To make it harder for someone to slip a user a page
2977 * which submits an edit form to the wiki without their
2978 * knowledge, a random token is associated with the login
2979 * session. If it's not passed back with the submission,
2980 * we won't save the page, or render user JavaScript and
2983 * For anon editors, who may not have a session, we just
2984 * include the constant suffix to prevent editing from
2985 * broken text-mangling proxies.
2987 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2991 * Subpage overridable method for printing the form for page content editing
2992 * By default this simply outputs wpTextbox1
2993 * Subclasses can override this to provide a custom UI for editing;
2994 * be it a form, or simply wpTextbox1 with a modified content that will be
2995 * reverse modified when extracted from the post data.
2996 * Note that this is basically the inverse for importContentFormData
2998 protected function showContentForm() {
2999 $this->showTextbox1();
3003 * Method to output wpTextbox1
3004 * The $textoverride method can be used by subclasses overriding showContentForm
3005 * to pass back to this method.
3007 * @param array $customAttribs Array of html attributes to use in the textarea
3008 * @param string $textoverride Optional text to override $this->textarea1 with
3010 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3011 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
3012 $attribs = array( 'style' => 'display:none;' );
3014 $classes = array(); // Textarea CSS
3015 if ( $this->mTitle
->isProtected( 'edit' ) &&
3016 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
3018 # Is the title semi-protected?
3019 if ( $this->mTitle
->isSemiProtected() ) {
3020 $classes[] = 'mw-textarea-sprotected';
3022 # Then it must be protected based on static groups (regular)
3023 $classes[] = 'mw-textarea-protected';
3025 # Is the title cascade-protected?
3026 if ( $this->mTitle
->isCascadeProtected() ) {
3027 $classes[] = 'mw-textarea-cprotected';
3031 $attribs = array( 'tabindex' => 1 );
3033 if ( is_array( $customAttribs ) ) {
3034 $attribs +
= $customAttribs;
3037 if ( count( $classes ) ) {
3038 if ( isset( $attribs['class'] ) ) {
3039 $classes[] = $attribs['class'];
3041 $attribs['class'] = implode( ' ', $classes );
3046 $textoverride !== null ?
$textoverride : $this->textbox1
,
3052 protected function showTextbox2() {
3053 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
3056 protected function showTextbox( $text, $name, $customAttribs = array() ) {
3057 global $wgOut, $wgUser;
3059 $wikitext = $this->safeUnicodeOutput( $text );
3060 if ( strval( $wikitext ) !== '' ) {
3061 // Ensure there's a newline at the end, otherwise adding lines
3063 // But don't add a newline if the ext is empty, or Firefox in XHTML
3064 // mode will show an extra newline. A bit annoying.
3068 $attribs = $customAttribs +
array(
3071 'cols' => $wgUser->getIntOption( 'cols' ),
3072 'rows' => $wgUser->getIntOption( 'rows' ),
3073 // Avoid PHP notices when appending preferences
3074 // (appending allows customAttribs['style'] to still work).
3078 $pageLang = $this->mTitle
->getPageLanguage();
3079 $attribs['lang'] = $pageLang->getHtmlCode();
3080 $attribs['dir'] = $pageLang->getDir();
3082 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3085 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3089 $classes[] = 'ontop';
3092 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3094 if ( $this->formtype
!= 'preview' ) {
3095 $attribs['style'] = 'display: none;';
3098 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
3100 if ( $this->formtype
== 'preview' ) {
3101 $this->showPreview( $previewOutput );
3103 // Empty content container for LivePreview
3104 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3105 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3106 'class' => 'mw-content-' . $pageViewLang->getDir() );
3107 $wgOut->addHTML( Html
::rawElement( 'div', $attribs ) );
3110 $wgOut->addHTML( '</div>' );
3112 if ( $this->formtype
== 'diff' ) {
3115 } catch ( MWContentSerializationException
$ex ) {
3117 'content-failed-to-parse',
3118 $this->contentModel
,
3119 $this->contentFormat
,
3122 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3128 * Append preview output to $wgOut.
3129 * Includes category rendering if this is a category page.
3131 * @param string $text The HTML to be output for the preview.
3133 protected function showPreview( $text ) {
3135 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3136 $this->mArticle
->openShowCategory();
3138 # This hook seems slightly odd here, but makes things more
3139 # consistent for extensions.
3140 Hooks
::run( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3141 $wgOut->addHTML( $text );
3142 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3143 $this->mArticle
->closeShowCategory();
3148 * Get a diff between the current contents of the edit box and the
3149 * version of the page we're editing from.
3151 * If this is a section edit, we'll replace the section as for final
3152 * save and then make a comparison.
3154 function showDiff() {
3155 global $wgUser, $wgContLang, $wgOut;
3157 $oldtitlemsg = 'currentrev';
3158 # if message does not exist, show diff against the preloaded default
3159 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3160 $oldtext = $this->mTitle
->getDefaultMessageText();
3161 if ( $oldtext !== false ) {
3162 $oldtitlemsg = 'defaultmessagetext';
3163 $oldContent = $this->toEditContent( $oldtext );
3168 $oldContent = $this->getCurrentContent();
3171 $textboxContent = $this->toEditContent( $this->textbox1
);
3173 $newContent = $this->mArticle
->replaceSectionContent(
3174 $this->section
, $textboxContent,
3175 $this->summary
, $this->edittime
);
3177 if ( $newContent ) {
3178 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3179 Hooks
::run( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3181 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
3182 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
3185 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3186 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3187 $newtitle = wfMessage( 'yourtext' )->parse();
3189 if ( !$oldContent ) {
3190 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3193 if ( !$newContent ) {
3194 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3197 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3198 $de->setContent( $oldContent, $newContent );
3200 $difftext = $de->getDiff( $oldtitle, $newtitle );
3201 $de->showDiffStyle();
3206 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3210 * Show the header copyright warning.
3212 protected function showHeaderCopyrightWarning() {
3213 $msg = 'editpage-head-copy-warn';
3214 if ( !wfMessage( $msg )->isDisabled() ) {
3216 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3217 'editpage-head-copy-warn' );
3222 * Give a chance for site and per-namespace customizations of
3223 * terms of service summary link that might exist separately
3224 * from the copyright notice.
3226 * This will display between the save button and the edit tools,
3227 * so should remain short!
3229 protected function showTosSummary() {
3230 $msg = 'editpage-tos-summary';
3231 Hooks
::run( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
3232 if ( !wfMessage( $msg )->isDisabled() ) {
3234 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3235 $wgOut->addWikiMsg( $msg );
3236 $wgOut->addHTML( '</div>' );
3240 protected function showEditTools() {
3242 $wgOut->addHTML( '<div class="mw-editTools">' .
3243 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3248 * Get the copyright warning
3250 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3253 protected function getCopywarn() {
3254 return self
::getCopyrightWarning( $this->mTitle
);
3258 * Get the copyright warning, by default returns wikitext
3260 * @param Title $title
3261 * @param string $format Output format, valid values are any function of a Message object
3264 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3265 global $wgRightsText;
3266 if ( $wgRightsText ) {
3267 $copywarnMsg = array( 'copyrightwarning',
3268 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3271 $copywarnMsg = array( 'copyrightwarning2',
3272 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3274 // Allow for site and per-namespace customization of contribution/copyright notice.
3275 Hooks
::run( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3277 return "<div id=\"editpage-copywarn\">\n" .
3278 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3282 * Get the Limit report for page previews
3285 * @param ParserOutput $output ParserOutput object from the parse
3286 * @return string HTML
3288 public static function getPreviewLimitReport( $output ) {
3289 if ( !$output ||
!$output->getLimitReportData() ) {
3293 $limitReport = Html
::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3294 wfMessage( 'limitreport-title' )->parseAsBlock()
3297 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3298 $limitReport .= Html
::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3300 $limitReport .= Html
::openElement( 'table', array(
3301 'class' => 'preview-limit-report wikitable'
3303 Html
::openElement( 'tbody' );
3305 foreach ( $output->getLimitReportData() as $key => $value ) {
3306 if ( Hooks
::run( 'ParserLimitReportFormat',
3307 array( $key, &$value, &$limitReport, true, true )
3309 $keyMsg = wfMessage( $key );
3310 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3311 if ( !$valueMsg->exists() ) {
3312 $valueMsg = new RawMessage( '$1' );
3314 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3315 $limitReport .= Html
::openElement( 'tr' ) .
3316 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3317 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3318 Html
::closeElement( 'tr' );
3323 $limitReport .= Html
::closeElement( 'tbody' ) .
3324 Html
::closeElement( 'table' ) .
3325 Html
::closeElement( 'div' );
3327 return $limitReport;
3330 protected function showStandardInputs( &$tabindex = 2 ) {
3332 $wgOut->addHTML( "<div class='editOptions'>\n" );
3334 if ( $this->section
!= 'new' ) {
3335 $this->showSummaryInput( false, $this->summary
);
3336 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3339 $checkboxes = $this->getCheckboxes( $tabindex,
3340 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
3341 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3343 // Show copyright warning.
3344 $wgOut->addWikiText( $this->getCopywarn() );
3345 $wgOut->addHTML( $this->editFormTextAfterWarn
);
3347 $wgOut->addHTML( "<div class='editButtons'>\n" );
3348 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3350 $cancel = $this->getCancelLink();
3351 if ( $cancel !== '' ) {
3352 $cancel .= Html
::element( 'span',
3353 array( 'class' => 'mw-editButtons-pipe-separator' ),
3354 wfMessage( 'pipe-separator' )->text() );
3357 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3358 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3360 'target' => 'helpwindow',
3361 'href' => $edithelpurl,
3363 $edithelp = Html
::linkButton( wfMessage( 'edithelp' )->text(),
3364 $attrs, array( 'mw-ui-quiet' ) ) .
3365 wfMessage( 'word-separator' )->escaped() .
3366 wfMessage( 'newwindow' )->parse();
3368 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3369 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3370 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3372 Hooks
::run( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3374 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3378 * Show an edit conflict. textbox1 is already shown in showEditForm().
3379 * If you want to use another entry point to this function, be careful.
3381 protected function showConflict() {
3384 if ( Hooks
::run( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3385 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3387 $content1 = $this->toEditContent( $this->textbox1
);
3388 $content2 = $this->toEditContent( $this->textbox2
);
3390 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3391 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3392 $de->setContent( $content2, $content1 );
3394 wfMessage( 'yourtext' )->parse(),
3395 wfMessage( 'storedversion' )->text()
3398 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3399 $this->showTextbox2();
3406 public function getCancelLink() {
3407 $cancelParams = array();
3408 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3409 $cancelParams['oldid'] = $this->oldid
;
3411 $attrs = array( 'id' => 'mw-editform-cancel' );
3413 return Linker
::linkKnown(
3414 $this->getContextTitle(),
3415 wfMessage( 'cancel' )->parse(),
3416 Html
::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3422 * Returns the URL to use in the form's action attribute.
3423 * This is used by EditPage subclasses when simply customizing the action
3424 * variable in the constructor is not enough. This can be used when the
3425 * EditPage lives inside of a Special page rather than a custom page action.
3427 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3430 protected function getActionURL( Title
$title ) {
3431 return $title->getLocalURL( array( 'action' => $this->action
) );
3435 * Check if a page was deleted while the user was editing it, before submit.
3436 * Note that we rely on the logging table, which hasn't been always there,
3437 * but that doesn't matter, because this only applies to brand new
3441 protected function wasDeletedSinceLastEdit() {
3442 if ( $this->deletedSinceEdit
!== null ) {
3443 return $this->deletedSinceEdit
;
3446 $this->deletedSinceEdit
= false;
3448 if ( !$this->mTitle
->exists() && $this->mTitle
->isDeletedQuick() ) {
3449 $this->lastDelete
= $this->getLastDelete();
3450 if ( $this->lastDelete
) {
3451 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3452 if ( $deleteTime > $this->starttime
) {
3453 $this->deletedSinceEdit
= true;
3458 return $this->deletedSinceEdit
;
3462 * @return bool|stdClass
3464 protected function getLastDelete() {
3465 $dbr = wfGetDB( DB_SLAVE
);
3466 $data = $dbr->selectRow(
3467 array( 'logging', 'user' ),
3480 'log_namespace' => $this->mTitle
->getNamespace(),
3481 'log_title' => $this->mTitle
->getDBkey(),
3482 'log_type' => 'delete',
3483 'log_action' => 'delete',
3487 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3489 // Quick paranoid permission checks...
3490 if ( is_object( $data ) ) {
3491 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3492 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
3495 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3496 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
3504 * Get the rendered text for previewing.
3505 * @throws MWException
3508 function getPreviewText() {
3509 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3510 global $wgAllowUserCss, $wgAllowUserJs;
3512 $stats = $wgOut->getContext()->getStats();
3514 if ( $wgRawHtml && !$this->mTokenOk
) {
3515 // Could be an offsite preview attempt. This is very unsafe if
3516 // HTML is enabled, as it could be an attack.
3518 if ( $this->textbox1
!== '' ) {
3519 // Do not put big scary notice, if previewing the empty
3520 // string, which happens when you initially edit
3521 // a category page, due to automatic preview-on-open.
3522 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3523 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3525 $stats->increment( 'edit.failures.session_loss' );
3532 $content = $this->toEditContent( $this->textbox1
);
3536 'AlternateEditPreview',
3537 array( $this, &$content, &$previewHTML, &$this->mParserOutput
) )
3539 return $previewHTML;
3542 # provide a anchor link to the editform
3543 $continueEditing = '<span class="mw-continue-editing">' .
3544 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3545 wfMessage( 'continue-editing' )->text() . ']]</span>';
3546 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3547 if ( $this->mTokenOkExceptSuffix
) {
3548 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3549 $stats->increment( 'edit.failures.bad_token' );
3551 $note = wfMessage( 'session_fail_preview' )->plain();
3552 $stats->increment( 'edit.failures.session_loss' );
3554 } elseif ( $this->incompleteForm
) {
3555 $note = wfMessage( 'edit_form_incomplete' )->plain();
3556 if ( $this->mTriedSave
) {
3557 $stats->increment( 'edit.failures.incomplete_form' );
3560 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3563 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
3564 $parserOptions->setIsPreview( true );
3565 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3567 # don't parse non-wikitext pages, show message about preview
3568 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3569 if ( $this->mTitle
->isCssJsSubpage() ) {
3571 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3577 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3579 if ( $level === 'user' && !$wgAllowUserCss ) {
3582 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3584 if ( $level === 'user' && !$wgAllowUserJs ) {
3591 # Used messages to make sure grep find them:
3592 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3593 if ( $level && $format ) {
3594 $note = "<div id='mw-{$level}{$format}preview'>" .
3595 wfMessage( "{$level}{$format}preview" )->text() .
3596 ' ' . $continueEditing . "</div>";
3600 # If we're adding a comment, we need to show the
3601 # summary as the headline
3602 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3603 $content = $content->addSectionHeader( $this->summary
);
3606 $hook_args = array( $this, &$content );
3607 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3608 Hooks
::run( 'EditPageGetPreviewContent', $hook_args );
3610 $parserOptions->enableLimitReport();
3612 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3613 # But it's now deprecated, so never mind
3615 $pstContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3616 $scopedCallback = $parserOptions->setupFakeRevision(
3617 $this->mTitle
, $pstContent, $wgUser );
3618 $parserOutput = $pstContent->getParserOutput( $this->mTitle
, null, $parserOptions );
3620 # Try to stash the edit for the final submission step
3621 # @todo: different date format preferences cause cache misses
3622 ApiStashEdit
::stashEditFromPreview(
3623 $this->getArticle(), $content, $pstContent,
3624 $parserOutput, $parserOptions, $parserOptions, wfTimestampNow()
3627 $parserOutput->setEditSectionTokens( false ); // no section edit links
3628 $previewHTML = $parserOutput->getText();
3629 $this->mParserOutput
= $parserOutput;
3630 $wgOut->addParserOutputMetadata( $parserOutput );
3632 if ( count( $parserOutput->getWarnings() ) ) {
3633 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3635 } catch ( MWContentSerializationException
$ex ) {
3637 'content-failed-to-parse',
3638 $this->contentModel
,
3639 $this->contentFormat
,
3642 $note .= "\n\n" . $m->parse();
3646 if ( $this->isConflict
) {
3647 $conflict = '<h2 id="mw-previewconflict">'
3648 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3650 $conflict = '<hr />';
3653 $previewhead = "<div class='previewnote'>\n" .
3654 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3655 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3657 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3658 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3659 'class' => 'mw-content-' . $pageViewLang->getDir() );
3660 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3662 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3668 function getTemplates() {
3669 if ( $this->preview ||
$this->section
!= '' ) {
3670 $templates = array();
3671 if ( !isset( $this->mParserOutput
) ) {
3674 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3675 foreach ( array_keys( $template ) as $dbk ) {
3676 $templates[] = Title
::makeTitle( $ns, $dbk );
3681 return $this->mTitle
->getTemplateLinksFrom();
3686 * Shows a bulletin board style toolbar for common editing functions.
3687 * It can be disabled in the user preferences.
3691 static function getEditToolbar() {
3692 global $wgContLang, $wgOut;
3693 global $wgEnableUploads, $wgForeignFileRepos;
3695 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3698 * $toolarray is an array of arrays each of which includes the
3699 * opening tag, the closing tag, optionally a sample text that is
3700 * inserted between the two when no selection is highlighted
3701 * and. The tip text is shown when the user moves the mouse
3704 * Images are defined in ResourceLoaderEditToolbarModule.
3708 'id' => 'mw-editbutton-bold',
3710 'close' => '\'\'\'',
3711 'sample' => wfMessage( 'bold_sample' )->text(),
3712 'tip' => wfMessage( 'bold_tip' )->text(),
3715 'id' => 'mw-editbutton-italic',
3718 'sample' => wfMessage( 'italic_sample' )->text(),
3719 'tip' => wfMessage( 'italic_tip' )->text(),
3722 'id' => 'mw-editbutton-link',
3725 'sample' => wfMessage( 'link_sample' )->text(),
3726 'tip' => wfMessage( 'link_tip' )->text(),
3729 'id' => 'mw-editbutton-extlink',
3732 'sample' => wfMessage( 'extlink_sample' )->text(),
3733 'tip' => wfMessage( 'extlink_tip' )->text(),
3736 'id' => 'mw-editbutton-headline',
3739 'sample' => wfMessage( 'headline_sample' )->text(),
3740 'tip' => wfMessage( 'headline_tip' )->text(),
3742 $imagesAvailable ?
array(
3743 'id' => 'mw-editbutton-image',
3744 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3746 'sample' => wfMessage( 'image_sample' )->text(),
3747 'tip' => wfMessage( 'image_tip' )->text(),
3749 $imagesAvailable ?
array(
3750 'id' => 'mw-editbutton-media',
3751 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3753 'sample' => wfMessage( 'media_sample' )->text(),
3754 'tip' => wfMessage( 'media_tip' )->text(),
3757 'id' => 'mw-editbutton-nowiki',
3758 'open' => "<nowiki>",
3759 'close' => "</nowiki>",
3760 'sample' => wfMessage( 'nowiki_sample' )->text(),
3761 'tip' => wfMessage( 'nowiki_tip' )->text(),
3764 'id' => 'mw-editbutton-signature',
3768 'tip' => wfMessage( 'sig_tip' )->text(),
3771 'id' => 'mw-editbutton-hr',
3772 'open' => "\n----\n",
3775 'tip' => wfMessage( 'hr_tip' )->text(),
3779 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3780 foreach ( $toolarray as $tool ) {
3786 // Images are defined in ResourceLoaderEditToolbarModule
3788 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3789 // Older browsers show a "speedtip" type message only for ALT.
3790 // Ideally these should be different, realistically they
3791 // probably don't need to be.
3799 $script .= Xml
::encodeJsCall(
3800 'mw.toolbar.addButton',
3802 ResourceLoader
::inDebugMode()
3807 $wgOut->addScript( ResourceLoader
::makeInlineScript( $script ) );
3809 $toolbar = '<div id="toolbar"></div>';
3811 Hooks
::run( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3817 * Returns an array of html code of the following checkboxes:
3820 * @param int $tabindex Current tabindex
3821 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3822 * status of the checkbox
3826 public function getCheckboxes( &$tabindex, $checked ) {
3827 global $wgUser, $wgUseMediaWikiUIEverywhere;
3829 $checkboxes = array();
3831 // don't show the minor edit checkbox if it's a new page or section
3832 if ( !$this->isNew
) {
3833 $checkboxes['minor'] = '';
3834 $minorLabel = wfMessage( 'minoredit' )->parse();
3835 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3837 'tabindex' => ++
$tabindex,
3838 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3839 'id' => 'wpMinoredit',
3842 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3843 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3844 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3845 ">{$minorLabel}</label>";
3847 if ( $wgUseMediaWikiUIEverywhere ) {
3848 $checkboxes['minor'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3850 Html
::closeElement( 'div' );
3852 $checkboxes['minor'] = $minorEditHtml;
3857 $watchLabel = wfMessage( 'watchthis' )->parse();
3858 $checkboxes['watch'] = '';
3859 if ( $wgUser->isLoggedIn() ) {
3861 'tabindex' => ++
$tabindex,
3862 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3863 'id' => 'wpWatchthis',
3866 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3867 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3868 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3869 ">{$watchLabel}</label>";
3870 if ( $wgUseMediaWikiUIEverywhere ) {
3871 $checkboxes['watch'] = Html
::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3873 Html
::closeElement( 'div' );
3875 $checkboxes['watch'] = $watchThisHtml;
3878 Hooks
::run( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3883 * Returns an array of html code of the following buttons:
3884 * save, diff, preview and live
3886 * @param int $tabindex Current tabindex
3890 public function getEditButtons( &$tabindex ) {
3896 'tabindex' => ++
$tabindex,
3897 ) + Linker
::tooltipAndAccesskeyAttribs( 'save' );
3898 $buttons['save'] = Html
::submitButton( wfMessage( 'savearticle' )->text(),
3899 $attribs, array( 'mw-ui-constructive' ) );
3901 ++
$tabindex; // use the same for preview and live preview
3903 'id' => 'wpPreview',
3904 'name' => 'wpPreview',
3905 'tabindex' => $tabindex,
3906 ) + Linker
::tooltipAndAccesskeyAttribs( 'preview' );
3907 $buttons['preview'] = Html
::submitButton( wfMessage( 'showpreview' )->text(),
3909 $buttons['live'] = '';
3914 'tabindex' => ++
$tabindex,
3915 ) + Linker
::tooltipAndAccesskeyAttribs( 'diff' );
3916 $buttons['diff'] = Html
::submitButton( wfMessage( 'showdiff' )->text(),
3919 Hooks
::run( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3924 * Creates a basic error page which informs the user that
3925 * they have attempted to edit a nonexistent section.
3927 function noSuchSectionPage() {
3930 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3932 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3933 Hooks
::run( 'EditPageNoSuchSection', array( &$this, &$res ) );
3934 $wgOut->addHTML( $res );
3936 $wgOut->returnToMain( false, $this->mTitle
);
3940 * Show "your edit contains spam" page with your diff and text
3942 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3944 public function spamPageWithContent( $match = false ) {
3945 global $wgOut, $wgLang;
3946 $this->textbox2
= $this->textbox1
;
3948 if ( is_array( $match ) ) {
3949 $match = $wgLang->listToText( $match );
3951 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3953 $wgOut->addHTML( '<div id="spamprotected">' );
3954 $wgOut->addWikiMsg( 'spamprotectiontext' );
3956 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3958 $wgOut->addHTML( '</div>' );
3960 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3963 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3964 $this->showTextbox2();
3966 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3970 * Check if the browser is on a blacklist of user-agents known to
3971 * mangle UTF-8 data on form submission. Returns true if Unicode
3972 * should make it through, false if it's known to be a problem.
3975 private function checkUnicodeCompliantBrowser() {
3976 global $wgBrowserBlackList, $wgRequest;
3978 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3979 if ( $currentbrowser === false ) {
3980 // No User-Agent header sent? Trust it by default...
3984 foreach ( $wgBrowserBlackList as $browser ) {
3985 if ( preg_match( $browser, $currentbrowser ) ) {
3993 * Filter an input field through a Unicode de-armoring process if it
3994 * came from an old browser with known broken Unicode editing issues.
3996 * @param WebRequest $request
3997 * @param string $field
4000 protected function safeUnicodeInput( $request, $field ) {
4001 $text = rtrim( $request->getText( $field ) );
4002 return $request->getBool( 'safemode' )
4003 ?
$this->unmakeSafe( $text )
4008 * Filter an output field through a Unicode armoring process if it is
4009 * going to an old browser with known broken Unicode editing issues.
4011 * @param string $text
4014 protected function safeUnicodeOutput( $text ) {
4016 $codedText = $wgContLang->recodeForEdit( $text );
4017 return $this->checkUnicodeCompliantBrowser()
4019 : $this->makeSafe( $codedText );
4023 * A number of web browsers are known to corrupt non-ASCII characters
4024 * in a UTF-8 text editing environment. To protect against this,
4025 * detected browsers will be served an armored version of the text,
4026 * with non-ASCII chars converted to numeric HTML character references.
4028 * Preexisting such character references will have a 0 added to them
4029 * to ensure that round-trips do not alter the original data.
4031 * @param string $invalue
4034 private function makeSafe( $invalue ) {
4035 // Armor existing references for reversibility.
4036 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
4041 $valueLength = strlen( $invalue );
4042 for ( $i = 0; $i < $valueLength; $i++
) {
4043 $bytevalue = ord( $invalue[$i] );
4044 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4045 $result .= chr( $bytevalue );
4047 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4048 $working = $working << 6;
4049 $working +
= ( $bytevalue & 0x3F );
4051 if ( $bytesleft <= 0 ) {
4052 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4054 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4055 $working = $bytevalue & 0x1F;
4057 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4058 $working = $bytevalue & 0x0F;
4060 } else { // 1111 0xxx
4061 $working = $bytevalue & 0x07;
4069 * Reverse the previously applied transliteration of non-ASCII characters
4070 * back to UTF-8. Used to protect data from corruption by broken web browsers
4071 * as listed in $wgBrowserBlackList.
4073 * @param string $invalue
4076 private function unmakeSafe( $invalue ) {
4078 $valueLength = strlen( $invalue );
4079 for ( $i = 0; $i < $valueLength; $i++
) {
4080 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4084 $hexstring .= $invalue[$i];
4086 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4088 // Do some sanity checks. These aren't needed for reversibility,
4089 // but should help keep the breakage down if the editor
4090 // breaks one of the entities whilst editing.
4091 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4092 $codepoint = hexdec( $hexstring );
4093 $result .= UtfNormal\Utils
::codepointToUtf8( $codepoint );
4095 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4098 $result .= substr( $invalue, $i, 1 );
4101 // reverse the transform that we made for reversibility reasons.
4102 return strtr( $result, array( "�" => "&#x" ) );