3 * Page edition user interface.
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.
41 * Status: Article successfully updated
43 const AS_SUCCESS_UPDATE
= 200;
46 * Status: Article successfully created
48 const AS_SUCCESS_NEW_ARTICLE
= 201;
51 * Status: Article update aborted by a hook function
53 const AS_HOOK_ERROR
= 210;
56 * Status: A hook function returned an error
58 const AS_HOOK_ERROR_EXPECTED
= 212;
61 * Status: User is blocked from editing this page
63 const AS_BLOCKED_PAGE_FOR_USER
= 215;
66 * Status: Content too big (> $wgMaxArticleSize)
68 const AS_CONTENT_TOO_BIG
= 216;
71 * Status: User cannot edit? (not used)
73 const AS_USER_CANNOT_EDIT
= 217;
76 * Status: this anonymous user is not allowed to edit this page
78 const AS_READ_ONLY_PAGE_ANON
= 218;
81 * Status: this logged in user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_LOGGED
= 219;
86 * Status: wiki is in readonly mode (wfReadOnly() == true)
88 const AS_READ_ONLY_PAGE
= 220;
91 * Status: rate limiter for action 'edit' was tripped
93 const AS_RATE_LIMITED
= 221;
96 * Status: article was deleted while editing and param wpRecreate == false or form
99 const AS_ARTICLE_WAS_DELETED
= 222;
102 * Status: user tried to create this page, but is not allowed to do that
103 * ( Title->userCan('create') == false )
105 const AS_NO_CREATE_PERMISSION
= 223;
108 * Status: user tried to create a blank page
110 const AS_BLANK_ARTICLE
= 224;
113 * Status: (non-resolvable) edit conflict
115 const AS_CONFLICT_DETECTED
= 225;
118 * Status: no edit summary given and the user has forceeditsummary set and the user is not
119 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
121 const AS_SUMMARY_NEEDED
= 226;
124 * Status: user tried to create a new section without content
126 const AS_TEXTBOX_EMPTY
= 228;
129 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
131 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
139 * Status: WikiPage::doEdit() was unsuccessful
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
146 const AS_SPAM_ERROR
= 232;
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
151 const AS_IMAGE_REDIRECT_ANON
= 233;
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
156 const AS_IMAGE_REDIRECT_LOGGED
= 234;
159 * Status: can't parse content
161 const AS_PARSE_ERROR
= 240;
164 * HTML id and name for the beginning of the edit form.
166 const EDITFORM_ID
= 'editform';
169 * Prefix of key for cookie used to pass post-edit state.
170 * The revision id edited is added after this
172 const POST_EDIT_COOKIE_KEY_PREFIX
= 'PostEditRevision';
175 * Duration of PostEdit cookie, in seconds.
176 * The cookie will be removed instantly if the JavaScript runs.
178 * Otherwise, though, we don't want the cookies to accumulate.
179 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible limit of only 20 cookies per domain.
180 * This still applies at least to some 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;
197 private $mContextTitle = null;
198 var $action = 'submit';
199 var $isConflict = false;
200 var $isCssJsSubpage = false;
201 var $isCssSubpage = false;
202 var $isJsSubpage = false;
203 var $isWrongCaseCssJsPage = false;
204 var $isNew = false; // new page or new section
205 var $deletedSinceEdit;
209 var $mTokenOk = false;
210 var $mTokenOkExceptSuffix = false;
211 var $mTriedSave = false;
212 var $incompleteForm = false;
214 var $kblength = false;
215 var $missingComment = false;
216 var $missingSummary = false;
217 var $allowBlankSummary = false;
220 #var $mPreviewTemplates;
228 * Has a summary been preset using GET parameter &summary= ?
231 var $hasPresetSummary = false;
233 var $mBaseRevision = false;
234 var $mShowSummaryField = true;
237 var $save = false, $preview = false, $diff = false;
238 var $minoredit = false, $watchthis = false, $recreate = false;
239 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
240 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
241 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
242 var $contentModel = null, $contentFormat = null;
244 # Placeholders for text injection by hooks (must be HTML)
245 # extensions should take care to _append_ to the present value
246 public $editFormPageTop = ''; // Before even the preview
247 public $editFormTextTop = '';
248 public $editFormTextBeforeContent = '';
249 public $editFormTextAfterWarn = '';
250 public $editFormTextAfterTools = '';
251 public $editFormTextBottom = '';
252 public $editFormTextAfterContent = '';
253 public $previewTextAfterContent = '';
254 public $mPreloadContent = null;
256 /* $didSave should be set to true whenever an article was successfully altered. */
257 public $didSave = false;
258 public $undidRev = 0;
260 public $suppressIntro = false;
263 * Set to true to allow editing of non-text content types.
267 public $allowNonTextContent = false;
270 * @param $article Article
272 public function __construct( Article
$article ) {
273 $this->mArticle
= $article;
274 $this->mTitle
= $article->getTitle();
276 $this->contentModel
= $this->mTitle
->getContentModel();
278 $handler = ContentHandler
::getForModelID( $this->contentModel
);
279 $this->contentFormat
= $handler->getDefaultFormat();
285 public function getArticle() {
286 return $this->mArticle
;
293 public function getTitle() {
294 return $this->mTitle
;
298 * Set the context Title object
300 * @param $title Title object or null
302 public function setContextTitle( $title ) {
303 $this->mContextTitle
= $title;
307 * Get the context title object.
308 * If not set, $wgTitle will be returned. This behavior might change in
309 * the future to return $this->mTitle instead.
311 * @return Title object
313 public function getContextTitle() {
314 if ( is_null( $this->mContextTitle
) ) {
318 return $this->mContextTitle
;
327 * This is the function that gets called for "action=edit". It
328 * sets up various member variables, then passes execution to
329 * another function, usually showEditForm()
331 * The edit form is self-submitting, so that when things like
332 * preview and edit conflicts occur, we get the same form back
333 * with the extra stuff added. Only when the final submission
334 * is made and all is well do we actually save and redirect to
335 * the newly-edited page.
338 global $wgOut, $wgRequest, $wgUser;
339 // Allow extensions to modify/prevent this form or submission
340 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
344 wfProfileIn( __METHOD__
);
345 wfDebug( __METHOD__
. ": enter\n" );
347 // If they used redlink=1 and the page exists, redirect to the main article
348 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
349 $wgOut->redirect( $this->mTitle
->getFullURL() );
350 wfProfileOut( __METHOD__
);
354 $this->importFormData( $wgRequest );
355 $this->firsttime
= false;
358 $this->livePreview();
359 wfProfileOut( __METHOD__
);
363 if ( wfReadOnly() && $this->save
) {
366 $this->preview
= true;
370 $this->formtype
= 'save';
371 } elseif ( $this->preview
) {
372 $this->formtype
= 'preview';
373 } elseif ( $this->diff
) {
374 $this->formtype
= 'diff';
375 } else { # First time through
376 $this->firsttime
= true;
377 if ( $this->previewOnOpen() ) {
378 $this->formtype
= 'preview';
380 $this->formtype
= 'initial';
384 $permErrors = $this->getEditPermissionErrors();
386 wfDebug( __METHOD__
. ": User can't edit\n" );
387 // Auto-block user's IP if the account was "hard" blocked
388 $wgUser->spreadAnyEditBlock();
390 $this->displayPermissionsError( $permErrors );
392 wfProfileOut( __METHOD__
);
396 wfProfileIn( __METHOD__
. "-business-end" );
398 $this->isConflict
= false;
399 // css / js subpages of user pages get a special treatment
400 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
401 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
402 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
403 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
405 # Show applicable editing introductions
406 if ( $this->formtype
== 'initial' ||
$this->firsttime
) {
410 # Attempt submission here. This will check for edit conflicts,
411 # and redundantly check for locked database, blocked IPs, etc.
412 # that edit() already checked just in case someone tries to sneak
413 # in the back door with a hand-edited submission URL.
415 if ( 'save' == $this->formtype
) {
416 if ( !$this->attemptSave() ) {
417 wfProfileOut( __METHOD__
. "-business-end" );
418 wfProfileOut( __METHOD__
);
423 # First time through: get contents, set time for conflict
425 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
426 if ( $this->initialiseForm() === false ) {
427 $this->noSuchSectionPage();
428 wfProfileOut( __METHOD__
. "-business-end" );
429 wfProfileOut( __METHOD__
);
433 if ( !$this->mTitle
->getArticleID() ) {
434 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
436 wfRunHooks( 'EditFormInitialText', array( $this ) );
441 $this->showEditForm();
442 wfProfileOut( __METHOD__
. "-business-end" );
443 wfProfileOut( __METHOD__
);
449 protected function getEditPermissionErrors() {
451 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
452 # Can this title be created?
453 if ( !$this->mTitle
->exists() ) {
454 $permErrors = array_merge( $permErrors,
455 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
457 # Ignore some permissions errors when a user is just previewing/viewing diffs
459 foreach ( $permErrors as $error ) {
460 if ( ( $this->preview ||
$this->diff
) &&
461 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
466 $permErrors = wfArrayDiff2( $permErrors, $remove );
471 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
472 * but with the following differences:
473 * - If redlink=1, the user will be redirected to the page
474 * - If there is content to display or the error occurs while either saving,
475 * previewing or showing the difference, it will be a
476 * "View source for ..." page displaying the source code after the error message.
479 * @param array $permErrors of permissions errors, as returned by
480 * Title::getUserPermissionsErrors().
481 * @throws PermissionsError
483 protected function displayPermissionsError( array $permErrors ) {
484 global $wgRequest, $wgOut;
486 if ( $wgRequest->getBool( 'redlink' ) ) {
487 // The edit page was reached via a red link.
488 // Redirect to the article page and let them click the edit tab if
489 // they really want a permission error.
490 $wgOut->redirect( $this->mTitle
->getFullURL() );
494 $content = $this->getContentObject();
496 # Use the normal message if there's nothing to display
497 if ( $this->firsttime
&& ( !$content ||
$content->isEmpty() ) ) {
498 $action = $this->mTitle
->exists() ?
'edit' :
499 ( $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage' );
500 throw new PermissionsError( $action, $permErrors );
503 $wgOut->setRobotPolicy( 'noindex,nofollow' );
504 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
505 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
506 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
507 $wgOut->addHTML( "<hr />\n" );
509 # If the user made changes, preserve them when showing the markup
510 # (This happens when a user is blocked during edit, for instance)
511 if ( !$this->firsttime
) {
512 $text = $this->textbox1
;
513 $wgOut->addWikiMsg( 'viewyourtext' );
515 $text = $this->toEditText( $content );
516 $wgOut->addWikiMsg( 'viewsourcetext' );
519 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
521 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
522 Linker
::formatTemplates( $this->getTemplates() ) ) );
524 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
526 if ( $this->mTitle
->exists() ) {
527 $wgOut->returnToMain( null, $this->mTitle
);
532 * Show a read-only error
533 * Parameters are the same as OutputPage:readOnlyPage()
534 * Redirect to the article page if redlink=1
535 * @deprecated in 1.19; use displayPermissionsError() instead
537 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
538 wfDeprecated( __METHOD__
, '1.19' );
540 global $wgRequest, $wgOut;
541 if ( $wgRequest->getBool( 'redlink' ) ) {
542 // The edit page was reached via a red link.
543 // Redirect to the article page and let them click the edit tab if
544 // they really want a permission error.
545 $wgOut->redirect( $this->mTitle
->getFullURL() );
547 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
552 * Should we show a preview when the edit form is first shown?
556 protected function previewOnOpen() {
557 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
558 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
559 // Explicit override from request
561 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
562 // Explicit override from request
564 } elseif ( $this->section
== 'new' ) {
565 // Nothing *to* preview for new sections
567 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
568 // Standard preference behavior
570 } elseif ( !$this->mTitle
->exists() &&
571 isset( $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] ) &&
572 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
574 // Categories are special
582 * Checks whether the user entered a skin name in uppercase,
583 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
587 protected function isWrongCaseCssJsPage() {
588 if ( $this->mTitle
->isCssJsSubpage() ) {
589 $name = $this->mTitle
->getSkinFromCssJsSubpage();
590 $skins = array_merge(
591 array_keys( Skin
::getSkinNames() ),
594 return !in_array( $name, $skins )
595 && in_array( strtolower( $name ), $skins );
602 * Returns whether section editing is supported for the current page.
603 * Subclasses may override this to replace the default behavior, which is
604 * to check ContentHandler::supportsSections.
606 * @return bool true if this edit page supports sections, false otherwise.
608 protected function isSectionEditSupported() {
609 $contentHandler = ContentHandler
::getForTitle( $this->mTitle
);
610 return $contentHandler->supportsSections();
614 * This function collects the form data and uses it to populate various member variables.
615 * @param $request WebRequest
617 function importFormData( &$request ) {
618 global $wgContLang, $wgUser;
620 wfProfileIn( __METHOD__
);
622 # Section edit can come from either the form or a link
623 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
625 if ( $this->section
!== null && $this->section
!== '' && !$this->isSectionEditSupported() ) {
626 wfProfileOut( __METHOD__
);
627 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
630 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
632 if ( $request->wasPosted() ) {
633 # These fields need to be checked for encoding.
634 # Also remove trailing whitespace, but don't remove _initial_
635 # whitespace from the text boxes. This may be significant formatting.
636 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
637 if ( !$request->getCheck( 'wpTextbox2' ) ) {
638 // Skip this if wpTextbox2 has input, it indicates that we came
639 // from a conflict page with raw page text, not a custom form
640 // modified by subclasses
641 wfProfileIn( get_class( $this ) . "::importContentFormData" );
642 $textbox1 = $this->importContentFormData( $request );
643 if ( $textbox1 !== null ) {
644 $this->textbox1
= $textbox1;
647 wfProfileOut( get_class( $this ) . "::importContentFormData" );
650 # Truncate for whole multibyte characters
651 $this->summary
= $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
653 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
654 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
656 $this->summary
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
658 # Treat sectiontitle the same way as summary.
659 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
660 # currently doing double duty as both edit summary and section title. Right now this
661 # is just to allow API edits to work around this limitation, but this should be
662 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
663 $this->sectiontitle
= $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
664 $this->sectiontitle
= preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle
);
666 $this->edittime
= $request->getVal( 'wpEdittime' );
667 $this->starttime
= $request->getVal( 'wpStarttime' );
669 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
671 if ( $this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null ) {
672 // wpTextbox1 field is missing, possibly due to being "too big"
673 // according to some filter rules such as Suhosin's setting for
674 // suhosin.request.max_value_length (d'oh)
675 $this->incompleteForm
= true;
677 // edittime should be one of our last fields; if it's missing,
678 // the submission probably broke somewhere in the middle.
679 $this->incompleteForm
= is_null( $this->edittime
);
681 if ( $this->incompleteForm
) {
682 # If the form is incomplete, force to preview.
683 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
684 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
685 $this->preview
= true;
687 /* Fallback for live preview */
688 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
689 $this->diff
= $request->getCheck( 'wpDiff' );
691 // Remember whether a save was requested, so we can indicate
692 // if we forced preview due to session failure.
693 $this->mTriedSave
= !$this->preview
;
695 if ( $this->tokenOk( $request ) ) {
696 # Some browsers will not report any submit button
697 # if the user hits enter in the comment box.
698 # The unmarked state will be assumed to be a save,
699 # if the form seems otherwise complete.
700 wfDebug( __METHOD__
. ": Passed token check.\n" );
701 } elseif ( $this->diff
) {
702 # Failed token check, but only requested "Show Changes".
703 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
705 # Page might be a hack attempt posted from
706 # an external site. Preview instead of saving.
707 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
708 $this->preview
= true;
711 $this->save
= !$this->preview
&& !$this->diff
;
712 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
713 $this->edittime
= null;
716 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
717 $this->starttime
= null;
720 $this->recreate
= $request->getCheck( 'wpRecreate' );
722 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
723 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
725 # Don't force edit summaries when a user is editing their own user or talk page
726 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
727 $this->mTitle
->getText() == $wgUser->getName() )
729 $this->allowBlankSummary
= true;
731 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary' );
734 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
736 # Not a posted form? Start with nothing.
737 wfDebug( __METHOD__
. ": Not a posted form.\n" );
738 $this->textbox1
= '';
740 $this->sectiontitle
= '';
741 $this->edittime
= '';
742 $this->starttime
= wfTimestampNow();
744 $this->preview
= false;
747 $this->minoredit
= false;
748 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overridden by request parameters
749 $this->recreate
= false;
751 // When creating a new section, we can preload a section title by passing it as the
752 // preloadtitle parameter in the URL (Bug 13100)
753 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
754 $this->sectiontitle
= $request->getVal( 'preloadtitle' );
755 // Once wpSummary isn't being use for setting section titles, we should delete this.
756 $this->summary
= $request->getVal( 'preloadtitle' );
758 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
759 $this->summary
= $request->getText( 'summary' );
760 if ( $this->summary
!== '' ) {
761 $this->hasPresetSummary
= true;
765 if ( $request->getVal( 'minor' ) ) {
766 $this->minoredit
= true;
770 $this->oldid
= $request->getInt( 'oldid' );
772 $this->bot
= $request->getBool( 'bot', true );
773 $this->nosummary
= $request->getBool( 'nosummary' );
775 $content_handler = ContentHandler
::getForTitle( $this->mTitle
);
776 $this->contentModel
= $request->getText( 'model', $content_handler->getModelID() ); #may be overridden by revision
777 $this->contentFormat
= $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
779 #TODO: check if the desired model is allowed in this namespace, and if a transition from the page's current model to the new model is allowed
780 #TODO: check if the desired content model supports the given content format!
782 $this->live
= $request->getCheck( 'live' );
783 $this->editintro
= $request->getText( 'editintro',
784 // Custom edit intro for new sections
785 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
787 // Allow extensions to modify form data
788 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
790 wfProfileOut( __METHOD__
);
794 * Subpage overridable method for extracting the page content data from the
795 * posted form to be placed in $this->textbox1, if using customized input
796 * this method should be overridden and return the page text that will be used
797 * for saving, preview parsing and so on...
799 * @param $request WebRequest
801 protected function importContentFormData( &$request ) {
802 return; // Don't do anything, EditPage already extracted wpTextbox1
806 * Initialise form fields in the object
807 * Called on the first invocation, e.g. when a user clicks an edit link
808 * @return bool -- if the requested section is valid
810 function initialiseForm() {
812 $this->edittime
= $this->mArticle
->getTimestamp();
814 $content = $this->getContentObject( false ); #TODO: track content object?!
815 if ( $content === false ) {
818 $this->textbox1
= $this->toEditText( $content );
820 // activate checkboxes if user wants them to be always active
821 # Sort out the "watch" checkbox
822 if ( $wgUser->getOption( 'watchdefault' ) ) {
824 $this->watchthis
= true;
825 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
827 $this->watchthis
= true;
828 } elseif ( $wgUser->isWatched( $this->mTitle
) ) {
830 $this->watchthis
= true;
832 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
833 $this->minoredit
= true;
835 if ( $this->textbox1
=== false ) {
843 * Fetch initial editing page content.
845 * @param $def_text string|bool
846 * @return mixed string on success, $def_text for invalid sections
848 * @deprecated since 1.21, get WikiPage::getContent() instead.
850 function getContent( $def_text = false ) {
851 ContentHandler
::deprecated( __METHOD__
, '1.21' );
853 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
854 $def_content = $this->toEditContent( $def_text );
856 $def_content = false;
859 $content = $this->getContentObject( $def_content );
861 // Note: EditPage should only be used with text based content anyway.
862 return $this->toEditText( $content );
866 * @param Content|null $def_content The default value to return
868 * @return mixed Content on success, $def_content for invalid sections
872 protected function getContentObject( $def_content = null ) {
873 global $wgOut, $wgRequest;
875 wfProfileIn( __METHOD__
);
879 // For message page not locally set, use the i18n message.
880 // For other non-existent articles, use preload text if any.
881 if ( !$this->mTitle
->exists() ||
$this->section
== 'new' ) {
882 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& $this->section
!= 'new' ) {
883 # If this is a system message, get the default text.
884 $msg = $this->mTitle
->getDefaultMessageText();
886 $content = $this->toEditContent( $msg );
888 if ( $content === false ) {
889 # If requested, preload some text.
890 $preload = $wgRequest->getVal( 'preload',
891 // Custom preload text for new sections
892 $this->section
=== 'new' ?
'MediaWiki:addsection-preload' : '' );
894 $content = $this->getPreloadedContent( $preload );
896 // For existing pages, get text based on "undo" or section parameters.
898 if ( $this->section
!= '' ) {
899 // Get section edit text (returns $def_text for invalid sections)
900 $orig = $this->getOriginalContent();
901 $content = $orig ?
$orig->getSection( $this->section
) : null;
904 $content = $def_content;
907 $undoafter = $wgRequest->getInt( 'undoafter' );
908 $undo = $wgRequest->getInt( 'undo' );
910 if ( $undo > 0 && $undoafter > 0 ) {
911 if ( $undo < $undoafter ) {
912 # If they got undoafter and undo round the wrong way, switch them
913 list( $undo, $undoafter ) = array( $undoafter, $undo );
916 $undorev = Revision
::newFromId( $undo );
917 $oldrev = Revision
::newFromId( $undoafter );
919 # Sanity check, make sure it's the right page,
920 # the revisions exist and they were not deleted.
921 # Otherwise, $content will be left as-is.
922 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
923 $undorev->getPage() == $oldrev->getPage() &&
924 $undorev->getPage() == $this->mTitle
->getArticleID() &&
925 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
926 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
928 $content = $this->mArticle
->getUndoContent( $undorev, $oldrev );
930 if ( $content === false ) {
931 # Warn the user that something went wrong
932 $undoMsg = 'failure';
934 # Inform the user of our success and set an automatic edit summary
935 $undoMsg = 'success';
937 # If we just undid one rev, use an autosummary
938 $firstrev = $oldrev->getNext();
939 if ( $firstrev && $firstrev->getId() == $undo ) {
940 $userText = $undorev->getUserText();
941 if ( $userText === '' ) {
942 $undoSummary = wfMessage(
943 'undo-summary-username-hidden',
945 )->inContentLanguage()->text();
947 $undoSummary = wfMessage(
951 )->inContentLanguage()->text();
953 if ( $this->summary
=== '' ) {
954 $this->summary
= $undoSummary;
956 $this->summary
= $undoSummary . wfMessage( 'colon-separator' )
957 ->inContentLanguage()->text() . $this->summary
;
959 $this->undidRev
= $undo;
961 $this->formtype
= 'diff';
964 // Failed basic sanity checks.
965 // Older revisions may have been removed since the link
966 // was created, or we may simply have got bogus input.
970 // Give grep a chance to find the usages: undo-success, undo-failure, undo-norev
971 $class = ( $undoMsg == 'success' ?
'' : 'error ' ) . "mw-undo-{$undoMsg}";
972 $this->editFormPageTop
.= $wgOut->parse( "<div class=\"{$class}\">" .
973 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
976 if ( $content === false ) {
977 $content = $this->getOriginalContent();
982 wfProfileOut( __METHOD__
);
987 * Get the content of the wanted revision, without section extraction.
989 * The result of this function can be used to compare user's input with
990 * section replaced in its context (using WikiPage::replaceSection())
991 * to the original text of the edit.
993 * This differs from Article::getContent() that when a missing revision is
994 * encountered the result will be null and not the
995 * 'missing-revision' message.
998 * @return Content|null
1000 private function getOriginalContent() {
1001 if ( $this->section
== 'new' ) {
1002 return $this->getCurrentContent();
1004 $revision = $this->mArticle
->getRevisionFetched();
1005 if ( $revision === null ) {
1006 if ( !$this->contentModel
) {
1007 $this->contentModel
= $this->getTitle()->getContentModel();
1009 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1011 return $handler->makeEmptyContent();
1013 $content = $revision->getContent();
1018 * Get the current content of the page. This is basically similar to
1019 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1020 * content object is returned instead of null.
1025 protected function getCurrentContent() {
1026 $rev = $this->mArticle
->getRevision();
1027 $content = $rev ?
$rev->getContent( Revision
::RAW
) : null;
1029 if ( $content === false ||
$content === null ) {
1030 if ( !$this->contentModel
) {
1031 $this->contentModel
= $this->getTitle()->getContentModel();
1033 $handler = ContentHandler
::getForModelID( $this->contentModel
);
1035 return $handler->makeEmptyContent();
1037 # nasty side-effect, but needed for consistency
1038 $this->contentModel
= $rev->getContentModel();
1039 $this->contentFormat
= $rev->getContentFormat();
1046 * Use this method before edit() to preload some text into the edit box
1048 * @param $text string
1049 * @deprecated since 1.21, use setPreloadedContent() instead.
1051 public function setPreloadedText( $text ) {
1052 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1054 $content = $this->toEditContent( $text );
1056 $this->setPreloadedContent( $content );
1060 * Use this method before edit() to preload some content into the edit box
1062 * @param $content Content
1066 public function setPreloadedContent( Content
$content ) {
1067 $this->mPreloadContent
= $content;
1071 * Get the contents to be preloaded into the box, either set by
1072 * an earlier setPreloadText() or by loading the given page.
1074 * @param string $preload representing the title to preload from.
1078 * @deprecated since 1.21, use getPreloadedContent() instead
1080 protected function getPreloadedText( $preload ) {
1081 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1083 $content = $this->getPreloadedContent( $preload );
1084 $text = $this->toEditText( $content );
1090 * Get the contents to be preloaded into the box, either set by
1091 * an earlier setPreloadText() or by loading the given page.
1093 * @param string $preload representing the title to preload from.
1099 protected function getPreloadedContent( $preload ) {
1102 if ( !empty( $this->mPreloadContent
) ) {
1103 return $this->mPreloadContent
;
1106 $handler = ContentHandler
::getForTitle( $this->getTitle() );
1108 if ( $preload === '' ) {
1109 return $handler->makeEmptyContent();
1112 $title = Title
::newFromText( $preload );
1113 # Check for existence to avoid getting MediaWiki:Noarticletext
1114 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1115 //TODO: somehow show a warning to the user!
1116 return $handler->makeEmptyContent();
1119 $page = WikiPage
::factory( $title );
1120 if ( $page->isRedirect() ) {
1121 $title = $page->getRedirectTarget();
1123 if ( $title === null ||
!$title->exists() ||
!$title->userCan( 'read', $wgUser ) ) {
1124 //TODO: somehow show a warning to the user!
1125 return $handler->makeEmptyContent();
1127 $page = WikiPage
::factory( $title );
1130 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1131 $content = $page->getContent( Revision
::RAW
);
1134 //TODO: somehow show a warning to the user!
1135 return $handler->makeEmptyContent();
1138 if ( $content->getModel() !== $handler->getModelID() ) {
1139 $converted = $content->convert( $handler->getModelID() );
1141 if ( !$converted ) {
1142 //TODO: somehow show a warning to the user!
1143 wfDebug( "Attempt to preload incompatible content: "
1144 . "can't convert " . $content->getModel()
1145 . " to " . $handler->getModelID() );
1147 return $handler->makeEmptyContent();
1150 $content = $converted;
1153 return $content->preloadTransform( $title, $parserOptions );
1157 * Make sure the form isn't faking a user's credentials.
1159 * @param $request WebRequest
1163 function tokenOk( &$request ) {
1165 $token = $request->getVal( 'wpEditToken' );
1166 $this->mTokenOk
= $wgUser->matchEditToken( $token );
1167 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
1168 return $this->mTokenOk
;
1172 * Sets post-edit cookie indicating the user just saved a particular revision.
1174 * This uses a temporary cookie for each revision ID so separate saves will never
1175 * interfere with each other.
1177 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1178 * the redirect. It must be clearable by JavaScript code, so it must not be
1179 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1182 * We use a path of '/' since wgCookiePath is not exposed to JS
1184 * If the variable were set on the server, it would be cached, which is unwanted
1185 * since the post-edit state should only apply to the load right after the save.
1187 protected function setPostEditCookie() {
1188 $revisionId = $this->mArticle
->getLatest();
1189 $postEditKey = self
::POST_EDIT_COOKIE_KEY_PREFIX
. $revisionId;
1191 $response = RequestContext
::getMain()->getRequest()->response();
1192 $response->setcookie( $postEditKey, '1', time() + self
::POST_EDIT_COOKIE_DURATION
, array(
1194 'httpOnly' => false,
1199 * Attempt submission
1200 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1201 * @return bool false if output is done, true if the rest of the form should be displayed
1203 function attemptSave() {
1204 global $wgUser, $wgOut;
1206 $resultDetails = false;
1207 # Allow bots to exempt some edits from bot flagging
1208 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
1209 $status = $this->internalAttemptSave( $resultDetails, $bot );
1210 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1211 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
1212 $this->didSave
= true;
1213 if ( !$resultDetails['nullEdit'] ) {
1214 $this->setPostEditCookie();
1218 switch ( $status->value
) {
1219 case self
::AS_HOOK_ERROR_EXPECTED
:
1220 case self
::AS_CONTENT_TOO_BIG
:
1221 case self
::AS_ARTICLE_WAS_DELETED
:
1222 case self
::AS_CONFLICT_DETECTED
:
1223 case self
::AS_SUMMARY_NEEDED
:
1224 case self
::AS_TEXTBOX_EMPTY
:
1225 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
1229 case self
::AS_HOOK_ERROR
:
1232 case self
::AS_PARSE_ERROR
:
1233 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1236 case self
::AS_SUCCESS_NEW_ARTICLE
:
1237 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
1238 $anchor = isset( $resultDetails['sectionanchor'] ) ?
$resultDetails['sectionanchor'] : '';
1239 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $anchor );
1242 case self
::AS_SUCCESS_UPDATE
:
1244 $sectionanchor = $resultDetails['sectionanchor'];
1246 // Give extensions a chance to modify URL query on update
1247 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
1249 if ( $resultDetails['redirect'] ) {
1250 if ( $extraQuery == '' ) {
1251 $extraQuery = 'redirect=no';
1253 $extraQuery = 'redirect=no&' . $extraQuery;
1256 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
1259 case self
::AS_BLANK_ARTICLE
:
1260 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1263 case self
::AS_SPAM_ERROR
:
1264 $this->spamPageWithContent( $resultDetails['spam'] );
1267 case self
::AS_BLOCKED_PAGE_FOR_USER
:
1268 throw new UserBlockedError( $wgUser->getBlock() );
1270 case self
::AS_IMAGE_REDIRECT_ANON
:
1271 case self
::AS_IMAGE_REDIRECT_LOGGED
:
1272 throw new PermissionsError( 'upload' );
1274 case self
::AS_READ_ONLY_PAGE_ANON
:
1275 case self
::AS_READ_ONLY_PAGE_LOGGED
:
1276 throw new PermissionsError( 'edit' );
1278 case self
::AS_READ_ONLY_PAGE
:
1279 throw new ReadOnlyError
;
1281 case self
::AS_RATE_LIMITED
:
1282 throw new ThrottledError();
1284 case self
::AS_NO_CREATE_PERMISSION
:
1285 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
1286 throw new PermissionsError( $permission );
1289 // We don't recognize $status->value. The only way that can happen
1290 // is if an extension hook aborted from inside ArticleSave.
1291 // Render the status object into $this->hookError
1292 // FIXME this sucks, we should just use the Status object throughout
1293 $this->hookError
= '<div class="error">' . $status->getWikitext() .
1300 * Run hooks that can filter edits just before they get saved.
1302 * @param Content $content the Content to filter.
1303 * @param Status $status for reporting the outcome to the caller
1304 * @param User $user the user performing the edit
1308 protected function runPostMergeFilters( Content
$content, Status
$status, User
$user ) {
1309 // Run old style post-section-merge edit filter
1310 if ( !ContentHandler
::runLegacyHooks( 'EditFilterMerged',
1311 array( $this, $content, &$this->hookError
, $this->summary
) ) ) {
1313 # Error messages etc. could be handled within the hook...
1314 $status->fatal( 'hookaborted' );
1315 $status->value
= self
::AS_HOOK_ERROR
;
1317 } elseif ( $this->hookError
!= '' ) {
1318 # ...or the hook could be expecting us to produce an error
1319 $status->fatal( 'hookaborted' );
1320 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1324 // Run new style post-section-merge edit filter
1325 if ( !wfRunHooks( 'EditFilterMergedContent',
1326 array( $this->mArticle
->getContext(), $content, $status, $this->summary
,
1327 $user, $this->minoredit
) ) ) {
1329 # Error messages etc. could be handled within the hook...
1330 // XXX: $status->value may already be something informative...
1331 $this->hookError
= $status->getWikiText();
1332 $status->fatal( 'hookaborted' );
1333 $status->value
= self
::AS_HOOK_ERROR
;
1335 } elseif ( !$status->isOK() ) {
1336 # ...or the hook could be expecting us to produce an error
1337 // FIXME this sucks, we should just use the Status object throughout
1338 $this->hookError
= $status->getWikiText();
1339 $status->fatal( 'hookaborted' );
1340 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1348 * Attempt submission (no UI)
1350 * @param array $result array to add statuses to, currently with the possible keys:
1351 * spam - string - Spam string from content if any spam is detected by matchSpamRegex
1352 * sectionanchor - string - Section anchor for a section save
1353 * nullEdit - boolean - Set if doEditContent is OK. True if null edit, false otherwise.
1354 * redirect - boolean - Set if doEditContent is OK. True if resulting revision is a redirect
1355 * @param bool $bot True if edit is being made under the bot right.
1357 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1359 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1360 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1361 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1363 function internalAttemptSave( &$result, $bot = false ) {
1364 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1366 $status = Status
::newGood();
1368 wfProfileIn( __METHOD__
);
1369 wfProfileIn( __METHOD__
. '-checks' );
1371 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1372 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1373 $status->fatal( 'hookaborted' );
1374 $status->value
= self
::AS_HOOK_ERROR
;
1375 wfProfileOut( __METHOD__
. '-checks' );
1376 wfProfileOut( __METHOD__
);
1381 # Construct Content object
1382 $textbox_content = $this->toEditContent( $this->textbox1
);
1383 } catch ( MWContentSerializationException
$ex ) {
1384 $status->fatal( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
1385 $status->value
= self
::AS_PARSE_ERROR
;
1386 wfProfileOut( __METHOD__
. '-checks' );
1387 wfProfileOut( __METHOD__
);
1391 # Check image redirect
1392 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
1393 $textbox_content->isRedirect() &&
1394 !$wgUser->isAllowed( 'upload' ) ) {
1395 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
1396 $status->setResult( false, $code );
1398 wfProfileOut( __METHOD__
. '-checks' );
1399 wfProfileOut( __METHOD__
);
1405 $match = self
::matchSummarySpamRegex( $this->summary
);
1406 if ( $match === false && $this->section
== 'new' ) {
1407 if ( $this->sectiontitle
!== '' ) {
1408 $match = self
::matchSpamRegex( $this->sectiontitle
);
1410 $match = self
::matchSpamRegex( $this->summary
);
1413 if ( $match === false ) {
1414 $match = self
::matchSpamRegex( $this->textbox1
);
1416 if ( $match !== false ) {
1417 $result['spam'] = $match;
1418 $ip = $wgRequest->getIP();
1419 $pdbk = $this->mTitle
->getPrefixedDBkey();
1420 $match = str_replace( "\n", '', $match );
1421 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1422 $status->fatal( 'spamprotectionmatch', $match );
1423 $status->value
= self
::AS_SPAM_ERROR
;
1424 wfProfileOut( __METHOD__
. '-checks' );
1425 wfProfileOut( __METHOD__
);
1428 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
1429 # Error messages etc. could be handled within the hook...
1430 $status->fatal( 'hookaborted' );
1431 $status->value
= self
::AS_HOOK_ERROR
;
1432 wfProfileOut( __METHOD__
. '-checks' );
1433 wfProfileOut( __METHOD__
);
1435 } elseif ( $this->hookError
!= '' ) {
1436 # ...or the hook could be expecting us to produce an error
1437 $status->fatal( 'hookaborted' );
1438 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1439 wfProfileOut( __METHOD__
. '-checks' );
1440 wfProfileOut( __METHOD__
);
1444 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
1445 // Auto-block user's IP if the account was "hard" blocked
1446 $wgUser->spreadAnyEditBlock();
1447 # Check block state against master, thus 'false'.
1448 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
1449 wfProfileOut( __METHOD__
. '-checks' );
1450 wfProfileOut( __METHOD__
);
1454 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1455 if ( $this->kblength
> $wgMaxArticleSize ) {
1456 // Error will be displayed by showEditForm()
1457 $this->tooBig
= true;
1458 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
1459 wfProfileOut( __METHOD__
. '-checks' );
1460 wfProfileOut( __METHOD__
);
1464 if ( !$wgUser->isAllowed( 'edit' ) ) {
1465 if ( $wgUser->isAnon() ) {
1466 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
1467 wfProfileOut( __METHOD__
. '-checks' );
1468 wfProfileOut( __METHOD__
);
1471 $status->fatal( 'readonlytext' );
1472 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
1473 wfProfileOut( __METHOD__
. '-checks' );
1474 wfProfileOut( __METHOD__
);
1479 if ( wfReadOnly() ) {
1480 $status->fatal( 'readonlytext' );
1481 $status->value
= self
::AS_READ_ONLY_PAGE
;
1482 wfProfileOut( __METHOD__
. '-checks' );
1483 wfProfileOut( __METHOD__
);
1486 if ( $wgUser->pingLimiter() ) {
1487 $status->fatal( 'actionthrottledtext' );
1488 $status->value
= self
::AS_RATE_LIMITED
;
1489 wfProfileOut( __METHOD__
. '-checks' );
1490 wfProfileOut( __METHOD__
);
1494 # If the article has been deleted while editing, don't save it without
1496 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1497 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1498 wfProfileOut( __METHOD__
. '-checks' );
1499 wfProfileOut( __METHOD__
);
1503 wfProfileOut( __METHOD__
. '-checks' );
1505 # Load the page data from the master. If anything changes in the meantime,
1506 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1507 $this->mArticle
->loadPageData( 'fromdbmaster' );
1508 $new = !$this->mArticle
->exists();
1511 // Late check for create permission, just in case *PARANOIA*
1512 if ( !$this->mTitle
->userCan( 'create', $wgUser ) ) {
1513 $status->fatal( 'nocreatetext' );
1514 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1515 wfDebug( __METHOD__
. ": no create permission\n" );
1516 wfProfileOut( __METHOD__
);
1520 // Don't save a new page if it's blank or if it's a MediaWiki:
1521 // message with content equivalent to default (allow empty pages
1522 // in this case to disable messages, see bug 50124)
1523 $defaultMessageText = $this->mTitle
->getDefaultMessageText();
1524 if( $this->mTitle
->getNamespace() === NS_MEDIAWIKI
&& $defaultMessageText !== false ) {
1525 $defaultText = $defaultMessageText;
1530 if ( $this->textbox1
=== $defaultText ) {
1531 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1532 wfProfileOut( __METHOD__
);
1536 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1537 wfProfileOut( __METHOD__
);
1541 $content = $textbox_content;
1543 $result['sectionanchor'] = '';
1544 if ( $this->section
== 'new' ) {
1545 if ( $this->sectiontitle
!== '' ) {
1546 // Insert the section title above the content.
1547 $content = $content->addSectionHeader( $this->sectiontitle
);
1549 // Jump to the new section
1550 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1552 // If no edit summary was specified, create one automatically from the section
1553 // title and have it link to the new section. Otherwise, respect the summary as
1555 if ( $this->summary
=== '' ) {
1556 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1557 $this->summary
= wfMessage( 'newsectionsummary' )
1558 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1560 } elseif ( $this->summary
!== '' ) {
1561 // Insert the section title above the content.
1562 $content = $content->addSectionHeader( $this->summary
);
1564 // Jump to the new section
1565 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1567 // Create a link to the new section from the edit summary.
1568 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1569 $this->summary
= wfMessage( 'newsectionsummary' )
1570 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1574 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1578 # Article exists. Check for edit conflict.
1580 $this->mArticle
->clear(); # Force reload of dates, etc.
1581 $timestamp = $this->mArticle
->getTimestamp();
1583 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1585 if ( $timestamp != $this->edittime
) {
1586 $this->isConflict
= true;
1587 if ( $this->section
== 'new' ) {
1588 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1589 $this->mArticle
->getComment() == $this->summary
) {
1590 // Probably a duplicate submission of a new comment.
1591 // This can happen when squid resends a request after
1592 // a timeout but the first one actually went through.
1593 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1595 // New comment; suppress conflict.
1596 $this->isConflict
= false;
1597 wfDebug( __METHOD__
. ": conflict suppressed; new section\n" );
1599 } elseif ( $this->section
== '' && Revision
::userWasLastToEdit( DB_MASTER
, $this->mTitle
->getArticleID(),
1600 $wgUser->getId(), $this->edittime
) ) {
1601 # Suppress edit conflict with self, except for section edits where merging is required.
1602 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1603 $this->isConflict
= false;
1607 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1608 // backwards compatibility with old forms/bots).
1609 if ( $this->sectiontitle
!== '' ) {
1610 $sectionTitle = $this->sectiontitle
;
1612 $sectionTitle = $this->summary
;
1617 if ( $this->isConflict
) {
1618 wfDebug( __METHOD__
. ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1619 . " (article time '{$timestamp}')\n" );
1621 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle, $this->edittime
);
1623 wfDebug( __METHOD__
. ": getting section '{$this->section}'\n" );
1624 $content = $this->mArticle
->replaceSectionContent( $this->section
, $textbox_content, $sectionTitle );
1627 if ( is_null( $content ) ) {
1628 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1629 $this->isConflict
= true;
1630 $content = $textbox_content; // do not try to merge here!
1631 } elseif ( $this->isConflict
) {
1633 if ( $this->mergeChangesIntoContent( $content ) ) {
1634 // Successful merge! Maybe we should tell the user the good news?
1635 $this->isConflict
= false;
1636 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1638 $this->section
= '';
1639 $this->textbox1
= ContentHandler
::getContentText( $content );
1640 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1644 if ( $this->isConflict
) {
1645 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1646 wfProfileOut( __METHOD__
);
1650 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1651 wfProfileOut( __METHOD__
);
1655 if ( $this->section
== 'new' ) {
1656 // Handle the user preference to force summaries here
1657 if ( !$this->allowBlankSummary
&& trim( $this->summary
) == '' ) {
1658 $this->missingSummary
= true;
1659 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1660 $status->value
= self
::AS_SUMMARY_NEEDED
;
1661 wfProfileOut( __METHOD__
);
1665 // Do not allow the user to post an empty comment
1666 if ( $this->textbox1
== '' ) {
1667 $this->missingComment
= true;
1668 $status->fatal( 'missingcommenttext' );
1669 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1670 wfProfileOut( __METHOD__
);
1673 } elseif ( !$this->allowBlankSummary
1674 && !$content->equals( $this->getOriginalContent() )
1675 && !$content->isRedirect()
1676 && md5( $this->summary
) == $this->autoSumm
1678 $this->missingSummary
= true;
1679 $status->fatal( 'missingsummary' );
1680 $status->value
= self
::AS_SUMMARY_NEEDED
;
1681 wfProfileOut( __METHOD__
);
1686 wfProfileIn( __METHOD__
. '-sectionanchor' );
1687 $sectionanchor = '';
1688 if ( $this->section
== 'new' ) {
1689 if ( $this->sectiontitle
!== '' ) {
1690 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle
);
1691 // If no edit summary was specified, create one automatically from the section
1692 // title and have it link to the new section. Otherwise, respect the summary as
1694 if ( $this->summary
=== '' ) {
1695 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle
);
1696 $this->summary
= wfMessage( 'newsectionsummary' )
1697 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1699 } elseif ( $this->summary
!== '' ) {
1700 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1701 # This is a new section, so create a link to the new section
1702 # in the revision summary.
1703 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1704 $this->summary
= wfMessage( 'newsectionsummary' )
1705 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1707 } elseif ( $this->section
!= '' ) {
1708 # Try to get a section anchor from the section source, redirect to edited section if header found
1709 # XXX: might be better to integrate this into Article::replaceSection
1710 # for duplicate heading checking and maybe parsing
1711 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1712 # we can't deal with anchors, includes, html etc in the header for now,
1713 # headline would need to be parsed to improve this
1714 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1715 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1718 $result['sectionanchor'] = $sectionanchor;
1719 wfProfileOut( __METHOD__
. '-sectionanchor' );
1721 // Save errors may fall down to the edit form, but we've now
1722 // merged the section into full text. Clear the section field
1723 // so that later submission of conflict forms won't try to
1724 // replace that into a duplicated mess.
1725 $this->textbox1
= $this->toEditText( $content );
1726 $this->section
= '';
1728 $status->value
= self
::AS_SUCCESS_UPDATE
;
1731 // Check for length errors again now that the section is merged in
1732 $this->kblength
= (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1733 if ( $this->kblength
> $wgMaxArticleSize ) {
1734 $this->tooBig
= true;
1735 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1736 wfProfileOut( __METHOD__
);
1740 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1741 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1742 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1743 ( $bot ? EDIT_FORCE_BOT
: 0 );
1745 $doEditStatus = $this->mArticle
->doEditContent( $content, $this->summary
, $flags,
1746 false, null, $this->contentFormat
);
1748 if ( !$doEditStatus->isOK() ) {
1749 // Failure from doEdit()
1750 // Show the edit conflict page for certain recognized errors from doEdit(),
1751 // but don't show it for errors from extension hooks
1752 $errors = $doEditStatus->getErrorsArray();
1753 if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
1754 'edit-already-exists' ) ) )
1756 $this->isConflict
= true;
1757 // Destroys data doEdit() put in $status->value but who cares
1758 $doEditStatus->value
= self
::AS_END
;
1760 wfProfileOut( __METHOD__
);
1761 return $doEditStatus;
1764 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1765 $result['redirect'] = $content->isRedirect();
1766 $this->updateWatchlist();
1767 wfProfileOut( __METHOD__
);
1772 * Register the change of watch status
1774 protected function updateWatchlist() {
1777 if ( $wgUser->isLoggedIn()
1778 && $this->watchthis
!= $wgUser->isWatched( $this->mTitle
, WatchedItem
::IGNORE_USER_RIGHTS
)
1780 $fname = __METHOD__
;
1781 $title = $this->mTitle
;
1782 $watch = $this->watchthis
;
1784 // Do this in its own transaction to reduce contention...
1785 $dbw = wfGetDB( DB_MASTER
);
1786 $dbw->onTransactionIdle( function() use ( $dbw, $title, $watch, $wgUser, $fname ) {
1787 $dbw->begin( $fname );
1788 WatchAction
::doWatchOrUnwatch( $watch, $title, $wgUser );
1789 $dbw->commit( $fname );
1795 * Attempts to merge text content with base and current revisions
1797 * @param $editText string
1800 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1802 function mergeChangesInto( &$editText ) {
1803 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1805 $editContent = $this->toEditContent( $editText );
1807 $ok = $this->mergeChangesIntoContent( $editContent );
1810 $editText = $this->toEditText( $editContent );
1817 * Attempts to do 3-way merge of edit content with a base revision
1818 * and current content, in case of edit conflict, in whichever way appropriate
1819 * for the content type.
1823 * @param $editContent
1827 private function mergeChangesIntoContent( &$editContent ) {
1828 wfProfileIn( __METHOD__
);
1830 $db = wfGetDB( DB_MASTER
);
1832 // This is the revision the editor started from
1833 $baseRevision = $this->getBaseRevision();
1834 $baseContent = $baseRevision ?
$baseRevision->getContent() : null;
1836 if ( is_null( $baseContent ) ) {
1837 wfProfileOut( __METHOD__
);
1841 // The current state, we want to merge updates into it
1842 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1843 $currentContent = $currentRevision ?
$currentRevision->getContent() : null;
1845 if ( is_null( $currentContent ) ) {
1846 wfProfileOut( __METHOD__
);
1850 $handler = ContentHandler
::getForModelID( $baseContent->getModel() );
1852 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1855 $editContent = $result;
1856 wfProfileOut( __METHOD__
);
1860 wfProfileOut( __METHOD__
);
1867 function getBaseRevision() {
1868 if ( !$this->mBaseRevision
) {
1869 $db = wfGetDB( DB_MASTER
);
1870 $baseRevision = Revision
::loadFromTimestamp(
1871 $db, $this->mTitle
, $this->edittime
);
1872 return $this->mBaseRevision
= $baseRevision;
1874 return $this->mBaseRevision
;
1879 * Check given input text against $wgSpamRegex, and return the text of the first match.
1881 * @param $text string
1883 * @return string|bool matching string or false
1885 public static function matchSpamRegex( $text ) {
1886 global $wgSpamRegex;
1887 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1888 $regexes = (array)$wgSpamRegex;
1889 return self
::matchSpamRegexInternal( $text, $regexes );
1893 * Check given input text against $wgSpamRegex, and return the text of the first match.
1895 * @param $text string
1897 * @return string|bool matching string or false
1899 public static function matchSummarySpamRegex( $text ) {
1900 global $wgSummarySpamRegex;
1901 $regexes = (array)$wgSummarySpamRegex;
1902 return self
::matchSpamRegexInternal( $text, $regexes );
1906 * @param $text string
1907 * @param $regexes array
1908 * @return bool|string
1910 protected static function matchSpamRegexInternal( $text, $regexes ) {
1911 foreach ( $regexes as $regex ) {
1913 if ( preg_match( $regex, $text, $matches ) ) {
1920 function setHeaders() {
1921 global $wgOut, $wgUser;
1923 $wgOut->addModules( 'mediawiki.action.edit' );
1924 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
1926 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1927 $wgOut->addModules( 'mediawiki.action.edit.preview' );
1930 if ( $wgUser->getOption( 'useeditwarning', false ) ) {
1931 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
1934 // Bug #19334: textarea jumps when editing articles in IE8
1935 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1937 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1939 # Enabled article-related sidebar, toplinks, etc.
1940 $wgOut->setArticleRelated( true );
1942 $contextTitle = $this->getContextTitle();
1943 if ( $this->isConflict
) {
1944 $msg = 'editconflict';
1945 } elseif ( $contextTitle->exists() && $this->section
!= '' ) {
1946 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1948 $msg = $contextTitle->exists() ||
( $contextTitle->getNamespace() == NS_MEDIAWIKI
&& $contextTitle->getDefaultMessageText() !== false ) ?
1949 'editing' : 'creating';
1951 # Use the title defined by DISPLAYTITLE magic word when present
1952 $displayTitle = isset( $this->mParserOutput
) ?
$this->mParserOutput
->getDisplayTitle() : false;
1953 if ( $displayTitle === false ) {
1954 $displayTitle = $contextTitle->getPrefixedText();
1956 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1960 * Show all applicable editing introductions
1962 protected function showIntro() {
1963 global $wgOut, $wgUser;
1964 if ( $this->suppressIntro
) {
1968 $namespace = $this->mTitle
->getNamespace();
1970 if ( $namespace == NS_MEDIAWIKI
) {
1971 # Show a warning if editing an interface message
1972 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1973 } elseif ( $namespace == NS_FILE
) {
1974 # Show a hint to shared repo
1975 $file = wfFindFile( $this->mTitle
);
1976 if ( $file && !$file->isLocal() ) {
1977 $descUrl = $file->getDescriptionUrl();
1978 # there must be a description url to show a hint to shared repo
1980 if ( !$this->mTitle
->exists() ) {
1981 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
1982 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1985 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1986 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1993 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1994 # Show log extract when the user is currently blocked
1995 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
1996 $parts = explode( '/', $this->mTitle
->getText(), 2 );
1997 $username = $parts[0];
1998 $user = User
::newFromName( $username, false /* allow IP users*/ );
1999 $ip = User
::isIP( $username );
2000 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2001 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2002 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2003 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
2004 LogEventsList
::showLogExtract(
2007 $user->getUserPage(),
2011 'showIfEmpty' => false,
2013 'blocked-notice-logextract',
2014 $user->getName() # Support GENDER in notice
2020 # Try to add a custom edit intro, or use the standard one if this is not possible.
2021 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
2022 if ( $wgUser->isLoggedIn() ) {
2023 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
2025 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
2028 # Give a notice if the user is editing a deleted/moved page...
2029 if ( !$this->mTitle
->exists() ) {
2030 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
2034 'conds' => array( "log_action != 'revision'" ),
2035 'showIfEmpty' => false,
2036 'msgKey' => array( 'recreate-moveddeleted-warn' )
2043 * Attempt to show a custom editing introduction, if supplied
2047 protected function showCustomIntro() {
2048 if ( $this->editintro
) {
2049 $title = Title
::newFromText( $this->editintro
);
2050 if ( $title instanceof Title
&& $title->exists() && $title->userCan( 'read' ) ) {
2052 // Added using template syntax, to take <noinclude>'s into account.
2053 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
2061 * Gets an editable textual representation of $content.
2062 * The textual representation can be turned by into a Content object by the
2063 * toEditContent() method.
2065 * If $content is null or false or a string, $content is returned unchanged.
2067 * If the given Content object is not of a type that can be edited using the text base EditPage,
2068 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2071 * @param Content|null|bool|string $content
2072 * @return String the editable text form of the content.
2074 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
2076 protected function toEditText( $content ) {
2077 if ( $content === null ||
$content === false ) {
2081 if ( is_string( $content ) ) {
2085 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
2086 throw new MWException( "This content model can not be edited as text: "
2087 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2090 return $content->serialize( $this->contentFormat
);
2094 * Turns the given text into a Content object by unserializing it.
2096 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
2097 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2100 * @param string|null|bool $text Text to unserialize
2101 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
2104 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
2105 * and $this->allowNonTextContent is not true.
2107 protected function toEditContent( $text ) {
2108 if ( $text === false ||
$text === null ) {
2112 $content = ContentHandler
::makeContent( $text, $this->getTitle(),
2113 $this->contentModel
, $this->contentFormat
);
2115 if ( !$this->allowNonTextContent
&& !( $content instanceof TextContent
) ) {
2116 throw new MWException( "This content model can not be edited as text: "
2117 . ContentHandler
::getLocalizedName( $content->getModel() ) );
2124 * Send the edit form and related headers to $wgOut
2125 * @param $formCallback Callback|null that takes an OutputPage parameter; will be called
2126 * during form output near the top, for captchas and the like.
2128 function showEditForm( $formCallback = null ) {
2129 global $wgOut, $wgUser;
2131 wfProfileIn( __METHOD__
);
2133 # need to parse the preview early so that we know which templates are used,
2134 # otherwise users with "show preview after edit box" will get a blank list
2135 # we parse this near the beginning so that setHeaders can do the title
2136 # setting work instead of leaving it in getPreviewText
2137 $previewOutput = '';
2138 if ( $this->formtype
== 'preview' ) {
2139 $previewOutput = $this->getPreviewText();
2142 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2144 $this->setHeaders();
2146 if ( $this->showHeader() === false ) {
2147 wfProfileOut( __METHOD__
);
2151 $wgOut->addHTML( $this->editFormPageTop
);
2153 if ( $wgUser->getOption( 'previewontop' ) ) {
2154 $this->displayPreviewArea( $previewOutput, true );
2157 $wgOut->addHTML( $this->editFormTextTop
);
2159 $showToolbar = true;
2160 if ( $this->wasDeletedSinceLastEdit() ) {
2161 if ( $this->formtype
== 'save' ) {
2162 // Hide the toolbar and edit area, user can click preview to get it back
2163 // Add an confirmation checkbox and explanation.
2164 $showToolbar = false;
2166 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2167 'deletedwhileediting' );
2171 // @todo add EditForm plugin interface and use it here!
2172 // search for textarea1 and textares2, and allow EditForm to override all uses.
2173 $wgOut->addHTML( Html
::openElement( 'form', array( 'id' => self
::EDITFORM_ID
, 'name' => self
::EDITFORM_ID
,
2174 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
2175 'enctype' => 'multipart/form-data' ) ) );
2177 if ( is_callable( $formCallback ) ) {
2178 call_user_func_array( $formCallback, array( &$wgOut ) );
2181 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2183 // Put these up at the top to ensure they aren't lost on early form submission
2184 $this->showFormBeforeText();
2186 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
2187 $username = $this->lastDelete
->user_name
;
2188 $comment = $this->lastDelete
->log_comment
;
2190 // It is better to not parse the comment at all than to have templates expanded in the middle
2191 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2192 $key = $comment === ''
2193 ?
'confirmrecreate-noreason'
2194 : 'confirmrecreate';
2196 '<div class="mw-confirm-recreate">' .
2197 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2198 Xml
::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2199 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2205 # When the summary is hidden, also hide them on preview/show changes
2206 if ( $this->nosummary
) {
2207 $wgOut->addHTML( Html
::hidden( 'nosummary', true ) );
2210 # If a blank edit summary was previously provided, and the appropriate
2211 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2212 # user being bounced back more than once in the event that a summary
2215 # For a bit more sophisticated detection of blank summaries, hash the
2216 # automatic one and pass that in the hidden field wpAutoSummary.
2217 if ( $this->missingSummary ||
( $this->section
== 'new' && $this->nosummary
) ) {
2218 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
2221 if ( $this->undidRev
) {
2222 $wgOut->addHTML( Html
::hidden( 'wpUndidRevision', $this->undidRev
) );
2225 if ( $this->hasPresetSummary
) {
2226 // If a summary has been preset using &summary= we don't want to prompt for
2227 // a different summary. Only prompt for a summary if the summary is blanked.
2229 $this->autoSumm
= md5( '' );
2232 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
2233 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
2235 $wgOut->addHTML( Html
::hidden( 'oldid', $this->oldid
) );
2237 $wgOut->addHTML( Html
::hidden( 'format', $this->contentFormat
) );
2238 $wgOut->addHTML( Html
::hidden( 'model', $this->contentModel
) );
2240 if ( $this->section
== 'new' ) {
2241 $this->showSummaryInput( true, $this->summary
);
2242 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
2245 $wgOut->addHTML( $this->editFormTextBeforeContent
);
2247 if ( !$this->isCssJsSubpage
&& $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2248 $wgOut->addHTML( EditPage
::getEditToolbar() );
2251 if ( $this->isConflict
) {
2252 // In an edit conflict bypass the overridable content form method
2253 // and fallback to the raw wpTextbox1 since editconflicts can't be
2254 // resolved between page source edits and custom ui edits using the
2256 $this->textbox2
= $this->textbox1
;
2258 $content = $this->getCurrentContent();
2259 $this->textbox1
= $this->toEditText( $content );
2261 $this->showTextbox1();
2263 $this->showContentForm();
2266 $wgOut->addHTML( $this->editFormTextAfterContent
);
2268 $this->showStandardInputs();
2270 $this->showFormAfterText();
2272 $this->showTosSummary();
2274 $this->showEditTools();
2276 $wgOut->addHTML( $this->editFormTextAfterTools
. "\n" );
2278 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2279 Linker
::formatTemplates( $this->getTemplates(), $this->preview
, $this->section
!= '' ) ) );
2281 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'hiddencats' ),
2282 Linker
::formatHiddenCategories( $this->mArticle
->getHiddenCategories() ) ) );
2284 $wgOut->addHTML( Html
::rawElement( 'div', array( 'class' => 'limitreport' ),
2285 self
::getPreviewLimitReport( $this->mParserOutput
) ) );
2287 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2289 if ( $this->isConflict
) {
2291 $this->showConflict();
2292 } catch ( MWContentSerializationException
$ex ) {
2293 // this can't really happen, but be nice if it does.
2294 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2295 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2299 $wgOut->addHTML( $this->editFormTextBottom
. "\n</form>\n" );
2301 if ( !$wgUser->getOption( 'previewontop' ) ) {
2302 $this->displayPreviewArea( $previewOutput, false );
2305 wfProfileOut( __METHOD__
);
2309 * Extract the section title from current section text, if any.
2311 * @param string $text
2312 * @return Mixed|string or false
2314 public static function extractSectionTitle( $text ) {
2315 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2316 if ( !empty( $matches[2] ) ) {
2318 return $wgParser->stripSectionName( trim( $matches[2] ) );
2324 protected function showHeader() {
2325 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2327 if ( $this->mTitle
->isTalkPage() ) {
2328 $wgOut->addWikiMsg( 'talkpagetext' );
2332 $wgOut->addHTML( implode( "\n", $this->mTitle
->getEditNotices( $this->oldid
) ) );
2334 if ( $this->isConflict
) {
2335 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2336 $this->edittime
= $this->mArticle
->getTimestamp();
2338 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
2339 // We use $this->section to much before this and getVal('wgSection') directly in other places
2340 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2341 // Someone is welcome to try refactoring though
2342 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2346 if ( $this->section
!= '' && $this->section
!= 'new' ) {
2347 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
2348 $sectionTitle = self
::extractSectionTitle( $this->textbox1
); //FIXME: use Content object
2349 if ( $sectionTitle !== false ) {
2350 $this->summary
= "/* $sectionTitle */ ";
2355 if ( $this->missingComment
) {
2356 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2359 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
2360 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2363 if ( $this->missingSummary
&& $this->section
== 'new' ) {
2364 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2367 if ( $this->hookError
!== '' ) {
2368 $wgOut->addWikiText( $this->hookError
);
2371 if ( !$this->checkUnicodeCompliantBrowser() ) {
2372 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2375 if ( $this->section
!= 'new' ) {
2376 $revision = $this->mArticle
->getRevisionFetched();
2378 // Let sysop know that this will make private content public if saved
2380 if ( !$revision->userCan( Revision
::DELETED_TEXT
, $wgUser ) ) {
2381 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2382 } elseif ( $revision->isDeleted( Revision
::DELETED_TEXT
) ) {
2383 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2386 if ( !$revision->isCurrent() ) {
2387 $this->mArticle
->setOldSubtitle( $revision->getId() );
2388 $wgOut->addWikiMsg( 'editingold' );
2390 } elseif ( $this->mTitle
->exists() ) {
2391 // Something went wrong
2393 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2394 array( 'missing-revision', $this->oldid
) );
2399 if ( wfReadOnly() ) {
2400 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2401 } elseif ( $wgUser->isAnon() ) {
2402 if ( $this->formtype
!= 'preview' ) {
2403 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2405 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2408 if ( $this->isCssJsSubpage
) {
2409 # Check the skin exists
2410 if ( $this->isWrongCaseCssJsPage
) {
2411 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
2413 if ( $this->formtype
!== 'preview' ) {
2414 if ( $this->isCssSubpage
) {
2415 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2418 if ( $this->isJsSubpage
) {
2419 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2425 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2426 # Is the title semi-protected?
2427 if ( $this->mTitle
->isSemiProtected() ) {
2428 $noticeMsg = 'semiprotectedpagewarning';
2430 # Then it must be protected based on static groups (regular)
2431 $noticeMsg = 'protectedpagewarning';
2433 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2434 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2436 if ( $this->mTitle
->isCascadeProtected() ) {
2437 # Is this page under cascading protection from some source pages?
2438 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
2439 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2440 $cascadeSourcesCount = count( $cascadeSources );
2441 if ( $cascadeSourcesCount > 0 ) {
2442 # Explain, and list the titles responsible
2443 foreach ( $cascadeSources as $page ) {
2444 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2447 $notice .= '</div>';
2448 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2450 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
2451 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
2453 'showIfEmpty' => false,
2454 'msgKey' => array( 'titleprotectedwarning' ),
2455 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2458 if ( $this->kblength
=== false ) {
2459 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
2462 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
2463 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2464 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2466 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2467 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2468 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
2472 # Add header copyright warning
2473 $this->showHeaderCopyrightWarning();
2477 * Standard summary input and label (wgSummary), abstracted so EditPage
2478 * subclasses may reorganize the form.
2479 * Note that you do not need to worry about the label's for=, it will be
2480 * inferred by the id given to the input. You can remove them both by
2481 * passing array( 'id' => false ) to $userInputAttrs.
2483 * @param string $summary The value of the summary input
2484 * @param string $labelText The html to place inside the label
2485 * @param array $inputAttrs of attrs to use on the input
2486 * @param array $spanLabelAttrs of attrs to use on the span inside the label
2488 * @return array An array in the format array( $label, $input )
2490 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2491 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2492 $inputAttrs = ( is_array( $inputAttrs ) ?
$inputAttrs : array() ) +
array(
2493 'id' => 'wpSummary',
2494 'maxlength' => '200',
2497 'spellcheck' => 'true',
2498 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
2500 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ?
$spanLabelAttrs : array() ) +
array(
2501 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
2502 'id' => "wpSummaryLabel"
2507 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2508 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
2511 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
2513 return array( $label, $input );
2517 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2518 * up top, or false if this is the comment summary
2519 * down below the textarea
2520 * @param string $summary The text of the summary to display
2523 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2524 global $wgOut, $wgContLang;
2525 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2526 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
2527 if ( $isSubjectPreview ) {
2528 if ( $this->nosummary
) {
2532 if ( !$this->mShowSummaryField
) {
2536 $summary = $wgContLang->recodeForEdit( $summary );
2537 $labelText = wfMessage( $isSubjectPreview ?
'subject' : 'summary' )->parse();
2538 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2539 $wgOut->addHTML( "{$label} {$input}" );
2543 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2544 * up top, or false if this is the comment summary
2545 * down below the textarea
2546 * @param string $summary the text of the summary to display
2549 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2550 // avoid spaces in preview, gets always trimmed on save
2551 $summary = trim( $summary );
2552 if ( !$summary ||
( !$this->preview
&& !$this->diff
) ) {
2558 if ( $isSubjectPreview ) {
2559 $summary = wfMessage( 'newsectionsummary', $wgParser->stripSectionName( $summary ) )
2560 ->inContentLanguage()->text();
2563 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
2565 $summary = wfMessage( $message )->parse() . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
2566 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2569 protected function showFormBeforeText() {
2571 $section = htmlspecialchars( $this->section
);
2572 $wgOut->addHTML( <<<HTML
2573 <input type='hidden' value="{$section}" name="wpSection" />
2574 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2575 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2576 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2580 if ( !$this->checkUnicodeCompliantBrowser() ) {
2581 $wgOut->addHTML( Html
::hidden( 'safemode', '1' ) );
2585 protected function showFormAfterText() {
2586 global $wgOut, $wgUser;
2588 * To make it harder for someone to slip a user a page
2589 * which submits an edit form to the wiki without their
2590 * knowledge, a random token is associated with the login
2591 * session. If it's not passed back with the submission,
2592 * we won't save the page, or render user JavaScript and
2595 * For anon editors, who may not have a session, we just
2596 * include the constant suffix to prevent editing from
2597 * broken text-mangling proxies.
2599 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2603 * Subpage overridable method for printing the form for page content editing
2604 * By default this simply outputs wpTextbox1
2605 * Subclasses can override this to provide a custom UI for editing;
2606 * be it a form, or simply wpTextbox1 with a modified content that will be
2607 * reverse modified when extracted from the post data.
2608 * Note that this is basically the inverse for importContentFormData
2610 protected function showContentForm() {
2611 $this->showTextbox1();
2615 * Method to output wpTextbox1
2616 * The $textoverride method can be used by subclasses overriding showContentForm
2617 * to pass back to this method.
2619 * @param array $customAttribs of html attributes to use in the textarea
2620 * @param string $textoverride optional text to override $this->textarea1 with
2622 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2623 if ( $this->wasDeletedSinceLastEdit() && $this->formtype
== 'save' ) {
2624 $attribs = array( 'style' => 'display:none;' );
2626 $classes = array(); // Textarea CSS
2627 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
2628 # Is the title semi-protected?
2629 if ( $this->mTitle
->isSemiProtected() ) {
2630 $classes[] = 'mw-textarea-sprotected';
2632 # Then it must be protected based on static groups (regular)
2633 $classes[] = 'mw-textarea-protected';
2635 # Is the title cascade-protected?
2636 if ( $this->mTitle
->isCascadeProtected() ) {
2637 $classes[] = 'mw-textarea-cprotected';
2641 $attribs = array( 'tabindex' => 1 );
2643 if ( is_array( $customAttribs ) ) {
2644 $attribs +
= $customAttribs;
2647 if ( count( $classes ) ) {
2648 if ( isset( $attribs['class'] ) ) {
2649 $classes[] = $attribs['class'];
2651 $attribs['class'] = implode( ' ', $classes );
2655 $this->showTextbox( $textoverride !== null ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
2658 protected function showTextbox2() {
2659 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2662 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2663 global $wgOut, $wgUser;
2665 $wikitext = $this->safeUnicodeOutput( $text );
2666 if ( strval( $wikitext ) !== '' ) {
2667 // Ensure there's a newline at the end, otherwise adding lines
2669 // But don't add a newline if the ext is empty, or Firefox in XHTML
2670 // mode will show an extra newline. A bit annoying.
2674 $attribs = $customAttribs +
array(
2677 'cols' => $wgUser->getIntOption( 'cols' ),
2678 'rows' => $wgUser->getIntOption( 'rows' ),
2679 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2682 $pageLang = $this->mTitle
->getPageLanguage();
2683 $attribs['lang'] = $pageLang->getCode();
2684 $attribs['dir'] = $pageLang->getDir();
2686 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
2689 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2693 $classes[] = 'ontop';
2696 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2698 if ( $this->formtype
!= 'preview' ) {
2699 $attribs['style'] = 'display: none;';
2702 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
2704 if ( $this->formtype
== 'preview' ) {
2705 $this->showPreview( $previewOutput );
2708 $wgOut->addHTML( '</div>' );
2710 if ( $this->formtype
== 'diff' ) {
2713 } catch ( MWContentSerializationException
$ex ) {
2714 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
2715 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2721 * Append preview output to $wgOut.
2722 * Includes category rendering if this is a category page.
2724 * @param string $text the HTML to be output for the preview.
2726 protected function showPreview( $text ) {
2728 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2729 $this->mArticle
->openShowCategory();
2731 # This hook seems slightly odd here, but makes things more
2732 # consistent for extensions.
2733 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2734 $wgOut->addHTML( $text );
2735 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
2736 $this->mArticle
->closeShowCategory();
2741 * Get a diff between the current contents of the edit box and the
2742 * version of the page we're editing from.
2744 * If this is a section edit, we'll replace the section as for final
2745 * save and then make a comparison.
2747 function showDiff() {
2748 global $wgUser, $wgContLang, $wgOut;
2750 $oldtitlemsg = 'currentrev';
2751 # if message does not exist, show diff against the preloaded default
2752 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
&& !$this->mTitle
->exists() ) {
2753 $oldtext = $this->mTitle
->getDefaultMessageText();
2754 if ( $oldtext !== false ) {
2755 $oldtitlemsg = 'defaultmessagetext';
2756 $oldContent = $this->toEditContent( $oldtext );
2761 $oldContent = $this->getCurrentContent();
2764 $textboxContent = $this->toEditContent( $this->textbox1
);
2766 $newContent = $this->mArticle
->replaceSectionContent(
2767 $this->section
, $textboxContent,
2768 $this->summary
, $this->edittime
);
2770 if ( $newContent ) {
2771 ContentHandler
::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2772 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2774 $popts = ParserOptions
::newFromUserAndLang( $wgUser, $wgContLang );
2775 $newContent = $newContent->preSaveTransform( $this->mTitle
, $wgUser, $popts );
2778 if ( ( $oldContent && !$oldContent->isEmpty() ) ||
( $newContent && !$newContent->isEmpty() ) ) {
2779 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2780 $newtitle = wfMessage( 'yourtext' )->parse();
2782 if ( !$oldContent ) {
2783 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
2786 if ( !$newContent ) {
2787 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
2790 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle
->getContext() );
2791 $de->setContent( $oldContent, $newContent );
2793 $difftext = $de->getDiff( $oldtitle, $newtitle );
2794 $de->showDiffStyle();
2799 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2803 * Show the header copyright warning.
2805 protected function showHeaderCopyrightWarning() {
2806 $msg = 'editpage-head-copy-warn';
2807 if ( !wfMessage( $msg )->isDisabled() ) {
2809 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2810 'editpage-head-copy-warn' );
2815 * Give a chance for site and per-namespace customizations of
2816 * terms of service summary link that might exist separately
2817 * from the copyright notice.
2819 * This will display between the save button and the edit tools,
2820 * so should remain short!
2822 protected function showTosSummary() {
2823 $msg = 'editpage-tos-summary';
2824 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
2825 if ( !wfMessage( $msg )->isDisabled() ) {
2827 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2828 $wgOut->addWikiMsg( $msg );
2829 $wgOut->addHTML( '</div>' );
2833 protected function showEditTools() {
2835 $wgOut->addHTML( '<div class="mw-editTools">' .
2836 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2841 * Get the copyright warning
2843 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2845 protected function getCopywarn() {
2846 return self
::getCopyrightWarning( $this->mTitle
);
2849 public static function getCopyrightWarning( $title ) {
2850 global $wgRightsText;
2851 if ( $wgRightsText ) {
2852 $copywarnMsg = array( 'copyrightwarning',
2853 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2856 $copywarnMsg = array( 'copyrightwarning2',
2857 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2859 // Allow for site and per-namespace customization of contribution/copyright notice.
2860 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2862 return "<div id=\"editpage-copywarn\">\n" .
2863 call_user_func_array( 'wfMessage', $copywarnMsg )->plain() . "\n</div>";
2867 * Get the Limit report for page previews
2870 * @param ParserOutput $output ParserOutput object from the parse
2871 * @return string HTML
2873 public static function getPreviewLimitReport( $output ) {
2874 if ( !$output ||
!$output->getLimitReportData() ) {
2878 wfProfileIn( __METHOD__
);
2880 $limitReport = Html
::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
2881 wfMessage( 'limitreport-title' )->parseAsBlock()
2884 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
2885 $limitReport .= Html
::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
2887 $limitReport .= Html
::openElement( 'table', array(
2888 'class' => 'preview-limit-report wikitable'
2890 Html
::openElement( 'tbody' );
2892 foreach ( $output->getLimitReportData() as $key => $value ) {
2893 if ( wfRunHooks( 'ParserLimitReportFormat',
2894 array( $key, $value, &$limitReport, true, true )
2896 $keyMsg = wfMessage( $key );
2897 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
2898 if ( !$valueMsg->exists() ) {
2899 $valueMsg = new RawMessage( '$1' );
2901 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
2902 $limitReport .= Html
::openElement( 'tr' ) .
2903 Html
::rawElement( 'th', null, $keyMsg->parse() ) .
2904 Html
::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
2905 Html
::closeElement( 'tr' );
2910 $limitReport .= Html
::closeElement( 'tbody' ) .
2911 Html
::closeElement( 'table' ) .
2912 Html
::closeElement( 'div' );
2914 wfProfileOut( __METHOD__
);
2916 return $limitReport;
2919 protected function showStandardInputs( &$tabindex = 2 ) {
2921 $wgOut->addHTML( "<div class='editOptions'>\n" );
2923 if ( $this->section
!= 'new' ) {
2924 $this->showSummaryInput( false, $this->summary
);
2925 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
2928 $checkboxes = $this->getCheckboxes( $tabindex,
2929 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
2930 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2932 // Show copyright warning.
2933 $wgOut->addWikiText( $this->getCopywarn() );
2934 $wgOut->addHTML( $this->editFormTextAfterWarn
);
2936 $wgOut->addHTML( "<div class='editButtons'>\n" );
2937 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2939 $cancel = $this->getCancelLink();
2940 if ( $cancel !== '' ) {
2941 $cancel .= Html
::element( 'span',
2942 array( 'class' => 'mw-editButtons-pipe-separator' ),
2943 wfMessage( 'pipe-separator' )->text() );
2945 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
2946 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2947 wfMessage( 'edithelp' )->escaped() . '</a> ' .
2948 wfMessage( 'newwindow' )->parse();
2949 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
2950 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
2951 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
2952 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
2953 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
2957 * Show an edit conflict. textbox1 is already shown in showEditForm().
2958 * If you want to use another entry point to this function, be careful.
2960 protected function showConflict() {
2963 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2964 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2966 $content1 = $this->toEditContent( $this->textbox1
);
2967 $content2 = $this->toEditContent( $this->textbox2
);
2969 $handler = ContentHandler
::getForModelID( $this->contentModel
);
2970 $de = $handler->createDifferenceEngine( $this->mArticle
->getContext() );
2971 $de->setContent( $content2, $content1 );
2973 wfMessage( 'yourtext' )->parse(),
2974 wfMessage( 'storedversion' )->text()
2977 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2978 $this->showTextbox2();
2985 public function getCancelLink() {
2986 $cancelParams = array();
2987 if ( !$this->isConflict
&& $this->oldid
> 0 ) {
2988 $cancelParams['oldid'] = $this->oldid
;
2991 return Linker
::linkKnown(
2992 $this->getContextTitle(),
2993 wfMessage( 'cancel' )->parse(),
2994 array( 'id' => 'mw-editform-cancel' ),
3000 * Returns the URL to use in the form's action attribute.
3001 * This is used by EditPage subclasses when simply customizing the action
3002 * variable in the constructor is not enough. This can be used when the
3003 * EditPage lives inside of a Special page rather than a custom page action.
3005 * @param $title Title object for which is being edited (where we go to for &action= links)
3008 protected function getActionURL( Title
$title ) {
3009 return $title->getLocalURL( array( 'action' => $this->action
) );
3013 * Check if a page was deleted while the user was editing it, before submit.
3014 * Note that we rely on the logging table, which hasn't been always there,
3015 * but that doesn't matter, because this only applies to brand new
3018 protected function wasDeletedSinceLastEdit() {
3019 if ( $this->deletedSinceEdit
!== null ) {
3020 return $this->deletedSinceEdit
;
3023 $this->deletedSinceEdit
= false;
3025 if ( $this->mTitle
->isDeletedQuick() ) {
3026 $this->lastDelete
= $this->getLastDelete();
3027 if ( $this->lastDelete
) {
3028 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
3029 if ( $deleteTime > $this->starttime
) {
3030 $this->deletedSinceEdit
= true;
3035 return $this->deletedSinceEdit
;
3038 protected function getLastDelete() {
3039 $dbr = wfGetDB( DB_SLAVE
);
3040 $data = $dbr->selectRow(
3041 array( 'logging', 'user' ),
3054 'log_namespace' => $this->mTitle
->getNamespace(),
3055 'log_title' => $this->mTitle
->getDBkey(),
3056 'log_type' => 'delete',
3057 'log_action' => 'delete',
3061 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3063 // Quick paranoid permission checks...
3064 if ( is_object( $data ) ) {
3065 if ( $data->log_deleted
& LogPage
::DELETED_USER
) {
3066 $data->user_name
= wfMessage( 'rev-deleted-user' )->escaped();
3069 if ( $data->log_deleted
& LogPage
::DELETED_COMMENT
) {
3070 $data->log_comment
= wfMessage( 'rev-deleted-comment' )->escaped();
3077 * Get the rendered text for previewing.
3078 * @throws MWException
3081 function getPreviewText() {
3082 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3084 wfProfileIn( __METHOD__
);
3086 if ( $wgRawHtml && !$this->mTokenOk
) {
3087 // Could be an offsite preview attempt. This is very unsafe if
3088 // HTML is enabled, as it could be an attack.
3090 if ( $this->textbox1
!== '' ) {
3091 // Do not put big scary notice, if previewing the empty
3092 // string, which happens when you initially edit
3093 // a category page, due to automatic preview-on-open.
3094 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3095 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3097 wfProfileOut( __METHOD__
);
3104 $content = $this->toEditContent( $this->textbox1
);
3107 if ( !wfRunHooks( 'AlternateEditPreview', array( $this, &$content, &$previewHTML, &$this->mParserOutput
) ) ) {
3108 wfProfileOut( __METHOD__
);
3109 return $previewHTML;
3112 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
3113 if ( $this->mTokenOkExceptSuffix
) {
3114 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3117 $note = wfMessage( 'session_fail_preview' )->plain();
3119 } elseif ( $this->incompleteForm
) {
3120 $note = wfMessage( 'edit_form_incomplete' )->plain();
3122 $note = wfMessage( 'previewnote' )->plain() .
3123 ' [[#' . self
::EDITFORM_ID
. '|' . $wgLang->getArrow() . ' ' . wfMessage( 'continue-editing' )->text() . ']]';
3126 $parserOptions = $this->mArticle
->makeParserOptions( $this->mArticle
->getContext() );
3127 $parserOptions->setEditSection( false );
3128 $parserOptions->setIsPreview( true );
3129 $parserOptions->setIsSectionPreview( !is_null( $this->section
) && $this->section
!== '' );
3131 # don't parse non-wikitext pages, show message about preview
3132 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
3133 if ( $this->mTitle
->isCssJsSubpage() ) {
3135 } elseif ( $this->mTitle
->isCssOrJsPage() ) {
3141 if ( $content->getModel() == CONTENT_MODEL_CSS
) {
3143 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT
) {
3149 # Used messages to make sure grep find them:
3150 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3151 if ( $level && $format ) {
3152 $note = "<div id='mw-{$level}{$format}preview'>" . wfMessage( "{$level}{$format}preview" )->text() . "</div>";
3156 $rt = $content->getRedirectChain();
3158 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
3161 # If we're adding a comment, we need to show the
3162 # summary as the headline
3163 if ( $this->section
=== "new" && $this->summary
!== "" ) {
3164 $content = $content->addSectionHeader( $this->summary
);
3167 $hook_args = array( $this, &$content );
3168 ContentHandler
::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3169 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3171 $parserOptions->enableLimitReport();
3173 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3174 # But it's now deprecated, so never mind
3176 $content = $content->preSaveTransform( $this->mTitle
, $wgUser, $parserOptions );
3177 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
3179 $previewHTML = $parserOutput->getText();
3180 $this->mParserOutput
= $parserOutput;
3181 $wgOut->addParserOutputNoText( $parserOutput );
3183 if ( count( $parserOutput->getWarnings() ) ) {
3184 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3187 } catch ( MWContentSerializationException
$ex ) {
3188 $m = wfMessage( 'content-failed-to-parse', $this->contentModel
, $this->contentFormat
, $ex->getMessage() );
3189 $note .= "\n\n" . $m->parse();
3193 if ( $this->isConflict
) {
3194 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3196 $conflict = '<hr />';
3199 $previewhead = "<div class='previewnote'>\n" .
3200 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3201 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3203 $pageViewLang = $this->mTitle
->getPageViewLanguage();
3204 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3205 'class' => 'mw-content-' . $pageViewLang->getDir() );
3206 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
3208 wfProfileOut( __METHOD__
);
3209 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
3215 function getTemplates() {
3216 if ( $this->preview ||
$this->section
!= '' ) {
3217 $templates = array();
3218 if ( !isset( $this->mParserOutput
) ) {
3221 foreach ( $this->mParserOutput
->getTemplates() as $ns => $template ) {
3222 foreach ( array_keys( $template ) as $dbk ) {
3223 $templates[] = Title
::makeTitle( $ns, $dbk );
3228 return $this->mTitle
->getTemplateLinksFrom();
3233 * Shows a bulletin board style toolbar for common editing functions.
3234 * It can be disabled in the user preferences.
3235 * The necessary JavaScript code can be found in skins/common/edit.js.
3239 static function getEditToolbar() {
3240 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3241 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
3243 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
3246 * $toolarray is an array of arrays each of which includes the
3247 * filename of the button image (without path), the opening
3248 * tag, the closing tag, optionally a sample text that is
3249 * inserted between the two when no selection is highlighted
3250 * and. The tip text is shown when the user moves the mouse
3253 * Also here: accesskeys (key), which are not used yet until
3254 * someone can figure out a way to make them work in
3255 * IE. However, we should make sure these keys are not defined
3260 'image' => $wgLang->getImageFile( 'button-bold' ),
3261 'id' => 'mw-editbutton-bold',
3263 'close' => '\'\'\'',
3264 'sample' => wfMessage( 'bold_sample' )->text(),
3265 'tip' => wfMessage( 'bold_tip' )->text(),
3269 'image' => $wgLang->getImageFile( 'button-italic' ),
3270 'id' => 'mw-editbutton-italic',
3273 'sample' => wfMessage( 'italic_sample' )->text(),
3274 'tip' => wfMessage( 'italic_tip' )->text(),
3278 'image' => $wgLang->getImageFile( 'button-link' ),
3279 'id' => 'mw-editbutton-link',
3282 'sample' => wfMessage( 'link_sample' )->text(),
3283 'tip' => wfMessage( 'link_tip' )->text(),
3287 'image' => $wgLang->getImageFile( 'button-extlink' ),
3288 'id' => 'mw-editbutton-extlink',
3291 'sample' => wfMessage( 'extlink_sample' )->text(),
3292 'tip' => wfMessage( 'extlink_tip' )->text(),
3296 'image' => $wgLang->getImageFile( 'button-headline' ),
3297 'id' => 'mw-editbutton-headline',
3300 'sample' => wfMessage( 'headline_sample' )->text(),
3301 'tip' => wfMessage( 'headline_tip' )->text(),
3304 $imagesAvailable ?
array(
3305 'image' => $wgLang->getImageFile( 'button-image' ),
3306 'id' => 'mw-editbutton-image',
3307 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
3309 'sample' => wfMessage( 'image_sample' )->text(),
3310 'tip' => wfMessage( 'image_tip' )->text(),
3313 $imagesAvailable ?
array(
3314 'image' => $wgLang->getImageFile( 'button-media' ),
3315 'id' => 'mw-editbutton-media',
3316 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
3318 'sample' => wfMessage( 'media_sample' )->text(),
3319 'tip' => wfMessage( 'media_tip' )->text(),
3323 'image' => $wgLang->getImageFile( 'button-math' ),
3324 'id' => 'mw-editbutton-math',
3326 'close' => "</math>",
3327 'sample' => wfMessage( 'math_sample' )->text(),
3328 'tip' => wfMessage( 'math_tip' )->text(),
3332 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3333 'id' => 'mw-editbutton-nowiki',
3334 'open' => "<nowiki>",
3335 'close' => "</nowiki>",
3336 'sample' => wfMessage( 'nowiki_sample' )->text(),
3337 'tip' => wfMessage( 'nowiki_tip' )->text(),
3341 'image' => $wgLang->getImageFile( 'button-sig' ),
3342 'id' => 'mw-editbutton-signature',
3346 'tip' => wfMessage( 'sig_tip' )->text(),
3350 'image' => $wgLang->getImageFile( 'button-hr' ),
3351 'id' => 'mw-editbutton-hr',
3352 'open' => "\n----\n",
3355 'tip' => wfMessage( 'hr_tip' )->text(),
3360 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3361 foreach ( $toolarray as $tool ) {
3367 $image = $wgStylePath . '/common/images/' . $tool['image'],
3368 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3369 // Older browsers show a "speedtip" type message only for ALT.
3370 // Ideally these should be different, realistically they
3371 // probably don't need to be.
3372 $tip = $tool['tip'],
3373 $open = $tool['open'],
3374 $close = $tool['close'],
3375 $sample = $tool['sample'],
3376 $cssId = $tool['id'],
3379 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
3382 // This used to be called on DOMReady from mediawiki.action.edit, which
3383 // ended up causing race conditions with the setup code above.
3385 "// Create button bar\n" .
3386 "$(function() { mw.toolbar.init(); } );\n";
3389 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
3391 $toolbar = '<div id="toolbar"></div>';
3393 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3399 * Returns an array of html code of the following checkboxes:
3402 * @param int $tabindex Current tabindex
3403 * @param array $checked of checkbox => bool, where bool indicates the checked
3404 * status of the checkbox
3408 public function getCheckboxes( &$tabindex, $checked ) {
3411 $checkboxes = array();
3413 // don't show the minor edit checkbox if it's a new page or section
3414 if ( !$this->isNew
) {
3415 $checkboxes['minor'] = '';
3416 $minorLabel = wfMessage( 'minoredit' )->parse();
3417 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3419 'tabindex' => ++
$tabindex,
3420 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3421 'id' => 'wpMinoredit',
3423 $checkboxes['minor'] =
3424 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3425 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
3426 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3427 ">{$minorLabel}</label>";
3431 $watchLabel = wfMessage( 'watchthis' )->parse();
3432 $checkboxes['watch'] = '';
3433 if ( $wgUser->isLoggedIn() ) {
3435 'tabindex' => ++
$tabindex,
3436 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3437 'id' => 'wpWatchthis',
3439 $checkboxes['watch'] =
3440 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3441 " <label for='wpWatchthis' id='mw-editpage-watch'" .
3442 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
3443 ">{$watchLabel}</label>";
3445 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3450 * Returns an array of html code of the following buttons:
3451 * save, diff, preview and live
3453 * @param int $tabindex Current tabindex
3457 public function getEditButtons( &$tabindex ) {
3464 'tabindex' => ++
$tabindex,
3465 'value' => wfMessage( 'savearticle' )->text(),
3466 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3467 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3469 $buttons['save'] = Xml
::element( 'input', $temp, '' );
3471 ++
$tabindex; // use the same for preview and live preview
3473 'id' => 'wpPreview',
3474 'name' => 'wpPreview',
3476 'tabindex' => $tabindex,
3477 'value' => wfMessage( 'showpreview' )->text(),
3478 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3479 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3481 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
3482 $buttons['live'] = '';
3488 'tabindex' => ++
$tabindex,
3489 'value' => wfMessage( 'showdiff' )->text(),
3490 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3491 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3493 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
3495 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3500 * Output preview text only. This can be sucked into the edit page
3501 * via JavaScript, and saves the server time rendering the skin as
3502 * well as theoretically being more robust on the client (doesn't
3503 * disturb the edit box's undo history, won't eat your text on
3506 * @todo This doesn't include category or interlanguage links.
3507 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3508 * or something...</s>" that might also require more skin
3509 * initialization, so check whether that's a problem.
3511 function livePreview() {
3514 header( 'Content-type: text/xml; charset=utf-8' );
3515 header( 'Cache-control: no-cache' );
3517 $previewText = $this->getPreviewText();
3518 #$categories = $skin->getCategoryLinks();
3521 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3522 Xml
::tags( 'livepreview', null,
3523 Xml
::element( 'preview', null, $previewText )
3524 #. Xml::element( 'category', null, $categories )
3530 * Call the stock "user is blocked" page
3532 * @deprecated in 1.19; throw an exception directly instead
3534 function blockedPage() {
3535 wfDeprecated( __METHOD__
, '1.19' );
3538 throw new UserBlockedError( $wgUser->getBlock() );
3542 * Produce the stock "please login to edit pages" page
3544 * @deprecated in 1.19; throw an exception directly instead
3546 function userNotLoggedInPage() {
3547 wfDeprecated( __METHOD__
, '1.19' );
3548 throw new PermissionsError( 'edit' );
3552 * Show an error page saying to the user that he has insufficient permissions
3553 * to create a new page
3555 * @deprecated in 1.19; throw an exception directly instead
3557 function noCreatePermission() {
3558 wfDeprecated( __METHOD__
, '1.19' );
3559 $permission = $this->mTitle
->isTalkPage() ?
'createtalk' : 'createpage';
3560 throw new PermissionsError( $permission );
3564 * Creates a basic error page which informs the user that
3565 * they have attempted to edit a nonexistent section.
3567 function noSuchSectionPage() {
3570 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3572 $res = wfMessage( 'nosuchsectiontext', $this->section
)->parseAsBlock();
3573 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3574 $wgOut->addHTML( $res );
3576 $wgOut->returnToMain( false, $this->mTitle
);
3580 * Produce the stock "your edit contains spam" page
3582 * @param string|bool $match Text which triggered one or more filters
3583 * @deprecated since 1.17 Use method spamPageWithContent() instead
3585 static function spamPage( $match = false ) {
3586 wfDeprecated( __METHOD__
, '1.17' );
3588 global $wgOut, $wgTitle;
3590 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3592 $wgOut->addHTML( '<div id="spamprotected">' );
3593 $wgOut->addWikiMsg( 'spamprotectiontext' );
3595 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3597 $wgOut->addHTML( '</div>' );
3599 $wgOut->returnToMain( false, $wgTitle );
3603 * Show "your edit contains spam" page with your diff and text
3605 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3607 public function spamPageWithContent( $match = false ) {
3608 global $wgOut, $wgLang;
3609 $this->textbox2
= $this->textbox1
;
3611 if ( is_array( $match ) ) {
3612 $match = $wgLang->listToText( $match );
3614 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3616 $wgOut->addHTML( '<div id="spamprotected">' );
3617 $wgOut->addWikiMsg( 'spamprotectiontext' );
3619 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3621 $wgOut->addHTML( '</div>' );
3623 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3626 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3627 $this->showTextbox2();
3629 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3633 * Format an anchor fragment as it would appear for a given section name
3634 * @param $text String
3638 function sectionAnchor( $text ) {
3640 return $wgParser->guessSectionNameFromWikiText( $text );
3644 * Check if the browser is on a blacklist of user-agents known to
3645 * mangle UTF-8 data on form submission. Returns true if Unicode
3646 * should make it through, false if it's known to be a problem.
3650 function checkUnicodeCompliantBrowser() {
3651 global $wgBrowserBlackList, $wgRequest;
3653 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3654 if ( $currentbrowser === false ) {
3655 // No User-Agent header sent? Trust it by default...
3659 foreach ( $wgBrowserBlackList as $browser ) {
3660 if ( preg_match( $browser, $currentbrowser ) ) {
3668 * Filter an input field through a Unicode de-armoring process if it
3669 * came from an old browser with known broken Unicode editing issues.
3671 * @param $request WebRequest
3672 * @param $field String
3676 function safeUnicodeInput( $request, $field ) {
3677 $text = rtrim( $request->getText( $field ) );
3678 return $request->getBool( 'safemode' )
3679 ?
$this->unmakesafe( $text )
3684 * @param $request WebRequest
3685 * @param $text string
3688 function safeUnicodeText( $request, $text ) {
3689 $text = rtrim( $text );
3690 return $request->getBool( 'safemode' )
3691 ?
$this->unmakesafe( $text )
3696 * Filter an output field through a Unicode armoring process if it is
3697 * going to an old browser with known broken Unicode editing issues.
3699 * @param $text String
3703 function safeUnicodeOutput( $text ) {
3705 $codedText = $wgContLang->recodeForEdit( $text );
3706 return $this->checkUnicodeCompliantBrowser()
3708 : $this->makesafe( $codedText );
3712 * A number of web browsers are known to corrupt non-ASCII characters
3713 * in a UTF-8 text editing environment. To protect against this,
3714 * detected browsers will be served an armored version of the text,
3715 * with non-ASCII chars converted to numeric HTML character references.
3717 * Preexisting such character references will have a 0 added to them
3718 * to ensure that round-trips do not alter the original data.
3720 * @param $invalue String
3724 function makesafe( $invalue ) {
3725 // Armor existing references for reversibility.
3726 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
3731 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3732 $bytevalue = ord( $invalue[$i] );
3733 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3734 $result .= chr( $bytevalue );
3736 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3737 $working = $working << 6;
3738 $working +
= ( $bytevalue & 0x3F );
3740 if ( $bytesleft <= 0 ) {
3741 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3743 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3744 $working = $bytevalue & 0x1F;
3746 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3747 $working = $bytevalue & 0x0F;
3749 } else { // 1111 0xxx
3750 $working = $bytevalue & 0x07;
3758 * Reverse the previously applied transliteration of non-ASCII characters
3759 * back to UTF-8. Used to protect data from corruption by broken web browsers
3760 * as listed in $wgBrowserBlackList.
3762 * @param $invalue String
3766 function unmakesafe( $invalue ) {
3768 for ( $i = 0; $i < strlen( $invalue ); $i++
) {
3769 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i +
3] != '0' ) ) {
3773 $hexstring .= $invalue[$i];
3775 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3777 // Do some sanity checks. These aren't needed for reversibility,
3778 // but should help keep the breakage down if the editor
3779 // breaks one of the entities whilst editing.
3780 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3781 $codepoint = hexdec( $hexstring );
3782 $result .= codepointToUtf8( $codepoint );
3784 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3787 $result .= substr( $invalue, $i, 1 );
3790 // reverse the transform that we made for reversibility reasons.
3791 return strtr( $result, array( "�" => "&#x" ) );