Refactor diffs
[mediawiki.git] / includes / EditPage.php
blob530e267453efdece70bf39bb611d1589218069a9
1 <?php
2 /**
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
20 * @file
23 /**
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
27 * interfaces.
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.
38 class EditPage {
40 /**
41 * Status: Article successfully updated
43 const AS_SUCCESS_UPDATE = 200;
45 /**
46 * Status: Article successfully created
48 const AS_SUCCESS_NEW_ARTICLE = 201;
50 /**
51 * Status: Article update aborted by a hook function
53 const AS_HOOK_ERROR = 210;
55 /**
56 * Status: A hook function returned an error
58 const AS_HOOK_ERROR_EXPECTED = 212;
60 /**
61 * Status: User is blocked from editing this page
63 const AS_BLOCKED_PAGE_FOR_USER = 215;
65 /**
66 * Status: Content too big (> $wgMaxArticleSize)
68 const AS_CONTENT_TOO_BIG = 216;
70 /**
71 * Status: User cannot edit? (not used)
73 const AS_USER_CANNOT_EDIT = 217;
75 /**
76 * Status: this anonymous user is not allowed to edit this page
78 const AS_READ_ONLY_PAGE_ANON = 218;
80 /**
81 * Status: this logged in user is not allowed to edit this page
83 const AS_READ_ONLY_PAGE_LOGGED = 219;
85 /**
86 * Status: wiki is in readonly mode (wfReadOnly() == true)
88 const AS_READ_ONLY_PAGE = 220;
90 /**
91 * Status: rate limiter for action 'edit' was tripped
93 const AS_RATE_LIMITED = 221;
95 /**
96 * Status: article was deleted while editing and param wpRecreate == false or form
97 * was not posted
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;
134 * not used
136 const AS_OK = 230;
139 * Status: WikiPage::doEdit() was unsuccessful
141 const AS_END = 231;
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;
189 * @var Article
191 var $mArticle;
194 * @var Title
196 var $mTitle;
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;
206 var $formtype;
207 var $firsttime;
208 var $lastDelete;
209 var $mTokenOk = false;
210 var $mTokenOkExceptSuffix = false;
211 var $mTriedSave = false;
212 var $incompleteForm = false;
213 var $tooBig = false;
214 var $kblength = false;
215 var $missingComment = false;
216 var $missingSummary = false;
217 var $allowBlankSummary = false;
218 var $autoSumm = '';
219 var $hookError = '';
220 #var $mPreviewTemplates;
223 * @var ParserOutput
225 var $mParserOutput;
228 * Has a summary been preset using GET parameter &summary= ?
229 * @var Bool
231 var $hasPresetSummary = false;
233 var $mBaseRevision = false;
234 var $mShowSummaryField = true;
236 # Form values
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.
265 * @var bool
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();
283 * @return Article
285 public function getArticle() {
286 return $this->mArticle;
290 * @since 1.19
291 * @return Title
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 ) ) {
315 global $wgTitle;
316 return $wgTitle;
317 } else {
318 return $this->mContextTitle;
322 function submit() {
323 $this->edit();
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.
337 function edit() {
338 global $wgOut, $wgRequest, $wgUser;
339 // Allow extensions to modify/prevent this form or submission
340 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
341 return;
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__ );
351 return;
354 $this->importFormData( $wgRequest );
355 $this->firsttime = false;
357 if ( $this->live ) {
358 $this->livePreview();
359 wfProfileOut( __METHOD__ );
360 return;
363 if ( wfReadOnly() && $this->save ) {
364 // Force preview
365 $this->save = false;
366 $this->preview = true;
369 if ( $this->save ) {
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';
379 } else {
380 $this->formtype = 'initial';
384 $permErrors = $this->getEditPermissionErrors();
385 if ( $permErrors ) {
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__ );
393 return;
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 ) {
407 $this->showIntro();
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__ );
419 return;
423 # First time through: get contents, set time for conflict
424 # checking, etc.
425 if ( 'initial' == $this->formtype || $this->firsttime ) {
426 if ( $this->initialiseForm() === false ) {
427 $this->noSuchSectionPage();
428 wfProfileOut( __METHOD__ . "-business-end" );
429 wfProfileOut( __METHOD__ );
430 return;
433 if ( !$this->mTitle->getArticleID() ) {
434 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
435 } else {
436 wfRunHooks( 'EditFormInitialText', array( $this ) );
441 $this->showEditForm();
442 wfProfileOut( __METHOD__ . "-business-end" );
443 wfProfileOut( __METHOD__ );
447 * @return array
449 protected function getEditPermissionErrors() {
450 global $wgUser;
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
458 $remove = array();
459 foreach ( $permErrors as $error ) {
460 if ( ( $this->preview || $this->diff ) &&
461 ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' ) )
463 $remove[] = $error;
466 $permErrors = wfArrayDiff2( $permErrors, $remove );
467 return $permErrors;
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.
478 * @since 1.19
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() );
491 return;
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' );
514 } else {
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() );
546 } else {
547 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
552 * Should we show a preview when the edit form is first shown?
554 * @return bool
556 protected function previewOnOpen() {
557 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
558 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
559 // Explicit override from request
560 return true;
561 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
562 // Explicit override from request
563 return false;
564 } elseif ( $this->section == 'new' ) {
565 // Nothing *to* preview for new sections
566 return false;
567 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
568 // Standard preference behavior
569 return true;
570 } elseif ( !$this->mTitle->exists() &&
571 isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] ) &&
572 $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
574 // Categories are special
575 return true;
576 } else {
577 return false;
582 * Checks whether the user entered a skin name in uppercase,
583 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
585 * @return bool
587 protected function isWrongCaseCssJsPage() {
588 if ( $this->mTitle->isCssJsSubpage() ) {
589 $name = $this->mTitle->getSkinFromCssJsSubpage();
590 $skins = array_merge(
591 array_keys( Skin::getSkinNames() ),
592 array( 'common' )
594 return !in_array( $name, $skins )
595 && in_array( strtolower( $name ), $skins );
596 } else {
597 return false;
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
655 # section titles.
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 $undidRev = $request->getInt( 'wpUndidRevision' );
670 if ( $undidRev ) {
671 $this->undidRev = $undidRev;
674 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
676 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
677 // wpTextbox1 field is missing, possibly due to being "too big"
678 // according to some filter rules such as Suhosin's setting for
679 // suhosin.request.max_value_length (d'oh)
680 $this->incompleteForm = true;
681 } else {
682 // edittime should be one of our last fields; if it's missing,
683 // the submission probably broke somewhere in the middle.
684 $this->incompleteForm = is_null( $this->edittime );
686 if ( $this->incompleteForm ) {
687 # If the form is incomplete, force to preview.
688 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
689 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
690 $this->preview = true;
691 } else {
692 /* Fallback for live preview */
693 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
694 $this->diff = $request->getCheck( 'wpDiff' );
696 // Remember whether a save was requested, so we can indicate
697 // if we forced preview due to session failure.
698 $this->mTriedSave = !$this->preview;
700 if ( $this->tokenOk( $request ) ) {
701 # Some browsers will not report any submit button
702 # if the user hits enter in the comment box.
703 # The unmarked state will be assumed to be a save,
704 # if the form seems otherwise complete.
705 wfDebug( __METHOD__ . ": Passed token check.\n" );
706 } elseif ( $this->diff ) {
707 # Failed token check, but only requested "Show Changes".
708 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
709 } else {
710 # Page might be a hack attempt posted from
711 # an external site. Preview instead of saving.
712 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
713 $this->preview = true;
716 $this->save = !$this->preview && !$this->diff;
717 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
718 $this->edittime = null;
721 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
722 $this->starttime = null;
725 $this->recreate = $request->getCheck( 'wpRecreate' );
727 $this->minoredit = $request->getCheck( 'wpMinoredit' );
728 $this->watchthis = $request->getCheck( 'wpWatchthis' );
730 # Don't force edit summaries when a user is editing their own user or talk page
731 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) &&
732 $this->mTitle->getText() == $wgUser->getName() )
734 $this->allowBlankSummary = true;
735 } else {
736 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' ) || !$wgUser->getOption( 'forceeditsummary' );
739 $this->autoSumm = $request->getText( 'wpAutoSummary' );
740 } else {
741 # Not a posted form? Start with nothing.
742 wfDebug( __METHOD__ . ": Not a posted form.\n" );
743 $this->textbox1 = '';
744 $this->summary = '';
745 $this->sectiontitle = '';
746 $this->edittime = '';
747 $this->starttime = wfTimestampNow();
748 $this->edit = false;
749 $this->preview = false;
750 $this->save = false;
751 $this->diff = false;
752 $this->minoredit = false;
753 $this->watchthis = $request->getBool( 'watchthis', false ); // Watch may be overridden by request parameters
754 $this->recreate = false;
756 // When creating a new section, we can preload a section title by passing it as the
757 // preloadtitle parameter in the URL (Bug 13100)
758 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
759 $this->sectiontitle = $request->getVal( 'preloadtitle' );
760 // Once wpSummary isn't being use for setting section titles, we should delete this.
761 $this->summary = $request->getVal( 'preloadtitle' );
763 elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
764 $this->summary = $request->getText( 'summary' );
765 if ( $this->summary !== '' ) {
766 $this->hasPresetSummary = true;
770 if ( $request->getVal( 'minor' ) ) {
771 $this->minoredit = true;
775 $this->oldid = $request->getInt( 'oldid' );
777 $this->bot = $request->getBool( 'bot', true );
778 $this->nosummary = $request->getBool( 'nosummary' );
780 $content_handler = ContentHandler::getForTitle( $this->mTitle );
781 $this->contentModel = $request->getText( 'model', $content_handler->getModelID() ); #may be overridden by revision
782 $this->contentFormat = $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
784 #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
785 #TODO: check if the desired content model supports the given content format!
787 $this->live = $request->getCheck( 'live' );
788 $this->editintro = $request->getText( 'editintro',
789 // Custom edit intro for new sections
790 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
792 // Allow extensions to modify form data
793 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
795 wfProfileOut( __METHOD__ );
799 * Subpage overridable method for extracting the page content data from the
800 * posted form to be placed in $this->textbox1, if using customized input
801 * this method should be overridden and return the page text that will be used
802 * for saving, preview parsing and so on...
804 * @param $request WebRequest
806 protected function importContentFormData( &$request ) {
807 return; // Don't do anything, EditPage already extracted wpTextbox1
811 * Initialise form fields in the object
812 * Called on the first invocation, e.g. when a user clicks an edit link
813 * @return bool -- if the requested section is valid
815 function initialiseForm() {
816 global $wgUser;
817 $this->edittime = $this->mArticle->getTimestamp();
819 $content = $this->getContentObject( false ); #TODO: track content object?!
820 if ( $content === false ) {
821 return false;
823 $this->textbox1 = $this->toEditText( $content );
825 // activate checkboxes if user wants them to be always active
826 # Sort out the "watch" checkbox
827 if ( $wgUser->getOption( 'watchdefault' ) ) {
828 # Watch all edits
829 $this->watchthis = true;
830 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
831 # Watch creations
832 $this->watchthis = true;
833 } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
834 # Already watched
835 $this->watchthis = true;
837 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
838 $this->minoredit = true;
840 if ( $this->textbox1 === false ) {
841 return false;
843 return true;
847 * Fetch initial editing page content.
849 * @param $def_text string|bool
850 * @return mixed string on success, $def_text for invalid sections
851 * @private
852 * @deprecated since 1.21, get WikiPage::getContent() instead.
854 function getContent( $def_text = false ) {
855 ContentHandler::deprecated( __METHOD__, '1.21' );
857 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
858 $def_content = $this->toEditContent( $def_text );
859 } else {
860 $def_content = false;
863 $content = $this->getContentObject( $def_content );
865 // Note: EditPage should only be used with text based content anyway.
866 return $this->toEditText( $content );
870 * @param Content|null $def_content The default value to return
872 * @return mixed Content on success, $def_content for invalid sections
874 * @since 1.21
876 protected function getContentObject( $def_content = null ) {
877 global $wgOut, $wgRequest;
879 wfProfileIn( __METHOD__ );
881 $content = false;
883 // For message page not locally set, use the i18n message.
884 // For other non-existent articles, use preload text if any.
885 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
886 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
887 # If this is a system message, get the default text.
888 $msg = $this->mTitle->getDefaultMessageText();
890 $content = $this->toEditContent( $msg );
892 if ( $content === false ) {
893 # If requested, preload some text.
894 $preload = $wgRequest->getVal( 'preload',
895 // Custom preload text for new sections
896 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
898 $content = $this->getPreloadedContent( $preload );
900 // For existing pages, get text based on "undo" or section parameters.
901 } else {
902 if ( $this->section != '' ) {
903 // Get section edit text (returns $def_text for invalid sections)
904 $orig = $this->getOriginalContent();
905 $content = $orig ? $orig->getSection( $this->section ) : null;
907 if ( !$content ) {
908 $content = $def_content;
910 } else {
911 $undoafter = $wgRequest->getInt( 'undoafter' );
912 $undo = $wgRequest->getInt( 'undo' );
914 if ( $undo > 0 && $undoafter > 0 ) {
915 if ( $undo < $undoafter ) {
916 # If they got undoafter and undo round the wrong way, switch them
917 list( $undo, $undoafter ) = array( $undoafter, $undo );
920 $undorev = Revision::newFromId( $undo );
921 $oldrev = Revision::newFromId( $undoafter );
923 # Sanity check, make sure it's the right page,
924 # the revisions exist and they were not deleted.
925 # Otherwise, $content will be left as-is.
926 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
927 $undorev->getPage() == $oldrev->getPage() &&
928 $undorev->getPage() == $this->mTitle->getArticleID() &&
929 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
930 !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
932 $content = $this->mArticle->getUndoContent( $undorev, $oldrev );
934 if ( $content === false ) {
935 # Warn the user that something went wrong
936 $undoMsg = 'failure';
937 } else {
938 # Inform the user of our success and set an automatic edit summary
939 $undoMsg = 'success';
941 # If we just undid one rev, use an autosummary
942 $firstrev = $oldrev->getNext();
943 if ( $firstrev && $firstrev->getId() == $undo ) {
944 $userText = $undorev->getUserText();
945 if ( $userText === '' ) {
946 $undoSummary = wfMessage(
947 'undo-summary-username-hidden',
948 $undo
949 )->inContentLanguage()->text();
950 } else {
951 $undoSummary = wfMessage(
952 'undo-summary',
953 $undo,
954 $userText
955 )->inContentLanguage()->text();
957 if ( $this->summary === '' ) {
958 $this->summary = $undoSummary;
959 } else {
960 $this->summary = $undoSummary . wfMessage( 'colon-separator' )
961 ->inContentLanguage()->text() . $this->summary;
963 $this->undidRev = $undo;
965 $this->formtype = 'diff';
967 } else {
968 // Failed basic sanity checks.
969 // Older revisions may have been removed since the link
970 // was created, or we may simply have got bogus input.
971 $undoMsg = 'norev';
974 // Messages: undo-success, undo-failure, undo-norev
975 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
976 $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
977 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
980 if ( $content === false ) {
981 $content = $this->getOriginalContent();
986 wfProfileOut( __METHOD__ );
987 return $content;
991 * Get the content of the wanted revision, without section extraction.
993 * The result of this function can be used to compare user's input with
994 * section replaced in its context (using WikiPage::replaceSection())
995 * to the original text of the edit.
997 * This differs from Article::getContent() that when a missing revision is
998 * encountered the result will be null and not the
999 * 'missing-revision' message.
1001 * @since 1.19
1002 * @return Content|null
1004 private function getOriginalContent() {
1005 if ( $this->section == 'new' ) {
1006 return $this->getCurrentContent();
1008 $revision = $this->mArticle->getRevisionFetched();
1009 if ( $revision === null ) {
1010 if ( !$this->contentModel ) {
1011 $this->contentModel = $this->getTitle()->getContentModel();
1013 $handler = ContentHandler::getForModelID( $this->contentModel );
1015 return $handler->makeEmptyContent();
1017 $content = $revision->getContent();
1018 return $content;
1022 * Get the current content of the page. This is basically similar to
1023 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1024 * content object is returned instead of null.
1026 * @since 1.21
1027 * @return Content
1029 protected function getCurrentContent() {
1030 $rev = $this->mArticle->getRevision();
1031 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1033 if ( $content === false || $content === null ) {
1034 if ( !$this->contentModel ) {
1035 $this->contentModel = $this->getTitle()->getContentModel();
1037 $handler = ContentHandler::getForModelID( $this->contentModel );
1039 return $handler->makeEmptyContent();
1040 } else {
1041 # nasty side-effect, but needed for consistency
1042 $this->contentModel = $rev->getContentModel();
1043 $this->contentFormat = $rev->getContentFormat();
1045 return $content;
1050 * Use this method before edit() to preload some text into the edit box
1052 * @param $text string
1053 * @deprecated since 1.21, use setPreloadedContent() instead.
1055 public function setPreloadedText( $text ) {
1056 ContentHandler::deprecated( __METHOD__, "1.21" );
1058 $content = $this->toEditContent( $text );
1060 $this->setPreloadedContent( $content );
1064 * Use this method before edit() to preload some content into the edit box
1066 * @param $content Content
1068 * @since 1.21
1070 public function setPreloadedContent( Content $content ) {
1071 $this->mPreloadContent = $content;
1075 * Get the contents to be preloaded into the box, either set by
1076 * an earlier setPreloadText() or by loading the given page.
1078 * @param string $preload representing the title to preload from.
1080 * @return String
1082 * @deprecated since 1.21, use getPreloadedContent() instead
1084 protected function getPreloadedText( $preload ) {
1085 ContentHandler::deprecated( __METHOD__, "1.21" );
1087 $content = $this->getPreloadedContent( $preload );
1088 $text = $this->toEditText( $content );
1090 return $text;
1094 * Get the contents to be preloaded into the box, either set by
1095 * an earlier setPreloadText() or by loading the given page.
1097 * @param string $preload representing the title to preload from.
1099 * @return Content
1101 * @since 1.21
1103 protected function getPreloadedContent( $preload ) {
1104 global $wgUser;
1106 if ( !empty( $this->mPreloadContent ) ) {
1107 return $this->mPreloadContent;
1110 $handler = ContentHandler::getForTitle( $this->getTitle() );
1112 if ( $preload === '' ) {
1113 return $handler->makeEmptyContent();
1116 $title = Title::newFromText( $preload );
1117 # Check for existence to avoid getting MediaWiki:Noarticletext
1118 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1119 //TODO: somehow show a warning to the user!
1120 return $handler->makeEmptyContent();
1123 $page = WikiPage::factory( $title );
1124 if ( $page->isRedirect() ) {
1125 $title = $page->getRedirectTarget();
1126 # Same as before
1127 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1128 //TODO: somehow show a warning to the user!
1129 return $handler->makeEmptyContent();
1131 $page = WikiPage::factory( $title );
1134 $parserOptions = ParserOptions::newFromUser( $wgUser );
1135 $content = $page->getContent( Revision::RAW );
1137 if ( !$content ) {
1138 //TODO: somehow show a warning to the user!
1139 return $handler->makeEmptyContent();
1142 if ( $content->getModel() !== $handler->getModelID() ) {
1143 $converted = $content->convert( $handler->getModelID() );
1145 if ( !$converted ) {
1146 //TODO: somehow show a warning to the user!
1147 wfDebug( "Attempt to preload incompatible content: "
1148 . "can't convert " . $content->getModel()
1149 . " to " . $handler->getModelID() );
1151 return $handler->makeEmptyContent();
1154 $content = $converted;
1157 return $content->preloadTransform( $title, $parserOptions );
1161 * Make sure the form isn't faking a user's credentials.
1163 * @param $request WebRequest
1164 * @return bool
1165 * @private
1167 function tokenOk( &$request ) {
1168 global $wgUser;
1169 $token = $request->getVal( 'wpEditToken' );
1170 $this->mTokenOk = $wgUser->matchEditToken( $token );
1171 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1172 return $this->mTokenOk;
1176 * Sets post-edit cookie indicating the user just saved a particular revision.
1178 * This uses a temporary cookie for each revision ID so separate saves will never
1179 * interfere with each other.
1181 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1182 * the redirect. It must be clearable by JavaScript code, so it must not be
1183 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1184 * variable.
1186 * We use a path of '/' since wgCookiePath is not exposed to JS
1188 * If the variable were set on the server, it would be cached, which is unwanted
1189 * since the post-edit state should only apply to the load right after the save.
1191 protected function setPostEditCookie() {
1192 $revisionId = $this->mArticle->getLatest();
1193 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1195 $response = RequestContext::getMain()->getRequest()->response();
1196 $response->setcookie( $postEditKey, '1', time() + self::POST_EDIT_COOKIE_DURATION, array(
1197 'path' => '/',
1198 'httpOnly' => false,
1199 ) );
1203 * Attempt submission
1204 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1205 * @return bool false if output is done, true if the rest of the form should be displayed
1207 function attemptSave() {
1208 global $wgUser, $wgOut;
1210 $resultDetails = false;
1211 # Allow bots to exempt some edits from bot flagging
1212 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1213 $status = $this->internalAttemptSave( $resultDetails, $bot );
1214 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1215 if ( $status->value == self::AS_SUCCESS_UPDATE || $status->value == self::AS_SUCCESS_NEW_ARTICLE ) {
1216 $this->didSave = true;
1217 if ( !$resultDetails['nullEdit'] ) {
1218 $this->setPostEditCookie();
1222 switch ( $status->value ) {
1223 case self::AS_HOOK_ERROR_EXPECTED:
1224 case self::AS_CONTENT_TOO_BIG:
1225 case self::AS_ARTICLE_WAS_DELETED:
1226 case self::AS_CONFLICT_DETECTED:
1227 case self::AS_SUMMARY_NEEDED:
1228 case self::AS_TEXTBOX_EMPTY:
1229 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1230 case self::AS_END:
1231 return true;
1233 case self::AS_HOOK_ERROR:
1234 return false;
1236 case self::AS_PARSE_ERROR:
1237 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1238 return true;
1240 case self::AS_SUCCESS_NEW_ARTICLE:
1241 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1242 $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1243 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1244 return false;
1246 case self::AS_SUCCESS_UPDATE:
1247 $extraQuery = '';
1248 $sectionanchor = $resultDetails['sectionanchor'];
1250 // Give extensions a chance to modify URL query on update
1251 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle, &$sectionanchor, &$extraQuery ) );
1253 if ( $resultDetails['redirect'] ) {
1254 if ( $extraQuery == '' ) {
1255 $extraQuery = 'redirect=no';
1256 } else {
1257 $extraQuery = 'redirect=no&' . $extraQuery;
1260 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1261 return false;
1263 case self::AS_BLANK_ARTICLE:
1264 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1265 return false;
1267 case self::AS_SPAM_ERROR:
1268 $this->spamPageWithContent( $resultDetails['spam'] );
1269 return false;
1271 case self::AS_BLOCKED_PAGE_FOR_USER:
1272 throw new UserBlockedError( $wgUser->getBlock() );
1274 case self::AS_IMAGE_REDIRECT_ANON:
1275 case self::AS_IMAGE_REDIRECT_LOGGED:
1276 throw new PermissionsError( 'upload' );
1278 case self::AS_READ_ONLY_PAGE_ANON:
1279 case self::AS_READ_ONLY_PAGE_LOGGED:
1280 throw new PermissionsError( 'edit' );
1282 case self::AS_READ_ONLY_PAGE:
1283 throw new ReadOnlyError;
1285 case self::AS_RATE_LIMITED:
1286 throw new ThrottledError();
1288 case self::AS_NO_CREATE_PERMISSION:
1289 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1290 throw new PermissionsError( $permission );
1292 default:
1293 // We don't recognize $status->value. The only way that can happen
1294 // is if an extension hook aborted from inside ArticleSave.
1295 // Render the status object into $this->hookError
1296 // FIXME this sucks, we should just use the Status object throughout
1297 $this->hookError = '<div class="error">' . $status->getWikitext() .
1298 '</div>';
1299 return true;
1304 * Run hooks that can filter edits just before they get saved.
1306 * @param Content $content the Content to filter.
1307 * @param Status $status for reporting the outcome to the caller
1308 * @param User $user the user performing the edit
1310 * @return bool
1312 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1313 // Run old style post-section-merge edit filter
1314 if ( !ContentHandler::runLegacyHooks( 'EditFilterMerged',
1315 array( $this, $content, &$this->hookError, $this->summary ) ) ) {
1317 # Error messages etc. could be handled within the hook...
1318 $status->fatal( 'hookaborted' );
1319 $status->value = self::AS_HOOK_ERROR;
1320 return false;
1321 } elseif ( $this->hookError != '' ) {
1322 # ...or the hook could be expecting us to produce an error
1323 $status->fatal( 'hookaborted' );
1324 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1325 return false;
1328 // Run new style post-section-merge edit filter
1329 if ( !wfRunHooks( 'EditFilterMergedContent',
1330 array( $this->mArticle->getContext(), $content, $status, $this->summary,
1331 $user, $this->minoredit ) ) ) {
1333 # Error messages etc. could be handled within the hook...
1334 // XXX: $status->value may already be something informative...
1335 $this->hookError = $status->getWikiText();
1336 $status->fatal( 'hookaborted' );
1337 $status->value = self::AS_HOOK_ERROR;
1338 return false;
1339 } elseif ( !$status->isOK() ) {
1340 # ...or the hook could be expecting us to produce an error
1341 // FIXME this sucks, we should just use the Status object throughout
1342 $this->hookError = $status->getWikiText();
1343 $status->fatal( 'hookaborted' );
1344 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1345 return false;
1348 return true;
1352 * Attempt submission (no UI)
1354 * @param array $result array to add statuses to, currently with the possible keys:
1355 * spam - string - Spam string from content if any spam is detected by matchSpamRegex
1356 * sectionanchor - string - Section anchor for a section save
1357 * nullEdit - boolean - Set if doEditContent is OK. True if null edit, false otherwise.
1358 * redirect - boolean - Set if doEditContent is OK. True if resulting revision is a redirect
1359 * @param bool $bot True if edit is being made under the bot right.
1361 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1363 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1364 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1365 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1367 function internalAttemptSave( &$result, $bot = false ) {
1368 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1370 $status = Status::newGood();
1372 wfProfileIn( __METHOD__ );
1373 wfProfileIn( __METHOD__ . '-checks' );
1375 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1376 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1377 $status->fatal( 'hookaborted' );
1378 $status->value = self::AS_HOOK_ERROR;
1379 wfProfileOut( __METHOD__ . '-checks' );
1380 wfProfileOut( __METHOD__ );
1381 return $status;
1384 $spam = $wgRequest->getText( 'wpAntispam' );
1385 if ( $spam !== '' ) {
1386 wfDebugLog(
1387 'SimpleAntiSpam',
1388 $wgUser->getName() .
1389 ' editing "' .
1390 $this->mTitle->getPrefixedText() .
1391 '" submitted bogus field "' .
1392 $spam .
1395 $status->fatal( 'spamprotectionmatch', false );
1396 $status->value = self::AS_SPAM_ERROR;
1397 wfProfileOut( __METHOD__ . '-checks' );
1398 wfProfileOut( __METHOD__ );
1399 return $status;
1402 try {
1403 # Construct Content object
1404 $textbox_content = $this->toEditContent( $this->textbox1 );
1405 } catch ( MWContentSerializationException $ex ) {
1406 $status->fatal( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
1407 $status->value = self::AS_PARSE_ERROR;
1408 wfProfileOut( __METHOD__ . '-checks' );
1409 wfProfileOut( __METHOD__ );
1410 return $status;
1413 # Check image redirect
1414 if ( $this->mTitle->getNamespace() == NS_FILE &&
1415 $textbox_content->isRedirect() &&
1416 !$wgUser->isAllowed( 'upload' ) ) {
1417 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1418 $status->setResult( false, $code );
1420 wfProfileOut( __METHOD__ . '-checks' );
1421 wfProfileOut( __METHOD__ );
1423 return $status;
1426 # Check for spam
1427 $match = self::matchSummarySpamRegex( $this->summary );
1428 if ( $match === false && $this->section == 'new' ) {
1429 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1430 # regular summaries, it is added to the actual wikitext.
1431 if ( $this->sectiontitle !== '' ) {
1432 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1433 $match = self::matchSpamRegex( $this->sectiontitle );
1434 } else {
1435 # This branch is taken when the "Add Topic" user interface is used, or the API
1436 # is used with the 'summary' parameter.
1437 $match = self::matchSpamRegex( $this->summary );
1440 if ( $match === false ) {
1441 $match = self::matchSpamRegex( $this->textbox1 );
1443 if ( $match !== false ) {
1444 $result['spam'] = $match;
1445 $ip = $wgRequest->getIP();
1446 $pdbk = $this->mTitle->getPrefixedDBkey();
1447 $match = str_replace( "\n", '', $match );
1448 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1449 $status->fatal( 'spamprotectionmatch', $match );
1450 $status->value = self::AS_SPAM_ERROR;
1451 wfProfileOut( __METHOD__ . '-checks' );
1452 wfProfileOut( __METHOD__ );
1453 return $status;
1455 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
1456 # Error messages etc. could be handled within the hook...
1457 $status->fatal( 'hookaborted' );
1458 $status->value = self::AS_HOOK_ERROR;
1459 wfProfileOut( __METHOD__ . '-checks' );
1460 wfProfileOut( __METHOD__ );
1461 return $status;
1462 } elseif ( $this->hookError != '' ) {
1463 # ...or the hook could be expecting us to produce an error
1464 $status->fatal( 'hookaborted' );
1465 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1466 wfProfileOut( __METHOD__ . '-checks' );
1467 wfProfileOut( __METHOD__ );
1468 return $status;
1471 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1472 // Auto-block user's IP if the account was "hard" blocked
1473 $wgUser->spreadAnyEditBlock();
1474 # Check block state against master, thus 'false'.
1475 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1476 wfProfileOut( __METHOD__ . '-checks' );
1477 wfProfileOut( __METHOD__ );
1478 return $status;
1481 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1482 if ( $this->kblength > $wgMaxArticleSize ) {
1483 // Error will be displayed by showEditForm()
1484 $this->tooBig = true;
1485 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1486 wfProfileOut( __METHOD__ . '-checks' );
1487 wfProfileOut( __METHOD__ );
1488 return $status;
1491 if ( !$wgUser->isAllowed( 'edit' ) ) {
1492 if ( $wgUser->isAnon() ) {
1493 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1494 wfProfileOut( __METHOD__ . '-checks' );
1495 wfProfileOut( __METHOD__ );
1496 return $status;
1497 } else {
1498 $status->fatal( 'readonlytext' );
1499 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1500 wfProfileOut( __METHOD__ . '-checks' );
1501 wfProfileOut( __METHOD__ );
1502 return $status;
1506 if ( wfReadOnly() ) {
1507 $status->fatal( 'readonlytext' );
1508 $status->value = self::AS_READ_ONLY_PAGE;
1509 wfProfileOut( __METHOD__ . '-checks' );
1510 wfProfileOut( __METHOD__ );
1511 return $status;
1513 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1514 $status->fatal( 'actionthrottledtext' );
1515 $status->value = self::AS_RATE_LIMITED;
1516 wfProfileOut( __METHOD__ . '-checks' );
1517 wfProfileOut( __METHOD__ );
1518 return $status;
1521 # If the article has been deleted while editing, don't save it without
1522 # confirmation
1523 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1524 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1525 wfProfileOut( __METHOD__ . '-checks' );
1526 wfProfileOut( __METHOD__ );
1527 return $status;
1530 wfProfileOut( __METHOD__ . '-checks' );
1532 # Load the page data from the master. If anything changes in the meantime,
1533 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1534 $this->mArticle->loadPageData( 'fromdbmaster' );
1535 $new = !$this->mArticle->exists();
1537 if ( $new ) {
1538 // Late check for create permission, just in case *PARANOIA*
1539 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1540 $status->fatal( 'nocreatetext' );
1541 $status->value = self::AS_NO_CREATE_PERMISSION;
1542 wfDebug( __METHOD__ . ": no create permission\n" );
1543 wfProfileOut( __METHOD__ );
1544 return $status;
1547 // Don't save a new page if it's blank or if it's a MediaWiki:
1548 // message with content equivalent to default (allow empty pages
1549 // in this case to disable messages, see bug 50124)
1550 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1551 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1552 $defaultText = $defaultMessageText;
1553 } else {
1554 $defaultText = '';
1557 if ( $this->textbox1 === $defaultText ) {
1558 $status->setResult( false, self::AS_BLANK_ARTICLE );
1559 wfProfileOut( __METHOD__ );
1560 return $status;
1563 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1564 wfProfileOut( __METHOD__ );
1565 return $status;
1568 $content = $textbox_content;
1570 $result['sectionanchor'] = '';
1571 if ( $this->section == 'new' ) {
1572 if ( $this->sectiontitle !== '' ) {
1573 // Insert the section title above the content.
1574 $content = $content->addSectionHeader( $this->sectiontitle );
1576 // Jump to the new section
1577 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1579 // If no edit summary was specified, create one automatically from the section
1580 // title and have it link to the new section. Otherwise, respect the summary as
1581 // passed.
1582 if ( $this->summary === '' ) {
1583 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1584 $this->summary = wfMessage( 'newsectionsummary' )
1585 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1587 } elseif ( $this->summary !== '' ) {
1588 // Insert the section title above the content.
1589 $content = $content->addSectionHeader( $this->summary );
1591 // Jump to the new section
1592 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1594 // Create a link to the new section from the edit summary.
1595 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1596 $this->summary = wfMessage( 'newsectionsummary' )
1597 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1601 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1603 } else { # not $new
1605 # Article exists. Check for edit conflict.
1607 $this->mArticle->clear(); # Force reload of dates, etc.
1608 $timestamp = $this->mArticle->getTimestamp();
1610 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1612 if ( $timestamp != $this->edittime ) {
1613 $this->isConflict = true;
1614 if ( $this->section == 'new' ) {
1615 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
1616 $this->mArticle->getComment() == $this->summary ) {
1617 // Probably a duplicate submission of a new comment.
1618 // This can happen when squid resends a request after
1619 // a timeout but the first one actually went through.
1620 wfDebug( __METHOD__ . ": duplicate new section submission; trigger edit conflict!\n" );
1621 } else {
1622 // New comment; suppress conflict.
1623 $this->isConflict = false;
1624 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1626 } elseif ( $this->section == '' && Revision::userWasLastToEdit( DB_MASTER, $this->mTitle->getArticleID(),
1627 $wgUser->getId(), $this->edittime ) ) {
1628 # Suppress edit conflict with self, except for section edits where merging is required.
1629 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1630 $this->isConflict = false;
1634 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1635 if ( $this->sectiontitle !== '' ) {
1636 $sectionTitle = $this->sectiontitle;
1637 } else {
1638 $sectionTitle = $this->summary;
1641 $content = null;
1643 if ( $this->isConflict ) {
1644 wfDebug( __METHOD__ . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1645 . " (article time '{$timestamp}')\n" );
1647 $content = $this->mArticle->replaceSectionContent( $this->section, $textbox_content, $sectionTitle, $this->edittime );
1648 } else {
1649 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
1650 $content = $this->mArticle->replaceSectionContent( $this->section, $textbox_content, $sectionTitle );
1653 if ( is_null( $content ) ) {
1654 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1655 $this->isConflict = true;
1656 $content = $textbox_content; // do not try to merge here!
1657 } elseif ( $this->isConflict ) {
1658 # Attempt merge
1659 if ( $this->mergeChangesIntoContent( $content ) ) {
1660 // Successful merge! Maybe we should tell the user the good news?
1661 $this->isConflict = false;
1662 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1663 } else {
1664 $this->section = '';
1665 $this->textbox1 = ContentHandler::getContentText( $content );
1666 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1670 if ( $this->isConflict ) {
1671 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1672 wfProfileOut( __METHOD__ );
1673 return $status;
1676 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1677 wfProfileOut( __METHOD__ );
1678 return $status;
1681 if ( $this->section == 'new' ) {
1682 // Handle the user preference to force summaries here
1683 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
1684 $this->missingSummary = true;
1685 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1686 $status->value = self::AS_SUMMARY_NEEDED;
1687 wfProfileOut( __METHOD__ );
1688 return $status;
1691 // Do not allow the user to post an empty comment
1692 if ( $this->textbox1 == '' ) {
1693 $this->missingComment = true;
1694 $status->fatal( 'missingcommenttext' );
1695 $status->value = self::AS_TEXTBOX_EMPTY;
1696 wfProfileOut( __METHOD__ );
1697 return $status;
1699 } elseif ( !$this->allowBlankSummary
1700 && !$content->equals( $this->getOriginalContent() )
1701 && !$content->isRedirect()
1702 && md5( $this->summary ) == $this->autoSumm
1704 $this->missingSummary = true;
1705 $status->fatal( 'missingsummary' );
1706 $status->value = self::AS_SUMMARY_NEEDED;
1707 wfProfileOut( __METHOD__ );
1708 return $status;
1711 # All's well
1712 wfProfileIn( __METHOD__ . '-sectionanchor' );
1713 $sectionanchor = '';
1714 if ( $this->section == 'new' ) {
1715 if ( $this->sectiontitle !== '' ) {
1716 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1717 // If no edit summary was specified, create one automatically from the section
1718 // title and have it link to the new section. Otherwise, respect the summary as
1719 // passed.
1720 if ( $this->summary === '' ) {
1721 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1722 $this->summary = wfMessage( 'newsectionsummary' )
1723 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1725 } elseif ( $this->summary !== '' ) {
1726 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1727 # This is a new section, so create a link to the new section
1728 # in the revision summary.
1729 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1730 $this->summary = wfMessage( 'newsectionsummary' )
1731 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1733 } elseif ( $this->section != '' ) {
1734 # Try to get a section anchor from the section source, redirect to edited section if header found
1735 # XXX: might be better to integrate this into Article::replaceSection
1736 # for duplicate heading checking and maybe parsing
1737 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1738 # we can't deal with anchors, includes, html etc in the header for now,
1739 # headline would need to be parsed to improve this
1740 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1741 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1744 $result['sectionanchor'] = $sectionanchor;
1745 wfProfileOut( __METHOD__ . '-sectionanchor' );
1747 // Save errors may fall down to the edit form, but we've now
1748 // merged the section into full text. Clear the section field
1749 // so that later submission of conflict forms won't try to
1750 // replace that into a duplicated mess.
1751 $this->textbox1 = $this->toEditText( $content );
1752 $this->section = '';
1754 $status->value = self::AS_SUCCESS_UPDATE;
1757 // Check for length errors again now that the section is merged in
1758 $this->kblength = (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1759 if ( $this->kblength > $wgMaxArticleSize ) {
1760 $this->tooBig = true;
1761 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
1762 wfProfileOut( __METHOD__ );
1763 return $status;
1766 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1767 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1768 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1769 ( $bot ? EDIT_FORCE_BOT : 0 );
1771 $doEditStatus = $this->mArticle->doEditContent( $content, $this->summary, $flags,
1772 false, null, $this->contentFormat );
1774 if ( !$doEditStatus->isOK() ) {
1775 // Failure from doEdit()
1776 // Show the edit conflict page for certain recognized errors from doEdit(),
1777 // but don't show it for errors from extension hooks
1778 $errors = $doEditStatus->getErrorsArray();
1779 if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
1780 'edit-already-exists' ) ) )
1782 $this->isConflict = true;
1783 // Destroys data doEdit() put in $status->value but who cares
1784 $doEditStatus->value = self::AS_END;
1786 wfProfileOut( __METHOD__ );
1787 return $doEditStatus;
1790 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1791 if ( $result['nullEdit'] ) {
1792 // We don't know if it was a null edit until now, so increment here
1793 $wgUser->pingLimiter( 'linkpurge' );
1795 $result['redirect'] = $content->isRedirect();
1796 $this->updateWatchlist();
1797 wfProfileOut( __METHOD__ );
1798 return $status;
1802 * Register the change of watch status
1804 protected function updateWatchlist() {
1805 global $wgUser;
1807 if ( $wgUser->isLoggedIn()
1808 && $this->watchthis != $wgUser->isWatched( $this->mTitle, WatchedItem::IGNORE_USER_RIGHTS )
1810 $fname = __METHOD__;
1811 $title = $this->mTitle;
1812 $watch = $this->watchthis;
1814 // Do this in its own transaction to reduce contention...
1815 $dbw = wfGetDB( DB_MASTER );
1816 $dbw->onTransactionIdle( function() use ( $dbw, $title, $watch, $wgUser, $fname ) {
1817 $dbw->begin( $fname );
1818 WatchAction::doWatchOrUnwatch( $watch, $title, $wgUser );
1819 $dbw->commit( $fname );
1820 } );
1825 * Attempts to merge text content with base and current revisions
1827 * @param $editText string
1829 * @return bool
1830 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1832 function mergeChangesInto( &$editText ) {
1833 ContentHandler::deprecated( __METHOD__, "1.21" );
1835 $editContent = $this->toEditContent( $editText );
1837 $ok = $this->mergeChangesIntoContent( $editContent );
1839 if ( $ok ) {
1840 $editText = $this->toEditText( $editContent );
1841 return true;
1843 return false;
1847 * Attempts to do 3-way merge of edit content with a base revision
1848 * and current content, in case of edit conflict, in whichever way appropriate
1849 * for the content type.
1851 * @since 1.21
1853 * @param $editContent
1855 * @return bool
1857 private function mergeChangesIntoContent( &$editContent ) {
1858 wfProfileIn( __METHOD__ );
1860 $db = wfGetDB( DB_MASTER );
1862 // This is the revision the editor started from
1863 $baseRevision = $this->getBaseRevision();
1864 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
1866 if ( is_null( $baseContent ) ) {
1867 wfProfileOut( __METHOD__ );
1868 return false;
1871 // The current state, we want to merge updates into it
1872 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1873 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
1875 if ( is_null( $currentContent ) ) {
1876 wfProfileOut( __METHOD__ );
1877 return false;
1880 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
1882 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1884 if ( $result ) {
1885 $editContent = $result;
1886 wfProfileOut( __METHOD__ );
1887 return true;
1890 wfProfileOut( __METHOD__ );
1891 return false;
1895 * @return Revision
1897 function getBaseRevision() {
1898 if ( !$this->mBaseRevision ) {
1899 $db = wfGetDB( DB_MASTER );
1900 $baseRevision = Revision::loadFromTimestamp(
1901 $db, $this->mTitle, $this->edittime );
1902 return $this->mBaseRevision = $baseRevision;
1903 } else {
1904 return $this->mBaseRevision;
1909 * Check given input text against $wgSpamRegex, and return the text of the first match.
1911 * @param $text string
1913 * @return string|bool matching string or false
1915 public static function matchSpamRegex( $text ) {
1916 global $wgSpamRegex;
1917 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1918 $regexes = (array)$wgSpamRegex;
1919 return self::matchSpamRegexInternal( $text, $regexes );
1923 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
1925 * @param $text string
1927 * @return string|bool matching string or false
1929 public static function matchSummarySpamRegex( $text ) {
1930 global $wgSummarySpamRegex;
1931 $regexes = (array)$wgSummarySpamRegex;
1932 return self::matchSpamRegexInternal( $text, $regexes );
1936 * @param $text string
1937 * @param $regexes array
1938 * @return bool|string
1940 protected static function matchSpamRegexInternal( $text, $regexes ) {
1941 foreach ( $regexes as $regex ) {
1942 $matches = array();
1943 if ( preg_match( $regex, $text, $matches ) ) {
1944 return $matches[0];
1947 return false;
1950 function setHeaders() {
1951 global $wgOut, $wgUser;
1953 $wgOut->addModules( 'mediawiki.action.edit' );
1954 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
1956 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1957 $wgOut->addModules( 'mediawiki.action.edit.preview' );
1960 if ( $wgUser->getOption( 'useeditwarning', false ) ) {
1961 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
1964 // Bug #19334: textarea jumps when editing articles in IE8
1965 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1967 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1969 # Enabled article-related sidebar, toplinks, etc.
1970 $wgOut->setArticleRelated( true );
1972 $contextTitle = $this->getContextTitle();
1973 if ( $this->isConflict ) {
1974 $msg = 'editconflict';
1975 } elseif ( $contextTitle->exists() && $this->section != '' ) {
1976 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
1977 } else {
1978 $msg = $contextTitle->exists() || ( $contextTitle->getNamespace() == NS_MEDIAWIKI && $contextTitle->getDefaultMessageText() !== false ) ?
1979 'editing' : 'creating';
1981 # Use the title defined by DISPLAYTITLE magic word when present
1982 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
1983 if ( $displayTitle === false ) {
1984 $displayTitle = $contextTitle->getPrefixedText();
1986 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1990 * Show all applicable editing introductions
1992 protected function showIntro() {
1993 global $wgOut, $wgUser;
1994 if ( $this->suppressIntro ) {
1995 return;
1998 $namespace = $this->mTitle->getNamespace();
2000 if ( $namespace == NS_MEDIAWIKI ) {
2001 # Show a warning if editing an interface message
2002 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2003 } elseif ( $namespace == NS_FILE ) {
2004 # Show a hint to shared repo
2005 $file = wfFindFile( $this->mTitle );
2006 if ( $file && !$file->isLocal() ) {
2007 $descUrl = $file->getDescriptionUrl();
2008 # there must be a description url to show a hint to shared repo
2009 if ( $descUrl ) {
2010 if ( !$this->mTitle->exists() ) {
2011 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2012 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2013 ) );
2014 } else {
2015 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2016 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2017 ) );
2023 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2024 # Show log extract when the user is currently blocked
2025 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2026 $parts = explode( '/', $this->mTitle->getText(), 2 );
2027 $username = $parts[0];
2028 $user = User::newFromName( $username, false /* allow IP users*/ );
2029 $ip = User::isIP( $username );
2030 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2031 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2032 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2033 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
2034 LogEventsList::showLogExtract(
2035 $wgOut,
2036 'block',
2037 $user->getUserPage(),
2039 array(
2040 'lim' => 1,
2041 'showIfEmpty' => false,
2042 'msgKey' => array(
2043 'blocked-notice-logextract',
2044 $user->getName() # Support GENDER in notice
2050 # Try to add a custom edit intro, or use the standard one if this is not possible.
2051 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2052 if ( $wgUser->isLoggedIn() ) {
2053 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
2054 } else {
2055 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
2058 # Give a notice if the user is editing a deleted/moved page...
2059 if ( !$this->mTitle->exists() ) {
2060 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
2062 array(
2063 'lim' => 10,
2064 'conds' => array( "log_action != 'revision'" ),
2065 'showIfEmpty' => false,
2066 'msgKey' => array( 'recreate-moveddeleted-warn' )
2073 * Attempt to show a custom editing introduction, if supplied
2075 * @return bool
2077 protected function showCustomIntro() {
2078 if ( $this->editintro ) {
2079 $title = Title::newFromText( $this->editintro );
2080 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2081 global $wgOut;
2082 // Added using template syntax, to take <noinclude>'s into account.
2083 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle );
2084 return true;
2087 return false;
2091 * Gets an editable textual representation of $content.
2092 * The textual representation can be turned by into a Content object by the
2093 * toEditContent() method.
2095 * If $content is null or false or a string, $content is returned unchanged.
2097 * If the given Content object is not of a type that can be edited using the text base EditPage,
2098 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2099 * content.
2101 * @param Content|null|bool|string $content
2102 * @return String the editable text form of the content.
2104 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
2106 protected function toEditText( $content ) {
2107 if ( $content === null || $content === false ) {
2108 return $content;
2111 if ( is_string( $content ) ) {
2112 return $content;
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() ) );
2120 return $content->serialize( $this->contentFormat );
2124 * Turns the given text into a Content object by unserializing it.
2126 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
2127 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2128 * content.
2130 * @param string|null|bool $text Text to unserialize
2131 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
2132 * returned instead.
2134 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
2135 * and $this->allowNonTextContent is not true.
2137 protected function toEditContent( $text ) {
2138 if ( $text === false || $text === null ) {
2139 return $text;
2142 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2143 $this->contentModel, $this->contentFormat );
2145 if ( !$this->allowNonTextContent && !( $content instanceof TextContent ) ) {
2146 throw new MWException( "This content model can not be edited as text: "
2147 . ContentHandler::getLocalizedName( $content->getModel() ) );
2150 return $content;
2154 * Send the edit form and related headers to $wgOut
2155 * @param $formCallback Callback|null that takes an OutputPage parameter; will be called
2156 * during form output near the top, for captchas and the like.
2158 function showEditForm( $formCallback = null ) {
2159 global $wgOut, $wgUser;
2161 wfProfileIn( __METHOD__ );
2163 # need to parse the preview early so that we know which templates are used,
2164 # otherwise users with "show preview after edit box" will get a blank list
2165 # we parse this near the beginning so that setHeaders can do the title
2166 # setting work instead of leaving it in getPreviewText
2167 $previewOutput = '';
2168 if ( $this->formtype == 'preview' ) {
2169 $previewOutput = $this->getPreviewText();
2172 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2174 $this->setHeaders();
2176 if ( $this->showHeader() === false ) {
2177 wfProfileOut( __METHOD__ );
2178 return;
2181 $wgOut->addHTML( $this->editFormPageTop );
2183 if ( $wgUser->getOption( 'previewontop' ) ) {
2184 $this->displayPreviewArea( $previewOutput, true );
2187 $wgOut->addHTML( $this->editFormTextTop );
2189 $showToolbar = true;
2190 if ( $this->wasDeletedSinceLastEdit() ) {
2191 if ( $this->formtype == 'save' ) {
2192 // Hide the toolbar and edit area, user can click preview to get it back
2193 // Add an confirmation checkbox and explanation.
2194 $showToolbar = false;
2195 } else {
2196 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2197 'deletedwhileediting' );
2201 // @todo add EditForm plugin interface and use it here!
2202 // search for textarea1 and textares2, and allow EditForm to override all uses.
2203 $wgOut->addHTML( Html::openElement( 'form', array( 'id' => self::EDITFORM_ID, 'name' => self::EDITFORM_ID,
2204 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
2205 'enctype' => 'multipart/form-data' ) ) );
2207 if ( is_callable( $formCallback ) ) {
2208 call_user_func_array( $formCallback, array( &$wgOut ) );
2211 // Add an empty field to trip up spambots
2212 $wgOut->addHTML(
2213 Xml::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2214 . Html::rawElement( 'label', array( 'for' => 'wpAntiSpam' ), wfMessage( 'simpleantispam-label' )->parse() )
2215 . Xml::element( 'input', array( 'type' => 'text', 'name' => 'wpAntispam', 'id' => 'wpAntispam', 'value' => '' ) )
2216 . Xml::closeElement( 'div' )
2219 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2221 // Put these up at the top to ensure they aren't lost on early form submission
2222 $this->showFormBeforeText();
2224 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2225 $username = $this->lastDelete->user_name;
2226 $comment = $this->lastDelete->log_comment;
2228 // It is better to not parse the comment at all than to have templates expanded in the middle
2229 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2230 $key = $comment === ''
2231 ? 'confirmrecreate-noreason'
2232 : 'confirmrecreate';
2233 $wgOut->addHTML(
2234 '<div class="mw-confirm-recreate">' .
2235 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2236 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2237 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2239 '</div>'
2243 # When the summary is hidden, also hide them on preview/show changes
2244 if ( $this->nosummary ) {
2245 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2248 # If a blank edit summary was previously provided, and the appropriate
2249 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2250 # user being bounced back more than once in the event that a summary
2251 # is not required.
2252 #####
2253 # For a bit more sophisticated detection of blank summaries, hash the
2254 # automatic one and pass that in the hidden field wpAutoSummary.
2255 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2256 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2259 if ( $this->undidRev ) {
2260 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2263 if ( $this->hasPresetSummary ) {
2264 // If a summary has been preset using &summary= we don't want to prompt for
2265 // a different summary. Only prompt for a summary if the summary is blanked.
2266 // (Bug 17416)
2267 $this->autoSumm = md5( '' );
2270 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2271 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2273 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2275 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2276 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2278 if ( $this->section == 'new' ) {
2279 $this->showSummaryInput( true, $this->summary );
2280 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2283 $wgOut->addHTML( $this->editFormTextBeforeContent );
2285 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2286 $wgOut->addHTML( EditPage::getEditToolbar() );
2289 if ( $this->isConflict ) {
2290 // In an edit conflict bypass the overridable content form method
2291 // and fallback to the raw wpTextbox1 since editconflicts can't be
2292 // resolved between page source edits and custom ui edits using the
2293 // custom edit ui.
2294 $this->textbox2 = $this->textbox1;
2296 $content = $this->getCurrentContent();
2297 $this->textbox1 = $this->toEditText( $content );
2299 $this->showTextbox1();
2300 } else {
2301 $this->showContentForm();
2304 $wgOut->addHTML( $this->editFormTextAfterContent );
2306 $this->showStandardInputs();
2308 $this->showFormAfterText();
2310 $this->showTosSummary();
2312 $this->showEditTools();
2314 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2316 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2317 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2319 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2320 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
2322 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'limitreport' ),
2323 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2325 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2327 if ( $this->isConflict ) {
2328 try {
2329 $this->showConflict();
2330 } catch ( MWContentSerializationException $ex ) {
2331 // this can't really happen, but be nice if it does.
2332 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
2333 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2337 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2339 if ( !$wgUser->getOption( 'previewontop' ) ) {
2340 $this->displayPreviewArea( $previewOutput, false );
2343 wfProfileOut( __METHOD__ );
2347 * Extract the section title from current section text, if any.
2349 * @param string $text
2350 * @return Mixed|string or false
2352 public static function extractSectionTitle( $text ) {
2353 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2354 if ( !empty( $matches[2] ) ) {
2355 global $wgParser;
2356 return $wgParser->stripSectionName( trim( $matches[2] ) );
2357 } else {
2358 return false;
2362 protected function showHeader() {
2363 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2365 if ( $this->mTitle->isTalkPage() ) {
2366 $wgOut->addWikiMsg( 'talkpagetext' );
2369 // Add edit notices
2370 $wgOut->addHTML( implode( "\n", $this->mTitle->getEditNotices( $this->oldid ) ) );
2372 if ( $this->isConflict ) {
2373 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2374 $this->edittime = $this->mArticle->getTimestamp();
2375 } else {
2376 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2377 // We use $this->section to much before this and getVal('wgSection') directly in other places
2378 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2379 // Someone is welcome to try refactoring though
2380 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2381 return false;
2384 if ( $this->section != '' && $this->section != 'new' ) {
2385 if ( !$this->summary && !$this->preview && !$this->diff ) {
2386 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); //FIXME: use Content object
2387 if ( $sectionTitle !== false ) {
2388 $this->summary = "/* $sectionTitle */ ";
2393 if ( $this->missingComment ) {
2394 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2397 if ( $this->missingSummary && $this->section != 'new' ) {
2398 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2401 if ( $this->missingSummary && $this->section == 'new' ) {
2402 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2405 if ( $this->hookError !== '' ) {
2406 $wgOut->addWikiText( $this->hookError );
2409 if ( !$this->checkUnicodeCompliantBrowser() ) {
2410 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2413 if ( $this->section != 'new' ) {
2414 $revision = $this->mArticle->getRevisionFetched();
2415 if ( $revision ) {
2416 // Let sysop know that this will make private content public if saved
2418 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2419 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2420 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2421 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2424 if ( !$revision->isCurrent() ) {
2425 $this->mArticle->setOldSubtitle( $revision->getId() );
2426 $wgOut->addWikiMsg( 'editingold' );
2428 } elseif ( $this->mTitle->exists() ) {
2429 // Something went wrong
2431 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2432 array( 'missing-revision', $this->oldid ) );
2437 if ( wfReadOnly() ) {
2438 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2439 } elseif ( $wgUser->isAnon() ) {
2440 if ( $this->formtype != 'preview' ) {
2441 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2442 } else {
2443 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2445 } else {
2446 if ( $this->isCssJsSubpage ) {
2447 # Check the skin exists
2448 if ( $this->isWrongCaseCssJsPage ) {
2449 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
2451 if ( $this->formtype !== 'preview' ) {
2452 if ( $this->isCssSubpage ) {
2453 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2456 if ( $this->isJsSubpage ) {
2457 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2463 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
2464 # Is the title semi-protected?
2465 if ( $this->mTitle->isSemiProtected() ) {
2466 $noticeMsg = 'semiprotectedpagewarning';
2467 } else {
2468 # Then it must be protected based on static groups (regular)
2469 $noticeMsg = 'protectedpagewarning';
2471 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2472 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2474 if ( $this->mTitle->isCascadeProtected() ) {
2475 # Is this page under cascading protection from some source pages?
2476 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2477 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2478 $cascadeSourcesCount = count( $cascadeSources );
2479 if ( $cascadeSourcesCount > 0 ) {
2480 # Explain, and list the titles responsible
2481 foreach ( $cascadeSources as $page ) {
2482 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2485 $notice .= '</div>';
2486 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2488 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2489 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2490 array( 'lim' => 1,
2491 'showIfEmpty' => false,
2492 'msgKey' => array( 'titleprotectedwarning' ),
2493 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2496 if ( $this->kblength === false ) {
2497 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2500 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2501 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2502 array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2503 } else {
2504 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2505 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2506 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
2510 # Add header copyright warning
2511 $this->showHeaderCopyrightWarning();
2515 * Standard summary input and label (wgSummary), abstracted so EditPage
2516 * subclasses may reorganize the form.
2517 * Note that you do not need to worry about the label's for=, it will be
2518 * inferred by the id given to the input. You can remove them both by
2519 * passing array( 'id' => false ) to $userInputAttrs.
2521 * @param string $summary The value of the summary input
2522 * @param string $labelText The html to place inside the label
2523 * @param array $inputAttrs of attrs to use on the input
2524 * @param array $spanLabelAttrs of attrs to use on the span inside the label
2526 * @return array An array in the format array( $label, $input )
2528 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2529 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2530 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2531 'id' => 'wpSummary',
2532 'maxlength' => '200',
2533 'tabindex' => '1',
2534 'size' => 60,
2535 'spellcheck' => 'true',
2536 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2538 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2539 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2540 'id' => "wpSummaryLabel"
2543 $label = null;
2544 if ( $labelText ) {
2545 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2546 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2549 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2551 return array( $label, $input );
2555 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2556 * up top, or false if this is the comment summary
2557 * down below the textarea
2558 * @param string $summary The text of the summary to display
2559 * @return String
2561 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2562 global $wgOut, $wgContLang;
2563 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2564 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2565 if ( $isSubjectPreview ) {
2566 if ( $this->nosummary ) {
2567 return;
2569 } else {
2570 if ( !$this->mShowSummaryField ) {
2571 return;
2574 $summary = $wgContLang->recodeForEdit( $summary );
2575 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2576 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2577 $wgOut->addHTML( "{$label} {$input}" );
2581 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2582 * up top, or false if this is the comment summary
2583 * down below the textarea
2584 * @param string $summary the text of the summary to display
2585 * @return String
2587 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2588 // avoid spaces in preview, gets always trimmed on save
2589 $summary = trim( $summary );
2590 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
2591 return "";
2594 global $wgParser;
2596 if ( $isSubjectPreview ) {
2597 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2598 ->inContentLanguage()->text();
2601 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2603 $summary = wfMessage( $message )->parse() . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2604 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2607 protected function showFormBeforeText() {
2608 global $wgOut;
2609 $section = htmlspecialchars( $this->section );
2610 $wgOut->addHTML( <<<HTML
2611 <input type='hidden' value="{$section}" name="wpSection" />
2612 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2613 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2614 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2616 HTML
2618 if ( !$this->checkUnicodeCompliantBrowser() ) {
2619 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2623 protected function showFormAfterText() {
2624 global $wgOut, $wgUser;
2626 * To make it harder for someone to slip a user a page
2627 * which submits an edit form to the wiki without their
2628 * knowledge, a random token is associated with the login
2629 * session. If it's not passed back with the submission,
2630 * we won't save the page, or render user JavaScript and
2631 * CSS previews.
2633 * For anon editors, who may not have a session, we just
2634 * include the constant suffix to prevent editing from
2635 * broken text-mangling proxies.
2637 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2641 * Subpage overridable method for printing the form for page content editing
2642 * By default this simply outputs wpTextbox1
2643 * Subclasses can override this to provide a custom UI for editing;
2644 * be it a form, or simply wpTextbox1 with a modified content that will be
2645 * reverse modified when extracted from the post data.
2646 * Note that this is basically the inverse for importContentFormData
2648 protected function showContentForm() {
2649 $this->showTextbox1();
2653 * Method to output wpTextbox1
2654 * The $textoverride method can be used by subclasses overriding showContentForm
2655 * to pass back to this method.
2657 * @param array $customAttribs of html attributes to use in the textarea
2658 * @param string $textoverride optional text to override $this->textarea1 with
2660 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2661 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2662 $attribs = array( 'style' => 'display:none;' );
2663 } else {
2664 $classes = array(); // Textarea CSS
2665 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
2666 # Is the title semi-protected?
2667 if ( $this->mTitle->isSemiProtected() ) {
2668 $classes[] = 'mw-textarea-sprotected';
2669 } else {
2670 # Then it must be protected based on static groups (regular)
2671 $classes[] = 'mw-textarea-protected';
2673 # Is the title cascade-protected?
2674 if ( $this->mTitle->isCascadeProtected() ) {
2675 $classes[] = 'mw-textarea-cprotected';
2679 $attribs = array( 'tabindex' => 1 );
2681 if ( is_array( $customAttribs ) ) {
2682 $attribs += $customAttribs;
2685 if ( count( $classes ) ) {
2686 if ( isset( $attribs['class'] ) ) {
2687 $classes[] = $attribs['class'];
2689 $attribs['class'] = implode( ' ', $classes );
2693 $this->showTextbox( $textoverride !== null ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
2696 protected function showTextbox2() {
2697 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2700 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2701 global $wgOut, $wgUser;
2703 $wikitext = $this->safeUnicodeOutput( $text );
2704 if ( strval( $wikitext ) !== '' ) {
2705 // Ensure there's a newline at the end, otherwise adding lines
2706 // is awkward.
2707 // But don't add a newline if the ext is empty, or Firefox in XHTML
2708 // mode will show an extra newline. A bit annoying.
2709 $wikitext .= "\n";
2712 $attribs = $customAttribs + array(
2713 'accesskey' => ',',
2714 'id' => $name,
2715 'cols' => $wgUser->getIntOption( 'cols' ),
2716 'rows' => $wgUser->getIntOption( 'rows' ),
2717 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2720 $pageLang = $this->mTitle->getPageLanguage();
2721 $attribs['lang'] = $pageLang->getCode();
2722 $attribs['dir'] = $pageLang->getDir();
2724 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
2727 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2728 global $wgOut;
2729 $classes = array();
2730 if ( $isOnTop ) {
2731 $classes[] = 'ontop';
2734 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2736 if ( $this->formtype != 'preview' ) {
2737 $attribs['style'] = 'display: none;';
2740 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
2742 if ( $this->formtype == 'preview' ) {
2743 $this->showPreview( $previewOutput );
2746 $wgOut->addHTML( '</div>' );
2748 if ( $this->formtype == 'diff' ) {
2749 try {
2750 $this->showDiff();
2751 } catch ( MWContentSerializationException $ex ) {
2752 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
2753 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2759 * Append preview output to $wgOut.
2760 * Includes category rendering if this is a category page.
2762 * @param string $text the HTML to be output for the preview.
2764 protected function showPreview( $text ) {
2765 global $wgOut;
2766 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2767 $this->mArticle->openShowCategory();
2769 # This hook seems slightly odd here, but makes things more
2770 # consistent for extensions.
2771 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2772 $wgOut->addHTML( $text );
2773 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2774 $this->mArticle->closeShowCategory();
2779 * Get a diff between the current contents of the edit box and the
2780 * version of the page we're editing from.
2782 * If this is a section edit, we'll replace the section as for final
2783 * save and then make a comparison.
2785 function showDiff() {
2786 global $wgUser, $wgContLang, $wgOut;
2788 $oldtitlemsg = 'currentrev';
2789 # if message does not exist, show diff against the preloaded default
2790 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
2791 $oldtext = $this->mTitle->getDefaultMessageText();
2792 if ( $oldtext !== false ) {
2793 $oldtitlemsg = 'defaultmessagetext';
2794 $oldContent = $this->toEditContent( $oldtext );
2795 } else {
2796 $oldContent = null;
2798 } else {
2799 $oldContent = $this->getCurrentContent();
2802 $textboxContent = $this->toEditContent( $this->textbox1 );
2804 $newContent = $this->mArticle->replaceSectionContent(
2805 $this->section, $textboxContent,
2806 $this->summary, $this->edittime );
2808 if ( $newContent ) {
2809 ContentHandler::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2810 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2812 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
2813 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
2816 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
2817 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2818 $newtitle = wfMessage( 'yourtext' )->parse();
2820 if ( !$oldContent ) {
2821 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
2824 if ( !$newContent ) {
2825 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
2828 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
2829 $de->setContent( $oldContent, $newContent );
2831 $difftext = $de->getDiff( $oldtitle, $newtitle );
2832 $de->showDiffStyle();
2833 } else {
2834 $difftext = '';
2837 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2841 * Show the header copyright warning.
2843 protected function showHeaderCopyrightWarning() {
2844 $msg = 'editpage-head-copy-warn';
2845 if ( !wfMessage( $msg )->isDisabled() ) {
2846 global $wgOut;
2847 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2848 'editpage-head-copy-warn' );
2853 * Give a chance for site and per-namespace customizations of
2854 * terms of service summary link that might exist separately
2855 * from the copyright notice.
2857 * This will display between the save button and the edit tools,
2858 * so should remain short!
2860 protected function showTosSummary() {
2861 $msg = 'editpage-tos-summary';
2862 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
2863 if ( !wfMessage( $msg )->isDisabled() ) {
2864 global $wgOut;
2865 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2866 $wgOut->addWikiMsg( $msg );
2867 $wgOut->addHTML( '</div>' );
2871 protected function showEditTools() {
2872 global $wgOut;
2873 $wgOut->addHTML( '<div class="mw-editTools">' .
2874 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2875 '</div>' );
2879 * Get the copyright warning
2881 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2883 protected function getCopywarn() {
2884 return self::getCopyrightWarning( $this->mTitle );
2888 * Get the copyright warning, by default returns wikitext
2890 * @param Title $title
2891 * @param string $format output format, valid values are any function of
2892 * a Message object
2893 * @return string
2895 public static function getCopyrightWarning( $title, $format = 'plain' ) {
2896 global $wgRightsText;
2897 if ( $wgRightsText ) {
2898 $copywarnMsg = array( 'copyrightwarning',
2899 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2900 $wgRightsText );
2901 } else {
2902 $copywarnMsg = array( 'copyrightwarning2',
2903 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2905 // Allow for site and per-namespace customization of contribution/copyright notice.
2906 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2908 return "<div id=\"editpage-copywarn\">\n" .
2909 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
2913 * Get the Limit report for page previews
2915 * @since 1.22
2916 * @param ParserOutput $output ParserOutput object from the parse
2917 * @return string HTML
2919 public static function getPreviewLimitReport( $output ) {
2920 if ( !$output || !$output->getLimitReportData() ) {
2921 return '';
2924 wfProfileIn( __METHOD__ );
2926 $limitReport = Html::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
2927 wfMessage( 'limitreport-title' )->parseAsBlock()
2930 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
2931 $limitReport .= Html::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
2933 $limitReport .= Html::openElement( 'table', array(
2934 'class' => 'preview-limit-report wikitable'
2935 ) ) .
2936 Html::openElement( 'tbody' );
2938 foreach ( $output->getLimitReportData() as $key => $value ) {
2939 if ( wfRunHooks( 'ParserLimitReportFormat',
2940 array( $key, $value, &$limitReport, true, true )
2941 ) ) {
2942 $keyMsg = wfMessage( $key );
2943 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
2944 if ( !$valueMsg->exists() ) {
2945 $valueMsg = new RawMessage( '$1' );
2947 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
2948 $limitReport .= Html::openElement( 'tr' ) .
2949 Html::rawElement( 'th', null, $keyMsg->parse() ) .
2950 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
2951 Html::closeElement( 'tr' );
2956 $limitReport .= Html::closeElement( 'tbody' ) .
2957 Html::closeElement( 'table' ) .
2958 Html::closeElement( 'div' );
2960 wfProfileOut( __METHOD__ );
2962 return $limitReport;
2965 protected function showStandardInputs( &$tabindex = 2 ) {
2966 global $wgOut;
2967 $wgOut->addHTML( "<div class='editOptions'>\n" );
2969 if ( $this->section != 'new' ) {
2970 $this->showSummaryInput( false, $this->summary );
2971 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
2974 $checkboxes = $this->getCheckboxes( $tabindex,
2975 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
2976 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2978 // Show copyright warning.
2979 $wgOut->addWikiText( $this->getCopywarn() );
2980 $wgOut->addHTML( $this->editFormTextAfterWarn );
2982 $wgOut->addHTML( "<div class='editButtons'>\n" );
2983 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2985 $cancel = $this->getCancelLink();
2986 if ( $cancel !== '' ) {
2987 $cancel .= Html::element( 'span',
2988 array( 'class' => 'mw-editButtons-pipe-separator' ),
2989 wfMessage( 'pipe-separator' )->text() );
2991 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
2992 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2993 wfMessage( 'edithelp' )->escaped() . '</a> ' .
2994 wfMessage( 'newwindow' )->parse();
2995 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
2996 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
2997 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
2998 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
2999 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3003 * Show an edit conflict. textbox1 is already shown in showEditForm().
3004 * If you want to use another entry point to this function, be careful.
3006 protected function showConflict() {
3007 global $wgOut;
3009 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3010 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3012 $content1 = $this->toEditContent( $this->textbox1 );
3013 $content2 = $this->toEditContent( $this->textbox2 );
3015 $handler = ContentHandler::getForModelID( $this->contentModel );
3016 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3017 $de->setContent( $content2, $content1 );
3018 $de->showDiff(
3019 wfMessage( 'yourtext' )->parse(),
3020 wfMessage( 'storedversion' )->text()
3023 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3024 $this->showTextbox2();
3029 * @return string
3031 public function getCancelLink() {
3032 $cancelParams = array();
3033 if ( !$this->isConflict && $this->oldid > 0 ) {
3034 $cancelParams['oldid'] = $this->oldid;
3037 return Linker::linkKnown(
3038 $this->getContextTitle(),
3039 wfMessage( 'cancel' )->parse(),
3040 array( 'id' => 'mw-editform-cancel' ),
3041 $cancelParams
3046 * Returns the URL to use in the form's action attribute.
3047 * This is used by EditPage subclasses when simply customizing the action
3048 * variable in the constructor is not enough. This can be used when the
3049 * EditPage lives inside of a Special page rather than a custom page action.
3051 * @param $title Title object for which is being edited (where we go to for &action= links)
3052 * @return string
3054 protected function getActionURL( Title $title ) {
3055 return $title->getLocalURL( array( 'action' => $this->action ) );
3059 * Check if a page was deleted while the user was editing it, before submit.
3060 * Note that we rely on the logging table, which hasn't been always there,
3061 * but that doesn't matter, because this only applies to brand new
3062 * deletes.
3064 protected function wasDeletedSinceLastEdit() {
3065 if ( $this->deletedSinceEdit !== null ) {
3066 return $this->deletedSinceEdit;
3069 $this->deletedSinceEdit = false;
3071 if ( $this->mTitle->isDeletedQuick() ) {
3072 $this->lastDelete = $this->getLastDelete();
3073 if ( $this->lastDelete ) {
3074 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3075 if ( $deleteTime > $this->starttime ) {
3076 $this->deletedSinceEdit = true;
3081 return $this->deletedSinceEdit;
3084 protected function getLastDelete() {
3085 $dbr = wfGetDB( DB_SLAVE );
3086 $data = $dbr->selectRow(
3087 array( 'logging', 'user' ),
3088 array(
3089 'log_type',
3090 'log_action',
3091 'log_timestamp',
3092 'log_user',
3093 'log_namespace',
3094 'log_title',
3095 'log_comment',
3096 'log_params',
3097 'log_deleted',
3098 'user_name'
3099 ), array(
3100 'log_namespace' => $this->mTitle->getNamespace(),
3101 'log_title' => $this->mTitle->getDBkey(),
3102 'log_type' => 'delete',
3103 'log_action' => 'delete',
3104 'user_id=log_user'
3106 __METHOD__,
3107 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3109 // Quick paranoid permission checks...
3110 if ( is_object( $data ) ) {
3111 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3112 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
3115 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3116 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
3119 return $data;
3123 * Get the rendered text for previewing.
3124 * @throws MWException
3125 * @return string
3127 function getPreviewText() {
3128 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3130 wfProfileIn( __METHOD__ );
3132 if ( $wgRawHtml && !$this->mTokenOk ) {
3133 // Could be an offsite preview attempt. This is very unsafe if
3134 // HTML is enabled, as it could be an attack.
3135 $parsedNote = '';
3136 if ( $this->textbox1 !== '' ) {
3137 // Do not put big scary notice, if previewing the empty
3138 // string, which happens when you initially edit
3139 // a category page, due to automatic preview-on-open.
3140 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3141 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3143 wfProfileOut( __METHOD__ );
3144 return $parsedNote;
3147 $note = '';
3149 try {
3150 $content = $this->toEditContent( $this->textbox1 );
3152 $previewHTML = '';
3153 if ( !wfRunHooks( 'AlternateEditPreview', array( $this, &$content, &$previewHTML, &$this->mParserOutput ) ) ) {
3154 wfProfileOut( __METHOD__ );
3155 return $previewHTML;
3158 if ( $this->mTriedSave && !$this->mTokenOk ) {
3159 if ( $this->mTokenOkExceptSuffix ) {
3160 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3162 } else {
3163 $note = wfMessage( 'session_fail_preview' )->plain();
3165 } elseif ( $this->incompleteForm ) {
3166 $note = wfMessage( 'edit_form_incomplete' )->plain();
3167 } else {
3168 $note = wfMessage( 'previewnote' )->plain() .
3169 ' [[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' . wfMessage( 'continue-editing' )->text() . ']]';
3172 $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
3173 $parserOptions->setEditSection( false );
3174 $parserOptions->setIsPreview( true );
3175 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3177 # don't parse non-wikitext pages, show message about preview
3178 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3179 if ( $this->mTitle->isCssJsSubpage() ) {
3180 $level = 'user';
3181 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3182 $level = 'site';
3183 } else {
3184 $level = false;
3187 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3188 $format = 'css';
3189 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3190 $format = 'js';
3191 } else {
3192 $format = false;
3195 # Used messages to make sure grep find them:
3196 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3197 if ( $level && $format ) {
3198 $note = "<div id='mw-{$level}{$format}preview'>" . wfMessage( "{$level}{$format}preview" )->text() . "</div>";
3202 $rt = $content->getRedirectChain();
3203 if ( $rt ) {
3204 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
3205 } else {
3207 # If we're adding a comment, we need to show the
3208 # summary as the headline
3209 if ( $this->section === "new" && $this->summary !== "" ) {
3210 $content = $content->addSectionHeader( $this->summary );
3213 $hook_args = array( $this, &$content );
3214 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3215 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3217 $parserOptions->enableLimitReport();
3219 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3220 # But it's now deprecated, so never mind
3222 $content = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3223 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
3225 $previewHTML = $parserOutput->getText();
3226 $this->mParserOutput = $parserOutput;
3227 $wgOut->addParserOutputNoText( $parserOutput );
3229 if ( count( $parserOutput->getWarnings() ) ) {
3230 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3233 } catch ( MWContentSerializationException $ex ) {
3234 $m = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
3235 $note .= "\n\n" . $m->parse();
3236 $previewHTML = '';
3239 if ( $this->isConflict ) {
3240 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3241 } else {
3242 $conflict = '<hr />';
3245 $previewhead = "<div class='previewnote'>\n" .
3246 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3247 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3249 $pageViewLang = $this->mTitle->getPageViewLanguage();
3250 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3251 'class' => 'mw-content-' . $pageViewLang->getDir() );
3252 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3254 wfProfileOut( __METHOD__ );
3255 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3259 * @return Array
3261 function getTemplates() {
3262 if ( $this->preview || $this->section != '' ) {
3263 $templates = array();
3264 if ( !isset( $this->mParserOutput ) ) {
3265 return $templates;
3267 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3268 foreach ( array_keys( $template ) as $dbk ) {
3269 $templates[] = Title::makeTitle( $ns, $dbk );
3272 return $templates;
3273 } else {
3274 return $this->mTitle->getTemplateLinksFrom();
3279 * Shows a bulletin board style toolbar for common editing functions.
3280 * It can be disabled in the user preferences.
3281 * The necessary JavaScript code can be found in skins/common/edit.js.
3283 * @return string
3285 static function getEditToolbar() {
3286 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3287 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
3289 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3292 * $toolarray is an array of arrays each of which includes the
3293 * filename of the button image (without path), the opening
3294 * tag, the closing tag, optionally a sample text that is
3295 * inserted between the two when no selection is highlighted
3296 * and. The tip text is shown when the user moves the mouse
3297 * over the button.
3299 * Also here: accesskeys (key), which are not used yet until
3300 * someone can figure out a way to make them work in
3301 * IE. However, we should make sure these keys are not defined
3302 * on the edit page.
3304 $toolarray = array(
3305 array(
3306 'image' => $wgLang->getImageFile( 'button-bold' ),
3307 'id' => 'mw-editbutton-bold',
3308 'open' => '\'\'\'',
3309 'close' => '\'\'\'',
3310 'sample' => wfMessage( 'bold_sample' )->text(),
3311 'tip' => wfMessage( 'bold_tip' )->text(),
3312 'key' => 'B'
3314 array(
3315 'image' => $wgLang->getImageFile( 'button-italic' ),
3316 'id' => 'mw-editbutton-italic',
3317 'open' => '\'\'',
3318 'close' => '\'\'',
3319 'sample' => wfMessage( 'italic_sample' )->text(),
3320 'tip' => wfMessage( 'italic_tip' )->text(),
3321 'key' => 'I'
3323 array(
3324 'image' => $wgLang->getImageFile( 'button-link' ),
3325 'id' => 'mw-editbutton-link',
3326 'open' => '[[',
3327 'close' => ']]',
3328 'sample' => wfMessage( 'link_sample' )->text(),
3329 'tip' => wfMessage( 'link_tip' )->text(),
3330 'key' => 'L'
3332 array(
3333 'image' => $wgLang->getImageFile( 'button-extlink' ),
3334 'id' => 'mw-editbutton-extlink',
3335 'open' => '[',
3336 'close' => ']',
3337 'sample' => wfMessage( 'extlink_sample' )->text(),
3338 'tip' => wfMessage( 'extlink_tip' )->text(),
3339 'key' => 'X'
3341 array(
3342 'image' => $wgLang->getImageFile( 'button-headline' ),
3343 'id' => 'mw-editbutton-headline',
3344 'open' => "\n== ",
3345 'close' => " ==\n",
3346 'sample' => wfMessage( 'headline_sample' )->text(),
3347 'tip' => wfMessage( 'headline_tip' )->text(),
3348 'key' => 'H'
3350 $imagesAvailable ? array(
3351 'image' => $wgLang->getImageFile( 'button-image' ),
3352 'id' => 'mw-editbutton-image',
3353 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3354 'close' => ']]',
3355 'sample' => wfMessage( 'image_sample' )->text(),
3356 'tip' => wfMessage( 'image_tip' )->text(),
3357 'key' => 'D',
3358 ) : false,
3359 $imagesAvailable ? array(
3360 'image' => $wgLang->getImageFile( 'button-media' ),
3361 'id' => 'mw-editbutton-media',
3362 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3363 'close' => ']]',
3364 'sample' => wfMessage( 'media_sample' )->text(),
3365 'tip' => wfMessage( 'media_tip' )->text(),
3366 'key' => 'M'
3367 ) : false,
3368 $wgUseTeX ? array(
3369 'image' => $wgLang->getImageFile( 'button-math' ),
3370 'id' => 'mw-editbutton-math',
3371 'open' => "<math>",
3372 'close' => "</math>",
3373 'sample' => wfMessage( 'math_sample' )->text(),
3374 'tip' => wfMessage( 'math_tip' )->text(),
3375 'key' => 'C'
3376 ) : false,
3377 array(
3378 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3379 'id' => 'mw-editbutton-nowiki',
3380 'open' => "<nowiki>",
3381 'close' => "</nowiki>",
3382 'sample' => wfMessage( 'nowiki_sample' )->text(),
3383 'tip' => wfMessage( 'nowiki_tip' )->text(),
3384 'key' => 'N'
3386 array(
3387 'image' => $wgLang->getImageFile( 'button-sig' ),
3388 'id' => 'mw-editbutton-signature',
3389 'open' => '--~~~~',
3390 'close' => '',
3391 'sample' => '',
3392 'tip' => wfMessage( 'sig_tip' )->text(),
3393 'key' => 'Y'
3395 array(
3396 'image' => $wgLang->getImageFile( 'button-hr' ),
3397 'id' => 'mw-editbutton-hr',
3398 'open' => "\n----\n",
3399 'close' => '',
3400 'sample' => '',
3401 'tip' => wfMessage( 'hr_tip' )->text(),
3402 'key' => 'R'
3406 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3407 foreach ( $toolarray as $tool ) {
3408 if ( !$tool ) {
3409 continue;
3412 $params = array(
3413 $image = $wgStylePath . '/common/images/' . $tool['image'],
3414 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3415 // Older browsers show a "speedtip" type message only for ALT.
3416 // Ideally these should be different, realistically they
3417 // probably don't need to be.
3418 $tip = $tool['tip'],
3419 $open = $tool['open'],
3420 $close = $tool['close'],
3421 $sample = $tool['sample'],
3422 $cssId = $tool['id'],
3425 $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
3428 // This used to be called on DOMReady from mediawiki.action.edit, which
3429 // ended up causing race conditions with the setup code above.
3430 $script .= "\n" .
3431 "// Create button bar\n" .
3432 "$(function() { mw.toolbar.init(); } );\n";
3434 $script .= '});';
3435 $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
3437 $toolbar = '<div id="toolbar"></div>';
3439 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3441 return $toolbar;
3445 * Returns an array of html code of the following checkboxes:
3446 * minor and watch
3448 * @param int $tabindex Current tabindex
3449 * @param array $checked of checkbox => bool, where bool indicates the checked
3450 * status of the checkbox
3452 * @return array
3454 public function getCheckboxes( &$tabindex, $checked ) {
3455 global $wgUser;
3457 $checkboxes = array();
3459 // don't show the minor edit checkbox if it's a new page or section
3460 if ( !$this->isNew ) {
3461 $checkboxes['minor'] = '';
3462 $minorLabel = wfMessage( 'minoredit' )->parse();
3463 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3464 $attribs = array(
3465 'tabindex' => ++$tabindex,
3466 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3467 'id' => 'wpMinoredit',
3469 $checkboxes['minor'] =
3470 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3471 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3472 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3473 ">{$minorLabel}</label>";
3477 $watchLabel = wfMessage( 'watchthis' )->parse();
3478 $checkboxes['watch'] = '';
3479 if ( $wgUser->isLoggedIn() ) {
3480 $attribs = array(
3481 'tabindex' => ++$tabindex,
3482 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3483 'id' => 'wpWatchthis',
3485 $checkboxes['watch'] =
3486 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3487 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3488 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3489 ">{$watchLabel}</label>";
3491 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3492 return $checkboxes;
3496 * Returns an array of html code of the following buttons:
3497 * save, diff, preview and live
3499 * @param int $tabindex Current tabindex
3501 * @return array
3503 public function getEditButtons( &$tabindex ) {
3504 $buttons = array();
3506 $temp = array(
3507 'id' => 'wpSave',
3508 'name' => 'wpSave',
3509 'type' => 'submit',
3510 'tabindex' => ++$tabindex,
3511 'value' => wfMessage( 'savearticle' )->text(),
3512 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3513 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3515 $buttons['save'] = Xml::element( 'input', $temp, '' );
3517 ++$tabindex; // use the same for preview and live preview
3518 $temp = array(
3519 'id' => 'wpPreview',
3520 'name' => 'wpPreview',
3521 'type' => 'submit',
3522 'tabindex' => $tabindex,
3523 'value' => wfMessage( 'showpreview' )->text(),
3524 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3525 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3527 $buttons['preview'] = Xml::element( 'input', $temp, '' );
3528 $buttons['live'] = '';
3530 $temp = array(
3531 'id' => 'wpDiff',
3532 'name' => 'wpDiff',
3533 'type' => 'submit',
3534 'tabindex' => ++$tabindex,
3535 'value' => wfMessage( 'showdiff' )->text(),
3536 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3537 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3539 $buttons['diff'] = Xml::element( 'input', $temp, '' );
3541 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3542 return $buttons;
3546 * Output preview text only. This can be sucked into the edit page
3547 * via JavaScript, and saves the server time rendering the skin as
3548 * well as theoretically being more robust on the client (doesn't
3549 * disturb the edit box's undo history, won't eat your text on
3550 * failure, etc).
3552 * @todo This doesn't include category or interlanguage links.
3553 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3554 * or something...</s>" that might also require more skin
3555 * initialization, so check whether that's a problem.
3557 function livePreview() {
3558 global $wgOut;
3559 $wgOut->disable();
3560 header( 'Content-type: text/xml; charset=utf-8' );
3561 header( 'Cache-control: no-cache' );
3563 $previewText = $this->getPreviewText();
3564 #$categories = $skin->getCategoryLinks();
3566 $s =
3567 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3568 Xml::tags( 'livepreview', null,
3569 Xml::element( 'preview', null, $previewText )
3570 #. Xml::element( 'category', null, $categories )
3572 echo $s;
3576 * Call the stock "user is blocked" page
3578 * @deprecated in 1.19; throw an exception directly instead
3580 function blockedPage() {
3581 wfDeprecated( __METHOD__, '1.19' );
3582 global $wgUser;
3584 throw new UserBlockedError( $wgUser->getBlock() );
3588 * Produce the stock "please login to edit pages" page
3590 * @deprecated in 1.19; throw an exception directly instead
3592 function userNotLoggedInPage() {
3593 wfDeprecated( __METHOD__, '1.19' );
3594 throw new PermissionsError( 'edit' );
3598 * Show an error page saying to the user that he has insufficient permissions
3599 * to create a new page
3601 * @deprecated in 1.19; throw an exception directly instead
3603 function noCreatePermission() {
3604 wfDeprecated( __METHOD__, '1.19' );
3605 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
3606 throw new PermissionsError( $permission );
3610 * Creates a basic error page which informs the user that
3611 * they have attempted to edit a nonexistent section.
3613 function noSuchSectionPage() {
3614 global $wgOut;
3616 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3618 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
3619 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3620 $wgOut->addHTML( $res );
3622 $wgOut->returnToMain( false, $this->mTitle );
3626 * Produce the stock "your edit contains spam" page
3628 * @param string|bool $match Text which triggered one or more filters
3629 * @deprecated since 1.17 Use method spamPageWithContent() instead
3631 static function spamPage( $match = false ) {
3632 wfDeprecated( __METHOD__, '1.17' );
3634 global $wgOut, $wgTitle;
3636 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3638 $wgOut->addHTML( '<div id="spamprotected">' );
3639 $wgOut->addWikiMsg( 'spamprotectiontext' );
3640 if ( $match ) {
3641 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3643 $wgOut->addHTML( '</div>' );
3645 $wgOut->returnToMain( false, $wgTitle );
3649 * Show "your edit contains spam" page with your diff and text
3651 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3653 public function spamPageWithContent( $match = false ) {
3654 global $wgOut, $wgLang;
3655 $this->textbox2 = $this->textbox1;
3657 if ( is_array( $match ) ) {
3658 $match = $wgLang->listToText( $match );
3660 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3662 $wgOut->addHTML( '<div id="spamprotected">' );
3663 $wgOut->addWikiMsg( 'spamprotectiontext' );
3664 if ( $match ) {
3665 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3667 $wgOut->addHTML( '</div>' );
3669 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3670 $this->showDiff();
3672 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3673 $this->showTextbox2();
3675 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3679 * Format an anchor fragment as it would appear for a given section name
3680 * @param $text String
3681 * @return String
3682 * @private
3684 function sectionAnchor( $text ) {
3685 global $wgParser;
3686 return $wgParser->guessSectionNameFromWikiText( $text );
3690 * Check if the browser is on a blacklist of user-agents known to
3691 * mangle UTF-8 data on form submission. Returns true if Unicode
3692 * should make it through, false if it's known to be a problem.
3693 * @return bool
3694 * @private
3696 function checkUnicodeCompliantBrowser() {
3697 global $wgBrowserBlackList, $wgRequest;
3699 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3700 if ( $currentbrowser === false ) {
3701 // No User-Agent header sent? Trust it by default...
3702 return true;
3705 foreach ( $wgBrowserBlackList as $browser ) {
3706 if ( preg_match( $browser, $currentbrowser ) ) {
3707 return false;
3710 return true;
3714 * Filter an input field through a Unicode de-armoring process if it
3715 * came from an old browser with known broken Unicode editing issues.
3717 * @param $request WebRequest
3718 * @param $field String
3719 * @return String
3720 * @private
3722 function safeUnicodeInput( $request, $field ) {
3723 $text = rtrim( $request->getText( $field ) );
3724 return $request->getBool( 'safemode' )
3725 ? $this->unmakesafe( $text )
3726 : $text;
3730 * @param $request WebRequest
3731 * @param $text string
3732 * @return string
3734 function safeUnicodeText( $request, $text ) {
3735 $text = rtrim( $text );
3736 return $request->getBool( 'safemode' )
3737 ? $this->unmakesafe( $text )
3738 : $text;
3742 * Filter an output field through a Unicode armoring process if it is
3743 * going to an old browser with known broken Unicode editing issues.
3745 * @param $text String
3746 * @return String
3747 * @private
3749 function safeUnicodeOutput( $text ) {
3750 global $wgContLang;
3751 $codedText = $wgContLang->recodeForEdit( $text );
3752 return $this->checkUnicodeCompliantBrowser()
3753 ? $codedText
3754 : $this->makesafe( $codedText );
3758 * A number of web browsers are known to corrupt non-ASCII characters
3759 * in a UTF-8 text editing environment. To protect against this,
3760 * detected browsers will be served an armored version of the text,
3761 * with non-ASCII chars converted to numeric HTML character references.
3763 * Preexisting such character references will have a 0 added to them
3764 * to ensure that round-trips do not alter the original data.
3766 * @param $invalue String
3767 * @return String
3768 * @private
3770 function makesafe( $invalue ) {
3771 // Armor existing references for reversibility.
3772 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
3774 $bytesleft = 0;
3775 $result = "";
3776 $working = 0;
3777 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3778 $bytevalue = ord( $invalue[$i] );
3779 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3780 $result .= chr( $bytevalue );
3781 $bytesleft = 0;
3782 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3783 $working = $working << 6;
3784 $working += ( $bytevalue & 0x3F );
3785 $bytesleft--;
3786 if ( $bytesleft <= 0 ) {
3787 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3789 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3790 $working = $bytevalue & 0x1F;
3791 $bytesleft = 1;
3792 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3793 $working = $bytevalue & 0x0F;
3794 $bytesleft = 2;
3795 } else { // 1111 0xxx
3796 $working = $bytevalue & 0x07;
3797 $bytesleft = 3;
3800 return $result;
3804 * Reverse the previously applied transliteration of non-ASCII characters
3805 * back to UTF-8. Used to protect data from corruption by broken web browsers
3806 * as listed in $wgBrowserBlackList.
3808 * @param $invalue String
3809 * @return String
3810 * @private
3812 function unmakesafe( $invalue ) {
3813 $result = "";
3814 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3815 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
3816 $i += 3;
3817 $hexstring = "";
3818 do {
3819 $hexstring .= $invalue[$i];
3820 $i++;
3821 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3823 // Do some sanity checks. These aren't needed for reversibility,
3824 // but should help keep the breakage down if the editor
3825 // breaks one of the entities whilst editing.
3826 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3827 $codepoint = hexdec( $hexstring );
3828 $result .= codepointToUtf8( $codepoint );
3829 } else {
3830 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3832 } else {
3833 $result .= substr( $invalue, $i, 1 );
3836 // reverse the transform that we made for reversibility reasons.
3837 return strtr( $result, array( "&#x0" => "&#x" ) );