Properly deprecate srprop=score|hasrelated
[mediawiki.git] / includes / EditPage.php
bloba14191a03530b40bc7170ca4c328a7ef82c7942b
1 <?php
2 /**
3 * User interface for page editing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
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 {
39 /**
40 * Status: Article successfully updated
42 const AS_SUCCESS_UPDATE = 200;
44 /**
45 * Status: Article successfully created
47 const AS_SUCCESS_NEW_ARTICLE = 201;
49 /**
50 * Status: Article update aborted by a hook function
52 const AS_HOOK_ERROR = 210;
54 /**
55 * Status: A hook function returned an error
57 const AS_HOOK_ERROR_EXPECTED = 212;
59 /**
60 * Status: User is blocked from editing this page
62 const AS_BLOCKED_PAGE_FOR_USER = 215;
64 /**
65 * Status: Content too big (> $wgMaxArticleSize)
67 const AS_CONTENT_TOO_BIG = 216;
69 /**
70 * Status: this anonymous user is not allowed to edit this page
72 const AS_READ_ONLY_PAGE_ANON = 218;
74 /**
75 * Status: this logged in user is not allowed to edit this page
77 const AS_READ_ONLY_PAGE_LOGGED = 219;
79 /**
80 * Status: wiki is in readonly mode (wfReadOnly() == true)
82 const AS_READ_ONLY_PAGE = 220;
84 /**
85 * Status: rate limiter for action 'edit' was tripped
87 const AS_RATE_LIMITED = 221;
89 /**
90 * Status: article was deleted while editing and param wpRecreate == false or form
91 * was not posted
93 const AS_ARTICLE_WAS_DELETED = 222;
95 /**
96 * Status: user tried to create this page, but is not allowed to do that
97 * ( Title->userCan('create') == false )
99 const AS_NO_CREATE_PERMISSION = 223;
102 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
104 const AS_BLANK_ARTICLE = 224;
107 * Status: (non-resolvable) edit conflict
109 const AS_CONFLICT_DETECTED = 225;
112 * Status: no edit summary given and the user has forceeditsummary set and the user is not
113 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
115 const AS_SUMMARY_NEEDED = 226;
118 * Status: user tried to create a new section without content
120 const AS_TEXTBOX_EMPTY = 228;
123 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
125 const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
128 * Status: WikiPage::doEdit() was unsuccessful
130 const AS_END = 231;
133 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
135 const AS_SPAM_ERROR = 232;
138 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
140 const AS_IMAGE_REDIRECT_ANON = 233;
143 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
145 const AS_IMAGE_REDIRECT_LOGGED = 234;
148 * Status: can't parse content
150 const AS_PARSE_ERROR = 240;
153 * HTML id and name for the beginning of the edit form.
155 const EDITFORM_ID = 'editform';
158 * Prefix of key for cookie used to pass post-edit state.
159 * The revision id edited is added after this
161 const POST_EDIT_COOKIE_KEY_PREFIX = 'PostEditRevision';
164 * Duration of PostEdit cookie, in seconds.
165 * The cookie will be removed instantly if the JavaScript runs.
167 * Otherwise, though, we don't want the cookies to accumulate.
168 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
169 * limit of only 20 cookies per domain. This still applies at least to some
170 * versions of IE without full updates:
171 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
173 * A value of 20 minutes should be enough to take into account slow loads and minor
174 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
176 const POST_EDIT_COOKIE_DURATION = 1200;
178 /** @var Article */
179 public $mArticle;
181 /** @var Title */
182 public $mTitle;
184 /** @var null|Title */
185 private $mContextTitle = null;
187 /** @var string */
188 protected $action = 'submit';
190 /** @var bool */
191 public $isConflict = false;
193 /** @var bool */
194 public $isCssJsSubpage = false;
196 /** @var bool */
197 public $isCssSubpage = false;
199 /** @var bool */
200 public $isJsSubpage = false;
202 /** @var bool */
203 protected $isWrongCaseCssJsPage = false;
205 /** @var bool New page or new section */
206 protected $isNew = false;
208 /** @var bool */
209 protected $deletedSinceEdit;
211 /** @var string */
212 public $formtype;
214 /** @var bool */
215 public $firsttime;
217 /** @var bool|stdClass */
218 protected $lastDelete;
220 /** @var bool
221 * This is public because SemanticForms uses it (bug 67522).
222 * However, please consider using this property publicly
223 * to be deprecated.
224 * @protected
226 public $mTokenOk = false;
228 /** @var bool */
229 protected $mTokenOkExceptSuffix = false;
231 /** @var bool */
232 protected $mTriedSave = false;
234 /** @var bool */
235 protected $incompleteForm = false;
237 /** @var bool */
238 protected $tooBig = false;
240 /** @var bool */
241 protected $kblength = false;
243 /** @var bool */
244 protected $missingComment = false;
246 /** @var bool */
247 protected $missingSummary = false;
249 /** @var bool */
250 protected $allowBlankSummary = false;
252 /** @var bool */
253 protected $blankArticle = false;
255 /** @var bool */
256 protected $allowBlankArticle = false;
258 /** @var string */
259 protected $autoSumm = '';
261 /** @var string */
262 public $hookError = '';
264 /** @var ParserOutput */
265 protected $mParserOutput;
267 /** @var bool Has a summary been preset using GET parameter &summary= ? */
268 protected $hasPresetSummary = false;
270 /** @var bool */
271 protected $mBaseRevision = false;
273 /** @var bool */
274 public $mShowSummaryField = true;
276 # Form values
278 /** @var bool */
279 public $save = false;
281 /** @var bool */
282 public $preview = false;
284 /** @var bool */
285 protected $diff = false;
287 /** @var bool */
288 public $minoredit = false;
290 /** @var bool */
291 protected $watchthis = false;
293 /** @var bool */
294 protected $recreate = false;
296 /** @var string */
297 public $textbox1 = '';
299 /** @var string */
300 public $textbox2 = '';
302 /** @var string */
303 public $summary = '';
305 /** @var bool */
306 protected $nosummary = false;
308 /** @var string */
309 public $edittime = '';
311 /** @var string */
312 public $section = '';
314 /** @var string */
315 public $sectiontitle = '';
317 /** @var string */
318 protected $starttime = '';
320 /** @var int */
321 public $oldid = 0;
323 /** @var string */
324 protected $editintro = '';
326 /** @var null */
327 public $scrolltop = null;
329 /** @var bool */
330 public $bot = true;
332 /** @var null|string */
333 public $contentModel = null;
335 /** @var null|string */
336 public $contentFormat = null;
338 # Placeholders for text injection by hooks (must be HTML)
339 # extensions should take care to _append_ to the present value
341 /** @var string Before even the preview */
342 public $editFormPageTop = '';
343 public $editFormTextTop = '';
344 public $editFormTextBeforeContent = '';
345 public $editFormTextAfterWarn = '';
346 public $editFormTextAfterTools = '';
347 public $editFormTextBottom = '';
348 public $editFormTextAfterContent = '';
349 public $previewTextAfterContent = '';
350 public $mPreloadContent = null;
352 /* $didSave should be set to true whenever an article was successfully altered. */
353 public $didSave = false;
354 public $undidRev = 0;
356 public $suppressIntro = false;
358 /** @var bool Set to true to allow editing of non-text content types. */
359 public $allowNonTextContent = false;
361 /** @var bool */
362 protected $edit;
364 /** @var bool */
365 public $live;
368 * @param Article $article
370 public function __construct( Article $article ) {
371 $this->mArticle = $article;
372 $this->mTitle = $article->getTitle();
374 $this->contentModel = $this->mTitle->getContentModel();
376 $handler = ContentHandler::getForModelID( $this->contentModel );
377 $this->contentFormat = $handler->getDefaultFormat();
381 * @return Article
383 public function getArticle() {
384 return $this->mArticle;
388 * @since 1.19
389 * @return Title
391 public function getTitle() {
392 return $this->mTitle;
396 * Set the context Title object
398 * @param Title|null $title Title object or null
400 public function setContextTitle( $title ) {
401 $this->mContextTitle = $title;
405 * Get the context title object.
406 * If not set, $wgTitle will be returned. This behavior might change in
407 * the future to return $this->mTitle instead.
409 * @return Title
411 public function getContextTitle() {
412 if ( is_null( $this->mContextTitle ) ) {
413 global $wgTitle;
414 return $wgTitle;
415 } else {
416 return $this->mContextTitle;
421 * Returns if the given content model is editable.
423 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
424 * @return bool
425 * @throws MWException If $modelId has no known handler
427 public function isSupportedContentModel( $modelId ) {
428 return $this->allowNonTextContent ||
429 ContentHandler::getForModelID( $modelId ) instanceof TextContentHandler;
432 function submit() {
433 $this->edit();
437 * This is the function that gets called for "action=edit". It
438 * sets up various member variables, then passes execution to
439 * another function, usually showEditForm()
441 * The edit form is self-submitting, so that when things like
442 * preview and edit conflicts occur, we get the same form back
443 * with the extra stuff added. Only when the final submission
444 * is made and all is well do we actually save and redirect to
445 * the newly-edited page.
447 function edit() {
448 global $wgOut, $wgRequest, $wgUser;
449 // Allow extensions to modify/prevent this form or submission
450 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
451 return;
454 wfProfileIn( __METHOD__ );
455 wfDebug( __METHOD__ . ": enter\n" );
457 // If they used redlink=1 and the page exists, redirect to the main article
458 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
459 $wgOut->redirect( $this->mTitle->getFullURL() );
460 wfProfileOut( __METHOD__ );
461 return;
464 $this->importFormData( $wgRequest );
465 $this->firsttime = false;
467 if ( $this->live ) {
468 $this->livePreview();
469 wfProfileOut( __METHOD__ );
470 return;
473 if ( wfReadOnly() && $this->save ) {
474 // Force preview
475 $this->save = false;
476 $this->preview = true;
479 if ( $this->save ) {
480 $this->formtype = 'save';
481 } elseif ( $this->preview ) {
482 $this->formtype = 'preview';
483 } elseif ( $this->diff ) {
484 $this->formtype = 'diff';
485 } else { # First time through
486 $this->firsttime = true;
487 if ( $this->previewOnOpen() ) {
488 $this->formtype = 'preview';
489 } else {
490 $this->formtype = 'initial';
494 $permErrors = $this->getEditPermissionErrors();
495 if ( $permErrors ) {
496 wfDebug( __METHOD__ . ": User can't edit\n" );
497 // Auto-block user's IP if the account was "hard" blocked
498 $wgUser->spreadAnyEditBlock();
500 $this->displayPermissionsError( $permErrors );
502 wfProfileOut( __METHOD__ );
503 return;
506 wfProfileIn( __METHOD__ . "-business-end" );
508 $this->isConflict = false;
509 // css / js subpages of user pages get a special treatment
510 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
511 $this->isCssSubpage = $this->mTitle->isCssSubpage();
512 $this->isJsSubpage = $this->mTitle->isJsSubpage();
513 // @todo FIXME: Silly assignment.
514 $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
516 # Show applicable editing introductions
517 if ( $this->formtype == 'initial' || $this->firsttime ) {
518 $this->showIntro();
521 # Attempt submission here. This will check for edit conflicts,
522 # and redundantly check for locked database, blocked IPs, etc.
523 # that edit() already checked just in case someone tries to sneak
524 # in the back door with a hand-edited submission URL.
526 if ( 'save' == $this->formtype ) {
527 if ( !$this->attemptSave() ) {
528 wfProfileOut( __METHOD__ . "-business-end" );
529 wfProfileOut( __METHOD__ );
530 return;
534 # First time through: get contents, set time for conflict
535 # checking, etc.
536 if ( 'initial' == $this->formtype || $this->firsttime ) {
537 if ( $this->initialiseForm() === false ) {
538 $this->noSuchSectionPage();
539 wfProfileOut( __METHOD__ . "-business-end" );
540 wfProfileOut( __METHOD__ );
541 return;
544 if ( !$this->mTitle->getArticleID() ) {
545 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
546 } else {
547 wfRunHooks( 'EditFormInitialText', array( $this ) );
552 $this->showEditForm();
553 wfProfileOut( __METHOD__ . "-business-end" );
554 wfProfileOut( __METHOD__ );
558 * @return array
560 protected function getEditPermissionErrors() {
561 global $wgUser;
562 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
563 # Can this title be created?
564 if ( !$this->mTitle->exists() ) {
565 $permErrors = array_merge( $permErrors,
566 wfArrayDiff2( $this->mTitle->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
568 # Ignore some permissions errors when a user is just previewing/viewing diffs
569 $remove = array();
570 foreach ( $permErrors as $error ) {
571 if ( ( $this->preview || $this->diff )
572 && ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' )
574 $remove[] = $error;
577 $permErrors = wfArrayDiff2( $permErrors, $remove );
578 return $permErrors;
582 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
583 * but with the following differences:
584 * - If redlink=1, the user will be redirected to the page
585 * - If there is content to display or the error occurs while either saving,
586 * previewing or showing the difference, it will be a
587 * "View source for ..." page displaying the source code after the error message.
589 * @since 1.19
590 * @param array $permErrors Array of permissions errors, as returned by
591 * Title::getUserPermissionsErrors().
592 * @throws PermissionsError
594 protected function displayPermissionsError( array $permErrors ) {
595 global $wgRequest, $wgOut;
597 if ( $wgRequest->getBool( 'redlink' ) ) {
598 // The edit page was reached via a red link.
599 // Redirect to the article page and let them click the edit tab if
600 // they really want a permission error.
601 $wgOut->redirect( $this->mTitle->getFullURL() );
602 return;
605 $content = $this->getContentObject();
607 # Use the normal message if there's nothing to display
608 if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
609 $action = $this->mTitle->exists() ? 'edit' :
610 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
611 throw new PermissionsError( $action, $permErrors );
614 wfRunHooks( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
616 $wgOut->setRobotPolicy( 'noindex,nofollow' );
617 $wgOut->setPageTitle( wfMessage(
618 'viewsource-title',
619 $this->getContextTitle()->getPrefixedText()
620 ) );
621 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
622 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
623 $wgOut->addHTML( "<hr />\n" );
625 # If the user made changes, preserve them when showing the markup
626 # (This happens when a user is blocked during edit, for instance)
627 if ( !$this->firsttime ) {
628 $text = $this->textbox1;
629 $wgOut->addWikiMsg( 'viewyourtext' );
630 } else {
631 $text = $this->toEditText( $content );
632 $wgOut->addWikiMsg( 'viewsourcetext' );
635 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
637 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
638 Linker::formatTemplates( $this->getTemplates() ) ) );
640 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
642 if ( $this->mTitle->exists() ) {
643 $wgOut->returnToMain( null, $this->mTitle );
648 * Should we show a preview when the edit form is first shown?
650 * @return bool
652 protected function previewOnOpen() {
653 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
654 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
655 // Explicit override from request
656 return true;
657 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
658 // Explicit override from request
659 return false;
660 } elseif ( $this->section == 'new' ) {
661 // Nothing *to* preview for new sections
662 return false;
663 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() )
664 && $wgUser->getOption( 'previewonfirst' )
666 // Standard preference behavior
667 return true;
668 } elseif ( !$this->mTitle->exists()
669 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
670 && $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]
672 // Categories are special
673 return true;
674 } else {
675 return false;
680 * Checks whether the user entered a skin name in uppercase,
681 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
683 * @return bool
685 protected function isWrongCaseCssJsPage() {
686 if ( $this->mTitle->isCssJsSubpage() ) {
687 $name = $this->mTitle->getSkinFromCssJsSubpage();
688 $skins = array_merge(
689 array_keys( Skin::getSkinNames() ),
690 array( 'common' )
692 return !in_array( $name, $skins )
693 && in_array( strtolower( $name ), $skins );
694 } else {
695 return false;
700 * Returns whether section editing is supported for the current page.
701 * Subclasses may override this to replace the default behavior, which is
702 * to check ContentHandler::supportsSections.
704 * @return bool True if this edit page supports sections, false otherwise.
706 protected function isSectionEditSupported() {
707 $contentHandler = ContentHandler::getForTitle( $this->mTitle );
708 return $contentHandler->supportsSections();
712 * This function collects the form data and uses it to populate various member variables.
713 * @param WebRequest $request
714 * @throws ErrorPageError
716 function importFormData( &$request ) {
717 global $wgContLang, $wgUser;
719 wfProfileIn( __METHOD__ );
721 # Section edit can come from either the form or a link
722 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
724 if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
725 wfProfileOut( __METHOD__ );
726 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
729 $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
731 if ( $request->wasPosted() ) {
732 # These fields need to be checked for encoding.
733 # Also remove trailing whitespace, but don't remove _initial_
734 # whitespace from the text boxes. This may be significant formatting.
735 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
736 if ( !$request->getCheck( 'wpTextbox2' ) ) {
737 // Skip this if wpTextbox2 has input, it indicates that we came
738 // from a conflict page with raw page text, not a custom form
739 // modified by subclasses
740 wfProfileIn( get_class( $this ) . "::importContentFormData" );
741 $textbox1 = $this->importContentFormData( $request );
742 if ( $textbox1 !== null ) {
743 $this->textbox1 = $textbox1;
746 wfProfileOut( get_class( $this ) . "::importContentFormData" );
749 # Truncate for whole multibyte characters
750 $this->summary = $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
752 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
753 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
754 # section titles.
755 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
757 # Treat sectiontitle the same way as summary.
758 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
759 # currently doing double duty as both edit summary and section title. Right now this
760 # is just to allow API edits to work around this limitation, but this should be
761 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
762 $this->sectiontitle = $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
763 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
765 $this->edittime = $request->getVal( 'wpEdittime' );
766 $this->starttime = $request->getVal( 'wpStarttime' );
768 $undidRev = $request->getInt( 'wpUndidRevision' );
769 if ( $undidRev ) {
770 $this->undidRev = $undidRev;
773 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
775 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
776 // wpTextbox1 field is missing, possibly due to being "too big"
777 // according to some filter rules such as Suhosin's setting for
778 // suhosin.request.max_value_length (d'oh)
779 $this->incompleteForm = true;
780 } else {
781 // If we receive the last parameter of the request, we can fairly
782 // claim the POST request has not been truncated.
784 // TODO: softened the check for cutover. Once we determine
785 // that it is safe, we should complete the transition by
786 // removing the "edittime" clause.
787 $this->incompleteForm = ( !$request->getVal( 'wpUltimateParam' ) && is_null( $this->edittime ) );
789 if ( $this->incompleteForm ) {
790 # If the form is incomplete, force to preview.
791 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
792 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
793 $this->preview = true;
794 } else {
795 /* Fallback for live preview */
796 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
797 $this->diff = $request->getCheck( 'wpDiff' );
799 // Remember whether a save was requested, so we can indicate
800 // if we forced preview due to session failure.
801 $this->mTriedSave = !$this->preview;
803 if ( $this->tokenOk( $request ) ) {
804 # Some browsers will not report any submit button
805 # if the user hits enter in the comment box.
806 # The unmarked state will be assumed to be a save,
807 # if the form seems otherwise complete.
808 wfDebug( __METHOD__ . ": Passed token check.\n" );
809 } elseif ( $this->diff ) {
810 # Failed token check, but only requested "Show Changes".
811 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
812 } else {
813 # Page might be a hack attempt posted from
814 # an external site. Preview instead of saving.
815 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
816 $this->preview = true;
819 $this->save = !$this->preview && !$this->diff;
820 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
821 $this->edittime = null;
824 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
825 $this->starttime = null;
828 $this->recreate = $request->getCheck( 'wpRecreate' );
830 $this->minoredit = $request->getCheck( 'wpMinoredit' );
831 $this->watchthis = $request->getCheck( 'wpWatchthis' );
833 # Don't force edit summaries when a user is editing their own user or talk page
834 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
835 && $this->mTitle->getText() == $wgUser->getName()
837 $this->allowBlankSummary = true;
838 } else {
839 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
840 || !$wgUser->getOption( 'forceeditsummary' );
843 $this->autoSumm = $request->getText( 'wpAutoSummary' );
845 $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
846 } else {
847 # Not a posted form? Start with nothing.
848 wfDebug( __METHOD__ . ": Not a posted form.\n" );
849 $this->textbox1 = '';
850 $this->summary = '';
851 $this->sectiontitle = '';
852 $this->edittime = '';
853 $this->starttime = wfTimestampNow();
854 $this->edit = false;
855 $this->preview = false;
856 $this->save = false;
857 $this->diff = false;
858 $this->minoredit = false;
859 // Watch may be overridden by request parameters
860 $this->watchthis = $request->getBool( 'watchthis', false );
861 $this->recreate = false;
863 // When creating a new section, we can preload a section title by passing it as the
864 // preloadtitle parameter in the URL (Bug 13100)
865 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
866 $this->sectiontitle = $request->getVal( 'preloadtitle' );
867 // Once wpSummary isn't being use for setting section titles, we should delete this.
868 $this->summary = $request->getVal( 'preloadtitle' );
869 } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
870 $this->summary = $request->getText( 'summary' );
871 if ( $this->summary !== '' ) {
872 $this->hasPresetSummary = true;
876 if ( $request->getVal( 'minor' ) ) {
877 $this->minoredit = true;
881 $this->oldid = $request->getInt( 'oldid' );
883 $this->bot = $request->getBool( 'bot', true );
884 $this->nosummary = $request->getBool( 'nosummary' );
886 // May be overridden by revision.
887 $this->contentModel = $request->getText( 'model', $this->contentModel );
888 // May be overridden by revision.
889 $this->contentFormat = $request->getText( 'format', $this->contentFormat );
891 if ( !ContentHandler::getForModelID( $this->contentModel )
892 ->isSupportedFormat( $this->contentFormat )
894 throw new ErrorPageError(
895 'editpage-notsupportedcontentformat-title',
896 'editpage-notsupportedcontentformat-text',
897 array( $this->contentFormat, ContentHandler::getLocalizedName( $this->contentModel ) )
902 * @todo Check if the desired model is allowed in this namespace, and if
903 * a transition from the page's current model to the new model is
904 * allowed.
907 $this->live = $request->getCheck( 'live' );
908 $this->editintro = $request->getText( 'editintro',
909 // Custom edit intro for new sections
910 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
912 // Allow extensions to modify form data
913 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
915 wfProfileOut( __METHOD__ );
919 * Subpage overridable method for extracting the page content data from the
920 * posted form to be placed in $this->textbox1, if using customized input
921 * this method should be overridden and return the page text that will be used
922 * for saving, preview parsing and so on...
924 * @param WebRequest $request
926 protected function importContentFormData( &$request ) {
927 return; // Don't do anything, EditPage already extracted wpTextbox1
931 * Initialise form fields in the object
932 * Called on the first invocation, e.g. when a user clicks an edit link
933 * @return bool If the requested section is valid
935 function initialiseForm() {
936 global $wgUser;
937 $this->edittime = $this->mArticle->getTimestamp();
939 $content = $this->getContentObject( false ); #TODO: track content object?!
940 if ( $content === false ) {
941 return false;
943 $this->textbox1 = $this->toEditText( $content );
945 // activate checkboxes if user wants them to be always active
946 # Sort out the "watch" checkbox
947 if ( $wgUser->getOption( 'watchdefault' ) ) {
948 # Watch all edits
949 $this->watchthis = true;
950 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
951 # Watch creations
952 $this->watchthis = true;
953 } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
954 # Already watched
955 $this->watchthis = true;
957 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
958 $this->minoredit = true;
960 if ( $this->textbox1 === false ) {
961 return false;
963 return true;
967 * @param Content|null $def_content The default value to return
969 * @return Content|null Content on success, $def_content for invalid sections
971 * @since 1.21
973 protected function getContentObject( $def_content = null ) {
974 global $wgOut, $wgRequest, $wgUser, $wgContLang;
976 wfProfileIn( __METHOD__ );
978 $content = false;
980 // For message page not locally set, use the i18n message.
981 // For other non-existent articles, use preload text if any.
982 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
983 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
984 # If this is a system message, get the default text.
985 $msg = $this->mTitle->getDefaultMessageText();
987 $content = $this->toEditContent( $msg );
989 if ( $content === false ) {
990 # If requested, preload some text.
991 $preload = $wgRequest->getVal( 'preload',
992 // Custom preload text for new sections
993 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
994 $params = $wgRequest->getArray( 'preloadparams', array() );
996 $content = $this->getPreloadedContent( $preload, $params );
998 // For existing pages, get text based on "undo" or section parameters.
999 } else {
1000 if ( $this->section != '' ) {
1001 // Get section edit text (returns $def_text for invalid sections)
1002 $orig = $this->getOriginalContent( $wgUser );
1003 $content = $orig ? $orig->getSection( $this->section ) : null;
1005 if ( !$content ) {
1006 $content = $def_content;
1008 } else {
1009 $undoafter = $wgRequest->getInt( 'undoafter' );
1010 $undo = $wgRequest->getInt( 'undo' );
1012 if ( $undo > 0 && $undoafter > 0 ) {
1014 $undorev = Revision::newFromId( $undo );
1015 $oldrev = Revision::newFromId( $undoafter );
1017 # Sanity check, make sure it's the right page,
1018 # the revisions exist and they were not deleted.
1019 # Otherwise, $content will be left as-is.
1020 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1021 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
1022 !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
1024 $content = $this->mArticle->getUndoContent( $undorev, $oldrev );
1026 if ( $content === false ) {
1027 # Warn the user that something went wrong
1028 $undoMsg = 'failure';
1029 } else {
1030 $oldContent = $this->mArticle->getPage()->getContent( Revision::RAW );
1031 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
1032 $newContent = $content->preSaveTransform( $this->mTitle, $wgUser, $popts );
1034 if ( $newContent->equals( $oldContent ) ) {
1035 # Tell the user that the undo results in no change,
1036 # i.e. the revisions were already undone.
1037 $undoMsg = 'nochange';
1038 $content = false;
1039 } else {
1040 # Inform the user of our success and set an automatic edit summary
1041 $undoMsg = 'success';
1043 # If we just undid one rev, use an autosummary
1044 $firstrev = $oldrev->getNext();
1045 if ( $firstrev && $firstrev->getId() == $undo ) {
1046 $userText = $undorev->getUserText();
1047 if ( $userText === '' ) {
1048 $undoSummary = wfMessage(
1049 'undo-summary-username-hidden',
1050 $undo
1051 )->inContentLanguage()->text();
1052 } else {
1053 $undoSummary = wfMessage(
1054 'undo-summary',
1055 $undo,
1056 $userText
1057 )->inContentLanguage()->text();
1059 if ( $this->summary === '' ) {
1060 $this->summary = $undoSummary;
1061 } else {
1062 $this->summary = $undoSummary . wfMessage( 'colon-separator' )
1063 ->inContentLanguage()->text() . $this->summary;
1065 $this->undidRev = $undo;
1067 $this->formtype = 'diff';
1070 } else {
1071 // Failed basic sanity checks.
1072 // Older revisions may have been removed since the link
1073 // was created, or we may simply have got bogus input.
1074 $undoMsg = 'norev';
1077 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1078 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1079 $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
1080 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1083 if ( $content === false ) {
1084 $content = $this->getOriginalContent( $wgUser );
1089 wfProfileOut( __METHOD__ );
1090 return $content;
1094 * Get the content of the wanted revision, without section extraction.
1096 * The result of this function can be used to compare user's input with
1097 * section replaced in its context (using WikiPage::replaceSection())
1098 * to the original text of the edit.
1100 * This differs from Article::getContent() that when a missing revision is
1101 * encountered the result will be null and not the
1102 * 'missing-revision' message.
1104 * @since 1.19
1105 * @param User $user The user to get the revision for
1106 * @return Content|null
1108 private function getOriginalContent( User $user ) {
1109 if ( $this->section == 'new' ) {
1110 return $this->getCurrentContent();
1112 $revision = $this->mArticle->getRevisionFetched();
1113 if ( $revision === null ) {
1114 if ( !$this->contentModel ) {
1115 $this->contentModel = $this->getTitle()->getContentModel();
1117 $handler = ContentHandler::getForModelID( $this->contentModel );
1119 return $handler->makeEmptyContent();
1121 $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
1122 return $content;
1126 * Get the current content of the page. This is basically similar to
1127 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1128 * content object is returned instead of null.
1130 * @since 1.21
1131 * @return Content
1133 protected function getCurrentContent() {
1134 $rev = $this->mArticle->getRevision();
1135 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1137 if ( $content === false || $content === null ) {
1138 if ( !$this->contentModel ) {
1139 $this->contentModel = $this->getTitle()->getContentModel();
1141 $handler = ContentHandler::getForModelID( $this->contentModel );
1143 return $handler->makeEmptyContent();
1144 } else {
1145 # nasty side-effect, but needed for consistency
1146 $this->contentModel = $rev->getContentModel();
1147 $this->contentFormat = $rev->getContentFormat();
1149 return $content;
1154 * Use this method before edit() to preload some content into the edit box
1156 * @param Content $content
1158 * @since 1.21
1160 public function setPreloadedContent( Content $content ) {
1161 $this->mPreloadContent = $content;
1165 * Get the contents to be preloaded into the box, either set by
1166 * an earlier setPreloadText() or by loading the given page.
1168 * @param string $preload Representing the title to preload from.
1169 * @param array $params Parameters to use (interface-message style) in the preloaded text
1171 * @return Content
1173 * @since 1.21
1175 protected function getPreloadedContent( $preload, $params = array() ) {
1176 global $wgUser;
1178 if ( !empty( $this->mPreloadContent ) ) {
1179 return $this->mPreloadContent;
1182 $handler = ContentHandler::getForTitle( $this->getTitle() );
1184 if ( $preload === '' ) {
1185 return $handler->makeEmptyContent();
1188 $title = Title::newFromText( $preload );
1189 # Check for existence to avoid getting MediaWiki:Noarticletext
1190 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1191 //TODO: somehow show a warning to the user!
1192 return $handler->makeEmptyContent();
1195 $page = WikiPage::factory( $title );
1196 if ( $page->isRedirect() ) {
1197 $title = $page->getRedirectTarget();
1198 # Same as before
1199 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1200 //TODO: somehow show a warning to the user!
1201 return $handler->makeEmptyContent();
1203 $page = WikiPage::factory( $title );
1206 $parserOptions = ParserOptions::newFromUser( $wgUser );
1207 $content = $page->getContent( Revision::RAW );
1209 if ( !$content ) {
1210 //TODO: somehow show a warning to the user!
1211 return $handler->makeEmptyContent();
1214 if ( $content->getModel() !== $handler->getModelID() ) {
1215 $converted = $content->convert( $handler->getModelID() );
1217 if ( !$converted ) {
1218 //TODO: somehow show a warning to the user!
1219 wfDebug( "Attempt to preload incompatible content: "
1220 . "can't convert " . $content->getModel()
1221 . " to " . $handler->getModelID() );
1223 return $handler->makeEmptyContent();
1226 $content = $converted;
1229 return $content->preloadTransform( $title, $parserOptions, $params );
1233 * Make sure the form isn't faking a user's credentials.
1235 * @param WebRequest $request
1236 * @return bool
1237 * @private
1239 function tokenOk( &$request ) {
1240 global $wgUser;
1241 $token = $request->getVal( 'wpEditToken' );
1242 $this->mTokenOk = $wgUser->matchEditToken( $token );
1243 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1244 return $this->mTokenOk;
1248 * Sets post-edit cookie indicating the user just saved a particular revision.
1250 * This uses a temporary cookie for each revision ID so separate saves will never
1251 * interfere with each other.
1253 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1254 * the redirect. It must be clearable by JavaScript code, so it must not be
1255 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1256 * variable.
1258 * If the variable were set on the server, it would be cached, which is unwanted
1259 * since the post-edit state should only apply to the load right after the save.
1261 * @param int $statusValue The status value (to check for new article status)
1263 protected function setPostEditCookie( $statusValue ) {
1264 $revisionId = $this->mArticle->getLatest();
1265 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1267 $val = 'saved';
1268 if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1269 $val = 'created';
1270 } elseif ( $this->oldid ) {
1271 $val = 'restored';
1274 $response = RequestContext::getMain()->getRequest()->response();
1275 $response->setcookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION, array(
1276 'httpOnly' => false,
1277 ) );
1281 * Attempt submission
1282 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1283 * @return bool False if output is done, true if the rest of the form should be displayed
1285 public function attemptSave() {
1286 global $wgUser;
1288 $resultDetails = false;
1289 # Allow bots to exempt some edits from bot flagging
1290 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1291 $status = $this->internalAttemptSave( $resultDetails, $bot );
1293 return $this->handleStatus( $status, $resultDetails );
1297 * Handle status, such as after attempt save
1299 * @param Status $status
1300 * @param array|bool $resultDetails
1302 * @throws ErrorPageError
1303 * @return bool False, if output is done, true if rest of the form should be displayed
1305 private function handleStatus( Status $status, $resultDetails ) {
1306 global $wgUser, $wgOut;
1309 * @todo FIXME: once the interface for internalAttemptSave() is made
1310 * nicer, this should use the message in $status
1312 if ( $status->value == self::AS_SUCCESS_UPDATE
1313 || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1315 $this->didSave = true;
1316 if ( !$resultDetails['nullEdit'] ) {
1317 $this->setPostEditCookie( $status->value );
1321 switch ( $status->value ) {
1322 case self::AS_HOOK_ERROR_EXPECTED:
1323 case self::AS_CONTENT_TOO_BIG:
1324 case self::AS_ARTICLE_WAS_DELETED:
1325 case self::AS_CONFLICT_DETECTED:
1326 case self::AS_SUMMARY_NEEDED:
1327 case self::AS_TEXTBOX_EMPTY:
1328 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1329 case self::AS_END:
1330 case self::AS_BLANK_ARTICLE:
1331 return true;
1333 case self::AS_HOOK_ERROR:
1334 return false;
1336 case self::AS_PARSE_ERROR:
1337 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1338 return true;
1340 case self::AS_SUCCESS_NEW_ARTICLE:
1341 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1342 $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1343 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1344 return false;
1346 case self::AS_SUCCESS_UPDATE:
1347 $extraQuery = '';
1348 $sectionanchor = $resultDetails['sectionanchor'];
1350 // Give extensions a chance to modify URL query on update
1351 wfRunHooks(
1352 'ArticleUpdateBeforeRedirect',
1353 array( $this->mArticle, &$sectionanchor, &$extraQuery )
1356 if ( $resultDetails['redirect'] ) {
1357 if ( $extraQuery == '' ) {
1358 $extraQuery = 'redirect=no';
1359 } else {
1360 $extraQuery = 'redirect=no&' . $extraQuery;
1363 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1364 return false;
1366 case self::AS_SPAM_ERROR:
1367 $this->spamPageWithContent( $resultDetails['spam'] );
1368 return false;
1370 case self::AS_BLOCKED_PAGE_FOR_USER:
1371 throw new UserBlockedError( $wgUser->getBlock() );
1373 case self::AS_IMAGE_REDIRECT_ANON:
1374 case self::AS_IMAGE_REDIRECT_LOGGED:
1375 throw new PermissionsError( 'upload' );
1377 case self::AS_READ_ONLY_PAGE_ANON:
1378 case self::AS_READ_ONLY_PAGE_LOGGED:
1379 throw new PermissionsError( 'edit' );
1381 case self::AS_READ_ONLY_PAGE:
1382 throw new ReadOnlyError;
1384 case self::AS_RATE_LIMITED:
1385 throw new ThrottledError();
1387 case self::AS_NO_CREATE_PERMISSION:
1388 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1389 throw new PermissionsError( $permission );
1391 default:
1392 // We don't recognize $status->value. The only way that can happen
1393 // is if an extension hook aborted from inside ArticleSave.
1394 // Render the status object into $this->hookError
1395 // FIXME this sucks, we should just use the Status object throughout
1396 $this->hookError = '<div class="error">' . $status->getWikitext() .
1397 '</div>';
1398 return true;
1403 * Run hooks that can filter edits just before they get saved.
1405 * @param Content $content The Content to filter.
1406 * @param Status $status For reporting the outcome to the caller
1407 * @param User $user The user performing the edit
1409 * @return bool
1411 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1412 // Run old style post-section-merge edit filter
1413 if ( !ContentHandler::runLegacyHooks( 'EditFilterMerged',
1414 array( $this, $content, &$this->hookError, $this->summary ) ) ) {
1416 # Error messages etc. could be handled within the hook...
1417 $status->fatal( 'hookaborted' );
1418 $status->value = self::AS_HOOK_ERROR;
1419 return false;
1420 } elseif ( $this->hookError != '' ) {
1421 # ...or the hook could be expecting us to produce an error
1422 $status->fatal( 'hookaborted' );
1423 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1424 return false;
1427 // Run new style post-section-merge edit filter
1428 if ( !wfRunHooks( 'EditFilterMergedContent',
1429 array( $this->mArticle->getContext(), $content, $status, $this->summary,
1430 $user, $this->minoredit ) ) ) {
1432 # Error messages etc. could be handled within the hook...
1433 // XXX: $status->value may already be something informative...
1434 $this->hookError = $status->getWikiText();
1435 $status->fatal( 'hookaborted' );
1436 $status->value = self::AS_HOOK_ERROR;
1437 return false;
1438 } elseif ( !$status->isOK() ) {
1439 # ...or the hook could be expecting us to produce an error
1440 // FIXME this sucks, we should just use the Status object throughout
1441 $this->hookError = $status->getWikiText();
1442 $status->fatal( 'hookaborted' );
1443 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1444 return false;
1447 return true;
1451 * Return the summary to be used for a new section.
1453 * @param string $sectionanchor Set to the section anchor text
1454 * @return string
1456 private function newSectionSummary( &$sectionanchor = null ) {
1457 global $wgParser;
1459 if ( $this->sectiontitle !== '' ) {
1460 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1461 // If no edit summary was specified, create one automatically from the section
1462 // title and have it link to the new section. Otherwise, respect the summary as
1463 // passed.
1464 if ( $this->summary === '' ) {
1465 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1466 return wfMessage( 'newsectionsummary' )
1467 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1469 } elseif ( $this->summary !== '' ) {
1470 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1471 # This is a new section, so create a link to the new section
1472 # in the revision summary.
1473 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1474 return wfMessage( 'newsectionsummary' )
1475 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1477 return $this->summary;
1481 * Attempt submission (no UI)
1483 * @param array $result Array to add statuses to, currently with the
1484 * possible keys:
1485 * - spam (string): Spam string from content if any spam is detected by
1486 * matchSpamRegex.
1487 * - sectionanchor (string): Section anchor for a section save.
1488 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1489 * false otherwise.
1490 * - redirect (bool): Set if doEditContent is OK. True if resulting
1491 * revision is a redirect.
1492 * @param bool $bot True if edit is being made under the bot right.
1494 * @return Status Status object, possibly with a message, but always with
1495 * one of the AS_* constants in $status->value,
1497 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1498 * various error display idiosyncrasies. There are also lots of cases
1499 * where error metadata is set in the object and retrieved later instead
1500 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1501 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1502 * time.
1504 function internalAttemptSave( &$result, $bot = false ) {
1505 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1507 $status = Status::newGood();
1509 wfProfileIn( __METHOD__ );
1510 wfProfileIn( __METHOD__ . '-checks' );
1512 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1513 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1514 $status->fatal( 'hookaborted' );
1515 $status->value = self::AS_HOOK_ERROR;
1516 wfProfileOut( __METHOD__ . '-checks' );
1517 wfProfileOut( __METHOD__ );
1518 return $status;
1521 $spam = $wgRequest->getText( 'wpAntispam' );
1522 if ( $spam !== '' ) {
1523 wfDebugLog(
1524 'SimpleAntiSpam',
1525 $wgUser->getName() .
1526 ' editing "' .
1527 $this->mTitle->getPrefixedText() .
1528 '" submitted bogus field "' .
1529 $spam .
1532 $status->fatal( 'spamprotectionmatch', false );
1533 $status->value = self::AS_SPAM_ERROR;
1534 wfProfileOut( __METHOD__ . '-checks' );
1535 wfProfileOut( __METHOD__ );
1536 return $status;
1539 try {
1540 # Construct Content object
1541 $textbox_content = $this->toEditContent( $this->textbox1 );
1542 } catch ( MWContentSerializationException $ex ) {
1543 $status->fatal(
1544 'content-failed-to-parse',
1545 $this->contentModel,
1546 $this->contentFormat,
1547 $ex->getMessage()
1549 $status->value = self::AS_PARSE_ERROR;
1550 wfProfileOut( __METHOD__ . '-checks' );
1551 wfProfileOut( __METHOD__ );
1552 return $status;
1555 # Check image redirect
1556 if ( $this->mTitle->getNamespace() == NS_FILE &&
1557 $textbox_content->isRedirect() &&
1558 !$wgUser->isAllowed( 'upload' )
1560 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1561 $status->setResult( false, $code );
1563 wfProfileOut( __METHOD__ . '-checks' );
1564 wfProfileOut( __METHOD__ );
1566 return $status;
1569 # Check for spam
1570 $match = self::matchSummarySpamRegex( $this->summary );
1571 if ( $match === false && $this->section == 'new' ) {
1572 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1573 # regular summaries, it is added to the actual wikitext.
1574 if ( $this->sectiontitle !== '' ) {
1575 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1576 $match = self::matchSpamRegex( $this->sectiontitle );
1577 } else {
1578 # This branch is taken when the "Add Topic" user interface is used, or the API
1579 # is used with the 'summary' parameter.
1580 $match = self::matchSpamRegex( $this->summary );
1583 if ( $match === false ) {
1584 $match = self::matchSpamRegex( $this->textbox1 );
1586 if ( $match !== false ) {
1587 $result['spam'] = $match;
1588 $ip = $wgRequest->getIP();
1589 $pdbk = $this->mTitle->getPrefixedDBkey();
1590 $match = str_replace( "\n", '', $match );
1591 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1592 $status->fatal( 'spamprotectionmatch', $match );
1593 $status->value = self::AS_SPAM_ERROR;
1594 wfProfileOut( __METHOD__ . '-checks' );
1595 wfProfileOut( __METHOD__ );
1596 return $status;
1598 if ( !wfRunHooks(
1599 'EditFilter',
1600 array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) )
1602 # Error messages etc. could be handled within the hook...
1603 $status->fatal( 'hookaborted' );
1604 $status->value = self::AS_HOOK_ERROR;
1605 wfProfileOut( __METHOD__ . '-checks' );
1606 wfProfileOut( __METHOD__ );
1607 return $status;
1608 } elseif ( $this->hookError != '' ) {
1609 # ...or the hook could be expecting us to produce an error
1610 $status->fatal( 'hookaborted' );
1611 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1612 wfProfileOut( __METHOD__ . '-checks' );
1613 wfProfileOut( __METHOD__ );
1614 return $status;
1617 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1618 // Auto-block user's IP if the account was "hard" blocked
1619 $wgUser->spreadAnyEditBlock();
1620 # Check block state against master, thus 'false'.
1621 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1622 wfProfileOut( __METHOD__ . '-checks' );
1623 wfProfileOut( __METHOD__ );
1624 return $status;
1627 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1628 if ( $this->kblength > $wgMaxArticleSize ) {
1629 // Error will be displayed by showEditForm()
1630 $this->tooBig = true;
1631 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1632 wfProfileOut( __METHOD__ . '-checks' );
1633 wfProfileOut( __METHOD__ );
1634 return $status;
1637 if ( !$wgUser->isAllowed( 'edit' ) ) {
1638 if ( $wgUser->isAnon() ) {
1639 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1640 wfProfileOut( __METHOD__ . '-checks' );
1641 wfProfileOut( __METHOD__ );
1642 return $status;
1643 } else {
1644 $status->fatal( 'readonlytext' );
1645 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1646 wfProfileOut( __METHOD__ . '-checks' );
1647 wfProfileOut( __METHOD__ );
1648 return $status;
1652 if ( wfReadOnly() ) {
1653 $status->fatal( 'readonlytext' );
1654 $status->value = self::AS_READ_ONLY_PAGE;
1655 wfProfileOut( __METHOD__ . '-checks' );
1656 wfProfileOut( __METHOD__ );
1657 return $status;
1659 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1660 $status->fatal( 'actionthrottledtext' );
1661 $status->value = self::AS_RATE_LIMITED;
1662 wfProfileOut( __METHOD__ . '-checks' );
1663 wfProfileOut( __METHOD__ );
1664 return $status;
1667 # If the article has been deleted while editing, don't save it without
1668 # confirmation
1669 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1670 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1671 wfProfileOut( __METHOD__ . '-checks' );
1672 wfProfileOut( __METHOD__ );
1673 return $status;
1676 wfProfileOut( __METHOD__ . '-checks' );
1678 # Load the page data from the master. If anything changes in the meantime,
1679 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1680 $this->mArticle->loadPageData( 'fromdbmaster' );
1681 $new = !$this->mArticle->exists();
1683 if ( $new ) {
1684 // Late check for create permission, just in case *PARANOIA*
1685 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1686 $status->fatal( 'nocreatetext' );
1687 $status->value = self::AS_NO_CREATE_PERMISSION;
1688 wfDebug( __METHOD__ . ": no create permission\n" );
1689 wfProfileOut( __METHOD__ );
1690 return $status;
1693 // Don't save a new page if it's blank or if it's a MediaWiki:
1694 // message with content equivalent to default (allow empty pages
1695 // in this case to disable messages, see bug 50124)
1696 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1697 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1698 $defaultText = $defaultMessageText;
1699 } else {
1700 $defaultText = '';
1703 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
1704 $this->blankArticle = true;
1705 $status->fatal( 'blankarticle' );
1706 $status->setResult( false, self::AS_BLANK_ARTICLE );
1707 wfProfileOut( __METHOD__ );
1708 return $status;
1711 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1712 wfProfileOut( __METHOD__ );
1713 return $status;
1716 $content = $textbox_content;
1718 $result['sectionanchor'] = '';
1719 if ( $this->section == 'new' ) {
1720 if ( $this->sectiontitle !== '' ) {
1721 // Insert the section title above the content.
1722 $content = $content->addSectionHeader( $this->sectiontitle );
1723 } elseif ( $this->summary !== '' ) {
1724 // Insert the section title above the content.
1725 $content = $content->addSectionHeader( $this->summary );
1727 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
1730 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1732 } else { # not $new
1734 # Article exists. Check for edit conflict.
1736 $this->mArticle->clear(); # Force reload of dates, etc.
1737 $timestamp = $this->mArticle->getTimestamp();
1739 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1741 if ( $timestamp != $this->edittime ) {
1742 $this->isConflict = true;
1743 if ( $this->section == 'new' ) {
1744 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
1745 $this->mArticle->getComment() == $this->newSectionSummary()
1747 // Probably a duplicate submission of a new comment.
1748 // This can happen when squid resends a request after
1749 // a timeout but the first one actually went through.
1750 wfDebug( __METHOD__
1751 . ": duplicate new section submission; trigger edit conflict!\n" );
1752 } else {
1753 // New comment; suppress conflict.
1754 $this->isConflict = false;
1755 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1757 } elseif ( $this->section == ''
1758 && Revision::userWasLastToEdit(
1759 DB_MASTER, $this->mTitle->getArticleID(),
1760 $wgUser->getId(), $this->edittime
1763 # Suppress edit conflict with self, except for section edits where merging is required.
1764 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1765 $this->isConflict = false;
1769 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1770 if ( $this->sectiontitle !== '' ) {
1771 $sectionTitle = $this->sectiontitle;
1772 } else {
1773 $sectionTitle = $this->summary;
1776 $content = null;
1778 if ( $this->isConflict ) {
1779 wfDebug( __METHOD__
1780 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1781 . " (article time '{$timestamp}')\n" );
1783 $content = $this->mArticle->replaceSectionContent(
1784 $this->section,
1785 $textbox_content,
1786 $sectionTitle,
1787 $this->edittime
1789 } else {
1790 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
1791 $content = $this->mArticle->replaceSectionContent(
1792 $this->section,
1793 $textbox_content,
1794 $sectionTitle
1798 if ( is_null( $content ) ) {
1799 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1800 $this->isConflict = true;
1801 $content = $textbox_content; // do not try to merge here!
1802 } elseif ( $this->isConflict ) {
1803 # Attempt merge
1804 if ( $this->mergeChangesIntoContent( $content ) ) {
1805 // Successful merge! Maybe we should tell the user the good news?
1806 $this->isConflict = false;
1807 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1808 } else {
1809 $this->section = '';
1810 $this->textbox1 = ContentHandler::getContentText( $content );
1811 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1815 if ( $this->isConflict ) {
1816 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1817 wfProfileOut( __METHOD__ );
1818 return $status;
1821 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1822 wfProfileOut( __METHOD__ );
1823 return $status;
1826 if ( $this->section == 'new' ) {
1827 // Handle the user preference to force summaries here
1828 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
1829 $this->missingSummary = true;
1830 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1831 $status->value = self::AS_SUMMARY_NEEDED;
1832 wfProfileOut( __METHOD__ );
1833 return $status;
1836 // Do not allow the user to post an empty comment
1837 if ( $this->textbox1 == '' ) {
1838 $this->missingComment = true;
1839 $status->fatal( 'missingcommenttext' );
1840 $status->value = self::AS_TEXTBOX_EMPTY;
1841 wfProfileOut( __METHOD__ );
1842 return $status;
1844 } elseif ( !$this->allowBlankSummary
1845 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1846 && !$content->isRedirect()
1847 && md5( $this->summary ) == $this->autoSumm
1849 $this->missingSummary = true;
1850 $status->fatal( 'missingsummary' );
1851 $status->value = self::AS_SUMMARY_NEEDED;
1852 wfProfileOut( __METHOD__ );
1853 return $status;
1856 # All's well
1857 wfProfileIn( __METHOD__ . '-sectionanchor' );
1858 $sectionanchor = '';
1859 if ( $this->section == 'new' ) {
1860 $this->summary = $this->newSectionSummary( $sectionanchor );
1861 } elseif ( $this->section != '' ) {
1862 # Try to get a section anchor from the section source, redirect
1863 # to edited section if header found.
1864 # XXX: Might be better to integrate this into Article::replaceSection
1865 # for duplicate heading checking and maybe parsing.
1866 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1867 # We can't deal with anchors, includes, html etc in the header for now,
1868 # headline would need to be parsed to improve this.
1869 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1870 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1873 $result['sectionanchor'] = $sectionanchor;
1874 wfProfileOut( __METHOD__ . '-sectionanchor' );
1876 // Save errors may fall down to the edit form, but we've now
1877 // merged the section into full text. Clear the section field
1878 // so that later submission of conflict forms won't try to
1879 // replace that into a duplicated mess.
1880 $this->textbox1 = $this->toEditText( $content );
1881 $this->section = '';
1883 $status->value = self::AS_SUCCESS_UPDATE;
1886 // Check for length errors again now that the section is merged in
1887 $this->kblength = (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1888 if ( $this->kblength > $wgMaxArticleSize ) {
1889 $this->tooBig = true;
1890 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
1891 wfProfileOut( __METHOD__ );
1892 return $status;
1895 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1896 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1897 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1898 ( $bot ? EDIT_FORCE_BOT : 0 );
1900 $doEditStatus = $this->mArticle->doEditContent( $content, $this->summary, $flags,
1901 false, null, $this->contentFormat );
1903 if ( !$doEditStatus->isOK() ) {
1904 // Failure from doEdit()
1905 // Show the edit conflict page for certain recognized errors from doEdit(),
1906 // but don't show it for errors from extension hooks
1907 $errors = $doEditStatus->getErrorsArray();
1908 if ( in_array( $errors[0][0],
1909 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1911 $this->isConflict = true;
1912 // Destroys data doEdit() put in $status->value but who cares
1913 $doEditStatus->value = self::AS_END;
1915 wfProfileOut( __METHOD__ );
1916 return $doEditStatus;
1919 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1920 if ( $result['nullEdit'] ) {
1921 // We don't know if it was a null edit until now, so increment here
1922 $wgUser->pingLimiter( 'linkpurge' );
1924 $result['redirect'] = $content->isRedirect();
1925 $this->updateWatchlist();
1926 wfProfileOut( __METHOD__ );
1927 return $status;
1931 * Register the change of watch status
1933 protected function updateWatchlist() {
1934 global $wgUser;
1936 if ( $wgUser->isLoggedIn()
1937 && $this->watchthis != $wgUser->isWatched( $this->mTitle, WatchedItem::IGNORE_USER_RIGHTS )
1939 $fname = __METHOD__;
1940 $title = $this->mTitle;
1941 $watch = $this->watchthis;
1943 // Do this in its own transaction to reduce contention...
1944 $dbw = wfGetDB( DB_MASTER );
1945 $dbw->onTransactionIdle( function () use ( $dbw, $title, $watch, $wgUser, $fname ) {
1946 $dbw->begin( $fname );
1947 WatchAction::doWatchOrUnwatch( $watch, $title, $wgUser );
1948 $dbw->commit( $fname );
1949 } );
1954 * Attempts to do 3-way merge of edit content with a base revision
1955 * and current content, in case of edit conflict, in whichever way appropriate
1956 * for the content type.
1958 * @since 1.21
1960 * @param Content $editContent
1962 * @return bool
1964 private function mergeChangesIntoContent( &$editContent ) {
1965 wfProfileIn( __METHOD__ );
1967 $db = wfGetDB( DB_MASTER );
1969 // This is the revision the editor started from
1970 $baseRevision = $this->getBaseRevision();
1971 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
1973 if ( is_null( $baseContent ) ) {
1974 wfProfileOut( __METHOD__ );
1975 return false;
1978 // The current state, we want to merge updates into it
1979 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1980 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
1982 if ( is_null( $currentContent ) ) {
1983 wfProfileOut( __METHOD__ );
1984 return false;
1987 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
1989 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1991 if ( $result ) {
1992 $editContent = $result;
1993 wfProfileOut( __METHOD__ );
1994 return true;
1997 wfProfileOut( __METHOD__ );
1998 return false;
2002 * @return Revision
2004 function getBaseRevision() {
2005 if ( !$this->mBaseRevision ) {
2006 $db = wfGetDB( DB_MASTER );
2007 $this->mBaseRevision = Revision::loadFromTimestamp(
2008 $db, $this->mTitle, $this->edittime );
2010 return $this->mBaseRevision;
2014 * Check given input text against $wgSpamRegex, and return the text of the first match.
2016 * @param string $text
2018 * @return string|bool Matching string or false
2020 public static function matchSpamRegex( $text ) {
2021 global $wgSpamRegex;
2022 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2023 $regexes = (array)$wgSpamRegex;
2024 return self::matchSpamRegexInternal( $text, $regexes );
2028 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2030 * @param string $text
2032 * @return string|bool Matching string or false
2034 public static function matchSummarySpamRegex( $text ) {
2035 global $wgSummarySpamRegex;
2036 $regexes = (array)$wgSummarySpamRegex;
2037 return self::matchSpamRegexInternal( $text, $regexes );
2041 * @param string $text
2042 * @param array $regexes
2043 * @return bool|string
2045 protected static function matchSpamRegexInternal( $text, $regexes ) {
2046 foreach ( $regexes as $regex ) {
2047 $matches = array();
2048 if ( preg_match( $regex, $text, $matches ) ) {
2049 return $matches[0];
2052 return false;
2055 function setHeaders() {
2056 global $wgOut, $wgUser;
2058 $wgOut->addModules( 'mediawiki.action.edit' );
2059 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2061 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
2062 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2065 if ( $wgUser->getOption( 'useeditwarning', false ) ) {
2066 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2069 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2071 # Enabled article-related sidebar, toplinks, etc.
2072 $wgOut->setArticleRelated( true );
2074 $contextTitle = $this->getContextTitle();
2075 if ( $this->isConflict ) {
2076 $msg = 'editconflict';
2077 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2078 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2079 } else {
2080 $msg = $contextTitle->exists()
2081 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2082 && $contextTitle->getDefaultMessageText() !== false
2084 ? 'editing'
2085 : 'creating';
2088 # Use the title defined by DISPLAYTITLE magic word when present
2089 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2090 if ( $displayTitle === false ) {
2091 $displayTitle = $contextTitle->getPrefixedText();
2093 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2097 * Show all applicable editing introductions
2099 protected function showIntro() {
2100 global $wgOut, $wgUser;
2101 if ( $this->suppressIntro ) {
2102 return;
2105 $namespace = $this->mTitle->getNamespace();
2107 if ( $namespace == NS_MEDIAWIKI ) {
2108 # Show a warning if editing an interface message
2109 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2110 } elseif ( $namespace == NS_FILE ) {
2111 # Show a hint to shared repo
2112 $file = wfFindFile( $this->mTitle );
2113 if ( $file && !$file->isLocal() ) {
2114 $descUrl = $file->getDescriptionUrl();
2115 # there must be a description url to show a hint to shared repo
2116 if ( $descUrl ) {
2117 if ( !$this->mTitle->exists() ) {
2118 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2119 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2120 ) );
2121 } else {
2122 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2123 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2124 ) );
2130 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2131 # Show log extract when the user is currently blocked
2132 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2133 $parts = explode( '/', $this->mTitle->getText(), 2 );
2134 $username = $parts[0];
2135 $user = User::newFromName( $username, false /* allow IP users*/ );
2136 $ip = User::isIP( $username );
2137 $block = Block::newFromTarget( $user, $user );
2138 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2139 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2140 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2141 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) { # Show log extract if the user is currently blocked
2142 LogEventsList::showLogExtract(
2143 $wgOut,
2144 'block',
2145 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2147 array(
2148 'lim' => 1,
2149 'showIfEmpty' => false,
2150 'msgKey' => array(
2151 'blocked-notice-logextract',
2152 $user->getName() # Support GENDER in notice
2158 # Try to add a custom edit intro, or use the standard one if this is not possible.
2159 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2160 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2161 wfMessage( 'helppage' )->inContentLanguage()->text()
2162 ) );
2163 if ( $wgUser->isLoggedIn() ) {
2164 $wgOut->wrapWikiMsg(
2165 // Suppress the external link icon, consider the help url an internal one
2166 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2167 array(
2168 'newarticletext',
2169 $helpLink
2172 } else {
2173 $wgOut->wrapWikiMsg(
2174 // Suppress the external link icon, consider the help url an internal one
2175 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2176 array(
2177 'newarticletextanon',
2178 $helpLink
2183 # Give a notice if the user is editing a deleted/moved page...
2184 if ( !$this->mTitle->exists() ) {
2185 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
2187 array(
2188 'lim' => 10,
2189 'conds' => array( "log_action != 'revision'" ),
2190 'showIfEmpty' => false,
2191 'msgKey' => array( 'recreate-moveddeleted-warn' )
2198 * Attempt to show a custom editing introduction, if supplied
2200 * @return bool
2202 protected function showCustomIntro() {
2203 if ( $this->editintro ) {
2204 $title = Title::newFromText( $this->editintro );
2205 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2206 global $wgOut;
2207 // Added using template syntax, to take <noinclude>'s into account.
2208 $wgOut->addWikiTextTitleTidy( '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>', $this->mTitle );
2209 return true;
2212 return false;
2216 * Gets an editable textual representation of $content.
2217 * The textual representation can be turned by into a Content object by the
2218 * toEditContent() method.
2220 * If $content is null or false or a string, $content is returned unchanged.
2222 * If the given Content object is not of a type that can be edited using
2223 * the text base EditPage, an exception will be raised. Set
2224 * $this->allowNonTextContent to true to allow editing of non-textual
2225 * content.
2227 * @param Content|null|bool|string $content
2228 * @return string The editable text form of the content.
2230 * @throws MWException If $content is not an instance of TextContent and
2231 * $this->allowNonTextContent is not true.
2233 protected function toEditText( $content ) {
2234 if ( $content === null || $content === false ) {
2235 return $content;
2238 if ( is_string( $content ) ) {
2239 return $content;
2242 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2243 throw new MWException( 'This content model is not supported: '
2244 . ContentHandler::getLocalizedName( $content->getModel() ) );
2247 return $content->serialize( $this->contentFormat );
2251 * Turns the given text into a Content object by unserializing it.
2253 * If the resulting Content object is not of a type that can be edited using
2254 * the text base EditPage, an exception will be raised. Set
2255 * $this->allowNonTextContent to true to allow editing of non-textual
2256 * content.
2258 * @param string|null|bool $text Text to unserialize
2259 * @return Content The content object created from $text. If $text was false
2260 * or null, false resp. null will be returned instead.
2262 * @throws MWException If unserializing the text results in a Content
2263 * object that is not an instance of TextContent and
2264 * $this->allowNonTextContent is not true.
2266 protected function toEditContent( $text ) {
2267 if ( $text === false || $text === null ) {
2268 return $text;
2271 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2272 $this->contentModel, $this->contentFormat );
2274 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2275 throw new MWException( 'This content model is not supported: '
2276 . ContentHandler::getLocalizedName( $content->getModel() ) );
2279 return $content;
2283 * Send the edit form and related headers to $wgOut
2284 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2285 * during form output near the top, for captchas and the like.
2287 function showEditForm( $formCallback = null ) {
2288 global $wgOut, $wgUser;
2290 wfProfileIn( __METHOD__ );
2292 # need to parse the preview early so that we know which templates are used,
2293 # otherwise users with "show preview after edit box" will get a blank list
2294 # we parse this near the beginning so that setHeaders can do the title
2295 # setting work instead of leaving it in getPreviewText
2296 $previewOutput = '';
2297 if ( $this->formtype == 'preview' ) {
2298 $previewOutput = $this->getPreviewText();
2301 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2303 $this->setHeaders();
2305 if ( $this->showHeader() === false ) {
2306 wfProfileOut( __METHOD__ );
2307 return;
2310 $wgOut->addHTML( $this->editFormPageTop );
2312 if ( $wgUser->getOption( 'previewontop' ) ) {
2313 $this->displayPreviewArea( $previewOutput, true );
2316 $wgOut->addHTML( $this->editFormTextTop );
2318 $showToolbar = true;
2319 if ( $this->wasDeletedSinceLastEdit() ) {
2320 if ( $this->formtype == 'save' ) {
2321 // Hide the toolbar and edit area, user can click preview to get it back
2322 // Add an confirmation checkbox and explanation.
2323 $showToolbar = false;
2324 } else {
2325 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2326 'deletedwhileediting' );
2330 // @todo add EditForm plugin interface and use it here!
2331 // search for textarea1 and textares2, and allow EditForm to override all uses.
2332 $wgOut->addHTML( Html::openElement(
2333 'form',
2334 array(
2335 'id' => self::EDITFORM_ID,
2336 'name' => self::EDITFORM_ID,
2337 'method' => 'post',
2338 'action' => $this->getActionURL( $this->getContextTitle() ),
2339 'enctype' => 'multipart/form-data'
2341 ) );
2343 if ( is_callable( $formCallback ) ) {
2344 call_user_func_array( $formCallback, array( &$wgOut ) );
2347 // Add an empty field to trip up spambots
2348 $wgOut->addHTML(
2349 Xml::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2350 . Html::rawElement(
2351 'label',
2352 array( 'for' => 'wpAntiSpam' ),
2353 wfMessage( 'simpleantispam-label' )->parse()
2355 . Xml::element(
2356 'input',
2357 array(
2358 'type' => 'text',
2359 'name' => 'wpAntispam',
2360 'id' => 'wpAntispam',
2361 'value' => ''
2364 . Xml::closeElement( 'div' )
2367 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2369 // Put these up at the top to ensure they aren't lost on early form submission
2370 $this->showFormBeforeText();
2372 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2373 $username = $this->lastDelete->user_name;
2374 $comment = $this->lastDelete->log_comment;
2376 // It is better to not parse the comment at all than to have templates expanded in the middle
2377 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2378 $key = $comment === ''
2379 ? 'confirmrecreate-noreason'
2380 : 'confirmrecreate';
2381 $wgOut->addHTML(
2382 '<div class="mw-confirm-recreate">' .
2383 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2384 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2385 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2387 '</div>'
2391 # When the summary is hidden, also hide them on preview/show changes
2392 if ( $this->nosummary ) {
2393 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2396 # If a blank edit summary was previously provided, and the appropriate
2397 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2398 # user being bounced back more than once in the event that a summary
2399 # is not required.
2400 #####
2401 # For a bit more sophisticated detection of blank summaries, hash the
2402 # automatic one and pass that in the hidden field wpAutoSummary.
2403 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2404 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2407 if ( $this->undidRev ) {
2408 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2411 if ( $this->hasPresetSummary ) {
2412 // If a summary has been preset using &summary= we don't want to prompt for
2413 // a different summary. Only prompt for a summary if the summary is blanked.
2414 // (Bug 17416)
2415 $this->autoSumm = md5( '' );
2418 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2419 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2421 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2423 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2424 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2426 if ( $this->section == 'new' ) {
2427 $this->showSummaryInput( true, $this->summary );
2428 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2431 $wgOut->addHTML( $this->editFormTextBeforeContent );
2433 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2434 $wgOut->addHTML( EditPage::getEditToolbar() );
2437 if ( $this->blankArticle ) {
2438 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2441 if ( $this->isConflict ) {
2442 // In an edit conflict bypass the overridable content form method
2443 // and fallback to the raw wpTextbox1 since editconflicts can't be
2444 // resolved between page source edits and custom ui edits using the
2445 // custom edit ui.
2446 $this->textbox2 = $this->textbox1;
2448 $content = $this->getCurrentContent();
2449 $this->textbox1 = $this->toEditText( $content );
2451 $this->showTextbox1();
2452 } else {
2453 $this->showContentForm();
2456 $wgOut->addHTML( $this->editFormTextAfterContent );
2458 $this->showStandardInputs();
2460 $this->showFormAfterText();
2462 $this->showTosSummary();
2464 $this->showEditTools();
2466 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2468 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2469 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2471 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2472 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
2474 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'limitreport' ),
2475 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2477 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2479 if ( $this->isConflict ) {
2480 try {
2481 $this->showConflict();
2482 } catch ( MWContentSerializationException $ex ) {
2483 // this can't really happen, but be nice if it does.
2484 $msg = wfMessage(
2485 'content-failed-to-parse',
2486 $this->contentModel,
2487 $this->contentFormat,
2488 $ex->getMessage()
2490 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2494 // Marker for detecting truncated form data. This must be the last
2495 // parameter sent in order to be of use, so do not move me.
2496 $wgOut->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2497 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2499 if ( !$wgUser->getOption( 'previewontop' ) ) {
2500 $this->displayPreviewArea( $previewOutput, false );
2503 wfProfileOut( __METHOD__ );
2507 * Extract the section title from current section text, if any.
2509 * @param string $text
2510 * @return string|bool String or false
2512 public static function extractSectionTitle( $text ) {
2513 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2514 if ( !empty( $matches[2] ) ) {
2515 global $wgParser;
2516 return $wgParser->stripSectionName( trim( $matches[2] ) );
2517 } else {
2518 return false;
2523 * @return bool
2525 protected function showHeader() {
2526 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2527 global $wgAllowUserCss, $wgAllowUserJs;
2529 if ( $this->mTitle->isTalkPage() ) {
2530 $wgOut->addWikiMsg( 'talkpagetext' );
2533 // Add edit notices
2534 $wgOut->addHTML( implode( "\n", $this->mTitle->getEditNotices( $this->oldid ) ) );
2536 if ( $this->isConflict ) {
2537 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2538 $this->edittime = $this->mArticle->getTimestamp();
2539 } else {
2540 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2541 // We use $this->section to much before this and getVal('wgSection') directly in other places
2542 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2543 // Someone is welcome to try refactoring though
2544 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2545 return false;
2548 if ( $this->section != '' && $this->section != 'new' ) {
2549 if ( !$this->summary && !$this->preview && !$this->diff ) {
2550 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); //FIXME: use Content object
2551 if ( $sectionTitle !== false ) {
2552 $this->summary = "/* $sectionTitle */ ";
2557 if ( $this->missingComment ) {
2558 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2561 if ( $this->missingSummary && $this->section != 'new' ) {
2562 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2565 if ( $this->missingSummary && $this->section == 'new' ) {
2566 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2569 if ( $this->blankArticle ) {
2570 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2573 if ( $this->hookError !== '' ) {
2574 $wgOut->addWikiText( $this->hookError );
2577 if ( !$this->checkUnicodeCompliantBrowser() ) {
2578 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2581 if ( $this->section != 'new' ) {
2582 $revision = $this->mArticle->getRevisionFetched();
2583 if ( $revision ) {
2584 // Let sysop know that this will make private content public if saved
2586 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2587 $wgOut->wrapWikiMsg(
2588 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2589 'rev-deleted-text-permission'
2591 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2592 $wgOut->wrapWikiMsg(
2593 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2594 'rev-deleted-text-view'
2598 if ( !$revision->isCurrent() ) {
2599 $this->mArticle->setOldSubtitle( $revision->getId() );
2600 $wgOut->addWikiMsg( 'editingold' );
2602 } elseif ( $this->mTitle->exists() ) {
2603 // Something went wrong
2605 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2606 array( 'missing-revision', $this->oldid ) );
2611 if ( wfReadOnly() ) {
2612 $wgOut->wrapWikiMsg(
2613 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2614 array( 'readonlywarning', wfReadOnlyReason() )
2616 } elseif ( $wgUser->isAnon() ) {
2617 if ( $this->formtype != 'preview' ) {
2618 $wgOut->wrapWikiMsg(
2619 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2620 array( 'anoneditwarning',
2621 // Log-in link
2622 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2623 // Sign-up link
2624 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2626 } else {
2627 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2628 'anonpreviewwarning'
2631 } else {
2632 if ( $this->isCssJsSubpage ) {
2633 # Check the skin exists
2634 if ( $this->isWrongCaseCssJsPage ) {
2635 $wgOut->wrapWikiMsg(
2636 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2637 array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() )
2640 if ( $this->formtype !== 'preview' ) {
2641 if ( $this->isCssSubpage && $wgAllowUserCss ) {
2642 $wgOut->wrapWikiMsg(
2643 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2644 array( 'usercssyoucanpreview' )
2648 if ( $this->isJsSubpage && $wgAllowUserJs ) {
2649 $wgOut->wrapWikiMsg(
2650 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2651 array( 'userjsyoucanpreview' )
2658 if ( $this->mTitle->isProtected( 'edit' ) &&
2659 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2661 # Is the title semi-protected?
2662 if ( $this->mTitle->isSemiProtected() ) {
2663 $noticeMsg = 'semiprotectedpagewarning';
2664 } else {
2665 # Then it must be protected based on static groups (regular)
2666 $noticeMsg = 'protectedpagewarning';
2668 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2669 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2671 if ( $this->mTitle->isCascadeProtected() ) {
2672 # Is this page under cascading protection from some source pages?
2673 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2674 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2675 $cascadeSourcesCount = count( $cascadeSources );
2676 if ( $cascadeSourcesCount > 0 ) {
2677 # Explain, and list the titles responsible
2678 foreach ( $cascadeSources as $page ) {
2679 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2682 $notice .= '</div>';
2683 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2685 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2686 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2687 array( 'lim' => 1,
2688 'showIfEmpty' => false,
2689 'msgKey' => array( 'titleprotectedwarning' ),
2690 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2693 if ( $this->kblength === false ) {
2694 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2697 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2698 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2699 array(
2700 'longpageerror',
2701 $wgLang->formatNum( $this->kblength ),
2702 $wgLang->formatNum( $wgMaxArticleSize )
2705 } else {
2706 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2707 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2708 array(
2709 'longpage-hint',
2710 $wgLang->formatSize( strlen( $this->textbox1 ) ),
2711 strlen( $this->textbox1 )
2716 # Add header copyright warning
2717 $this->showHeaderCopyrightWarning();
2719 return true;
2723 * Standard summary input and label (wgSummary), abstracted so EditPage
2724 * subclasses may reorganize the form.
2725 * Note that you do not need to worry about the label's for=, it will be
2726 * inferred by the id given to the input. You can remove them both by
2727 * passing array( 'id' => false ) to $userInputAttrs.
2729 * @param string $summary The value of the summary input
2730 * @param string $labelText The html to place inside the label
2731 * @param array $inputAttrs Array of attrs to use on the input
2732 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2734 * @return array An array in the format array( $label, $input )
2736 function getSummaryInput( $summary = "", $labelText = null,
2737 $inputAttrs = null, $spanLabelAttrs = null
2739 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2740 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2741 'id' => 'wpSummary',
2742 'maxlength' => '200',
2743 'tabindex' => '1',
2744 'size' => 60,
2745 'spellcheck' => 'true',
2746 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2748 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2749 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2750 'id' => "wpSummaryLabel"
2753 $label = null;
2754 if ( $labelText ) {
2755 $label = Xml::tags(
2756 'label',
2757 $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null,
2758 $labelText
2760 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2763 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2765 return array( $label, $input );
2769 * @param bool $isSubjectPreview True if this is the section subject/title
2770 * up top, or false if this is the comment summary
2771 * down below the textarea
2772 * @param string $summary The text of the summary to display
2774 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2775 global $wgOut, $wgContLang;
2776 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2777 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2778 if ( $isSubjectPreview ) {
2779 if ( $this->nosummary ) {
2780 return;
2782 } else {
2783 if ( !$this->mShowSummaryField ) {
2784 return;
2787 $summary = $wgContLang->recodeForEdit( $summary );
2788 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2789 list( $label, $input ) = $this->getSummaryInput(
2790 $summary,
2791 $labelText,
2792 array( 'class' => $summaryClass ),
2793 array()
2795 $wgOut->addHTML( "{$label} {$input}" );
2799 * @param bool $isSubjectPreview True if this is the section subject/title
2800 * up top, or false if this is the comment summary
2801 * down below the textarea
2802 * @param string $summary The text of the summary to display
2803 * @return string
2805 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2806 // avoid spaces in preview, gets always trimmed on save
2807 $summary = trim( $summary );
2808 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
2809 return "";
2812 global $wgParser;
2814 if ( $isSubjectPreview ) {
2815 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2816 ->inContentLanguage()->text();
2819 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2821 $summary = wfMessage( $message )->parse()
2822 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2823 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2826 protected function showFormBeforeText() {
2827 global $wgOut;
2828 $section = htmlspecialchars( $this->section );
2829 $wgOut->addHTML( <<<HTML
2830 <input type='hidden' value="{$section}" name="wpSection" />
2831 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2832 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2833 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2835 HTML
2837 if ( !$this->checkUnicodeCompliantBrowser() ) {
2838 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2842 protected function showFormAfterText() {
2843 global $wgOut, $wgUser;
2845 * To make it harder for someone to slip a user a page
2846 * which submits an edit form to the wiki without their
2847 * knowledge, a random token is associated with the login
2848 * session. If it's not passed back with the submission,
2849 * we won't save the page, or render user JavaScript and
2850 * CSS previews.
2852 * For anon editors, who may not have a session, we just
2853 * include the constant suffix to prevent editing from
2854 * broken text-mangling proxies.
2856 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2860 * Subpage overridable method for printing the form for page content editing
2861 * By default this simply outputs wpTextbox1
2862 * Subclasses can override this to provide a custom UI for editing;
2863 * be it a form, or simply wpTextbox1 with a modified content that will be
2864 * reverse modified when extracted from the post data.
2865 * Note that this is basically the inverse for importContentFormData
2867 protected function showContentForm() {
2868 $this->showTextbox1();
2872 * Method to output wpTextbox1
2873 * The $textoverride method can be used by subclasses overriding showContentForm
2874 * to pass back to this method.
2876 * @param array $customAttribs Array of html attributes to use in the textarea
2877 * @param string $textoverride Optional text to override $this->textarea1 with
2879 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2880 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2881 $attribs = array( 'style' => 'display:none;' );
2882 } else {
2883 $classes = array(); // Textarea CSS
2884 if ( $this->mTitle->isProtected( 'edit' ) &&
2885 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2887 # Is the title semi-protected?
2888 if ( $this->mTitle->isSemiProtected() ) {
2889 $classes[] = 'mw-textarea-sprotected';
2890 } else {
2891 # Then it must be protected based on static groups (regular)
2892 $classes[] = 'mw-textarea-protected';
2894 # Is the title cascade-protected?
2895 if ( $this->mTitle->isCascadeProtected() ) {
2896 $classes[] = 'mw-textarea-cprotected';
2900 $attribs = array( 'tabindex' => 1 );
2902 if ( is_array( $customAttribs ) ) {
2903 $attribs += $customAttribs;
2906 if ( count( $classes ) ) {
2907 if ( isset( $attribs['class'] ) ) {
2908 $classes[] = $attribs['class'];
2910 $attribs['class'] = implode( ' ', $classes );
2914 $this->showTextbox(
2915 $textoverride !== null ? $textoverride : $this->textbox1,
2916 'wpTextbox1',
2917 $attribs
2921 protected function showTextbox2() {
2922 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2925 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2926 global $wgOut, $wgUser;
2928 $wikitext = $this->safeUnicodeOutput( $text );
2929 if ( strval( $wikitext ) !== '' ) {
2930 // Ensure there's a newline at the end, otherwise adding lines
2931 // is awkward.
2932 // But don't add a newline if the ext is empty, or Firefox in XHTML
2933 // mode will show an extra newline. A bit annoying.
2934 $wikitext .= "\n";
2937 $attribs = $customAttribs + array(
2938 'accesskey' => ',',
2939 'id' => $name,
2940 'cols' => $wgUser->getIntOption( 'cols' ),
2941 'rows' => $wgUser->getIntOption( 'rows' ),
2942 // Avoid PHP notices when appending preferences
2943 // (appending allows customAttribs['style'] to still work).
2944 'style' => ''
2947 $pageLang = $this->mTitle->getPageLanguage();
2948 $attribs['lang'] = $pageLang->getCode();
2949 $attribs['dir'] = $pageLang->getDir();
2951 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
2954 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2955 global $wgOut;
2956 $classes = array();
2957 if ( $isOnTop ) {
2958 $classes[] = 'ontop';
2961 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2963 if ( $this->formtype != 'preview' ) {
2964 $attribs['style'] = 'display: none;';
2967 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
2969 if ( $this->formtype == 'preview' ) {
2970 $this->showPreview( $previewOutput );
2973 $wgOut->addHTML( '</div>' );
2975 if ( $this->formtype == 'diff' ) {
2976 try {
2977 $this->showDiff();
2978 } catch ( MWContentSerializationException $ex ) {
2979 $msg = wfMessage(
2980 'content-failed-to-parse',
2981 $this->contentModel,
2982 $this->contentFormat,
2983 $ex->getMessage()
2985 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2991 * Append preview output to $wgOut.
2992 * Includes category rendering if this is a category page.
2994 * @param string $text The HTML to be output for the preview.
2996 protected function showPreview( $text ) {
2997 global $wgOut;
2998 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2999 $this->mArticle->openShowCategory();
3001 # This hook seems slightly odd here, but makes things more
3002 # consistent for extensions.
3003 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3004 $wgOut->addHTML( $text );
3005 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3006 $this->mArticle->closeShowCategory();
3011 * Get a diff between the current contents of the edit box and the
3012 * version of the page we're editing from.
3014 * If this is a section edit, we'll replace the section as for final
3015 * save and then make a comparison.
3017 function showDiff() {
3018 global $wgUser, $wgContLang, $wgOut;
3020 $oldtitlemsg = 'currentrev';
3021 # if message does not exist, show diff against the preloaded default
3022 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3023 $oldtext = $this->mTitle->getDefaultMessageText();
3024 if ( $oldtext !== false ) {
3025 $oldtitlemsg = 'defaultmessagetext';
3026 $oldContent = $this->toEditContent( $oldtext );
3027 } else {
3028 $oldContent = null;
3030 } else {
3031 $oldContent = $this->getCurrentContent();
3034 $textboxContent = $this->toEditContent( $this->textbox1 );
3036 $newContent = $this->mArticle->replaceSectionContent(
3037 $this->section, $textboxContent,
3038 $this->summary, $this->edittime );
3040 if ( $newContent ) {
3041 ContentHandler::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3042 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3044 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
3045 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
3048 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3049 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3050 $newtitle = wfMessage( 'yourtext' )->parse();
3052 if ( !$oldContent ) {
3053 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3056 if ( !$newContent ) {
3057 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3060 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
3061 $de->setContent( $oldContent, $newContent );
3063 $difftext = $de->getDiff( $oldtitle, $newtitle );
3064 $de->showDiffStyle();
3065 } else {
3066 $difftext = '';
3069 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3073 * Show the header copyright warning.
3075 protected function showHeaderCopyrightWarning() {
3076 $msg = 'editpage-head-copy-warn';
3077 if ( !wfMessage( $msg )->isDisabled() ) {
3078 global $wgOut;
3079 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3080 'editpage-head-copy-warn' );
3085 * Give a chance for site and per-namespace customizations of
3086 * terms of service summary link that might exist separately
3087 * from the copyright notice.
3089 * This will display between the save button and the edit tools,
3090 * so should remain short!
3092 protected function showTosSummary() {
3093 $msg = 'editpage-tos-summary';
3094 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
3095 if ( !wfMessage( $msg )->isDisabled() ) {
3096 global $wgOut;
3097 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3098 $wgOut->addWikiMsg( $msg );
3099 $wgOut->addHTML( '</div>' );
3103 protected function showEditTools() {
3104 global $wgOut;
3105 $wgOut->addHTML( '<div class="mw-editTools">' .
3106 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3107 '</div>' );
3111 * Get the copyright warning
3113 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3114 * @return string
3116 protected function getCopywarn() {
3117 return self::getCopyrightWarning( $this->mTitle );
3121 * Get the copyright warning, by default returns wikitext
3123 * @param Title $title
3124 * @param string $format Output format, valid values are any function of a Message object
3125 * @return string
3127 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3128 global $wgRightsText;
3129 if ( $wgRightsText ) {
3130 $copywarnMsg = array( 'copyrightwarning',
3131 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3132 $wgRightsText );
3133 } else {
3134 $copywarnMsg = array( 'copyrightwarning2',
3135 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3137 // Allow for site and per-namespace customization of contribution/copyright notice.
3138 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3140 return "<div id=\"editpage-copywarn\">\n" .
3141 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3145 * Get the Limit report for page previews
3147 * @since 1.22
3148 * @param ParserOutput $output ParserOutput object from the parse
3149 * @return string HTML
3151 public static function getPreviewLimitReport( $output ) {
3152 if ( !$output || !$output->getLimitReportData() ) {
3153 return '';
3156 wfProfileIn( __METHOD__ );
3158 $limitReport = Html::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3159 wfMessage( 'limitreport-title' )->parseAsBlock()
3162 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3163 $limitReport .= Html::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3165 $limitReport .= Html::openElement( 'table', array(
3166 'class' => 'preview-limit-report wikitable'
3167 ) ) .
3168 Html::openElement( 'tbody' );
3170 foreach ( $output->getLimitReportData() as $key => $value ) {
3171 if ( wfRunHooks( 'ParserLimitReportFormat',
3172 array( $key, &$value, &$limitReport, true, true )
3173 ) ) {
3174 $keyMsg = wfMessage( $key );
3175 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3176 if ( !$valueMsg->exists() ) {
3177 $valueMsg = new RawMessage( '$1' );
3179 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3180 $limitReport .= Html::openElement( 'tr' ) .
3181 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3182 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3183 Html::closeElement( 'tr' );
3188 $limitReport .= Html::closeElement( 'tbody' ) .
3189 Html::closeElement( 'table' ) .
3190 Html::closeElement( 'div' );
3192 wfProfileOut( __METHOD__ );
3194 return $limitReport;
3197 protected function showStandardInputs( &$tabindex = 2 ) {
3198 global $wgOut, $wgUseMediaWikiUIEverywhere;
3199 $wgOut->addHTML( "<div class='editOptions'>\n" );
3201 if ( $this->section != 'new' ) {
3202 $this->showSummaryInput( false, $this->summary );
3203 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3206 $checkboxes = $this->getCheckboxes( $tabindex,
3207 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
3208 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3210 // Show copyright warning.
3211 $wgOut->addWikiText( $this->getCopywarn() );
3212 $wgOut->addHTML( $this->editFormTextAfterWarn );
3214 $wgOut->addHTML( "<div class='editButtons'>\n" );
3215 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3217 $cancel = $this->getCancelLink();
3218 if ( $cancel !== '' ) {
3219 $cancel .= Html::element( 'span',
3220 array( 'class' => 'mw-editButtons-pipe-separator' ),
3221 wfMessage( 'pipe-separator' )->text() );
3224 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3225 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3226 $attrs = array(
3227 'target' => 'helpwindow',
3228 'href' => $edithelpurl,
3230 if ( $wgUseMediaWikiUIEverywhere ) {
3231 $attrs['class'] = 'mw-ui-button mw-ui-quiet';
3233 $edithelp = Html::element( 'a', $attrs, wfMessage( 'edithelp' )->text() ) .
3234 wfMessage( 'newwindow' )->parse();
3236 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3237 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3238 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3240 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3242 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3246 * Show an edit conflict. textbox1 is already shown in showEditForm().
3247 * If you want to use another entry point to this function, be careful.
3249 protected function showConflict() {
3250 global $wgOut;
3252 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3253 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3255 $content1 = $this->toEditContent( $this->textbox1 );
3256 $content2 = $this->toEditContent( $this->textbox2 );
3258 $handler = ContentHandler::getForModelID( $this->contentModel );
3259 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3260 $de->setContent( $content2, $content1 );
3261 $de->showDiff(
3262 wfMessage( 'yourtext' )->parse(),
3263 wfMessage( 'storedversion' )->text()
3266 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3267 $this->showTextbox2();
3272 * @return string
3274 public function getCancelLink() {
3275 global $wgUseMediaWikiUIEverywhere;
3276 $cancelParams = array();
3277 if ( !$this->isConflict && $this->oldid > 0 ) {
3278 $cancelParams['oldid'] = $this->oldid;
3280 $attrs = array( 'id' => 'mw-editform-cancel' );
3281 if ( $wgUseMediaWikiUIEverywhere ) {
3282 $attrs['class'] = 'mw-ui-button mw-ui-quiet';
3285 return Linker::linkKnown(
3286 $this->getContextTitle(),
3287 wfMessage( 'cancel' )->parse(),
3288 $attrs,
3289 $cancelParams
3294 * Returns the URL to use in the form's action attribute.
3295 * This is used by EditPage subclasses when simply customizing the action
3296 * variable in the constructor is not enough. This can be used when the
3297 * EditPage lives inside of a Special page rather than a custom page action.
3299 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3300 * @return string
3302 protected function getActionURL( Title $title ) {
3303 return $title->getLocalURL( array( 'action' => $this->action ) );
3307 * Check if a page was deleted while the user was editing it, before submit.
3308 * Note that we rely on the logging table, which hasn't been always there,
3309 * but that doesn't matter, because this only applies to brand new
3310 * deletes.
3311 * @return bool
3313 protected function wasDeletedSinceLastEdit() {
3314 if ( $this->deletedSinceEdit !== null ) {
3315 return $this->deletedSinceEdit;
3318 $this->deletedSinceEdit = false;
3320 if ( $this->mTitle->isDeletedQuick() ) {
3321 $this->lastDelete = $this->getLastDelete();
3322 if ( $this->lastDelete ) {
3323 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3324 if ( $deleteTime > $this->starttime ) {
3325 $this->deletedSinceEdit = true;
3330 return $this->deletedSinceEdit;
3334 * @return bool|stdClass
3336 protected function getLastDelete() {
3337 $dbr = wfGetDB( DB_SLAVE );
3338 $data = $dbr->selectRow(
3339 array( 'logging', 'user' ),
3340 array(
3341 'log_type',
3342 'log_action',
3343 'log_timestamp',
3344 'log_user',
3345 'log_namespace',
3346 'log_title',
3347 'log_comment',
3348 'log_params',
3349 'log_deleted',
3350 'user_name'
3351 ), array(
3352 'log_namespace' => $this->mTitle->getNamespace(),
3353 'log_title' => $this->mTitle->getDBkey(),
3354 'log_type' => 'delete',
3355 'log_action' => 'delete',
3356 'user_id=log_user'
3358 __METHOD__,
3359 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3361 // Quick paranoid permission checks...
3362 if ( is_object( $data ) ) {
3363 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3364 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
3367 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3368 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
3372 return $data;
3376 * Get the rendered text for previewing.
3377 * @throws MWException
3378 * @return string
3380 function getPreviewText() {
3381 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3382 global $wgAllowUserCss, $wgAllowUserJs;
3384 wfProfileIn( __METHOD__ );
3386 if ( $wgRawHtml && !$this->mTokenOk ) {
3387 // Could be an offsite preview attempt. This is very unsafe if
3388 // HTML is enabled, as it could be an attack.
3389 $parsedNote = '';
3390 if ( $this->textbox1 !== '' ) {
3391 // Do not put big scary notice, if previewing the empty
3392 // string, which happens when you initially edit
3393 // a category page, due to automatic preview-on-open.
3394 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3395 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3397 wfProfileOut( __METHOD__ );
3398 return $parsedNote;
3401 $note = '';
3403 try {
3404 $content = $this->toEditContent( $this->textbox1 );
3406 $previewHTML = '';
3407 if ( !wfRunHooks(
3408 'AlternateEditPreview',
3409 array( $this, &$content, &$previewHTML, &$this->mParserOutput ) )
3411 wfProfileOut( __METHOD__ );
3412 return $previewHTML;
3415 # provide a anchor link to the editform
3416 $continueEditing = '<span class="mw-continue-editing">' .
3417 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3418 wfMessage( 'continue-editing' )->text() . ']]</span>';
3419 if ( $this->mTriedSave && !$this->mTokenOk ) {
3420 if ( $this->mTokenOkExceptSuffix ) {
3421 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3422 } else {
3423 $note = wfMessage( 'session_fail_preview' )->plain();
3425 } elseif ( $this->incompleteForm ) {
3426 $note = wfMessage( 'edit_form_incomplete' )->plain();
3427 } else {
3428 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3431 $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
3432 $parserOptions->setEditSection( false );
3433 $parserOptions->setIsPreview( true );
3434 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3436 # don't parse non-wikitext pages, show message about preview
3437 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3438 if ( $this->mTitle->isCssJsSubpage() ) {
3439 $level = 'user';
3440 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3441 $level = 'site';
3442 } else {
3443 $level = false;
3446 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3447 $format = 'css';
3448 if ( $level === 'user' && !$wgAllowUserCss ) {
3449 $format = false;
3451 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3452 $format = 'js';
3453 if ( $level === 'user' && !$wgAllowUserJs ) {
3454 $format = false;
3456 } else {
3457 $format = false;
3460 # Used messages to make sure grep find them:
3461 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3462 if ( $level && $format ) {
3463 $note = "<div id='mw-{$level}{$format}preview'>" .
3464 wfMessage( "{$level}{$format}preview" )->text() .
3465 ' ' . $continueEditing . "</div>";
3469 # If we're adding a comment, we need to show the
3470 # summary as the headline
3471 if ( $this->section === "new" && $this->summary !== "" ) {
3472 $content = $content->addSectionHeader( $this->summary );
3475 $hook_args = array( $this, &$content );
3476 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3477 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3479 $parserOptions->enableLimitReport();
3481 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3482 # But it's now deprecated, so never mind
3484 $content = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3485 $parserOutput = $content->getParserOutput(
3486 $this->getArticle()->getTitle(),
3487 null,
3488 $parserOptions
3491 $previewHTML = $parserOutput->getText();
3492 $this->mParserOutput = $parserOutput;
3493 $wgOut->addParserOutputMetadata( $parserOutput );
3495 if ( count( $parserOutput->getWarnings() ) ) {
3496 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3498 } catch ( MWContentSerializationException $ex ) {
3499 $m = wfMessage(
3500 'content-failed-to-parse',
3501 $this->contentModel,
3502 $this->contentFormat,
3503 $ex->getMessage()
3505 $note .= "\n\n" . $m->parse();
3506 $previewHTML = '';
3509 if ( $this->isConflict ) {
3510 $conflict = '<h2 id="mw-previewconflict">'
3511 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3512 } else {
3513 $conflict = '<hr />';
3516 $previewhead = "<div class='previewnote'>\n" .
3517 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3518 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3520 $pageViewLang = $this->mTitle->getPageViewLanguage();
3521 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3522 'class' => 'mw-content-' . $pageViewLang->getDir() );
3523 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3525 wfProfileOut( __METHOD__ );
3526 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3530 * @return array
3532 function getTemplates() {
3533 if ( $this->preview || $this->section != '' ) {
3534 $templates = array();
3535 if ( !isset( $this->mParserOutput ) ) {
3536 return $templates;
3538 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3539 foreach ( array_keys( $template ) as $dbk ) {
3540 $templates[] = Title::makeTitle( $ns, $dbk );
3543 return $templates;
3544 } else {
3545 return $this->mTitle->getTemplateLinksFrom();
3550 * Shows a bulletin board style toolbar for common editing functions.
3551 * It can be disabled in the user preferences.
3553 * @return string
3555 static function getEditToolbar() {
3556 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3557 global $wgEnableUploads, $wgForeignFileRepos;
3559 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3562 * $toolarray is an array of arrays each of which includes the
3563 * filename of the button image (without path), the opening
3564 * tag, the closing tag, optionally a sample text that is
3565 * inserted between the two when no selection is highlighted
3566 * and. The tip text is shown when the user moves the mouse
3567 * over the button.
3569 $toolarray = array(
3570 array(
3571 'image' => $wgLang->getImageFile( 'button-bold' ),
3572 'id' => 'mw-editbutton-bold',
3573 'open' => '\'\'\'',
3574 'close' => '\'\'\'',
3575 'sample' => wfMessage( 'bold_sample' )->text(),
3576 'tip' => wfMessage( 'bold_tip' )->text(),
3578 array(
3579 'image' => $wgLang->getImageFile( 'button-italic' ),
3580 'id' => 'mw-editbutton-italic',
3581 'open' => '\'\'',
3582 'close' => '\'\'',
3583 'sample' => wfMessage( 'italic_sample' )->text(),
3584 'tip' => wfMessage( 'italic_tip' )->text(),
3586 array(
3587 'image' => $wgLang->getImageFile( 'button-link' ),
3588 'id' => 'mw-editbutton-link',
3589 'open' => '[[',
3590 'close' => ']]',
3591 'sample' => wfMessage( 'link_sample' )->text(),
3592 'tip' => wfMessage( 'link_tip' )->text(),
3594 array(
3595 'image' => $wgLang->getImageFile( 'button-extlink' ),
3596 'id' => 'mw-editbutton-extlink',
3597 'open' => '[',
3598 'close' => ']',
3599 'sample' => wfMessage( 'extlink_sample' )->text(),
3600 'tip' => wfMessage( 'extlink_tip' )->text(),
3602 array(
3603 'image' => $wgLang->getImageFile( 'button-headline' ),
3604 'id' => 'mw-editbutton-headline',
3605 'open' => "\n== ",
3606 'close' => " ==\n",
3607 'sample' => wfMessage( 'headline_sample' )->text(),
3608 'tip' => wfMessage( 'headline_tip' )->text(),
3610 $imagesAvailable ? array(
3611 'image' => $wgLang->getImageFile( 'button-image' ),
3612 'id' => 'mw-editbutton-image',
3613 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3614 'close' => ']]',
3615 'sample' => wfMessage( 'image_sample' )->text(),
3616 'tip' => wfMessage( 'image_tip' )->text(),
3617 ) : false,
3618 $imagesAvailable ? array(
3619 'image' => $wgLang->getImageFile( 'button-media' ),
3620 'id' => 'mw-editbutton-media',
3621 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3622 'close' => ']]',
3623 'sample' => wfMessage( 'media_sample' )->text(),
3624 'tip' => wfMessage( 'media_tip' )->text(),
3625 ) : false,
3626 array(
3627 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3628 'id' => 'mw-editbutton-nowiki',
3629 'open' => "<nowiki>",
3630 'close' => "</nowiki>",
3631 'sample' => wfMessage( 'nowiki_sample' )->text(),
3632 'tip' => wfMessage( 'nowiki_tip' )->text(),
3634 array(
3635 'image' => $wgLang->getImageFile( 'button-sig' ),
3636 'id' => 'mw-editbutton-signature',
3637 'open' => '--~~~~',
3638 'close' => '',
3639 'sample' => '',
3640 'tip' => wfMessage( 'sig_tip' )->text(),
3642 array(
3643 'image' => $wgLang->getImageFile( 'button-hr' ),
3644 'id' => 'mw-editbutton-hr',
3645 'open' => "\n----\n",
3646 'close' => '',
3647 'sample' => '',
3648 'tip' => wfMessage( 'hr_tip' )->text(),
3652 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3653 foreach ( $toolarray as $tool ) {
3654 if ( !$tool ) {
3655 continue;
3658 $params = array(
3659 $wgStylePath . '/common/images/' . $tool['image'],
3660 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3661 // Older browsers show a "speedtip" type message only for ALT.
3662 // Ideally these should be different, realistically they
3663 // probably don't need to be.
3664 $tool['tip'],
3665 $tool['open'],
3666 $tool['close'],
3667 $tool['sample'],
3668 $tool['id'],
3671 $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
3674 // This used to be called on DOMReady from mediawiki.action.edit, which
3675 // ended up causing race conditions with the setup code above.
3676 $script .= "\n" .
3677 "// Create button bar\n" .
3678 "$(function() { mw.toolbar.init(); } );\n";
3680 $script .= '});';
3681 $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
3683 $toolbar = '<div id="toolbar"></div>';
3685 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3687 return $toolbar;
3691 * Returns an array of html code of the following checkboxes:
3692 * minor and watch
3694 * @param int $tabindex Current tabindex
3695 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3696 * status of the checkbox
3698 * @return array
3700 public function getCheckboxes( &$tabindex, $checked ) {
3701 global $wgUser, $wgUseMediaWikiUIEverywhere;
3703 $checkboxes = array();
3705 // don't show the minor edit checkbox if it's a new page or section
3706 if ( !$this->isNew ) {
3707 $checkboxes['minor'] = '';
3708 $minorLabel = wfMessage( 'minoredit' )->parse();
3709 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3710 $attribs = array(
3711 'tabindex' => ++$tabindex,
3712 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3713 'id' => 'wpMinoredit',
3715 $minorEditHtml =
3716 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3717 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3718 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3719 ">{$minorLabel}</label>";
3721 if ( $wgUseMediaWikiUIEverywhere ) {
3722 $checkboxes['minor'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3723 $minorEditHtml .
3724 Html::closeElement( 'div' );
3725 } else {
3726 $checkboxes['minor'] = $minorEditHtml;
3731 $watchLabel = wfMessage( 'watchthis' )->parse();
3732 $checkboxes['watch'] = '';
3733 if ( $wgUser->isLoggedIn() ) {
3734 $attribs = array(
3735 'tabindex' => ++$tabindex,
3736 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3737 'id' => 'wpWatchthis',
3739 $watchThisHtml =
3740 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3741 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3742 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3743 ">{$watchLabel}</label>";
3744 if ( $wgUseMediaWikiUIEverywhere ) {
3745 $checkboxes['watch'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3746 $watchThisHtml .
3747 Html::closeElement( 'div' );
3748 } else {
3749 $checkboxes['watch'] = $watchThisHtml;
3752 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3753 return $checkboxes;
3757 * Returns an array of html code of the following buttons:
3758 * save, diff, preview and live
3760 * @param int $tabindex Current tabindex
3762 * @return array
3764 public function getEditButtons( &$tabindex ) {
3765 global $wgUseMediaWikiUIEverywhere;
3767 $buttons = array();
3769 $attribs = array(
3770 'id' => 'wpSave',
3771 'name' => 'wpSave',
3772 'type' => 'submit',
3773 'tabindex' => ++$tabindex,
3774 'value' => wfMessage( 'savearticle' )->text(),
3775 ) + Linker::tooltipAndAccesskeyAttribs( 'save' );
3776 if ( $wgUseMediaWikiUIEverywhere ) {
3777 $attribs['class'] = 'mw-ui-button mw-ui-constructive';
3779 $buttons['save'] = Xml::element( 'input', $attribs, '' );
3781 ++$tabindex; // use the same for preview and live preview
3782 $attribs = array(
3783 'id' => 'wpPreview',
3784 'name' => 'wpPreview',
3785 'type' => 'submit',
3786 'tabindex' => $tabindex,
3787 'value' => wfMessage( 'showpreview' )->text(),
3788 ) + Linker::tooltipAndAccesskeyAttribs( 'preview' );
3789 if ( $wgUseMediaWikiUIEverywhere ) {
3790 $attribs['class'] = 'mw-ui-button mw-ui-progressive';
3792 $buttons['preview'] = Xml::element( 'input', $attribs, '' );
3793 $buttons['live'] = '';
3795 $attribs = array(
3796 'id' => 'wpDiff',
3797 'name' => 'wpDiff',
3798 'type' => 'submit',
3799 'tabindex' => ++$tabindex,
3800 'value' => wfMessage( 'showdiff' )->text(),
3801 ) + Linker::tooltipAndAccesskeyAttribs( 'diff' );
3802 if ( $wgUseMediaWikiUIEverywhere ) {
3803 $attribs['class'] = 'mw-ui-button mw-ui-progressive';
3805 $buttons['diff'] = Xml::element( 'input', $attribs, '' );
3807 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3808 return $buttons;
3812 * Output preview text only. This can be sucked into the edit page
3813 * via JavaScript, and saves the server time rendering the skin as
3814 * well as theoretically being more robust on the client (doesn't
3815 * disturb the edit box's undo history, won't eat your text on
3816 * failure, etc).
3818 * @todo This doesn't include category or interlanguage links.
3819 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3820 * or something...</s>" that might also require more skin
3821 * initialization, so check whether that's a problem.
3823 function livePreview() {
3824 global $wgOut;
3825 $wgOut->disable();
3826 header( 'Content-type: text/xml; charset=utf-8' );
3827 header( 'Cache-control: no-cache' );
3829 $previewText = $this->getPreviewText();
3830 #$categories = $skin->getCategoryLinks();
3832 $s =
3833 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3834 Xml::tags( 'livepreview', null,
3835 Xml::element( 'preview', null, $previewText )
3836 #. Xml::element( 'category', null, $categories )
3838 echo $s;
3842 * Creates a basic error page which informs the user that
3843 * they have attempted to edit a nonexistent section.
3845 function noSuchSectionPage() {
3846 global $wgOut;
3848 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3850 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
3851 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3852 $wgOut->addHTML( $res );
3854 $wgOut->returnToMain( false, $this->mTitle );
3858 * Show "your edit contains spam" page with your diff and text
3860 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3862 public function spamPageWithContent( $match = false ) {
3863 global $wgOut, $wgLang;
3864 $this->textbox2 = $this->textbox1;
3866 if ( is_array( $match ) ) {
3867 $match = $wgLang->listToText( $match );
3869 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3871 $wgOut->addHTML( '<div id="spamprotected">' );
3872 $wgOut->addWikiMsg( 'spamprotectiontext' );
3873 if ( $match ) {
3874 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3876 $wgOut->addHTML( '</div>' );
3878 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3879 $this->showDiff();
3881 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3882 $this->showTextbox2();
3884 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3888 * Check if the browser is on a blacklist of user-agents known to
3889 * mangle UTF-8 data on form submission. Returns true if Unicode
3890 * should make it through, false if it's known to be a problem.
3891 * @return bool
3893 private function checkUnicodeCompliantBrowser() {
3894 global $wgBrowserBlackList, $wgRequest;
3896 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3897 if ( $currentbrowser === false ) {
3898 // No User-Agent header sent? Trust it by default...
3899 return true;
3902 foreach ( $wgBrowserBlackList as $browser ) {
3903 if ( preg_match( $browser, $currentbrowser ) ) {
3904 return false;
3907 return true;
3911 * Filter an input field through a Unicode de-armoring process if it
3912 * came from an old browser with known broken Unicode editing issues.
3914 * @param WebRequest $request
3915 * @param string $field
3916 * @return string
3918 protected function safeUnicodeInput( $request, $field ) {
3919 $text = rtrim( $request->getText( $field ) );
3920 return $request->getBool( 'safemode' )
3921 ? $this->unmakeSafe( $text )
3922 : $text;
3926 * Filter an output field through a Unicode armoring process if it is
3927 * going to an old browser with known broken Unicode editing issues.
3929 * @param string $text
3930 * @return string
3932 protected function safeUnicodeOutput( $text ) {
3933 global $wgContLang;
3934 $codedText = $wgContLang->recodeForEdit( $text );
3935 return $this->checkUnicodeCompliantBrowser()
3936 ? $codedText
3937 : $this->makeSafe( $codedText );
3941 * A number of web browsers are known to corrupt non-ASCII characters
3942 * in a UTF-8 text editing environment. To protect against this,
3943 * detected browsers will be served an armored version of the text,
3944 * with non-ASCII chars converted to numeric HTML character references.
3946 * Preexisting such character references will have a 0 added to them
3947 * to ensure that round-trips do not alter the original data.
3949 * @param string $invalue
3950 * @return string
3952 private function makeSafe( $invalue ) {
3953 // Armor existing references for reversibility.
3954 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
3956 $bytesleft = 0;
3957 $result = "";
3958 $working = 0;
3959 $valueLength = strlen( $invalue );
3960 for ( $i = 0; $i < $valueLength; $i++ ) {
3961 $bytevalue = ord( $invalue[$i] );
3962 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3963 $result .= chr( $bytevalue );
3964 $bytesleft = 0;
3965 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3966 $working = $working << 6;
3967 $working += ( $bytevalue & 0x3F );
3968 $bytesleft--;
3969 if ( $bytesleft <= 0 ) {
3970 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3972 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3973 $working = $bytevalue & 0x1F;
3974 $bytesleft = 1;
3975 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3976 $working = $bytevalue & 0x0F;
3977 $bytesleft = 2;
3978 } else { // 1111 0xxx
3979 $working = $bytevalue & 0x07;
3980 $bytesleft = 3;
3983 return $result;
3987 * Reverse the previously applied transliteration of non-ASCII characters
3988 * back to UTF-8. Used to protect data from corruption by broken web browsers
3989 * as listed in $wgBrowserBlackList.
3991 * @param string $invalue
3992 * @return string
3994 private function unmakeSafe( $invalue ) {
3995 $result = "";
3996 $valueLength = strlen( $invalue );
3997 for ( $i = 0; $i < $valueLength; $i++ ) {
3998 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
3999 $i += 3;
4000 $hexstring = "";
4001 do {
4002 $hexstring .= $invalue[$i];
4003 $i++;
4004 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4006 // Do some sanity checks. These aren't needed for reversibility,
4007 // but should help keep the breakage down if the editor
4008 // breaks one of the entities whilst editing.
4009 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
4010 $codepoint = hexdec( $hexstring );
4011 $result .= codepointToUtf8( $codepoint );
4012 } else {
4013 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4015 } else {
4016 $result .= substr( $invalue, $i, 1 );
4019 // reverse the transform that we made for reversibility reasons.
4020 return strtr( $result, array( "&#x0" => "&#x" ) );