Implement extension registration from an extension.json file
[mediawiki.git] / includes / EditPage.php
blob6497c40619e852c486a0df60963318587be32fab
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();
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 wfProfileIn( __METHOD__ . "-business-end" );
520 $this->isConflict = false;
521 // css / js subpages of user pages get a special treatment
522 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
523 $this->isCssSubpage = $this->mTitle->isCssSubpage();
524 $this->isJsSubpage = $this->mTitle->isJsSubpage();
525 // @todo FIXME: Silly assignment.
526 $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
528 # Show applicable editing introductions
529 if ( $this->formtype == 'initial' || $this->firsttime ) {
530 $this->showIntro();
533 # Attempt submission here. This will check for edit conflicts,
534 # and redundantly check for locked database, blocked IPs, etc.
535 # that edit() already checked just in case someone tries to sneak
536 # in the back door with a hand-edited submission URL.
538 if ( 'save' == $this->formtype ) {
539 if ( !$this->attemptSave() ) {
540 wfProfileOut( __METHOD__ . "-business-end" );
541 return;
545 # First time through: get contents, set time for conflict
546 # checking, etc.
547 if ( 'initial' == $this->formtype || $this->firsttime ) {
548 if ( $this->initialiseForm() === false ) {
549 $this->noSuchSectionPage();
550 wfProfileOut( __METHOD__ . "-business-end" );
551 return;
554 if ( !$this->mTitle->getArticleID() ) {
555 Hooks::run( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
556 } else {
557 Hooks::run( 'EditFormInitialText', array( $this ) );
562 $this->showEditForm();
563 wfProfileOut( __METHOD__ . "-business-end" );
567 * @return array
569 protected function getEditPermissionErrors() {
570 global $wgUser;
571 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
572 # Can this title be created?
573 if ( !$this->mTitle->exists() ) {
574 $permErrors = array_merge( $permErrors,
575 wfArrayDiff2( $this->mTitle->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
577 # Ignore some permissions errors when a user is just previewing/viewing diffs
578 $remove = array();
579 foreach ( $permErrors as $error ) {
580 if ( ( $this->preview || $this->diff )
581 && ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' )
583 $remove[] = $error;
586 $permErrors = wfArrayDiff2( $permErrors, $remove );
587 return $permErrors;
591 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
592 * but with the following differences:
593 * - If redlink=1, the user will be redirected to the page
594 * - If there is content to display or the error occurs while either saving,
595 * previewing or showing the difference, it will be a
596 * "View source for ..." page displaying the source code after the error message.
598 * @since 1.19
599 * @param array $permErrors Array of permissions errors, as returned by
600 * Title::getUserPermissionsErrors().
601 * @throws PermissionsError
603 protected function displayPermissionsError( array $permErrors ) {
604 global $wgRequest, $wgOut;
606 if ( $wgRequest->getBool( 'redlink' ) ) {
607 // The edit page was reached via a red link.
608 // Redirect to the article page and let them click the edit tab if
609 // they really want a permission error.
610 $wgOut->redirect( $this->mTitle->getFullURL() );
611 return;
614 $content = $this->getContentObject();
616 # Use the normal message if there's nothing to display
617 if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
618 $action = $this->mTitle->exists() ? 'edit' :
619 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
620 throw new PermissionsError( $action, $permErrors );
623 Hooks::run( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
625 $wgOut->setRobotPolicy( 'noindex,nofollow' );
626 $wgOut->setPageTitle( wfMessage(
627 'viewsource-title',
628 $this->getContextTitle()->getPrefixedText()
629 ) );
630 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
631 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
632 $wgOut->addHTML( "<hr />\n" );
634 # If the user made changes, preserve them when showing the markup
635 # (This happens when a user is blocked during edit, for instance)
636 if ( !$this->firsttime ) {
637 $text = $this->textbox1;
638 $wgOut->addWikiMsg( 'viewyourtext' );
639 } else {
640 $text = $this->toEditText( $content );
641 $wgOut->addWikiMsg( 'viewsourcetext' );
644 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
646 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
647 Linker::formatTemplates( $this->getTemplates() ) ) );
649 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
651 if ( $this->mTitle->exists() ) {
652 $wgOut->returnToMain( null, $this->mTitle );
657 * Should we show a preview when the edit form is first shown?
659 * @return bool
661 protected function previewOnOpen() {
662 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
663 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
664 // Explicit override from request
665 return true;
666 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
667 // Explicit override from request
668 return false;
669 } elseif ( $this->section == 'new' ) {
670 // Nothing *to* preview for new sections
671 return false;
672 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() )
673 && $wgUser->getOption( 'previewonfirst' )
675 // Standard preference behavior
676 return true;
677 } elseif ( !$this->mTitle->exists()
678 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
679 && $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]
681 // Categories are special
682 return true;
683 } else {
684 return false;
689 * Checks whether the user entered a skin name in uppercase,
690 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
692 * @return bool
694 protected function isWrongCaseCssJsPage() {
695 if ( $this->mTitle->isCssJsSubpage() ) {
696 $name = $this->mTitle->getSkinFromCssJsSubpage();
697 $skins = array_merge(
698 array_keys( Skin::getSkinNames() ),
699 array( 'common' )
701 return !in_array( $name, $skins )
702 && in_array( strtolower( $name ), $skins );
703 } else {
704 return false;
709 * Returns whether section editing is supported for the current page.
710 * Subclasses may override this to replace the default behavior, which is
711 * to check ContentHandler::supportsSections.
713 * @return bool True if this edit page supports sections, false otherwise.
715 protected function isSectionEditSupported() {
716 $contentHandler = ContentHandler::getForTitle( $this->mTitle );
717 return $contentHandler->supportsSections();
721 * This function collects the form data and uses it to populate various member variables.
722 * @param WebRequest $request
723 * @throws ErrorPageError
725 function importFormData( &$request ) {
726 global $wgContLang, $wgUser;
729 # Section edit can come from either the form or a link
730 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
732 if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
733 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
736 $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
738 if ( $request->wasPosted() ) {
739 # These fields need to be checked for encoding.
740 # Also remove trailing whitespace, but don't remove _initial_
741 # whitespace from the text boxes. This may be significant formatting.
742 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
743 if ( !$request->getCheck( 'wpTextbox2' ) ) {
744 // Skip this if wpTextbox2 has input, it indicates that we came
745 // from a conflict page with raw page text, not a custom form
746 // modified by subclasses
747 wfProfileIn( get_class( $this ) . "::importContentFormData" );
748 $textbox1 = $this->importContentFormData( $request );
749 if ( $textbox1 !== null ) {
750 $this->textbox1 = $textbox1;
753 wfProfileOut( get_class( $this ) . "::importContentFormData" );
756 # Truncate for whole multibyte characters
757 $this->summary = $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
759 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
760 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
761 # section titles.
762 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
764 # Treat sectiontitle the same way as summary.
765 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
766 # currently doing double duty as both edit summary and section title. Right now this
767 # is just to allow API edits to work around this limitation, but this should be
768 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
769 $this->sectiontitle = $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
770 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
772 $this->edittime = $request->getVal( 'wpEdittime' );
773 $this->starttime = $request->getVal( 'wpStarttime' );
775 $undidRev = $request->getInt( 'wpUndidRevision' );
776 if ( $undidRev ) {
777 $this->undidRev = $undidRev;
780 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
782 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
783 // wpTextbox1 field is missing, possibly due to being "too big"
784 // according to some filter rules such as Suhosin's setting for
785 // suhosin.request.max_value_length (d'oh)
786 $this->incompleteForm = true;
787 } else {
788 // If we receive the last parameter of the request, we can fairly
789 // claim the POST request has not been truncated.
791 // TODO: softened the check for cutover. Once we determine
792 // that it is safe, we should complete the transition by
793 // removing the "edittime" clause.
794 $this->incompleteForm = ( !$request->getVal( 'wpUltimateParam' )
795 && is_null( $this->edittime ) );
797 if ( $this->incompleteForm ) {
798 # If the form is incomplete, force to preview.
799 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
800 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
801 $this->preview = true;
802 } else {
803 /* Fallback for live preview */
804 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
805 $this->diff = $request->getCheck( 'wpDiff' );
807 // Remember whether a save was requested, so we can indicate
808 // if we forced preview due to session failure.
809 $this->mTriedSave = !$this->preview;
811 if ( $this->tokenOk( $request ) ) {
812 # Some browsers will not report any submit button
813 # if the user hits enter in the comment box.
814 # The unmarked state will be assumed to be a save,
815 # if the form seems otherwise complete.
816 wfDebug( __METHOD__ . ": Passed token check.\n" );
817 } elseif ( $this->diff ) {
818 # Failed token check, but only requested "Show Changes".
819 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
820 } else {
821 # Page might be a hack attempt posted from
822 # an external site. Preview instead of saving.
823 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
824 $this->preview = true;
827 $this->save = !$this->preview && !$this->diff;
828 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
829 $this->edittime = null;
832 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
833 $this->starttime = null;
836 $this->recreate = $request->getCheck( 'wpRecreate' );
838 $this->minoredit = $request->getCheck( 'wpMinoredit' );
839 $this->watchthis = $request->getCheck( 'wpWatchthis' );
841 # Don't force edit summaries when a user is editing their own user or talk page
842 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
843 && $this->mTitle->getText() == $wgUser->getName()
845 $this->allowBlankSummary = true;
846 } else {
847 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
848 || !$wgUser->getOption( 'forceeditsummary' );
851 $this->autoSumm = $request->getText( 'wpAutoSummary' );
853 $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
854 $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
855 } else {
856 # Not a posted form? Start with nothing.
857 wfDebug( __METHOD__ . ": Not a posted form.\n" );
858 $this->textbox1 = '';
859 $this->summary = '';
860 $this->sectiontitle = '';
861 $this->edittime = '';
862 $this->starttime = wfTimestampNow();
863 $this->edit = false;
864 $this->preview = false;
865 $this->save = false;
866 $this->diff = false;
867 $this->minoredit = false;
868 // Watch may be overridden by request parameters
869 $this->watchthis = $request->getBool( 'watchthis', false );
870 $this->recreate = false;
872 // When creating a new section, we can preload a section title by passing it as the
873 // preloadtitle parameter in the URL (Bug 13100)
874 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
875 $this->sectiontitle = $request->getVal( 'preloadtitle' );
876 // Once wpSummary isn't being use for setting section titles, we should delete this.
877 $this->summary = $request->getVal( 'preloadtitle' );
878 } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
879 $this->summary = $request->getText( 'summary' );
880 if ( $this->summary !== '' ) {
881 $this->hasPresetSummary = true;
885 if ( $request->getVal( 'minor' ) ) {
886 $this->minoredit = true;
890 $this->oldid = $request->getInt( 'oldid' );
891 $this->parentRevId = $request->getInt( 'parentRevId' );
893 $this->bot = $request->getBool( 'bot', true );
894 $this->nosummary = $request->getBool( 'nosummary' );
896 // May be overridden by revision.
897 $this->contentModel = $request->getText( 'model', $this->contentModel );
898 // May be overridden by revision.
899 $this->contentFormat = $request->getText( 'format', $this->contentFormat );
901 if ( !ContentHandler::getForModelID( $this->contentModel )
902 ->isSupportedFormat( $this->contentFormat )
904 throw new ErrorPageError(
905 'editpage-notsupportedcontentformat-title',
906 'editpage-notsupportedcontentformat-text',
907 array( $this->contentFormat, ContentHandler::getLocalizedName( $this->contentModel ) )
912 * @todo Check if the desired model is allowed in this namespace, and if
913 * a transition from the page's current model to the new model is
914 * allowed.
917 $this->live = $request->getCheck( 'live' );
918 $this->editintro = $request->getText( 'editintro',
919 // Custom edit intro for new sections
920 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
922 // Allow extensions to modify form data
923 Hooks::run( 'EditPage::importFormData', array( $this, $request ) );
928 * Subpage overridable method for extracting the page content data from the
929 * posted form to be placed in $this->textbox1, if using customized input
930 * this method should be overridden and return the page text that will be used
931 * for saving, preview parsing and so on...
933 * @param WebRequest $request
935 protected function importContentFormData( &$request ) {
936 return; // Don't do anything, EditPage already extracted wpTextbox1
940 * Initialise form fields in the object
941 * Called on the first invocation, e.g. when a user clicks an edit link
942 * @return bool If the requested section is valid
944 function initialiseForm() {
945 global $wgUser;
946 $this->edittime = $this->mArticle->getTimestamp();
948 $content = $this->getContentObject( false ); #TODO: track content object?!
949 if ( $content === false ) {
950 return false;
952 $this->textbox1 = $this->toEditText( $content );
954 // activate checkboxes if user wants them to be always active
955 # Sort out the "watch" checkbox
956 if ( $wgUser->getOption( 'watchdefault' ) ) {
957 # Watch all edits
958 $this->watchthis = true;
959 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
960 # Watch creations
961 $this->watchthis = true;
962 } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
963 # Already watched
964 $this->watchthis = true;
966 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
967 $this->minoredit = true;
969 if ( $this->textbox1 === false ) {
970 return false;
972 return true;
976 * @param Content|null $def_content The default value to return
978 * @return Content|null Content on success, $def_content for invalid sections
980 * @since 1.21
982 protected function getContentObject( $def_content = null ) {
983 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 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1290 * @return bool False if output is done, true if the rest of the form should be displayed
1292 public function attemptSave() {
1293 global $wgUser;
1295 $resultDetails = false;
1296 # Allow bots to exempt some edits from bot flagging
1297 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1298 $status = $this->internalAttemptSave( $resultDetails, $bot );
1300 return $this->handleStatus( $status, $resultDetails );
1304 * Handle status, such as after attempt save
1306 * @param Status $status
1307 * @param array|bool $resultDetails
1309 * @throws ErrorPageError
1310 * @return bool False, if output is done, true if rest of the form should be displayed
1312 private function handleStatus( Status $status, $resultDetails ) {
1313 global $wgUser, $wgOut;
1316 * @todo FIXME: once the interface for internalAttemptSave() is made
1317 * nicer, this should use the message in $status
1319 if ( $status->value == self::AS_SUCCESS_UPDATE
1320 || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1322 $this->didSave = true;
1323 if ( !$resultDetails['nullEdit'] ) {
1324 $this->setPostEditCookie( $status->value );
1328 switch ( $status->value ) {
1329 case self::AS_HOOK_ERROR_EXPECTED:
1330 case self::AS_CONTENT_TOO_BIG:
1331 case self::AS_ARTICLE_WAS_DELETED:
1332 case self::AS_CONFLICT_DETECTED:
1333 case self::AS_SUMMARY_NEEDED:
1334 case self::AS_TEXTBOX_EMPTY:
1335 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1336 case self::AS_END:
1337 case self::AS_BLANK_ARTICLE:
1338 case self::AS_SELF_REDIRECT:
1339 return true;
1341 case self::AS_HOOK_ERROR:
1342 return false;
1344 case self::AS_PARSE_ERROR:
1345 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1346 return true;
1348 case self::AS_SUCCESS_NEW_ARTICLE:
1349 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1350 $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1351 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1352 return false;
1354 case self::AS_SUCCESS_UPDATE:
1355 $extraQuery = '';
1356 $sectionanchor = $resultDetails['sectionanchor'];
1358 // Give extensions a chance to modify URL query on update
1359 Hooks::run(
1360 'ArticleUpdateBeforeRedirect',
1361 array( $this->mArticle, &$sectionanchor, &$extraQuery )
1364 if ( $resultDetails['redirect'] ) {
1365 if ( $extraQuery == '' ) {
1366 $extraQuery = 'redirect=no';
1367 } else {
1368 $extraQuery = 'redirect=no&' . $extraQuery;
1371 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1372 return false;
1374 case self::AS_SPAM_ERROR:
1375 $this->spamPageWithContent( $resultDetails['spam'] );
1376 return false;
1378 case self::AS_BLOCKED_PAGE_FOR_USER:
1379 throw new UserBlockedError( $wgUser->getBlock() );
1381 case self::AS_IMAGE_REDIRECT_ANON:
1382 case self::AS_IMAGE_REDIRECT_LOGGED:
1383 throw new PermissionsError( 'upload' );
1385 case self::AS_READ_ONLY_PAGE_ANON:
1386 case self::AS_READ_ONLY_PAGE_LOGGED:
1387 throw new PermissionsError( 'edit' );
1389 case self::AS_READ_ONLY_PAGE:
1390 throw new ReadOnlyError;
1392 case self::AS_RATE_LIMITED:
1393 throw new ThrottledError();
1395 case self::AS_NO_CREATE_PERMISSION:
1396 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1397 throw new PermissionsError( $permission );
1399 case self::AS_NO_CHANGE_CONTENT_MODEL:
1400 throw new PermissionsError( 'editcontentmodel' );
1402 default:
1403 // We don't recognize $status->value. The only way that can happen
1404 // is if an extension hook aborted from inside ArticleSave.
1405 // Render the status object into $this->hookError
1406 // FIXME this sucks, we should just use the Status object throughout
1407 $this->hookError = '<div class="error">' . $status->getWikitext() .
1408 '</div>';
1409 return true;
1414 * Run hooks that can filter edits just before they get saved.
1416 * @param Content $content The Content to filter.
1417 * @param Status $status For reporting the outcome to the caller
1418 * @param User $user The user performing the edit
1420 * @return bool
1422 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1423 // Run old style post-section-merge edit filter
1424 if ( !ContentHandler::runLegacyHooks( 'EditFilterMerged',
1425 array( $this, $content, &$this->hookError, $this->summary ) )
1427 # Error messages etc. could be handled within the hook...
1428 $status->fatal( 'hookaborted' );
1429 $status->value = self::AS_HOOK_ERROR;
1430 return false;
1431 } elseif ( $this->hookError != '' ) {
1432 # ...or the hook could be expecting us to produce an error
1433 $status->fatal( 'hookaborted' );
1434 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1435 return false;
1438 // Run new style post-section-merge edit filter
1439 if ( !Hooks::run( 'EditFilterMergedContent',
1440 array( $this->mArticle->getContext(), $content, $status, $this->summary,
1441 $user, $this->minoredit ) )
1443 # Error messages etc. could be handled within the hook...
1444 if ( $status->isGood() ) {
1445 $status->fatal( 'hookaborted' );
1446 // Not setting $this->hookError here is a hack to allow the hook
1447 // to cause a return to the edit page without $this->hookError
1448 // being set. This is used by ConfirmEdit to display a captcha
1449 // without any error message cruft.
1450 } else {
1451 $this->hookError = $status->getWikiText();
1453 // Use the existing $status->value if the hook set it
1454 if ( !$status->value ) {
1455 $status->value = self::AS_HOOK_ERROR;
1457 return false;
1458 } elseif ( !$status->isOK() ) {
1459 # ...or the hook could be expecting us to produce an error
1460 // FIXME this sucks, we should just use the Status object throughout
1461 $this->hookError = $status->getWikiText();
1462 $status->fatal( 'hookaborted' );
1463 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1464 return false;
1467 return true;
1471 * Return the summary to be used for a new section.
1473 * @param string $sectionanchor Set to the section anchor text
1474 * @return string
1476 private function newSectionSummary( &$sectionanchor = null ) {
1477 global $wgParser;
1479 if ( $this->sectiontitle !== '' ) {
1480 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1481 // If no edit summary was specified, create one automatically from the section
1482 // title and have it link to the new section. Otherwise, respect the summary as
1483 // passed.
1484 if ( $this->summary === '' ) {
1485 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1486 return wfMessage( 'newsectionsummary' )
1487 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1489 } elseif ( $this->summary !== '' ) {
1490 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1491 # This is a new section, so create a link to the new section
1492 # in the revision summary.
1493 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1494 return wfMessage( 'newsectionsummary' )
1495 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1497 return $this->summary;
1501 * Attempt submission (no UI)
1503 * @param array $result Array to add statuses to, currently with the
1504 * possible keys:
1505 * - spam (string): Spam string from content if any spam is detected by
1506 * matchSpamRegex.
1507 * - sectionanchor (string): Section anchor for a section save.
1508 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1509 * false otherwise.
1510 * - redirect (bool): Set if doEditContent is OK. True if resulting
1511 * revision is a redirect.
1512 * @param bool $bot True if edit is being made under the bot right.
1514 * @return Status Status object, possibly with a message, but always with
1515 * one of the AS_* constants in $status->value,
1517 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1518 * various error display idiosyncrasies. There are also lots of cases
1519 * where error metadata is set in the object and retrieved later instead
1520 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1521 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1522 * time.
1524 function internalAttemptSave( &$result, $bot = false ) {
1525 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1527 $status = Status::newGood();
1529 wfProfileIn( __METHOD__ . '-checks' );
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 wfProfileOut( __METHOD__ . '-checks' );
1536 return $status;
1539 $spam = $wgRequest->getText( 'wpAntispam' );
1540 if ( $spam !== '' ) {
1541 wfDebugLog(
1542 'SimpleAntiSpam',
1543 $wgUser->getName() .
1544 ' editing "' .
1545 $this->mTitle->getPrefixedText() .
1546 '" submitted bogus field "' .
1547 $spam .
1550 $status->fatal( 'spamprotectionmatch', false );
1551 $status->value = self::AS_SPAM_ERROR;
1552 wfProfileOut( __METHOD__ . '-checks' );
1553 return $status;
1556 try {
1557 # Construct Content object
1558 $textbox_content = $this->toEditContent( $this->textbox1 );
1559 } catch ( MWContentSerializationException $ex ) {
1560 $status->fatal(
1561 'content-failed-to-parse',
1562 $this->contentModel,
1563 $this->contentFormat,
1564 $ex->getMessage()
1566 $status->value = self::AS_PARSE_ERROR;
1567 wfProfileOut( __METHOD__ . '-checks' );
1568 return $status;
1571 # Check image redirect
1572 if ( $this->mTitle->getNamespace() == NS_FILE &&
1573 $textbox_content->isRedirect() &&
1574 !$wgUser->isAllowed( 'upload' )
1576 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1577 $status->setResult( false, $code );
1579 wfProfileOut( __METHOD__ . '-checks' );
1581 return $status;
1584 # Check for spam
1585 $match = self::matchSummarySpamRegex( $this->summary );
1586 if ( $match === false && $this->section == 'new' ) {
1587 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1588 # regular summaries, it is added to the actual wikitext.
1589 if ( $this->sectiontitle !== '' ) {
1590 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1591 $match = self::matchSpamRegex( $this->sectiontitle );
1592 } else {
1593 # This branch is taken when the "Add Topic" user interface is used, or the API
1594 # is used with the 'summary' parameter.
1595 $match = self::matchSpamRegex( $this->summary );
1598 if ( $match === false ) {
1599 $match = self::matchSpamRegex( $this->textbox1 );
1601 if ( $match !== false ) {
1602 $result['spam'] = $match;
1603 $ip = $wgRequest->getIP();
1604 $pdbk = $this->mTitle->getPrefixedDBkey();
1605 $match = str_replace( "\n", '', $match );
1606 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1607 $status->fatal( 'spamprotectionmatch', $match );
1608 $status->value = self::AS_SPAM_ERROR;
1609 wfProfileOut( __METHOD__ . '-checks' );
1610 return $status;
1612 if ( !Hooks::run(
1613 'EditFilter',
1614 array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) )
1616 # Error messages etc. could be handled within the hook...
1617 $status->fatal( 'hookaborted' );
1618 $status->value = self::AS_HOOK_ERROR;
1619 wfProfileOut( __METHOD__ . '-checks' );
1620 return $status;
1621 } elseif ( $this->hookError != '' ) {
1622 # ...or the hook could be expecting us to produce an error
1623 $status->fatal( 'hookaborted' );
1624 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1625 wfProfileOut( __METHOD__ . '-checks' );
1626 return $status;
1629 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1630 // Auto-block user's IP if the account was "hard" blocked
1631 $wgUser->spreadAnyEditBlock();
1632 # Check block state against master, thus 'false'.
1633 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1634 wfProfileOut( __METHOD__ . '-checks' );
1635 return $status;
1638 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1639 if ( $this->kblength > $wgMaxArticleSize ) {
1640 // Error will be displayed by showEditForm()
1641 $this->tooBig = true;
1642 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1643 wfProfileOut( __METHOD__ . '-checks' );
1644 return $status;
1647 if ( !$wgUser->isAllowed( 'edit' ) ) {
1648 if ( $wgUser->isAnon() ) {
1649 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1650 wfProfileOut( __METHOD__ . '-checks' );
1651 return $status;
1652 } else {
1653 $status->fatal( 'readonlytext' );
1654 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1655 wfProfileOut( __METHOD__ . '-checks' );
1656 return $status;
1660 if ( $this->contentModel !== $this->mTitle->getContentModel()
1661 && !$wgUser->isAllowed( 'editcontentmodel' )
1663 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1664 wfProfileOut( __METHOD__ . '-checks' );
1665 return $status;
1668 if ( wfReadOnly() ) {
1669 $status->fatal( 'readonlytext' );
1670 $status->value = self::AS_READ_ONLY_PAGE;
1671 wfProfileOut( __METHOD__ . '-checks' );
1672 return $status;
1674 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1675 $status->fatal( 'actionthrottledtext' );
1676 $status->value = self::AS_RATE_LIMITED;
1677 wfProfileOut( __METHOD__ . '-checks' );
1678 return $status;
1681 # If the article has been deleted while editing, don't save it without
1682 # confirmation
1683 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1684 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1685 wfProfileOut( __METHOD__ . '-checks' );
1686 return $status;
1689 wfProfileOut( __METHOD__ . '-checks' );
1691 # Load the page data from the master. If anything changes in the meantime,
1692 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1693 $this->mArticle->loadPageData( 'fromdbmaster' );
1694 $new = !$this->mArticle->exists();
1696 if ( $new ) {
1697 // Late check for create permission, just in case *PARANOIA*
1698 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1699 $status->fatal( 'nocreatetext' );
1700 $status->value = self::AS_NO_CREATE_PERMISSION;
1701 wfDebug( __METHOD__ . ": no create permission\n" );
1702 return $status;
1705 // Don't save a new page if it's blank or if it's a MediaWiki:
1706 // message with content equivalent to default (allow empty pages
1707 // in this case to disable messages, see bug 50124)
1708 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1709 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1710 $defaultText = $defaultMessageText;
1711 } else {
1712 $defaultText = '';
1715 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
1716 $this->blankArticle = true;
1717 $status->fatal( 'blankarticle' );
1718 $status->setResult( false, self::AS_BLANK_ARTICLE );
1719 return $status;
1722 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1723 return $status;
1726 $content = $textbox_content;
1728 $result['sectionanchor'] = '';
1729 if ( $this->section == 'new' ) {
1730 if ( $this->sectiontitle !== '' ) {
1731 // Insert the section title above the content.
1732 $content = $content->addSectionHeader( $this->sectiontitle );
1733 } elseif ( $this->summary !== '' ) {
1734 // Insert the section title above the content.
1735 $content = $content->addSectionHeader( $this->summary );
1737 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
1740 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1742 } else { # not $new
1744 # Article exists. Check for edit conflict.
1746 $this->mArticle->clear(); # Force reload of dates, etc.
1747 $timestamp = $this->mArticle->getTimestamp();
1749 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1751 if ( $timestamp != $this->edittime ) {
1752 $this->isConflict = true;
1753 if ( $this->section == 'new' ) {
1754 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
1755 $this->mArticle->getComment() == $this->newSectionSummary()
1757 // Probably a duplicate submission of a new comment.
1758 // This can happen when squid resends a request after
1759 // a timeout but the first one actually went through.
1760 wfDebug( __METHOD__
1761 . ": duplicate new section submission; trigger edit conflict!\n" );
1762 } else {
1763 // New comment; suppress conflict.
1764 $this->isConflict = false;
1765 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1767 } elseif ( $this->section == ''
1768 && Revision::userWasLastToEdit(
1769 DB_MASTER, $this->mTitle->getArticleID(),
1770 $wgUser->getId(), $this->edittime
1773 # Suppress edit conflict with self, except for section edits where merging is required.
1774 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1775 $this->isConflict = false;
1779 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1780 if ( $this->sectiontitle !== '' ) {
1781 $sectionTitle = $this->sectiontitle;
1782 } else {
1783 $sectionTitle = $this->summary;
1786 $content = null;
1788 if ( $this->isConflict ) {
1789 wfDebug( __METHOD__
1790 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1791 . " (article time '{$timestamp}')\n" );
1793 $content = $this->mArticle->replaceSectionContent(
1794 $this->section,
1795 $textbox_content,
1796 $sectionTitle,
1797 $this->edittime
1799 } else {
1800 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
1801 $content = $this->mArticle->replaceSectionContent(
1802 $this->section,
1803 $textbox_content,
1804 $sectionTitle
1808 if ( is_null( $content ) ) {
1809 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1810 $this->isConflict = true;
1811 $content = $textbox_content; // do not try to merge here!
1812 } elseif ( $this->isConflict ) {
1813 # Attempt merge
1814 if ( $this->mergeChangesIntoContent( $content ) ) {
1815 // Successful merge! Maybe we should tell the user the good news?
1816 $this->isConflict = false;
1817 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1818 } else {
1819 $this->section = '';
1820 $this->textbox1 = ContentHandler::getContentText( $content );
1821 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1825 if ( $this->isConflict ) {
1826 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1827 return $status;
1830 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1831 return $status;
1834 if ( $this->section == 'new' ) {
1835 // Handle the user preference to force summaries here
1836 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
1837 $this->missingSummary = true;
1838 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1839 $status->value = self::AS_SUMMARY_NEEDED;
1840 return $status;
1843 // Do not allow the user to post an empty comment
1844 if ( $this->textbox1 == '' ) {
1845 $this->missingComment = true;
1846 $status->fatal( 'missingcommenttext' );
1847 $status->value = self::AS_TEXTBOX_EMPTY;
1848 return $status;
1850 } elseif ( !$this->allowBlankSummary
1851 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1852 && !$content->isRedirect()
1853 && md5( $this->summary ) == $this->autoSumm
1855 $this->missingSummary = true;
1856 $status->fatal( 'missingsummary' );
1857 $status->value = self::AS_SUMMARY_NEEDED;
1858 return $status;
1861 # All's well
1862 wfProfileIn( __METHOD__ . '-sectionanchor' );
1863 $sectionanchor = '';
1864 if ( $this->section == 'new' ) {
1865 $this->summary = $this->newSectionSummary( $sectionanchor );
1866 } elseif ( $this->section != '' ) {
1867 # Try to get a section anchor from the section source, redirect
1868 # to edited section if header found.
1869 # XXX: Might be better to integrate this into Article::replaceSection
1870 # for duplicate heading checking and maybe parsing.
1871 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1872 # We can't deal with anchors, includes, html etc in the header for now,
1873 # headline would need to be parsed to improve this.
1874 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1875 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1878 $result['sectionanchor'] = $sectionanchor;
1879 wfProfileOut( __METHOD__ . '-sectionanchor' );
1881 // Save errors may fall down to the edit form, but we've now
1882 // merged the section into full text. Clear the section field
1883 // so that later submission of conflict forms won't try to
1884 // replace that into a duplicated mess.
1885 $this->textbox1 = $this->toEditText( $content );
1886 $this->section = '';
1888 $status->value = self::AS_SUCCESS_UPDATE;
1891 if ( !$this->allowSelfRedirect
1892 && $content->isRedirect()
1893 && $content->getRedirectTarget()->equals( $this->getTitle() )
1895 // If the page already redirects to itself, don't warn.
1896 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
1897 if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
1898 $this->selfRedirect = true;
1899 $status->fatal( 'selfredirect' );
1900 $status->value = self::AS_SELF_REDIRECT;
1901 return $status;
1905 // Check for length errors again now that the section is merged in
1906 $this->kblength = (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1907 if ( $this->kblength > $wgMaxArticleSize ) {
1908 $this->tooBig = true;
1909 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
1910 return $status;
1913 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1914 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1915 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1916 ( $bot ? EDIT_FORCE_BOT : 0 );
1918 $doEditStatus = $this->mArticle->doEditContent(
1919 $content,
1920 $this->summary,
1921 $flags,
1922 false,
1923 null,
1924 $content->getDefaultFormat()
1927 if ( !$doEditStatus->isOK() ) {
1928 // Failure from doEdit()
1929 // Show the edit conflict page for certain recognized errors from doEdit(),
1930 // but don't show it for errors from extension hooks
1931 $errors = $doEditStatus->getErrorsArray();
1932 if ( in_array( $errors[0][0],
1933 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1935 $this->isConflict = true;
1936 // Destroys data doEdit() put in $status->value but who cares
1937 $doEditStatus->value = self::AS_END;
1939 return $doEditStatus;
1942 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1943 if ( $result['nullEdit'] ) {
1944 // We don't know if it was a null edit until now, so increment here
1945 $wgUser->pingLimiter( 'linkpurge' );
1947 $result['redirect'] = $content->isRedirect();
1948 $this->updateWatchlist();
1949 return $status;
1953 * Register the change of watch status
1955 protected function updateWatchlist() {
1956 global $wgUser;
1958 if ( $wgUser->isLoggedIn()
1959 && $this->watchthis != $wgUser->isWatched( $this->mTitle, WatchedItem::IGNORE_USER_RIGHTS )
1961 $fname = __METHOD__;
1962 $title = $this->mTitle;
1963 $watch = $this->watchthis;
1965 // Do this in its own transaction to reduce contention...
1966 $dbw = wfGetDB( DB_MASTER );
1967 $dbw->onTransactionIdle( function () use ( $dbw, $title, $watch, $wgUser, $fname ) {
1968 WatchAction::doWatchOrUnwatch( $watch, $title, $wgUser );
1969 } );
1974 * Attempts to do 3-way merge of edit content with a base revision
1975 * and current content, in case of edit conflict, in whichever way appropriate
1976 * for the content type.
1978 * @since 1.21
1980 * @param Content $editContent
1982 * @return bool
1984 private function mergeChangesIntoContent( &$editContent ) {
1986 $db = wfGetDB( DB_MASTER );
1988 // This is the revision the editor started from
1989 $baseRevision = $this->getBaseRevision();
1990 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
1992 if ( is_null( $baseContent ) ) {
1993 return false;
1996 // The current state, we want to merge updates into it
1997 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1998 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2000 if ( is_null( $currentContent ) ) {
2001 return false;
2004 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2006 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2008 if ( $result ) {
2009 $editContent = $result;
2010 return true;
2013 return false;
2017 * @return Revision
2019 function getBaseRevision() {
2020 if ( !$this->mBaseRevision ) {
2021 $db = wfGetDB( DB_MASTER );
2022 $this->mBaseRevision = Revision::loadFromTimestamp(
2023 $db, $this->mTitle, $this->edittime );
2025 return $this->mBaseRevision;
2029 * Check given input text against $wgSpamRegex, and return the text of the first match.
2031 * @param string $text
2033 * @return string|bool Matching string or false
2035 public static function matchSpamRegex( $text ) {
2036 global $wgSpamRegex;
2037 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2038 $regexes = (array)$wgSpamRegex;
2039 return self::matchSpamRegexInternal( $text, $regexes );
2043 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2045 * @param string $text
2047 * @return string|bool Matching string or false
2049 public static function matchSummarySpamRegex( $text ) {
2050 global $wgSummarySpamRegex;
2051 $regexes = (array)$wgSummarySpamRegex;
2052 return self::matchSpamRegexInternal( $text, $regexes );
2056 * @param string $text
2057 * @param array $regexes
2058 * @return bool|string
2060 protected static function matchSpamRegexInternal( $text, $regexes ) {
2061 foreach ( $regexes as $regex ) {
2062 $matches = array();
2063 if ( preg_match( $regex, $text, $matches ) ) {
2064 return $matches[0];
2067 return false;
2070 function setHeaders() {
2071 global $wgOut, $wgUser, $wgAjaxEditStash;
2073 $wgOut->addModules( 'mediawiki.action.edit' );
2074 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2076 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2077 // The addition of default buttons is handled by getEditToolbar() which
2078 // has its own dependency on this module. The call here ensures the module
2079 // is loaded in time (it has position "top") for other modules to register
2080 // buttons (e.g. extensions, gadgets, user scripts).
2081 $wgOut->addModules( 'mediawiki.toolbar' );
2084 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2085 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2088 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2089 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2092 if ( $wgAjaxEditStash ) {
2093 $wgOut->addModules( 'mediawiki.action.edit.stash' );
2096 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2098 # Enabled article-related sidebar, toplinks, etc.
2099 $wgOut->setArticleRelated( true );
2101 $contextTitle = $this->getContextTitle();
2102 if ( $this->isConflict ) {
2103 $msg = 'editconflict';
2104 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2105 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2106 } else {
2107 $msg = $contextTitle->exists()
2108 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2109 && $contextTitle->getDefaultMessageText() !== false
2111 ? 'editing'
2112 : 'creating';
2115 # Use the title defined by DISPLAYTITLE magic word when present
2116 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2117 if ( $displayTitle === false ) {
2118 $displayTitle = $contextTitle->getPrefixedText();
2120 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2124 * Show all applicable editing introductions
2126 protected function showIntro() {
2127 global $wgOut, $wgUser;
2128 if ( $this->suppressIntro ) {
2129 return;
2132 $namespace = $this->mTitle->getNamespace();
2134 if ( $namespace == NS_MEDIAWIKI ) {
2135 # Show a warning if editing an interface message
2136 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2137 # If this is a default message (but not css or js),
2138 # show a hint that it is translatable on translatewiki.net
2139 if ( !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2140 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2142 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2143 if ( $defaultMessageText !== false ) {
2144 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2145 'translateinterface' );
2148 } elseif ( $namespace == NS_FILE ) {
2149 # Show a hint to shared repo
2150 $file = wfFindFile( $this->mTitle );
2151 if ( $file && !$file->isLocal() ) {
2152 $descUrl = $file->getDescriptionUrl();
2153 # there must be a description url to show a hint to shared repo
2154 if ( $descUrl ) {
2155 if ( !$this->mTitle->exists() ) {
2156 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2157 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2158 ) );
2159 } else {
2160 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2161 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2162 ) );
2168 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2169 # Show log extract when the user is currently blocked
2170 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2171 $parts = explode( '/', $this->mTitle->getText(), 2 );
2172 $username = $parts[0];
2173 $user = User::newFromName( $username, false /* allow IP users*/ );
2174 $ip = User::isIP( $username );
2175 $block = Block::newFromTarget( $user, $user );
2176 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2177 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2178 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2179 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2180 # Show log extract if the user is currently blocked
2181 LogEventsList::showLogExtract(
2182 $wgOut,
2183 'block',
2184 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2186 array(
2187 'lim' => 1,
2188 'showIfEmpty' => false,
2189 'msgKey' => array(
2190 'blocked-notice-logextract',
2191 $user->getName() # Support GENDER in notice
2197 # Try to add a custom edit intro, or use the standard one if this is not possible.
2198 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2199 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2200 wfMessage( 'helppage' )->inContentLanguage()->text()
2201 ) );
2202 if ( $wgUser->isLoggedIn() ) {
2203 $wgOut->wrapWikiMsg(
2204 // Suppress the external link icon, consider the help url an internal one
2205 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2206 array(
2207 'newarticletext',
2208 $helpLink
2211 } else {
2212 $wgOut->wrapWikiMsg(
2213 // Suppress the external link icon, consider the help url an internal one
2214 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2215 array(
2216 'newarticletextanon',
2217 $helpLink
2222 # Give a notice if the user is editing a deleted/moved page...
2223 if ( !$this->mTitle->exists() ) {
2224 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
2226 array(
2227 'lim' => 10,
2228 'conds' => array( "log_action != 'revision'" ),
2229 'showIfEmpty' => false,
2230 'msgKey' => array( 'recreate-moveddeleted-warn' )
2237 * Attempt to show a custom editing introduction, if supplied
2239 * @return bool
2241 protected function showCustomIntro() {
2242 if ( $this->editintro ) {
2243 $title = Title::newFromText( $this->editintro );
2244 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2245 global $wgOut;
2246 // Added using template syntax, to take <noinclude>'s into account.
2247 $wgOut->addWikiTextTitleTidy(
2248 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2249 $this->mTitle
2251 return true;
2254 return false;
2258 * Gets an editable textual representation of $content.
2259 * The textual representation can be turned by into a Content object by the
2260 * toEditContent() method.
2262 * If $content is null or false or a string, $content is returned unchanged.
2264 * If the given Content object is not of a type that can be edited using
2265 * the text base EditPage, an exception will be raised. Set
2266 * $this->allowNonTextContent to true to allow editing of non-textual
2267 * content.
2269 * @param Content|null|bool|string $content
2270 * @return string The editable text form of the content.
2272 * @throws MWException If $content is not an instance of TextContent and
2273 * $this->allowNonTextContent is not true.
2275 protected function toEditText( $content ) {
2276 if ( $content === null || $content === false || is_string( $content ) ) {
2277 return $content;
2280 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2281 throw new MWException( 'This content model is not supported: '
2282 . ContentHandler::getLocalizedName( $content->getModel() ) );
2285 return $content->serialize( $this->contentFormat );
2289 * Turns the given text into a Content object by unserializing it.
2291 * If the resulting Content object is not of a type that can be edited using
2292 * the text base EditPage, an exception will be raised. Set
2293 * $this->allowNonTextContent to true to allow editing of non-textual
2294 * content.
2296 * @param string|null|bool $text Text to unserialize
2297 * @return Content The content object created from $text. If $text was false
2298 * or null, false resp. null will be returned instead.
2300 * @throws MWException If unserializing the text results in a Content
2301 * object that is not an instance of TextContent and
2302 * $this->allowNonTextContent is not true.
2304 protected function toEditContent( $text ) {
2305 if ( $text === false || $text === null ) {
2306 return $text;
2309 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2310 $this->contentModel, $this->contentFormat );
2312 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2313 throw new MWException( 'This content model is not supported: '
2314 . ContentHandler::getLocalizedName( $content->getModel() ) );
2317 return $content;
2321 * Send the edit form and related headers to $wgOut
2322 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2323 * during form output near the top, for captchas and the like.
2325 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2326 * use the EditPage::showEditForm:fields hook instead.
2328 function showEditForm( $formCallback = null ) {
2329 global $wgOut, $wgUser;
2332 # need to parse the preview early so that we know which templates are used,
2333 # otherwise users with "show preview after edit box" will get a blank list
2334 # we parse this near the beginning so that setHeaders can do the title
2335 # setting work instead of leaving it in getPreviewText
2336 $previewOutput = '';
2337 if ( $this->formtype == 'preview' ) {
2338 $previewOutput = $this->getPreviewText();
2341 Hooks::run( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2343 $this->setHeaders();
2345 if ( $this->showHeader() === false ) {
2346 return;
2349 $wgOut->addHTML( $this->editFormPageTop );
2351 if ( $wgUser->getOption( 'previewontop' ) ) {
2352 $this->displayPreviewArea( $previewOutput, true );
2355 $wgOut->addHTML( $this->editFormTextTop );
2357 $showToolbar = true;
2358 if ( $this->wasDeletedSinceLastEdit() ) {
2359 if ( $this->formtype == 'save' ) {
2360 // Hide the toolbar and edit area, user can click preview to get it back
2361 // Add an confirmation checkbox and explanation.
2362 $showToolbar = false;
2363 } else {
2364 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2365 'deletedwhileediting' );
2369 // @todo add EditForm plugin interface and use it here!
2370 // search for textarea1 and textares2, and allow EditForm to override all uses.
2371 $wgOut->addHTML( Html::openElement(
2372 'form',
2373 array(
2374 'id' => self::EDITFORM_ID,
2375 'name' => self::EDITFORM_ID,
2376 'method' => 'post',
2377 'action' => $this->getActionURL( $this->getContextTitle() ),
2378 'enctype' => 'multipart/form-data'
2380 ) );
2382 if ( is_callable( $formCallback ) ) {
2383 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2384 call_user_func_array( $formCallback, array( &$wgOut ) );
2387 // Add an empty field to trip up spambots
2388 $wgOut->addHTML(
2389 Xml::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2390 . Html::rawElement(
2391 'label',
2392 array( 'for' => 'wpAntiSpam' ),
2393 wfMessage( 'simpleantispam-label' )->parse()
2395 . Xml::element(
2396 'input',
2397 array(
2398 'type' => 'text',
2399 'name' => 'wpAntispam',
2400 'id' => 'wpAntispam',
2401 'value' => ''
2404 . Xml::closeElement( 'div' )
2407 Hooks::run( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2409 // Put these up at the top to ensure they aren't lost on early form submission
2410 $this->showFormBeforeText();
2412 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2413 $username = $this->lastDelete->user_name;
2414 $comment = $this->lastDelete->log_comment;
2416 // It is better to not parse the comment at all than to have templates expanded in the middle
2417 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2418 $key = $comment === ''
2419 ? 'confirmrecreate-noreason'
2420 : 'confirmrecreate';
2421 $wgOut->addHTML(
2422 '<div class="mw-confirm-recreate">' .
2423 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2424 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2425 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2427 '</div>'
2431 # When the summary is hidden, also hide them on preview/show changes
2432 if ( $this->nosummary ) {
2433 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2436 # If a blank edit summary was previously provided, and the appropriate
2437 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2438 # user being bounced back more than once in the event that a summary
2439 # is not required.
2440 #####
2441 # For a bit more sophisticated detection of blank summaries, hash the
2442 # automatic one and pass that in the hidden field wpAutoSummary.
2443 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2444 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2447 if ( $this->undidRev ) {
2448 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2451 if ( $this->selfRedirect ) {
2452 $wgOut->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2455 if ( $this->hasPresetSummary ) {
2456 // If a summary has been preset using &summary= we don't want to prompt for
2457 // a different summary. Only prompt for a summary if the summary is blanked.
2458 // (Bug 17416)
2459 $this->autoSumm = md5( '' );
2462 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2463 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2465 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2466 $wgOut->addHTML( Html::hidden( 'parentRevId',
2467 $this->parentRevId ?: $this->mArticle->getRevIdFetched() ) );
2469 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2470 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2472 if ( $this->section == 'new' ) {
2473 $this->showSummaryInput( true, $this->summary );
2474 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2477 $wgOut->addHTML( $this->editFormTextBeforeContent );
2479 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2480 $wgOut->addHTML( EditPage::getEditToolbar() );
2483 if ( $this->blankArticle ) {
2484 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2487 if ( $this->isConflict ) {
2488 // In an edit conflict bypass the overridable content form method
2489 // and fallback to the raw wpTextbox1 since editconflicts can't be
2490 // resolved between page source edits and custom ui edits using the
2491 // custom edit ui.
2492 $this->textbox2 = $this->textbox1;
2494 $content = $this->getCurrentContent();
2495 $this->textbox1 = $this->toEditText( $content );
2497 $this->showTextbox1();
2498 } else {
2499 $this->showContentForm();
2502 $wgOut->addHTML( $this->editFormTextAfterContent );
2504 $this->showStandardInputs();
2506 $this->showFormAfterText();
2508 $this->showTosSummary();
2510 $this->showEditTools();
2512 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2514 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2515 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2517 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2518 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
2520 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'limitreport' ),
2521 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2523 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2525 if ( $this->isConflict ) {
2526 try {
2527 $this->showConflict();
2528 } catch ( MWContentSerializationException $ex ) {
2529 // this can't really happen, but be nice if it does.
2530 $msg = wfMessage(
2531 'content-failed-to-parse',
2532 $this->contentModel,
2533 $this->contentFormat,
2534 $ex->getMessage()
2536 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2540 // Marker for detecting truncated form data. This must be the last
2541 // parameter sent in order to be of use, so do not move me.
2542 $wgOut->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2543 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2545 if ( !$wgUser->getOption( 'previewontop' ) ) {
2546 $this->displayPreviewArea( $previewOutput, false );
2552 * Extract the section title from current section text, if any.
2554 * @param string $text
2555 * @return string|bool String or false
2557 public static function extractSectionTitle( $text ) {
2558 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2559 if ( !empty( $matches[2] ) ) {
2560 global $wgParser;
2561 return $wgParser->stripSectionName( trim( $matches[2] ) );
2562 } else {
2563 return false;
2568 * @return bool
2570 protected function showHeader() {
2571 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2572 global $wgAllowUserCss, $wgAllowUserJs;
2574 if ( $this->mTitle->isTalkPage() ) {
2575 $wgOut->addWikiMsg( 'talkpagetext' );
2578 // Add edit notices
2579 $wgOut->addHTML( implode( "\n", $this->mTitle->getEditNotices( $this->oldid ) ) );
2581 if ( $this->isConflict ) {
2582 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2583 $this->edittime = $this->mArticle->getTimestamp();
2584 } else {
2585 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2586 // We use $this->section to much before this and getVal('wgSection') directly in other places
2587 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2588 // Someone is welcome to try refactoring though
2589 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2590 return false;
2593 if ( $this->section != '' && $this->section != 'new' ) {
2594 if ( !$this->summary && !$this->preview && !$this->diff ) {
2595 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); //FIXME: use Content object
2596 if ( $sectionTitle !== false ) {
2597 $this->summary = "/* $sectionTitle */ ";
2602 if ( $this->missingComment ) {
2603 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2606 if ( $this->missingSummary && $this->section != 'new' ) {
2607 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2610 if ( $this->missingSummary && $this->section == 'new' ) {
2611 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2614 if ( $this->blankArticle ) {
2615 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2618 if ( $this->selfRedirect ) {
2619 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2622 if ( $this->hookError !== '' ) {
2623 $wgOut->addWikiText( $this->hookError );
2626 if ( !$this->checkUnicodeCompliantBrowser() ) {
2627 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2630 if ( $this->section != 'new' ) {
2631 $revision = $this->mArticle->getRevisionFetched();
2632 if ( $revision ) {
2633 // Let sysop know that this will make private content public if saved
2635 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2636 $wgOut->wrapWikiMsg(
2637 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2638 'rev-deleted-text-permission'
2640 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2641 $wgOut->wrapWikiMsg(
2642 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2643 'rev-deleted-text-view'
2647 if ( !$revision->isCurrent() ) {
2648 $this->mArticle->setOldSubtitle( $revision->getId() );
2649 $wgOut->addWikiMsg( 'editingold' );
2651 } elseif ( $this->mTitle->exists() ) {
2652 // Something went wrong
2654 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2655 array( 'missing-revision', $this->oldid ) );
2660 if ( wfReadOnly() ) {
2661 $wgOut->wrapWikiMsg(
2662 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2663 array( 'readonlywarning', wfReadOnlyReason() )
2665 } elseif ( $wgUser->isAnon() ) {
2666 if ( $this->formtype != 'preview' ) {
2667 $wgOut->wrapWikiMsg(
2668 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2669 array( 'anoneditwarning',
2670 // Log-in link
2671 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2672 // Sign-up link
2673 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2675 } else {
2676 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2677 'anonpreviewwarning'
2680 } else {
2681 if ( $this->isCssJsSubpage ) {
2682 # Check the skin exists
2683 if ( $this->isWrongCaseCssJsPage ) {
2684 $wgOut->wrapWikiMsg(
2685 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2686 array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() )
2689 if ( $this->formtype !== 'preview' ) {
2690 if ( $this->isCssSubpage && $wgAllowUserCss ) {
2691 $wgOut->wrapWikiMsg(
2692 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2693 array( 'usercssyoucanpreview' )
2697 if ( $this->isJsSubpage && $wgAllowUserJs ) {
2698 $wgOut->wrapWikiMsg(
2699 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2700 array( 'userjsyoucanpreview' )
2707 if ( $this->mTitle->isProtected( 'edit' ) &&
2708 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2710 # Is the title semi-protected?
2711 if ( $this->mTitle->isSemiProtected() ) {
2712 $noticeMsg = 'semiprotectedpagewarning';
2713 } else {
2714 # Then it must be protected based on static groups (regular)
2715 $noticeMsg = 'protectedpagewarning';
2717 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2718 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2720 if ( $this->mTitle->isCascadeProtected() ) {
2721 # Is this page under cascading protection from some source pages?
2722 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2723 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2724 $cascadeSourcesCount = count( $cascadeSources );
2725 if ( $cascadeSourcesCount > 0 ) {
2726 # Explain, and list the titles responsible
2727 foreach ( $cascadeSources as $page ) {
2728 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2731 $notice .= '</div>';
2732 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2734 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2735 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2736 array( 'lim' => 1,
2737 'showIfEmpty' => false,
2738 'msgKey' => array( 'titleprotectedwarning' ),
2739 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2742 if ( $this->kblength === false ) {
2743 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2746 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2747 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2748 array(
2749 'longpageerror',
2750 $wgLang->formatNum( $this->kblength ),
2751 $wgLang->formatNum( $wgMaxArticleSize )
2754 } else {
2755 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2756 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2757 array(
2758 'longpage-hint',
2759 $wgLang->formatSize( strlen( $this->textbox1 ) ),
2760 strlen( $this->textbox1 )
2765 # Add header copyright warning
2766 $this->showHeaderCopyrightWarning();
2768 return true;
2772 * Standard summary input and label (wgSummary), abstracted so EditPage
2773 * subclasses may reorganize the form.
2774 * Note that you do not need to worry about the label's for=, it will be
2775 * inferred by the id given to the input. You can remove them both by
2776 * passing array( 'id' => false ) to $userInputAttrs.
2778 * @param string $summary The value of the summary input
2779 * @param string $labelText The html to place inside the label
2780 * @param array $inputAttrs Array of attrs to use on the input
2781 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2783 * @return array An array in the format array( $label, $input )
2785 function getSummaryInput( $summary = "", $labelText = null,
2786 $inputAttrs = null, $spanLabelAttrs = null
2788 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2789 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2790 'id' => 'wpSummary',
2791 'maxlength' => '200',
2792 'tabindex' => '1',
2793 'size' => 60,
2794 'spellcheck' => 'true',
2795 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2797 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2798 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2799 'id' => "wpSummaryLabel"
2802 $label = null;
2803 if ( $labelText ) {
2804 $label = Xml::tags(
2805 'label',
2806 $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null,
2807 $labelText
2809 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2812 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2814 return array( $label, $input );
2818 * @param bool $isSubjectPreview True if this is the section subject/title
2819 * up top, or false if this is the comment summary
2820 * down below the textarea
2821 * @param string $summary The text of the summary to display
2823 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2824 global $wgOut, $wgContLang;
2825 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2826 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2827 if ( $isSubjectPreview ) {
2828 if ( $this->nosummary ) {
2829 return;
2831 } else {
2832 if ( !$this->mShowSummaryField ) {
2833 return;
2836 $summary = $wgContLang->recodeForEdit( $summary );
2837 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2838 list( $label, $input ) = $this->getSummaryInput(
2839 $summary,
2840 $labelText,
2841 array( 'class' => $summaryClass ),
2842 array()
2844 $wgOut->addHTML( "{$label} {$input}" );
2848 * @param bool $isSubjectPreview True if this is the section subject/title
2849 * up top, or false if this is the comment summary
2850 * down below the textarea
2851 * @param string $summary The text of the summary to display
2852 * @return string
2854 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2855 // avoid spaces in preview, gets always trimmed on save
2856 $summary = trim( $summary );
2857 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
2858 return "";
2861 global $wgParser;
2863 if ( $isSubjectPreview ) {
2864 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2865 ->inContentLanguage()->text();
2868 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2870 $summary = wfMessage( $message )->parse()
2871 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2872 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2875 protected function showFormBeforeText() {
2876 global $wgOut;
2877 $section = htmlspecialchars( $this->section );
2878 $wgOut->addHTML( <<<HTML
2879 <input type='hidden' value="{$section}" name="wpSection"/>
2880 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2881 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2882 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2884 HTML
2886 if ( !$this->checkUnicodeCompliantBrowser() ) {
2887 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2891 protected function showFormAfterText() {
2892 global $wgOut, $wgUser;
2894 * To make it harder for someone to slip a user a page
2895 * which submits an edit form to the wiki without their
2896 * knowledge, a random token is associated with the login
2897 * session. If it's not passed back with the submission,
2898 * we won't save the page, or render user JavaScript and
2899 * CSS previews.
2901 * For anon editors, who may not have a session, we just
2902 * include the constant suffix to prevent editing from
2903 * broken text-mangling proxies.
2905 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2909 * Subpage overridable method for printing the form for page content editing
2910 * By default this simply outputs wpTextbox1
2911 * Subclasses can override this to provide a custom UI for editing;
2912 * be it a form, or simply wpTextbox1 with a modified content that will be
2913 * reverse modified when extracted from the post data.
2914 * Note that this is basically the inverse for importContentFormData
2916 protected function showContentForm() {
2917 $this->showTextbox1();
2921 * Method to output wpTextbox1
2922 * The $textoverride method can be used by subclasses overriding showContentForm
2923 * to pass back to this method.
2925 * @param array $customAttribs Array of html attributes to use in the textarea
2926 * @param string $textoverride Optional text to override $this->textarea1 with
2928 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2929 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2930 $attribs = array( 'style' => 'display:none;' );
2931 } else {
2932 $classes = array(); // Textarea CSS
2933 if ( $this->mTitle->isProtected( 'edit' ) &&
2934 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2936 # Is the title semi-protected?
2937 if ( $this->mTitle->isSemiProtected() ) {
2938 $classes[] = 'mw-textarea-sprotected';
2939 } else {
2940 # Then it must be protected based on static groups (regular)
2941 $classes[] = 'mw-textarea-protected';
2943 # Is the title cascade-protected?
2944 if ( $this->mTitle->isCascadeProtected() ) {
2945 $classes[] = 'mw-textarea-cprotected';
2949 $attribs = array( 'tabindex' => 1 );
2951 if ( is_array( $customAttribs ) ) {
2952 $attribs += $customAttribs;
2955 if ( count( $classes ) ) {
2956 if ( isset( $attribs['class'] ) ) {
2957 $classes[] = $attribs['class'];
2959 $attribs['class'] = implode( ' ', $classes );
2963 $this->showTextbox(
2964 $textoverride !== null ? $textoverride : $this->textbox1,
2965 'wpTextbox1',
2966 $attribs
2970 protected function showTextbox2() {
2971 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2974 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2975 global $wgOut, $wgUser;
2977 $wikitext = $this->safeUnicodeOutput( $text );
2978 if ( strval( $wikitext ) !== '' ) {
2979 // Ensure there's a newline at the end, otherwise adding lines
2980 // is awkward.
2981 // But don't add a newline if the ext is empty, or Firefox in XHTML
2982 // mode will show an extra newline. A bit annoying.
2983 $wikitext .= "\n";
2986 $attribs = $customAttribs + array(
2987 'accesskey' => ',',
2988 'id' => $name,
2989 'cols' => $wgUser->getIntOption( 'cols' ),
2990 'rows' => $wgUser->getIntOption( 'rows' ),
2991 // Avoid PHP notices when appending preferences
2992 // (appending allows customAttribs['style'] to still work).
2993 'style' => ''
2996 $pageLang = $this->mTitle->getPageLanguage();
2997 $attribs['lang'] = $pageLang->getHtmlCode();
2998 $attribs['dir'] = $pageLang->getDir();
3000 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
3003 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3004 global $wgOut;
3005 $classes = array();
3006 if ( $isOnTop ) {
3007 $classes[] = 'ontop';
3010 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3012 if ( $this->formtype != 'preview' ) {
3013 $attribs['style'] = 'display: none;';
3016 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
3018 if ( $this->formtype == 'preview' ) {
3019 $this->showPreview( $previewOutput );
3022 $wgOut->addHTML( '</div>' );
3024 if ( $this->formtype == 'diff' ) {
3025 try {
3026 $this->showDiff();
3027 } catch ( MWContentSerializationException $ex ) {
3028 $msg = wfMessage(
3029 'content-failed-to-parse',
3030 $this->contentModel,
3031 $this->contentFormat,
3032 $ex->getMessage()
3034 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3040 * Append preview output to $wgOut.
3041 * Includes category rendering if this is a category page.
3043 * @param string $text The HTML to be output for the preview.
3045 protected function showPreview( $text ) {
3046 global $wgOut;
3047 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3048 $this->mArticle->openShowCategory();
3050 # This hook seems slightly odd here, but makes things more
3051 # consistent for extensions.
3052 Hooks::run( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3053 $wgOut->addHTML( $text );
3054 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3055 $this->mArticle->closeShowCategory();
3060 * Get a diff between the current contents of the edit box and the
3061 * version of the page we're editing from.
3063 * If this is a section edit, we'll replace the section as for final
3064 * save and then make a comparison.
3066 function showDiff() {
3067 global $wgUser, $wgContLang, $wgOut;
3069 $oldtitlemsg = 'currentrev';
3070 # if message does not exist, show diff against the preloaded default
3071 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3072 $oldtext = $this->mTitle->getDefaultMessageText();
3073 if ( $oldtext !== false ) {
3074 $oldtitlemsg = 'defaultmessagetext';
3075 $oldContent = $this->toEditContent( $oldtext );
3076 } else {
3077 $oldContent = null;
3079 } else {
3080 $oldContent = $this->getCurrentContent();
3083 $textboxContent = $this->toEditContent( $this->textbox1 );
3085 $newContent = $this->mArticle->replaceSectionContent(
3086 $this->section, $textboxContent,
3087 $this->summary, $this->edittime );
3089 if ( $newContent ) {
3090 ContentHandler::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3091 Hooks::run( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3093 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
3094 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
3097 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3098 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3099 $newtitle = wfMessage( 'yourtext' )->parse();
3101 if ( !$oldContent ) {
3102 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3105 if ( !$newContent ) {
3106 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3109 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
3110 $de->setContent( $oldContent, $newContent );
3112 $difftext = $de->getDiff( $oldtitle, $newtitle );
3113 $de->showDiffStyle();
3114 } else {
3115 $difftext = '';
3118 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3122 * Show the header copyright warning.
3124 protected function showHeaderCopyrightWarning() {
3125 $msg = 'editpage-head-copy-warn';
3126 if ( !wfMessage( $msg )->isDisabled() ) {
3127 global $wgOut;
3128 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3129 'editpage-head-copy-warn' );
3134 * Give a chance for site and per-namespace customizations of
3135 * terms of service summary link that might exist separately
3136 * from the copyright notice.
3138 * This will display between the save button and the edit tools,
3139 * so should remain short!
3141 protected function showTosSummary() {
3142 $msg = 'editpage-tos-summary';
3143 Hooks::run( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
3144 if ( !wfMessage( $msg )->isDisabled() ) {
3145 global $wgOut;
3146 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3147 $wgOut->addWikiMsg( $msg );
3148 $wgOut->addHTML( '</div>' );
3152 protected function showEditTools() {
3153 global $wgOut;
3154 $wgOut->addHTML( '<div class="mw-editTools">' .
3155 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3156 '</div>' );
3160 * Get the copyright warning
3162 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3163 * @return string
3165 protected function getCopywarn() {
3166 return self::getCopyrightWarning( $this->mTitle );
3170 * Get the copyright warning, by default returns wikitext
3172 * @param Title $title
3173 * @param string $format Output format, valid values are any function of a Message object
3174 * @return string
3176 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3177 global $wgRightsText;
3178 if ( $wgRightsText ) {
3179 $copywarnMsg = array( 'copyrightwarning',
3180 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3181 $wgRightsText );
3182 } else {
3183 $copywarnMsg = array( 'copyrightwarning2',
3184 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3186 // Allow for site and per-namespace customization of contribution/copyright notice.
3187 Hooks::run( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3189 return "<div id=\"editpage-copywarn\">\n" .
3190 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3194 * Get the Limit report for page previews
3196 * @since 1.22
3197 * @param ParserOutput $output ParserOutput object from the parse
3198 * @return string HTML
3200 public static function getPreviewLimitReport( $output ) {
3201 if ( !$output || !$output->getLimitReportData() ) {
3202 return '';
3206 $limitReport = Html::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3207 wfMessage( 'limitreport-title' )->parseAsBlock()
3210 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3211 $limitReport .= Html::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3213 $limitReport .= Html::openElement( 'table', array(
3214 'class' => 'preview-limit-report wikitable'
3215 ) ) .
3216 Html::openElement( 'tbody' );
3218 foreach ( $output->getLimitReportData() as $key => $value ) {
3219 if ( Hooks::run( 'ParserLimitReportFormat',
3220 array( $key, &$value, &$limitReport, true, true )
3221 ) ) {
3222 $keyMsg = wfMessage( $key );
3223 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3224 if ( !$valueMsg->exists() ) {
3225 $valueMsg = new RawMessage( '$1' );
3227 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3228 $limitReport .= Html::openElement( 'tr' ) .
3229 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3230 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3231 Html::closeElement( 'tr' );
3236 $limitReport .= Html::closeElement( 'tbody' ) .
3237 Html::closeElement( 'table' ) .
3238 Html::closeElement( 'div' );
3241 return $limitReport;
3244 protected function showStandardInputs( &$tabindex = 2 ) {
3245 global $wgOut;
3246 $wgOut->addHTML( "<div class='editOptions'>\n" );
3248 if ( $this->section != 'new' ) {
3249 $this->showSummaryInput( false, $this->summary );
3250 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3253 $checkboxes = $this->getCheckboxes( $tabindex,
3254 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
3255 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3257 // Show copyright warning.
3258 $wgOut->addWikiText( $this->getCopywarn() );
3259 $wgOut->addHTML( $this->editFormTextAfterWarn );
3261 $wgOut->addHTML( "<div class='editButtons'>\n" );
3262 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3264 $cancel = $this->getCancelLink();
3265 if ( $cancel !== '' ) {
3266 $cancel .= Html::element( 'span',
3267 array( 'class' => 'mw-editButtons-pipe-separator' ),
3268 wfMessage( 'pipe-separator' )->text() );
3271 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3272 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3273 $attrs = array(
3274 'target' => 'helpwindow',
3275 'href' => $edithelpurl,
3277 $edithelp = Html::linkButton( wfMessage( 'edithelp' )->text(),
3278 $attrs, array( 'mw-ui-quiet' ) ) .
3279 wfMessage( 'word-separator' )->escaped() .
3280 wfMessage( 'newwindow' )->parse();
3282 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3283 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3284 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3286 Hooks::run( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3288 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3292 * Show an edit conflict. textbox1 is already shown in showEditForm().
3293 * If you want to use another entry point to this function, be careful.
3295 protected function showConflict() {
3296 global $wgOut;
3298 if ( Hooks::run( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3299 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3301 $content1 = $this->toEditContent( $this->textbox1 );
3302 $content2 = $this->toEditContent( $this->textbox2 );
3304 $handler = ContentHandler::getForModelID( $this->contentModel );
3305 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3306 $de->setContent( $content2, $content1 );
3307 $de->showDiff(
3308 wfMessage( 'yourtext' )->parse(),
3309 wfMessage( 'storedversion' )->text()
3312 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3313 $this->showTextbox2();
3318 * @return string
3320 public function getCancelLink() {
3321 $cancelParams = array();
3322 if ( !$this->isConflict && $this->oldid > 0 ) {
3323 $cancelParams['oldid'] = $this->oldid;
3325 $attrs = array( 'id' => 'mw-editform-cancel' );
3327 return Linker::linkKnown(
3328 $this->getContextTitle(),
3329 wfMessage( 'cancel' )->parse(),
3330 Html::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3331 $cancelParams
3336 * Returns the URL to use in the form's action attribute.
3337 * This is used by EditPage subclasses when simply customizing the action
3338 * variable in the constructor is not enough. This can be used when the
3339 * EditPage lives inside of a Special page rather than a custom page action.
3341 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3342 * @return string
3344 protected function getActionURL( Title $title ) {
3345 return $title->getLocalURL( array( 'action' => $this->action ) );
3349 * Check if a page was deleted while the user was editing it, before submit.
3350 * Note that we rely on the logging table, which hasn't been always there,
3351 * but that doesn't matter, because this only applies to brand new
3352 * deletes.
3353 * @return bool
3355 protected function wasDeletedSinceLastEdit() {
3356 if ( $this->deletedSinceEdit !== null ) {
3357 return $this->deletedSinceEdit;
3360 $this->deletedSinceEdit = false;
3362 if ( $this->mTitle->isDeletedQuick() ) {
3363 $this->lastDelete = $this->getLastDelete();
3364 if ( $this->lastDelete ) {
3365 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3366 if ( $deleteTime > $this->starttime ) {
3367 $this->deletedSinceEdit = true;
3372 return $this->deletedSinceEdit;
3376 * @return bool|stdClass
3378 protected function getLastDelete() {
3379 $dbr = wfGetDB( DB_SLAVE );
3380 $data = $dbr->selectRow(
3381 array( 'logging', 'user' ),
3382 array(
3383 'log_type',
3384 'log_action',
3385 'log_timestamp',
3386 'log_user',
3387 'log_namespace',
3388 'log_title',
3389 'log_comment',
3390 'log_params',
3391 'log_deleted',
3392 'user_name'
3393 ), array(
3394 'log_namespace' => $this->mTitle->getNamespace(),
3395 'log_title' => $this->mTitle->getDBkey(),
3396 'log_type' => 'delete',
3397 'log_action' => 'delete',
3398 'user_id=log_user'
3400 __METHOD__,
3401 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3403 // Quick paranoid permission checks...
3404 if ( is_object( $data ) ) {
3405 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3406 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
3409 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3410 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
3414 return $data;
3418 * Get the rendered text for previewing.
3419 * @throws MWException
3420 * @return string
3422 function getPreviewText() {
3423 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3424 global $wgAllowUserCss, $wgAllowUserJs;
3427 if ( $wgRawHtml && !$this->mTokenOk ) {
3428 // Could be an offsite preview attempt. This is very unsafe if
3429 // HTML is enabled, as it could be an attack.
3430 $parsedNote = '';
3431 if ( $this->textbox1 !== '' ) {
3432 // Do not put big scary notice, if previewing the empty
3433 // string, which happens when you initially edit
3434 // a category page, due to automatic preview-on-open.
3435 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3436 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3438 return $parsedNote;
3441 $note = '';
3443 try {
3444 $content = $this->toEditContent( $this->textbox1 );
3446 $previewHTML = '';
3447 if ( !Hooks::run(
3448 'AlternateEditPreview',
3449 array( $this, &$content, &$previewHTML, &$this->mParserOutput ) )
3451 return $previewHTML;
3454 # provide a anchor link to the editform
3455 $continueEditing = '<span class="mw-continue-editing">' .
3456 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3457 wfMessage( 'continue-editing' )->text() . ']]</span>';
3458 if ( $this->mTriedSave && !$this->mTokenOk ) {
3459 if ( $this->mTokenOkExceptSuffix ) {
3460 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3461 } else {
3462 $note = wfMessage( 'session_fail_preview' )->plain();
3464 } elseif ( $this->incompleteForm ) {
3465 $note = wfMessage( 'edit_form_incomplete' )->plain();
3466 } else {
3467 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3470 $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
3471 $parserOptions->setIsPreview( true );
3472 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3474 # don't parse non-wikitext pages, show message about preview
3475 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3476 if ( $this->mTitle->isCssJsSubpage() ) {
3477 $level = 'user';
3478 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3479 $level = 'site';
3480 } else {
3481 $level = false;
3484 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3485 $format = 'css';
3486 if ( $level === 'user' && !$wgAllowUserCss ) {
3487 $format = false;
3489 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3490 $format = 'js';
3491 if ( $level === 'user' && !$wgAllowUserJs ) {
3492 $format = false;
3494 } else {
3495 $format = false;
3498 # Used messages to make sure grep find them:
3499 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3500 if ( $level && $format ) {
3501 $note = "<div id='mw-{$level}{$format}preview'>" .
3502 wfMessage( "{$level}{$format}preview" )->text() .
3503 ' ' . $continueEditing . "</div>";
3507 # If we're adding a comment, we need to show the
3508 # summary as the headline
3509 if ( $this->section === "new" && $this->summary !== "" ) {
3510 $content = $content->addSectionHeader( $this->summary );
3513 $hook_args = array( $this, &$content );
3514 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3515 Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3517 $parserOptions->enableLimitReport();
3519 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3520 # But it's now deprecated, so never mind
3522 $pstContent = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3523 $scopedCallback = $parserOptions->setupFakeRevision(
3524 $this->mTitle, $pstContent, $wgUser );
3525 $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
3527 # Try to stash the edit for the final submission step
3528 # @todo: different date format preferences cause cache misses
3529 ApiStashEdit::stashEditFromPreview(
3530 $this->getArticle(), $content, $pstContent,
3531 $parserOutput, $parserOptions, $parserOptions, wfTimestampNow()
3534 $parserOutput->setEditSectionTokens( false ); // no section edit links
3535 $previewHTML = $parserOutput->getText();
3536 $this->mParserOutput = $parserOutput;
3537 $wgOut->addParserOutputMetadata( $parserOutput );
3539 if ( count( $parserOutput->getWarnings() ) ) {
3540 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3542 } catch ( MWContentSerializationException $ex ) {
3543 $m = wfMessage(
3544 'content-failed-to-parse',
3545 $this->contentModel,
3546 $this->contentFormat,
3547 $ex->getMessage()
3549 $note .= "\n\n" . $m->parse();
3550 $previewHTML = '';
3553 if ( $this->isConflict ) {
3554 $conflict = '<h2 id="mw-previewconflict">'
3555 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3556 } else {
3557 $conflict = '<hr />';
3560 $previewhead = "<div class='previewnote'>\n" .
3561 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3562 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3564 $pageViewLang = $this->mTitle->getPageViewLanguage();
3565 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3566 'class' => 'mw-content-' . $pageViewLang->getDir() );
3567 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3569 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3573 * @return array
3575 function getTemplates() {
3576 if ( $this->preview || $this->section != '' ) {
3577 $templates = array();
3578 if ( !isset( $this->mParserOutput ) ) {
3579 return $templates;
3581 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3582 foreach ( array_keys( $template ) as $dbk ) {
3583 $templates[] = Title::makeTitle( $ns, $dbk );
3586 return $templates;
3587 } else {
3588 return $this->mTitle->getTemplateLinksFrom();
3593 * Shows a bulletin board style toolbar for common editing functions.
3594 * It can be disabled in the user preferences.
3596 * @return string
3598 static function getEditToolbar() {
3599 global $wgContLang, $wgOut;
3600 global $wgEnableUploads, $wgForeignFileRepos;
3602 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3605 * $toolarray is an array of arrays each of which includes the
3606 * opening tag, the closing tag, optionally a sample text that is
3607 * inserted between the two when no selection is highlighted
3608 * and. The tip text is shown when the user moves the mouse
3609 * over the button.
3611 * Images are defined in ResourceLoaderEditToolbarModule.
3613 $toolarray = array(
3614 array(
3615 'id' => 'mw-editbutton-bold',
3616 'open' => '\'\'\'',
3617 'close' => '\'\'\'',
3618 'sample' => wfMessage( 'bold_sample' )->text(),
3619 'tip' => wfMessage( 'bold_tip' )->text(),
3621 array(
3622 'id' => 'mw-editbutton-italic',
3623 'open' => '\'\'',
3624 'close' => '\'\'',
3625 'sample' => wfMessage( 'italic_sample' )->text(),
3626 'tip' => wfMessage( 'italic_tip' )->text(),
3628 array(
3629 'id' => 'mw-editbutton-link',
3630 'open' => '[[',
3631 'close' => ']]',
3632 'sample' => wfMessage( 'link_sample' )->text(),
3633 'tip' => wfMessage( 'link_tip' )->text(),
3635 array(
3636 'id' => 'mw-editbutton-extlink',
3637 'open' => '[',
3638 'close' => ']',
3639 'sample' => wfMessage( 'extlink_sample' )->text(),
3640 'tip' => wfMessage( 'extlink_tip' )->text(),
3642 array(
3643 'id' => 'mw-editbutton-headline',
3644 'open' => "\n== ",
3645 'close' => " ==\n",
3646 'sample' => wfMessage( 'headline_sample' )->text(),
3647 'tip' => wfMessage( 'headline_tip' )->text(),
3649 $imagesAvailable ? array(
3650 'id' => 'mw-editbutton-image',
3651 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3652 'close' => ']]',
3653 'sample' => wfMessage( 'image_sample' )->text(),
3654 'tip' => wfMessage( 'image_tip' )->text(),
3655 ) : false,
3656 $imagesAvailable ? array(
3657 'id' => 'mw-editbutton-media',
3658 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3659 'close' => ']]',
3660 'sample' => wfMessage( 'media_sample' )->text(),
3661 'tip' => wfMessage( 'media_tip' )->text(),
3662 ) : false,
3663 array(
3664 'id' => 'mw-editbutton-nowiki',
3665 'open' => "<nowiki>",
3666 'close' => "</nowiki>",
3667 'sample' => wfMessage( 'nowiki_sample' )->text(),
3668 'tip' => wfMessage( 'nowiki_tip' )->text(),
3670 array(
3671 'id' => 'mw-editbutton-signature',
3672 'open' => '--~~~~',
3673 'close' => '',
3674 'sample' => '',
3675 'tip' => wfMessage( 'sig_tip' )->text(),
3677 array(
3678 'id' => 'mw-editbutton-hr',
3679 'open' => "\n----\n",
3680 'close' => '',
3681 'sample' => '',
3682 'tip' => wfMessage( 'hr_tip' )->text(),
3686 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3687 foreach ( $toolarray as $tool ) {
3688 if ( !$tool ) {
3689 continue;
3692 $params = array(
3693 // Images are defined in ResourceLoaderEditToolbarModule
3694 false,
3695 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3696 // Older browsers show a "speedtip" type message only for ALT.
3697 // Ideally these should be different, realistically they
3698 // probably don't need to be.
3699 $tool['tip'],
3700 $tool['open'],
3701 $tool['close'],
3702 $tool['sample'],
3703 $tool['id'],
3706 $script .= Xml::encodeJsCall(
3707 'mw.toolbar.addButton',
3708 $params,
3709 ResourceLoader::inDebugMode()
3713 $script .= '});';
3714 $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
3716 $toolbar = '<div id="toolbar"></div>';
3718 Hooks::run( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3720 return $toolbar;
3724 * Returns an array of html code of the following checkboxes:
3725 * minor and watch
3727 * @param int $tabindex Current tabindex
3728 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3729 * status of the checkbox
3731 * @return array
3733 public function getCheckboxes( &$tabindex, $checked ) {
3734 global $wgUser, $wgUseMediaWikiUIEverywhere;
3736 $checkboxes = array();
3738 // don't show the minor edit checkbox if it's a new page or section
3739 if ( !$this->isNew ) {
3740 $checkboxes['minor'] = '';
3741 $minorLabel = wfMessage( 'minoredit' )->parse();
3742 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3743 $attribs = array(
3744 'tabindex' => ++$tabindex,
3745 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3746 'id' => 'wpMinoredit',
3748 $minorEditHtml =
3749 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3750 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3751 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3752 ">{$minorLabel}</label>";
3754 if ( $wgUseMediaWikiUIEverywhere ) {
3755 $checkboxes['minor'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3756 $minorEditHtml .
3757 Html::closeElement( 'div' );
3758 } else {
3759 $checkboxes['minor'] = $minorEditHtml;
3764 $watchLabel = wfMessage( 'watchthis' )->parse();
3765 $checkboxes['watch'] = '';
3766 if ( $wgUser->isLoggedIn() ) {
3767 $attribs = array(
3768 'tabindex' => ++$tabindex,
3769 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3770 'id' => 'wpWatchthis',
3772 $watchThisHtml =
3773 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3774 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3775 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3776 ">{$watchLabel}</label>";
3777 if ( $wgUseMediaWikiUIEverywhere ) {
3778 $checkboxes['watch'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3779 $watchThisHtml .
3780 Html::closeElement( 'div' );
3781 } else {
3782 $checkboxes['watch'] = $watchThisHtml;
3785 Hooks::run( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3786 return $checkboxes;
3790 * Returns an array of html code of the following buttons:
3791 * save, diff, preview and live
3793 * @param int $tabindex Current tabindex
3795 * @return array
3797 public function getEditButtons( &$tabindex ) {
3798 $buttons = array();
3800 $attribs = array(
3801 'id' => 'wpSave',
3802 'name' => 'wpSave',
3803 'tabindex' => ++$tabindex,
3804 ) + Linker::tooltipAndAccesskeyAttribs( 'save' );
3805 $buttons['save'] = Html::submitButton( wfMessage( 'savearticle' )->text(),
3806 $attribs, array( 'mw-ui-constructive' ) );
3808 ++$tabindex; // use the same for preview and live preview
3809 $attribs = array(
3810 'id' => 'wpPreview',
3811 'name' => 'wpPreview',
3812 'tabindex' => $tabindex,
3813 ) + Linker::tooltipAndAccesskeyAttribs( 'preview' );
3814 $buttons['preview'] = Html::submitButton( wfMessage( 'showpreview' )->text(),
3815 $attribs );
3816 $buttons['live'] = '';
3818 $attribs = array(
3819 'id' => 'wpDiff',
3820 'name' => 'wpDiff',
3821 'tabindex' => ++$tabindex,
3822 ) + Linker::tooltipAndAccesskeyAttribs( 'diff' );
3823 $buttons['diff'] = Html::submitButton( wfMessage( 'showdiff' )->text(),
3824 $attribs );
3826 Hooks::run( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3827 return $buttons;
3831 * Output preview text only. This can be sucked into the edit page
3832 * via JavaScript, and saves the server time rendering the skin as
3833 * well as theoretically being more robust on the client (doesn't
3834 * disturb the edit box's undo history, won't eat your text on
3835 * failure, etc).
3837 * @todo This doesn't include category or interlanguage links.
3838 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3839 * or something...</s>" that might also require more skin
3840 * initialization, so check whether that's a problem.
3842 function livePreview() {
3843 global $wgOut;
3844 $wgOut->disable();
3845 header( 'Content-type: text/xml; charset=utf-8' );
3846 header( 'Cache-control: no-cache' );
3848 $previewText = $this->getPreviewText();
3849 #$categories = $skin->getCategoryLinks();
3851 $s =
3852 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3853 Xml::tags( 'livepreview', null,
3854 Xml::element( 'preview', null, $previewText )
3855 #. Xml::element( 'category', null, $categories )
3857 echo $s;
3861 * Creates a basic error page which informs the user that
3862 * they have attempted to edit a nonexistent section.
3864 function noSuchSectionPage() {
3865 global $wgOut;
3867 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3869 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
3870 Hooks::run( 'EditPageNoSuchSection', array( &$this, &$res ) );
3871 $wgOut->addHTML( $res );
3873 $wgOut->returnToMain( false, $this->mTitle );
3877 * Show "your edit contains spam" page with your diff and text
3879 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3881 public function spamPageWithContent( $match = false ) {
3882 global $wgOut, $wgLang;
3883 $this->textbox2 = $this->textbox1;
3885 if ( is_array( $match ) ) {
3886 $match = $wgLang->listToText( $match );
3888 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3890 $wgOut->addHTML( '<div id="spamprotected">' );
3891 $wgOut->addWikiMsg( 'spamprotectiontext' );
3892 if ( $match ) {
3893 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3895 $wgOut->addHTML( '</div>' );
3897 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3898 $this->showDiff();
3900 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3901 $this->showTextbox2();
3903 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3907 * Check if the browser is on a blacklist of user-agents known to
3908 * mangle UTF-8 data on form submission. Returns true if Unicode
3909 * should make it through, false if it's known to be a problem.
3910 * @return bool
3912 private function checkUnicodeCompliantBrowser() {
3913 global $wgBrowserBlackList, $wgRequest;
3915 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3916 if ( $currentbrowser === false ) {
3917 // No User-Agent header sent? Trust it by default...
3918 return true;
3921 foreach ( $wgBrowserBlackList as $browser ) {
3922 if ( preg_match( $browser, $currentbrowser ) ) {
3923 return false;
3926 return true;
3930 * Filter an input field through a Unicode de-armoring process if it
3931 * came from an old browser with known broken Unicode editing issues.
3933 * @param WebRequest $request
3934 * @param string $field
3935 * @return string
3937 protected function safeUnicodeInput( $request, $field ) {
3938 $text = rtrim( $request->getText( $field ) );
3939 return $request->getBool( 'safemode' )
3940 ? $this->unmakeSafe( $text )
3941 : $text;
3945 * Filter an output field through a Unicode armoring process if it is
3946 * going to an old browser with known broken Unicode editing issues.
3948 * @param string $text
3949 * @return string
3951 protected function safeUnicodeOutput( $text ) {
3952 global $wgContLang;
3953 $codedText = $wgContLang->recodeForEdit( $text );
3954 return $this->checkUnicodeCompliantBrowser()
3955 ? $codedText
3956 : $this->makeSafe( $codedText );
3960 * A number of web browsers are known to corrupt non-ASCII characters
3961 * in a UTF-8 text editing environment. To protect against this,
3962 * detected browsers will be served an armored version of the text,
3963 * with non-ASCII chars converted to numeric HTML character references.
3965 * Preexisting such character references will have a 0 added to them
3966 * to ensure that round-trips do not alter the original data.
3968 * @param string $invalue
3969 * @return string
3971 private function makeSafe( $invalue ) {
3972 // Armor existing references for reversibility.
3973 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
3975 $bytesleft = 0;
3976 $result = "";
3977 $working = 0;
3978 $valueLength = strlen( $invalue );
3979 for ( $i = 0; $i < $valueLength; $i++ ) {
3980 $bytevalue = ord( $invalue[$i] );
3981 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3982 $result .= chr( $bytevalue );
3983 $bytesleft = 0;
3984 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3985 $working = $working << 6;
3986 $working += ( $bytevalue & 0x3F );
3987 $bytesleft--;
3988 if ( $bytesleft <= 0 ) {
3989 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3991 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3992 $working = $bytevalue & 0x1F;
3993 $bytesleft = 1;
3994 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3995 $working = $bytevalue & 0x0F;
3996 $bytesleft = 2;
3997 } else { // 1111 0xxx
3998 $working = $bytevalue & 0x07;
3999 $bytesleft = 3;
4002 return $result;
4006 * Reverse the previously applied transliteration of non-ASCII characters
4007 * back to UTF-8. Used to protect data from corruption by broken web browsers
4008 * as listed in $wgBrowserBlackList.
4010 * @param string $invalue
4011 * @return string
4013 private function unmakeSafe( $invalue ) {
4014 $result = "";
4015 $valueLength = strlen( $invalue );
4016 for ( $i = 0; $i < $valueLength; $i++ ) {
4017 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
4018 $i += 3;
4019 $hexstring = "";
4020 do {
4021 $hexstring .= $invalue[$i];
4022 $i++;
4023 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4025 // Do some sanity checks. These aren't needed for reversibility,
4026 // but should help keep the breakage down if the editor
4027 // breaks one of the entities whilst editing.
4028 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4029 $codepoint = hexdec( $hexstring );
4030 $result .= codepointToUtf8( $codepoint );
4031 } else {
4032 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4034 } else {
4035 $result .= substr( $invalue, $i, 1 );
4038 // reverse the transform that we made for reversibility reasons.
4039 return strtr( $result, array( "&#x0" => "&#x" ) );