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: User cannot edit? (not used)
72 const AS_USER_CANNOT_EDIT
= 217;
75 * Status: this anonymous user is not allowed to edit this page
77 const AS_READ_ONLY_PAGE_ANON
= 218;
80 * Status: this logged in user is not allowed to edit this page
82 const AS_READ_ONLY_PAGE_LOGGED
= 219;
85 * Status: wiki is in readonly mode (wfReadOnly() == true)
87 const AS_READ_ONLY_PAGE
= 220;
90 * Status: rate limiter for action 'edit' was tripped
92 const AS_RATE_LIMITED
= 221;
95 * Status: article was deleted while editing and param wpRecreate == false or form
98 const AS_ARTICLE_WAS_DELETED
= 222;
101 * Status: user tried to create this page, but is not allowed to do that
102 * ( Title->userCan('create') == false )
104 const AS_NO_CREATE_PERMISSION
= 223;
107 * Status: user tried to create a blank page
109 const AS_BLANK_ARTICLE
= 224;
112 * Status: (non-resolvable) edit conflict
114 const AS_CONFLICT_DETECTED
= 225;
117 * Status: no edit summary given and the user has forceeditsummary set and the user is not
118 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
120 const AS_SUMMARY_NEEDED
= 226;
123 * Status: user tried to create a new section without content
125 const AS_TEXTBOX_EMPTY
= 228;
128 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
130 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
138 * Status: WikiPage::doEdit() was unsuccessful
143 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
145 const AS_SPAM_ERROR
= 232;
148 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
150 const AS_IMAGE_REDIRECT_ANON
= 233;
153 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
155 const AS_IMAGE_REDIRECT_LOGGED
= 234;
158 * Status: can't parse content
160 const AS_PARSE_ERROR
= 240;
163 * HTML id and name for the beginning of the edit form.
165 const EDITFORM_ID
= 'editform';
168 * Prefix of key for cookie used to pass post-edit state.
169 * The revision id edited is added after this
171 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
174 * Duration of PostEdit cookie, in seconds.
175 * The cookie will be removed instantly if the JavaScript runs.
177 * Otherwise, though, we don't want the cookies to accumulate.
178 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
179 * limit of only 20 cookies per domain. This still applies at least to some
180 * versions of IE without full updates:
181 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
183 * A value of 20 minutes should be enough to take into account slow loads and minor
184 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
186 const POST_EDIT_COOKIE_DURATION
= 1200;
194 /** @var null|Title */
195 private $mContextTitle = null;
198 protected $action = 'submit';
201 public $isConflict = false;
204 public $isCssJsSubpage = false;
207 public $isCssSubpage = false;
210 public $isJsSubpage = false;
213 protected $isWrongCaseCssJsPage = false;
215 /** @var bool New page or new section */
216 protected $isNew = false;
219 protected $deletedSinceEdit;
227 /** @var bool|stdClass */
228 protected $lastDelete;
231 protected $mTokenOk = false;
234 protected $mTokenOkExceptSuffix = false;
237 protected $mTriedSave = false;
240 protected $incompleteForm = false;
243 protected $tooBig = false;
246 protected $kblength = false;
249 protected $missingComment = false;
252 protected $missingSummary = false;
255 protected $allowBlankSummary = false;
258 protected $autoSumm = '';
261 public $hookError = '';
263 /** @var ParserOutput */
264 protected $mParserOutput;
266 /** @var bool Has a summary been preset using GET parameter &summary= ? */
267 protected $hasPresetSummary = false;
270 protected $mBaseRevision = false;
273 public $mShowSummaryField = true;
278 public $save = false;
281 public $preview = false;
284 protected $diff = false;
287 public $minoredit = false;
290 protected $watchthis = false;
293 protected $recreate = false;
296 public $textbox1 = '';
299 public $textbox2 = '';
302 public $summary = '';
305 protected $nosummary = false;
308 public $edittime = '';
311 public $section = '';
314 public $sectiontitle = '';
317 protected $starttime = '';
323 protected $editintro = '';
326 public $scrolltop = null;
331 /** @var null|string */
332 public $contentModel = null;
334 /** @var null|string */
335 public $contentFormat = null;
337 # Placeholders for text injection by hooks (must be HTML)
338 # extensions should take care to _append_ to the present value
340 /** @var string Before even the preview */
341 public $editFormPageTop = '';
342 public $editFormTextTop = '';
343 public $editFormTextBeforeContent = '';
344 public $editFormTextAfterWarn = '';
345 public $editFormTextAfterTools = '';
346 public $editFormTextBottom = '';
347 public $editFormTextAfterContent = '';
348 public $previewTextAfterContent = '';
349 public $mPreloadContent = null;
351 /* $didSave should be set to true whenever an article was successfully altered. */
352 public $didSave = false;
353 public $undidRev = 0;
355 public $suppressIntro = false;
357 /** @var bool Set to true to allow editing of non-text content types. */
358 public $allowNonTextContent = false;
367 * @param Article $article
369 public function __construct( Article
$article ) {
370 $this->mArticle
= $article;
371 $this->mTitle
= $article->getTitle();
373 $this->contentModel
= $this->mTitle
->getContentModel();
375 $handler = ContentHandler
::getForModelID( $this->contentModel
);
376 $this->contentFormat
= $handler->getDefaultFormat();
382 public function getArticle() {
383 return $this->mArticle
;
390 public function getTitle() {
391 return $this->mTitle
;
395 * Set the context Title object
397 * @param Title|null $title Title object or null
399 public function setContextTitle( $title ) {
400 $this->mContextTitle
= $title;
404 * Get the context title object.
405 * If not set, $wgTitle will be returned. This behavior might change in
406 * the future to return $this->mTitle instead.
410 public function getContextTitle() {
411 if ( is_null( $this->mContextTitle
) ) {
415 return $this->mContextTitle
;
420 * Returns if the given content model is editable.
422 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
424 * @throws MWException if $modelId has no known handler
426 public function isSupportedContentModel( $modelId ) {
427 return $this->allowNonTextContent ||
428 ContentHandler
::getForModelID( $modelId ) instanceof TextContentHandler
;
436 * This is the function that gets called for "action=edit". It
437 * sets up various member variables, then passes execution to
438 * another function, usually showEditForm()
440 * The edit form is self-submitting, so that when things like
441 * preview and edit conflicts occur, we get the same form back
442 * with the extra stuff added. Only when the final submission
443 * is made and all is well do we actually save and redirect to
444 * the newly-edited page.
447 global $wgOut, $wgRequest, $wgUser;
448 // Allow extensions to modify/prevent this form or submission
449 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
453 wfProfileIn( __METHOD__
);
454 wfDebug( __METHOD__
. ": enter\n" );
456 // If they used redlink=1 and the page exists, redirect to the main article
457 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
458 $wgOut->redirect( $this->mTitle
->getFullURL() );
459 wfProfileOut( __METHOD__
);
463 $this->importFormData( $wgRequest );
464 $this->firsttime
= false;
467 $this->livePreview();
468 wfProfileOut( __METHOD__
);
472 if ( wfReadOnly() && $this->save
) {
475 $this->preview
= true;
479 $this->formtype
= 'save';
480 } elseif ( $this->preview
) {
481 $this->formtype
= 'preview';
482 } elseif ( $this->diff
) {
483 $this->formtype
= 'diff';
484 } else { # First time through
485 $this->firsttime
= true;
486 if ( $this->previewOnOpen() ) {
487 $this->formtype
= 'preview';
489 $this->formtype
= 'initial';
493 $permErrors = $this->getEditPermissionErrors();
495 wfDebug( __METHOD__
. ": User can't edit\n" );
496 // Auto-block user's IP if the account was "hard" blocked
497 $wgUser->spreadAnyEditBlock();
499 $this->displayPermissionsError( $permErrors );
501 wfProfileOut( __METHOD__
);
505 wfProfileIn( __METHOD__
. "-business-end" );
507 $this->isConflict
= false;
508 // css / js subpages of user pages get a special treatment
509 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
510 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
511 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
512 // @todo FIXME: Silly assignment.
513 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
515 # Show applicable editing introductions
516 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
520 # Attempt submission here. This will check for edit conflicts,
521 # and redundantly check for locked database, blocked IPs, etc.
522 # that edit() already checked just in case someone tries to sneak
523 # in the back door with a hand-edited submission URL.
525 if ( 'save' == $this->formtype
) {
526 if ( !$this->attemptSave() ) {
527 wfProfileOut( __METHOD__
. "-business-end" );
528 wfProfileOut( __METHOD__
);
533 # First time through: get contents, set time for conflict
535 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
536 if ( $this->initialiseForm() === false ) {
537 $this->noSuchSectionPage();
538 wfProfileOut( __METHOD__
. "-business-end" );
539 wfProfileOut( __METHOD__
);
543 if ( !$this->mTitle
->getArticleID() ) {
544 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
546 wfRunHooks( 'EditFormInitialText', array( $this ) );
551 $this->showEditForm();
552 wfProfileOut( __METHOD__
. "-business-end" );
553 wfProfileOut( __METHOD__
);
559 protected function getEditPermissionErrors() {
561 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
562 # Can this title be created?
563 if ( !$this->mTitle
->exists() ) {
564 $permErrors = array_merge( $permErrors,
565 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
567 # Ignore some permissions errors when a user is just previewing/viewing diffs
569 foreach ( $permErrors as $error ) {
570 if ( ( $this->preview ||
$this->diff
)
571 && ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' )
576 $permErrors = wfArrayDiff2( $permErrors, $remove );
581 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
582 * but with the following differences:
583 * - If redlink=1, the user will be redirected to the page
584 * - If there is content to display or the error occurs while either saving,
585 * previewing or showing the difference, it will be a
586 * "View source for ..." page displaying the source code after the error message.
589 * @param array $permErrors Array of permissions errors, as returned by
590 * Title::getUserPermissionsErrors().
591 * @throws PermissionsError
593 protected function displayPermissionsError( array $permErrors ) {
594 global $wgRequest, $wgOut;
596 if ( $wgRequest->getBool( 'redlink' ) ) {
597 // The edit page was reached via a red link.
598 // Redirect to the article page and let them click the edit tab if
599 // they really want a permission error.
600 $wgOut->redirect( $this->mTitle
->getFullURL() );
604 $content = $this->getContentObject();
606 # Use the normal message if there's nothing to display
607 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
608 $action = $this->mTitle
->exists() ?
'edit' :
609 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
610 throw new PermissionsError( $action, $permErrors );
613 wfRunHooks( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
615 $wgOut->setRobotPolicy( 'noindex,nofollow' );
616 $wgOut->setPageTitle( wfMessage(
618 $this->getContextTitle()->getPrefixedText()
620 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
621 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
622 $wgOut->addHTML( "<hr />\n" );
624 # If the user made changes, preserve them when showing the markup
625 # (This happens when a user is blocked during edit, for instance)
626 if ( !$this->firsttime
) {
627 $text = $this->textbox1
;
628 $wgOut->addWikiMsg( 'viewyourtext' );
630 $text = $this->toEditText( $content );
631 $wgOut->addWikiMsg( 'viewsourcetext' );
634 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
636 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
637 Linker
::formatTemplates( $this->getTemplates() ) ) );
639 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
641 if ( $this->mTitle
->exists() ) {
642 $wgOut->returnToMain( null, $this->mTitle
);
647 * Show a read-only error
648 * Parameters are the same as OutputPage:readOnlyPage()
649 * Redirect to the article page if redlink=1
650 * @deprecated since 1.19; use displayPermissionsError() instead
652 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
653 wfDeprecated( __METHOD__
, '1.19' );
655 global $wgRequest, $wgOut;
656 if ( $wgRequest->getBool( 'redlink' ) ) {
657 // The edit page was reached via a red link.
658 // Redirect to the article page and let them click the edit tab if
659 // they really want a permission error.
660 $wgOut->redirect( $this->mTitle
->getFullURL() );
662 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
667 * Should we show a preview when the edit form is first shown?
671 protected function previewOnOpen() {
672 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
673 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
674 // Explicit override from request
676 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
677 // Explicit override from request
679 } elseif ( $this->section
== 'new' ) {
680 // Nothing *to* preview for new sections
682 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() )
683 && $wgUser->getOption( 'previewonfirst' )
685 // Standard preference behavior
687 } elseif ( !$this->mTitle
->exists()
688 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
689 && $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]
691 // Categories are special
699 * Checks whether the user entered a skin name in uppercase,
700 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
704 protected function isWrongCaseCssJsPage() {
705 if ( $this->mTitle
->isCssJsSubpage() ) {
706 $name = $this->mTitle
->getSkinFromCssJsSubpage();
707 $skins = array_merge(
708 array_keys( Skin
::getSkinNames() ),
711 return !in_array( $name, $skins )
712 && in_array( strtolower( $name ), $skins );
719 * Returns whether section editing is supported for the current page.
720 * Subclasses may override this to replace the default behavior, which is
721 * to check ContentHandler::supportsSections.
723 * @return bool true if this edit page supports sections, false otherwise.
725 protected function isSectionEditSupported() {
726 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
727 return $contentHandler->supportsSections();
731 * This function collects the form data and uses it to populate various member variables.
732 * @param WebRequest $request
733 * @throws ErrorPageError
735 function importFormData( &$request ) {
736 global $wgContLang, $wgUser;
738 wfProfileIn( __METHOD__
);
740 # Section edit can come from either the form or a link
741 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
743 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
744 wfProfileOut( __METHOD__
);
745 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
748 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
750 if ( $request->wasPosted() ) {
751 # These fields need to be checked for encoding.
752 # Also remove trailing whitespace, but don't remove _initial_
753 # whitespace from the text boxes. This may be significant formatting.
754 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
755 if ( !$request->getCheck( 'wpTextbox2' ) ) {
756 // Skip this if wpTextbox2 has input, it indicates that we came
757 // from a conflict page with raw page text, not a custom form
758 // modified by subclasses
759 wfProfileIn( get_class( $this ) . "::importContentFormData" );
760 $textbox1 = $this->importContentFormData( $request );
761 if ( $textbox1 !== null ) {
762 $this->textbox1
= $textbox1;
765 wfProfileOut( get_class( $this ) . "::importContentFormData" );
768 # Truncate for whole multibyte characters
769 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
771 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
772 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
774 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
776 # Treat sectiontitle the same way as summary.
777 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
778 # currently doing double duty as both edit summary and section title. Right now this
779 # is just to allow API edits to work around this limitation, but this should be
780 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
781 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
782 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
784 $this->edittime
= $request->getVal( 'wpEdittime' );
785 $this->starttime
= $request->getVal( 'wpStarttime' );
787 $undidRev = $request->getInt( 'wpUndidRevision' );
789 $this->undidRev
= $undidRev;
792 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
794 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
795 // wpTextbox1 field is missing, possibly due to being "too big"
796 // according to some filter rules such as Suhosin's setting for
797 // suhosin.request.max_value_length (d'oh)
798 $this->incompleteForm
= true;
800 // If we receive the last parameter of the request, we can fairly
801 // claim the POST request has not been truncated.
803 // TODO: softened the check for cutover. Once we determine
804 // that it is safe, we should complete the transition by
805 // removing the "edittime" clause.
806 $this->incompleteForm
= ( !$request->getVal( 'wpUltimateParam' ) && is_null( $this->edittime
) );
808 if ( $this->incompleteForm
) {
809 # If the form is incomplete, force to preview.
810 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
811 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
812 $this->preview
= true;
814 /* Fallback for live preview */
815 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
816 $this->diff
= $request->getCheck( 'wpDiff' );
818 // Remember whether a save was requested, so we can indicate
819 // if we forced preview due to session failure.
820 $this->mTriedSave
= !$this->preview
;
822 if ( $this->tokenOk( $request ) ) {
823 # Some browsers will not report any submit button
824 # if the user hits enter in the comment box.
825 # The unmarked state will be assumed to be a save,
826 # if the form seems otherwise complete.
827 wfDebug( __METHOD__
. ": Passed token check.\n" );
828 } elseif ( $this->diff
) {
829 # Failed token check, but only requested "Show Changes".
830 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
832 # Page might be a hack attempt posted from
833 # an external site. Preview instead of saving.
834 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
835 $this->preview
= true;
838 $this->save
= !$this->preview
&& !$this->diff
;
839 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
840 $this->edittime
= null;
843 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
844 $this->starttime
= null;
847 $this->recreate
= $request->getCheck( 'wpRecreate' );
849 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
850 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
852 # Don't force edit summaries when a user is editing their own user or talk page
853 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
)
854 && $this->mTitle
->getText() == $wgUser->getName()
856 $this->allowBlankSummary
= true;
858 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' )
859 ||
!$wgUser->getOption( 'forceeditsummary' );
862 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
864 # Not a posted form? Start with nothing.
865 wfDebug( __METHOD__
. ": Not a posted form.\n" );
866 $this->textbox1
= '';
868 $this->sectiontitle
= '';
869 $this->edittime
= '';
870 $this->starttime
= wfTimestampNow();
872 $this->preview
= false;
875 $this->minoredit
= false;
876 // Watch may be overridden by request parameters
877 $this->watchthis
= $request->getBool( 'watchthis', false );
878 $this->recreate
= false;
880 // When creating a new section, we can preload a section title by passing it as the
881 // preloadtitle parameter in the URL (Bug 13100)
882 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
883 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
884 // Once wpSummary isn't being use for setting section titles, we should delete this.
885 $this->summary
= $request->getVal( 'preloadtitle' );
886 } elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
887 $this->summary
= $request->getText( 'summary' );
888 if ( $this->summary
!== '' ) {
889 $this->hasPresetSummary
= true;
893 if ( $request->getVal( 'minor' ) ) {
894 $this->minoredit
= true;
898 $this->oldid
= $request->getInt( 'oldid' );
900 $this->bot
= $request->getBool( 'bot', true );
901 $this->nosummary
= $request->getBool( 'nosummary' );
903 // May be overridden by revision.
904 $this->contentModel
= $request->getText( 'model', $this->contentModel
);
905 // May be overridden by revision.
906 $this->contentFormat
= $request->getText( 'format', $this->contentFormat
);
908 if ( !ContentHandler
::getForModelID( $this->contentModel
)
909 ->isSupportedFormat( $this->contentFormat
)
911 throw new ErrorPageError(
912 'editpage-notsupportedcontentformat-title',
913 'editpage-notsupportedcontentformat-text',
914 array( $this->contentFormat
, ContentHandler
::getLocalizedName( $this->contentModel
) )
919 * @todo Check if the desired model is allowed in this namespace, and if
920 * a transition from the page's current model to the new model is
924 $this->live
= $request->getCheck( 'live' );
925 $this->editintro
= $request->getText( 'editintro',
926 // Custom edit intro for new sections
927 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
929 // Allow extensions to modify form data
930 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
932 wfProfileOut( __METHOD__
);
936 * Subpage overridable method for extracting the page content data from the
937 * posted form to be placed in $this->textbox1, if using customized input
938 * this method should be overridden and return the page text that will be used
939 * for saving, preview parsing and so on...
941 * @param WebRequest $request
943 protected function importContentFormData( &$request ) {
944 return; // Don't do anything, EditPage already extracted wpTextbox1
948 * Initialise form fields in the object
949 * Called on the first invocation, e.g. when a user clicks an edit link
950 * @return bool If the requested section is valid
952 function initialiseForm() {
954 $this->edittime
= $this->mArticle
->getTimestamp();
956 $content = $this->getContentObject( false ); #TODO: track content object?!
957 if ( $content === false ) {
960 $this->textbox1
= $this->toEditText( $content );
962 // activate checkboxes if user wants them to be always active
963 # Sort out the "watch" checkbox
964 if ( $wgUser->getOption( 'watchdefault' ) ) {
966 $this->watchthis
= true;
967 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
969 $this->watchthis
= true;
970 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
972 $this->watchthis
= true;
974 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
975 $this->minoredit
= true;
977 if ( $this->textbox1
=== false ) {
984 * Fetch initial editing page content.
986 * @param string|bool $def_text
987 * @return string|bool string on success, $def_text for invalid sections
989 * @deprecated since 1.21, get WikiPage::getContent() instead.
991 function getContent( $def_text = false ) {
992 ContentHandler
::deprecated( __METHOD__
, '1.21' );
994 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
995 $def_content = $this->toEditContent( $def_text );
997 $def_content = false;
1000 $content = $this->getContentObject( $def_content );
1002 // Note: EditPage should only be used with text based content anyway.
1003 return $this->toEditText( $content );
1007 * @param Content|null $def_content The default value to return
1009 * @return Content|null Content on success, $def_content for invalid sections
1013 protected function getContentObject( $def_content = null ) {
1014 global $wgOut, $wgRequest, $wgUser, $wgContLang;
1016 wfProfileIn( __METHOD__
);
1020 // For message page not locally set, use the i18n message.
1021 // For other non-existent articles, use preload text if any.
1022 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
1023 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
1024 # If this is a system message, get the default text.
1025 $msg = $this->mTitle
->getDefaultMessageText();
1027 $content = $this->toEditContent( $msg );
1029 if ( $content === false ) {
1030 # If requested, preload some text.
1031 $preload = $wgRequest->getVal( 'preload',
1032 // Custom preload text for new sections
1033 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
1034 $params = $wgRequest->getArray( 'preloadparams', array() );
1036 $content = $this->getPreloadedContent( $preload, $params );
1038 // For existing pages, get text based on "undo" or section parameters.
1040 if ( $this->section
!= '' ) {
1041 // Get section edit text (returns $def_text for invalid sections)
1042 $orig = $this->getOriginalContent( $wgUser );
1043 $content = $orig ?
$orig->getSection( $this->section
) : null;
1046 $content = $def_content;
1049 $undoafter = $wgRequest->getInt( 'undoafter' );
1050 $undo = $wgRequest->getInt( 'undo' );
1052 if ( $undo > 0 && $undoafter > 0 ) {
1054 $undorev = Revision
::newFromId( $undo );
1055 $oldrev = Revision
::newFromId( $undoafter );
1057 # Sanity check, make sure it's the right page,
1058 # the revisions exist and they were not deleted.
1059 # Otherwise, $content will be left as-is.
1060 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1061 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
1062 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
1064 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
1066 if ( $content === false ) {
1067 # Warn the user that something went wrong
1068 $undoMsg = 'failure';
1070 $oldContent = $this->mArticle
->getPage()->getContent( Revision
::RAW
);
1071 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
1072 $newContent = $content->preSaveTransform( $this->mTitle
, $wgUser, $popts );
1074 if ( $newContent->equals( $oldContent ) ) {
1075 # Tell the user that the undo results in no change,
1076 # i.e. the revisions were already undone.
1077 $undoMsg = 'nochange';
1080 # Inform the user of our success and set an automatic edit summary
1081 $undoMsg = 'success';
1083 # If we just undid one rev, use an autosummary
1084 $firstrev = $oldrev->getNext();
1085 if ( $firstrev && $firstrev->getId() == $undo ) {
1086 $userText = $undorev->getUserText();
1087 if ( $userText === '' ) {
1088 $undoSummary = wfMessage(
1089 'undo-summary-username-hidden',
1091 )->inContentLanguage()->text();
1093 $undoSummary = wfMessage(
1097 )->inContentLanguage()->text();
1099 if ( $this->summary
=== '' ) {
1100 $this->summary
= $undoSummary;
1102 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
1103 ->inContentLanguage()->text() . $this->summary
;
1105 $this->undidRev
= $undo;
1107 $this->formtype
= 'diff';
1111 // Failed basic sanity checks.
1112 // Older revisions may have been removed since the link
1113 // was created, or we may simply have got bogus input.
1117 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1118 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
1119 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
1120 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1123 if ( $content === false ) {
1124 $content = $this->getOriginalContent( $wgUser );
1129 wfProfileOut( __METHOD__
);
1134 * Get the content of the wanted revision, without section extraction.
1136 * The result of this function can be used to compare user's input with
1137 * section replaced in its context (using WikiPage::replaceSection())
1138 * to the original text of the edit.
1140 * This differs from Article::getContent() that when a missing revision is
1141 * encountered the result will be null and not the
1142 * 'missing-revision' message.
1145 * @param User $user The user to get the revision for
1146 * @return Content|null
1148 private function getOriginalContent( User
$user ) {
1149 if ( $this->section
== 'new' ) {
1150 return $this->getCurrentContent();
1152 $revision = $this->mArticle
->getRevisionFetched();
1153 if ( $revision === null ) {
1154 if ( !$this->contentModel
) {
1155 $this->contentModel
= $this->getTitle()->getContentModel();
1157 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1159 return $handler->makeEmptyContent();
1161 $content = $revision->getContent( Revision
::FOR_THIS_USER
, $user );
1166 * Get the current content of the page. This is basically similar to
1167 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1168 * content object is returned instead of null.
1173 protected function getCurrentContent() {
1174 $rev = $this->mArticle
->getRevision();
1175 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1177 if ( $content === false ||
$content === null ) {
1178 if ( !$this->contentModel
) {
1179 $this->contentModel
= $this->getTitle()->getContentModel();
1181 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1183 return $handler->makeEmptyContent();
1185 # nasty side-effect, but needed for consistency
1186 $this->contentModel
= $rev->getContentModel();
1187 $this->contentFormat
= $rev->getContentFormat();
1194 * Use this method before edit() to preload some text into the edit box
1196 * @param string $text
1197 * @deprecated since 1.21, use setPreloadedContent() instead.
1199 public function setPreloadedText( $text ) {
1200 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1202 $content = $this->toEditContent( $text );
1204 $this->setPreloadedContent( $content );
1208 * Use this method before edit() to preload some content into the edit box
1210 * @param Content $content
1214 public function setPreloadedContent( Content
$content ) {
1215 $this->mPreloadContent
= $content;
1219 * Get the contents to be preloaded into the box, either set by
1220 * an earlier setPreloadText() or by loading the given page.
1222 * @param string $preload representing the title to preload from.
1226 * @deprecated since 1.21, use getPreloadedContent() instead
1228 protected function getPreloadedText( $preload ) {
1229 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1231 $content = $this->getPreloadedContent( $preload );
1232 $text = $this->toEditText( $content );
1238 * Get the contents to be preloaded into the box, either set by
1239 * an earlier setPreloadText() or by loading the given page.
1241 * @param string $preload Representing the title to preload from.
1242 * @param array $params Parameters to use (interface-message style) in the preloaded text
1248 protected function getPreloadedContent( $preload, $params = array() ) {
1251 if ( !empty( $this->mPreloadContent
) ) {
1252 return $this->mPreloadContent
;
1255 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1257 if ( $preload === '' ) {
1258 return $handler->makeEmptyContent();
1261 $title = Title
::newFromText( $preload );
1262 # Check for existence to avoid getting MediaWiki:Noarticletext
1263 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1264 //TODO: somehow show a warning to the user!
1265 return $handler->makeEmptyContent();
1268 $page = WikiPage
::factory( $title );
1269 if ( $page->isRedirect() ) {
1270 $title = $page->getRedirectTarget();
1272 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1273 //TODO: somehow show a warning to the user!
1274 return $handler->makeEmptyContent();
1276 $page = WikiPage
::factory( $title );
1279 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1280 $content = $page->getContent( Revision
::RAW
);
1283 //TODO: somehow show a warning to the user!
1284 return $handler->makeEmptyContent();
1287 if ( $content->getModel() !== $handler->getModelID() ) {
1288 $converted = $content->convert( $handler->getModelID() );
1290 if ( !$converted ) {
1291 //TODO: somehow show a warning to the user!
1292 wfDebug( "Attempt to preload incompatible content: "
1293 . "can't convert " . $content->getModel()
1294 . " to " . $handler->getModelID() );
1296 return $handler->makeEmptyContent();
1299 $content = $converted;
1302 return $content->preloadTransform( $title, $parserOptions, $params );
1306 * Make sure the form isn't faking a user's credentials.
1308 * @param WebRequest $request
1312 function tokenOk( &$request ) {
1314 $token = $request->getVal( 'wpEditToken' );
1315 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1316 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1317 return $this->mTokenOk
;
1321 * Sets post-edit cookie indicating the user just saved a particular revision.
1323 * This uses a temporary cookie for each revision ID so separate saves will never
1324 * interfere with each other.
1326 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1327 * the redirect. It must be clearable by JavaScript code, so it must not be
1328 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1331 * If the variable were set on the server, it would be cached, which is unwanted
1332 * since the post-edit state should only apply to the load right after the save.
1334 * @param $statusValue int The status value (to check for new article status)
1336 protected function setPostEditCookie( $statusValue ) {
1337 $revisionId = $this->mArticle
->getLatest();
1338 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1341 if ( $statusValue == self
::AS_SUCCESS_NEW_ARTICLE
) {
1343 } elseif ( $this->oldid
) {
1347 $response = RequestContext
::getMain()->getRequest()->response();
1348 $response->setcookie( $postEditKey, $val, time() + self
::POST_EDIT_COOKIE_DURATION
, array(
1349 'httpOnly' => false,
1354 * Attempt submission
1355 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1356 * @return bool false if output is done, true if the rest of the form should be displayed
1358 public function attemptSave() {
1361 $resultDetails = false;
1362 # Allow bots to exempt some edits from bot flagging
1363 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1364 $status = $this->internalAttemptSave( $resultDetails, $bot );
1366 return $this->handleStatus( $status, $resultDetails );
1370 * Handle status, such as after attempt save
1372 * @param Status $status
1373 * @param array|bool $resultDetails
1375 * @throws ErrorPageError
1376 * @return bool false, if output is done, true if rest of the form should be displayed
1378 private function handleStatus( Status
$status, $resultDetails ) {
1379 global $wgUser, $wgOut;
1382 * @todo FIXME: once the interface for internalAttemptSave() is made
1383 * nicer, this should use the message in $status
1385 if ( $status->value
== self
::AS_SUCCESS_UPDATE
1386 ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
1388 $this->didSave
= true;
1389 if ( !$resultDetails['nullEdit'] ) {
1390 $this->setPostEditCookie( $status->value
);
1394 switch ( $status->value
) {
1395 case self
::AS_HOOK_ERROR_EXPECTED
:
1396 case self
::AS_CONTENT_TOO_BIG
:
1397 case self
::AS_ARTICLE_WAS_DELETED
:
1398 case self
::AS_CONFLICT_DETECTED
:
1399 case self
::AS_SUMMARY_NEEDED
:
1400 case self
::AS_TEXTBOX_EMPTY
:
1401 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1405 case self
::AS_HOOK_ERROR
:
1408 case self
::AS_PARSE_ERROR
:
1409 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1412 case self
::AS_SUCCESS_NEW_ARTICLE
:
1413 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1414 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1415 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1418 case self
::AS_SUCCESS_UPDATE
:
1420 $sectionanchor = $resultDetails['sectionanchor'];
1422 // Give extensions a chance to modify URL query on update
1424 'ArticleUpdateBeforeRedirect',
1425 array( $this->mArticle
, &$sectionanchor, &$extraQuery )
1428 if ( $resultDetails['redirect'] ) {
1429 if ( $extraQuery == '' ) {
1430 $extraQuery = 'redirect=no';
1432 $extraQuery = 'redirect=no&' . $extraQuery;
1435 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1438 case self
::AS_BLANK_ARTICLE
:
1439 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1442 case self
::AS_SPAM_ERROR
:
1443 $this->spamPageWithContent( $resultDetails['spam'] );
1446 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1447 throw new UserBlockedError( $wgUser->getBlock() );
1449 case self
::AS_IMAGE_REDIRECT_ANON
:
1450 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1451 throw new PermissionsError( 'upload' );
1453 case self
::AS_READ_ONLY_PAGE_ANON
:
1454 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1455 throw new PermissionsError( 'edit' );
1457 case self
::AS_READ_ONLY_PAGE
:
1458 throw new ReadOnlyError
;
1460 case self
::AS_RATE_LIMITED
:
1461 throw new ThrottledError();
1463 case self
::AS_NO_CREATE_PERMISSION
:
1464 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1465 throw new PermissionsError( $permission );
1468 // We don't recognize $status->value. The only way that can happen
1469 // is if an extension hook aborted from inside ArticleSave.
1470 // Render the status object into $this->hookError
1471 // FIXME this sucks, we should just use the Status object throughout
1472 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1479 * Run hooks that can filter edits just before they get saved.
1481 * @param Content $content The Content to filter.
1482 * @param Status $status For reporting the outcome to the caller
1483 * @param User $user The user performing the edit
1487 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1488 // Run old style post-section-merge edit filter
1489 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1490 array( $this, $content, &$this->hookError
, $this->summary
) ) ) {
1492 # Error messages etc. could be handled within the hook...
1493 $status->fatal( 'hookaborted' );
1494 $status->value
= self
::AS_HOOK_ERROR
;
1496 } elseif ( $this->hookError
!= '' ) {
1497 # ...or the hook could be expecting us to produce an error
1498 $status->fatal( 'hookaborted' );
1499 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1503 // Run new style post-section-merge edit filter
1504 if ( !wfRunHooks( 'EditFilterMergedContent',
1505 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1506 $user, $this->minoredit
) ) ) {
1508 # Error messages etc. could be handled within the hook...
1509 // XXX: $status->value may already be something informative...
1510 $this->hookError
= $status->getWikiText();
1511 $status->fatal( 'hookaborted' );
1512 $status->value
= self
::AS_HOOK_ERROR
;
1514 } elseif ( !$status->isOK() ) {
1515 # ...or the hook could be expecting us to produce an error
1516 // FIXME this sucks, we should just use the Status object throughout
1517 $this->hookError
= $status->getWikiText();
1518 $status->fatal( 'hookaborted' );
1519 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1527 * Return the summary to be used for a new section.
1529 * @param string $sectionanchor Set to the section anchor text
1532 private function newSectionSummary( &$sectionanchor = null ) {
1535 if ( $this->sectiontitle
!== '' ) {
1536 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1537 // If no edit summary was specified, create one automatically from the section
1538 // title and have it link to the new section. Otherwise, respect the summary as
1540 if ( $this->summary
=== '' ) {
1541 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1542 return wfMessage( 'newsectionsummary' )
1543 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1545 } elseif ( $this->summary
!== '' ) {
1546 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1547 # This is a new section, so create a link to the new section
1548 # in the revision summary.
1549 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1550 return wfMessage( 'newsectionsummary' )
1551 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1553 return $this->summary
;
1558 * Attempt submission (no UI)
1560 * @param array $result Array to add statuses to, currently with the
1562 * - spam (string): Spam string from content if any spam is detected by
1564 * - sectionanchor (string): Section anchor for a section save.
1565 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1567 * - redirect (bool): Set if doEditContent is OK. True if resulting
1568 * revision is a redirect.
1569 * @param bool $bot True if edit is being made under the bot right.
1571 * @return Status Status object, possibly with a message, but always with
1572 * one of the AS_* constants in $status->value,
1574 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1575 * various error display idiosyncrasies. There are also lots of cases
1576 * where error metadata is set in the object and retrieved later instead
1577 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1578 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1581 function internalAttemptSave( &$result, $bot = false ) {
1582 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1584 $status = Status
::newGood();
1586 wfProfileIn( __METHOD__
);
1587 wfProfileIn( __METHOD__
. '-checks' );
1589 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1590 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1591 $status->fatal( 'hookaborted' );
1592 $status->value
= self
::AS_HOOK_ERROR
;
1593 wfProfileOut( __METHOD__
. '-checks' );
1594 wfProfileOut( __METHOD__
);
1598 $spam = $wgRequest->getText( 'wpAntispam' );
1599 if ( $spam !== '' ) {
1602 $wgUser->getName() .
1604 $this->mTitle
->getPrefixedText() .
1605 '" submitted bogus field "' .
1609 $status->fatal( 'spamprotectionmatch', false );
1610 $status->value
= self
::AS_SPAM_ERROR
;
1611 wfProfileOut( __METHOD__
. '-checks' );
1612 wfProfileOut( __METHOD__
);
1617 # Construct Content object
1618 $textbox_content = $this->toEditContent( $this->textbox1
);
1619 } catch ( MWContentSerializationException
$ex ) {
1621 'content-failed-to-parse',
1622 $this->contentModel
,
1623 $this->contentFormat
,
1626 $status->value
= self
::AS_PARSE_ERROR
;
1627 wfProfileOut( __METHOD__
. '-checks' );
1628 wfProfileOut( __METHOD__
);
1632 # Check image redirect
1633 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1634 $textbox_content->isRedirect() &&
1635 !$wgUser->isAllowed( 'upload' )
1637 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1638 $status->setResult( false, $code );
1640 wfProfileOut( __METHOD__
. '-checks' );
1641 wfProfileOut( __METHOD__
);
1647 $match = self
::matchSummarySpamRegex( $this->summary
);
1648 if ( $match === false && $this->section
== 'new' ) {
1649 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1650 # regular summaries, it is added to the actual wikitext.
1651 if ( $this->sectiontitle
!== '' ) {
1652 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1653 $match = self
::matchSpamRegex( $this->sectiontitle
);
1655 # This branch is taken when the "Add Topic" user interface is used, or the API
1656 # is used with the 'summary' parameter.
1657 $match = self
::matchSpamRegex( $this->summary
);
1660 if ( $match === false ) {
1661 $match = self
::matchSpamRegex( $this->textbox1
);
1663 if ( $match !== false ) {
1664 $result['spam'] = $match;
1665 $ip = $wgRequest->getIP();
1666 $pdbk = $this->mTitle
->getPrefixedDBkey();
1667 $match = str_replace( "\n", '', $match );
1668 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1669 $status->fatal( 'spamprotectionmatch', $match );
1670 $status->value
= self
::AS_SPAM_ERROR
;
1671 wfProfileOut( __METHOD__
. '-checks' );
1672 wfProfileOut( __METHOD__
);
1677 array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) )
1679 # Error messages etc. could be handled within the hook...
1680 $status->fatal( 'hookaborted' );
1681 $status->value
= self
::AS_HOOK_ERROR
;
1682 wfProfileOut( __METHOD__
. '-checks' );
1683 wfProfileOut( __METHOD__
);
1685 } elseif ( $this->hookError
!= '' ) {
1686 # ...or the hook could be expecting us to produce an error
1687 $status->fatal( 'hookaborted' );
1688 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1689 wfProfileOut( __METHOD__
. '-checks' );
1690 wfProfileOut( __METHOD__
);
1694 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1695 // Auto-block user's IP if the account was "hard" blocked
1696 $wgUser->spreadAnyEditBlock();
1697 # Check block state against master, thus 'false'.
1698 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1699 wfProfileOut( __METHOD__
. '-checks' );
1700 wfProfileOut( __METHOD__
);
1704 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1705 if ( $this->kblength
> $wgMaxArticleSize ) {
1706 // Error will be displayed by showEditForm()
1707 $this->tooBig
= true;
1708 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1709 wfProfileOut( __METHOD__
. '-checks' );
1710 wfProfileOut( __METHOD__
);
1714 if ( !$wgUser->isAllowed( 'edit' ) ) {
1715 if ( $wgUser->isAnon() ) {
1716 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1717 wfProfileOut( __METHOD__
. '-checks' );
1718 wfProfileOut( __METHOD__
);
1721 $status->fatal( 'readonlytext' );
1722 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1723 wfProfileOut( __METHOD__
. '-checks' );
1724 wfProfileOut( __METHOD__
);
1729 if ( wfReadOnly() ) {
1730 $status->fatal( 'readonlytext' );
1731 $status->value
= self
::AS_READ_ONLY_PAGE
;
1732 wfProfileOut( __METHOD__
. '-checks' );
1733 wfProfileOut( __METHOD__
);
1736 if ( $wgUser->pingLimiter() ||
$wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1737 $status->fatal( 'actionthrottledtext' );
1738 $status->value
= self
::AS_RATE_LIMITED
;
1739 wfProfileOut( __METHOD__
. '-checks' );
1740 wfProfileOut( __METHOD__
);
1744 # If the article has been deleted while editing, don't save it without
1746 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1747 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1748 wfProfileOut( __METHOD__
. '-checks' );
1749 wfProfileOut( __METHOD__
);
1753 wfProfileOut( __METHOD__
. '-checks' );
1755 # Load the page data from the master. If anything changes in the meantime,
1756 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1757 $this->mArticle
->loadPageData( 'fromdbmaster' );
1758 $new = !$this->mArticle
->exists();
1761 // Late check for create permission, just in case *PARANOIA*
1762 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1763 $status->fatal( 'nocreatetext' );
1764 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1765 wfDebug( __METHOD__
. ": no create permission\n" );
1766 wfProfileOut( __METHOD__
);
1770 // Don't save a new page if it's blank or if it's a MediaWiki:
1771 // message with content equivalent to default (allow empty pages
1772 // in this case to disable messages, see bug 50124)
1773 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1774 if ( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1775 $defaultText = $defaultMessageText;
1780 if ( $this->textbox1
=== $defaultText ) {
1781 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1782 wfProfileOut( __METHOD__
);
1786 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1787 wfProfileOut( __METHOD__
);
1791 $content = $textbox_content;
1793 $result['sectionanchor'] = '';
1794 if ( $this->section
== 'new' ) {
1795 if ( $this->sectiontitle
!== '' ) {
1796 // Insert the section title above the content.
1797 $content = $content->addSectionHeader( $this->sectiontitle
);
1798 } elseif ( $this->summary
!== '' ) {
1799 // Insert the section title above the content.
1800 $content = $content->addSectionHeader( $this->summary
);
1802 $this->summary
= $this->newSectionSummary( $result['sectionanchor'] );
1805 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1809 # Article exists. Check for edit conflict.
1811 $this->mArticle
->clear(); # Force reload of dates, etc.
1812 $timestamp = $this->mArticle
->getTimestamp();
1814 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1816 if ( $timestamp != $this->edittime
) {
1817 $this->isConflict
= true;
1818 if ( $this->section
== 'new' ) {
1819 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1820 $this->mArticle
->getComment() == $this->newSectionSummary()
1822 // Probably a duplicate submission of a new comment.
1823 // This can happen when squid resends a request after
1824 // a timeout but the first one actually went through.
1826 . ": duplicate new section submission; trigger edit conflict!\n" );
1828 // New comment; suppress conflict.
1829 $this->isConflict
= false;
1830 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1832 } elseif ( $this->section
== ''
1833 && Revision
::userWasLastToEdit(
1834 DB_MASTER
, $this->mTitle
->getArticleID(),
1835 $wgUser->getId(), $this->edittime
1838 # Suppress edit conflict with self, except for section edits where merging is required.
1839 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1840 $this->isConflict
= false;
1844 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1845 if ( $this->sectiontitle
!== '' ) {
1846 $sectionTitle = $this->sectiontitle
;
1848 $sectionTitle = $this->summary
;
1853 if ( $this->isConflict
) {
1855 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1856 . " (article time '{$timestamp}')\n" );
1858 $content = $this->mArticle
->replaceSectionContent(
1865 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1866 $content = $this->mArticle
->replaceSectionContent(
1873 if ( is_null( $content ) ) {
1874 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1875 $this->isConflict
= true;
1876 $content = $textbox_content; // do not try to merge here!
1877 } elseif ( $this->isConflict
) {
1879 if ( $this->mergeChangesIntoContent( $content ) ) {
1880 // Successful merge! Maybe we should tell the user the good news?
1881 $this->isConflict
= false;
1882 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1884 $this->section
= '';
1885 $this->textbox1
= ContentHandler
::getContentText( $content );
1886 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1890 if ( $this->isConflict
) {
1891 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1892 wfProfileOut( __METHOD__
);
1896 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1897 wfProfileOut( __METHOD__
);
1901 if ( $this->section
== 'new' ) {
1902 // Handle the user preference to force summaries here
1903 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1904 $this->missingSummary
= true;
1905 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1906 $status->value
= self
::AS_SUMMARY_NEEDED
;
1907 wfProfileOut( __METHOD__
);
1911 // Do not allow the user to post an empty comment
1912 if ( $this->textbox1
== '' ) {
1913 $this->missingComment
= true;
1914 $status->fatal( 'missingcommenttext' );
1915 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1916 wfProfileOut( __METHOD__
);
1919 } elseif ( !$this->allowBlankSummary
1920 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1921 && !$content->isRedirect()
1922 && md5( $this->summary
) == $this->autoSumm
1924 $this->missingSummary
= true;
1925 $status->fatal( 'missingsummary' );
1926 $status->value
= self
::AS_SUMMARY_NEEDED
;
1927 wfProfileOut( __METHOD__
);
1932 wfProfileIn( __METHOD__
. '-sectionanchor' );
1933 $sectionanchor = '';
1934 if ( $this->section
== 'new' ) {
1935 $this->summary
= $this->newSectionSummary( $sectionanchor );
1936 } elseif ( $this->section
!= '' ) {
1937 # Try to get a section anchor from the section source, redirect
1938 # to edited section if header found.
1939 # XXX: Might be better to integrate this into Article::replaceSection
1940 # for duplicate heading checking and maybe parsing.
1941 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1942 # We can't deal with anchors, includes, html etc in the header for now,
1943 # headline would need to be parsed to improve this.
1944 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1945 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1948 $result['sectionanchor'] = $sectionanchor;
1949 wfProfileOut( __METHOD__
. '-sectionanchor' );
1951 // Save errors may fall down to the edit form, but we've now
1952 // merged the section into full text. Clear the section field
1953 // so that later submission of conflict forms won't try to
1954 // replace that into a duplicated mess.
1955 $this->textbox1
= $this->toEditText( $content );
1956 $this->section
= '';
1958 $status->value
= self
::AS_SUCCESS_UPDATE
;
1961 // Check for length errors again now that the section is merged in
1962 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1963 if ( $this->kblength
> $wgMaxArticleSize ) {
1964 $this->tooBig
= true;
1965 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1966 wfProfileOut( __METHOD__
);
1970 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1971 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1972 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1973 ( $bot ? EDIT_FORCE_BOT
: 0 );
1975 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags,
1976 false, null, $this->contentFormat
);
1978 if ( !$doEditStatus->isOK() ) {
1979 // Failure from doEdit()
1980 // Show the edit conflict page for certain recognized errors from doEdit(),
1981 // but don't show it for errors from extension hooks
1982 $errors = $doEditStatus->getErrorsArray();
1983 if ( in_array( $errors[0][0],
1984 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1986 $this->isConflict
= true;
1987 // Destroys data doEdit() put in $status->value but who cares
1988 $doEditStatus->value
= self
::AS_END
;
1990 wfProfileOut( __METHOD__
);
1991 return $doEditStatus;
1994 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1995 if ( $result['nullEdit'] ) {
1996 // We don't know if it was a null edit until now, so increment here
1997 $wgUser->pingLimiter( 'linkpurge' );
1999 $result['redirect'] = $content->isRedirect();
2000 $this->updateWatchlist();
2001 wfProfileOut( __METHOD__
);
2006 * Register the change of watch status
2008 protected function updateWatchlist() {
2011 if ( $wgUser->isLoggedIn()
2012 && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
, WatchedItem
::IGNORE_USER_RIGHTS
)
2014 $fname = __METHOD__
;
2015 $title = $this->mTitle
;
2016 $watch = $this->watchthis
;
2018 // Do this in its own transaction to reduce contention...
2019 $dbw = wfGetDB( DB_MASTER
);
2020 $dbw->onTransactionIdle( function() use ( $dbw, $title, $watch, $wgUser, $fname ) {
2021 $dbw->begin( $fname );
2022 WatchAction
::doWatchOrUnwatch( $watch, $title, $wgUser );
2023 $dbw->commit( $fname );
2029 * Attempts to merge text content with base and current revisions
2031 * @param string $editText
2034 * @deprecated since 1.21, use mergeChangesIntoContent() instead
2036 function mergeChangesInto( &$editText ) {
2037 ContentHandler
::deprecated( __METHOD__
, "1.21" );
2039 $editContent = $this->toEditContent( $editText );
2041 $ok = $this->mergeChangesIntoContent( $editContent );
2044 $editText = $this->toEditText( $editContent );
2051 * Attempts to do 3-way merge of edit content with a base revision
2052 * and current content, in case of edit conflict, in whichever way appropriate
2053 * for the content type.
2057 * @param Content $editContent
2061 private function mergeChangesIntoContent( &$editContent ) {
2062 wfProfileIn( __METHOD__
);
2064 $db = wfGetDB( DB_MASTER
);
2066 // This is the revision the editor started from
2067 $baseRevision = $this->getBaseRevision();
2068 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
2070 if ( is_null( $baseContent ) ) {
2071 wfProfileOut( __METHOD__
);
2075 // The current state, we want to merge updates into it
2076 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2077 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
2079 if ( is_null( $currentContent ) ) {
2080 wfProfileOut( __METHOD__
);
2084 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
2086 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2089 $editContent = $result;
2090 wfProfileOut( __METHOD__
);
2094 wfProfileOut( __METHOD__
);
2101 function getBaseRevision() {
2102 if ( !$this->mBaseRevision
) {
2103 $db = wfGetDB( DB_MASTER
);
2104 $this->mBaseRevision
= Revision
::loadFromTimestamp(
2105 $db, $this->mTitle
, $this->edittime
);
2107 return $this->mBaseRevision
;
2111 * Check given input text against $wgSpamRegex, and return the text of the first match.
2113 * @param string $text
2115 * @return string|bool Matching string or false
2117 public static function matchSpamRegex( $text ) {
2118 global $wgSpamRegex;
2119 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2120 $regexes = (array)$wgSpamRegex;
2121 return self
::matchSpamRegexInternal( $text, $regexes );
2125 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2127 * @param string $text
2129 * @return string|bool Matching string or false
2131 public static function matchSummarySpamRegex( $text ) {
2132 global $wgSummarySpamRegex;
2133 $regexes = (array)$wgSummarySpamRegex;
2134 return self
::matchSpamRegexInternal( $text, $regexes );
2138 * @param string $text
2139 * @param array $regexes
2140 * @return bool|string
2142 protected static function matchSpamRegexInternal( $text, $regexes ) {
2143 foreach ( $regexes as $regex ) {
2145 if ( preg_match( $regex, $text, $matches ) ) {
2152 function setHeaders() {
2153 global $wgOut, $wgUser;
2155 $wgOut->addModules( 'mediawiki.action.edit' );
2156 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2158 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
2159 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2162 if ( $wgUser->getOption( 'useeditwarning', false ) ) {
2163 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2166 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2168 # Enabled article-related sidebar, toplinks, etc.
2169 $wgOut->setArticleRelated( true );
2171 $contextTitle = $this->getContextTitle();
2172 if ( $this->isConflict
) {
2173 $msg = 'editconflict';
2174 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
2175 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
2177 $msg = $contextTitle->exists()
2178 ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
2179 && $contextTitle->getDefaultMessageText() !== false
2185 # Use the title defined by DISPLAYTITLE magic word when present
2186 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
2187 if ( $displayTitle === false ) {
2188 $displayTitle = $contextTitle->getPrefixedText();
2190 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2194 * Show all applicable editing introductions
2196 protected function showIntro() {
2197 global $wgOut, $wgUser;
2198 if ( $this->suppressIntro
) {
2202 $namespace = $this->mTitle
->getNamespace();
2204 if ( $namespace == NS_MEDIAWIKI
) {
2205 # Show a warning if editing an interface message
2206 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2207 } elseif ( $namespace == NS_FILE
) {
2208 # Show a hint to shared repo
2209 $file = wfFindFile( $this->mTitle
);
2210 if ( $file && !$file->isLocal() ) {
2211 $descUrl = $file->getDescriptionUrl();
2212 # there must be a description url to show a hint to shared repo
2214 if ( !$this->mTitle
->exists() ) {
2215 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2216 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2219 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2220 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2227 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2228 # Show log extract when the user is currently blocked
2229 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
2230 $parts = explode( '/', $this->mTitle
->getText(), 2 );
2231 $username = $parts[0];
2232 $user = User
::newFromName( $username, false /* allow IP users*/ );
2233 $ip = User
::isIP( $username );
2234 $block = Block
::newFromTarget( $user, $user );
2235 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2236 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2237 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2238 } elseif ( !is_null( $block ) && $block->getType() != Block
::TYPE_AUTO
) { # Show log extract if the user is currently blocked
2239 LogEventsList
::showLogExtract(
2242 MWNamespace
::getCanonicalName( NS_USER
) . ':' . $block->getTarget(),
2246 'showIfEmpty' => false,
2248 'blocked-notice-logextract',
2249 $user->getName() # Support GENDER in notice
2255 # Try to add a custom edit intro, or use the standard one if this is not possible.
2256 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2257 $helpLink = wfExpandUrl( Skin
::makeInternalOrExternalUrl(
2258 wfMessage( 'helppage' )->inContentLanguage()->text()
2260 if ( $wgUser->isLoggedIn() ) {
2261 $wgOut->wrapWikiMsg(
2262 // Suppress the external link icon, consider the help url an internal one
2263 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2270 $wgOut->wrapWikiMsg(
2271 // Suppress the external link icon, consider the help url an internal one
2272 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2274 'newarticletextanon',
2280 # Give a notice if the user is editing a deleted/moved page...
2281 if ( !$this->mTitle
->exists() ) {
2282 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
2286 'conds' => array( "log_action != 'revision'" ),
2287 'showIfEmpty' => false,
2288 'msgKey' => array( 'recreate-moveddeleted-warn' )
2295 * Attempt to show a custom editing introduction, if supplied
2299 protected function showCustomIntro() {
2300 if ( $this->editintro
) {
2301 $title = Title
::newFromText( $this->editintro
);
2302 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2304 // Added using template syntax, to take <noinclude>'s into account.
2305 $wgOut->addWikiTextTitleTidy( '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>', $this->mTitle
);
2313 * Gets an editable textual representation of $content.
2314 * The textual representation can be turned by into a Content object by the
2315 * toEditContent() method.
2317 * If $content is null or false or a string, $content is returned unchanged.
2319 * If the given Content object is not of a type that can be edited using
2320 * the text base EditPage, an exception will be raised. Set
2321 * $this->allowNonTextContent to true to allow editing of non-textual
2324 * @param Content|null|bool|string $content
2325 * @return string The editable text form of the content.
2327 * @throws MWException if $content is not an instance of TextContent and
2328 * $this->allowNonTextContent is not true.
2330 protected function toEditText( $content ) {
2331 if ( $content === null ||
$content === false ) {
2335 if ( is_string( $content ) ) {
2339 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2340 throw new MWException( 'This content model is not supported: '
2341 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2344 return $content->serialize( $this->contentFormat
);
2348 * Turns the given text into a Content object by unserializing it.
2350 * If the resulting Content object is not of a type that can be edited using
2351 * the text base EditPage, an exception will be raised. Set
2352 * $this->allowNonTextContent to true to allow editing of non-textual
2355 * @param string|null|bool $text Text to unserialize
2356 * @return Content The content object created from $text. If $text was false
2357 * or null, false resp. null will be returned instead.
2359 * @throws MWException if unserializing the text results in a Content
2360 * object that is not an instance of TextContent and
2361 * $this->allowNonTextContent is not true.
2363 protected function toEditContent( $text ) {
2364 if ( $text === false ||
$text === null ) {
2368 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2369 $this->contentModel
, $this->contentFormat
);
2371 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2372 throw new MWException( 'This content model is not supported: '
2373 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2380 * Send the edit form and related headers to $wgOut
2381 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2382 * during form output near the top, for captchas and the like.
2384 function showEditForm( $formCallback = null ) {
2385 global $wgOut, $wgUser;
2387 wfProfileIn( __METHOD__
);
2389 # need to parse the preview early so that we know which templates are used,
2390 # otherwise users with "show preview after edit box" will get a blank list
2391 # we parse this near the beginning so that setHeaders can do the title
2392 # setting work instead of leaving it in getPreviewText
2393 $previewOutput = '';
2394 if ( $this->formtype
== 'preview' ) {
2395 $previewOutput = $this->getPreviewText();
2398 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2400 $this->setHeaders();
2402 if ( $this->showHeader() === false ) {
2403 wfProfileOut( __METHOD__
);
2407 $wgOut->addHTML( $this->editFormPageTop
);
2409 if ( $wgUser->getOption( 'previewontop' ) ) {
2410 $this->displayPreviewArea( $previewOutput, true );
2413 $wgOut->addHTML( $this->editFormTextTop
);
2415 $showToolbar = true;
2416 if ( $this->wasDeletedSinceLastEdit() ) {
2417 if ( $this->formtype
== 'save' ) {
2418 // Hide the toolbar and edit area, user can click preview to get it back
2419 // Add an confirmation checkbox and explanation.
2420 $showToolbar = false;
2422 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2423 'deletedwhileediting' );
2427 // @todo add EditForm plugin interface and use it here!
2428 // search for textarea1 and textares2, and allow EditForm to override all uses.
2429 $wgOut->addHTML( Html
::openElement(
2432 'id' => self
::EDITFORM_ID
,
2433 'name' => self
::EDITFORM_ID
,
2435 'action' => $this->getActionURL( $this->getContextTitle() ),
2436 'enctype' => 'multipart/form-data'
2440 if ( is_callable( $formCallback ) ) {
2441 call_user_func_array( $formCallback, array( &$wgOut ) );
2444 // Add an empty field to trip up spambots
2446 Xml
::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2449 array( 'for' => 'wpAntiSpam' ),
2450 wfMessage( 'simpleantispam-label' )->parse()
2456 'name' => 'wpAntispam',
2457 'id' => 'wpAntispam',
2461 . Xml
::closeElement( 'div' )
2464 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2466 // Put these up at the top to ensure they aren't lost on early form submission
2467 $this->showFormBeforeText();
2469 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2470 $username = $this->lastDelete
->user_name
;
2471 $comment = $this->lastDelete
->log_comment
;
2473 // It is better to not parse the comment at all than to have templates expanded in the middle
2474 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2475 $key = $comment === ''
2476 ?
'confirmrecreate-noreason'
2477 : 'confirmrecreate';
2479 '<div class="mw-confirm-recreate">' .
2480 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2481 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2482 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2488 # When the summary is hidden, also hide them on preview/show changes
2489 if ( $this->nosummary
) {
2490 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2493 # If a blank edit summary was previously provided, and the appropriate
2494 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2495 # user being bounced back more than once in the event that a summary
2498 # For a bit more sophisticated detection of blank summaries, hash the
2499 # automatic one and pass that in the hidden field wpAutoSummary.
2500 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2501 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2504 if ( $this->undidRev
) {
2505 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2508 if ( $this->hasPresetSummary
) {
2509 // If a summary has been preset using &summary= we don't want to prompt for
2510 // a different summary. Only prompt for a summary if the summary is blanked.
2512 $this->autoSumm
= md5( '' );
2515 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2516 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2518 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2520 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2521 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2523 if ( $this->section
== 'new' ) {
2524 $this->showSummaryInput( true, $this->summary
);
2525 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2528 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2530 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2531 $wgOut->addHTML( EditPage
::getEditToolbar() );
2534 if ( $this->isConflict
) {
2535 // In an edit conflict bypass the overridable content form method
2536 // and fallback to the raw wpTextbox1 since editconflicts can't be
2537 // resolved between page source edits and custom ui edits using the
2539 $this->textbox2
= $this->textbox1
;
2541 $content = $this->getCurrentContent();
2542 $this->textbox1
= $this->toEditText( $content );
2544 $this->showTextbox1();
2546 $this->showContentForm();
2549 $wgOut->addHTML( $this->editFormTextAfterContent
);
2551 $this->showStandardInputs();
2553 $this->showFormAfterText();
2555 $this->showTosSummary();
2557 $this->showEditTools();
2559 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2561 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2562 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2564 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2565 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2567 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'limitreport' ),
2568 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2570 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2572 if ( $this->isConflict
) {
2574 $this->showConflict();
2575 } catch ( MWContentSerializationException
$ex ) {
2576 // this can't really happen, but be nice if it does.
2578 'content-failed-to-parse',
2579 $this->contentModel
,
2580 $this->contentFormat
,
2583 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2587 // Marker for detecting truncated form data. This must be the last
2588 // parameter sent in order to be of use, so do not move me.
2589 $wgOut->addHTML( Html
::hidden( 'wpUltimateParam', true ) );
2590 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2592 if ( !$wgUser->getOption( 'previewontop' ) ) {
2593 $this->displayPreviewArea( $previewOutput, false );
2596 wfProfileOut( __METHOD__
);
2600 * Extract the section title from current section text, if any.
2602 * @param string $text
2603 * @return string|bool string or false
2605 public static function extractSectionTitle( $text ) {
2606 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2607 if ( !empty( $matches[2] ) ) {
2609 return $wgParser->stripSectionName( trim( $matches[2] ) );
2618 protected function showHeader() {
2619 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2620 global $wgAllowUserCss, $wgAllowUserJs;
2622 if ( $this->mTitle
->isTalkPage() ) {
2623 $wgOut->addWikiMsg( 'talkpagetext' );
2627 $wgOut->addHTML( implode( "\n", $this->mTitle
->getEditNotices( $this->oldid
) ) );
2629 if ( $this->isConflict
) {
2630 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2631 $this->edittime
= $this->mArticle
->getTimestamp();
2633 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2634 // We use $this->section to much before this and getVal('wgSection') directly in other places
2635 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2636 // Someone is welcome to try refactoring though
2637 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2641 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2642 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2643 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2644 if ( $sectionTitle !== false ) {
2645 $this->summary
= "/* $sectionTitle */ ";
2650 if ( $this->missingComment
) {
2651 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2654 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2655 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2658 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2659 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2662 if ( $this->hookError
!== '' ) {
2663 $wgOut->addWikiText( $this->hookError
);
2666 if ( !$this->checkUnicodeCompliantBrowser() ) {
2667 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2670 if ( $this->section
!= 'new' ) {
2671 $revision = $this->mArticle
->getRevisionFetched();
2673 // Let sysop know that this will make private content public if saved
2675 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2676 $wgOut->wrapWikiMsg(
2677 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2678 'rev-deleted-text-permission'
2680 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2681 $wgOut->wrapWikiMsg(
2682 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2683 'rev-deleted-text-view'
2687 if ( !$revision->isCurrent() ) {
2688 $this->mArticle
->setOldSubtitle( $revision->getId() );
2689 $wgOut->addWikiMsg( 'editingold' );
2691 } elseif ( $this->mTitle
->exists() ) {
2692 // Something went wrong
2694 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2695 array( 'missing-revision', $this->oldid
) );
2700 if ( wfReadOnly() ) {
2701 $wgOut->wrapWikiMsg(
2702 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2703 array( 'readonlywarning', wfReadOnlyReason() )
2705 } elseif ( $wgUser->isAnon() ) {
2706 if ( $this->formtype
!= 'preview' ) {
2707 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2709 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2712 if ( $this->isCssJsSubpage
) {
2713 # Check the skin exists
2714 if ( $this->isWrongCaseCssJsPage
) {
2715 $wgOut->wrapWikiMsg(
2716 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2717 array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() )
2720 if ( $this->formtype
!== 'preview' ) {
2721 if ( $this->isCssSubpage
&& $wgAllowUserCss ) {
2722 $wgOut->wrapWikiMsg(
2723 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2724 array( 'usercssyoucanpreview' )
2728 if ( $this->isJsSubpage
&& $wgAllowUserJs ) {
2729 $wgOut->wrapWikiMsg(
2730 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2731 array( 'userjsyoucanpreview' )
2738 if ( $this->mTitle
->isProtected( 'edit' ) &&
2739 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2741 # Is the title semi-protected?
2742 if ( $this->mTitle
->isSemiProtected() ) {
2743 $noticeMsg = 'semiprotectedpagewarning';
2745 # Then it must be protected based on static groups (regular)
2746 $noticeMsg = 'protectedpagewarning';
2748 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2749 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2751 if ( $this->mTitle
->isCascadeProtected() ) {
2752 # Is this page under cascading protection from some source pages?
2753 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2754 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2755 $cascadeSourcesCount = count( $cascadeSources );
2756 if ( $cascadeSourcesCount > 0 ) {
2757 # Explain, and list the titles responsible
2758 foreach ( $cascadeSources as $page ) {
2759 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2762 $notice .= '</div>';
2763 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2765 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2766 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2768 'showIfEmpty' => false,
2769 'msgKey' => array( 'titleprotectedwarning' ),
2770 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2773 if ( $this->kblength
=== false ) {
2774 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2777 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2778 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2781 $wgLang->formatNum( $this->kblength
),
2782 $wgLang->formatNum( $wgMaxArticleSize )
2786 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2787 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2790 $wgLang->formatSize( strlen( $this->textbox1
) ),
2791 strlen( $this->textbox1
)
2796 # Add header copyright warning
2797 $this->showHeaderCopyrightWarning();
2803 * Standard summary input and label (wgSummary), abstracted so EditPage
2804 * subclasses may reorganize the form.
2805 * Note that you do not need to worry about the label's for=, it will be
2806 * inferred by the id given to the input. You can remove them both by
2807 * passing array( 'id' => false ) to $userInputAttrs.
2809 * @param string $summary The value of the summary input
2810 * @param string $labelText The html to place inside the label
2811 * @param array $inputAttrs Array of attrs to use on the input
2812 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2814 * @return array An array in the format array( $label, $input )
2816 function getSummaryInput( $summary = "", $labelText = null,
2817 $inputAttrs = null, $spanLabelAttrs = null
2819 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2820 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2821 'id' => 'wpSummary',
2822 'maxlength' => '200',
2825 'spellcheck' => 'true',
2826 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2828 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2829 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2830 'id' => "wpSummaryLabel"
2837 $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null,
2840 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2843 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2845 return array( $label, $input );
2849 * @param bool $isSubjectPreview true if this is the section subject/title
2850 * up top, or false if this is the comment summary
2851 * down below the textarea
2852 * @param string $summary The text of the summary to display
2855 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2856 global $wgOut, $wgContLang;
2857 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2858 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2859 if ( $isSubjectPreview ) {
2860 if ( $this->nosummary
) {
2864 if ( !$this->mShowSummaryField
) {
2868 $summary = $wgContLang->recodeForEdit( $summary );
2869 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2870 list( $label, $input ) = $this->getSummaryInput(
2873 array( 'class' => $summaryClass ),
2876 $wgOut->addHTML( "{$label} {$input}" );
2880 * @param bool $isSubjectPreview true if this is the section subject/title
2881 * up top, or false if this is the comment summary
2882 * down below the textarea
2883 * @param string $summary The text of the summary to display
2886 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2887 // avoid spaces in preview, gets always trimmed on save
2888 $summary = trim( $summary );
2889 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2895 if ( $isSubjectPreview ) {
2896 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2897 ->inContentLanguage()->text();
2900 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2902 $summary = wfMessage( $message )->parse()
2903 . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2904 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2907 protected function showFormBeforeText() {
2909 $section = htmlspecialchars( $this->section
);
2910 $wgOut->addHTML( <<<HTML
2911 <input type='hidden' value="{$section}" name="wpSection" />
2912 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2913 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2914 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2918 if ( !$this->checkUnicodeCompliantBrowser() ) {
2919 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2923 protected function showFormAfterText() {
2924 global $wgOut, $wgUser;
2926 * To make it harder for someone to slip a user a page
2927 * which submits an edit form to the wiki without their
2928 * knowledge, a random token is associated with the login
2929 * session. If it's not passed back with the submission,
2930 * we won't save the page, or render user JavaScript and
2933 * For anon editors, who may not have a session, we just
2934 * include the constant suffix to prevent editing from
2935 * broken text-mangling proxies.
2937 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2941 * Subpage overridable method for printing the form for page content editing
2942 * By default this simply outputs wpTextbox1
2943 * Subclasses can override this to provide a custom UI for editing;
2944 * be it a form, or simply wpTextbox1 with a modified content that will be
2945 * reverse modified when extracted from the post data.
2946 * Note that this is basically the inverse for importContentFormData
2948 protected function showContentForm() {
2949 $this->showTextbox1();
2953 * Method to output wpTextbox1
2954 * The $textoverride method can be used by subclasses overriding showContentForm
2955 * to pass back to this method.
2957 * @param array $customAttribs Array of html attributes to use in the textarea
2958 * @param string $textoverride Optional text to override $this->textarea1 with
2960 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2961 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2962 $attribs = array( 'style' => 'display:none;' );
2964 $classes = array(); // Textarea CSS
2965 if ( $this->mTitle
->isProtected( 'edit' ) &&
2966 MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) !== array( '' )
2968 # Is the title semi-protected?
2969 if ( $this->mTitle
->isSemiProtected() ) {
2970 $classes[] = 'mw-textarea-sprotected';
2972 # Then it must be protected based on static groups (regular)
2973 $classes[] = 'mw-textarea-protected';
2975 # Is the title cascade-protected?
2976 if ( $this->mTitle
->isCascadeProtected() ) {
2977 $classes[] = 'mw-textarea-cprotected';
2981 $attribs = array( 'tabindex' => 1 );
2983 if ( is_array( $customAttribs ) ) {
2984 $attribs +
= $customAttribs;
2987 if ( count( $classes ) ) {
2988 if ( isset( $attribs['class'] ) ) {
2989 $classes[] = $attribs['class'];
2991 $attribs['class'] = implode( ' ', $classes );
2996 $textoverride !== null ?
$textoverride : $this->textbox1
,
3002 protected function showTextbox2() {
3003 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
3006 protected function showTextbox( $text, $name, $customAttribs = array() ) {
3007 global $wgOut, $wgUser;
3009 $wikitext = $this->safeUnicodeOutput( $text );
3010 if ( strval( $wikitext ) !== '' ) {
3011 // Ensure there's a newline at the end, otherwise adding lines
3013 // But don't add a newline if the ext is empty, or Firefox in XHTML
3014 // mode will show an extra newline. A bit annoying.
3018 $attribs = $customAttribs +
array(
3021 'cols' => $wgUser->getIntOption( 'cols' ),
3022 'rows' => $wgUser->getIntOption( 'rows' ),
3023 // Avoid PHP notices when appending preferences
3024 // (appending allows customAttribs['style'] to still work).
3028 $pageLang = $this->mTitle
->getPageLanguage();
3029 $attribs['lang'] = $pageLang->getCode();
3030 $attribs['dir'] = $pageLang->getDir();
3032 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
3035 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3039 $classes[] = 'ontop';
3042 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3044 if ( $this->formtype
!= 'preview' ) {
3045 $attribs['style'] = 'display: none;';
3048 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
3050 if ( $this->formtype
== 'preview' ) {
3051 $this->showPreview( $previewOutput );
3054 $wgOut->addHTML( '</div>' );
3056 if ( $this->formtype
== 'diff' ) {
3059 } catch ( MWContentSerializationException
$ex ) {
3061 'content-failed-to-parse',
3062 $this->contentModel
,
3063 $this->contentFormat
,
3066 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3072 * Append preview output to $wgOut.
3073 * Includes category rendering if this is a category page.
3075 * @param string $text The HTML to be output for the preview.
3077 protected function showPreview( $text ) {
3079 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3080 $this->mArticle
->openShowCategory();
3082 # This hook seems slightly odd here, but makes things more
3083 # consistent for extensions.
3084 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3085 $wgOut->addHTML( $text );
3086 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3087 $this->mArticle
->closeShowCategory();
3092 * Get a diff between the current contents of the edit box and the
3093 * version of the page we're editing from.
3095 * If this is a section edit, we'll replace the section as for final
3096 * save and then make a comparison.
3098 function showDiff() {
3099 global $wgUser, $wgContLang, $wgOut;
3101 $oldtitlemsg = 'currentrev';
3102 # if message does not exist, show diff against the preloaded default
3103 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
3104 $oldtext = $this->mTitle
->getDefaultMessageText();
3105 if ( $oldtext !== false ) {
3106 $oldtitlemsg = 'defaultmessagetext';
3107 $oldContent = $this->toEditContent( $oldtext );
3112 $oldContent = $this->getCurrentContent();
3115 $textboxContent = $this->toEditContent( $this->textbox1
);
3117 $newContent = $this->mArticle
->replaceSectionContent(
3118 $this->section
, $textboxContent,
3119 $this->summary
, $this->edittime
);
3121 if ( $newContent ) {
3122 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3123 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3125 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
3126 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
3129 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
3130 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3131 $newtitle = wfMessage( 'yourtext' )->parse();
3133 if ( !$oldContent ) {
3134 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3137 if ( !$newContent ) {
3138 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3141 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
3142 $de->setContent( $oldContent, $newContent );
3144 $difftext = $de->getDiff( $oldtitle, $newtitle );
3145 $de->showDiffStyle();
3150 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3154 * Show the header copyright warning.
3156 protected function showHeaderCopyrightWarning() {
3157 $msg = 'editpage-head-copy-warn';
3158 if ( !wfMessage( $msg )->isDisabled() ) {
3160 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3161 'editpage-head-copy-warn' );
3166 * Give a chance for site and per-namespace customizations of
3167 * terms of service summary link that might exist separately
3168 * from the copyright notice.
3170 * This will display between the save button and the edit tools,
3171 * so should remain short!
3173 protected function showTosSummary() {
3174 $msg = 'editpage-tos-summary';
3175 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
3176 if ( !wfMessage( $msg )->isDisabled() ) {
3178 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3179 $wgOut->addWikiMsg( $msg );
3180 $wgOut->addHTML( '</div>' );
3184 protected function showEditTools() {
3186 $wgOut->addHTML( '<div class="mw-editTools">' .
3187 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3192 * Get the copyright warning
3194 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3196 protected function getCopywarn() {
3197 return self
::getCopyrightWarning( $this->mTitle
);
3201 * Get the copyright warning, by default returns wikitext
3203 * @param Title $title
3204 * @param string $format Output format, valid values are any function of a Message object
3207 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3208 global $wgRightsText;
3209 if ( $wgRightsText ) {
3210 $copywarnMsg = array( 'copyrightwarning',
3211 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3214 $copywarnMsg = array( 'copyrightwarning2',
3215 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3217 // Allow for site and per-namespace customization of contribution/copyright notice.
3218 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3220 return "<div id=\"editpage-copywarn\">\n" .
3221 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3225 * Get the Limit report for page previews
3228 * @param ParserOutput $output ParserOutput object from the parse
3229 * @return string HTML
3231 public static function getPreviewLimitReport( $output ) {
3232 if ( !$output ||
!$output->getLimitReportData() ) {
3236 wfProfileIn( __METHOD__
);
3238 $limitReport = Html
::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3239 wfMessage( 'limitreport-title' )->parseAsBlock()
3242 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3243 $limitReport .= Html
::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3245 $limitReport .= Html
::openElement( 'table', array(
3246 'class' => 'preview-limit-report wikitable'
3248 Html
::openElement( 'tbody' );
3250 foreach ( $output->getLimitReportData() as $key => $value ) {
3251 if ( wfRunHooks( 'ParserLimitReportFormat',
3252 array( $key, &$value, &$limitReport, true, true )
3254 $keyMsg = wfMessage( $key );
3255 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3256 if ( !$valueMsg->exists() ) {
3257 $valueMsg = new RawMessage( '$1' );
3259 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3260 $limitReport .= Html
::openElement( 'tr' ) .
3261 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
3262 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3263 Html
::closeElement( 'tr' );
3268 $limitReport .= Html
::closeElement( 'tbody' ) .
3269 Html
::closeElement( 'table' ) .
3270 Html
::closeElement( 'div' );
3272 wfProfileOut( __METHOD__
);
3274 return $limitReport;
3277 protected function showStandardInputs( &$tabindex = 2 ) {
3279 $wgOut->addHTML( "<div class='editOptions'>\n" );
3281 if ( $this->section
!= 'new' ) {
3282 $this->showSummaryInput( false, $this->summary
);
3283 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
3286 $checkboxes = $this->getCheckboxes( $tabindex,
3287 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
3288 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3290 // Show copyright warning.
3291 $wgOut->addWikiText( $this->getCopywarn() );
3292 $wgOut->addHTML( $this->editFormTextAfterWarn
);
3294 $wgOut->addHTML( "<div class='editButtons'>\n" );
3295 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3297 $cancel = $this->getCancelLink();
3298 if ( $cancel !== '' ) {
3299 $cancel .= Html
::element( 'span',
3300 array( 'class' => 'mw-editButtons-pipe-separator' ),
3301 wfMessage( 'pipe-separator' )->text() );
3304 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3305 $edithelpurl = Skin
::makeInternalOrExternalUrl( $message );
3306 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
3307 wfMessage( 'edithelp' )->escaped() . '</a> ' .
3308 wfMessage( 'newwindow' )->parse();
3310 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3311 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3312 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3314 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3316 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3320 * Show an edit conflict. textbox1 is already shown in showEditForm().
3321 * If you want to use another entry point to this function, be careful.
3323 protected function showConflict() {
3326 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3327 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3329 $content1 = $this->toEditContent( $this->textbox1
);
3330 $content2 = $this->toEditContent( $this->textbox2
);
3332 $handler = ContentHandler
::getForModelID( $this->contentModel
);
3333 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
3334 $de->setContent( $content2, $content1 );
3336 wfMessage( 'yourtext' )->parse(),
3337 wfMessage( 'storedversion' )->text()
3340 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3341 $this->showTextbox2();
3348 public function getCancelLink() {
3349 $cancelParams = array();
3350 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
3351 $cancelParams['oldid'] = $this->oldid
;
3354 return Linker
::linkKnown(
3355 $this->getContextTitle(),
3356 wfMessage( 'cancel' )->parse(),
3357 array( 'id' => 'mw-editform-cancel' ),
3363 * Returns the URL to use in the form's action attribute.
3364 * This is used by EditPage subclasses when simply customizing the action
3365 * variable in the constructor is not enough. This can be used when the
3366 * EditPage lives inside of a Special page rather than a custom page action.
3368 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3371 protected function getActionURL( Title
$title ) {
3372 return $title->getLocalURL( array( 'action' => $this->action
) );
3376 * Check if a page was deleted while the user was editing it, before submit.
3377 * Note that we rely on the logging table, which hasn't been always there,
3378 * but that doesn't matter, because this only applies to brand new
3382 protected function wasDeletedSinceLastEdit() {
3383 if ( $this->deletedSinceEdit
!== null ) {
3384 return $this->deletedSinceEdit
;
3387 $this->deletedSinceEdit
= false;
3389 if ( $this->mTitle
->isDeletedQuick() ) {
3390 $this->lastDelete
= $this->getLastDelete();
3391 if ( $this->lastDelete
) {
3392 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3393 if ( $deleteTime > $this->starttime
) {
3394 $this->deletedSinceEdit
= true;
3399 return $this->deletedSinceEdit
;
3403 * @return bool|stdClass
3405 protected function getLastDelete() {
3406 $dbr = wfGetDB( DB_SLAVE
);
3407 $data = $dbr->selectRow(
3408 array( 'logging', 'user' ),
3421 'log_namespace' => $this->mTitle
->getNamespace(),
3422 'log_title' => $this->mTitle
->getDBkey(),
3423 'log_type' => 'delete',
3424 'log_action' => 'delete',
3428 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3430 // Quick paranoid permission checks...
3431 if ( is_object( $data ) ) {
3432 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3433 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
3436 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3437 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
3445 * Get the rendered text for previewing.
3446 * @throws MWException
3449 function getPreviewText() {
3450 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3451 global $wgAllowUserCss, $wgAllowUserJs;
3453 wfProfileIn( __METHOD__
);
3455 if ( $wgRawHtml && !$this->mTokenOk
) {
3456 // Could be an offsite preview attempt. This is very unsafe if
3457 // HTML is enabled, as it could be an attack.
3459 if ( $this->textbox1
!== '' ) {
3460 // Do not put big scary notice, if previewing the empty
3461 // string, which happens when you initially edit
3462 // a category page, due to automatic preview-on-open.
3463 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3464 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3466 wfProfileOut( __METHOD__
);
3473 $content = $this->toEditContent( $this->textbox1
);
3477 'AlternateEditPreview',
3478 array( $this, &$content, &$previewHTML, &$this->mParserOutput
) )
3480 wfProfileOut( __METHOD__
);
3481 return $previewHTML;
3484 # provide a anchor link to the editform
3485 $continueEditing = '<span class="mw-continue-editing">' .
3486 '[[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' .
3487 wfMessage( 'continue-editing' )->text() . ']]</span>';
3488 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3489 if ( $this->mTokenOkExceptSuffix
) {
3490 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3492 $note = wfMessage( 'session_fail_preview' )->plain();
3494 } elseif ( $this->incompleteForm
) {
3495 $note = wfMessage( 'edit_form_incomplete' )->plain();
3497 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3500 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
3501 $parserOptions->setEditSection( false );
3502 $parserOptions->setIsPreview( true );
3503 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3505 # don't parse non-wikitext pages, show message about preview
3506 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3507 if ( $this->mTitle
->isCssJsSubpage() ) {
3509 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3515 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3517 if ( $level === 'user' && !$wgAllowUserCss ) {
3520 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3522 if ( $level === 'user' && !$wgAllowUserJs ) {
3529 # Used messages to make sure grep find them:
3530 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3531 if ( $level && $format ) {
3532 $note = "<div id='mw-{$level}{$format}preview'>" .
3533 wfMessage( "{$level}{$format}preview" )->text() .
3534 ' ' . $continueEditing . "</div>";
3538 # If we're adding a comment, we need to show the
3539 # summary as the headline
3540 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3541 $content = $content->addSectionHeader( $this->summary
);
3544 $hook_args = array( $this, &$content );
3545 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3546 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3548 $parserOptions->enableLimitReport();
3550 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3551 # But it's now deprecated, so never mind
3553 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3554 $parserOutput = $content->getParserOutput(
3555 $this->getArticle()->getTitle(),
3560 $previewHTML = $parserOutput->getText();
3561 $this->mParserOutput
= $parserOutput;
3562 $wgOut->addParserOutputMetadata( $parserOutput );
3564 if ( count( $parserOutput->getWarnings() ) ) {
3565 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3567 } catch ( MWContentSerializationException
$ex ) {
3569 'content-failed-to-parse',
3570 $this->contentModel
,
3571 $this->contentFormat
,
3574 $note .= "\n\n" . $m->parse();
3578 if ( $this->isConflict
) {
3579 $conflict = '<h2 id="mw-previewconflict">'
3580 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3582 $conflict = '<hr />';
3585 $previewhead = "<div class='previewnote'>\n" .
3586 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3587 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3589 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3590 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3591 'class' => 'mw-content-' . $pageViewLang->getDir() );
3592 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3594 wfProfileOut( __METHOD__
);
3595 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3601 function getTemplates() {
3602 if ( $this->preview ||
$this->section
!= '' ) {
3603 $templates = array();
3604 if ( !isset( $this->mParserOutput
) ) {
3607 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3608 foreach ( array_keys( $template ) as $dbk ) {
3609 $templates[] = Title
::makeTitle( $ns, $dbk );
3614 return $this->mTitle
->getTemplateLinksFrom();
3619 * Shows a bulletin board style toolbar for common editing functions.
3620 * It can be disabled in the user preferences.
3621 * The necessary JavaScript code can be found in skins/common/edit.js.
3625 static function getEditToolbar() {
3626 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3627 global $wgEnableUploads, $wgForeignFileRepos;
3629 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3632 * $toolarray is an array of arrays each of which includes the
3633 * filename of the button image (without path), the opening
3634 * tag, the closing tag, optionally a sample text that is
3635 * inserted between the two when no selection is highlighted
3636 * and. The tip text is shown when the user moves the mouse
3639 * Also here: accesskeys (key), which are not used yet until
3640 * someone can figure out a way to make them work in
3641 * IE. However, we should make sure these keys are not defined
3646 'image' => $wgLang->getImageFile( 'button-bold' ),
3647 'id' => 'mw-editbutton-bold',
3649 'close' => '\'\'\'',
3650 'sample' => wfMessage( 'bold_sample' )->text(),
3651 'tip' => wfMessage( 'bold_tip' )->text(),
3655 'image' => $wgLang->getImageFile( 'button-italic' ),
3656 'id' => 'mw-editbutton-italic',
3659 'sample' => wfMessage( 'italic_sample' )->text(),
3660 'tip' => wfMessage( 'italic_tip' )->text(),
3664 'image' => $wgLang->getImageFile( 'button-link' ),
3665 'id' => 'mw-editbutton-link',
3668 'sample' => wfMessage( 'link_sample' )->text(),
3669 'tip' => wfMessage( 'link_tip' )->text(),
3673 'image' => $wgLang->getImageFile( 'button-extlink' ),
3674 'id' => 'mw-editbutton-extlink',
3677 'sample' => wfMessage( 'extlink_sample' )->text(),
3678 'tip' => wfMessage( 'extlink_tip' )->text(),
3682 'image' => $wgLang->getImageFile( 'button-headline' ),
3683 'id' => 'mw-editbutton-headline',
3686 'sample' => wfMessage( 'headline_sample' )->text(),
3687 'tip' => wfMessage( 'headline_tip' )->text(),
3690 $imagesAvailable ?
array(
3691 'image' => $wgLang->getImageFile( 'button-image' ),
3692 'id' => 'mw-editbutton-image',
3693 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3695 'sample' => wfMessage( 'image_sample' )->text(),
3696 'tip' => wfMessage( 'image_tip' )->text(),
3699 $imagesAvailable ?
array(
3700 'image' => $wgLang->getImageFile( 'button-media' ),
3701 'id' => 'mw-editbutton-media',
3702 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3704 'sample' => wfMessage( 'media_sample' )->text(),
3705 'tip' => wfMessage( 'media_tip' )->text(),
3709 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3710 'id' => 'mw-editbutton-nowiki',
3711 'open' => "<nowiki>",
3712 'close' => "</nowiki>",
3713 'sample' => wfMessage( 'nowiki_sample' )->text(),
3714 'tip' => wfMessage( 'nowiki_tip' )->text(),
3718 'image' => $wgLang->getImageFile( 'button-sig' ),
3719 'id' => 'mw-editbutton-signature',
3723 'tip' => wfMessage( 'sig_tip' )->text(),
3727 'image' => $wgLang->getImageFile( 'button-hr' ),
3728 'id' => 'mw-editbutton-hr',
3729 'open' => "\n----\n",
3732 'tip' => wfMessage( 'hr_tip' )->text(),
3737 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3738 foreach ( $toolarray as $tool ) {
3744 $wgStylePath . '/common/images/' . $tool['image'],
3745 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3746 // Older browsers show a "speedtip" type message only for ALT.
3747 // Ideally these should be different, realistically they
3748 // probably don't need to be.
3756 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3759 // This used to be called on DOMReady from mediawiki.action.edit, which
3760 // ended up causing race conditions with the setup code above.
3762 "// Create button bar\n" .
3763 "$(function() { mw.toolbar.init(); } );\n";
3766 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3768 $toolbar = '<div id="toolbar"></div>';
3770 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3776 * Returns an array of html code of the following checkboxes:
3779 * @param int $tabindex Current tabindex
3780 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3781 * status of the checkbox
3785 public function getCheckboxes( &$tabindex, $checked ) {
3788 $checkboxes = array();
3790 // don't show the minor edit checkbox if it's a new page or section
3791 if ( !$this->isNew
) {
3792 $checkboxes['minor'] = '';
3793 $minorLabel = wfMessage( 'minoredit' )->parse();
3794 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3796 'tabindex' => ++
$tabindex,
3797 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3798 'id' => 'wpMinoredit',
3800 $checkboxes['minor'] =
3801 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3802 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3803 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3804 ">{$minorLabel}</label>";
3808 $watchLabel = wfMessage( 'watchthis' )->parse();
3809 $checkboxes['watch'] = '';
3810 if ( $wgUser->isLoggedIn() ) {
3812 'tabindex' => ++
$tabindex,
3813 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3814 'id' => 'wpWatchthis',
3816 $checkboxes['watch'] =
3817 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3818 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3819 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3820 ">{$watchLabel}</label>";
3822 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3827 * Returns an array of html code of the following buttons:
3828 * save, diff, preview and live
3830 * @param int $tabindex Current tabindex
3834 public function getEditButtons( &$tabindex ) {
3841 'tabindex' => ++
$tabindex,
3842 'value' => wfMessage( 'savearticle' )->text(),
3843 ) + Linker
::tooltipAndAccesskeyAttribs( 'save' );
3844 $buttons['save'] = Xml
::element( 'input', $attribs, '' );
3846 ++
$tabindex; // use the same for preview and live preview
3848 'id' => 'wpPreview',
3849 'name' => 'wpPreview',
3851 'tabindex' => $tabindex,
3852 'value' => wfMessage( 'showpreview' )->text(),
3853 ) + Linker
::tooltipAndAccesskeyAttribs( 'preview' );
3854 $buttons['preview'] = Xml
::element( 'input', $attribs, '' );
3855 $buttons['live'] = '';
3861 'tabindex' => ++
$tabindex,
3862 'value' => wfMessage( 'showdiff' )->text(),
3863 ) + Linker
::tooltipAndAccesskeyAttribs( 'diff' );
3864 $buttons['diff'] = Xml
::element( 'input', $attribs, '' );
3866 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3871 * Output preview text only. This can be sucked into the edit page
3872 * via JavaScript, and saves the server time rendering the skin as
3873 * well as theoretically being more robust on the client (doesn't
3874 * disturb the edit box's undo history, won't eat your text on
3877 * @todo This doesn't include category or interlanguage links.
3878 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3879 * or something...</s>" that might also require more skin
3880 * initialization, so check whether that's a problem.
3882 function livePreview() {
3885 header( 'Content-type: text/xml; charset=utf-8' );
3886 header( 'Cache-control: no-cache' );
3888 $previewText = $this->getPreviewText();
3889 #$categories = $skin->getCategoryLinks();
3892 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3893 Xml
::tags( 'livepreview', null,
3894 Xml
::element( 'preview', null, $previewText )
3895 #. Xml::element( 'category', null, $categories )
3901 * Call the stock "user is blocked" page
3903 * @deprecated since 1.19; throw an exception directly instead
3905 function blockedPage() {
3906 wfDeprecated( __METHOD__
, '1.19' );
3909 throw new UserBlockedError( $wgUser->getBlock() );
3913 * Produce the stock "please login to edit pages" page
3915 * @deprecated since 1.19; throw an exception directly instead
3917 function userNotLoggedInPage() {
3918 wfDeprecated( __METHOD__
, '1.19' );
3919 throw new PermissionsError( 'edit' );
3923 * Show an error page saying to the user that he has insufficient permissions
3924 * to create a new page
3926 * @deprecated since 1.19; throw an exception directly instead
3928 function noCreatePermission() {
3929 wfDeprecated( __METHOD__
, '1.19' );
3930 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3931 throw new PermissionsError( $permission );
3935 * Creates a basic error page which informs the user that
3936 * they have attempted to edit a nonexistent section.
3938 function noSuchSectionPage() {
3941 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3943 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3944 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3945 $wgOut->addHTML( $res );
3947 $wgOut->returnToMain( false, $this->mTitle
);
3951 * Show "your edit contains spam" page with your diff and text
3953 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3955 public function spamPageWithContent( $match = false ) {
3956 global $wgOut, $wgLang;
3957 $this->textbox2
= $this->textbox1
;
3959 if ( is_array( $match ) ) {
3960 $match = $wgLang->listToText( $match );
3962 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3964 $wgOut->addHTML( '<div id="spamprotected">' );
3965 $wgOut->addWikiMsg( 'spamprotectiontext' );
3967 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3969 $wgOut->addHTML( '</div>' );
3971 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3974 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3975 $this->showTextbox2();
3977 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3981 * Check if the browser is on a blacklist of user-agents known to
3982 * mangle UTF-8 data on form submission. Returns true if Unicode
3983 * should make it through, false if it's known to be a problem.
3986 private function checkUnicodeCompliantBrowser() {
3987 global $wgBrowserBlackList, $wgRequest;
3989 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3990 if ( $currentbrowser === false ) {
3991 // No User-Agent header sent? Trust it by default...
3995 foreach ( $wgBrowserBlackList as $browser ) {
3996 if ( preg_match( $browser, $currentbrowser ) ) {
4004 * Filter an input field through a Unicode de-armoring process if it
4005 * came from an old browser with known broken Unicode editing issues.
4007 * @param WebRequest $request
4008 * @param string $field
4011 protected function safeUnicodeInput( $request, $field ) {
4012 $text = rtrim( $request->getText( $field ) );
4013 return $request->getBool( 'safemode' )
4014 ?
$this->unmakeSafe( $text )
4019 * Filter an output field through a Unicode armoring process if it is
4020 * going to an old browser with known broken Unicode editing issues.
4022 * @param string $text
4025 protected function safeUnicodeOutput( $text ) {
4027 $codedText = $wgContLang->recodeForEdit( $text );
4028 return $this->checkUnicodeCompliantBrowser()
4030 : $this->makeSafe( $codedText );
4034 * A number of web browsers are known to corrupt non-ASCII characters
4035 * in a UTF-8 text editing environment. To protect against this,
4036 * detected browsers will be served an armored version of the text,
4037 * with non-ASCII chars converted to numeric HTML character references.
4039 * Preexisting such character references will have a 0 added to them
4040 * to ensure that round-trips do not alter the original data.
4042 * @param string $invalue
4045 private function makeSafe( $invalue ) {
4046 // Armor existing references for reversibility.
4047 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
4052 $valueLength = strlen( $invalue );
4053 for ( $i = 0; $i < $valueLength; $i++
) {
4054 $bytevalue = ord( $invalue[$i] );
4055 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4056 $result .= chr( $bytevalue );
4058 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4059 $working = $working << 6;
4060 $working +
= ( $bytevalue & 0x3F );
4062 if ( $bytesleft <= 0 ) {
4063 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4065 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4066 $working = $bytevalue & 0x1F;
4068 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4069 $working = $bytevalue & 0x0F;
4071 } else { // 1111 0xxx
4072 $working = $bytevalue & 0x07;
4080 * Reverse the previously applied transliteration of non-ASCII characters
4081 * back to UTF-8. Used to protect data from corruption by broken web browsers
4082 * as listed in $wgBrowserBlackList.
4084 * @param string $invalue
4087 private function unmakeSafe( $invalue ) {
4089 $valueLength = strlen( $invalue );
4090 for ( $i = 0; $i < $valueLength; $i++
) {
4091 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
4095 $hexstring .= $invalue[$i];
4097 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4099 // Do some sanity checks. These aren't needed for reversibility,
4100 // but should help keep the breakage down if the editor
4101 // breaks one of the entities whilst editing.
4102 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
4103 $codepoint = hexdec( $hexstring );
4104 $result .= codepointToUtf8( $codepoint );
4106 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4109 $result .= substr( $invalue, $i, 1 );
4112 // reverse the transform that we made for reversibility reasons.
4113 return strtr( $result, array( "�" => "&#x" ) );