Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / EditPage.php
bloba8a17cf90be9914af62ca5e0536abed86b36a8a6
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: user tried to modify the content model, but is not allowed to do that
149 * ( User::isAllowed('editcontentmodel') == false )
151 const AS_NO_CHANGE_CONTENT_MODEL = 235;
154 * Status: user tried to create self-redirect (redirect to the same article) and
155 * wpIgnoreSelfRedirect == false
157 const AS_SELF_REDIRECT = 236;
160 * Status: can't parse content
162 const AS_PARSE_ERROR = 240;
165 * HTML id and name for the beginning of the edit form.
167 const EDITFORM_ID = 'editform';
170 * Prefix of key for cookie used to pass post-edit state.
171 * The revision id edited is added after this
173 const POST_EDIT_COOKIE_KEY_PREFIX = 'PostEditRevision';
176 * Duration of PostEdit cookie, in seconds.
177 * The cookie will be removed instantly if the JavaScript runs.
179 * Otherwise, though, we don't want the cookies to accumulate.
180 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
181 * limit of only 20 cookies per domain. This still applies at least to some
182 * versions of IE without full updates:
183 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
185 * A value of 20 minutes should be enough to take into account slow loads and minor
186 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
188 const POST_EDIT_COOKIE_DURATION = 1200;
190 /** @var Article */
191 public $mArticle;
193 /** @var Title */
194 public $mTitle;
196 /** @var null|Title */
197 private $mContextTitle = null;
199 /** @var string */
200 public $action = 'submit';
202 /** @var bool */
203 public $isConflict = false;
205 /** @var bool */
206 public $isCssJsSubpage = false;
208 /** @var bool */
209 public $isCssSubpage = false;
211 /** @var bool */
212 public $isJsSubpage = false;
214 /** @var bool */
215 public $isWrongCaseCssJsPage = false;
217 /** @var bool New page or new section */
218 public $isNew = false;
220 /** @var bool */
221 public $deletedSinceEdit;
223 /** @var string */
224 public $formtype;
226 /** @var bool */
227 public $firsttime;
229 /** @var bool|stdClass */
230 public $lastDelete;
232 /** @var bool */
233 public $mTokenOk = false;
235 /** @var bool */
236 public $mTokenOkExceptSuffix = false;
238 /** @var bool */
239 public $mTriedSave = false;
241 /** @var bool */
242 public $incompleteForm = false;
244 /** @var bool */
245 public $tooBig = false;
247 /** @var bool */
248 public $kblength = false;
250 /** @var bool */
251 public $missingComment = false;
253 /** @var bool */
254 public $missingSummary = false;
256 /** @var bool */
257 public $allowBlankSummary = false;
259 /** @var bool */
260 protected $blankArticle = false;
262 /** @var bool */
263 protected $allowBlankArticle = false;
265 /** @var bool */
266 protected $selfRedirect = false;
268 /** @var bool */
269 protected $allowSelfRedirect = false;
271 /** @var string */
272 public $autoSumm = '';
274 /** @var string */
275 public $hookError = '';
277 /** @var ParserOutput */
278 public $mParserOutput;
280 /** @var bool Has a summary been preset using GET parameter &summary= ? */
281 public $hasPresetSummary = false;
283 /** @var bool */
284 public $mBaseRevision = false;
286 /** @var bool */
287 public $mShowSummaryField = true;
289 # Form values
291 /** @var bool */
292 public $save = false;
294 /** @var bool */
295 public $preview = false;
297 /** @var bool */
298 public $diff = false;
300 /** @var bool */
301 public $minoredit = false;
303 /** @var bool */
304 public $watchthis = false;
306 /** @var bool */
307 public $recreate = false;
309 /** @var string */
310 public $textbox1 = '';
312 /** @var string */
313 public $textbox2 = '';
315 /** @var string */
316 public $summary = '';
318 /** @var bool */
319 public $nosummary = false;
321 /** @var string */
322 public $edittime = '';
324 /** @var string */
325 public $section = '';
327 /** @var string */
328 public $sectiontitle = '';
330 /** @var string */
331 public $starttime = '';
333 /** @var int */
334 public $oldid = 0;
336 /** @var int */
337 public $parentRevId = 0;
339 /** @var string */
340 public $editintro = '';
342 /** @var null */
343 public $scrolltop = null;
345 /** @var bool */
346 public $bot = true;
348 /** @var null|string */
349 public $contentModel = null;
351 /** @var null|string */
352 public $contentFormat = null;
354 # Placeholders for text injection by hooks (must be HTML)
355 # extensions should take care to _append_ to the present value
357 /** @var string Before even the preview */
358 public $editFormPageTop = '';
359 public $editFormTextTop = '';
360 public $editFormTextBeforeContent = '';
361 public $editFormTextAfterWarn = '';
362 public $editFormTextAfterTools = '';
363 public $editFormTextBottom = '';
364 public $editFormTextAfterContent = '';
365 public $previewTextAfterContent = '';
366 public $mPreloadContent = null;
368 /* $didSave should be set to true whenever an article was successfully altered. */
369 public $didSave = false;
370 public $undidRev = 0;
372 public $suppressIntro = false;
374 /** @var bool Set to true to allow editing of non-text content types. */
375 public $allowNonTextContent = false;
377 /** @var bool */
378 protected $edit;
380 /** @var bool */
381 public $live;
384 * @param Article $article
386 public function __construct( Article $article ) {
387 $this->mArticle = $article;
388 $this->mTitle = $article->getTitle();
390 $this->contentModel = $this->mTitle->getContentModel();
392 $handler = ContentHandler::getForModelID( $this->contentModel );
393 $this->contentFormat = $handler->getDefaultFormat();
397 * @return Article
399 public function getArticle() {
400 return $this->mArticle;
404 * @since 1.19
405 * @return Title
407 public function getTitle() {
408 return $this->mTitle;
412 * Set the context Title object
414 * @param Title|null $title Title object or null
416 public function setContextTitle( $title ) {
417 $this->mContextTitle = $title;
421 * Get the context title object.
422 * If not set, $wgTitle will be returned. This behavior might change in
423 * the future to return $this->mTitle instead.
425 * @return Title
427 public function getContextTitle() {
428 if ( is_null( $this->mContextTitle ) ) {
429 global $wgTitle;
430 return $wgTitle;
431 } else {
432 return $this->mContextTitle;
437 * Returns if the given content model is editable.
439 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
440 * @return bool
441 * @throws MWException If $modelId has no known handler
443 public function isSupportedContentModel( $modelId ) {
444 return $this->allowNonTextContent ||
445 ContentHandler::getForModelID( $modelId ) instanceof TextContentHandler;
448 function submit() {
449 $this->edit();
453 * This is the function that gets called for "action=edit". It
454 * sets up various member variables, then passes execution to
455 * another function, usually showEditForm()
457 * The edit form is self-submitting, so that when things like
458 * preview and edit conflicts occur, we get the same form back
459 * with the extra stuff added. Only when the final submission
460 * is made and all is well do we actually save and redirect to
461 * the newly-edited page.
463 function edit() {
464 global $wgOut, $wgRequest, $wgUser;
465 // Allow extensions to modify/prevent this form or submission
466 if ( !Hooks::run( 'AlternateEdit', array( $this ) ) ) {
467 return;
470 wfDebug( __METHOD__ . ": enter\n" );
472 // If they used redlink=1 and the page exists, redirect to the main article
473 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
474 $wgOut->redirect( $this->mTitle->getFullURL() );
475 return;
478 $this->importFormData( $wgRequest );
479 $this->firsttime = false;
481 if ( $this->live ) {
482 $this->livePreview();
483 return;
486 if ( wfReadOnly() && $this->save ) {
487 // Force preview
488 $this->save = false;
489 $this->preview = true;
492 if ( $this->save ) {
493 $this->formtype = 'save';
494 } elseif ( $this->preview ) {
495 $this->formtype = 'preview';
496 } elseif ( $this->diff ) {
497 $this->formtype = 'diff';
498 } else { # First time through
499 $this->firsttime = true;
500 if ( $this->previewOnOpen() ) {
501 $this->formtype = 'preview';
502 } else {
503 $this->formtype = 'initial';
507 $permErrors = $this->getEditPermissionErrors( $this->save ? 'secure' : 'full' );
508 if ( $permErrors ) {
509 wfDebug( __METHOD__ . ": User can't edit\n" );
510 // Auto-block user's IP if the account was "hard" blocked
511 $wgUser->spreadAnyEditBlock();
513 $this->displayPermissionsError( $permErrors );
515 return;
518 $this->isConflict = false;
519 // css / js subpages of user pages get a special treatment
520 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
521 $this->isCssSubpage = $this->mTitle->isCssSubpage();
522 $this->isJsSubpage = $this->mTitle->isJsSubpage();
523 // @todo FIXME: Silly assignment.
524 $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
526 # Show applicable editing introductions
527 if ( $this->formtype == 'initial' || $this->firsttime ) {
528 $this->showIntro();
531 # Attempt submission here. This will check for edit conflicts,
532 # and redundantly check for locked database, blocked IPs, etc.
533 # that edit() already checked just in case someone tries to sneak
534 # in the back door with a hand-edited submission URL.
536 if ( 'save' == $this->formtype ) {
537 $resultDetails = null;
538 $status = $this->attemptSave( $resultDetails );
539 if ( !$this->handleStatus( $status, $resultDetails ) ) {
540 return;
544 # First time through: get contents, set time for conflict
545 # checking, etc.
546 if ( 'initial' == $this->formtype || $this->firsttime ) {
547 if ( $this->initialiseForm() === false ) {
548 $this->noSuchSectionPage();
549 return;
552 if ( !$this->mTitle->getArticleID() ) {
553 Hooks::run( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
554 } else {
555 Hooks::run( 'EditFormInitialText', array( $this ) );
560 $this->showEditForm();
564 * @param string $rigor Same format as Title::getUserPermissionErrors()
565 * @return array
567 protected function getEditPermissionErrors( $rigor = 'secure' ) {
568 global $wgUser;
570 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
571 # Can this title be created?
572 if ( !$this->mTitle->exists() ) {
573 $permErrors = array_merge(
574 $permErrors,
575 wfArrayDiff2(
576 $this->mTitle->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
577 $permErrors
581 # Ignore some permissions errors when a user is just previewing/viewing diffs
582 $remove = array();
583 foreach ( $permErrors as $error ) {
584 if ( ( $this->preview || $this->diff )
585 && ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' )
587 $remove[] = $error;
590 $permErrors = wfArrayDiff2( $permErrors, $remove );
592 return $permErrors;
596 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
597 * but with the following differences:
598 * - If redlink=1, the user will be redirected to the page
599 * - If there is content to display or the error occurs while either saving,
600 * previewing or showing the difference, it will be a
601 * "View source for ..." page displaying the source code after the error message.
603 * @since 1.19
604 * @param array $permErrors Array of permissions errors, as returned by
605 * Title::getUserPermissionsErrors().
606 * @throws PermissionsError
608 protected function displayPermissionsError( array $permErrors ) {
609 global $wgRequest, $wgOut;
611 if ( $wgRequest->getBool( 'redlink' ) ) {
612 // The edit page was reached via a red link.
613 // Redirect to the article page and let them click the edit tab if
614 // they really want a permission error.
615 $wgOut->redirect( $this->mTitle->getFullURL() );
616 return;
619 $content = $this->getContentObject();
621 # Use the normal message if there's nothing to display
622 if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
623 $action = $this->mTitle->exists() ? 'edit' :
624 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
625 throw new PermissionsError( $action, $permErrors );
628 Hooks::run( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
630 $wgOut->setRobotPolicy( 'noindex,nofollow' );
631 $wgOut->setPageTitle( wfMessage(
632 'viewsource-title',
633 $this->getContextTitle()->getPrefixedText()
634 ) );
635 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
636 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
637 $wgOut->addHTML( "<hr />\n" );
639 # If the user made changes, preserve them when showing the markup
640 # (This happens when a user is blocked during edit, for instance)
641 if ( !$this->firsttime ) {
642 $text = $this->textbox1;
643 $wgOut->addWikiMsg( 'viewyourtext' );
644 } else {
645 $text = $this->toEditText( $content );
646 $wgOut->addWikiMsg( 'viewsourcetext' );
649 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
651 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
652 Linker::formatTemplates( $this->getTemplates() ) ) );
654 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
656 if ( $this->mTitle->exists() ) {
657 $wgOut->returnToMain( null, $this->mTitle );
662 * Should we show a preview when the edit form is first shown?
664 * @return bool
666 protected function previewOnOpen() {
667 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
668 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
669 // Explicit override from request
670 return true;
671 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
672 // Explicit override from request
673 return false;
674 } elseif ( $this->section == 'new' ) {
675 // Nothing *to* preview for new sections
676 return false;
677 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() )
678 && $wgUser->getOption( 'previewonfirst' )
680 // Standard preference behavior
681 return true;
682 } elseif ( !$this->mTitle->exists()
683 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
684 && $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]
686 // Categories are special
687 return true;
688 } else {
689 return false;
694 * Checks whether the user entered a skin name in uppercase,
695 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
697 * @return bool
699 protected function isWrongCaseCssJsPage() {
700 if ( $this->mTitle->isCssJsSubpage() ) {
701 $name = $this->mTitle->getSkinFromCssJsSubpage();
702 $skins = array_merge(
703 array_keys( Skin::getSkinNames() ),
704 array( 'common' )
706 return !in_array( $name, $skins )
707 && in_array( strtolower( $name ), $skins );
708 } else {
709 return false;
714 * Returns whether section editing is supported for the current page.
715 * Subclasses may override this to replace the default behavior, which is
716 * to check ContentHandler::supportsSections.
718 * @return bool True if this edit page supports sections, false otherwise.
720 protected function isSectionEditSupported() {
721 $contentHandler = ContentHandler::getForTitle( $this->mTitle );
722 return $contentHandler->supportsSections();
726 * This function collects the form data and uses it to populate various member variables.
727 * @param WebRequest $request
728 * @throws ErrorPageError
730 function importFormData( &$request ) {
731 global $wgContLang, $wgUser;
733 # Section edit can come from either the form or a link
734 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
736 if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
737 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
740 $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
742 if ( $request->wasPosted() ) {
743 # These fields need to be checked for encoding.
744 # Also remove trailing whitespace, but don't remove _initial_
745 # whitespace from the text boxes. This may be significant formatting.
746 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
747 if ( !$request->getCheck( 'wpTextbox2' ) ) {
748 // Skip this if wpTextbox2 has input, it indicates that we came
749 // from a conflict page with raw page text, not a custom form
750 // modified by subclasses
751 $textbox1 = $this->importContentFormData( $request );
752 if ( $textbox1 !== null ) {
753 $this->textbox1 = $textbox1;
757 # Truncate for whole multibyte characters
758 $this->summary = $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
760 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
761 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
762 # section titles.
763 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
765 # Treat sectiontitle the same way as summary.
766 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
767 # currently doing double duty as both edit summary and section title. Right now this
768 # is just to allow API edits to work around this limitation, but this should be
769 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
770 $this->sectiontitle = $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
771 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
773 $this->edittime = $request->getVal( 'wpEdittime' );
774 $this->starttime = $request->getVal( 'wpStarttime' );
776 $undidRev = $request->getInt( 'wpUndidRevision' );
777 if ( $undidRev ) {
778 $this->undidRev = $undidRev;
781 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
783 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
784 // wpTextbox1 field is missing, possibly due to being "too big"
785 // according to some filter rules such as Suhosin's setting for
786 // suhosin.request.max_value_length (d'oh)
787 $this->incompleteForm = true;
788 } else {
789 // If we receive the last parameter of the request, we can fairly
790 // claim the POST request has not been truncated.
792 // TODO: softened the check for cutover. Once we determine
793 // that it is safe, we should complete the transition by
794 // removing the "edittime" clause.
795 $this->incompleteForm = ( !$request->getVal( 'wpUltimateParam' )
796 && is_null( $this->edittime ) );
798 if ( $this->incompleteForm ) {
799 # If the form is incomplete, force to preview.
800 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
801 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
802 $this->preview = true;
803 } else {
804 /* Fallback for live preview */
805 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
806 $this->diff = $request->getCheck( 'wpDiff' );
808 // Remember whether a save was requested, so we can indicate
809 // if we forced preview due to session failure.
810 $this->mTriedSave = !$this->preview;
812 if ( $this->tokenOk( $request ) ) {
813 # Some browsers will not report any submit button
814 # if the user hits enter in the comment box.
815 # The unmarked state will be assumed to be a save,
816 # if the form seems otherwise complete.
817 wfDebug( __METHOD__ . ": Passed token check.\n" );
818 } elseif ( $this->diff ) {
819 # Failed token check, but only requested "Show Changes".
820 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
821 } else {
822 # Page might be a hack attempt posted from
823 # an external site. Preview instead of saving.
824 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
825 $this->preview = true;
828 $this->save = !$this->preview && !$this->diff;
829 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
830 $this->edittime = null;
833 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
834 $this->starttime = null;
837 $this->recreate = $request->getCheck( 'wpRecreate' );
839 $this->minoredit = $request->getCheck( 'wpMinoredit' );
840 $this->watchthis = $request->getCheck( 'wpWatchthis' );
842 # Don't force edit summaries when a user is editing their own user or talk page
843 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
844 && $this->mTitle->getText() == $wgUser->getName()
846 $this->allowBlankSummary = true;
847 } else {
848 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
849 || !$wgUser->getOption( 'forceeditsummary' );
852 $this->autoSumm = $request->getText( 'wpAutoSummary' );
854 $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
855 $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
856 } else {
857 # Not a posted form? Start with nothing.
858 wfDebug( __METHOD__ . ": Not a posted form.\n" );
859 $this->textbox1 = '';
860 $this->summary = '';
861 $this->sectiontitle = '';
862 $this->edittime = '';
863 $this->starttime = wfTimestampNow();
864 $this->edit = false;
865 $this->preview = false;
866 $this->save = false;
867 $this->diff = false;
868 $this->minoredit = false;
869 // Watch may be overridden by request parameters
870 $this->watchthis = $request->getBool( 'watchthis', false );
871 $this->recreate = false;
873 // When creating a new section, we can preload a section title by passing it as the
874 // preloadtitle parameter in the URL (Bug 13100)
875 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
876 $this->sectiontitle = $request->getVal( 'preloadtitle' );
877 // Once wpSummary isn't being use for setting section titles, we should delete this.
878 $this->summary = $request->getVal( 'preloadtitle' );
879 } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
880 $this->summary = $request->getText( 'summary' );
881 if ( $this->summary !== '' ) {
882 $this->hasPresetSummary = true;
886 if ( $request->getVal( 'minor' ) ) {
887 $this->minoredit = true;
891 $this->oldid = $request->getInt( 'oldid' );
892 $this->parentRevId = $request->getInt( 'parentRevId' );
894 $this->bot = $request->getBool( 'bot', true );
895 $this->nosummary = $request->getBool( 'nosummary' );
897 // May be overridden by revision.
898 $this->contentModel = $request->getText( 'model', $this->contentModel );
899 // May be overridden by revision.
900 $this->contentFormat = $request->getText( 'format', $this->contentFormat );
902 if ( !ContentHandler::getForModelID( $this->contentModel )
903 ->isSupportedFormat( $this->contentFormat )
905 throw new ErrorPageError(
906 'editpage-notsupportedcontentformat-title',
907 'editpage-notsupportedcontentformat-text',
908 array( $this->contentFormat, ContentHandler::getLocalizedName( $this->contentModel ) )
913 * @todo Check if the desired model is allowed in this namespace, and if
914 * a transition from the page's current model to the new model is
915 * allowed.
918 $this->live = $request->getCheck( 'live' );
919 $this->editintro = $request->getText( 'editintro',
920 // Custom edit intro for new sections
921 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
923 // Allow extensions to modify form data
924 Hooks::run( 'EditPage::importFormData', array( $this, $request ) );
929 * Subpage overridable method for extracting the page content data from the
930 * posted form to be placed in $this->textbox1, if using customized input
931 * this method should be overridden and return the page text that will be used
932 * for saving, preview parsing and so on...
934 * @param WebRequest $request
936 protected function importContentFormData( &$request ) {
937 return; // Don't do anything, EditPage already extracted wpTextbox1
941 * Initialise form fields in the object
942 * Called on the first invocation, e.g. when a user clicks an edit link
943 * @return bool If the requested section is valid
945 function initialiseForm() {
946 global $wgUser;
947 $this->edittime = $this->mArticle->getTimestamp();
949 $content = $this->getContentObject( false ); #TODO: track content object?!
950 if ( $content === false ) {
951 return false;
953 $this->textbox1 = $this->toEditText( $content );
955 // activate checkboxes if user wants them to be always active
956 # Sort out the "watch" checkbox
957 if ( $wgUser->getOption( 'watchdefault' ) ) {
958 # Watch all edits
959 $this->watchthis = true;
960 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
961 # Watch creations
962 $this->watchthis = true;
963 } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
964 # Already watched
965 $this->watchthis = true;
967 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
968 $this->minoredit = true;
970 if ( $this->textbox1 === false ) {
971 return false;
973 return true;
977 * @param Content|null $def_content The default value to return
979 * @return Content|null Content on success, $def_content for invalid sections
981 * @since 1.21
983 protected function getContentObject( $def_content = null ) {
984 global $wgOut, $wgRequest, $wgUser, $wgContLang;
986 $content = false;
988 // For message page not locally set, use the i18n message.
989 // For other non-existent articles, use preload text if any.
990 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
991 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
992 # If this is a system message, get the default text.
993 $msg = $this->mTitle->getDefaultMessageText();
995 $content = $this->toEditContent( $msg );
997 if ( $content === false ) {
998 # If requested, preload some text.
999 $preload = $wgRequest->getVal( 'preload',
1000 // Custom preload text for new sections
1001 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
1002 $params = $wgRequest->getArray( 'preloadparams', array() );
1004 $content = $this->getPreloadedContent( $preload, $params );
1006 // For existing pages, get text based on "undo" or section parameters.
1007 } else {
1008 if ( $this->section != '' ) {
1009 // Get section edit text (returns $def_text for invalid sections)
1010 $orig = $this->getOriginalContent( $wgUser );
1011 $content = $orig ? $orig->getSection( $this->section ) : null;
1013 if ( !$content ) {
1014 $content = $def_content;
1016 } else {
1017 $undoafter = $wgRequest->getInt( 'undoafter' );
1018 $undo = $wgRequest->getInt( 'undo' );
1020 if ( $undo > 0 && $undoafter > 0 ) {
1022 $undorev = Revision::newFromId( $undo );
1023 $oldrev = Revision::newFromId( $undoafter );
1025 # Sanity check, make sure it's the right page,
1026 # the revisions exist and they were not deleted.
1027 # Otherwise, $content will be left as-is.
1028 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1029 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
1030 !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
1032 $content = $this->mArticle->getUndoContent( $undorev, $oldrev );
1034 if ( $content === false ) {
1035 # Warn the user that something went wrong
1036 $undoMsg = 'failure';
1037 } else {
1038 $oldContent = $this->mArticle->getPage()->getContent( Revision::RAW );
1039 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
1040 $newContent = $content->preSaveTransform( $this->mTitle, $wgUser, $popts );
1042 if ( $newContent->equals( $oldContent ) ) {
1043 # Tell the user that the undo results in no change,
1044 # i.e. the revisions were already undone.
1045 $undoMsg = 'nochange';
1046 $content = false;
1047 } else {
1048 # Inform the user of our success and set an automatic edit summary
1049 $undoMsg = 'success';
1051 # If we just undid one rev, use an autosummary
1052 $firstrev = $oldrev->getNext();
1053 if ( $firstrev && $firstrev->getId() == $undo ) {
1054 $userText = $undorev->getUserText();
1055 if ( $userText === '' ) {
1056 $undoSummary = wfMessage(
1057 'undo-summary-username-hidden',
1058 $undo
1059 )->inContentLanguage()->text();
1060 } else {
1061 $undoSummary = wfMessage(
1062 'undo-summary',
1063 $undo,
1064 $userText
1065 )->inContentLanguage()->text();
1067 if ( $this->summary === '' ) {
1068 $this->summary = $undoSummary;
1069 } else {
1070 $this->summary = $undoSummary . wfMessage( 'colon-separator' )
1071 ->inContentLanguage()->text() . $this->summary;
1073 $this->undidRev = $undo;
1075 $this->formtype = 'diff';
1078 } else {
1079 // Failed basic sanity checks.
1080 // Older revisions may have been removed since the link
1081 // was created, or we may simply have got bogus input.
1082 $undoMsg = 'norev';
1085 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1086 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1087 $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
1088 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1091 if ( $content === false ) {
1092 $content = $this->getOriginalContent( $wgUser );
1097 return $content;
1101 * Get the content of the wanted revision, without section extraction.
1103 * The result of this function can be used to compare user's input with
1104 * section replaced in its context (using WikiPage::replaceSection())
1105 * to the original text of the edit.
1107 * This differs from Article::getContent() that when a missing revision is
1108 * encountered the result will be null and not the
1109 * 'missing-revision' message.
1111 * @since 1.19
1112 * @param User $user The user to get the revision for
1113 * @return Content|null
1115 private function getOriginalContent( User $user ) {
1116 if ( $this->section == 'new' ) {
1117 return $this->getCurrentContent();
1119 $revision = $this->mArticle->getRevisionFetched();
1120 if ( $revision === null ) {
1121 if ( !$this->contentModel ) {
1122 $this->contentModel = $this->getTitle()->getContentModel();
1124 $handler = ContentHandler::getForModelID( $this->contentModel );
1126 return $handler->makeEmptyContent();
1128 $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
1129 return $content;
1133 * Get the current content of the page. This is basically similar to
1134 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1135 * content object is returned instead of null.
1137 * @since 1.21
1138 * @return Content
1140 protected function getCurrentContent() {
1141 $rev = $this->mArticle->getRevision();
1142 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1144 if ( $content === false || $content === null ) {
1145 if ( !$this->contentModel ) {
1146 $this->contentModel = $this->getTitle()->getContentModel();
1148 $handler = ContentHandler::getForModelID( $this->contentModel );
1150 return $handler->makeEmptyContent();
1151 } else {
1152 # nasty side-effect, but needed for consistency
1153 $this->contentModel = $rev->getContentModel();
1154 $this->contentFormat = $rev->getContentFormat();
1156 return $content;
1161 * Use this method before edit() to preload some content into the edit box
1163 * @param Content $content
1165 * @since 1.21
1167 public function setPreloadedContent( Content $content ) {
1168 $this->mPreloadContent = $content;
1172 * Get the contents to be preloaded into the box, either set by
1173 * an earlier setPreloadText() or by loading the given page.
1175 * @param string $preload Representing the title to preload from.
1176 * @param array $params Parameters to use (interface-message style) in the preloaded text
1178 * @return Content
1180 * @since 1.21
1182 protected function getPreloadedContent( $preload, $params = array() ) {
1183 global $wgUser;
1185 if ( !empty( $this->mPreloadContent ) ) {
1186 return $this->mPreloadContent;
1189 $handler = ContentHandler::getForTitle( $this->getTitle() );
1191 if ( $preload === '' ) {
1192 return $handler->makeEmptyContent();
1195 $title = Title::newFromText( $preload );
1196 # Check for existence to avoid getting MediaWiki:Noarticletext
1197 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1198 //TODO: somehow show a warning to the user!
1199 return $handler->makeEmptyContent();
1202 $page = WikiPage::factory( $title );
1203 if ( $page->isRedirect() ) {
1204 $title = $page->getRedirectTarget();
1205 # Same as before
1206 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1207 //TODO: somehow show a warning to the user!
1208 return $handler->makeEmptyContent();
1210 $page = WikiPage::factory( $title );
1213 $parserOptions = ParserOptions::newFromUser( $wgUser );
1214 $content = $page->getContent( Revision::RAW );
1216 if ( !$content ) {
1217 //TODO: somehow show a warning to the user!
1218 return $handler->makeEmptyContent();
1221 if ( $content->getModel() !== $handler->getModelID() ) {
1222 $converted = $content->convert( $handler->getModelID() );
1224 if ( !$converted ) {
1225 //TODO: somehow show a warning to the user!
1226 wfDebug( "Attempt to preload incompatible content: "
1227 . "can't convert " . $content->getModel()
1228 . " to " . $handler->getModelID() );
1230 return $handler->makeEmptyContent();
1233 $content = $converted;
1236 return $content->preloadTransform( $title, $parserOptions, $params );
1240 * Make sure the form isn't faking a user's credentials.
1242 * @param WebRequest $request
1243 * @return bool
1244 * @private
1246 function tokenOk( &$request ) {
1247 global $wgUser;
1248 $token = $request->getVal( 'wpEditToken' );
1249 $this->mTokenOk = $wgUser->matchEditToken( $token );
1250 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1251 return $this->mTokenOk;
1255 * Sets post-edit cookie indicating the user just saved a particular revision.
1257 * This uses a temporary cookie for each revision ID so separate saves will never
1258 * interfere with each other.
1260 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1261 * the redirect. It must be clearable by JavaScript code, so it must not be
1262 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1263 * variable.
1265 * If the variable were set on the server, it would be cached, which is unwanted
1266 * since the post-edit state should only apply to the load right after the save.
1268 * @param int $statusValue The status value (to check for new article status)
1270 protected function setPostEditCookie( $statusValue ) {
1271 $revisionId = $this->mArticle->getLatest();
1272 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1274 $val = 'saved';
1275 if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1276 $val = 'created';
1277 } elseif ( $this->oldid ) {
1278 $val = 'restored';
1281 $response = RequestContext::getMain()->getRequest()->response();
1282 $response->setcookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION, array(
1283 'httpOnly' => false,
1284 ) );
1288 * Attempt submission
1289 * @param array $resultDetails See docs for $result in internalAttemptSave
1290 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1291 * @return Status The resulting status object.
1293 public function attemptSave( &$resultDetails = false ) {
1294 global $wgUser;
1296 # Allow bots to exempt some edits from bot flagging
1297 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1298 $status = $this->internalAttemptSave( $resultDetails, $bot );
1300 Hooks::run( 'EditPage::attemptSave:after', array( $this, $status, $resultDetails ) );
1302 return $status;
1306 * Handle status, such as after attempt save
1308 * @param Status $status
1309 * @param array|bool $resultDetails
1311 * @throws ErrorPageError
1312 * @return bool False, if output is done, true if rest of the form should be displayed
1314 private function handleStatus( Status $status, $resultDetails ) {
1315 global $wgUser, $wgOut;
1318 * @todo FIXME: once the interface for internalAttemptSave() is made
1319 * nicer, this should use the message in $status
1321 if ( $status->value == self::AS_SUCCESS_UPDATE
1322 || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1324 $this->didSave = true;
1325 if ( !$resultDetails['nullEdit'] ) {
1326 $this->setPostEditCookie( $status->value );
1330 switch ( $status->value ) {
1331 case self::AS_HOOK_ERROR_EXPECTED:
1332 case self::AS_CONTENT_TOO_BIG:
1333 case self::AS_ARTICLE_WAS_DELETED:
1334 case self::AS_CONFLICT_DETECTED:
1335 case self::AS_SUMMARY_NEEDED:
1336 case self::AS_TEXTBOX_EMPTY:
1337 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1338 case self::AS_END:
1339 case self::AS_BLANK_ARTICLE:
1340 case self::AS_SELF_REDIRECT:
1341 return true;
1343 case self::AS_HOOK_ERROR:
1344 return false;
1346 case self::AS_PARSE_ERROR:
1347 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1348 return true;
1350 case self::AS_SUCCESS_NEW_ARTICLE:
1351 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1352 $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1353 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1354 return false;
1356 case self::AS_SUCCESS_UPDATE:
1357 $extraQuery = '';
1358 $sectionanchor = $resultDetails['sectionanchor'];
1360 // Give extensions a chance to modify URL query on update
1361 Hooks::run(
1362 'ArticleUpdateBeforeRedirect',
1363 array( $this->mArticle, &$sectionanchor, &$extraQuery )
1366 if ( $resultDetails['redirect'] ) {
1367 if ( $extraQuery == '' ) {
1368 $extraQuery = 'redirect=no';
1369 } else {
1370 $extraQuery = 'redirect=no&' . $extraQuery;
1373 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1374 return false;
1376 case self::AS_SPAM_ERROR:
1377 $this->spamPageWithContent( $resultDetails['spam'] );
1378 return false;
1380 case self::AS_BLOCKED_PAGE_FOR_USER:
1381 throw new UserBlockedError( $wgUser->getBlock() );
1383 case self::AS_IMAGE_REDIRECT_ANON:
1384 case self::AS_IMAGE_REDIRECT_LOGGED:
1385 throw new PermissionsError( 'upload' );
1387 case self::AS_READ_ONLY_PAGE_ANON:
1388 case self::AS_READ_ONLY_PAGE_LOGGED:
1389 throw new PermissionsError( 'edit' );
1391 case self::AS_READ_ONLY_PAGE:
1392 throw new ReadOnlyError;
1394 case self::AS_RATE_LIMITED:
1395 throw new ThrottledError();
1397 case self::AS_NO_CREATE_PERMISSION:
1398 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1399 throw new PermissionsError( $permission );
1401 case self::AS_NO_CHANGE_CONTENT_MODEL:
1402 throw new PermissionsError( 'editcontentmodel' );
1404 default:
1405 // We don't recognize $status->value. The only way that can happen
1406 // is if an extension hook aborted from inside ArticleSave.
1407 // Render the status object into $this->hookError
1408 // FIXME this sucks, we should just use the Status object throughout
1409 $this->hookError = '<div class="error">' . $status->getWikitext() .
1410 '</div>';
1411 return true;
1416 * Run hooks that can filter edits just before they get saved.
1418 * @param Content $content The Content to filter.
1419 * @param Status $status For reporting the outcome to the caller
1420 * @param User $user The user performing the edit
1422 * @return bool
1424 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1425 // Run old style post-section-merge edit filter
1426 if ( !ContentHandler::runLegacyHooks( 'EditFilterMerged',
1427 array( $this, $content, &$this->hookError, $this->summary ) )
1429 # Error messages etc. could be handled within the hook...
1430 $status->fatal( 'hookaborted' );
1431 $status->value = self::AS_HOOK_ERROR;
1432 return false;
1433 } elseif ( $this->hookError != '' ) {
1434 # ...or the hook could be expecting us to produce an error
1435 $status->fatal( 'hookaborted' );
1436 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1437 return false;
1440 // Run new style post-section-merge edit filter
1441 if ( !Hooks::run( 'EditFilterMergedContent',
1442 array( $this->mArticle->getContext(), $content, $status, $this->summary,
1443 $user, $this->minoredit ) )
1445 # Error messages etc. could be handled within the hook...
1446 if ( $status->isGood() ) {
1447 $status->fatal( 'hookaborted' );
1448 // Not setting $this->hookError here is a hack to allow the hook
1449 // to cause a return to the edit page without $this->hookError
1450 // being set. This is used by ConfirmEdit to display a captcha
1451 // without any error message cruft.
1452 } else {
1453 $this->hookError = $status->getWikiText();
1455 // Use the existing $status->value if the hook set it
1456 if ( !$status->value ) {
1457 $status->value = self::AS_HOOK_ERROR;
1459 return false;
1460 } elseif ( !$status->isOK() ) {
1461 # ...or the hook could be expecting us to produce an error
1462 // FIXME this sucks, we should just use the Status object throughout
1463 $this->hookError = $status->getWikiText();
1464 $status->fatal( 'hookaborted' );
1465 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1466 return false;
1469 return true;
1473 * Return the summary to be used for a new section.
1475 * @param string $sectionanchor Set to the section anchor text
1476 * @return string
1478 private function newSectionSummary( &$sectionanchor = null ) {
1479 global $wgParser;
1481 if ( $this->sectiontitle !== '' ) {
1482 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1483 // If no edit summary was specified, create one automatically from the section
1484 // title and have it link to the new section. Otherwise, respect the summary as
1485 // passed.
1486 if ( $this->summary === '' ) {
1487 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1488 return wfMessage( 'newsectionsummary' )
1489 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1491 } elseif ( $this->summary !== '' ) {
1492 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1493 # This is a new section, so create a link to the new section
1494 # in the revision summary.
1495 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1496 return wfMessage( 'newsectionsummary' )
1497 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1499 return $this->summary;
1503 * Attempt submission (no UI)
1505 * @param array $result Array to add statuses to, currently with the
1506 * possible keys:
1507 * - spam (string): Spam string from content if any spam is detected by
1508 * matchSpamRegex.
1509 * - sectionanchor (string): Section anchor for a section save.
1510 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1511 * false otherwise.
1512 * - redirect (bool): Set if doEditContent is OK. True if resulting
1513 * revision is a redirect.
1514 * @param bool $bot True if edit is being made under the bot right.
1516 * @return Status Status object, possibly with a message, but always with
1517 * one of the AS_* constants in $status->value,
1519 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1520 * various error display idiosyncrasies. There are also lots of cases
1521 * where error metadata is set in the object and retrieved later instead
1522 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1523 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1524 * time.
1526 function internalAttemptSave( &$result, $bot = false ) {
1527 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1529 $status = Status::newGood();
1531 if ( !Hooks::run( 'EditPage::attemptSave', array( $this ) ) ) {
1532 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1533 $status->fatal( 'hookaborted' );
1534 $status->value = self::AS_HOOK_ERROR;
1535 return $status;
1538 $spam = $wgRequest->getText( 'wpAntispam' );
1539 if ( $spam !== '' ) {
1540 wfDebugLog(
1541 'SimpleAntiSpam',
1542 $wgUser->getName() .
1543 ' editing "' .
1544 $this->mTitle->getPrefixedText() .
1545 '" submitted bogus field "' .
1546 $spam .
1549 $status->fatal( 'spamprotectionmatch', false );
1550 $status->value = self::AS_SPAM_ERROR;
1551 return $status;
1554 try {
1555 # Construct Content object
1556 $textbox_content = $this->toEditContent( $this->textbox1 );
1557 } catch ( MWContentSerializationException $ex ) {
1558 $status->fatal(
1559 'content-failed-to-parse',
1560 $this->contentModel,
1561 $this->contentFormat,
1562 $ex->getMessage()
1564 $status->value = self::AS_PARSE_ERROR;
1565 return $status;
1568 # Check image redirect
1569 if ( $this->mTitle->getNamespace() == NS_FILE &&
1570 $textbox_content->isRedirect() &&
1571 !$wgUser->isAllowed( 'upload' )
1573 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1574 $status->setResult( false, $code );
1576 return $status;
1579 # Check for spam
1580 $match = self::matchSummarySpamRegex( $this->summary );
1581 if ( $match === false && $this->section == 'new' ) {
1582 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1583 # regular summaries, it is added to the actual wikitext.
1584 if ( $this->sectiontitle !== '' ) {
1585 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1586 $match = self::matchSpamRegex( $this->sectiontitle );
1587 } else {
1588 # This branch is taken when the "Add Topic" user interface is used, or the API
1589 # is used with the 'summary' parameter.
1590 $match = self::matchSpamRegex( $this->summary );
1593 if ( $match === false ) {
1594 $match = self::matchSpamRegex( $this->textbox1 );
1596 if ( $match !== false ) {
1597 $result['spam'] = $match;
1598 $ip = $wgRequest->getIP();
1599 $pdbk = $this->mTitle->getPrefixedDBkey();
1600 $match = str_replace( "\n", '', $match );
1601 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1602 $status->fatal( 'spamprotectionmatch', $match );
1603 $status->value = self::AS_SPAM_ERROR;
1604 return $status;
1606 if ( !Hooks::run(
1607 'EditFilter',
1608 array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) )
1610 # Error messages etc. could be handled within the hook...
1611 $status->fatal( 'hookaborted' );
1612 $status->value = self::AS_HOOK_ERROR;
1613 return $status;
1614 } elseif ( $this->hookError != '' ) {
1615 # ...or the hook could be expecting us to produce an error
1616 $status->fatal( 'hookaborted' );
1617 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1618 return $status;
1621 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1622 // Auto-block user's IP if the account was "hard" blocked
1623 $wgUser->spreadAnyEditBlock();
1624 # Check block state against master, thus 'false'.
1625 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1626 return $status;
1629 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1630 if ( $this->kblength > $wgMaxArticleSize ) {
1631 // Error will be displayed by showEditForm()
1632 $this->tooBig = true;
1633 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1634 return $status;
1637 if ( !$wgUser->isAllowed( 'edit' ) ) {
1638 if ( $wgUser->isAnon() ) {
1639 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1640 return $status;
1641 } else {
1642 $status->fatal( 'readonlytext' );
1643 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1644 return $status;
1648 if ( $this->contentModel !== $this->mTitle->getContentModel()
1649 && !$wgUser->isAllowed( 'editcontentmodel' )
1651 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1652 return $status;
1655 if ( wfReadOnly() ) {
1656 $status->fatal( 'readonlytext' );
1657 $status->value = self::AS_READ_ONLY_PAGE;
1658 return $status;
1660 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1661 $status->fatal( 'actionthrottledtext' );
1662 $status->value = self::AS_RATE_LIMITED;
1663 return $status;
1666 # If the article has been deleted while editing, don't save it without
1667 # confirmation
1668 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1669 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1670 return $status;
1673 # Load the page data from the master. If anything changes in the meantime,
1674 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1675 $this->mArticle->loadPageData( 'fromdbmaster' );
1676 $new = !$this->mArticle->exists();
1678 if ( $new ) {
1679 // Late check for create permission, just in case *PARANOIA*
1680 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1681 $status->fatal( 'nocreatetext' );
1682 $status->value = self::AS_NO_CREATE_PERMISSION;
1683 wfDebug( __METHOD__ . ": no create permission\n" );
1684 return $status;
1687 // Don't save a new page if it's blank or if it's a MediaWiki:
1688 // message with content equivalent to default (allow empty pages
1689 // in this case to disable messages, see bug 50124)
1690 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1691 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1692 $defaultText = $defaultMessageText;
1693 } else {
1694 $defaultText = '';
1697 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
1698 $this->blankArticle = true;
1699 $status->fatal( 'blankarticle' );
1700 $status->setResult( false, self::AS_BLANK_ARTICLE );
1701 return $status;
1704 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1705 return $status;
1708 $content = $textbox_content;
1710 $result['sectionanchor'] = '';
1711 if ( $this->section == 'new' ) {
1712 if ( $this->sectiontitle !== '' ) {
1713 // Insert the section title above the content.
1714 $content = $content->addSectionHeader( $this->sectiontitle );
1715 } elseif ( $this->summary !== '' ) {
1716 // Insert the section title above the content.
1717 $content = $content->addSectionHeader( $this->summary );
1719 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
1722 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1724 } else { # not $new
1726 # Article exists. Check for edit conflict.
1728 $this->mArticle->clear(); # Force reload of dates, etc.
1729 $timestamp = $this->mArticle->getTimestamp();
1731 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1733 if ( $timestamp != $this->edittime ) {
1734 $this->isConflict = true;
1735 if ( $this->section == 'new' ) {
1736 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
1737 $this->mArticle->getComment() == $this->newSectionSummary()
1739 // Probably a duplicate submission of a new comment.
1740 // This can happen when squid resends a request after
1741 // a timeout but the first one actually went through.
1742 wfDebug( __METHOD__
1743 . ": duplicate new section submission; trigger edit conflict!\n" );
1744 } else {
1745 // New comment; suppress conflict.
1746 $this->isConflict = false;
1747 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1749 } elseif ( $this->section == ''
1750 && Revision::userWasLastToEdit(
1751 DB_MASTER, $this->mTitle->getArticleID(),
1752 $wgUser->getId(), $this->edittime
1755 # Suppress edit conflict with self, except for section edits where merging is required.
1756 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1757 $this->isConflict = false;
1761 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1762 if ( $this->sectiontitle !== '' ) {
1763 $sectionTitle = $this->sectiontitle;
1764 } else {
1765 $sectionTitle = $this->summary;
1768 $content = null;
1770 if ( $this->isConflict ) {
1771 wfDebug( __METHOD__
1772 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1773 . " (article time '{$timestamp}')\n" );
1775 $content = $this->mArticle->replaceSectionContent(
1776 $this->section,
1777 $textbox_content,
1778 $sectionTitle,
1779 $this->edittime
1781 } else {
1782 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
1783 $content = $this->mArticle->replaceSectionContent(
1784 $this->section,
1785 $textbox_content,
1786 $sectionTitle
1790 if ( is_null( $content ) ) {
1791 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1792 $this->isConflict = true;
1793 $content = $textbox_content; // do not try to merge here!
1794 } elseif ( $this->isConflict ) {
1795 # Attempt merge
1796 if ( $this->mergeChangesIntoContent( $content ) ) {
1797 // Successful merge! Maybe we should tell the user the good news?
1798 $this->isConflict = false;
1799 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1800 } else {
1801 $this->section = '';
1802 $this->textbox1 = ContentHandler::getContentText( $content );
1803 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1807 if ( $this->isConflict ) {
1808 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1809 return $status;
1812 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1813 return $status;
1816 if ( $this->section == 'new' ) {
1817 // Handle the user preference to force summaries here
1818 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
1819 $this->missingSummary = true;
1820 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1821 $status->value = self::AS_SUMMARY_NEEDED;
1822 return $status;
1825 // Do not allow the user to post an empty comment
1826 if ( $this->textbox1 == '' ) {
1827 $this->missingComment = true;
1828 $status->fatal( 'missingcommenttext' );
1829 $status->value = self::AS_TEXTBOX_EMPTY;
1830 return $status;
1832 } elseif ( !$this->allowBlankSummary
1833 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1834 && !$content->isRedirect()
1835 && md5( $this->summary ) == $this->autoSumm
1837 $this->missingSummary = true;
1838 $status->fatal( 'missingsummary' );
1839 $status->value = self::AS_SUMMARY_NEEDED;
1840 return $status;
1843 # All's well
1844 $sectionanchor = '';
1845 if ( $this->section == 'new' ) {
1846 $this->summary = $this->newSectionSummary( $sectionanchor );
1847 } elseif ( $this->section != '' ) {
1848 # Try to get a section anchor from the section source, redirect
1849 # to edited section if header found.
1850 # XXX: Might be better to integrate this into Article::replaceSection
1851 # for duplicate heading checking and maybe parsing.
1852 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1853 # We can't deal with anchors, includes, html etc in the header for now,
1854 # headline would need to be parsed to improve this.
1855 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1856 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1859 $result['sectionanchor'] = $sectionanchor;
1861 // Save errors may fall down to the edit form, but we've now
1862 // merged the section into full text. Clear the section field
1863 // so that later submission of conflict forms won't try to
1864 // replace that into a duplicated mess.
1865 $this->textbox1 = $this->toEditText( $content );
1866 $this->section = '';
1868 $status->value = self::AS_SUCCESS_UPDATE;
1871 if ( !$this->allowSelfRedirect
1872 && $content->isRedirect()
1873 && $content->getRedirectTarget()->equals( $this->getTitle() )
1875 // If the page already redirects to itself, don't warn.
1876 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
1877 if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
1878 $this->selfRedirect = true;
1879 $status->fatal( 'selfredirect' );
1880 $status->value = self::AS_SELF_REDIRECT;
1881 return $status;
1885 // Check for length errors again now that the section is merged in
1886 $this->kblength = (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1887 if ( $this->kblength > $wgMaxArticleSize ) {
1888 $this->tooBig = true;
1889 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
1890 return $status;
1893 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1894 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1895 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1896 ( $bot ? EDIT_FORCE_BOT : 0 );
1898 $doEditStatus = $this->mArticle->doEditContent(
1899 $content,
1900 $this->summary,
1901 $flags,
1902 false,
1903 null,
1904 $content->getDefaultFormat()
1907 if ( !$doEditStatus->isOK() ) {
1908 // Failure from doEdit()
1909 // Show the edit conflict page for certain recognized errors from doEdit(),
1910 // but don't show it for errors from extension hooks
1911 $errors = $doEditStatus->getErrorsArray();
1912 if ( in_array( $errors[0][0],
1913 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1915 $this->isConflict = true;
1916 // Destroys data doEdit() put in $status->value but who cares
1917 $doEditStatus->value = self::AS_END;
1919 return $doEditStatus;
1922 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1923 if ( $result['nullEdit'] ) {
1924 // We don't know if it was a null edit until now, so increment here
1925 $wgUser->pingLimiter( 'linkpurge' );
1927 $result['redirect'] = $content->isRedirect();
1928 $this->updateWatchlist();
1929 return $status;
1933 * Register the change of watch status
1935 protected function updateWatchlist() {
1936 global $wgUser;
1938 if ( $wgUser->isLoggedIn()
1939 && $this->watchthis != $wgUser->isWatched( $this->mTitle, WatchedItem::IGNORE_USER_RIGHTS )
1941 $fname = __METHOD__;
1942 $title = $this->mTitle;
1943 $watch = $this->watchthis;
1945 // Do this in its own transaction to reduce contention...
1946 $dbw = wfGetDB( DB_MASTER );
1947 $dbw->onTransactionIdle( function () use ( $dbw, $title, $watch, $wgUser, $fname ) {
1948 WatchAction::doWatchOrUnwatch( $watch, $title, $wgUser );
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 ) {
1966 $db = wfGetDB( DB_MASTER );
1968 // This is the revision the editor started from
1969 $baseRevision = $this->getBaseRevision();
1970 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
1972 if ( is_null( $baseContent ) ) {
1973 return false;
1976 // The current state, we want to merge updates into it
1977 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1978 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
1980 if ( is_null( $currentContent ) ) {
1981 return false;
1984 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
1986 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1988 if ( $result ) {
1989 $editContent = $result;
1990 return true;
1993 return false;
1997 * @return Revision
1999 function getBaseRevision() {
2000 if ( !$this->mBaseRevision ) {
2001 $db = wfGetDB( DB_MASTER );
2002 $this->mBaseRevision = Revision::loadFromTimestamp(
2003 $db, $this->mTitle, $this->edittime );
2005 return $this->mBaseRevision;
2009 * Check given input text against $wgSpamRegex, and return the text of the first match.
2011 * @param string $text
2013 * @return string|bool Matching string or false
2015 public static function matchSpamRegex( $text ) {
2016 global $wgSpamRegex;
2017 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2018 $regexes = (array)$wgSpamRegex;
2019 return self::matchSpamRegexInternal( $text, $regexes );
2023 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2025 * @param string $text
2027 * @return string|bool Matching string or false
2029 public static function matchSummarySpamRegex( $text ) {
2030 global $wgSummarySpamRegex;
2031 $regexes = (array)$wgSummarySpamRegex;
2032 return self::matchSpamRegexInternal( $text, $regexes );
2036 * @param string $text
2037 * @param array $regexes
2038 * @return bool|string
2040 protected static function matchSpamRegexInternal( $text, $regexes ) {
2041 foreach ( $regexes as $regex ) {
2042 $matches = array();
2043 if ( preg_match( $regex, $text, $matches ) ) {
2044 return $matches[0];
2047 return false;
2050 function setHeaders() {
2051 global $wgOut, $wgUser, $wgAjaxEditStash;
2053 $wgOut->addModules( 'mediawiki.action.edit' );
2054 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2056 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2057 // The addition of default buttons is handled by getEditToolbar() which
2058 // has its own dependency on this module. The call here ensures the module
2059 // is loaded in time (it has position "top") for other modules to register
2060 // buttons (e.g. extensions, gadgets, user scripts).
2061 $wgOut->addModules( 'mediawiki.toolbar' );
2064 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2065 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2068 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2069 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2072 if ( $wgAjaxEditStash ) {
2073 $wgOut->addModules( 'mediawiki.action.edit.stash' );
2076 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2078 # Enabled article-related sidebar, toplinks, etc.
2079 $wgOut->setArticleRelated( true );
2081 $contextTitle = $this->getContextTitle();
2082 if ( $this->isConflict ) {
2083 $msg = 'editconflict';
2084 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2085 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2086 } else {
2087 $msg = $contextTitle->exists()
2088 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2089 && $contextTitle->getDefaultMessageText() !== false
2091 ? 'editing'
2092 : 'creating';
2095 # Use the title defined by DISPLAYTITLE magic word when present
2096 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2097 if ( $displayTitle === false ) {
2098 $displayTitle = $contextTitle->getPrefixedText();
2100 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2104 * Show all applicable editing introductions
2106 protected function showIntro() {
2107 global $wgOut, $wgUser;
2108 if ( $this->suppressIntro ) {
2109 return;
2112 $namespace = $this->mTitle->getNamespace();
2114 if ( $namespace == NS_MEDIAWIKI ) {
2115 # Show a warning if editing an interface message
2116 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2117 # If this is a default message (but not css or js),
2118 # show a hint that it is translatable on translatewiki.net
2119 if ( !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2120 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2122 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2123 if ( $defaultMessageText !== false ) {
2124 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2125 'translateinterface' );
2128 } elseif ( $namespace == NS_FILE ) {
2129 # Show a hint to shared repo
2130 $file = wfFindFile( $this->mTitle );
2131 if ( $file && !$file->isLocal() ) {
2132 $descUrl = $file->getDescriptionUrl();
2133 # there must be a description url to show a hint to shared repo
2134 if ( $descUrl ) {
2135 if ( !$this->mTitle->exists() ) {
2136 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2137 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2138 ) );
2139 } else {
2140 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2141 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2142 ) );
2148 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2149 # Show log extract when the user is currently blocked
2150 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2151 $parts = explode( '/', $this->mTitle->getText(), 2 );
2152 $username = $parts[0];
2153 $user = User::newFromName( $username, false /* allow IP users*/ );
2154 $ip = User::isIP( $username );
2155 $block = Block::newFromTarget( $user, $user );
2156 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2157 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2158 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2159 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2160 # Show log extract if the user is currently blocked
2161 LogEventsList::showLogExtract(
2162 $wgOut,
2163 'block',
2164 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2166 array(
2167 'lim' => 1,
2168 'showIfEmpty' => false,
2169 'msgKey' => array(
2170 'blocked-notice-logextract',
2171 $user->getName() # Support GENDER in notice
2177 # Try to add a custom edit intro, or use the standard one if this is not possible.
2178 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2179 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2180 wfMessage( 'helppage' )->inContentLanguage()->text()
2181 ) );
2182 if ( $wgUser->isLoggedIn() ) {
2183 $wgOut->wrapWikiMsg(
2184 // Suppress the external link icon, consider the help url an internal one
2185 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2186 array(
2187 'newarticletext',
2188 $helpLink
2191 } else {
2192 $wgOut->wrapWikiMsg(
2193 // Suppress the external link icon, consider the help url an internal one
2194 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2195 array(
2196 'newarticletextanon',
2197 $helpLink
2202 # Give a notice if the user is editing a deleted/moved page...
2203 if ( !$this->mTitle->exists() ) {
2204 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
2206 array(
2207 'lim' => 10,
2208 'conds' => array( "log_action != 'revision'" ),
2209 'showIfEmpty' => false,
2210 'msgKey' => array( 'recreate-moveddeleted-warn' )
2217 * Attempt to show a custom editing introduction, if supplied
2219 * @return bool
2221 protected function showCustomIntro() {
2222 if ( $this->editintro ) {
2223 $title = Title::newFromText( $this->editintro );
2224 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2225 global $wgOut;
2226 // Added using template syntax, to take <noinclude>'s into account.
2227 $wgOut->addWikiTextTitleTidy(
2228 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2229 $this->mTitle
2231 return true;
2234 return false;
2238 * Gets an editable textual representation of $content.
2239 * The textual representation can be turned by into a Content object by the
2240 * toEditContent() method.
2242 * If $content is null or false or a string, $content is returned unchanged.
2244 * If the given Content object is not of a type that can be edited using
2245 * the text base EditPage, an exception will be raised. Set
2246 * $this->allowNonTextContent to true to allow editing of non-textual
2247 * content.
2249 * @param Content|null|bool|string $content
2250 * @return string The editable text form of the content.
2252 * @throws MWException If $content is not an instance of TextContent and
2253 * $this->allowNonTextContent is not true.
2255 protected function toEditText( $content ) {
2256 if ( $content === null || $content === false || is_string( $content ) ) {
2257 return $content;
2260 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2261 throw new MWException( 'This content model is not supported: '
2262 . ContentHandler::getLocalizedName( $content->getModel() ) );
2265 return $content->serialize( $this->contentFormat );
2269 * Turns the given text into a Content object by unserializing it.
2271 * If the resulting Content object is not of a type that can be edited using
2272 * the text base EditPage, an exception will be raised. Set
2273 * $this->allowNonTextContent to true to allow editing of non-textual
2274 * content.
2276 * @param string|null|bool $text Text to unserialize
2277 * @return Content The content object created from $text. If $text was false
2278 * or null, false resp. null will be returned instead.
2280 * @throws MWException If unserializing the text results in a Content
2281 * object that is not an instance of TextContent and
2282 * $this->allowNonTextContent is not true.
2284 protected function toEditContent( $text ) {
2285 if ( $text === false || $text === null ) {
2286 return $text;
2289 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2290 $this->contentModel, $this->contentFormat );
2292 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2293 throw new MWException( 'This content model is not supported: '
2294 . ContentHandler::getLocalizedName( $content->getModel() ) );
2297 return $content;
2301 * Send the edit form and related headers to $wgOut
2302 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2303 * during form output near the top, for captchas and the like.
2305 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2306 * use the EditPage::showEditForm:fields hook instead.
2308 function showEditForm( $formCallback = null ) {
2309 global $wgOut, $wgUser;
2311 # need to parse the preview early so that we know which templates are used,
2312 # otherwise users with "show preview after edit box" will get a blank list
2313 # we parse this near the beginning so that setHeaders can do the title
2314 # setting work instead of leaving it in getPreviewText
2315 $previewOutput = '';
2316 if ( $this->formtype == 'preview' ) {
2317 $previewOutput = $this->getPreviewText();
2320 Hooks::run( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2322 $this->setHeaders();
2324 if ( $this->showHeader() === false ) {
2325 return;
2328 $wgOut->addHTML( $this->editFormPageTop );
2330 if ( $wgUser->getOption( 'previewontop' ) ) {
2331 $this->displayPreviewArea( $previewOutput, true );
2334 $wgOut->addHTML( $this->editFormTextTop );
2336 $showToolbar = true;
2337 if ( $this->wasDeletedSinceLastEdit() ) {
2338 if ( $this->formtype == 'save' ) {
2339 // Hide the toolbar and edit area, user can click preview to get it back
2340 // Add an confirmation checkbox and explanation.
2341 $showToolbar = false;
2342 } else {
2343 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2344 'deletedwhileediting' );
2348 // @todo add EditForm plugin interface and use it here!
2349 // search for textarea1 and textares2, and allow EditForm to override all uses.
2350 $wgOut->addHTML( Html::openElement(
2351 'form',
2352 array(
2353 'id' => self::EDITFORM_ID,
2354 'name' => self::EDITFORM_ID,
2355 'method' => 'post',
2356 'action' => $this->getActionURL( $this->getContextTitle() ),
2357 'enctype' => 'multipart/form-data'
2359 ) );
2361 if ( is_callable( $formCallback ) ) {
2362 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2363 call_user_func_array( $formCallback, array( &$wgOut ) );
2366 // Add an empty field to trip up spambots
2367 $wgOut->addHTML(
2368 Xml::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2369 . Html::rawElement(
2370 'label',
2371 array( 'for' => 'wpAntiSpam' ),
2372 wfMessage( 'simpleantispam-label' )->parse()
2374 . Xml::element(
2375 'input',
2376 array(
2377 'type' => 'text',
2378 'name' => 'wpAntispam',
2379 'id' => 'wpAntispam',
2380 'value' => ''
2383 . Xml::closeElement( 'div' )
2386 Hooks::run( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2388 // Put these up at the top to ensure they aren't lost on early form submission
2389 $this->showFormBeforeText();
2391 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2392 $username = $this->lastDelete->user_name;
2393 $comment = $this->lastDelete->log_comment;
2395 // It is better to not parse the comment at all than to have templates expanded in the middle
2396 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2397 $key = $comment === ''
2398 ? 'confirmrecreate-noreason'
2399 : 'confirmrecreate';
2400 $wgOut->addHTML(
2401 '<div class="mw-confirm-recreate">' .
2402 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2403 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2404 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2406 '</div>'
2410 # When the summary is hidden, also hide them on preview/show changes
2411 if ( $this->nosummary ) {
2412 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2415 # If a blank edit summary was previously provided, and the appropriate
2416 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2417 # user being bounced back more than once in the event that a summary
2418 # is not required.
2419 #####
2420 # For a bit more sophisticated detection of blank summaries, hash the
2421 # automatic one and pass that in the hidden field wpAutoSummary.
2422 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2423 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2426 if ( $this->undidRev ) {
2427 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2430 if ( $this->selfRedirect ) {
2431 $wgOut->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2434 if ( $this->hasPresetSummary ) {
2435 // If a summary has been preset using &summary= we don't want to prompt for
2436 // a different summary. Only prompt for a summary if the summary is blanked.
2437 // (Bug 17416)
2438 $this->autoSumm = md5( '' );
2441 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2442 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2444 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2445 $wgOut->addHTML( Html::hidden( 'parentRevId',
2446 $this->parentRevId ?: $this->mArticle->getRevIdFetched() ) );
2448 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2449 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2451 if ( $this->section == 'new' ) {
2452 $this->showSummaryInput( true, $this->summary );
2453 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2456 $wgOut->addHTML( $this->editFormTextBeforeContent );
2458 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2459 $wgOut->addHTML( EditPage::getEditToolbar() );
2462 if ( $this->blankArticle ) {
2463 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2466 if ( $this->isConflict ) {
2467 // In an edit conflict bypass the overridable content form method
2468 // and fallback to the raw wpTextbox1 since editconflicts can't be
2469 // resolved between page source edits and custom ui edits using the
2470 // custom edit ui.
2471 $this->textbox2 = $this->textbox1;
2473 $content = $this->getCurrentContent();
2474 $this->textbox1 = $this->toEditText( $content );
2476 $this->showTextbox1();
2477 } else {
2478 $this->showContentForm();
2481 $wgOut->addHTML( $this->editFormTextAfterContent );
2483 $this->showStandardInputs();
2485 $this->showFormAfterText();
2487 $this->showTosSummary();
2489 $this->showEditTools();
2491 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2493 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2494 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2496 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2497 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
2499 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'limitreport' ),
2500 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2502 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2504 if ( $this->isConflict ) {
2505 try {
2506 $this->showConflict();
2507 } catch ( MWContentSerializationException $ex ) {
2508 // this can't really happen, but be nice if it does.
2509 $msg = wfMessage(
2510 'content-failed-to-parse',
2511 $this->contentModel,
2512 $this->contentFormat,
2513 $ex->getMessage()
2515 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2519 // Marker for detecting truncated form data. This must be the last
2520 // parameter sent in order to be of use, so do not move me.
2521 $wgOut->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2522 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2524 if ( !$wgUser->getOption( 'previewontop' ) ) {
2525 $this->displayPreviewArea( $previewOutput, false );
2531 * Extract the section title from current section text, if any.
2533 * @param string $text
2534 * @return string|bool String or false
2536 public static function extractSectionTitle( $text ) {
2537 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2538 if ( !empty( $matches[2] ) ) {
2539 global $wgParser;
2540 return $wgParser->stripSectionName( trim( $matches[2] ) );
2541 } else {
2542 return false;
2547 * @return bool
2549 protected function showHeader() {
2550 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2551 global $wgAllowUserCss, $wgAllowUserJs;
2553 if ( $this->mTitle->isTalkPage() ) {
2554 $wgOut->addWikiMsg( 'talkpagetext' );
2557 // Add edit notices
2558 $wgOut->addHTML( implode( "\n", $this->mTitle->getEditNotices( $this->oldid ) ) );
2560 if ( $this->isConflict ) {
2561 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2562 $this->edittime = $this->mArticle->getTimestamp();
2563 } else {
2564 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2565 // We use $this->section to much before this and getVal('wgSection') directly in other places
2566 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2567 // Someone is welcome to try refactoring though
2568 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2569 return false;
2572 if ( $this->section != '' && $this->section != 'new' ) {
2573 if ( !$this->summary && !$this->preview && !$this->diff ) {
2574 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); //FIXME: use Content object
2575 if ( $sectionTitle !== false ) {
2576 $this->summary = "/* $sectionTitle */ ";
2581 if ( $this->missingComment ) {
2582 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2585 if ( $this->missingSummary && $this->section != 'new' ) {
2586 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2589 if ( $this->missingSummary && $this->section == 'new' ) {
2590 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2593 if ( $this->blankArticle ) {
2594 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2597 if ( $this->selfRedirect ) {
2598 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2601 if ( $this->hookError !== '' ) {
2602 $wgOut->addWikiText( $this->hookError );
2605 if ( !$this->checkUnicodeCompliantBrowser() ) {
2606 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2609 if ( $this->section != 'new' ) {
2610 $revision = $this->mArticle->getRevisionFetched();
2611 if ( $revision ) {
2612 // Let sysop know that this will make private content public if saved
2614 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2615 $wgOut->wrapWikiMsg(
2616 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2617 'rev-deleted-text-permission'
2619 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2620 $wgOut->wrapWikiMsg(
2621 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2622 'rev-deleted-text-view'
2626 if ( !$revision->isCurrent() ) {
2627 $this->mArticle->setOldSubtitle( $revision->getId() );
2628 $wgOut->addWikiMsg( 'editingold' );
2630 } elseif ( $this->mTitle->exists() ) {
2631 // Something went wrong
2633 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2634 array( 'missing-revision', $this->oldid ) );
2639 if ( wfReadOnly() ) {
2640 $wgOut->wrapWikiMsg(
2641 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2642 array( 'readonlywarning', wfReadOnlyReason() )
2644 } elseif ( $wgUser->isAnon() ) {
2645 if ( $this->formtype != 'preview' ) {
2646 $wgOut->wrapWikiMsg(
2647 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2648 array( 'anoneditwarning',
2649 // Log-in link
2650 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2651 // Sign-up link
2652 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2654 } else {
2655 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2656 'anonpreviewwarning'
2659 } else {
2660 if ( $this->isCssJsSubpage ) {
2661 # Check the skin exists
2662 if ( $this->isWrongCaseCssJsPage ) {
2663 $wgOut->wrapWikiMsg(
2664 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2665 array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() )
2668 if ( $this->formtype !== 'preview' ) {
2669 if ( $this->isCssSubpage && $wgAllowUserCss ) {
2670 $wgOut->wrapWikiMsg(
2671 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2672 array( 'usercssyoucanpreview' )
2676 if ( $this->isJsSubpage && $wgAllowUserJs ) {
2677 $wgOut->wrapWikiMsg(
2678 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2679 array( 'userjsyoucanpreview' )
2686 if ( $this->mTitle->isProtected( 'edit' ) &&
2687 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2689 # Is the title semi-protected?
2690 if ( $this->mTitle->isSemiProtected() ) {
2691 $noticeMsg = 'semiprotectedpagewarning';
2692 } else {
2693 # Then it must be protected based on static groups (regular)
2694 $noticeMsg = 'protectedpagewarning';
2696 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2697 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2699 if ( $this->mTitle->isCascadeProtected() ) {
2700 # Is this page under cascading protection from some source pages?
2701 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2702 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2703 $cascadeSourcesCount = count( $cascadeSources );
2704 if ( $cascadeSourcesCount > 0 ) {
2705 # Explain, and list the titles responsible
2706 foreach ( $cascadeSources as $page ) {
2707 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2710 $notice .= '</div>';
2711 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2713 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2714 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2715 array( 'lim' => 1,
2716 'showIfEmpty' => false,
2717 'msgKey' => array( 'titleprotectedwarning' ),
2718 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2721 if ( $this->kblength === false ) {
2722 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2725 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2726 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2727 array(
2728 'longpageerror',
2729 $wgLang->formatNum( $this->kblength ),
2730 $wgLang->formatNum( $wgMaxArticleSize )
2733 } else {
2734 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2735 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2736 array(
2737 'longpage-hint',
2738 $wgLang->formatSize( strlen( $this->textbox1 ) ),
2739 strlen( $this->textbox1 )
2744 # Add header copyright warning
2745 $this->showHeaderCopyrightWarning();
2747 return true;
2751 * Standard summary input and label (wgSummary), abstracted so EditPage
2752 * subclasses may reorganize the form.
2753 * Note that you do not need to worry about the label's for=, it will be
2754 * inferred by the id given to the input. You can remove them both by
2755 * passing array( 'id' => false ) to $userInputAttrs.
2757 * @param string $summary The value of the summary input
2758 * @param string $labelText The html to place inside the label
2759 * @param array $inputAttrs Array of attrs to use on the input
2760 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2762 * @return array An array in the format array( $label, $input )
2764 function getSummaryInput( $summary = "", $labelText = null,
2765 $inputAttrs = null, $spanLabelAttrs = null
2767 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2768 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2769 'id' => 'wpSummary',
2770 'maxlength' => '200',
2771 'tabindex' => '1',
2772 'size' => 60,
2773 'spellcheck' => 'true',
2774 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2776 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2777 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2778 'id' => "wpSummaryLabel"
2781 $label = null;
2782 if ( $labelText ) {
2783 $label = Xml::tags(
2784 'label',
2785 $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null,
2786 $labelText
2788 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2791 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2793 return array( $label, $input );
2797 * @param bool $isSubjectPreview True if this is the section subject/title
2798 * up top, or false if this is the comment summary
2799 * down below the textarea
2800 * @param string $summary The text of the summary to display
2802 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2803 global $wgOut, $wgContLang;
2804 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2805 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2806 if ( $isSubjectPreview ) {
2807 if ( $this->nosummary ) {
2808 return;
2810 } else {
2811 if ( !$this->mShowSummaryField ) {
2812 return;
2815 $summary = $wgContLang->recodeForEdit( $summary );
2816 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2817 list( $label, $input ) = $this->getSummaryInput(
2818 $summary,
2819 $labelText,
2820 array( 'class' => $summaryClass ),
2821 array()
2823 $wgOut->addHTML( "{$label} {$input}" );
2827 * @param bool $isSubjectPreview True if this is the section subject/title
2828 * up top, or false if this is the comment summary
2829 * down below the textarea
2830 * @param string $summary The text of the summary to display
2831 * @return string
2833 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2834 // avoid spaces in preview, gets always trimmed on save
2835 $summary = trim( $summary );
2836 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
2837 return "";
2840 global $wgParser;
2842 if ( $isSubjectPreview ) {
2843 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2844 ->inContentLanguage()->text();
2847 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2849 $summary = wfMessage( $message )->parse()
2850 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2851 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2854 protected function showFormBeforeText() {
2855 global $wgOut;
2856 $section = htmlspecialchars( $this->section );
2857 $wgOut->addHTML( <<<HTML
2858 <input type='hidden' value="{$section}" name="wpSection"/>
2859 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2860 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2861 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2863 HTML
2865 if ( !$this->checkUnicodeCompliantBrowser() ) {
2866 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2870 protected function showFormAfterText() {
2871 global $wgOut, $wgUser;
2873 * To make it harder for someone to slip a user a page
2874 * which submits an edit form to the wiki without their
2875 * knowledge, a random token is associated with the login
2876 * session. If it's not passed back with the submission,
2877 * we won't save the page, or render user JavaScript and
2878 * CSS previews.
2880 * For anon editors, who may not have a session, we just
2881 * include the constant suffix to prevent editing from
2882 * broken text-mangling proxies.
2884 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2888 * Subpage overridable method for printing the form for page content editing
2889 * By default this simply outputs wpTextbox1
2890 * Subclasses can override this to provide a custom UI for editing;
2891 * be it a form, or simply wpTextbox1 with a modified content that will be
2892 * reverse modified when extracted from the post data.
2893 * Note that this is basically the inverse for importContentFormData
2895 protected function showContentForm() {
2896 $this->showTextbox1();
2900 * Method to output wpTextbox1
2901 * The $textoverride method can be used by subclasses overriding showContentForm
2902 * to pass back to this method.
2904 * @param array $customAttribs Array of html attributes to use in the textarea
2905 * @param string $textoverride Optional text to override $this->textarea1 with
2907 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2908 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2909 $attribs = array( 'style' => 'display:none;' );
2910 } else {
2911 $classes = array(); // Textarea CSS
2912 if ( $this->mTitle->isProtected( 'edit' ) &&
2913 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2915 # Is the title semi-protected?
2916 if ( $this->mTitle->isSemiProtected() ) {
2917 $classes[] = 'mw-textarea-sprotected';
2918 } else {
2919 # Then it must be protected based on static groups (regular)
2920 $classes[] = 'mw-textarea-protected';
2922 # Is the title cascade-protected?
2923 if ( $this->mTitle->isCascadeProtected() ) {
2924 $classes[] = 'mw-textarea-cprotected';
2928 $attribs = array( 'tabindex' => 1 );
2930 if ( is_array( $customAttribs ) ) {
2931 $attribs += $customAttribs;
2934 if ( count( $classes ) ) {
2935 if ( isset( $attribs['class'] ) ) {
2936 $classes[] = $attribs['class'];
2938 $attribs['class'] = implode( ' ', $classes );
2942 $this->showTextbox(
2943 $textoverride !== null ? $textoverride : $this->textbox1,
2944 'wpTextbox1',
2945 $attribs
2949 protected function showTextbox2() {
2950 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2953 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2954 global $wgOut, $wgUser;
2956 $wikitext = $this->safeUnicodeOutput( $text );
2957 if ( strval( $wikitext ) !== '' ) {
2958 // Ensure there's a newline at the end, otherwise adding lines
2959 // is awkward.
2960 // But don't add a newline if the ext is empty, or Firefox in XHTML
2961 // mode will show an extra newline. A bit annoying.
2962 $wikitext .= "\n";
2965 $attribs = $customAttribs + array(
2966 'accesskey' => ',',
2967 'id' => $name,
2968 'cols' => $wgUser->getIntOption( 'cols' ),
2969 'rows' => $wgUser->getIntOption( 'rows' ),
2970 // Avoid PHP notices when appending preferences
2971 // (appending allows customAttribs['style'] to still work).
2972 'style' => ''
2975 $pageLang = $this->mTitle->getPageLanguage();
2976 $attribs['lang'] = $pageLang->getHtmlCode();
2977 $attribs['dir'] = $pageLang->getDir();
2979 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
2982 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2983 global $wgOut;
2984 $classes = array();
2985 if ( $isOnTop ) {
2986 $classes[] = 'ontop';
2989 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2991 if ( $this->formtype != 'preview' ) {
2992 $attribs['style'] = 'display: none;';
2995 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
2997 if ( $this->formtype == 'preview' ) {
2998 $this->showPreview( $previewOutput );
2999 } else {
3000 // Empty content container for LivePreview
3001 $pageViewLang = $this->mTitle->getPageViewLanguage();
3002 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3003 'class' => 'mw-content-' . $pageViewLang->getDir() );
3004 $wgOut->addHTML( Html::rawElement( 'div', $attribs ) );
3007 $wgOut->addHTML( '</div>' );
3009 if ( $this->formtype == 'diff' ) {
3010 try {
3011 $this->showDiff();
3012 } catch ( MWContentSerializationException $ex ) {
3013 $msg = wfMessage(
3014 'content-failed-to-parse',
3015 $this->contentModel,
3016 $this->contentFormat,
3017 $ex->getMessage()
3019 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3025 * Append preview output to $wgOut.
3026 * Includes category rendering if this is a category page.
3028 * @param string $text The HTML to be output for the preview.
3030 protected function showPreview( $text ) {
3031 global $wgOut;
3032 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3033 $this->mArticle->openShowCategory();
3035 # This hook seems slightly odd here, but makes things more
3036 # consistent for extensions.
3037 Hooks::run( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3038 $wgOut->addHTML( $text );
3039 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3040 $this->mArticle->closeShowCategory();
3045 * Get a diff between the current contents of the edit box and the
3046 * version of the page we're editing from.
3048 * If this is a section edit, we'll replace the section as for final
3049 * save and then make a comparison.
3051 function showDiff() {
3052 global $wgUser, $wgContLang, $wgOut;
3054 $oldtitlemsg = 'currentrev';
3055 # if message does not exist, show diff against the preloaded default
3056 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3057 $oldtext = $this->mTitle->getDefaultMessageText();
3058 if ( $oldtext !== false ) {
3059 $oldtitlemsg = 'defaultmessagetext';
3060 $oldContent = $this->toEditContent( $oldtext );
3061 } else {
3062 $oldContent = null;
3064 } else {
3065 $oldContent = $this->getCurrentContent();
3068 $textboxContent = $this->toEditContent( $this->textbox1 );
3070 $newContent = $this->mArticle->replaceSectionContent(
3071 $this->section, $textboxContent,
3072 $this->summary, $this->edittime );
3074 if ( $newContent ) {
3075 ContentHandler::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3076 Hooks::run( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3078 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
3079 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
3082 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3083 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3084 $newtitle = wfMessage( 'yourtext' )->parse();
3086 if ( !$oldContent ) {
3087 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3090 if ( !$newContent ) {
3091 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3094 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
3095 $de->setContent( $oldContent, $newContent );
3097 $difftext = $de->getDiff( $oldtitle, $newtitle );
3098 $de->showDiffStyle();
3099 } else {
3100 $difftext = '';
3103 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3107 * Show the header copyright warning.
3109 protected function showHeaderCopyrightWarning() {
3110 $msg = 'editpage-head-copy-warn';
3111 if ( !wfMessage( $msg )->isDisabled() ) {
3112 global $wgOut;
3113 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3114 'editpage-head-copy-warn' );
3119 * Give a chance for site and per-namespace customizations of
3120 * terms of service summary link that might exist separately
3121 * from the copyright notice.
3123 * This will display between the save button and the edit tools,
3124 * so should remain short!
3126 protected function showTosSummary() {
3127 $msg = 'editpage-tos-summary';
3128 Hooks::run( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
3129 if ( !wfMessage( $msg )->isDisabled() ) {
3130 global $wgOut;
3131 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3132 $wgOut->addWikiMsg( $msg );
3133 $wgOut->addHTML( '</div>' );
3137 protected function showEditTools() {
3138 global $wgOut;
3139 $wgOut->addHTML( '<div class="mw-editTools">' .
3140 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3141 '</div>' );
3145 * Get the copyright warning
3147 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3148 * @return string
3150 protected function getCopywarn() {
3151 return self::getCopyrightWarning( $this->mTitle );
3155 * Get the copyright warning, by default returns wikitext
3157 * @param Title $title
3158 * @param string $format Output format, valid values are any function of a Message object
3159 * @return string
3161 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3162 global $wgRightsText;
3163 if ( $wgRightsText ) {
3164 $copywarnMsg = array( 'copyrightwarning',
3165 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3166 $wgRightsText );
3167 } else {
3168 $copywarnMsg = array( 'copyrightwarning2',
3169 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3171 // Allow for site and per-namespace customization of contribution/copyright notice.
3172 Hooks::run( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3174 return "<div id=\"editpage-copywarn\">\n" .
3175 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3179 * Get the Limit report for page previews
3181 * @since 1.22
3182 * @param ParserOutput $output ParserOutput object from the parse
3183 * @return string HTML
3185 public static function getPreviewLimitReport( $output ) {
3186 if ( !$output || !$output->getLimitReportData() ) {
3187 return '';
3190 $limitReport = Html::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3191 wfMessage( 'limitreport-title' )->parseAsBlock()
3194 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3195 $limitReport .= Html::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3197 $limitReport .= Html::openElement( 'table', array(
3198 'class' => 'preview-limit-report wikitable'
3199 ) ) .
3200 Html::openElement( 'tbody' );
3202 foreach ( $output->getLimitReportData() as $key => $value ) {
3203 if ( Hooks::run( 'ParserLimitReportFormat',
3204 array( $key, &$value, &$limitReport, true, true )
3205 ) ) {
3206 $keyMsg = wfMessage( $key );
3207 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3208 if ( !$valueMsg->exists() ) {
3209 $valueMsg = new RawMessage( '$1' );
3211 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3212 $limitReport .= Html::openElement( 'tr' ) .
3213 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3214 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3215 Html::closeElement( 'tr' );
3220 $limitReport .= Html::closeElement( 'tbody' ) .
3221 Html::closeElement( 'table' ) .
3222 Html::closeElement( 'div' );
3224 return $limitReport;
3227 protected function showStandardInputs( &$tabindex = 2 ) {
3228 global $wgOut;
3229 $wgOut->addHTML( "<div class='editOptions'>\n" );
3231 if ( $this->section != 'new' ) {
3232 $this->showSummaryInput( false, $this->summary );
3233 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3236 $checkboxes = $this->getCheckboxes( $tabindex,
3237 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
3238 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3240 // Show copyright warning.
3241 $wgOut->addWikiText( $this->getCopywarn() );
3242 $wgOut->addHTML( $this->editFormTextAfterWarn );
3244 $wgOut->addHTML( "<div class='editButtons'>\n" );
3245 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3247 $cancel = $this->getCancelLink();
3248 if ( $cancel !== '' ) {
3249 $cancel .= Html::element( 'span',
3250 array( 'class' => 'mw-editButtons-pipe-separator' ),
3251 wfMessage( 'pipe-separator' )->text() );
3254 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3255 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3256 $attrs = array(
3257 'target' => 'helpwindow',
3258 'href' => $edithelpurl,
3260 $edithelp = Html::linkButton( wfMessage( 'edithelp' )->text(),
3261 $attrs, array( 'mw-ui-quiet' ) ) .
3262 wfMessage( 'word-separator' )->escaped() .
3263 wfMessage( 'newwindow' )->parse();
3265 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3266 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3267 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3269 Hooks::run( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3271 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3275 * Show an edit conflict. textbox1 is already shown in showEditForm().
3276 * If you want to use another entry point to this function, be careful.
3278 protected function showConflict() {
3279 global $wgOut;
3281 if ( Hooks::run( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3282 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3284 $content1 = $this->toEditContent( $this->textbox1 );
3285 $content2 = $this->toEditContent( $this->textbox2 );
3287 $handler = ContentHandler::getForModelID( $this->contentModel );
3288 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3289 $de->setContent( $content2, $content1 );
3290 $de->showDiff(
3291 wfMessage( 'yourtext' )->parse(),
3292 wfMessage( 'storedversion' )->text()
3295 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3296 $this->showTextbox2();
3301 * @return string
3303 public function getCancelLink() {
3304 $cancelParams = array();
3305 if ( !$this->isConflict && $this->oldid > 0 ) {
3306 $cancelParams['oldid'] = $this->oldid;
3308 $attrs = array( 'id' => 'mw-editform-cancel' );
3310 return Linker::linkKnown(
3311 $this->getContextTitle(),
3312 wfMessage( 'cancel' )->parse(),
3313 Html::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3314 $cancelParams
3319 * Returns the URL to use in the form's action attribute.
3320 * This is used by EditPage subclasses when simply customizing the action
3321 * variable in the constructor is not enough. This can be used when the
3322 * EditPage lives inside of a Special page rather than a custom page action.
3324 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3325 * @return string
3327 protected function getActionURL( Title $title ) {
3328 return $title->getLocalURL( array( 'action' => $this->action ) );
3332 * Check if a page was deleted while the user was editing it, before submit.
3333 * Note that we rely on the logging table, which hasn't been always there,
3334 * but that doesn't matter, because this only applies to brand new
3335 * deletes.
3336 * @return bool
3338 protected function wasDeletedSinceLastEdit() {
3339 if ( $this->deletedSinceEdit !== null ) {
3340 return $this->deletedSinceEdit;
3343 $this->deletedSinceEdit = false;
3345 if ( $this->mTitle->isDeletedQuick() ) {
3346 $this->lastDelete = $this->getLastDelete();
3347 if ( $this->lastDelete ) {
3348 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3349 if ( $deleteTime > $this->starttime ) {
3350 $this->deletedSinceEdit = true;
3355 return $this->deletedSinceEdit;
3359 * @return bool|stdClass
3361 protected function getLastDelete() {
3362 $dbr = wfGetDB( DB_SLAVE );
3363 $data = $dbr->selectRow(
3364 array( 'logging', 'user' ),
3365 array(
3366 'log_type',
3367 'log_action',
3368 'log_timestamp',
3369 'log_user',
3370 'log_namespace',
3371 'log_title',
3372 'log_comment',
3373 'log_params',
3374 'log_deleted',
3375 'user_name'
3376 ), array(
3377 'log_namespace' => $this->mTitle->getNamespace(),
3378 'log_title' => $this->mTitle->getDBkey(),
3379 'log_type' => 'delete',
3380 'log_action' => 'delete',
3381 'user_id=log_user'
3383 __METHOD__,
3384 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3386 // Quick paranoid permission checks...
3387 if ( is_object( $data ) ) {
3388 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3389 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
3392 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3393 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
3397 return $data;
3401 * Get the rendered text for previewing.
3402 * @throws MWException
3403 * @return string
3405 function getPreviewText() {
3406 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3407 global $wgAllowUserCss, $wgAllowUserJs;
3409 if ( $wgRawHtml && !$this->mTokenOk ) {
3410 // Could be an offsite preview attempt. This is very unsafe if
3411 // HTML is enabled, as it could be an attack.
3412 $parsedNote = '';
3413 if ( $this->textbox1 !== '' ) {
3414 // Do not put big scary notice, if previewing the empty
3415 // string, which happens when you initially edit
3416 // a category page, due to automatic preview-on-open.
3417 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3418 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3420 return $parsedNote;
3423 $note = '';
3425 try {
3426 $content = $this->toEditContent( $this->textbox1 );
3428 $previewHTML = '';
3429 if ( !Hooks::run(
3430 'AlternateEditPreview',
3431 array( $this, &$content, &$previewHTML, &$this->mParserOutput ) )
3433 return $previewHTML;
3436 # provide a anchor link to the editform
3437 $continueEditing = '<span class="mw-continue-editing">' .
3438 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3439 wfMessage( 'continue-editing' )->text() . ']]</span>';
3440 if ( $this->mTriedSave && !$this->mTokenOk ) {
3441 if ( $this->mTokenOkExceptSuffix ) {
3442 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3443 } else {
3444 $note = wfMessage( 'session_fail_preview' )->plain();
3446 } elseif ( $this->incompleteForm ) {
3447 $note = wfMessage( 'edit_form_incomplete' )->plain();
3448 } else {
3449 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3452 $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
3453 $parserOptions->setIsPreview( true );
3454 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3456 # don't parse non-wikitext pages, show message about preview
3457 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3458 if ( $this->mTitle->isCssJsSubpage() ) {
3459 $level = 'user';
3460 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3461 $level = 'site';
3462 } else {
3463 $level = false;
3466 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3467 $format = 'css';
3468 if ( $level === 'user' && !$wgAllowUserCss ) {
3469 $format = false;
3471 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3472 $format = 'js';
3473 if ( $level === 'user' && !$wgAllowUserJs ) {
3474 $format = false;
3476 } else {
3477 $format = false;
3480 # Used messages to make sure grep find them:
3481 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3482 if ( $level && $format ) {
3483 $note = "<div id='mw-{$level}{$format}preview'>" .
3484 wfMessage( "{$level}{$format}preview" )->text() .
3485 ' ' . $continueEditing . "</div>";
3489 # If we're adding a comment, we need to show the
3490 # summary as the headline
3491 if ( $this->section === "new" && $this->summary !== "" ) {
3492 $content = $content->addSectionHeader( $this->summary );
3495 $hook_args = array( $this, &$content );
3496 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3497 Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3499 $parserOptions->enableLimitReport();
3501 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3502 # But it's now deprecated, so never mind
3504 $pstContent = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3505 $scopedCallback = $parserOptions->setupFakeRevision(
3506 $this->mTitle, $pstContent, $wgUser );
3507 $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
3509 # Try to stash the edit for the final submission step
3510 # @todo: different date format preferences cause cache misses
3511 ApiStashEdit::stashEditFromPreview(
3512 $this->getArticle(), $content, $pstContent,
3513 $parserOutput, $parserOptions, $parserOptions, wfTimestampNow()
3516 $parserOutput->setEditSectionTokens( false ); // no section edit links
3517 $previewHTML = $parserOutput->getText();
3518 $this->mParserOutput = $parserOutput;
3519 $wgOut->addParserOutputMetadata( $parserOutput );
3521 if ( count( $parserOutput->getWarnings() ) ) {
3522 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3524 } catch ( MWContentSerializationException $ex ) {
3525 $m = wfMessage(
3526 'content-failed-to-parse',
3527 $this->contentModel,
3528 $this->contentFormat,
3529 $ex->getMessage()
3531 $note .= "\n\n" . $m->parse();
3532 $previewHTML = '';
3535 if ( $this->isConflict ) {
3536 $conflict = '<h2 id="mw-previewconflict">'
3537 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3538 } else {
3539 $conflict = '<hr />';
3542 $previewhead = "<div class='previewnote'>\n" .
3543 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3544 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3546 $pageViewLang = $this->mTitle->getPageViewLanguage();
3547 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3548 'class' => 'mw-content-' . $pageViewLang->getDir() );
3549 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3551 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3555 * @return array
3557 function getTemplates() {
3558 if ( $this->preview || $this->section != '' ) {
3559 $templates = array();
3560 if ( !isset( $this->mParserOutput ) ) {
3561 return $templates;
3563 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3564 foreach ( array_keys( $template ) as $dbk ) {
3565 $templates[] = Title::makeTitle( $ns, $dbk );
3568 return $templates;
3569 } else {
3570 return $this->mTitle->getTemplateLinksFrom();
3575 * Shows a bulletin board style toolbar for common editing functions.
3576 * It can be disabled in the user preferences.
3578 * @return string
3580 static function getEditToolbar() {
3581 global $wgContLang, $wgOut;
3582 global $wgEnableUploads, $wgForeignFileRepos;
3584 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3587 * $toolarray is an array of arrays each of which includes the
3588 * opening tag, the closing tag, optionally a sample text that is
3589 * inserted between the two when no selection is highlighted
3590 * and. The tip text is shown when the user moves the mouse
3591 * over the button.
3593 * Images are defined in ResourceLoaderEditToolbarModule.
3595 $toolarray = array(
3596 array(
3597 'id' => 'mw-editbutton-bold',
3598 'open' => '\'\'\'',
3599 'close' => '\'\'\'',
3600 'sample' => wfMessage( 'bold_sample' )->text(),
3601 'tip' => wfMessage( 'bold_tip' )->text(),
3603 array(
3604 'id' => 'mw-editbutton-italic',
3605 'open' => '\'\'',
3606 'close' => '\'\'',
3607 'sample' => wfMessage( 'italic_sample' )->text(),
3608 'tip' => wfMessage( 'italic_tip' )->text(),
3610 array(
3611 'id' => 'mw-editbutton-link',
3612 'open' => '[[',
3613 'close' => ']]',
3614 'sample' => wfMessage( 'link_sample' )->text(),
3615 'tip' => wfMessage( 'link_tip' )->text(),
3617 array(
3618 'id' => 'mw-editbutton-extlink',
3619 'open' => '[',
3620 'close' => ']',
3621 'sample' => wfMessage( 'extlink_sample' )->text(),
3622 'tip' => wfMessage( 'extlink_tip' )->text(),
3624 array(
3625 'id' => 'mw-editbutton-headline',
3626 'open' => "\n== ",
3627 'close' => " ==\n",
3628 'sample' => wfMessage( 'headline_sample' )->text(),
3629 'tip' => wfMessage( 'headline_tip' )->text(),
3631 $imagesAvailable ? array(
3632 'id' => 'mw-editbutton-image',
3633 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3634 'close' => ']]',
3635 'sample' => wfMessage( 'image_sample' )->text(),
3636 'tip' => wfMessage( 'image_tip' )->text(),
3637 ) : false,
3638 $imagesAvailable ? array(
3639 'id' => 'mw-editbutton-media',
3640 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3641 'close' => ']]',
3642 'sample' => wfMessage( 'media_sample' )->text(),
3643 'tip' => wfMessage( 'media_tip' )->text(),
3644 ) : false,
3645 array(
3646 'id' => 'mw-editbutton-nowiki',
3647 'open' => "<nowiki>",
3648 'close' => "</nowiki>",
3649 'sample' => wfMessage( 'nowiki_sample' )->text(),
3650 'tip' => wfMessage( 'nowiki_tip' )->text(),
3652 array(
3653 'id' => 'mw-editbutton-signature',
3654 'open' => '--~~~~',
3655 'close' => '',
3656 'sample' => '',
3657 'tip' => wfMessage( 'sig_tip' )->text(),
3659 array(
3660 'id' => 'mw-editbutton-hr',
3661 'open' => "\n----\n",
3662 'close' => '',
3663 'sample' => '',
3664 'tip' => wfMessage( 'hr_tip' )->text(),
3668 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3669 foreach ( $toolarray as $tool ) {
3670 if ( !$tool ) {
3671 continue;
3674 $params = array(
3675 // Images are defined in ResourceLoaderEditToolbarModule
3676 false,
3677 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3678 // Older browsers show a "speedtip" type message only for ALT.
3679 // Ideally these should be different, realistically they
3680 // probably don't need to be.
3681 $tool['tip'],
3682 $tool['open'],
3683 $tool['close'],
3684 $tool['sample'],
3685 $tool['id'],
3688 $script .= Xml::encodeJsCall(
3689 'mw.toolbar.addButton',
3690 $params,
3691 ResourceLoader::inDebugMode()
3695 $script .= '});';
3696 $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
3698 $toolbar = '<div id="toolbar"></div>';
3700 Hooks::run( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3702 return $toolbar;
3706 * Returns an array of html code of the following checkboxes:
3707 * minor and watch
3709 * @param int $tabindex Current tabindex
3710 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3711 * status of the checkbox
3713 * @return array
3715 public function getCheckboxes( &$tabindex, $checked ) {
3716 global $wgUser, $wgUseMediaWikiUIEverywhere;
3718 $checkboxes = array();
3720 // don't show the minor edit checkbox if it's a new page or section
3721 if ( !$this->isNew ) {
3722 $checkboxes['minor'] = '';
3723 $minorLabel = wfMessage( 'minoredit' )->parse();
3724 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3725 $attribs = array(
3726 'tabindex' => ++$tabindex,
3727 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3728 'id' => 'wpMinoredit',
3730 $minorEditHtml =
3731 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3732 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3733 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3734 ">{$minorLabel}</label>";
3736 if ( $wgUseMediaWikiUIEverywhere ) {
3737 $checkboxes['minor'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3738 $minorEditHtml .
3739 Html::closeElement( 'div' );
3740 } else {
3741 $checkboxes['minor'] = $minorEditHtml;
3746 $watchLabel = wfMessage( 'watchthis' )->parse();
3747 $checkboxes['watch'] = '';
3748 if ( $wgUser->isLoggedIn() ) {
3749 $attribs = array(
3750 'tabindex' => ++$tabindex,
3751 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3752 'id' => 'wpWatchthis',
3754 $watchThisHtml =
3755 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3756 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3757 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3758 ">{$watchLabel}</label>";
3759 if ( $wgUseMediaWikiUIEverywhere ) {
3760 $checkboxes['watch'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3761 $watchThisHtml .
3762 Html::closeElement( 'div' );
3763 } else {
3764 $checkboxes['watch'] = $watchThisHtml;
3767 Hooks::run( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3768 return $checkboxes;
3772 * Returns an array of html code of the following buttons:
3773 * save, diff, preview and live
3775 * @param int $tabindex Current tabindex
3777 * @return array
3779 public function getEditButtons( &$tabindex ) {
3780 $buttons = array();
3782 $attribs = array(
3783 'id' => 'wpSave',
3784 'name' => 'wpSave',
3785 'tabindex' => ++$tabindex,
3786 ) + Linker::tooltipAndAccesskeyAttribs( 'save' );
3787 $buttons['save'] = Html::submitButton( wfMessage( 'savearticle' )->text(),
3788 $attribs, array( 'mw-ui-constructive' ) );
3790 ++$tabindex; // use the same for preview and live preview
3791 $attribs = array(
3792 'id' => 'wpPreview',
3793 'name' => 'wpPreview',
3794 'tabindex' => $tabindex,
3795 ) + Linker::tooltipAndAccesskeyAttribs( 'preview' );
3796 $buttons['preview'] = Html::submitButton( wfMessage( 'showpreview' )->text(),
3797 $attribs );
3798 $buttons['live'] = '';
3800 $attribs = array(
3801 'id' => 'wpDiff',
3802 'name' => 'wpDiff',
3803 'tabindex' => ++$tabindex,
3804 ) + Linker::tooltipAndAccesskeyAttribs( 'diff' );
3805 $buttons['diff'] = Html::submitButton( wfMessage( 'showdiff' )->text(),
3806 $attribs );
3808 Hooks::run( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3809 return $buttons;
3813 * Output preview text only. This can be sucked into the edit page
3814 * via JavaScript, and saves the server time rendering the skin as
3815 * well as theoretically being more robust on the client (doesn't
3816 * disturb the edit box's undo history, won't eat your text on
3817 * failure, etc).
3819 * @todo This doesn't include category or interlanguage links.
3820 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3821 * or something...</s>" that might also require more skin
3822 * initialization, so check whether that's a problem.
3824 function livePreview() {
3825 global $wgOut;
3826 $wgOut->disable();
3827 header( 'Content-type: text/xml; charset=utf-8' );
3828 header( 'Cache-control: no-cache' );
3830 $previewText = $this->getPreviewText();
3831 #$categories = $skin->getCategoryLinks();
3833 $s =
3834 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3835 Xml::tags( 'livepreview', null,
3836 Xml::element( 'preview', null, $previewText )
3837 #. Xml::element( 'category', null, $categories )
3839 echo $s;
3843 * Creates a basic error page which informs the user that
3844 * they have attempted to edit a nonexistent section.
3846 function noSuchSectionPage() {
3847 global $wgOut;
3849 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3851 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
3852 Hooks::run( 'EditPageNoSuchSection', array( &$this, &$res ) );
3853 $wgOut->addHTML( $res );
3855 $wgOut->returnToMain( false, $this->mTitle );
3859 * Show "your edit contains spam" page with your diff and text
3861 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3863 public function spamPageWithContent( $match = false ) {
3864 global $wgOut, $wgLang;
3865 $this->textbox2 = $this->textbox1;
3867 if ( is_array( $match ) ) {
3868 $match = $wgLang->listToText( $match );
3870 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3872 $wgOut->addHTML( '<div id="spamprotected">' );
3873 $wgOut->addWikiMsg( 'spamprotectiontext' );
3874 if ( $match ) {
3875 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3877 $wgOut->addHTML( '</div>' );
3879 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3880 $this->showDiff();
3882 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3883 $this->showTextbox2();
3885 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3889 * Check if the browser is on a blacklist of user-agents known to
3890 * mangle UTF-8 data on form submission. Returns true if Unicode
3891 * should make it through, false if it's known to be a problem.
3892 * @return bool
3894 private function checkUnicodeCompliantBrowser() {
3895 global $wgBrowserBlackList, $wgRequest;
3897 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3898 if ( $currentbrowser === false ) {
3899 // No User-Agent header sent? Trust it by default...
3900 return true;
3903 foreach ( $wgBrowserBlackList as $browser ) {
3904 if ( preg_match( $browser, $currentbrowser ) ) {
3905 return false;
3908 return true;
3912 * Filter an input field through a Unicode de-armoring process if it
3913 * came from an old browser with known broken Unicode editing issues.
3915 * @param WebRequest $request
3916 * @param string $field
3917 * @return string
3919 protected function safeUnicodeInput( $request, $field ) {
3920 $text = rtrim( $request->getText( $field ) );
3921 return $request->getBool( 'safemode' )
3922 ? $this->unmakeSafe( $text )
3923 : $text;
3927 * Filter an output field through a Unicode armoring process if it is
3928 * going to an old browser with known broken Unicode editing issues.
3930 * @param string $text
3931 * @return string
3933 protected function safeUnicodeOutput( $text ) {
3934 global $wgContLang;
3935 $codedText = $wgContLang->recodeForEdit( $text );
3936 return $this->checkUnicodeCompliantBrowser()
3937 ? $codedText
3938 : $this->makeSafe( $codedText );
3942 * A number of web browsers are known to corrupt non-ASCII characters
3943 * in a UTF-8 text editing environment. To protect against this,
3944 * detected browsers will be served an armored version of the text,
3945 * with non-ASCII chars converted to numeric HTML character references.
3947 * Preexisting such character references will have a 0 added to them
3948 * to ensure that round-trips do not alter the original data.
3950 * @param string $invalue
3951 * @return string
3953 private function makeSafe( $invalue ) {
3954 // Armor existing references for reversibility.
3955 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
3957 $bytesleft = 0;
3958 $result = "";
3959 $working = 0;
3960 $valueLength = strlen( $invalue );
3961 for ( $i = 0; $i < $valueLength; $i++ ) {
3962 $bytevalue = ord( $invalue[$i] );
3963 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3964 $result .= chr( $bytevalue );
3965 $bytesleft = 0;
3966 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3967 $working = $working << 6;
3968 $working += ( $bytevalue & 0x3F );
3969 $bytesleft--;
3970 if ( $bytesleft <= 0 ) {
3971 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3973 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3974 $working = $bytevalue & 0x1F;
3975 $bytesleft = 1;
3976 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3977 $working = $bytevalue & 0x0F;
3978 $bytesleft = 2;
3979 } else { // 1111 0xxx
3980 $working = $bytevalue & 0x07;
3981 $bytesleft = 3;
3984 return $result;
3988 * Reverse the previously applied transliteration of non-ASCII characters
3989 * back to UTF-8. Used to protect data from corruption by broken web browsers
3990 * as listed in $wgBrowserBlackList.
3992 * @param string $invalue
3993 * @return string
3995 private function unmakeSafe( $invalue ) {
3996 $result = "";
3997 $valueLength = strlen( $invalue );
3998 for ( $i = 0; $i < $valueLength; $i++ ) {
3999 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
4000 $i += 3;
4001 $hexstring = "";
4002 do {
4003 $hexstring .= $invalue[$i];
4004 $i++;
4005 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4007 // Do some sanity checks. These aren't needed for reversibility,
4008 // but should help keep the breakage down if the editor
4009 // breaks one of the entities whilst editing.
4010 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4011 $codepoint = hexdec( $hexstring );
4012 $result .= codepointToUtf8( $codepoint );
4013 } else {
4014 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4016 } else {
4017 $result .= substr( $invalue, $i, 1 );
4020 // reverse the transform that we made for reversibility reasons.
4021 return strtr( $result, array( "&#x0" => "&#x" ) );